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
namespace CadastroTarefas.Utils { public class ValidacaoUtil { public static bool ValidarEmail(string email) { if (email.Contains("@") && email.Contains(".")) { return true; } return false; } public static bool ValidarSenha (string senha, string confirmaSenha) { if (senha.Length >= 6 && confirmaSenha.Equals(senha)) { return true; } return false; }//end ValidarSenha() } }
24.478261
76
0.484902
[ "MIT" ]
lukkanog/C---Exerc-cios
MVC/CadastroTarefas/Utils/ValidacaoUtil.cs
563
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Renci.SshNet.Tests.Classes { [TestClass] public class ForwardedPortRemoteTest_Stop_PortStarted_ChannelBound : ForwardedPortRemoteTest_Dispose_PortStarted_ChannelBound { protected override void Act() { ForwardedPort.Stop(); } } }
24.642857
129
0.718841
[ "MIT" ]
0xced/SSH.NET
src/Renci.SshNet.Tests/Classes/ForwardedPortRemoteTest_Stop_PortStarted_ChannelBound.cs
347
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT license. using System; using AutoCrane.Interfaces; namespace AutoCrane.Services { internal sealed class MonkeyWorkload : IMonkeyWorkload { private readonly Random random; private readonly IClock clock; private int failPercent; private DateTimeOffset failUntil; public MonkeyWorkload(IClock clock) { this.random = new Random(); this.failPercent = 0; this.failUntil = DateTimeOffset.MinValue; this.clock = clock; } public bool ShouldFail() { var now = this.clock.Get(); if (now > this.failUntil) { return false; } var randVal = this.random.Next(100); return this.failPercent > randVal; } public void SetFailPercentage(int pct, TimeSpan until) { this.failPercent = pct; this.failUntil = this.clock.Get() + until; } } }
24.767442
62
0.56338
[ "MIT" ]
QPC-database/AutoCrane
src/AutoCrane/Services/MonkeyWorkload.cs
1,067
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace XData.Data.Objects { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class BuiltIn { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal BuiltIn() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("XData.Data.Objects.BuiltIn", typeof(BuiltIn).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to &lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot; ?&gt; ///&lt;configuration&gt; /// /// &lt;dataConverter name=&quot;json&quot; type=&quot;XData.Data.Objects.ToJsonConverter&quot; /&gt; /// &lt;dataConverter name=&quot;xml&quot; type=&quot;XData.Data.Objects.ToXmlConverter&quot; /&gt; /// ///&lt;/configuration&gt; ///. /// </summary> internal static string DataConverter { get { return ResourceManager.GetString("DataConverter", resourceCulture); } } /// <summary> /// Looks up a localized string similar to &lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot; ?&gt; ///&lt;configuration&gt; /// /// &lt;dateFormatter name=&quot;.NET&quot; type=&quot;XData.Data.Objects.DotNETDateFormatter&quot;&gt; /// &lt;format type=&quot;System.String&quot; /&gt; /// &lt;/dateFormatter&gt; /// /// &lt;dateFormatter name=&quot;Json.NET&quot; type=&quot;XData.Data.Objects.JsonNETFormatter&quot; /&gt; /// ///&lt;/configuration&gt; ///. /// </summary> internal static string DateFormatter { get { return ResourceManager.GetString("DateFormatter", resourceCulture); } } } }
43.737374
170
0.574365
[ "MIT" ]
shantiw/Entitybank
Entitybase/Objects/BuiltIn.Designer.cs
4,332
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 finspace-2021-03-12.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.Finspace.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.Finspace.Model.Internal.MarshallTransformations { /// <summary> /// DeleteEnvironment Request Marshaller /// </summary> public class DeleteEnvironmentRequestMarshaller : IMarshaller<IRequest, DeleteEnvironmentRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((DeleteEnvironmentRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(DeleteEnvironmentRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.Finspace"); request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2021-03-12"; request.HttpMethod = "DELETE"; if (!publicRequest.IsSetEnvironmentId()) throw new AmazonFinspaceException("Request object does not have required field EnvironmentId set"); request.AddPathResource("{environmentId}", StringUtils.FromString(publicRequest.EnvironmentId)); request.ResourcePath = "/environment/{environmentId}"; return request; } private static DeleteEnvironmentRequestMarshaller _instance = new DeleteEnvironmentRequestMarshaller(); internal static DeleteEnvironmentRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static DeleteEnvironmentRequestMarshaller Instance { get { return _instance; } } } }
35.103448
149
0.66241
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/Finspace/Generated/Model/Internal/MarshallTransformations/DeleteEnvironmentRequestMarshaller.cs
3,054
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/winioctl.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System.Runtime.InteropServices; namespace TerraFX.Interop.UnitTests { /// <summary>Provides validation of the <see cref="SCM_PD_FIRMWARE_ACTIVATE" /> struct.</summary> public static unsafe partial class SCM_PD_FIRMWARE_ACTIVATETests { /// <summary>Validates that the <see cref="SCM_PD_FIRMWARE_ACTIVATE" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<SCM_PD_FIRMWARE_ACTIVATE>(), Is.EqualTo(sizeof(SCM_PD_FIRMWARE_ACTIVATE))); } /// <summary>Validates that the <see cref="SCM_PD_FIRMWARE_ACTIVATE" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(SCM_PD_FIRMWARE_ACTIVATE).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="SCM_PD_FIRMWARE_ACTIVATE" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { Assert.That(sizeof(SCM_PD_FIRMWARE_ACTIVATE), Is.EqualTo(16)); } } }
40.583333
145
0.686516
[ "MIT" ]
DaZombieKiller/terrafx.interop.windows
tests/Interop/Windows/um/winioctl/SCM_PD_FIRMWARE_ACTIVATETests.cs
1,463
C#
namespace SQLAzureMWUtils { partial class BCPCommandEditor { /// <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() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(BCPCommandEditor)); this.btnSave = new System.Windows.Forms.Button(); this.btnCancel = new System.Windows.Forms.Button(); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.tbBCPCommand = new System.Windows.Forms.TextBox(); this.tbNumOfRows = new System.Windows.Forms.TextBox(); this.SuspendLayout(); // // btnSave // resources.ApplyResources(this.btnSave, "btnSave"); this.btnSave.DialogResult = System.Windows.Forms.DialogResult.Yes; this.btnSave.Name = "btnSave"; this.btnSave.UseVisualStyleBackColor = true; // // btnCancel // resources.ApplyResources(this.btnCancel, "btnCancel"); this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.btnCancel.Name = "btnCancel"; this.btnCancel.UseVisualStyleBackColor = true; // // label1 // resources.ApplyResources(this.label1, "label1"); this.label1.Name = "label1"; // // label2 // resources.ApplyResources(this.label2, "label2"); this.label2.Name = "label2"; // // tbBCPCommand // resources.ApplyResources(this.tbBCPCommand, "tbBCPCommand"); this.tbBCPCommand.Name = "tbBCPCommand"; // // tbNumOfRows // resources.ApplyResources(this.tbNumOfRows, "tbNumOfRows"); this.tbNumOfRows.Name = "tbNumOfRows"; // // BCPCommandEditor // resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.tbNumOfRows); this.Controls.Add(this.tbBCPCommand); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Controls.Add(this.btnCancel); this.Controls.Add(this.btnSave); this.Name = "BCPCommandEditor"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button btnSave; private System.Windows.Forms.Button btnCancel; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.TextBox tbBCPCommand; private System.Windows.Forms.TextBox tbNumOfRows; } }
37.777778
148
0.570588
[ "MIT" ]
GurappaCoforgeTech/Professional-Azure-SQL-Database-Administration-Third-Edition
Chapter03/SQLAzureMigration-master/SQLAzureMWUtils/BCPCommandEditor.Designer.cs
3,742
C#
namespace Kongrevsky.Infrastructure.LogManager.Repository { #region << Using >> using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; using AutoMapper; using Kongrevsky.Infrastructure.LogManager.Infrastructure; using Kongrevsky.Infrastructure.LogManager.Models; using Kongrevsky.Infrastructure.Models; using Kongrevsky.Infrastructure.Repository; using Kongrevsky.Infrastructure.Repository.Utils; using Kongrevsky.Utilities.Enumerable; using Kongrevsky.Utilities.String; using Microsoft.Extensions.Options; #endregion internal class LogRepository : KongrevskyRepository<LogItem, LogDbContext>, ILogRepository { private const string LogNotFound = "Log not found"; public LogRepository(IKongrevskyDatabaseFactory<LogDbContext> kongrevskyDatabaseFactory, IOptions<LogManagerOptions> options) : base(kongrevskyDatabaseFactory) { _options = options.Value; if (_options.AppName.IsNullOrWhiteSpace()) throw new ArgumentException("Config is required", nameof(_options.AppName)); } private LogManagerOptions _options { get; } public async Task<ResultObjectInfo<LogItemDto>> GetLogAsync(string logId) { var log = await GetAsync(x => x.Id == logId && x.AppName == _options.AppName); if (log == null) return NotFound<LogItemDto>(LogNotFound); var mapper = AutoMapperDomainUtils.GetMapper(config => config.CreateMap<LogItem, LogItemDto>()); return Ok(mapper.Map<LogItemDto>(log)); } public async Task<ResultObjectInfo<LogItemDto>> GetLogAsync(int logNumber) { var log = await GetAsync(x => x.Number == logNumber && x.AppName == _options.AppName); if (log == null) return NotFound<LogItemDto>(LogNotFound); var mapper = AutoMapperDomainUtils.GetMapper(config => config.CreateMap<LogItem, LogItemDto>()); return Ok(mapper.Map<LogItemDto>(log)); } public async Task<LogItemPaging> GetLogsAsync(LogItemPaging filter) { var search = filter.Search.SplitBySpaces(); var startDate = filter.StartDate?.ToUniversalTime(); var endDate = filter.EndDate?.ToUniversalTime(); var where = new List<Expression<Func<LogItem, bool>>>(); where.AddIfTrue(startDate.HasValue, x => startDate <= x.DateCreated); where.AddIfTrue(endDate.HasValue, x => x.DateCreated <= endDate); where.AddIfTrue(filter.LogType.HasValue, x => filter.LogType == x.LogType); where.AddIfTrue(search.Any(), x => search.All(s => x.Action.Contains(s))); foreach (var filterAdditionalInfoLogItem in filter.AdditionalInfoLogItems) { switch (filterAdditionalInfoLogItem.Type) { case AdditionalInfoLogItemFilterType.Contains: where.Add(x => x.AdditionalInfoLogItems.FirstOrDefault(i => i.Name == filterAdditionalInfoLogItem.Name).Value.Contains(filterAdditionalInfoLogItem.Value)); break; case AdditionalInfoLogItemFilterType.Equal: where.Add(x => x.AdditionalInfoLogItems.FirstOrDefault(i => i.Name == filterAdditionalInfoLogItem.Name).Value == filterAdditionalInfoLogItem.Value); break; case AdditionalInfoLogItemFilterType.StartWith: where.Add(x => x.AdditionalInfoLogItems.FirstOrDefault(i => i.Name == filterAdditionalInfoLogItem.Name).Value.StartsWith(filterAdditionalInfoLogItem.Value)); break; case AdditionalInfoLogItemFilterType.EndWith: where.Add(x => x.AdditionalInfoLogItems.FirstOrDefault(i => i.Name == filterAdditionalInfoLogItem.Name).Value.EndsWith(filterAdditionalInfoLogItem.Value)); break; } } Action<IMapperConfigurationExpression> configurationProvider = config => { config.CreateMap<LogItem, LogItemDto>(); }; Expression<Func<LogItem, bool>> checkPermission = item => item.AppName == _options.AppName; var request = GetPage(filter, checkPermission, where, configurationProvider); await filter.SetResult(request); return filter; } public Task<string> CreateLogAsync(CreateLogItemDto log) { var newLog = new LogItem { AppName = _options.AppName, LogType = log.LogType, Action = log.Action, UserEmail = log.UserEmail, UserName = log.UserName }; newLog.AdditionalInfoLogItems = log.AdditionalInfo.Select(x => new AdditionalInfoLogItem() { LogItemId = newLog.Id, Name = x.Name, Value = x.Value }).ToList(); Add(newLog); return Task.FromResult(newLog.Id); } public async Task<int> DeleteLogsAsync(DeleteLogsFilterDto filter) { var startDate = filter.StartDate?.ToUniversalTime(); var endDate = filter.EndDate?.ToUniversalTime(); var where = new List<Expression<Func<LogItem, bool>>>(); where.Add(x => x.AppName == _options.AppName); where.AddIfTrue(startDate.HasValue, x => startDate <= x.DateCreated); where.AddIfTrue(endDate.HasValue, x => x.DateCreated <= endDate); where.AddIfTrue(filter.LogType.HasValue, x => filter.LogType == x.LogType); var queryable = GetMany(x => true); queryable = where.Aggregate(queryable, (current, expression) => current.Where(expression)); var deletedNumber = BulkDelete(await queryable.ToListAsync(), item => item.Id); return deletedNumber; } public async Task<ResultInfo> DeleteLogAsync(string logId) { var log = await GetAsync(x => x.Id == logId && x.AppName == _options.AppName); if (log == null) return NotFound(LogNotFound); Delete(log); return Ok(); } public async Task<ResultInfo> DeleteLogAsync(int logNumber) { var log = await GetAsync(x => x.Number == logNumber && x.AppName == _options.AppName); if (log == null) return NotFound(LogNotFound); Delete(log); return Ok(); } } }
44.648148
181
0.572791
[ "MIT" ]
gpcaretti/libraries
Kongrevsky.Libraries/Infrastructure/Kongrevsky.Infrastructure.LogManager/Repository/LogRepository.cs
7,235
C#
using GeekShopping.Web.Models; namespace GeekShopping.Web.Services.IServices { public interface ICouponService { Task<CouponViewModel> GetCoupon(string code, string token); } }
20
67
0.725
[ "Apache-2.0" ]
RaulSCoelho/microservices-dotnet6
S16_ErudioMicroservices.NET6-CreatingGeekShopping.CouponAPIMicroservice/GeekShopping/GeekShopping.Web/Services/IServices/ICouponService.cs
202
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/WinTrust.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System; using System.Runtime.InteropServices; namespace TerraFX.Interop.UnitTests { /// <summary>Provides validation of the <see cref="CAT_MEMBERINFO" /> struct.</summary> public static unsafe partial class CAT_MEMBERINFOTests { /// <summary>Validates that the <see cref="CAT_MEMBERINFO" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<CAT_MEMBERINFO>(), Is.EqualTo(sizeof(CAT_MEMBERINFO))); } /// <summary>Validates that the <see cref="CAT_MEMBERINFO" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(CAT_MEMBERINFO).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="CAT_MEMBERINFO" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { if (Environment.Is64BitProcess) { Assert.That(sizeof(CAT_MEMBERINFO), Is.EqualTo(16)); } else { Assert.That(sizeof(CAT_MEMBERINFO), Is.EqualTo(8)); } } } }
35.772727
145
0.632147
[ "MIT" ]
DaZombieKiller/terrafx.interop.windows
tests/Interop/Windows/um/wintrust/CAT_MEMBERINFOTests.cs
1,576
C#
// © Alexander Kozlenko. Licensed under the MIT License. using System; using System.Reflection; using Anemonis.AspNetCore.JsonRpc; using Microsoft.AspNetCore.Http; namespace Microsoft.AspNetCore.Builder { /// <summary>The JSON-RPC 2.0 middleware extensions for the <see cref="IApplicationBuilder" />.</summary> public static class JsonRpcBuilderExtensions { /// <summary>Adds the specified JSON-RPC 2.0 handler to the application's request pipeline for the specified path.</summary> /// <param name="builder">The <see cref="IApplicationBuilder" /> to add the middleware to.</param> /// <param name="type">The type of the handler.</param> /// <param name="path">The request path for JSON-RPC methods.</param> /// <returns>A reference to this instance after the operation has completed.</returns> /// <exception cref="ArgumentException"><paramref name="type" /> is not class or does not implement the <see cref="IJsonRpcHandler" /> interface.</exception> /// <exception cref="ArgumentNullException"><paramref name="builder" /> or <paramref name="type" /> is <see langword="null" />.</exception> public static IApplicationBuilder UseJsonRpcHandler(this IApplicationBuilder builder, Type type, PathString path = default) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } if (type == null) { throw new ArgumentNullException(nameof(type)); } InterfaceAssistant<IJsonRpcHandler>.VerifyTypeParam(type, nameof(type)); if (!path.HasValue) { var jsonRpcRouteAtribute = type.GetCustomAttribute<JsonRpcRouteAttribute>(); if (jsonRpcRouteAtribute != null) { path = jsonRpcRouteAtribute.Path; } } var middlewareType = typeof(JsonRpcMiddleware<>).MakeGenericType(type); return builder.Map(path, b => b.UseMiddleware(middlewareType)); } /// <summary>Adds the specified JSON-RPC 2.0 handler to the application's request pipeline for the specified path.</summary> /// <typeparam name="T">The type of the handler.</typeparam> /// <param name="builder">The <see cref="IApplicationBuilder" /> to add the middleware to.</param> /// <param name="path">The request path for JSON-RPC methods.</param> /// <returns>A reference to this instance after the operation has completed.</returns> /// <exception cref="ArgumentNullException"><paramref name="builder" /> is <see langword="null" />.</exception> public static IApplicationBuilder UseJsonRpcHandler<T>(this IApplicationBuilder builder, PathString path = default) where T : class, IJsonRpcHandler { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } if (!path.HasValue) { var jsonRpcRouteAtribute = typeof(T).GetCustomAttribute<JsonRpcRouteAttribute>(); if (jsonRpcRouteAtribute != null) { path = jsonRpcRouteAtribute.Path; } } return builder.Map(path, b => b.UseMiddleware(typeof(JsonRpcMiddleware<T>))); } /// <summary>Adds JSON-RPC 2.0 handlers from the current application domain to the application's request pipeline.</summary> /// <param name="builder">The <see cref="IApplicationBuilder" /> to add the middleware to.</param> /// <returns>A reference to this instance after the operation has completed.</returns> /// <exception cref="ArgumentNullException"><paramref name="builder" /> is <see langword="null" />.</exception> public static IApplicationBuilder UseJsonRpcHandlers(this IApplicationBuilder builder) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } var types = InterfaceAssistant<IJsonRpcHandler>.GetDefinedTypes(); for (var i = 0; i < types.Count; i++) { var jsonRpcRouteAtribute = types[i].GetCustomAttribute<JsonRpcRouteAttribute>(); if (jsonRpcRouteAtribute == null) { continue; } var middlewareType = typeof(JsonRpcMiddleware<>).MakeGenericType(types[i]); builder.Map(jsonRpcRouteAtribute.Path, b => b.UseMiddleware(middlewareType)); } return builder; } /// <summary>Adds the specified JSON-RPC 2.0 service to the application's request pipeline for the specified path.</summary> /// <param name="builder">The <see cref="IApplicationBuilder" /> to add the middleware to.</param> /// <param name="type">The type of the service.</param> /// <param name="path">The request path for JSON-RPC methods.</param> /// <returns>A reference to this instance after the operation has completed.</returns> /// <exception cref="ArgumentException"><paramref name="type" /> is not class or does not implement the <see cref="IJsonRpcService" /> interface.</exception> /// <exception cref="ArgumentNullException"><paramref name="builder" /> or <paramref name="type" /> is <see langword="null" />.</exception> public static IApplicationBuilder UseJsonRpcService(this IApplicationBuilder builder, Type type, PathString path = default) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } if (type == null) { throw new ArgumentNullException(nameof(type)); } InterfaceAssistant<IJsonRpcService>.VerifyTypeParam(type, nameof(type)); if (!path.HasValue) { var jsonRpcRouteAtribute = type.GetCustomAttribute<JsonRpcRouteAttribute>(); if (jsonRpcRouteAtribute != null) { path = jsonRpcRouteAtribute.Path; } } var middlewareType = typeof(JsonRpcMiddleware<>).MakeGenericType(typeof(JsonRpcServiceHandler<>).MakeGenericType(type)); return builder.Map(path, b => b.UseMiddleware(middlewareType)); } /// <summary>Adds the specified JSON-RPC 2.0 service to the application's request pipeline for the specified path.</summary> /// <typeparam name="T">The type of the service.</typeparam> /// <param name="builder">The <see cref="IApplicationBuilder" /> to add the middleware to.</param> /// <param name="path">The request path for JSON-RPC methods.</param> /// <returns>A reference to this instance after the operation has completed.</returns> /// <exception cref="ArgumentNullException"><paramref name="builder" /> is <see langword="null" />.</exception> public static IApplicationBuilder UseJsonRpcService<T>(this IApplicationBuilder builder, PathString path = default) where T : class, IJsonRpcService { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } if (!path.HasValue) { var jsonRpcRouteAtribute = typeof(T).GetCustomAttribute<JsonRpcRouteAttribute>(); if (jsonRpcRouteAtribute != null) { path = jsonRpcRouteAtribute.Path; } } return builder.Map(path, b => b.UseMiddleware(typeof(JsonRpcMiddleware<JsonRpcServiceHandler<T>>))); } /// <summary>Adds JSON-RPC 2.0 services from the current application domain to the application's request pipeline.</summary> /// <param name="builder">The <see cref="IApplicationBuilder" /> to add the middleware to.</param> /// <returns>A reference to this instance after the operation has completed.</returns> /// <exception cref="ArgumentNullException"><paramref name="builder" /> is <see langword="null" />.</exception> public static IApplicationBuilder UseJsonRpcServices(this IApplicationBuilder builder) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } var types = InterfaceAssistant<IJsonRpcService>.GetDefinedTypes(); for (var i = 0; i < types.Count; i++) { var jsonRpcRouteAtribute = types[i].GetCustomAttribute<JsonRpcRouteAttribute>(); if (jsonRpcRouteAtribute == null) { continue; } var middlewareType = typeof(JsonRpcMiddleware<>).MakeGenericType(typeof(JsonRpcServiceHandler<>).MakeGenericType(types[i])); builder.Map(jsonRpcRouteAtribute.Path, b => b.UseMiddleware(middlewareType)); } return builder; } /// <summary>Adds JSON-RPC 2.0 handlers and services from the current application domain to the application's request pipeline.</summary> /// <param name="builder">The <see cref="IApplicationBuilder" /> to add the middleware to.</param> /// <returns>A reference to this instance after the operation has completed.</returns> /// <exception cref="ArgumentNullException"><paramref name="builder" /> is <see langword="null" />.</exception> public static IApplicationBuilder UseJsonRpc(this IApplicationBuilder builder) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } builder.UseJsonRpcHandlers(); builder.UseJsonRpcServices(); return builder; } } }
46.018433
165
0.610054
[ "MIT" ]
BigDaddy1337/aspnetcore-json-rpc
src/Anemonis.AspNetCore.JsonRpc/JsonRpcBuilderExtensions.cs
9,989
C#
// Copyright (c) Josef Pihrt. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Immutable; using System.Composition; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Roslynator.CSharp.Refactorings; namespace Roslynator.CSharp.CodeFixProviders { [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(ReplaceTabWithSpacesCodeFixProvider))] [Shared] public class ReplaceTabWithSpacesCodeFixProvider : BaseCodeFixProvider { public sealed override ImmutableArray<string> FixableDiagnosticIds { get { return ImmutableArray.Create(DiagnosticIdentifiers.AvoidUsageOfTab); } } public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) { CodeAction codeAction = CodeAction.Create( "Replace tab with spaces", cancellationToken => AvoidUsageOfTabRefactoring.RefactorAsync(context.Document, context.Span, cancellationToken), DiagnosticIdentifiers.AvoidUsageOfTab + EquivalenceKeySuffix); context.RegisterCodeFix(codeAction, context.Diagnostics); var tcs = new TaskCompletionSource<object>(); tcs.SetResult(null); return tcs.Task; } } }
37.051282
160
0.72526
[ "Apache-2.0" ]
MarcosMeli/Roslynator
source/Analyzers/CodeFixProviders/ReplaceTabWithSpacesCodeFixProvider.cs
1,447
C#
#region Copyright (c) 2011-2022 Technosoftware GmbH. All rights reserved //----------------------------------------------------------------------------- // Copyright (c) 2011-2022 Technosoftware GmbH. All rights reserved // Web: https://www.technosoftware.com // // The source code in this file is covered under a dual-license scenario: // - Owner of a purchased license: SCLA 1.0 // - GPL V3: everybody else // // SCLA license terms accompanied with this source code. // See SCLA 1.0://technosoftware.com/license/Source_Code_License_Agreement.pdf // // GNU General Public License as published by the Free Software Foundation; // version 3 of the License are accompanied with this source code. // See https://technosoftware.com/license/GPLv3License.txt // // This source code 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. //----------------------------------------------------------------------------- #endregion Copyright (c) 2011-2022 Technosoftware GmbH. All rights reserved #region Using Directives #endregion namespace Technosoftware.DaAeHdaClient { /// <summary> /// Defines string constants for well-known OPC URL schemes. /// </summary> public class OpcUrlScheme { /// <summary> /// OPC over http. /// </summary> public const string HTTP = "http"; /// <summary> /// OPC Alarms and Events /// </summary> public const string AE = "opcae"; /// <summary> /// OPC Data Access /// </summary> public const string DA = "opcda"; /// <summary> /// OPC Historical Data Access /// </summary> public const string HDA = "opchda"; /// <summary> /// OPC Express Interface /// </summary> public const string XI = "opcxi"; } }
31.836066
79
0.594748
[ "MIT" ]
technosoftware-gmbh/opc-daaehda-client-net
src/Technosoftware/DaAeHdaClient/OpcUrlScheme.cs
1,942
C#
// This file has been generated by the GUI designer. Do not modify. namespace RLToolkit.Widgets { public partial class DynamicRow { private global::Gtk.VBox handler; private global::Gtk.VBox rowBox; private global::Gtk.HBox rowHandler; private global::Gtk.Label labelEmpty1; private global::Gtk.Button btnMinus; private global::Gtk.Button btnPlus; private global::Gtk.Label labelEmpty2; /// <summary> /// Build this instance. /// </summary> protected virtual void Build () { global::Stetic.Gui.Initialize (this); // Widget RLToolkit.Widgets.DynamicRow global::Stetic.BinContainer.Attach (this); this.Name = "RLToolkit.Widgets.DynamicRow"; // Container child RLToolkit.Widgets.DynamicRow.Gtk.Container+ContainerChild this.handler = new global::Gtk.VBox (); this.handler.Name = "handler"; this.handler.Spacing = 6; // Container child handler.Gtk.Box+BoxChild this.rowBox = new global::Gtk.VBox (); this.rowBox.Name = "rowBox"; this.rowBox.Spacing = 6; this.handler.Add (this.rowBox); global::Gtk.Box.BoxChild w1 = ((global::Gtk.Box.BoxChild)(this.handler [this.rowBox])); w1.Position = 0; // Container child handler.Gtk.Box+BoxChild this.rowHandler = new global::Gtk.HBox (); this.rowHandler.Name = "rowHandler"; this.rowHandler.Spacing = 6; // Container child rowHandler.Gtk.Box+BoxChild this.labelEmpty1 = new global::Gtk.Label (); this.labelEmpty1.WidthRequest = 30; this.labelEmpty1.Name = "labelEmpty1"; this.rowHandler.Add (this.labelEmpty1); global::Gtk.Box.BoxChild w2 = ((global::Gtk.Box.BoxChild)(this.rowHandler [this.labelEmpty1])); w2.Position = 0; w2.Expand = false; w2.Fill = false; // Container child rowHandler.Gtk.Box+BoxChild this.btnMinus = new global::Gtk.Button (); this.btnMinus.WidthRequest = 22; this.btnMinus.CanFocus = true; this.btnMinus.Name = "btnMinus"; this.btnMinus.UseUnderline = true; this.btnMinus.Label = global::Mono.Unix.Catalog.GetString ("-"); this.rowHandler.Add (this.btnMinus); global::Gtk.Box.BoxChild w3 = ((global::Gtk.Box.BoxChild)(this.rowHandler [this.btnMinus])); w3.Position = 1; w3.Expand = false; w3.Fill = false; // Container child rowHandler.Gtk.Box+BoxChild this.btnPlus = new global::Gtk.Button (); this.btnPlus.WidthRequest = 22; this.btnPlus.CanFocus = true; this.btnPlus.Name = "btnPlus"; this.btnPlus.UseUnderline = true; this.btnPlus.Label = global::Mono.Unix.Catalog.GetString ("+"); this.rowHandler.Add (this.btnPlus); global::Gtk.Box.BoxChild w4 = ((global::Gtk.Box.BoxChild)(this.rowHandler [this.btnPlus])); w4.Position = 2; w4.Expand = false; w4.Fill = false; // Container child rowHandler.Gtk.Box+BoxChild this.labelEmpty2 = new global::Gtk.Label (); this.labelEmpty2.Name = "labelEmpty2"; this.rowHandler.Add (this.labelEmpty2); global::Gtk.Box.BoxChild w5 = ((global::Gtk.Box.BoxChild)(this.rowHandler [this.labelEmpty2])); w5.PackType = ((global::Gtk.PackType)(1)); w5.Position = 3; this.handler.Add (this.rowHandler); global::Gtk.Box.BoxChild w6 = ((global::Gtk.Box.BoxChild)(this.handler [this.rowHandler])); w6.Position = 1; w6.Expand = false; w6.Fill = false; this.Add (this.handler); if ((this.Child != null)) { this.Child.ShowAll (); } this.Hide (); this.btnMinus.Clicked += new global::System.EventHandler (this.OnBtnMinusClicked); this.btnPlus.Clicked += new global::System.EventHandler (this.OnBtnPlusClicked); } } }
37.87234
98
0.690449
[ "MIT" ]
rl132/RLToolkit
Widgets/gtk-gui/RLToolkit.Widgets.DynamicRow.cs
3,560
C#
using Newtonsoft.Json; namespace Birko.SuperFaktura.Response.Client { public class PagedResponse : PagedResponse<ListItem> { [JsonProperty(PropertyName = "items", NullValueHandling = NullValueHandling.Ignore)] [JsonConverter(typeof(Converters.ItemListConverter<ListItem>))] public override ItemList<ListItem> Items { get; set; } } }
30.916667
92
0.722372
[ "MIT" ]
andrjfrks/SuperFakturaAPI.NET
Response/Client/PagedResponse.cs
373
C#
using DALHelperNet; using DALHelperNet.Interfaces.Attributes; using DALHelperNetExample.Models; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace DALHelperNetExample.Helpers { public class ExampleObjectHelper { private static IEnumerable<ExampleObject> GetExampleObjects(string ExampleObjectInternalId = null) { var typeQuery = $@"SELECT * FROM {typeof(ExampleObject).GetCustomAttribute<DALTable>().TableName ?? "example_objects"} WHERE active = 1 {(string.IsNullOrWhiteSpace(ExampleObjectInternalId) ? "#" : null)}AND InternalId = @internal_id {(string.IsNullOrWhiteSpace(ExampleObjectInternalId) ? "#" : null)}LIMIT 1 ;"; return DALHelper.GetDataObjects<ExampleObject>(ExampleConnectionStringTypes.FirstApplicationDatabase, typeQuery, new Dictionary<string, object> { { "@internal_id", ExampleObjectInternalId } }); } public static ExampleObject GetExampleObject(string ExampleObjectInternalId) { return GetExampleObjects(ExampleObjectInternalId: ExampleObjectInternalId) .FirstOrDefault(); } public static IEnumerable<ExampleObject> GetAllExampleObjects() { return GetExampleObjects(); } public static int DeleteExampleObject(string ExampleObjectId) { var deleteQuery = $@"UPDATE {typeof(ExampleObject).GetCustomAttribute<DALTable>()?.TableName ?? "example_objects"} SET active = 0 WHERE InternalId = @internal_id;"; var rowsUpdated = DALHelper.DoDatabaseWork<int>(ExampleConnectionStringTypes.FirstApplicationDatabase, deleteQuery, new Dictionary<string, object> { { "@internal_id", ExampleObjectId } }); return rowsUpdated; } } }
39.918367
205
0.680982
[ "MIT" ]
jdaugherty-bdl/DALHelperNet
DALHelperNetExample/DALHelperNetExample/Helpers/ExampleObjectHelper.cs
1,958
C#
namespace InCube.Core.Collections; /// <summary> /// A collection of extension methods related to arrays. /// </summary> [PublicAPI] public static class Arrays { /// <summary> /// Creates a constant array. /// </summary> /// <param name="length">The length of the output array.</param> /// <param name="value">The value to set at every index.</param> /// <typeparam name="T">The type of the output array.</typeparam> /// <returns>An array filled with a single object.</returns> public static T[] Constant<T>(this int length, T value) where T : notnull { var result = new T[length]; result.Set(value); return result; } /// <summary> /// Creates a constant array. /// </summary> /// <param name="length">The length of the output array.</param> /// <param name="value">The value to set at every index.</param> /// <typeparam name="T">The type of the output array.</typeparam> /// <returns>An array filled with a single object.</returns> public static T?[] ConstantNullable<T>(this int length, T? value) { var result = new T[length]; result.Set(value); return result; } /// <summary> /// Sets all the elements of the <paramref name="array" /> to the <see cref="value" />. /// </summary> /// <param name="array">The array to modify.</param> /// <param name="value">The value to modify the array with.</param> /// <typeparam name="T">The type of the array.</typeparam> public static void Set<T>(this T[] array, T value) { for (var i = 0; i < array.Length; i++) array[i] = value; } }
34.102041
91
0.599641
[ "MIT" ]
hypdeb/core
src/InCube.Core/Collections/Arrays.cs
1,671
C#
using System; namespace ImageLib { public class EntryPoint { public static void Main(string[] args) { if(ImageLib.ImageMaker.StartImageServer("/tmp/water.jpg")){ Console.WriteLine( ImageLib.ImageMaker.MakeImage("/tmp/image.jpg")); } } } }
21.066667
84
0.56962
[ "Apache-2.0" ]
metacall/rotulin
image/Main.cs
316
C#
// *********************************************************************** // Assembly : Noob.D2CMSApi // Author : Administrator // Created : 04-05-2020 // // Last Modified By : Administrator // Last Modified On : 2020-04-05 // *********************************************************************** // <copyright file="DisableIdGenerationAttribute.cs" company="Noob.D2CMSApi"> // Copyright (c) . All rights reserved. // </copyright> // <summary></summary> // *********************************************************************** using System; namespace Noob.Domain.Entities { /// <summary> /// Class DisableIdGenerationAttribute. /// Implements the <see cref="System.Attribute" /> /// </summary> /// <seealso cref="System.Attribute" /> public class DisableIdGenerationAttribute : Attribute { } }
30.892857
77
0.472832
[ "MIT" ]
noobwu/DncZeus
Noob.Core/Ddd/Domain/Entities/DisableIdGenerationAttribute.cs
867
C#
// Copyright 2020-2021 Mykhailo Shevchuk & Contributors // // Licensed under the MIT license; // you may not use this file except in compliance with the License. // // 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 LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading.Tasks; using Serilog.Core; using Serilog.Debugging; using Serilog.Events; using Serilog.Formatting; using Serilog.Sinks.Grafana.Loki.Infrastructure; using Serilog.Sinks.Grafana.Loki.Utils; namespace Serilog.Sinks.Grafana.Loki { internal class LokiSink : ILogEventSink, IDisposable { private readonly string _requestUri; private readonly int _batchPostingLimit; private readonly ITextFormatter _textFormatter; private readonly ILokiBatchFormatter _batchFormatter; private readonly ILokiHttpClient _httpClient; private readonly ExponentialBackoffConnectionSchedule _connectionSchedule; private readonly object _syncRoot = new(); private readonly PortableTimer _timer; private readonly BoundedQueue<LogEvent> _queue; private readonly bool _useInternalTimestamp; private readonly Queue<(LogEvent LogEntry, DateTimeOffset Timestamp)> _waitingBatch = new(); private bool _isDisposed; public LokiSink( string requestUri, int batchPostingLimit, int? queueLimit, TimeSpan period, ITextFormatter textFormatter, ILokiBatchFormatter batchFormatter, ILokiHttpClient httpClient, bool useInternalTimestamp) { _requestUri = requestUri ?? throw new ArgumentNullException(nameof(requestUri)); _batchPostingLimit = batchPostingLimit; _textFormatter = textFormatter ?? throw new ArgumentNullException(nameof(textFormatter)); _batchFormatter = batchFormatter ?? throw new ArgumentNullException(nameof(batchFormatter)); _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); _connectionSchedule = new ExponentialBackoffConnectionSchedule(period); _timer = new PortableTimer(OnTick); _queue = new BoundedQueue<LogEvent>(queueLimit); _useInternalTimestamp = useInternalTimestamp; SetTimer(); } public void Emit(LogEvent logEvent) { if (logEvent == null) { throw new ArgumentNullException(nameof(logEvent)); } if (!_queue.TryEnqueue(logEvent)) { SelfLog.WriteLine("Queue has reached it's limit and the log event {@Event} will be dropped", logEvent); } } public void Dispose() { lock (_syncRoot) { if (_isDisposed) { return; } _isDisposed = true; } _timer.Dispose(); OnTick().GetAwaiter().GetResult(); _httpClient.Dispose(); } private async Task OnTick() { try { bool batchWasFull; do { while (_waitingBatch.Count < _batchPostingLimit && _queue.TryDequeue(out var next)) { _waitingBatch.Enqueue(((LogEvent LogEntry, DateTimeOffset Timestamp))(next!)); } batchWasFull = _waitingBatch.Count >= _batchPostingLimit; if (_waitingBatch.Count > 0) { HttpResponseMessage response; using (var contentStream = new MemoryStream()) { using (var contentWriter = new StreamWriter(contentStream, Encoding.UTF8WithoutBom)) { _batchFormatter.Format(_waitingBatch, _textFormatter, contentWriter); await contentWriter.FlushAsync(); contentStream.Position = 0; if (contentStream.Length == 0) { continue; } response = await _httpClient .PostAsync(_requestUri, contentStream) .ConfigureAwait(false); } } if (response.IsSuccessStatusCode) { _connectionSchedule.MarkSuccess(); _waitingBatch.Clear(); } else { SelfLog.WriteLine( "Received failure on HTTP shipping ({0}): {1}. {2} log events will be dropped", (int)response.StatusCode, await response.Content.ReadAsStringAsync().ConfigureAwait(false), _waitingBatch.Count); _connectionSchedule.MarkFailure(); _waitingBatch.Clear(); break; } } else { _connectionSchedule.MarkSuccess(); } } while (batchWasFull); } catch (Exception ex) { SelfLog.WriteLine("Exception while emitting periodic batch from {0}: {1}", this, ex); _connectionSchedule.MarkFailure(); } finally { lock (_syncRoot) { if (!_isDisposed) { SetTimer(); } } } } private void SetTimer() { _timer.Start(_connectionSchedule.NextInterval); } } }
36.81768
120
0.50105
[ "MIT" ]
raphaelquati/serilog-sinks-grafana-loki
src/Serilog.Sinks.Grafana.Loki/LokiSink.cs
6,666
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.Devices.V20190322.Inputs { /// <summary> /// The properties of an IoT hub shared access policy. /// </summary> public sealed class SharedAccessSignatureAuthorizationRuleArgs : Pulumi.ResourceArgs { /// <summary> /// The name of the shared access policy. /// </summary> [Input("keyName", required: true)] public Input<string> KeyName { get; set; } = null!; /// <summary> /// The primary key. /// </summary> [Input("primaryKey")] public Input<string>? PrimaryKey { get; set; } /// <summary> /// The permissions assigned to the shared access policy. /// </summary> [Input("rights", required: true)] public Input<Pulumi.AzureNative.Devices.V20190322.AccessRights> Rights { get; set; } = null!; /// <summary> /// The secondary key. /// </summary> [Input("secondaryKey")] public Input<string>? SecondaryKey { get; set; } public SharedAccessSignatureAuthorizationRuleArgs() { } } }
30.12766
101
0.610876
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/Devices/V20190322/Inputs/SharedAccessSignatureAuthorizationRuleArgs.cs
1,416
C#
using Modbus4Net.Utility; using System; using System.Collections.Generic; using System.Linq; namespace Modbus4Net.Extensions.Enron { /// <summary> /// Utility extensions for the Enron Modbus dialect. /// </summary> public static class EnronModbus { /// <summary> /// Read contiguous block of 32 bit holding registers. /// </summary> /// <param name="master">The Modbus master.</param> /// <param name="slaveAddress">Address of device to read values from.</param> /// <param name="startAddress">Address to begin reading.</param> /// <param name="numberOfPoints">Number of holding registers to read.</param> /// <returns>Holding registers status</returns> public static uint[] ReadHoldingRegisters32( this IModbusMaster master, byte slaveAddress, ushort startAddress, ushort numberOfPoints) { if (master == null) { throw new ArgumentNullException(nameof(master)); } ValidateNumberOfPoints(numberOfPoints, 62); // read 16 bit chunks and perform conversion ushort[] rawRegisters = master.ReadHoldingRegisters( slaveAddress, startAddress, (ushort)(numberOfPoints * 2)); return Convert(rawRegisters).ToArray(); } /// <summary> /// Read contiguous block of 32 bit input registers. /// </summary> /// <param name="master">The Modbus master.</param> /// <param name="slaveAddress">Address of device to read values from.</param> /// <param name="startAddress">Address to begin reading.</param> /// <param name="numberOfPoints">Number of holding registers to read.</param> /// <returns>Input registers status</returns> public static uint[] ReadInputRegisters32( this IModbusMaster master, byte slaveAddress, ushort startAddress, ushort numberOfPoints) { if (master == null) { throw new ArgumentNullException(nameof(master)); } ValidateNumberOfPoints(numberOfPoints, 62); ushort[] rawRegisters = master.ReadInputRegisters( slaveAddress, startAddress, (ushort)(numberOfPoints * 2)); return Convert(rawRegisters).ToArray(); } /// <summary> /// Write a single 16 bit holding register. /// </summary> /// <param name="master">The Modbus master.</param> /// <param name="slaveAddress">Address of the device to write to.</param> /// <param name="registerAddress">Address to write.</param> /// <param name="value">Value to write.</param> public static void WriteSingleRegister32( this IModbusMaster master, byte slaveAddress, ushort registerAddress, uint value) { if (master == null) { throw new ArgumentNullException(nameof(master)); } master.WriteMultipleRegisters32(slaveAddress, registerAddress, new[] { value }); } /// <summary> /// Write a block of contiguous 32 bit holding registers. /// </summary> /// <param name="master">The Modbus master.</param> /// <param name="slaveAddress">Address of the device to write to.</param> /// <param name="startAddress">Address to begin writing values.</param> /// <param name="data">Values to write.</param> public static void WriteMultipleRegisters32( this IModbusMaster master, byte slaveAddress, ushort startAddress, uint[] data) { if (master == null) { throw new ArgumentNullException(nameof(master)); } if (data == null) { throw new ArgumentNullException(nameof(data)); } if (data.Length == 0 || data.Length > 61) { throw new ArgumentException("The length of argument data must be between 1 and 61 inclusive."); } master.WriteMultipleRegisters(slaveAddress, startAddress, Convert(data).ToArray()); } /// <summary> /// Convert the 32 bit registers to two 16 bit values. /// </summary> private static IEnumerable<ushort> Convert(uint[] registers) { foreach (uint register in registers) { // low order value yield return BitConverter.ToUInt16(BitConverter.GetBytes(register), 0); // high order value yield return BitConverter.ToUInt16(BitConverter.GetBytes(register), 2); } } /// <summary> /// Convert the 16 bit registers to 32 bit registers. /// </summary> private static IEnumerable<uint> Convert(ushort[] registers) { for (int i = 0; i < registers.Length; i++) { yield return ModbusUtility.GetUInt32(registers[i + 1], registers[i]); i++; } } private static void ValidateNumberOfPoints(ushort numberOfPoints, ushort maxNumberOfPoints) { if (numberOfPoints < 1 || numberOfPoints > maxNumberOfPoints) { string msg = $"Argument numberOfPoints must be between 1 and {maxNumberOfPoints} inclusive."; throw new ArgumentException(msg); } } } }
35.47205
111
0.558571
[ "MIT" ]
gsulc/Modbus4Net
Modbus4Net/Extensions/Enron/EnronModbus.cs
5,713
C#
using System.Collections.Generic; namespace HayleesThreads.Models { public class Category { public Category() { this.JoinTables = new HashSet<CategoryProduct>(); } public int CategoryId { get; set; } public string CategoryName { get; set; } public string CategoryDescription { get; set; } public virtual ApplicationUser User { get; set; } public virtual ICollection<CategoryProduct> JoinTables { get; set; } } }
24.105263
72
0.687773
[ "Unlicense" ]
calliestump/HayleesThreads.Solution
HayleesThreads/Models/Category.cs
458
C#
//////////////////////////////////////////////////////////////////////// // // This file is part of gmic-sharp-pdn, a library that extends // gmic-sharp for use with Paint.NET Effect plugins. // // Copyright (c) 2020, 2021 Nicholas Hayes // // This file is licensed under the MIT License. // See LICENSE.txt for complete licensing and attribution information. // //////////////////////////////////////////////////////////////////////// using GmicSharp; namespace GmicSharpPdn { internal sealed class PdnGmicBitmapOutputFactory : IGmicOutputImageFactory<PdnGmicBitmap> { private PdnGmicBitmapOutputFactory() { } public static PdnGmicBitmapOutputFactory Instance { get; } = new PdnGmicBitmapOutputFactory(); public PdnGmicBitmap Create(int width, int height, GmicPixelFormat gmicPixelFormat) { // The gmicPixelFormat parameter is ignored because // Paint.NET Surfaces are always the same format (32-bit BGRA). return new PdnGmicBitmap(width, height); } } }
32.242424
102
0.595865
[ "MIT" ]
0xC0000054/gmic-sharp-pdn
src/PdnGmicBitmapOutputFactory.cs
1,066
C#
using System; using System.Reflection; using System.Collections.Generic; using System.Linq; using Verse; namespace Vehicles { public static class Ext_Settings { /// <summary> /// Get all fields containing PostToSettings attribute in <paramref name="type"/> /// </summary> /// <param name="type"></param> public static List<FieldInfo> GetPostSettingsFields(this Type type) { return type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(f => Attribute.IsDefined(f, typeof(PostToSettingsAttribute))).ToList(); } /// <summary> /// Combine integers together from version string for ordering /// </summary> /// <param name="version"></param> public static int CombineVersionString(string version) { string rawVersion = new string(version.Where(c => char.IsDigit(c)).ToArray()); if (int.TryParse(rawVersion, out int order)) { return order; } Log.Error($"Unable to parse {version} as raw value following Major.Minor.Revision sequence."); return 0; } } }
28.944444
172
0.709213
[ "MIT" ]
SmashPhil/Boats
Source/Vehicles/Utility/Extensions/Ext_Settings.cs
1,044
C#
using helper.mvvm.baseclasses; using StreamCompanion.Contract; using StreamCompanion.Contract.StreamTemplate; using System.Collections.ObjectModel; using System.Linq; using IViewModel = StreamCompanion.Contract.StreamTemplate.IViewModel; namespace StreamCompanion.StreamTemplate { using helper.mvvm.commands; using System; public class ViewModel : ViewModelBase<IViewModel>, IViewModel { private readonly IController controller; private bool editMode; public ViewModel(IController controller) { this.controller = controller; this.StreamLanguages = new ObservableCollection<string>(Enum.GetNames(typeof(Language))); this.LoadData(); this.SaveAndExitCmd = new ActionCommand(this.SaveAndExit); this.AddStreamWebsiteCmd = new ActionCommand(this.AddNewStreamWebsite); this.EditStreamWebsiteCmd = new ActionCommand(this.EditSelectedStreamWebsite, () => this.SelectedItem != null); this.MoveUpCmd = new ActionCommand(this.MoveUp); this.MoveDownCmd = new ActionCommand(this.MoveDown); this.DoneCmd = new ActionCommand(this.Done, this.NewStreamingWebsiteIsValid); this.CancelCmd = new ActionCommand(() => this.IsStreamingWebsiteVisible = false); } public ObservableCollection<IStreamItem> Streams { get { return this.Get(x => x.Streams); } private set { this.Set(x => x.Streams, value); } } public IStreamItem SelectedItem { get { return this.Get(x => x.SelectedItem); } set { this.Set(x => x.SelectedItem, value); } } public ActionCommand SaveAndExitCmd { get; private set; } public ActionCommand AddStreamWebsiteCmd { get; private set; } public ActionCommand EditStreamWebsiteCmd { get; private set; } public ActionCommand MoveUpCmd { get; private set; } public ActionCommand MoveDownCmd { get; private set; } public ActionCommand DoneCmd { get; private set; } public ActionCommand CancelCmd { get; private set; } public bool IsDone { get { return this.Get(x => x.IsDone); } private set { this.Set(x => x.IsDone, value); } } public bool IsStreamingWebsiteVisible { get { return this.Get(x => x.IsStreamingWebsiteVisible); } set { this.Set(x => x.IsStreamingWebsiteVisible, value); } } public string NewStreamingWebsite { get { return this.Get(x => x.NewStreamingWebsite); } set { this.Set(x => x.NewStreamingWebsite, value); } } public string WhitespaceReplacement { get { return this.Get(x => x.WhitespaceReplacement); } set { this.Set(x => x.WhitespaceReplacement, value); } } public string GenericUrl { get { return this.Get(x => x.GenericUrl); } set { this.Set(x => x.GenericUrl, value); } } public string UsedOnTypes { get { return this.Get(x => x.UsedOnTypes); } set { this.Set(x => x.UsedOnTypes, value); } } public bool IsGeneral { get { return this.Get(x => x.IsGeneral); } set { if (value) { this.IsTv = true; this.IsAnime = true; this.IsCartoon = true; this.IsMovie = true; this.UsedOnTypes = SerieType.Mixed.ToString(); } else { this.IsTv = false; this.IsAnime = false; this.IsCartoon = false; this.IsMovie = false; this.UsedOnTypes = string.Empty; } this.Set(x => x.IsGeneral, value); } } public bool IsTv { get { return this.Get(x => x.IsTv); } set { if (value) { this.UsedOnTypes += SerieType.TV + ","; } this.Set(x => x.IsTv, value); } } public bool IsAnime { get { return this.Get(x => x.IsAnime); } set { if (value) { this.UsedOnTypes += SerieType.Anime + ","; } this.Set(x => x.IsAnime, value); } } public bool IsCartoon { get { return this.Get(x => x.IsCartoon); } set { if (value) { this.UsedOnTypes += SerieType.Cartoon + ","; } this.Set(x => x.IsCartoon, value); } } public bool IsMovie { get { return this.Get(x => x.IsMovie); } set { if (value) { this.UsedOnTypes += SerieType.Movie + ","; } this.Set(x => x.IsMovie, value); } } public string SelectedStreamLanguage { get { return this.Get(x => x.SelectedStreamLanguage); } set { this.Set(x => x.SelectedStreamLanguage, value); } } public ObservableCollection<string> StreamLanguages { get { return this.Get(x => x.StreamLanguages); } private set { this.Set(x => x.StreamLanguages, value); } } private void LoadData() { this.Streams = new ObservableCollection<IStreamItem>(this.controller.LoadStreamTemplates()); } private void SaveAndExit() { this.controller.SaveStreamTemplates(new Model(this.Streams.Cast<StreamItem>().ToList())); this.IsDone = true; } private void MoveUp() { var currentIndex = this.Streams.IndexOf(this.SelectedItem); if (currentIndex != 0) { this.Streams.Move(currentIndex, currentIndex - 1); } } private void MoveDown() { var currentIndex = this.Streams.IndexOf(this.SelectedItem); if (currentIndex != this.Streams.Count - 1) { this.Streams.Move(currentIndex, currentIndex + 1); } } private bool NewStreamingWebsiteIsValid() { return !string.IsNullOrWhiteSpace(this.NewStreamingWebsite) && !string.IsNullOrWhiteSpace(this.WhitespaceReplacement) && !string.IsNullOrWhiteSpace(this.GenericUrl); } private void AddNewStreamWebsite() { this.editMode = false; this.NewStreamingWebsite = string.Empty; this.GenericUrl = string.Empty; this.WhitespaceReplacement = string.Empty; this.IsGeneral = false; this.IsStreamingWebsiteVisible = true; this.SelectedStreamLanguage = Language.English.ToString(); } private void EditSelectedStreamWebsite() { var site = this.SelectedItem.Website; this.NewStreamingWebsite = site.Substring(0, site.LastIndexOf('/')); this.GenericUrl = site.Substring(site.LastIndexOf('/') + 1); this.WhitespaceReplacement = this.SelectedItem.WhitespaceReplacement; this.SelectedStreamLanguage = this.SelectedItem.StreamLanguage; var usedTypes = this.SelectedItem.UsedOnTypes; if (usedTypes == SerieType.Mixed.ToString()) { this.IsGeneral = true; } else { if (usedTypes.Contains(SerieType.TV.ToString())) { this.IsTv = true; } if (usedTypes.Contains(SerieType.Anime.ToString())) { this.IsAnime = true; } if (usedTypes.Contains(SerieType.Cartoon.ToString())) { this.IsCartoon = true; } if (usedTypes.Contains(SerieType.Movie.ToString())) { this.IsMovie = true; } } this.editMode = true; this.IsStreamingWebsiteVisible = true; } private void Done() { if (!this.NewStreamingWebsite.EndsWith("/")) { this.NewStreamingWebsite += "/"; } var website = string.Format("{0}{1}", this.NewStreamingWebsite, this.GenericUrl); var type = this.UsedOnTypes; if (this.UsedOnTypes.EndsWith(",")) { type = this.UsedOnTypes.Substring(0, this.UsedOnTypes.Length - 1); } if (this.editMode) { this.SelectedItem.StreamLanguage = this.SelectedStreamLanguage; this.SelectedItem.UsedOnTypes = type; this.SelectedItem.Website = website; this.SelectedItem.WhitespaceReplacement = this.WhitespaceReplacement; } else { this.Streams.Add(new StreamItem(website, this.WhitespaceReplacement, type, this.SelectedStreamLanguage)); } this.IsStreamingWebsiteVisible = false; } } }
31.681967
123
0.515885
[ "MIT" ]
dreanor/StreamCompanion
src/streamtemplate/ViewModel.cs
9,665
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Xamarin.Forms.Sandbox.WPF.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
40
151
0.584259
[ "MIT" ]
DaraOladapo/Xamarin.Forms
Xamarin.Forms.Sandbox.WPF/Properties/Settings.Designer.cs
1,082
C#
using System.Collections.Generic; using System.Threading.Tasks; using SanvaadServer.DataModels; namespace SanvaadServer.Hubs { public interface ISanvaadHub { Task ReceiveMessage(Message message); Task JoinedRoom(string roomId, string userId, string displayName); Task LeftRoom(string roomId, string userId); Task GetSelfDetails(User user); Task GetRemoteUser(string userName, string userId); Task PaticipantsList(List<User> users); Task AddScreenSharingModality(string userId, string screenSharingCallId); Task ScreenSharingStatus(string status, string userName); Task ScreeenSharingStatusWithUserList(List<string> userIds, string status); } }
34.809524
83
0.73461
[ "MIT" ]
SwapnilSilam/sanvaad
sanvaad-server/SanvaadServer/Hubs/ISanvaadHub.cs
733
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Dominio.Convertidores; using System.Data.Entity; namespace Dominio.Querys { public partial class Querys : Entidad.IEntidadQuery { public bool InsertarEntidad(Dtos.entidadDTO dto) { try { using (var modelo = new PersistenciaDatos.BDlogisticaEntities()) { var entity = dto.ToEntity(); modelo.entidad.Add(entity); modelo.SaveChanges(); return true; } } catch (Exception) { throw new NotImplementedException(); } } public bool ActualizarEntidad(Dtos.entidadDTO dto) { try { using (var modelo = new PersistenciaDatos.BDlogisticaEntities()) { var w = modelo.entidad.Where(q => q.Ruc == dto.Ruc).Select(q => q).FirstOrDefault(); if (w == null) return false; Dominio.Convertidores.entidadAssembler.Actualizar(dto, w); modelo.SaveChanges(); return true; } } catch (Exception) { throw new NotImplementedException(); } } public bool EliminarEntidad(string ruc) { try { using (var modelo = new PersistenciaDatos.BDlogisticaEntities()) { PersistenciaDatos.entidad x = modelo.entidad.Where(q => q.Ruc == ruc).Select(q => q).FirstOrDefault(); if (x == null) return false; modelo.entidad.Remove(x); modelo.SaveChanges(); return true; } } catch (Exception) { throw new NotImplementedException(); } } public List<Dtos.entidadDTO> ListarEntidadXnombre(string nombreentidad) { try { using (var modelo = new PersistenciaDatos.BDlogisticaEntities()) { var entity = modelo.entidad.Where(q => q.nombre_entidad.Contains(nombreentidad)).Select(q => q).ToList(); if (entity == null) return null; return Dominio.Convertidores.entidadAssembler.ToDTOs(entity); } } catch (Exception) { throw new NotImplementedException(); }; } public List<Dtos.entidadDTO> ListarEntidades() { try { using (var modelo = new PersistenciaDatos.BDlogisticaEntities()) { var entity = modelo.entidad.Select(q => q).ToList(); if (entity == null) return null; return Dominio.Convertidores.entidadAssembler.ToDTOs(entity); } } catch (Exception) { throw new NotImplementedException(); } } public Dtos.entidadDTO BuscarEntidadPorID(string ruc) { try { using (var modelo = new PersistenciaDatos.BDlogisticaEntities()) { var entity = modelo.entidad.Where(q => q.Ruc == ruc).Select(q => q).FirstOrDefault(); if (entity == null) return null; return Dominio.Convertidores.entidadAssembler.ToDTO(entity); } } catch (Exception) { throw new NotImplementedException(); }; } } }
30.077519
125
0.473454
[ "Apache-2.0" ]
Gsaico/MasterDetails_LogisticaMVVM
LOGISTICADB/Dominio/Querys/Entidad/EntidadQuery.cs
3,882
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Bbt.Campaign.Public.Dtos.Target.Group { public class TargetGroupDto { public TargetGroupDto() { TargetList = new List<TargetParameterDto>(); } public int Id { get; set; } //public decimal? TargetAmount { get; set; } public string? TargetAmountStr { get; set; } public string TargetAmountCurrencyCode{ get; set; } //public decimal? RemainAmount { get; set; } public string? RemainAmountStr { get; set; } //public int? TargetNumberOfTransaction { get; set; } public List<TargetParameterDto> TargetList { get; set; } } }
30.111111
69
0.648216
[ "MIT" ]
hub-burgan-com-tr/bbt.loyalty
src/Bbt.Campaign.Api/Bbt.Campaign.Public/Dtos/Target/Group/TargetGroupDto.cs
815
C#
using System; using System.Text; public class Rectangle : IDrawable { private int width; private int height; public Rectangle(int width, int height) { this.width = width; this.height = height; } public int Width { get { return this.width; } private set { this.width = value; } } public int Height { get { return this.height; } private set { this.height = value; } } public void Draw() { var drawingSymbol = '*'; var emptySymbol = ' '; var builder = new StringBuilder(); for (int row = 0; row < this.height; row++) { builder.Append(drawingSymbol); if (row == 0 || row == this.height - 1) { builder.Append(DrawLine(this.width - 2, drawingSymbol)); } else { builder.Append(DrawLine(this.width - 2, emptySymbol)); } if (this.width >= 2) { builder.Append(drawingSymbol); } builder.AppendLine(); } Console.WriteLine(builder.ToString().Trim()); } private string DrawLine(int lineWidth, char symbol) { var lineBuilder = new StringBuilder(); for (int i = 0; i < lineWidth; i++) { lineBuilder.Append(symbol); } return lineBuilder.ToString(); } }
22.353846
72
0.498968
[ "MIT" ]
inser788/CSharp-Fundamentals-OOP-Basics
Exercises/11 INTERFACES AND ABSTRACTION - LAB/Interfaces-Lab/01_Shapes/Rectangle.cs
1,455
C#
using System.Collections; using UnityEngine; namespace Vehicles.Car { [RequireComponent(typeof(AudioSource))] public class CarWheelEffects : MonoBehaviour { #region Members public Transform m_SkidTrailPrefab; public static Transform m_SkidTrailsDetachedParent; public ParticleSystem m_SkidParticles; public bool m_Skidding { get; private set; } public bool m_PlayingAudio { get; private set; } private AudioSource m_AudioSource; private Transform m_SkidTrail; private WheelCollider m_WheelCollider; #endregion #region Actions private void Start() { m_SkidParticles = transform.root.GetComponentInChildren<ParticleSystem>(); if (m_SkidParticles == null) { Debug.LogWarning(" no particle system found on car to generate smoke particles", gameObject); } else { m_SkidParticles.Stop(); } m_WheelCollider = GetComponent<WheelCollider>(); m_AudioSource = GetComponent<AudioSource>(); m_PlayingAudio = false; if (m_SkidTrailsDetachedParent == null) { m_SkidTrailsDetachedParent = new GameObject("Skid Trails - Detached").transform; } } public void EmitTyreSmoke() { m_SkidParticles.transform.position = transform.position - transform.up * m_WheelCollider.radius; m_SkidParticles.Emit(1); if (!m_Skidding) { StartCoroutine(StartSkidTrail()); } } public void PlayAudio() { m_AudioSource.Play(); m_PlayingAudio = true; } public void StopAudio() { m_AudioSource.Stop(); m_PlayingAudio = false; } public IEnumerator StartSkidTrail() { m_Skidding = true; m_SkidTrail = Instantiate(m_SkidTrailPrefab); while (m_SkidTrail == null) { yield return null; } m_SkidTrail.parent = transform; m_SkidTrail.localPosition = -Vector3.up * m_WheelCollider.radius; } public void EndSkidTrail() { if (!m_Skidding) { return; } m_Skidding = false; m_SkidTrail.parent = m_SkidTrailsDetachedParent; Destroy(m_SkidTrail.gameObject, 10); } #endregion } }
25.144231
109
0.551816
[ "MIT" ]
Voossu/Driving-Range-Project
Assets/[Common]/Vehicles/Scripts/Effects/CarWheelEffects.cs
2,615
C#
/* * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH * under one or more contributor license agreements. See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. Camunda licenses this file to you under the Apache License, * Version 2.0; 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 org.camunda.bpm.engine.impl.cmmn.operation { using CmmnActivityBehavior = org.camunda.bpm.engine.impl.cmmn.behavior.CmmnActivityBehavior; using CmmnExecution = org.camunda.bpm.engine.impl.cmmn.execution.CmmnExecution; /// <summary> /// @author Roman Smirnov /// /// </summary> public class AtomicOperationCaseExecutionComplete : AbstractAtomicOperationCaseExecutionComplete { public virtual string CanonicalName { get { return "case-execution-complete"; } } protected internal override void triggerBehavior(CmmnActivityBehavior behavior, CmmnExecution execution) { behavior.onCompletion(execution); } } }
33.477273
107
0.760353
[ "Apache-2.0" ]
luizfbicalho/Camunda.NET
camunda-bpm-platform-net/engine/src/main/java/org/camunda/bpm/engine/impl/cmmn/operation/AtomicOperationCaseExecutionComplete.cs
1,475
C#
// Copyright Naked Objects Group Ltd, 45 Station Road, Henley on Thames, UK, RG9 1AT // 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.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("RestfulObjects.Mvc.App")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("RestfulObjects.Mvc.App")] [assembly: AssemblyCopyright("Copyright © Microsoft 2014")] [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("e8badc58-a6a3-4e3e-8c3c-e8c01ba39000")] // 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 Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
44
136
0.755556
[ "Apache-2.0" ]
Giovanni-Russo-Boscoli/NakedObjectsFramework
Rest/NakedObjects.Rest.App/Properties/AssemblyInfo.cs
1,983
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. namespace System.Security.Permissions { [Serializable] public sealed partial class ZoneIdentityPermission : CodeAccessPermission { public ZoneIdentityPermission(PermissionState state) { } public ZoneIdentityPermission(SecurityZone zone) { } public SecurityZone SecurityZone { get; set; } public override IPermission Copy() { return this; } public override void FromXml(SecurityElement esd) { } public override IPermission Intersect(IPermission target) { return default(IPermission); } public override bool IsSubsetOf(IPermission target) { return false; } public override SecurityElement ToXml() { return default(SecurityElement); } public override IPermission Union(IPermission target) { return default(IPermission); } } }
48.380952
98
0.730315
[ "MIT" ]
Aevitas/corefx
src/System.Security.Permissions/src/System/Security/Permissions/ZoneIdentityPermission.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. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.NetApp { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for SnapshotsOperations. /// </summary> public static partial class SnapshotsOperationsExtensions { /// <summary> /// Describe all snapshots /// </summary> /// <remarks> /// List all snapshots associated with the volume /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='accountName'> /// The name of the NetApp account /// </param> /// <param name='poolName'> /// The name of the capacity pool /// </param> /// <param name='volumeName'> /// The name of the volume /// </param> public static IEnumerable<Snapshot> List(this ISnapshotsOperations operations, string resourceGroupName, string accountName, string poolName, string volumeName) { return operations.ListAsync(resourceGroupName, accountName, poolName, volumeName).GetAwaiter().GetResult(); } /// <summary> /// Describe all snapshots /// </summary> /// <remarks> /// List all snapshots associated with the volume /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='accountName'> /// The name of the NetApp account /// </param> /// <param name='poolName'> /// The name of the capacity pool /// </param> /// <param name='volumeName'> /// The name of the volume /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IEnumerable<Snapshot>> ListAsync(this ISnapshotsOperations operations, string resourceGroupName, string accountName, string poolName, string volumeName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, accountName, poolName, volumeName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Describe a snapshot /// </summary> /// <remarks> /// Get details of the specified snapshot /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='accountName'> /// The name of the NetApp account /// </param> /// <param name='poolName'> /// The name of the capacity pool /// </param> /// <param name='volumeName'> /// The name of the volume /// </param> /// <param name='snapshotName'> /// The name of the snapshot /// </param> public static Snapshot Get(this ISnapshotsOperations operations, string resourceGroupName, string accountName, string poolName, string volumeName, string snapshotName) { return operations.GetAsync(resourceGroupName, accountName, poolName, volumeName, snapshotName).GetAwaiter().GetResult(); } /// <summary> /// Describe a snapshot /// </summary> /// <remarks> /// Get details of the specified snapshot /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='accountName'> /// The name of the NetApp account /// </param> /// <param name='poolName'> /// The name of the capacity pool /// </param> /// <param name='volumeName'> /// The name of the volume /// </param> /// <param name='snapshotName'> /// The name of the snapshot /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Snapshot> GetAsync(this ISnapshotsOperations operations, string resourceGroupName, string accountName, string poolName, string volumeName, string snapshotName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, accountName, poolName, volumeName, snapshotName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Create a snapshot /// </summary> /// <remarks> /// Create the specified snapshot within the given volume /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Snapshot object supplied in the body of the operation. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='accountName'> /// The name of the NetApp account /// </param> /// <param name='poolName'> /// The name of the capacity pool /// </param> /// <param name='volumeName'> /// The name of the volume /// </param> /// <param name='snapshotName'> /// The name of the snapshot /// </param> public static Snapshot Create(this ISnapshotsOperations operations, Snapshot body, string resourceGroupName, string accountName, string poolName, string volumeName, string snapshotName) { return operations.CreateAsync(body, resourceGroupName, accountName, poolName, volumeName, snapshotName).GetAwaiter().GetResult(); } /// <summary> /// Create a snapshot /// </summary> /// <remarks> /// Create the specified snapshot within the given volume /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Snapshot object supplied in the body of the operation. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='accountName'> /// The name of the NetApp account /// </param> /// <param name='poolName'> /// The name of the capacity pool /// </param> /// <param name='volumeName'> /// The name of the volume /// </param> /// <param name='snapshotName'> /// The name of the snapshot /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Snapshot> CreateAsync(this ISnapshotsOperations operations, Snapshot body, string resourceGroupName, string accountName, string poolName, string volumeName, string snapshotName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateWithHttpMessagesAsync(body, resourceGroupName, accountName, poolName, volumeName, snapshotName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Update a snapshot /// </summary> /// <remarks> /// Patch a snapshot /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Snapshot object supplied in the body of the operation. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='accountName'> /// The name of the NetApp account /// </param> /// <param name='poolName'> /// The name of the capacity pool /// </param> /// <param name='volumeName'> /// The name of the volume /// </param> /// <param name='snapshotName'> /// The name of the snapshot /// </param> public static Snapshot Update(this ISnapshotsOperations operations, object body, string resourceGroupName, string accountName, string poolName, string volumeName, string snapshotName) { return operations.UpdateAsync(body, resourceGroupName, accountName, poolName, volumeName, snapshotName).GetAwaiter().GetResult(); } /// <summary> /// Update a snapshot /// </summary> /// <remarks> /// Patch a snapshot /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Snapshot object supplied in the body of the operation. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='accountName'> /// The name of the NetApp account /// </param> /// <param name='poolName'> /// The name of the capacity pool /// </param> /// <param name='volumeName'> /// The name of the volume /// </param> /// <param name='snapshotName'> /// The name of the snapshot /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Snapshot> UpdateAsync(this ISnapshotsOperations operations, object body, string resourceGroupName, string accountName, string poolName, string volumeName, string snapshotName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.UpdateWithHttpMessagesAsync(body, resourceGroupName, accountName, poolName, volumeName, snapshotName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Delete a snapshot /// </summary> /// <remarks> /// Delete snapshot /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='accountName'> /// The name of the NetApp account /// </param> /// <param name='poolName'> /// The name of the capacity pool /// </param> /// <param name='volumeName'> /// The name of the volume /// </param> /// <param name='snapshotName'> /// The name of the snapshot /// </param> public static void Delete(this ISnapshotsOperations operations, string resourceGroupName, string accountName, string poolName, string volumeName, string snapshotName) { operations.DeleteAsync(resourceGroupName, accountName, poolName, volumeName, snapshotName).GetAwaiter().GetResult(); } /// <summary> /// Delete a snapshot /// </summary> /// <remarks> /// Delete snapshot /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='accountName'> /// The name of the NetApp account /// </param> /// <param name='poolName'> /// The name of the capacity pool /// </param> /// <param name='volumeName'> /// The name of the volume /// </param> /// <param name='snapshotName'> /// The name of the snapshot /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this ISnapshotsOperations operations, string resourceGroupName, string accountName, string poolName, string volumeName, string snapshotName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteWithHttpMessagesAsync(resourceGroupName, accountName, poolName, volumeName, snapshotName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Create a new Snapshot Restore Files request /// </summary> /// <remarks> /// Restore the specified files from the specified snapshot to the active /// filesystem /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Restore payload supplied in the body of the operation. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='accountName'> /// The name of the NetApp account /// </param> /// <param name='poolName'> /// The name of the capacity pool /// </param> /// <param name='volumeName'> /// The name of the volume /// </param> /// <param name='snapshotName'> /// The name of the snapshot /// </param> public static void RestoreFiles(this ISnapshotsOperations operations, SnapshotRestoreFiles body, string resourceGroupName, string accountName, string poolName, string volumeName, string snapshotName) { operations.RestoreFilesAsync(body, resourceGroupName, accountName, poolName, volumeName, snapshotName).GetAwaiter().GetResult(); } /// <summary> /// Create a new Snapshot Restore Files request /// </summary> /// <remarks> /// Restore the specified files from the specified snapshot to the active /// filesystem /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Restore payload supplied in the body of the operation. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='accountName'> /// The name of the NetApp account /// </param> /// <param name='poolName'> /// The name of the capacity pool /// </param> /// <param name='volumeName'> /// The name of the volume /// </param> /// <param name='snapshotName'> /// The name of the snapshot /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task RestoreFilesAsync(this ISnapshotsOperations operations, SnapshotRestoreFiles body, string resourceGroupName, string accountName, string poolName, string volumeName, string snapshotName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.RestoreFilesWithHttpMessagesAsync(body, resourceGroupName, accountName, poolName, volumeName, snapshotName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Create a snapshot /// </summary> /// <remarks> /// Create the specified snapshot within the given volume /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Snapshot object supplied in the body of the operation. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='accountName'> /// The name of the NetApp account /// </param> /// <param name='poolName'> /// The name of the capacity pool /// </param> /// <param name='volumeName'> /// The name of the volume /// </param> /// <param name='snapshotName'> /// The name of the snapshot /// </param> public static Snapshot BeginCreate(this ISnapshotsOperations operations, Snapshot body, string resourceGroupName, string accountName, string poolName, string volumeName, string snapshotName) { return operations.BeginCreateAsync(body, resourceGroupName, accountName, poolName, volumeName, snapshotName).GetAwaiter().GetResult(); } /// <summary> /// Create a snapshot /// </summary> /// <remarks> /// Create the specified snapshot within the given volume /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Snapshot object supplied in the body of the operation. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='accountName'> /// The name of the NetApp account /// </param> /// <param name='poolName'> /// The name of the capacity pool /// </param> /// <param name='volumeName'> /// The name of the volume /// </param> /// <param name='snapshotName'> /// The name of the snapshot /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Snapshot> BeginCreateAsync(this ISnapshotsOperations operations, Snapshot body, string resourceGroupName, string accountName, string poolName, string volumeName, string snapshotName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginCreateWithHttpMessagesAsync(body, resourceGroupName, accountName, poolName, volumeName, snapshotName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Update a snapshot /// </summary> /// <remarks> /// Patch a snapshot /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Snapshot object supplied in the body of the operation. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='accountName'> /// The name of the NetApp account /// </param> /// <param name='poolName'> /// The name of the capacity pool /// </param> /// <param name='volumeName'> /// The name of the volume /// </param> /// <param name='snapshotName'> /// The name of the snapshot /// </param> public static Snapshot BeginUpdate(this ISnapshotsOperations operations, object body, string resourceGroupName, string accountName, string poolName, string volumeName, string snapshotName) { return operations.BeginUpdateAsync(body, resourceGroupName, accountName, poolName, volumeName, snapshotName).GetAwaiter().GetResult(); } /// <summary> /// Update a snapshot /// </summary> /// <remarks> /// Patch a snapshot /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Snapshot object supplied in the body of the operation. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='accountName'> /// The name of the NetApp account /// </param> /// <param name='poolName'> /// The name of the capacity pool /// </param> /// <param name='volumeName'> /// The name of the volume /// </param> /// <param name='snapshotName'> /// The name of the snapshot /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Snapshot> BeginUpdateAsync(this ISnapshotsOperations operations, object body, string resourceGroupName, string accountName, string poolName, string volumeName, string snapshotName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginUpdateWithHttpMessagesAsync(body, resourceGroupName, accountName, poolName, volumeName, snapshotName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Delete a snapshot /// </summary> /// <remarks> /// Delete snapshot /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='accountName'> /// The name of the NetApp account /// </param> /// <param name='poolName'> /// The name of the capacity pool /// </param> /// <param name='volumeName'> /// The name of the volume /// </param> /// <param name='snapshotName'> /// The name of the snapshot /// </param> public static void BeginDelete(this ISnapshotsOperations operations, string resourceGroupName, string accountName, string poolName, string volumeName, string snapshotName) { operations.BeginDeleteAsync(resourceGroupName, accountName, poolName, volumeName, snapshotName).GetAwaiter().GetResult(); } /// <summary> /// Delete a snapshot /// </summary> /// <remarks> /// Delete snapshot /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='accountName'> /// The name of the NetApp account /// </param> /// <param name='poolName'> /// The name of the capacity pool /// </param> /// <param name='volumeName'> /// The name of the volume /// </param> /// <param name='snapshotName'> /// The name of the snapshot /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task BeginDeleteAsync(this ISnapshotsOperations operations, string resourceGroupName, string accountName, string poolName, string volumeName, string snapshotName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, accountName, poolName, volumeName, snapshotName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Create a new Snapshot Restore Files request /// </summary> /// <remarks> /// Restore the specified files from the specified snapshot to the active /// filesystem /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Restore payload supplied in the body of the operation. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='accountName'> /// The name of the NetApp account /// </param> /// <param name='poolName'> /// The name of the capacity pool /// </param> /// <param name='volumeName'> /// The name of the volume /// </param> /// <param name='snapshotName'> /// The name of the snapshot /// </param> public static void BeginRestoreFiles(this ISnapshotsOperations operations, SnapshotRestoreFiles body, string resourceGroupName, string accountName, string poolName, string volumeName, string snapshotName) { operations.BeginRestoreFilesAsync(body, resourceGroupName, accountName, poolName, volumeName, snapshotName).GetAwaiter().GetResult(); } /// <summary> /// Create a new Snapshot Restore Files request /// </summary> /// <remarks> /// Restore the specified files from the specified snapshot to the active /// filesystem /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Restore payload supplied in the body of the operation. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='accountName'> /// The name of the NetApp account /// </param> /// <param name='poolName'> /// The name of the capacity pool /// </param> /// <param name='volumeName'> /// The name of the volume /// </param> /// <param name='snapshotName'> /// The name of the snapshot /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task BeginRestoreFilesAsync(this ISnapshotsOperations operations, SnapshotRestoreFiles body, string resourceGroupName, string accountName, string poolName, string volumeName, string snapshotName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.BeginRestoreFilesWithHttpMessagesAsync(body, resourceGroupName, accountName, poolName, volumeName, snapshotName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } } }
44.150725
293
0.526983
[ "MIT" ]
AikoBB/azure-sdk-for-net
sdk/netapp/Microsoft.Azure.Management.NetApp/src/Generated/SnapshotsOperationsExtensions.cs
30,464
C#
#region License // FocusBehaviour.cs // // Copyright (c) 2012 Xoqal.com // // 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. #endregion namespace Xoqal.Presentation.Extentions { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; /// <summary> /// Provide set focus operation for binding. /// </summary> public static class FocusBehaviour { /// <summary> /// Identifies the ForceFocus dependency property /// </summary> public static readonly DependencyProperty ForceFocusProperty = DependencyProperty.RegisterAttached( "ForceFocus", typeof(bool), typeof(FocusBehaviour), new FrameworkPropertyMetadata( false, FrameworkPropertyMetadataOptions.None, (d, e) => { if ((bool)e.NewValue) { if (d is UIElement) { ((UIElement)d).Focus(); } } })); /// <summary> /// Gets the force focus. /// </summary> /// <param name="d">The d.</param> /// <returns></returns> public static bool GetForceFocus(DependencyObject d) { return (bool)d.GetValue(FocusBehaviour.ForceFocusProperty); } /// <summary> /// Sets the force focus. /// </summary> /// <param name="d">The d.</param> /// <param name="val">if set to <c>true</c> [val].</param> public static void SetForceFocus(DependencyObject d, bool val) { d.SetValue(FocusBehaviour.ForceFocusProperty, val); } } }
32.093333
75
0.5484
[ "Apache-2.0" ]
AmirKarimi/Xoqal
Source/Xoqal.Presentation/Extentions/FocusBehaviour.cs
2,407
C#
/* * Copyright (C) Sportradar AG. See LICENSE for full license governing this code */ using System; using System.Collections.Generic; using Dawn; using System.Linq; using Sportradar.OddsFeed.SDK.Messages; namespace Sportradar.OddsFeed.SDK.Entities.Internal { /// <summary> /// Defines builder for routing keys and checks for feed sessions combo validation /// </summary> public static class FeedRoutingKeyBuilder { // hi.-.live.odds_change.5.sr:match.12329150.nodeId (.producerId) // Note: there is a dot in event_id /// <summary> /// Validates input list of message interests and returns list of routing keys combination per interest /// </summary> /// <param name="interests">The list of all session interests</param> /// <param name="nodeId">The node id</param> /// <returns></returns> public static IEnumerable<IEnumerable<string>> GenerateKeys(IEnumerable<MessageInterest> interests, int nodeId = 0) { Guard.Argument(interests, nameof(interests)).NotNull().NotEmpty(); var messageInterests = interests as IList<MessageInterest> ?? interests.ToList(); var sessionKeys = new List<List<string>>(messageInterests.Count); ValidateInterestCombination(messageInterests); var both = HaveBothLowAndHigh(messageInterests); foreach (var interest in messageInterests) { if (both && interest == MessageInterest.LowPriorityMessages) { sessionKeys.Add(GetBaseKeys(interest, nodeId).Union(GetLiveKeys()).ToList()); continue; } sessionKeys.Add(GetBaseKeys(interest, nodeId).Union(GetStandardKeys().Union(GetLiveKeys())).ToList()); } return sessionKeys; } /// <summary> /// Gets the standard keys usually added to all sessions /// </summary> /// <returns>IEnumerable&lt;System.String&gt;.</returns> public static IEnumerable<string> GetStandardKeys() { return new List<string> { "-.-.-.product_down.#", "-.-.-.snapshot_complete.#" }; } /// <summary> /// Gets the live keys /// </summary> /// <returns>IEnumerable&lt;System.String&gt;.</returns> public static IEnumerable<string> GetLiveKeys() { return new List<string> { "-.-.-.alive.#" }; } private static void ValidateInterestCombination(IEnumerable<MessageInterest> interests) { var messageInterests = interests as IList<MessageInterest> ?? interests.ToList(); if (!messageInterests.Any()) { throw new ArgumentException("Empty MessageInterest list not allowed.", nameof(interests)); } if (messageInterests.Count == 1) { return; } if (messageInterests.Count > 3) { throw new ArgumentException("Combination of MessageInterests is not supported.", nameof(interests)); } if ((messageInterests.Contains(MessageInterest.LowPriorityMessages) && !messageInterests.Contains(MessageInterest.HighPriorityMessages)) && !(messageInterests.Contains(MessageInterest.LowPriorityMessages) && messageInterests.Contains(MessageInterest.HighPriorityMessages))) { throw new ArgumentException("Combination must have both Low and High priority messages", nameof(interests)); } } private static bool HaveBothLowAndHigh(IEnumerable<MessageInterest> interests) { var low = false; var high = false; foreach (var interest in interests) { if (interest == MessageInterest.HighPriorityMessages) { high = true; } if (interest == MessageInterest.LowPriorityMessages) { low = true; } } return low && high; } private static IEnumerable<string> GetBaseKeys(MessageInterest interest, int nodeId) { var keys = new List<string>(); if (interest == MessageInterest.AllMessages) { keys = AllMessages().ToList(); } else if (interest == MessageInterest.LiveMessagesOnly) { keys = LiveMessagesOnly().ToList(); } else if (interest == MessageInterest.PrematchMessagesOnly) { keys = PrematchMessagesOnly().ToList(); } else if (interest == MessageInterest.HighPriorityMessages) { keys = HighPriorityMessages().ToList(); } else if (interest == MessageInterest.LowPriorityMessages) { keys = LowPriorityMessages().ToList(); } else if (interest == MessageInterest.VirtualSportMessages) { keys = VirtualSportMessages().ToList(); } else if (interest.IsEventSpecific) { keys = SpecificEventsOnly(interest.Events).ToList(); } if (keys.Any()) { var tmpKeys = new List<string>(); foreach (var key in keys) { tmpKeys.Add($"{key}.-.#"); if (nodeId != 0) { tmpKeys.Add($"{key}.{nodeId}.#"); } } keys = tmpKeys; } if (!keys.Any()) { throw new ArgumentOutOfRangeException(nameof(interest), "Unknown MessageInterest."); } return keys; } /// <summary> /// Constructs a <see cref="MessageInterest"/> indicating an interest in all messages /// </summary> /// <returns>A <see cref="MessageInterest"/> indicating an interest in all messages</returns> private static IEnumerable<string> AllMessages() { return new[] { //$"*.*.*.{odds_change.MessageName}.*.*.*", //$"*.*.*.{bet_stop.MessageName}.*.*.*", //$"*.*.*.{bet_settlement.MessageName}.*.*.*", //$"*.*.*.{rollback_bet_settlement.MessageName}.*.*.*", //$"*.*.*.{bet_cancel.MessageName}.*.*.*", //$"*.*.*.{rollback_bet_cancel.MessageName}.*.*.*", //$"*.*.*.{fixture_change.MessageName}.*.*.*" "*.*.*.*.*.*.*" }; } /// <summary> /// Constructs a <see cref="MessageInterest"/> indicating an interest in live messages /// </summary> /// <returns>A <see cref="MessageInterest"/> indicating an interest in live messages</returns> private static IEnumerable<string> LiveMessagesOnly() { return new[] { //$"*.*.live.{odds_change.MessageName}.*.*.*", //$"*.*.live.{bet_stop.MessageName}.*.*.*", //$"*.*.live.{bet_settlement.MessageName}.*.*.*", //$"*.*.live.{rollback_bet_settlement.MessageName}.*.*.*", //$"*.*.live.{bet_cancel.MessageName}.*.*.*", //$"*.*.live.{rollback_bet_cancel.MessageName}.*.*.*", //$"*.*.live.{fixture_change.MessageName}.*.*.*" "*.*.live.*.*.*.*" }; } /// <summary> /// Constructs a <see cref="MessageInterest"/> indicating an interest in pre-match messages /// </summary> /// <returns>A <see cref="MessageInterest"/> indicating an interest in pre-match messages</returns> private static IEnumerable<string> PrematchMessagesOnly() { return new[] { //$"*.pre.*.{odds_change.MessageName}.*.*.*", //$"*.pre.*.{bet_stop.MessageName}.*.*.*", //$"*.pre.*.{bet_settlement.MessageName}.*.*.*", //$"*.pre.*.{rollback_bet_settlement.MessageName}.*.*.*", //$"*.pre.*.{bet_cancel.MessageName}.*.*.*", //$"*.pre.*.{rollback_bet_cancel.MessageName}.*.*.*", //$"*.pre.*.{fixture_change.MessageName}.*.*.*" "*.pre.*.*.*.*.*" }; } /// <summary> /// Constructs a <see cref="MessageInterest"/> indicating an interest in hi priority messages /// </summary> /// <returns>A <see cref="MessageInterest"/> indicating an interest in high priority messages</returns> private static IEnumerable<string> HighPriorityMessages() { return new[] { "hi.*.*.*.*.*.*" }; } /// <summary> /// Constructs a <see cref="MessageInterest"/> indicating an interest in low priority messages /// </summary> /// <returns>A <see cref="MessageInterest"/> indicating an interest in low priority messages</returns> private static IEnumerable<string> LowPriorityMessages() { return new[] { "lo.*.*.*.*.*.*" }; } /// <summary> /// Constructs a <see cref="MessageInterest"/> indicating an interest in low priority messages /// </summary> /// <returns>A <see cref="MessageInterest"/> indicating an interest in low priority messages</returns> private static IEnumerable<string> VirtualSportMessages() { return new[] { "*.virt.*.*.*.*.*", "*.*.virt.*.*.*.*" }; } /// <summary> /// Constructs a <see cref="MessageInterest"/> indicating an interest in messages associated with specific events /// </summary> /// <param name="eventIds">A <see cref="IEnumerable{Integer}"/> specifying the target events</param> /// <returns>A <see cref="MessageInterest"/> indicating an interest in messages associated with specific events</returns> private static IEnumerable<string> SpecificEventsOnly(IEnumerable<URN> eventIds) { Guard.Argument(eventIds, nameof(eventIds)).NotNull().NotEmpty(); //channels using this routing key will also receive 'system' messages so they have to be manually removed in the receiver return eventIds.Select(u => $"#.{u.Prefix}:{u.Type}.{u.Id}"); } } }
39.01444
152
0.525678
[ "Apache-2.0" ]
deuko/UnifiedOddsSdkNet
src/Sportradar.OddsFeed.SDK.Entities/Internal/FeedRoutingKeyBuilder.cs
10,809
C#
namespace SaaSFulfillmentClient { using System; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Newtonsoft.Json; using SaaSFulfillmentClient.AzureAD; using SaaSFulfillmentClient.Models; public class CustomMeteringClient : RestClient<CustomMeteringClient>, ICustomMeteringClient { public CustomMeteringClient(IOptionsMonitor<SecuredFulfillmentClientConfiguration> optionsMonitor, ILogger<CustomMeteringClient> logger) : this(null, optionsMonitor.CurrentValue, logger) { } public CustomMeteringClient(SecuredFulfillmentClientConfiguration options, ILogger<CustomMeteringClient> logger) : this(null, options, logger) { } public CustomMeteringClient( HttpMessageHandler httpMessageHandler, SecuredFulfillmentClientConfiguration options, ILogger<CustomMeteringClient> logger) : base(options, logger, httpMessageHandler) { } public async Task<CustomMeteringRequestResult> RecordBatchUsageAsync(Guid requestId, Guid correlationId, IEnumerable<Usage> usage, CancellationToken cancellationToken) { var requestUrl = FluentUriBuilder .Start(this.baseUri) .AddPath("batchUsageEvent") .AddQuery(DefaultApiVersionParameterName, this.apiVersion) .Uri; requestId = requestId == default ? Guid.NewGuid() : requestId; correlationId = correlationId == default ? Guid.NewGuid() : correlationId; var response = await this.SendRequestAndReturnResult( HttpMethod.Post, requestUrl, requestId, correlationId, null, JsonConvert.SerializeObject(usage), cancellationToken); switch (response.StatusCode) { case HttpStatusCode.OK: return await AzureMarketplaceRequestResult.ParseAsync<CustomMeteringBatchSuccessResult>(response); case HttpStatusCode.Forbidden: return await AzureMarketplaceRequestResult.ParseAsync<CustomMeteringForbiddenResult>(response); case HttpStatusCode.Conflict: return await AzureMarketplaceRequestResult.ParseAsync<CustomMeteringConflictResult>(response); case HttpStatusCode.BadRequest: return await AzureMarketplaceRequestResult.ParseAsync<CustomMeteringBadRequestResult>(response); default: throw new ApplicationException($"Unknown response from the API {await response.Content.ReadAsStringAsync()}"); } } public async Task<CustomMeteringRequestResult> RecordUsageAsync(Guid requestId, Guid correlationId, Usage usage, CancellationToken cancellationToken) { var requestUrl = FluentUriBuilder .Start(this.baseUri) .AddPath("usageEvent") .AddQuery(DefaultApiVersionParameterName, this.apiVersion) .Uri; requestId = requestId == default ? Guid.NewGuid() : requestId; correlationId = correlationId == default ? Guid.NewGuid() : correlationId; var response = await this.SendRequestAndReturnResult( HttpMethod.Post, requestUrl, requestId, correlationId, null, JsonConvert.SerializeObject(usage), cancellationToken); switch (response.StatusCode) { case HttpStatusCode.OK: return await AzureMarketplaceRequestResult.ParseAsync<CustomMeteringSuccessResult>(response); case HttpStatusCode.Forbidden: return await AzureMarketplaceRequestResult.ParseAsync<CustomMeteringForbiddenResult>(response); case HttpStatusCode.Conflict: return await AzureMarketplaceRequestResult.ParseAsync<CustomMeteringConflictResult>(response); case HttpStatusCode.BadRequest: return await AzureMarketplaceRequestResult.ParseAsync<CustomMeteringBadRequestResult>(response); default: throw new ApplicationException($"Unknown response from the API {await response.Content.ReadAsStringAsync()}"); } } } }
41.375
175
0.602216
[ "MIT" ]
dstarr/AzureMarketplaceSaaSApiClient
src/CustomMeteringClient.cs
4,967
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Management.Automation; using System.Management.Automation.Internal; using System.Text; using Microsoft.PowerShell.Commands; namespace Microsoft.PowerShell.Commands.Internal.Format { internal static class DefaultScalarTypes { internal static bool IsTypeInList(Collection<string> typeNames) { // NOTE: we do not use inheritance here, since we deal with // value types or with types where inheritance is not a factor for the selection string typeName = PSObjectHelper.PSObjectIsOfExactType(typeNames); if (string.IsNullOrEmpty(typeName)) return false; string originalTypeName = Deserializer.MaskDeserializationPrefix(typeName); if (string.IsNullOrEmpty(originalTypeName)) return false; // check if the type is derived from a System.Enum // e.g. in C# // enum Foo { Red, Black, Green} if (PSObjectHelper.PSObjectIsEnum(typeNames)) return true; return s_defaultScalarTypesHash.Contains(originalTypeName); } static DefaultScalarTypes() { s_defaultScalarTypesHash.Add("System.String"); s_defaultScalarTypesHash.Add("System.SByte"); s_defaultScalarTypesHash.Add("System.Byte"); s_defaultScalarTypesHash.Add("System.Int16"); s_defaultScalarTypesHash.Add("System.UInt16"); s_defaultScalarTypesHash.Add("System.Int32"); s_defaultScalarTypesHash.Add("System.UInt32"); s_defaultScalarTypesHash.Add("System.Int64"); s_defaultScalarTypesHash.Add("System.UInt64"); s_defaultScalarTypesHash.Add("System.Char"); s_defaultScalarTypesHash.Add("System.Single"); s_defaultScalarTypesHash.Add("System.Double"); s_defaultScalarTypesHash.Add("System.Boolean"); s_defaultScalarTypesHash.Add("System.Decimal"); s_defaultScalarTypesHash.Add("System.IntPtr"); s_defaultScalarTypesHash.Add("System.Security.SecureString"); s_defaultScalarTypesHash.Add("System.Numerics.BigInteger"); } private static readonly HashSet<string> s_defaultScalarTypesHash = new HashSet<string>(StringComparer.OrdinalIgnoreCase); } /// <summary> /// Class to manage the selection of a desired view type and /// manage state associated to the selected view. /// </summary> internal sealed class FormatViewManager { #region tracer [TraceSource("FormatViewBinding", "Format view binding")] private static PSTraceSource s_formatViewBindingTracer = PSTraceSource.GetTracer("FormatViewBinding", "Format view binding", false); #endregion tracer private static string PSObjectTypeName(PSObject so) { // if so is not null, its TypeNames will not be null if (so != null) { var typeNames = so.InternalTypeNames; if (typeNames.Count > 0) { return typeNames[0]; } } return string.Empty; } internal void Initialize(TerminatingErrorContext errorContext, PSPropertyExpressionFactory expressionFactory, TypeInfoDataBase db, PSObject so, FormatShape shape, FormattingCommandLineParameters parameters) { ViewDefinition view = null; const string findViewType = "FINDING VIEW TYPE: {0}"; const string findViewShapeType = "FINDING VIEW {0} TYPE: {1}"; const string findViewNameType = "FINDING VIEW NAME: {0} TYPE: {1}"; const string viewFound = "An applicable view has been found"; const string viewNotFound = "No applicable view has been found"; try { DisplayDataQuery.SetTracer(s_formatViewBindingTracer); // shape not specified: we need to select one var typeNames = so.InternalTypeNames; if (shape == FormatShape.Undefined) { using (s_formatViewBindingTracer.TraceScope(findViewType, PSObjectTypeName(so))) { view = DisplayDataQuery.GetViewByShapeAndType(expressionFactory, db, shape, typeNames, null); } if (view != null) { // we got a matching view from the database // use this and we are done _viewGenerator = SelectViewGeneratorFromViewDefinition( errorContext, expressionFactory, db, view, parameters); s_formatViewBindingTracer.WriteLine(viewFound); PrepareViewForRemoteObjects(ViewGenerator, so); return; } s_formatViewBindingTracer.WriteLine(viewNotFound); // we did not get any default view (and shape), we need to force one // we just select properties out of the object itself, since they were not // specified on the command line _viewGenerator = SelectViewGeneratorFromProperties(shape, so, errorContext, expressionFactory, db, null); PrepareViewForRemoteObjects(ViewGenerator, so); return; } // we have a predefined shape: did the user specify properties on the command line? if (parameters != null && parameters.mshParameterList.Count > 0) { _viewGenerator = SelectViewGeneratorFromProperties(shape, so, errorContext, expressionFactory, db, parameters); return; } // predefined shape: did the user specify the name of a view? if (parameters != null && !string.IsNullOrEmpty(parameters.viewName)) { using (s_formatViewBindingTracer.TraceScope(findViewNameType, parameters.viewName, PSObjectTypeName(so))) { view = DisplayDataQuery.GetViewByShapeAndType(expressionFactory, db, shape, typeNames, parameters.viewName); } if (view != null) { _viewGenerator = SelectViewGeneratorFromViewDefinition( errorContext, expressionFactory, db, view, parameters); s_formatViewBindingTracer.WriteLine(viewFound); return; } s_formatViewBindingTracer.WriteLine(viewNotFound); // illegal input, we have to terminate ProcessUnknownViewName(errorContext, parameters.viewName, so, db, shape); } // predefined shape: do we have a default view in format.ps1xml? using (s_formatViewBindingTracer.TraceScope(findViewShapeType, shape, PSObjectTypeName(so))) { view = DisplayDataQuery.GetViewByShapeAndType(expressionFactory, db, shape, typeNames, null); } if (view != null) { _viewGenerator = SelectViewGeneratorFromViewDefinition( errorContext, expressionFactory, db, view, parameters); s_formatViewBindingTracer.WriteLine(viewFound); PrepareViewForRemoteObjects(ViewGenerator, so); return; } s_formatViewBindingTracer.WriteLine(viewNotFound); // we just select properties out of the object itself _viewGenerator = SelectViewGeneratorFromProperties(shape, so, errorContext, expressionFactory, db, parameters); PrepareViewForRemoteObjects(ViewGenerator, so); } finally { DisplayDataQuery.ResetTracer(); } } /// <summary> /// Prepares a given view for remote object processing ie., lets the view /// display (or not) ComputerName property. This will query the object to /// check if ComputerName property is present. If present, this will prepare /// the view. /// </summary> /// <param name="viewGenerator"></param> /// <param name="so"></param> private static void PrepareViewForRemoteObjects(ViewGenerator viewGenerator, PSObject so) { if (PSObjectHelper.ShouldShowComputerNameProperty(so)) { viewGenerator.PrepareForRemoteObjects(so); } } /// <summary> /// Helper method to process Unknown error message. /// It helps is creating appropriate error message to /// be displayed to the user. /// </summary> /// <param name="errorContext">Error context.</param> /// <param name="viewName">Uses supplied view name.</param> /// <param name="so">Source object.</param> /// <param name="db">Types info database.</param> /// <param name="formatShape">Requested format shape.</param> private static void ProcessUnknownViewName(TerminatingErrorContext errorContext, string viewName, PSObject so, TypeInfoDataBase db, FormatShape formatShape) { string msg = null; bool foundValidViews = false; string formatTypeName = null; string separator = ", "; StringBuilder validViewFormats = new StringBuilder(); if (so != null && so.BaseObject != null && db != null && db.viewDefinitionsSection != null && db.viewDefinitionsSection.viewDefinitionList != null && db.viewDefinitionsSection.viewDefinitionList.Count > 0) { StringBuilder validViews = new StringBuilder(); string currentObjectTypeName = so.BaseObject.GetType().ToString(); Type formatType = null; if (formatShape == FormatShape.Table) { formatType = typeof(TableControlBody); formatTypeName = "Table"; } else if (formatShape == FormatShape.List) { formatType = typeof(ListControlBody); formatTypeName = "List"; } else if (formatShape == FormatShape.Wide) { formatType = typeof(WideControlBody); formatTypeName = "Wide"; } else if (formatShape == FormatShape.Complex) { formatType = typeof(ComplexControlBody); formatTypeName = "Custom"; } if (formatType != null) { foreach (ViewDefinition currentViewDefinition in db.viewDefinitionsSection.viewDefinitionList) { if (currentViewDefinition.mainControl != null) { foreach (TypeOrGroupReference currentTypeOrGroupReference in currentViewDefinition.appliesTo.referenceList) { if (!string.IsNullOrEmpty(currentTypeOrGroupReference.name) && string.Equals(currentObjectTypeName, currentTypeOrGroupReference.name, StringComparison.OrdinalIgnoreCase)) { if (currentViewDefinition.mainControl.GetType() == formatType) { validViews.Append(currentViewDefinition.name); validViews.Append(separator); } else if (string.Equals(viewName, currentViewDefinition.name, StringComparison.OrdinalIgnoreCase)) { string cmdletFormatName = null; if (currentViewDefinition.mainControl is TableControlBody) { cmdletFormatName = "Format-Table"; } else if (currentViewDefinition.mainControl is ListControlBody) { cmdletFormatName = "Format-List"; } else if (currentViewDefinition.mainControl is WideControlBody) { cmdletFormatName = "Format-Wide"; } else if (currentViewDefinition.mainControl is ComplexControlBody) { cmdletFormatName = "Format-Custom"; } if (validViewFormats.Length == 0) { string suggestValidViewNamePrefix = StringUtil.Format(FormatAndOut_format_xxx.SuggestValidViewNamePrefix); validViewFormats.Append(suggestValidViewNamePrefix); } else { validViewFormats.Append(", "); } validViewFormats.Append(cmdletFormatName); } } } } } } if (validViews.Length > 0) { validViews.Remove(validViews.Length - separator.Length, separator.Length); msg = StringUtil.Format(FormatAndOut_format_xxx.InvalidViewNameError, viewName, formatTypeName, validViews.ToString()); foundValidViews = true; } } if (!foundValidViews) { StringBuilder unKnowViewFormatStringBuilder = new StringBuilder(); if (validViewFormats.Length > 0) { // unKnowViewFormatStringBuilder.Append(StringUtil.Format(FormatAndOut_format_xxx.UnknownViewNameError, viewName)); unKnowViewFormatStringBuilder.Append(StringUtil.Format(FormatAndOut_format_xxx.UnknownViewNameErrorSuffix, viewName, formatTypeName)); unKnowViewFormatStringBuilder.Append(validViewFormats.ToString()); } else { unKnowViewFormatStringBuilder.Append(StringUtil.Format(FormatAndOut_format_xxx.UnknownViewNameError, viewName)); unKnowViewFormatStringBuilder.Append(StringUtil.Format(FormatAndOut_format_xxx.NonExistingViewNameError, formatTypeName, so.BaseObject.GetType())); } msg = unKnowViewFormatStringBuilder.ToString(); ; } ErrorRecord errorRecord = new ErrorRecord( new PipelineStoppedException(), "FormatViewNotFound", ErrorCategory.ObjectNotFound, viewName); errorRecord.ErrorDetails = new ErrorDetails(msg); errorContext.ThrowTerminatingError(errorRecord); } internal ViewGenerator ViewGenerator { get { Diagnostics.Assert(_viewGenerator != null, "this.viewGenerator cannot be null"); return _viewGenerator; } } private static ViewGenerator SelectViewGeneratorFromViewDefinition( TerminatingErrorContext errorContext, PSPropertyExpressionFactory expressionFactory, TypeInfoDataBase db, ViewDefinition view, FormattingCommandLineParameters parameters) { ViewGenerator viewGenerator = null; if (view.mainControl is TableControlBody) { viewGenerator = new TableViewGenerator(); } else if (view.mainControl is ListControlBody) { viewGenerator = new ListViewGenerator(); } else if (view.mainControl is WideControlBody) { viewGenerator = new WideViewGenerator(); } else if (view.mainControl is ComplexControlBody) { viewGenerator = new ComplexViewGenerator(); } Diagnostics.Assert(viewGenerator != null, "viewGenerator != null"); viewGenerator.Initialize(errorContext, expressionFactory, db, view, parameters); return viewGenerator; } private static ViewGenerator SelectViewGeneratorFromProperties(FormatShape shape, PSObject so, TerminatingErrorContext errorContext, PSPropertyExpressionFactory expressionFactory, TypeInfoDataBase db, FormattingCommandLineParameters parameters) { // use some heuristics to determine the shape if none is specified if (shape == FormatShape.Undefined && parameters == null) { // check first if we have a known shape for a type var typeNames = so.InternalTypeNames; shape = DisplayDataQuery.GetShapeFromType(expressionFactory, db, typeNames); if (shape == FormatShape.Undefined) { // check if we can have a table: // we want to get the # of properties we are going to display List<PSPropertyExpression> expressionList = PSObjectHelper.GetDefaultPropertySet(so); if (expressionList.Count == 0) { // we failed to get anything from a property set // we just get the first properties out of the first object foreach (MshResolvedExpressionParameterAssociation mrepa in AssociationManager.ExpandAll(so)) { expressionList.Add(mrepa.ResolvedExpression); } } // decide what shape we want for the given number of properties shape = DisplayDataQuery.GetShapeFromPropertyCount(db, expressionList.Count); } } ViewGenerator viewGenerator = null; if (shape == FormatShape.Table) { viewGenerator = new TableViewGenerator(); } else if (shape == FormatShape.List) { viewGenerator = new ListViewGenerator(); } else if (shape == FormatShape.Wide) { viewGenerator = new WideViewGenerator(); } else if (shape == FormatShape.Complex) { viewGenerator = new ComplexViewGenerator(); } Diagnostics.Assert(viewGenerator != null, "viewGenerator != null"); viewGenerator.Initialize(errorContext, expressionFactory, so, db, parameters); return viewGenerator; } /// <summary> /// The view generator that produced data for a selected shape. /// </summary> private ViewGenerator _viewGenerator = null; } /// <summary> /// Class to manage the selection of a desired view type /// for out of band objects. /// </summary> internal static class OutOfBandFormatViewManager { private static bool IsNotRemotingProperty(string name) { var isRemotingPropertyName = name.Equals(RemotingConstants.ComputerNameNoteProperty, StringComparison.OrdinalIgnoreCase) || name.Equals(RemotingConstants.ShowComputerNameNoteProperty, StringComparison.OrdinalIgnoreCase) || name.Equals(RemotingConstants.RunspaceIdNoteProperty, StringComparison.OrdinalIgnoreCase) || name.Equals(RemotingConstants.SourceJobInstanceId, StringComparison.OrdinalIgnoreCase); return !isRemotingPropertyName; } private static readonly MemberNamePredicate NameIsNotRemotingProperty = IsNotRemotingProperty; internal static bool HasNonRemotingProperties(PSObject so) => so.GetFirstPropertyOrDefault(NameIsNotRemotingProperty) != null; internal static FormatEntryData GenerateOutOfBandData(TerminatingErrorContext errorContext, PSPropertyExpressionFactory expressionFactory, TypeInfoDataBase db, PSObject so, int enumerationLimit, bool useToStringFallback, out List<ErrorRecord> errors) { errors = null; var typeNames = so.InternalTypeNames; ViewDefinition view = DisplayDataQuery.GetOutOfBandView(expressionFactory, db, typeNames); ViewGenerator outOfBandViewGenerator; if (view != null) { // process an out of band view retrieved from the display database if (view.mainControl is ComplexControlBody) { outOfBandViewGenerator = new ComplexViewGenerator(); } else { outOfBandViewGenerator = new ListViewGenerator(); } outOfBandViewGenerator.Initialize(errorContext, expressionFactory, db, view, null); } else { if (DefaultScalarTypes.IsTypeInList(typeNames) || !HasNonRemotingProperties(so)) { // we force a ToString() on well known types return GenerateOutOfBandObjectAsToString(so); } if (!useToStringFallback) { return null; } // we must check we have enough properties for a list view if (new PSPropertyExpression("*").ResolveNames(so).Count <= 0) { return null; } // we do not have a view, we default to list view // process an out of band view as a default outOfBandViewGenerator = new ListViewGenerator(); outOfBandViewGenerator.Initialize(errorContext, expressionFactory, so, db, null); } FormatEntryData fed = outOfBandViewGenerator.GeneratePayload(so, enumerationLimit); fed.outOfBand = true; fed.writeStream = so.WriteStream; errors = outOfBandViewGenerator.ErrorManager.DrainFailedResultList(); return fed; } internal static FormatEntryData GenerateOutOfBandObjectAsToString(PSObject so) { FormatEntryData fed = new FormatEntryData(); fed.outOfBand = true; RawTextFormatEntry rawTextEntry = new RawTextFormatEntry(); rawTextEntry.text = so.ToString(); fed.formatEntryInfo = rawTextEntry; return fed; } } /// <summary> /// Helper class to manage the logging of errors resulting from /// evaluations of PSPropertyExpression instances /// /// Depending on settings, it queues the failing PSPropertyExpressionResult /// instances and generates a list of out-of-band FormatEntryData /// objects to be sent to the output pipeline. /// </summary> internal sealed class FormatErrorManager { internal FormatErrorManager(FormatErrorPolicy formatErrorPolicy) { _formatErrorPolicy = formatErrorPolicy; } /// <summary> /// Log a failed evaluation of an PSPropertyExpression. /// </summary> /// <param name="result">PSPropertyExpressionResult containing the failed evaluation data.</param> /// <param name="sourceObject">Object used to evaluate the PSPropertyExpression.</param> internal void LogPSPropertyExpressionFailedResult(PSPropertyExpressionResult result, object sourceObject) { if (!_formatErrorPolicy.ShowErrorsAsMessages) return; PSPropertyExpressionError error = new PSPropertyExpressionError(); error.result = result; error.sourceObject = sourceObject; _formattingErrorList.Add(error); } /// <summary> /// Log a failed formatting operation. /// </summary> /// <param name="error">String format error object.</param> internal void LogStringFormatError(StringFormatError error) { if (!_formatErrorPolicy.ShowErrorsAsMessages) return; _formattingErrorList.Add(error); } internal bool DisplayErrorStrings { get { return _formatErrorPolicy.ShowErrorsInFormattedOutput; } } internal bool DisplayFormatErrorString { get { // NOTE: we key off the same flag return this.DisplayErrorStrings; } } internal string ErrorString { get { return _formatErrorPolicy.errorStringInFormattedOutput; } } internal string FormatErrorString { get { return _formatErrorPolicy.formatErrorStringInFormattedOutput; } } /// <summary> /// Provide a list of ErrorRecord entries /// to be written to the error pipeline and clear the list of pending /// errors. /// </summary> /// <returns>List of ErrorRecord objects.</returns> internal List<ErrorRecord> DrainFailedResultList() { if (!_formatErrorPolicy.ShowErrorsAsMessages) return null; List<ErrorRecord> retVal = new List<ErrorRecord>(); foreach (FormattingError error in _formattingErrorList) { ErrorRecord errorRecord = GenerateErrorRecord(error); if (errorRecord != null) retVal.Add(errorRecord); } _formattingErrorList.Clear(); return retVal; } /// <summary> /// Conversion between an error internal representation and ErrorRecord. /// </summary> /// <param name="error">Internal error object.</param> /// <returns>Corresponding ErrorRecord instance.</returns> private static ErrorRecord GenerateErrorRecord(FormattingError error) { ErrorRecord errorRecord = null; string msg = null; PSPropertyExpressionError psPropertyExpressionError = error as PSPropertyExpressionError; if (psPropertyExpressionError != null) { errorRecord = new ErrorRecord( psPropertyExpressionError.result.Exception, "PSPropertyExpressionError", ErrorCategory.InvalidArgument, psPropertyExpressionError.sourceObject); msg = StringUtil.Format(FormatAndOut_format_xxx.PSPropertyExpressionError, psPropertyExpressionError.result.ResolvedExpression.ToString()); errorRecord.ErrorDetails = new ErrorDetails(msg); } StringFormatError formattingError = error as StringFormatError; if (formattingError != null) { errorRecord = new ErrorRecord( formattingError.exception, "formattingError", ErrorCategory.InvalidArgument, formattingError.sourceObject); msg = StringUtil.Format(FormatAndOut_format_xxx.FormattingError, formattingError.formatString); errorRecord.ErrorDetails = new ErrorDetails(msg); } return errorRecord; } private FormatErrorPolicy _formatErrorPolicy; /// <summary> /// Current list of failed PSPropertyExpression evaluations. /// </summary> private List<FormattingError> _formattingErrorList = new List<FormattingError>(); } }
44.165457
167
0.537332
[ "MIT" ]
3v1lW1th1n/PowerShell-1
src/System.Management.Automation/FormatAndOutput/common/FormatViewManager.cs
30,430
C#
/* * Copyright (c) 2018 THL A29 Limited, a Tencent company. 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 TencentCloud.Wav.V20210129.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class CreateLeadResponse : AbstractModel { /// <summary> /// 线索处理状态码: 0-表示创建成功, 1-表示线索合并,2-表示线索重复 /// </summary> [JsonProperty("BusinessCode")] public long? BusinessCode{ get; set; } /// <summary> /// 线索处理结果描述 /// </summary> [JsonProperty("BusinessMsg")] public string BusinessMsg{ get; set; } /// <summary> /// 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 /// </summary> [JsonProperty("RequestId")] public string RequestId{ get; set; } /// <summary> /// For internal usage only. DO NOT USE IT. /// </summary> public override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamSimple(map, prefix + "BusinessCode", this.BusinessCode); this.SetParamSimple(map, prefix + "BusinessMsg", this.BusinessMsg); this.SetParamSimple(map, prefix + "RequestId", this.RequestId); } } }
31.396552
81
0.634267
[ "Apache-2.0" ]
TencentCloud/tencentcloud-sdk-dotnet
TencentCloud/Wav/V20210129/Models/CreateLeadResponse.cs
1,951
C#
namespace MassTransit.ConsumeConfigurators { using GreenPipes; public interface IActivityConfigurationObserverConnector { /// <summary> /// Connect a configuration observer to the bus configurator, which is invoked as routing slip activities are configured. /// </summary> /// <param name="observer"></param> /// <returns></returns> ConnectHandle ConnectActivityConfigurationObserver(IActivityConfigurationObserver observer); } }
31
129
0.695565
[ "ECL-2.0", "Apache-2.0" ]
ArmyMedalMei/MassTransit
src/MassTransit/Configuration/ConsumeConfigurators/IActivityConfigurationObserverConnector.cs
496
C#
// <auto-generated> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/automl/v1/service.proto // </auto-generated> // Original file comments: // Copyright 2020 Google LLC // // 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. // #pragma warning disable 0414, 1591 #region Designer generated code using grpc = global::Grpc.Core; namespace Google.Cloud.AutoML.V1 { /// <summary> /// AutoML Server API. /// /// The resource names are assigned by the server. /// The server never reuses names that it has created after the resources with /// those names are deleted. /// /// An ID of a resource is the last element of the item's resource name. For /// `projects/{project_id}/locations/{location_id}/datasets/{dataset_id}`, then /// the id for the item is `{dataset_id}`. /// /// Currently the only supported `location_id` is "us-central1". /// /// On any input that is documented to expect a string parameter in /// snake_case or kebab-case, either of those cases is accepted. /// </summary> public static partial class AutoMl { static readonly string __ServiceName = "google.cloud.automl.v1.AutoMl"; [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] static void __Helper_SerializeMessage(global::Google.Protobuf.IMessage message, grpc::SerializationContext context) { #if !GRPC_DISABLE_PROTOBUF_BUFFER_SERIALIZATION if (message is global::Google.Protobuf.IBufferMessage) { context.SetPayloadLength(message.CalculateSize()); global::Google.Protobuf.MessageExtensions.WriteTo(message, context.GetBufferWriter()); context.Complete(); return; } #endif context.Complete(global::Google.Protobuf.MessageExtensions.ToByteArray(message)); } [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] static class __Helper_MessageCache<T> { public static readonly bool IsBufferMessage = global::System.Reflection.IntrospectionExtensions.GetTypeInfo(typeof(global::Google.Protobuf.IBufferMessage)).IsAssignableFrom(typeof(T)); } [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] static T __Helper_DeserializeMessage<T>(grpc::DeserializationContext context, global::Google.Protobuf.MessageParser<T> parser) where T : global::Google.Protobuf.IMessage<T> { #if !GRPC_DISABLE_PROTOBUF_BUFFER_SERIALIZATION if (__Helper_MessageCache<T>.IsBufferMessage) { return parser.ParseFrom(context.PayloadAsReadOnlySequence()); } #endif return parser.ParseFrom(context.PayloadAsNewBuffer()); } [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] static readonly grpc::Marshaller<global::Google.Cloud.AutoML.V1.CreateDatasetRequest> __Marshaller_google_cloud_automl_v1_CreateDatasetRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Cloud.AutoML.V1.CreateDatasetRequest.Parser)); [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] static readonly grpc::Marshaller<global::Google.LongRunning.Operation> __Marshaller_google_longrunning_Operation = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.LongRunning.Operation.Parser)); [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] static readonly grpc::Marshaller<global::Google.Cloud.AutoML.V1.GetDatasetRequest> __Marshaller_google_cloud_automl_v1_GetDatasetRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Cloud.AutoML.V1.GetDatasetRequest.Parser)); [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] static readonly grpc::Marshaller<global::Google.Cloud.AutoML.V1.Dataset> __Marshaller_google_cloud_automl_v1_Dataset = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Cloud.AutoML.V1.Dataset.Parser)); [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] static readonly grpc::Marshaller<global::Google.Cloud.AutoML.V1.ListDatasetsRequest> __Marshaller_google_cloud_automl_v1_ListDatasetsRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Cloud.AutoML.V1.ListDatasetsRequest.Parser)); [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] static readonly grpc::Marshaller<global::Google.Cloud.AutoML.V1.ListDatasetsResponse> __Marshaller_google_cloud_automl_v1_ListDatasetsResponse = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Cloud.AutoML.V1.ListDatasetsResponse.Parser)); [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] static readonly grpc::Marshaller<global::Google.Cloud.AutoML.V1.UpdateDatasetRequest> __Marshaller_google_cloud_automl_v1_UpdateDatasetRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Cloud.AutoML.V1.UpdateDatasetRequest.Parser)); [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] static readonly grpc::Marshaller<global::Google.Cloud.AutoML.V1.DeleteDatasetRequest> __Marshaller_google_cloud_automl_v1_DeleteDatasetRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Cloud.AutoML.V1.DeleteDatasetRequest.Parser)); [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] static readonly grpc::Marshaller<global::Google.Cloud.AutoML.V1.ImportDataRequest> __Marshaller_google_cloud_automl_v1_ImportDataRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Cloud.AutoML.V1.ImportDataRequest.Parser)); [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] static readonly grpc::Marshaller<global::Google.Cloud.AutoML.V1.ExportDataRequest> __Marshaller_google_cloud_automl_v1_ExportDataRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Cloud.AutoML.V1.ExportDataRequest.Parser)); [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] static readonly grpc::Marshaller<global::Google.Cloud.AutoML.V1.GetAnnotationSpecRequest> __Marshaller_google_cloud_automl_v1_GetAnnotationSpecRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Cloud.AutoML.V1.GetAnnotationSpecRequest.Parser)); [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] static readonly grpc::Marshaller<global::Google.Cloud.AutoML.V1.AnnotationSpec> __Marshaller_google_cloud_automl_v1_AnnotationSpec = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Cloud.AutoML.V1.AnnotationSpec.Parser)); [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] static readonly grpc::Marshaller<global::Google.Cloud.AutoML.V1.CreateModelRequest> __Marshaller_google_cloud_automl_v1_CreateModelRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Cloud.AutoML.V1.CreateModelRequest.Parser)); [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] static readonly grpc::Marshaller<global::Google.Cloud.AutoML.V1.GetModelRequest> __Marshaller_google_cloud_automl_v1_GetModelRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Cloud.AutoML.V1.GetModelRequest.Parser)); [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] static readonly grpc::Marshaller<global::Google.Cloud.AutoML.V1.Model> __Marshaller_google_cloud_automl_v1_Model = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Cloud.AutoML.V1.Model.Parser)); [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] static readonly grpc::Marshaller<global::Google.Cloud.AutoML.V1.ListModelsRequest> __Marshaller_google_cloud_automl_v1_ListModelsRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Cloud.AutoML.V1.ListModelsRequest.Parser)); [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] static readonly grpc::Marshaller<global::Google.Cloud.AutoML.V1.ListModelsResponse> __Marshaller_google_cloud_automl_v1_ListModelsResponse = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Cloud.AutoML.V1.ListModelsResponse.Parser)); [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] static readonly grpc::Marshaller<global::Google.Cloud.AutoML.V1.DeleteModelRequest> __Marshaller_google_cloud_automl_v1_DeleteModelRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Cloud.AutoML.V1.DeleteModelRequest.Parser)); [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] static readonly grpc::Marshaller<global::Google.Cloud.AutoML.V1.UpdateModelRequest> __Marshaller_google_cloud_automl_v1_UpdateModelRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Cloud.AutoML.V1.UpdateModelRequest.Parser)); [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] static readonly grpc::Marshaller<global::Google.Cloud.AutoML.V1.DeployModelRequest> __Marshaller_google_cloud_automl_v1_DeployModelRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Cloud.AutoML.V1.DeployModelRequest.Parser)); [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] static readonly grpc::Marshaller<global::Google.Cloud.AutoML.V1.UndeployModelRequest> __Marshaller_google_cloud_automl_v1_UndeployModelRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Cloud.AutoML.V1.UndeployModelRequest.Parser)); [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] static readonly grpc::Marshaller<global::Google.Cloud.AutoML.V1.ExportModelRequest> __Marshaller_google_cloud_automl_v1_ExportModelRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Cloud.AutoML.V1.ExportModelRequest.Parser)); [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] static readonly grpc::Marshaller<global::Google.Cloud.AutoML.V1.GetModelEvaluationRequest> __Marshaller_google_cloud_automl_v1_GetModelEvaluationRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Cloud.AutoML.V1.GetModelEvaluationRequest.Parser)); [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] static readonly grpc::Marshaller<global::Google.Cloud.AutoML.V1.ModelEvaluation> __Marshaller_google_cloud_automl_v1_ModelEvaluation = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Cloud.AutoML.V1.ModelEvaluation.Parser)); [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] static readonly grpc::Marshaller<global::Google.Cloud.AutoML.V1.ListModelEvaluationsRequest> __Marshaller_google_cloud_automl_v1_ListModelEvaluationsRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Cloud.AutoML.V1.ListModelEvaluationsRequest.Parser)); [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] static readonly grpc::Marshaller<global::Google.Cloud.AutoML.V1.ListModelEvaluationsResponse> __Marshaller_google_cloud_automl_v1_ListModelEvaluationsResponse = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Cloud.AutoML.V1.ListModelEvaluationsResponse.Parser)); [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] static readonly grpc::Method<global::Google.Cloud.AutoML.V1.CreateDatasetRequest, global::Google.LongRunning.Operation> __Method_CreateDataset = new grpc::Method<global::Google.Cloud.AutoML.V1.CreateDatasetRequest, global::Google.LongRunning.Operation>( grpc::MethodType.Unary, __ServiceName, "CreateDataset", __Marshaller_google_cloud_automl_v1_CreateDatasetRequest, __Marshaller_google_longrunning_Operation); [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] static readonly grpc::Method<global::Google.Cloud.AutoML.V1.GetDatasetRequest, global::Google.Cloud.AutoML.V1.Dataset> __Method_GetDataset = new grpc::Method<global::Google.Cloud.AutoML.V1.GetDatasetRequest, global::Google.Cloud.AutoML.V1.Dataset>( grpc::MethodType.Unary, __ServiceName, "GetDataset", __Marshaller_google_cloud_automl_v1_GetDatasetRequest, __Marshaller_google_cloud_automl_v1_Dataset); [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] static readonly grpc::Method<global::Google.Cloud.AutoML.V1.ListDatasetsRequest, global::Google.Cloud.AutoML.V1.ListDatasetsResponse> __Method_ListDatasets = new grpc::Method<global::Google.Cloud.AutoML.V1.ListDatasetsRequest, global::Google.Cloud.AutoML.V1.ListDatasetsResponse>( grpc::MethodType.Unary, __ServiceName, "ListDatasets", __Marshaller_google_cloud_automl_v1_ListDatasetsRequest, __Marshaller_google_cloud_automl_v1_ListDatasetsResponse); [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] static readonly grpc::Method<global::Google.Cloud.AutoML.V1.UpdateDatasetRequest, global::Google.Cloud.AutoML.V1.Dataset> __Method_UpdateDataset = new grpc::Method<global::Google.Cloud.AutoML.V1.UpdateDatasetRequest, global::Google.Cloud.AutoML.V1.Dataset>( grpc::MethodType.Unary, __ServiceName, "UpdateDataset", __Marshaller_google_cloud_automl_v1_UpdateDatasetRequest, __Marshaller_google_cloud_automl_v1_Dataset); [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] static readonly grpc::Method<global::Google.Cloud.AutoML.V1.DeleteDatasetRequest, global::Google.LongRunning.Operation> __Method_DeleteDataset = new grpc::Method<global::Google.Cloud.AutoML.V1.DeleteDatasetRequest, global::Google.LongRunning.Operation>( grpc::MethodType.Unary, __ServiceName, "DeleteDataset", __Marshaller_google_cloud_automl_v1_DeleteDatasetRequest, __Marshaller_google_longrunning_Operation); [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] static readonly grpc::Method<global::Google.Cloud.AutoML.V1.ImportDataRequest, global::Google.LongRunning.Operation> __Method_ImportData = new grpc::Method<global::Google.Cloud.AutoML.V1.ImportDataRequest, global::Google.LongRunning.Operation>( grpc::MethodType.Unary, __ServiceName, "ImportData", __Marshaller_google_cloud_automl_v1_ImportDataRequest, __Marshaller_google_longrunning_Operation); [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] static readonly grpc::Method<global::Google.Cloud.AutoML.V1.ExportDataRequest, global::Google.LongRunning.Operation> __Method_ExportData = new grpc::Method<global::Google.Cloud.AutoML.V1.ExportDataRequest, global::Google.LongRunning.Operation>( grpc::MethodType.Unary, __ServiceName, "ExportData", __Marshaller_google_cloud_automl_v1_ExportDataRequest, __Marshaller_google_longrunning_Operation); [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] static readonly grpc::Method<global::Google.Cloud.AutoML.V1.GetAnnotationSpecRequest, global::Google.Cloud.AutoML.V1.AnnotationSpec> __Method_GetAnnotationSpec = new grpc::Method<global::Google.Cloud.AutoML.V1.GetAnnotationSpecRequest, global::Google.Cloud.AutoML.V1.AnnotationSpec>( grpc::MethodType.Unary, __ServiceName, "GetAnnotationSpec", __Marshaller_google_cloud_automl_v1_GetAnnotationSpecRequest, __Marshaller_google_cloud_automl_v1_AnnotationSpec); [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] static readonly grpc::Method<global::Google.Cloud.AutoML.V1.CreateModelRequest, global::Google.LongRunning.Operation> __Method_CreateModel = new grpc::Method<global::Google.Cloud.AutoML.V1.CreateModelRequest, global::Google.LongRunning.Operation>( grpc::MethodType.Unary, __ServiceName, "CreateModel", __Marshaller_google_cloud_automl_v1_CreateModelRequest, __Marshaller_google_longrunning_Operation); [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] static readonly grpc::Method<global::Google.Cloud.AutoML.V1.GetModelRequest, global::Google.Cloud.AutoML.V1.Model> __Method_GetModel = new grpc::Method<global::Google.Cloud.AutoML.V1.GetModelRequest, global::Google.Cloud.AutoML.V1.Model>( grpc::MethodType.Unary, __ServiceName, "GetModel", __Marshaller_google_cloud_automl_v1_GetModelRequest, __Marshaller_google_cloud_automl_v1_Model); [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] static readonly grpc::Method<global::Google.Cloud.AutoML.V1.ListModelsRequest, global::Google.Cloud.AutoML.V1.ListModelsResponse> __Method_ListModels = new grpc::Method<global::Google.Cloud.AutoML.V1.ListModelsRequest, global::Google.Cloud.AutoML.V1.ListModelsResponse>( grpc::MethodType.Unary, __ServiceName, "ListModels", __Marshaller_google_cloud_automl_v1_ListModelsRequest, __Marshaller_google_cloud_automl_v1_ListModelsResponse); [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] static readonly grpc::Method<global::Google.Cloud.AutoML.V1.DeleteModelRequest, global::Google.LongRunning.Operation> __Method_DeleteModel = new grpc::Method<global::Google.Cloud.AutoML.V1.DeleteModelRequest, global::Google.LongRunning.Operation>( grpc::MethodType.Unary, __ServiceName, "DeleteModel", __Marshaller_google_cloud_automl_v1_DeleteModelRequest, __Marshaller_google_longrunning_Operation); [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] static readonly grpc::Method<global::Google.Cloud.AutoML.V1.UpdateModelRequest, global::Google.Cloud.AutoML.V1.Model> __Method_UpdateModel = new grpc::Method<global::Google.Cloud.AutoML.V1.UpdateModelRequest, global::Google.Cloud.AutoML.V1.Model>( grpc::MethodType.Unary, __ServiceName, "UpdateModel", __Marshaller_google_cloud_automl_v1_UpdateModelRequest, __Marshaller_google_cloud_automl_v1_Model); [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] static readonly grpc::Method<global::Google.Cloud.AutoML.V1.DeployModelRequest, global::Google.LongRunning.Operation> __Method_DeployModel = new grpc::Method<global::Google.Cloud.AutoML.V1.DeployModelRequest, global::Google.LongRunning.Operation>( grpc::MethodType.Unary, __ServiceName, "DeployModel", __Marshaller_google_cloud_automl_v1_DeployModelRequest, __Marshaller_google_longrunning_Operation); [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] static readonly grpc::Method<global::Google.Cloud.AutoML.V1.UndeployModelRequest, global::Google.LongRunning.Operation> __Method_UndeployModel = new grpc::Method<global::Google.Cloud.AutoML.V1.UndeployModelRequest, global::Google.LongRunning.Operation>( grpc::MethodType.Unary, __ServiceName, "UndeployModel", __Marshaller_google_cloud_automl_v1_UndeployModelRequest, __Marshaller_google_longrunning_Operation); [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] static readonly grpc::Method<global::Google.Cloud.AutoML.V1.ExportModelRequest, global::Google.LongRunning.Operation> __Method_ExportModel = new grpc::Method<global::Google.Cloud.AutoML.V1.ExportModelRequest, global::Google.LongRunning.Operation>( grpc::MethodType.Unary, __ServiceName, "ExportModel", __Marshaller_google_cloud_automl_v1_ExportModelRequest, __Marshaller_google_longrunning_Operation); [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] static readonly grpc::Method<global::Google.Cloud.AutoML.V1.GetModelEvaluationRequest, global::Google.Cloud.AutoML.V1.ModelEvaluation> __Method_GetModelEvaluation = new grpc::Method<global::Google.Cloud.AutoML.V1.GetModelEvaluationRequest, global::Google.Cloud.AutoML.V1.ModelEvaluation>( grpc::MethodType.Unary, __ServiceName, "GetModelEvaluation", __Marshaller_google_cloud_automl_v1_GetModelEvaluationRequest, __Marshaller_google_cloud_automl_v1_ModelEvaluation); [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] static readonly grpc::Method<global::Google.Cloud.AutoML.V1.ListModelEvaluationsRequest, global::Google.Cloud.AutoML.V1.ListModelEvaluationsResponse> __Method_ListModelEvaluations = new grpc::Method<global::Google.Cloud.AutoML.V1.ListModelEvaluationsRequest, global::Google.Cloud.AutoML.V1.ListModelEvaluationsResponse>( grpc::MethodType.Unary, __ServiceName, "ListModelEvaluations", __Marshaller_google_cloud_automl_v1_ListModelEvaluationsRequest, __Marshaller_google_cloud_automl_v1_ListModelEvaluationsResponse); /// <summary>Service descriptor</summary> public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor { get { return global::Google.Cloud.AutoML.V1.ServiceReflection.Descriptor.Services[0]; } } /// <summary>Base class for server-side implementations of AutoMl</summary> [grpc::BindServiceMethod(typeof(AutoMl), "BindService")] public abstract partial class AutoMlBase { /// <summary> /// Creates a dataset. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual global::System.Threading.Tasks.Task<global::Google.LongRunning.Operation> CreateDataset(global::Google.Cloud.AutoML.V1.CreateDatasetRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Gets a dataset. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.AutoML.V1.Dataset> GetDataset(global::Google.Cloud.AutoML.V1.GetDatasetRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Lists datasets in a project. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.AutoML.V1.ListDatasetsResponse> ListDatasets(global::Google.Cloud.AutoML.V1.ListDatasetsRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Updates a dataset. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.AutoML.V1.Dataset> UpdateDataset(global::Google.Cloud.AutoML.V1.UpdateDatasetRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Deletes a dataset and all of its contents. /// Returns empty response in the /// [response][google.longrunning.Operation.response] field when it completes, /// and `delete_details` in the /// [metadata][google.longrunning.Operation.metadata] field. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual global::System.Threading.Tasks.Task<global::Google.LongRunning.Operation> DeleteDataset(global::Google.Cloud.AutoML.V1.DeleteDatasetRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Imports data into a dataset. /// For Tables this method can only be called on an empty Dataset. /// /// For Tables: /// * A /// [schema_inference_version][google.cloud.automl.v1.InputConfig.params] /// parameter must be explicitly set. /// Returns an empty response in the /// [response][google.longrunning.Operation.response] field when it completes. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual global::System.Threading.Tasks.Task<global::Google.LongRunning.Operation> ImportData(global::Google.Cloud.AutoML.V1.ImportDataRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Exports dataset's data to the provided output location. /// Returns an empty response in the /// [response][google.longrunning.Operation.response] field when it completes. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual global::System.Threading.Tasks.Task<global::Google.LongRunning.Operation> ExportData(global::Google.Cloud.AutoML.V1.ExportDataRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Gets an annotation spec. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.AutoML.V1.AnnotationSpec> GetAnnotationSpec(global::Google.Cloud.AutoML.V1.GetAnnotationSpecRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Creates a model. /// Returns a Model in the [response][google.longrunning.Operation.response] /// field when it completes. /// When you create a model, several model evaluations are created for it: /// a global evaluation, and one evaluation for each annotation spec. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual global::System.Threading.Tasks.Task<global::Google.LongRunning.Operation> CreateModel(global::Google.Cloud.AutoML.V1.CreateModelRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Gets a model. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.AutoML.V1.Model> GetModel(global::Google.Cloud.AutoML.V1.GetModelRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Lists models. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.AutoML.V1.ListModelsResponse> ListModels(global::Google.Cloud.AutoML.V1.ListModelsRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Deletes a model. /// Returns `google.protobuf.Empty` in the /// [response][google.longrunning.Operation.response] field when it completes, /// and `delete_details` in the /// [metadata][google.longrunning.Operation.metadata] field. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual global::System.Threading.Tasks.Task<global::Google.LongRunning.Operation> DeleteModel(global::Google.Cloud.AutoML.V1.DeleteModelRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Updates a model. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.AutoML.V1.Model> UpdateModel(global::Google.Cloud.AutoML.V1.UpdateModelRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Deploys a model. If a model is already deployed, deploying it with the /// same parameters has no effect. Deploying with different parametrs /// (as e.g. changing /// /// [node_number][google.cloud.automl.v1p1beta.ImageObjectDetectionModelDeploymentMetadata.node_number]) /// will reset the deployment state without pausing the model's availability. /// /// Only applicable for Text Classification, Image Object Detection , Tables, and Image Segmentation; all other domains manage /// deployment automatically. /// /// Returns an empty response in the /// [response][google.longrunning.Operation.response] field when it completes. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual global::System.Threading.Tasks.Task<global::Google.LongRunning.Operation> DeployModel(global::Google.Cloud.AutoML.V1.DeployModelRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Undeploys a model. If the model is not deployed this method has no effect. /// /// Only applicable for Text Classification, Image Object Detection and Tables; /// all other domains manage deployment automatically. /// /// Returns an empty response in the /// [response][google.longrunning.Operation.response] field when it completes. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual global::System.Threading.Tasks.Task<global::Google.LongRunning.Operation> UndeployModel(global::Google.Cloud.AutoML.V1.UndeployModelRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Exports a trained, "export-able", model to a user specified Google Cloud /// Storage location. A model is considered export-able if and only if it has /// an export format defined for it in /// [ModelExportOutputConfig][google.cloud.automl.v1.ModelExportOutputConfig]. /// /// Returns an empty response in the /// [response][google.longrunning.Operation.response] field when it completes. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual global::System.Threading.Tasks.Task<global::Google.LongRunning.Operation> ExportModel(global::Google.Cloud.AutoML.V1.ExportModelRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Gets a model evaluation. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.AutoML.V1.ModelEvaluation> GetModelEvaluation(global::Google.Cloud.AutoML.V1.GetModelEvaluationRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Lists model evaluations. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.AutoML.V1.ListModelEvaluationsResponse> ListModelEvaluations(global::Google.Cloud.AutoML.V1.ListModelEvaluationsRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } } /// <summary>Client for AutoMl</summary> public partial class AutoMlClient : grpc::ClientBase<AutoMlClient> { /// <summary>Creates a new client for AutoMl</summary> /// <param name="channel">The channel to use to make remote calls.</param> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public AutoMlClient(grpc::ChannelBase channel) : base(channel) { } /// <summary>Creates a new client for AutoMl that uses a custom <c>CallInvoker</c>.</summary> /// <param name="callInvoker">The callInvoker to use to make remote calls.</param> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public AutoMlClient(grpc::CallInvoker callInvoker) : base(callInvoker) { } /// <summary>Protected parameterless constructor to allow creation of test doubles.</summary> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] protected AutoMlClient() : base() { } /// <summary>Protected constructor to allow creation of configured clients.</summary> /// <param name="configuration">The client configuration.</param> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] protected AutoMlClient(ClientBaseConfiguration configuration) : base(configuration) { } /// <summary> /// Creates a dataset. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual global::Google.LongRunning.Operation CreateDataset(global::Google.Cloud.AutoML.V1.CreateDatasetRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return CreateDataset(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Creates a dataset. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual global::Google.LongRunning.Operation CreateDataset(global::Google.Cloud.AutoML.V1.CreateDatasetRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_CreateDataset, null, options, request); } /// <summary> /// Creates a dataset. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual grpc::AsyncUnaryCall<global::Google.LongRunning.Operation> CreateDatasetAsync(global::Google.Cloud.AutoML.V1.CreateDatasetRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return CreateDatasetAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Creates a dataset. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual grpc::AsyncUnaryCall<global::Google.LongRunning.Operation> CreateDatasetAsync(global::Google.Cloud.AutoML.V1.CreateDatasetRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_CreateDataset, null, options, request); } /// <summary> /// Gets a dataset. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual global::Google.Cloud.AutoML.V1.Dataset GetDataset(global::Google.Cloud.AutoML.V1.GetDatasetRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return GetDataset(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Gets a dataset. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual global::Google.Cloud.AutoML.V1.Dataset GetDataset(global::Google.Cloud.AutoML.V1.GetDatasetRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_GetDataset, null, options, request); } /// <summary> /// Gets a dataset. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual grpc::AsyncUnaryCall<global::Google.Cloud.AutoML.V1.Dataset> GetDatasetAsync(global::Google.Cloud.AutoML.V1.GetDatasetRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return GetDatasetAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Gets a dataset. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual grpc::AsyncUnaryCall<global::Google.Cloud.AutoML.V1.Dataset> GetDatasetAsync(global::Google.Cloud.AutoML.V1.GetDatasetRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_GetDataset, null, options, request); } /// <summary> /// Lists datasets in a project. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual global::Google.Cloud.AutoML.V1.ListDatasetsResponse ListDatasets(global::Google.Cloud.AutoML.V1.ListDatasetsRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return ListDatasets(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists datasets in a project. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual global::Google.Cloud.AutoML.V1.ListDatasetsResponse ListDatasets(global::Google.Cloud.AutoML.V1.ListDatasetsRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_ListDatasets, null, options, request); } /// <summary> /// Lists datasets in a project. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual grpc::AsyncUnaryCall<global::Google.Cloud.AutoML.V1.ListDatasetsResponse> ListDatasetsAsync(global::Google.Cloud.AutoML.V1.ListDatasetsRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return ListDatasetsAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists datasets in a project. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual grpc::AsyncUnaryCall<global::Google.Cloud.AutoML.V1.ListDatasetsResponse> ListDatasetsAsync(global::Google.Cloud.AutoML.V1.ListDatasetsRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_ListDatasets, null, options, request); } /// <summary> /// Updates a dataset. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual global::Google.Cloud.AutoML.V1.Dataset UpdateDataset(global::Google.Cloud.AutoML.V1.UpdateDatasetRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return UpdateDataset(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Updates a dataset. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual global::Google.Cloud.AutoML.V1.Dataset UpdateDataset(global::Google.Cloud.AutoML.V1.UpdateDatasetRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_UpdateDataset, null, options, request); } /// <summary> /// Updates a dataset. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual grpc::AsyncUnaryCall<global::Google.Cloud.AutoML.V1.Dataset> UpdateDatasetAsync(global::Google.Cloud.AutoML.V1.UpdateDatasetRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return UpdateDatasetAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Updates a dataset. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual grpc::AsyncUnaryCall<global::Google.Cloud.AutoML.V1.Dataset> UpdateDatasetAsync(global::Google.Cloud.AutoML.V1.UpdateDatasetRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_UpdateDataset, null, options, request); } /// <summary> /// Deletes a dataset and all of its contents. /// Returns empty response in the /// [response][google.longrunning.Operation.response] field when it completes, /// and `delete_details` in the /// [metadata][google.longrunning.Operation.metadata] field. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual global::Google.LongRunning.Operation DeleteDataset(global::Google.Cloud.AutoML.V1.DeleteDatasetRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return DeleteDataset(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Deletes a dataset and all of its contents. /// Returns empty response in the /// [response][google.longrunning.Operation.response] field when it completes, /// and `delete_details` in the /// [metadata][google.longrunning.Operation.metadata] field. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual global::Google.LongRunning.Operation DeleteDataset(global::Google.Cloud.AutoML.V1.DeleteDatasetRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_DeleteDataset, null, options, request); } /// <summary> /// Deletes a dataset and all of its contents. /// Returns empty response in the /// [response][google.longrunning.Operation.response] field when it completes, /// and `delete_details` in the /// [metadata][google.longrunning.Operation.metadata] field. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual grpc::AsyncUnaryCall<global::Google.LongRunning.Operation> DeleteDatasetAsync(global::Google.Cloud.AutoML.V1.DeleteDatasetRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return DeleteDatasetAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Deletes a dataset and all of its contents. /// Returns empty response in the /// [response][google.longrunning.Operation.response] field when it completes, /// and `delete_details` in the /// [metadata][google.longrunning.Operation.metadata] field. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual grpc::AsyncUnaryCall<global::Google.LongRunning.Operation> DeleteDatasetAsync(global::Google.Cloud.AutoML.V1.DeleteDatasetRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_DeleteDataset, null, options, request); } /// <summary> /// Imports data into a dataset. /// For Tables this method can only be called on an empty Dataset. /// /// For Tables: /// * A /// [schema_inference_version][google.cloud.automl.v1.InputConfig.params] /// parameter must be explicitly set. /// Returns an empty response in the /// [response][google.longrunning.Operation.response] field when it completes. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual global::Google.LongRunning.Operation ImportData(global::Google.Cloud.AutoML.V1.ImportDataRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return ImportData(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Imports data into a dataset. /// For Tables this method can only be called on an empty Dataset. /// /// For Tables: /// * A /// [schema_inference_version][google.cloud.automl.v1.InputConfig.params] /// parameter must be explicitly set. /// Returns an empty response in the /// [response][google.longrunning.Operation.response] field when it completes. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual global::Google.LongRunning.Operation ImportData(global::Google.Cloud.AutoML.V1.ImportDataRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_ImportData, null, options, request); } /// <summary> /// Imports data into a dataset. /// For Tables this method can only be called on an empty Dataset. /// /// For Tables: /// * A /// [schema_inference_version][google.cloud.automl.v1.InputConfig.params] /// parameter must be explicitly set. /// Returns an empty response in the /// [response][google.longrunning.Operation.response] field when it completes. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual grpc::AsyncUnaryCall<global::Google.LongRunning.Operation> ImportDataAsync(global::Google.Cloud.AutoML.V1.ImportDataRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return ImportDataAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Imports data into a dataset. /// For Tables this method can only be called on an empty Dataset. /// /// For Tables: /// * A /// [schema_inference_version][google.cloud.automl.v1.InputConfig.params] /// parameter must be explicitly set. /// Returns an empty response in the /// [response][google.longrunning.Operation.response] field when it completes. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual grpc::AsyncUnaryCall<global::Google.LongRunning.Operation> ImportDataAsync(global::Google.Cloud.AutoML.V1.ImportDataRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_ImportData, null, options, request); } /// <summary> /// Exports dataset's data to the provided output location. /// Returns an empty response in the /// [response][google.longrunning.Operation.response] field when it completes. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual global::Google.LongRunning.Operation ExportData(global::Google.Cloud.AutoML.V1.ExportDataRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return ExportData(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Exports dataset's data to the provided output location. /// Returns an empty response in the /// [response][google.longrunning.Operation.response] field when it completes. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual global::Google.LongRunning.Operation ExportData(global::Google.Cloud.AutoML.V1.ExportDataRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_ExportData, null, options, request); } /// <summary> /// Exports dataset's data to the provided output location. /// Returns an empty response in the /// [response][google.longrunning.Operation.response] field when it completes. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual grpc::AsyncUnaryCall<global::Google.LongRunning.Operation> ExportDataAsync(global::Google.Cloud.AutoML.V1.ExportDataRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return ExportDataAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Exports dataset's data to the provided output location. /// Returns an empty response in the /// [response][google.longrunning.Operation.response] field when it completes. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual grpc::AsyncUnaryCall<global::Google.LongRunning.Operation> ExportDataAsync(global::Google.Cloud.AutoML.V1.ExportDataRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_ExportData, null, options, request); } /// <summary> /// Gets an annotation spec. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual global::Google.Cloud.AutoML.V1.AnnotationSpec GetAnnotationSpec(global::Google.Cloud.AutoML.V1.GetAnnotationSpecRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return GetAnnotationSpec(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Gets an annotation spec. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual global::Google.Cloud.AutoML.V1.AnnotationSpec GetAnnotationSpec(global::Google.Cloud.AutoML.V1.GetAnnotationSpecRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_GetAnnotationSpec, null, options, request); } /// <summary> /// Gets an annotation spec. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual grpc::AsyncUnaryCall<global::Google.Cloud.AutoML.V1.AnnotationSpec> GetAnnotationSpecAsync(global::Google.Cloud.AutoML.V1.GetAnnotationSpecRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return GetAnnotationSpecAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Gets an annotation spec. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual grpc::AsyncUnaryCall<global::Google.Cloud.AutoML.V1.AnnotationSpec> GetAnnotationSpecAsync(global::Google.Cloud.AutoML.V1.GetAnnotationSpecRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_GetAnnotationSpec, null, options, request); } /// <summary> /// Creates a model. /// Returns a Model in the [response][google.longrunning.Operation.response] /// field when it completes. /// When you create a model, several model evaluations are created for it: /// a global evaluation, and one evaluation for each annotation spec. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual global::Google.LongRunning.Operation CreateModel(global::Google.Cloud.AutoML.V1.CreateModelRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return CreateModel(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Creates a model. /// Returns a Model in the [response][google.longrunning.Operation.response] /// field when it completes. /// When you create a model, several model evaluations are created for it: /// a global evaluation, and one evaluation for each annotation spec. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual global::Google.LongRunning.Operation CreateModel(global::Google.Cloud.AutoML.V1.CreateModelRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_CreateModel, null, options, request); } /// <summary> /// Creates a model. /// Returns a Model in the [response][google.longrunning.Operation.response] /// field when it completes. /// When you create a model, several model evaluations are created for it: /// a global evaluation, and one evaluation for each annotation spec. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual grpc::AsyncUnaryCall<global::Google.LongRunning.Operation> CreateModelAsync(global::Google.Cloud.AutoML.V1.CreateModelRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return CreateModelAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Creates a model. /// Returns a Model in the [response][google.longrunning.Operation.response] /// field when it completes. /// When you create a model, several model evaluations are created for it: /// a global evaluation, and one evaluation for each annotation spec. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual grpc::AsyncUnaryCall<global::Google.LongRunning.Operation> CreateModelAsync(global::Google.Cloud.AutoML.V1.CreateModelRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_CreateModel, null, options, request); } /// <summary> /// Gets a model. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual global::Google.Cloud.AutoML.V1.Model GetModel(global::Google.Cloud.AutoML.V1.GetModelRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return GetModel(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Gets a model. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual global::Google.Cloud.AutoML.V1.Model GetModel(global::Google.Cloud.AutoML.V1.GetModelRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_GetModel, null, options, request); } /// <summary> /// Gets a model. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual grpc::AsyncUnaryCall<global::Google.Cloud.AutoML.V1.Model> GetModelAsync(global::Google.Cloud.AutoML.V1.GetModelRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return GetModelAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Gets a model. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual grpc::AsyncUnaryCall<global::Google.Cloud.AutoML.V1.Model> GetModelAsync(global::Google.Cloud.AutoML.V1.GetModelRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_GetModel, null, options, request); } /// <summary> /// Lists models. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual global::Google.Cloud.AutoML.V1.ListModelsResponse ListModels(global::Google.Cloud.AutoML.V1.ListModelsRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return ListModels(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists models. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual global::Google.Cloud.AutoML.V1.ListModelsResponse ListModels(global::Google.Cloud.AutoML.V1.ListModelsRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_ListModels, null, options, request); } /// <summary> /// Lists models. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual grpc::AsyncUnaryCall<global::Google.Cloud.AutoML.V1.ListModelsResponse> ListModelsAsync(global::Google.Cloud.AutoML.V1.ListModelsRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return ListModelsAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists models. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual grpc::AsyncUnaryCall<global::Google.Cloud.AutoML.V1.ListModelsResponse> ListModelsAsync(global::Google.Cloud.AutoML.V1.ListModelsRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_ListModels, null, options, request); } /// <summary> /// Deletes a model. /// Returns `google.protobuf.Empty` in the /// [response][google.longrunning.Operation.response] field when it completes, /// and `delete_details` in the /// [metadata][google.longrunning.Operation.metadata] field. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual global::Google.LongRunning.Operation DeleteModel(global::Google.Cloud.AutoML.V1.DeleteModelRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return DeleteModel(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Deletes a model. /// Returns `google.protobuf.Empty` in the /// [response][google.longrunning.Operation.response] field when it completes, /// and `delete_details` in the /// [metadata][google.longrunning.Operation.metadata] field. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual global::Google.LongRunning.Operation DeleteModel(global::Google.Cloud.AutoML.V1.DeleteModelRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_DeleteModel, null, options, request); } /// <summary> /// Deletes a model. /// Returns `google.protobuf.Empty` in the /// [response][google.longrunning.Operation.response] field when it completes, /// and `delete_details` in the /// [metadata][google.longrunning.Operation.metadata] field. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual grpc::AsyncUnaryCall<global::Google.LongRunning.Operation> DeleteModelAsync(global::Google.Cloud.AutoML.V1.DeleteModelRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return DeleteModelAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Deletes a model. /// Returns `google.protobuf.Empty` in the /// [response][google.longrunning.Operation.response] field when it completes, /// and `delete_details` in the /// [metadata][google.longrunning.Operation.metadata] field. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual grpc::AsyncUnaryCall<global::Google.LongRunning.Operation> DeleteModelAsync(global::Google.Cloud.AutoML.V1.DeleteModelRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_DeleteModel, null, options, request); } /// <summary> /// Updates a model. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual global::Google.Cloud.AutoML.V1.Model UpdateModel(global::Google.Cloud.AutoML.V1.UpdateModelRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return UpdateModel(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Updates a model. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual global::Google.Cloud.AutoML.V1.Model UpdateModel(global::Google.Cloud.AutoML.V1.UpdateModelRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_UpdateModel, null, options, request); } /// <summary> /// Updates a model. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual grpc::AsyncUnaryCall<global::Google.Cloud.AutoML.V1.Model> UpdateModelAsync(global::Google.Cloud.AutoML.V1.UpdateModelRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return UpdateModelAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Updates a model. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual grpc::AsyncUnaryCall<global::Google.Cloud.AutoML.V1.Model> UpdateModelAsync(global::Google.Cloud.AutoML.V1.UpdateModelRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_UpdateModel, null, options, request); } /// <summary> /// Deploys a model. If a model is already deployed, deploying it with the /// same parameters has no effect. Deploying with different parametrs /// (as e.g. changing /// /// [node_number][google.cloud.automl.v1p1beta.ImageObjectDetectionModelDeploymentMetadata.node_number]) /// will reset the deployment state without pausing the model's availability. /// /// Only applicable for Text Classification, Image Object Detection , Tables, and Image Segmentation; all other domains manage /// deployment automatically. /// /// Returns an empty response in the /// [response][google.longrunning.Operation.response] field when it completes. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual global::Google.LongRunning.Operation DeployModel(global::Google.Cloud.AutoML.V1.DeployModelRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return DeployModel(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Deploys a model. If a model is already deployed, deploying it with the /// same parameters has no effect. Deploying with different parametrs /// (as e.g. changing /// /// [node_number][google.cloud.automl.v1p1beta.ImageObjectDetectionModelDeploymentMetadata.node_number]) /// will reset the deployment state without pausing the model's availability. /// /// Only applicable for Text Classification, Image Object Detection , Tables, and Image Segmentation; all other domains manage /// deployment automatically. /// /// Returns an empty response in the /// [response][google.longrunning.Operation.response] field when it completes. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual global::Google.LongRunning.Operation DeployModel(global::Google.Cloud.AutoML.V1.DeployModelRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_DeployModel, null, options, request); } /// <summary> /// Deploys a model. If a model is already deployed, deploying it with the /// same parameters has no effect. Deploying with different parametrs /// (as e.g. changing /// /// [node_number][google.cloud.automl.v1p1beta.ImageObjectDetectionModelDeploymentMetadata.node_number]) /// will reset the deployment state without pausing the model's availability. /// /// Only applicable for Text Classification, Image Object Detection , Tables, and Image Segmentation; all other domains manage /// deployment automatically. /// /// Returns an empty response in the /// [response][google.longrunning.Operation.response] field when it completes. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual grpc::AsyncUnaryCall<global::Google.LongRunning.Operation> DeployModelAsync(global::Google.Cloud.AutoML.V1.DeployModelRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return DeployModelAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Deploys a model. If a model is already deployed, deploying it with the /// same parameters has no effect. Deploying with different parametrs /// (as e.g. changing /// /// [node_number][google.cloud.automl.v1p1beta.ImageObjectDetectionModelDeploymentMetadata.node_number]) /// will reset the deployment state without pausing the model's availability. /// /// Only applicable for Text Classification, Image Object Detection , Tables, and Image Segmentation; all other domains manage /// deployment automatically. /// /// Returns an empty response in the /// [response][google.longrunning.Operation.response] field when it completes. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual grpc::AsyncUnaryCall<global::Google.LongRunning.Operation> DeployModelAsync(global::Google.Cloud.AutoML.V1.DeployModelRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_DeployModel, null, options, request); } /// <summary> /// Undeploys a model. If the model is not deployed this method has no effect. /// /// Only applicable for Text Classification, Image Object Detection and Tables; /// all other domains manage deployment automatically. /// /// Returns an empty response in the /// [response][google.longrunning.Operation.response] field when it completes. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual global::Google.LongRunning.Operation UndeployModel(global::Google.Cloud.AutoML.V1.UndeployModelRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return UndeployModel(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Undeploys a model. If the model is not deployed this method has no effect. /// /// Only applicable for Text Classification, Image Object Detection and Tables; /// all other domains manage deployment automatically. /// /// Returns an empty response in the /// [response][google.longrunning.Operation.response] field when it completes. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual global::Google.LongRunning.Operation UndeployModel(global::Google.Cloud.AutoML.V1.UndeployModelRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_UndeployModel, null, options, request); } /// <summary> /// Undeploys a model. If the model is not deployed this method has no effect. /// /// Only applicable for Text Classification, Image Object Detection and Tables; /// all other domains manage deployment automatically. /// /// Returns an empty response in the /// [response][google.longrunning.Operation.response] field when it completes. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual grpc::AsyncUnaryCall<global::Google.LongRunning.Operation> UndeployModelAsync(global::Google.Cloud.AutoML.V1.UndeployModelRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return UndeployModelAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Undeploys a model. If the model is not deployed this method has no effect. /// /// Only applicable for Text Classification, Image Object Detection and Tables; /// all other domains manage deployment automatically. /// /// Returns an empty response in the /// [response][google.longrunning.Operation.response] field when it completes. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual grpc::AsyncUnaryCall<global::Google.LongRunning.Operation> UndeployModelAsync(global::Google.Cloud.AutoML.V1.UndeployModelRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_UndeployModel, null, options, request); } /// <summary> /// Exports a trained, "export-able", model to a user specified Google Cloud /// Storage location. A model is considered export-able if and only if it has /// an export format defined for it in /// [ModelExportOutputConfig][google.cloud.automl.v1.ModelExportOutputConfig]. /// /// Returns an empty response in the /// [response][google.longrunning.Operation.response] field when it completes. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual global::Google.LongRunning.Operation ExportModel(global::Google.Cloud.AutoML.V1.ExportModelRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return ExportModel(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Exports a trained, "export-able", model to a user specified Google Cloud /// Storage location. A model is considered export-able if and only if it has /// an export format defined for it in /// [ModelExportOutputConfig][google.cloud.automl.v1.ModelExportOutputConfig]. /// /// Returns an empty response in the /// [response][google.longrunning.Operation.response] field when it completes. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual global::Google.LongRunning.Operation ExportModel(global::Google.Cloud.AutoML.V1.ExportModelRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_ExportModel, null, options, request); } /// <summary> /// Exports a trained, "export-able", model to a user specified Google Cloud /// Storage location. A model is considered export-able if and only if it has /// an export format defined for it in /// [ModelExportOutputConfig][google.cloud.automl.v1.ModelExportOutputConfig]. /// /// Returns an empty response in the /// [response][google.longrunning.Operation.response] field when it completes. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual grpc::AsyncUnaryCall<global::Google.LongRunning.Operation> ExportModelAsync(global::Google.Cloud.AutoML.V1.ExportModelRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return ExportModelAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Exports a trained, "export-able", model to a user specified Google Cloud /// Storage location. A model is considered export-able if and only if it has /// an export format defined for it in /// [ModelExportOutputConfig][google.cloud.automl.v1.ModelExportOutputConfig]. /// /// Returns an empty response in the /// [response][google.longrunning.Operation.response] field when it completes. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual grpc::AsyncUnaryCall<global::Google.LongRunning.Operation> ExportModelAsync(global::Google.Cloud.AutoML.V1.ExportModelRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_ExportModel, null, options, request); } /// <summary> /// Gets a model evaluation. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual global::Google.Cloud.AutoML.V1.ModelEvaluation GetModelEvaluation(global::Google.Cloud.AutoML.V1.GetModelEvaluationRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return GetModelEvaluation(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Gets a model evaluation. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual global::Google.Cloud.AutoML.V1.ModelEvaluation GetModelEvaluation(global::Google.Cloud.AutoML.V1.GetModelEvaluationRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_GetModelEvaluation, null, options, request); } /// <summary> /// Gets a model evaluation. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual grpc::AsyncUnaryCall<global::Google.Cloud.AutoML.V1.ModelEvaluation> GetModelEvaluationAsync(global::Google.Cloud.AutoML.V1.GetModelEvaluationRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return GetModelEvaluationAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Gets a model evaluation. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual grpc::AsyncUnaryCall<global::Google.Cloud.AutoML.V1.ModelEvaluation> GetModelEvaluationAsync(global::Google.Cloud.AutoML.V1.GetModelEvaluationRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_GetModelEvaluation, null, options, request); } /// <summary> /// Lists model evaluations. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual global::Google.Cloud.AutoML.V1.ListModelEvaluationsResponse ListModelEvaluations(global::Google.Cloud.AutoML.V1.ListModelEvaluationsRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return ListModelEvaluations(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists model evaluations. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual global::Google.Cloud.AutoML.V1.ListModelEvaluationsResponse ListModelEvaluations(global::Google.Cloud.AutoML.V1.ListModelEvaluationsRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_ListModelEvaluations, null, options, request); } /// <summary> /// Lists model evaluations. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual grpc::AsyncUnaryCall<global::Google.Cloud.AutoML.V1.ListModelEvaluationsResponse> ListModelEvaluationsAsync(global::Google.Cloud.AutoML.V1.ListModelEvaluationsRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return ListModelEvaluationsAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists model evaluations. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public virtual grpc::AsyncUnaryCall<global::Google.Cloud.AutoML.V1.ListModelEvaluationsResponse> ListModelEvaluationsAsync(global::Google.Cloud.AutoML.V1.ListModelEvaluationsRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_ListModelEvaluations, null, options, request); } /// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] protected override AutoMlClient NewInstance(ClientBaseConfiguration configuration) { return new AutoMlClient(configuration); } } /// <summary>Creates service definition that can be registered with a server</summary> /// <param name="serviceImpl">An object implementing the server-side handling logic.</param> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public static grpc::ServerServiceDefinition BindService(AutoMlBase serviceImpl) { return grpc::ServerServiceDefinition.CreateBuilder() .AddMethod(__Method_CreateDataset, serviceImpl.CreateDataset) .AddMethod(__Method_GetDataset, serviceImpl.GetDataset) .AddMethod(__Method_ListDatasets, serviceImpl.ListDatasets) .AddMethod(__Method_UpdateDataset, serviceImpl.UpdateDataset) .AddMethod(__Method_DeleteDataset, serviceImpl.DeleteDataset) .AddMethod(__Method_ImportData, serviceImpl.ImportData) .AddMethod(__Method_ExportData, serviceImpl.ExportData) .AddMethod(__Method_GetAnnotationSpec, serviceImpl.GetAnnotationSpec) .AddMethod(__Method_CreateModel, serviceImpl.CreateModel) .AddMethod(__Method_GetModel, serviceImpl.GetModel) .AddMethod(__Method_ListModels, serviceImpl.ListModels) .AddMethod(__Method_DeleteModel, serviceImpl.DeleteModel) .AddMethod(__Method_UpdateModel, serviceImpl.UpdateModel) .AddMethod(__Method_DeployModel, serviceImpl.DeployModel) .AddMethod(__Method_UndeployModel, serviceImpl.UndeployModel) .AddMethod(__Method_ExportModel, serviceImpl.ExportModel) .AddMethod(__Method_GetModelEvaluation, serviceImpl.GetModelEvaluation) .AddMethod(__Method_ListModelEvaluations, serviceImpl.ListModelEvaluations).Build(); } /// <summary>Register service method with a service binder with or without implementation. Useful when customizing the service binding logic. /// Note: this method is part of an experimental API that can change or be removed without any prior notice.</summary> /// <param name="serviceBinder">Service methods will be bound by calling <c>AddMethod</c> on this object.</param> /// <param name="serviceImpl">An object implementing the server-side handling logic.</param> [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] public static void BindService(grpc::ServiceBinderBase serviceBinder, AutoMlBase serviceImpl) { serviceBinder.AddMethod(__Method_CreateDataset, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Google.Cloud.AutoML.V1.CreateDatasetRequest, global::Google.LongRunning.Operation>(serviceImpl.CreateDataset)); serviceBinder.AddMethod(__Method_GetDataset, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Google.Cloud.AutoML.V1.GetDatasetRequest, global::Google.Cloud.AutoML.V1.Dataset>(serviceImpl.GetDataset)); serviceBinder.AddMethod(__Method_ListDatasets, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Google.Cloud.AutoML.V1.ListDatasetsRequest, global::Google.Cloud.AutoML.V1.ListDatasetsResponse>(serviceImpl.ListDatasets)); serviceBinder.AddMethod(__Method_UpdateDataset, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Google.Cloud.AutoML.V1.UpdateDatasetRequest, global::Google.Cloud.AutoML.V1.Dataset>(serviceImpl.UpdateDataset)); serviceBinder.AddMethod(__Method_DeleteDataset, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Google.Cloud.AutoML.V1.DeleteDatasetRequest, global::Google.LongRunning.Operation>(serviceImpl.DeleteDataset)); serviceBinder.AddMethod(__Method_ImportData, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Google.Cloud.AutoML.V1.ImportDataRequest, global::Google.LongRunning.Operation>(serviceImpl.ImportData)); serviceBinder.AddMethod(__Method_ExportData, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Google.Cloud.AutoML.V1.ExportDataRequest, global::Google.LongRunning.Operation>(serviceImpl.ExportData)); serviceBinder.AddMethod(__Method_GetAnnotationSpec, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Google.Cloud.AutoML.V1.GetAnnotationSpecRequest, global::Google.Cloud.AutoML.V1.AnnotationSpec>(serviceImpl.GetAnnotationSpec)); serviceBinder.AddMethod(__Method_CreateModel, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Google.Cloud.AutoML.V1.CreateModelRequest, global::Google.LongRunning.Operation>(serviceImpl.CreateModel)); serviceBinder.AddMethod(__Method_GetModel, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Google.Cloud.AutoML.V1.GetModelRequest, global::Google.Cloud.AutoML.V1.Model>(serviceImpl.GetModel)); serviceBinder.AddMethod(__Method_ListModels, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Google.Cloud.AutoML.V1.ListModelsRequest, global::Google.Cloud.AutoML.V1.ListModelsResponse>(serviceImpl.ListModels)); serviceBinder.AddMethod(__Method_DeleteModel, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Google.Cloud.AutoML.V1.DeleteModelRequest, global::Google.LongRunning.Operation>(serviceImpl.DeleteModel)); serviceBinder.AddMethod(__Method_UpdateModel, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Google.Cloud.AutoML.V1.UpdateModelRequest, global::Google.Cloud.AutoML.V1.Model>(serviceImpl.UpdateModel)); serviceBinder.AddMethod(__Method_DeployModel, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Google.Cloud.AutoML.V1.DeployModelRequest, global::Google.LongRunning.Operation>(serviceImpl.DeployModel)); serviceBinder.AddMethod(__Method_UndeployModel, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Google.Cloud.AutoML.V1.UndeployModelRequest, global::Google.LongRunning.Operation>(serviceImpl.UndeployModel)); serviceBinder.AddMethod(__Method_ExportModel, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Google.Cloud.AutoML.V1.ExportModelRequest, global::Google.LongRunning.Operation>(serviceImpl.ExportModel)); serviceBinder.AddMethod(__Method_GetModelEvaluation, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Google.Cloud.AutoML.V1.GetModelEvaluationRequest, global::Google.Cloud.AutoML.V1.ModelEvaluation>(serviceImpl.GetModelEvaluation)); serviceBinder.AddMethod(__Method_ListModelEvaluations, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Google.Cloud.AutoML.V1.ListModelEvaluationsRequest, global::Google.Cloud.AutoML.V1.ListModelEvaluationsResponse>(serviceImpl.ListModelEvaluations)); } } } #endregion
71.284442
385
0.722225
[ "Apache-2.0" ]
Mattlk13/google-cloud-dotnet
apis/Google.Cloud.AutoML.V1/Google.Cloud.AutoML.V1/ServiceGrpc.g.cs
120,043
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 gamelift-2015-10-01.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.GameLift.Model { /// <summary> /// This is the response object from the DeleteVpcPeeringConnection operation. /// </summary> public partial class DeleteVpcPeeringConnectionResponse : AmazonWebServiceResponse { } }
29.921053
106
0.738786
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/GameLift/Generated/Model/DeleteVpcPeeringConnectionResponse.cs
1,137
C#
using System.Web; using MarkdownDeep; namespace CroquetAustralia.Library.Content { public class MarkdownTransformer : IMarkdownTransformer { public IHtmlString MarkdownToHtml(string content) { var markdown = new Markdown { // ExtraMode is required to support tables. ExtraMode = true }; var html = markdown.Transform(content); return new HtmlString(html); } } }
23.428571
59
0.583333
[ "MIT" ]
croquet-australia/croquet-australia-website
source/CroquetAustralia.Library/Content/MarkdownTransformer.cs
492
C#
/* Copyright (c) 2017, Nokia All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using net.nuagenetworks.bambou; using net.nuagenetworks.vspk.v6; namespace net.nuagenetworks.vspk.v6.fetchers { public class VNFMetadatasFetcher: RestFetcher<VNFMetadata> { private const long serialVersionUID = 1L; public VNFMetadatasFetcher(RestObject parentRestObj) : base(parentRestObj, typeof(VNFMetadata)) { } } }
41.638298
86
0.748084
[ "BSD-3-Clause" ]
nuagenetworks/vspk-csharp
vspk/vspk/VNFMetadatasFetcher.cs
1,957
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Navigation; using Microsoft.Phone.Controls; using Microsoft.Phone.Shell; using System.Windows.Media; using System.Windows.Media.Imaging; using Microsoft.Xna.Framework.Media; using System.IO; using System.Threading; using System.Windows.Threading; using System.Diagnostics; using System.Windows.Media.Animation; using System.Runtime.InteropServices.WindowsRuntime; using PerfectCamera.Filters; using PerfectCamera.Filters.Artistic; using PerfectCamera.Filters.FilterControls; using System.IO.IsolatedStorage; using Windows.Storage.Streams; using System.Threading.Tasks; using Lumia.Imaging; using Lumia.Imaging.Adjustments; using Lumia.Imaging.Artistic; using Lumia.Imaging.Custom; using Lumia.Imaging.Compositing; using Lumia.Imaging.Transforms; using PerfectCamera.Filters.Lomo; using PerfectCamera.Filters.Funny; using PerfectCamera.Filters.Retro; using PerfectCamera.Filters.MagicSkin; namespace PerfectCamera { public class EffectGroup<T>: List<T> { public string Name { get; set; } public Uri ThumbnailUri { get; set; } } public partial class EditPage : PhoneApplicationPage { private EffectIndex _selectedEffect = new EffectIndex(0, 0); private Picture _editingPicture = null; private Semaphore _editSemaphore = new Semaphore(1,1); // Constants private const String DebugTag = "PreviewPage: "; private const double DefaultOutputResolutionWidth = 480; private const double DefaultOutputResolutionHeight = 640; private const String FileNamePrefix = "FilterEffects_"; private const String TombstoneImageDir = "TempData"; private const String TombstoneImageFile = "TempData\\TempImage.jpg"; private const String EffectGroupIndexKey = "GroupIndex"; private const String FilterIndexKey = "FilterIndex"; private const int HideControlsDelay = 2; // Seconds private const String PivotItemNamePrefix = "PivotItem_"; private const String FilterPropertyControlNamePrefix = "FilterPropertyControl_"; // Members private List<EffectGroup<AbstractFilter>> _effects = null; private ProgressIndicator _progressIndicator = new ProgressIndicator(); private DispatcherTimer _timer = null; private FilterPropertiesControl _controlToHide = null; private bool _isNewPageInstance = false; private MemoryStream _editingStream = new MemoryStream(); private AbstractFilter _lastSelectedFilter = null; public EditPage() { InitializeComponent(); if (PhoneApplicationService.Current.State.ContainsKey("EditPicture")) { _editingPicture = PhoneApplicationService.Current.State["EditPicture"] as Picture; if (_editingPicture != null) { var stream = _editingPicture.GetImage(); stream.CopyTo(_editingStream); _editingStream.Position = 0; BitmapImage img = new BitmapImage(); img.SetSource(_editingStream); CurrentEditImage.Source = img; OriginalImageHolder.Source = img; } } _isNewPageInstance = true; _progressIndicator.IsIndeterminate = true; CreateComponents(); } protected override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); // If _isNewPageInstance is true, the state may need to be restored. if (_isNewPageInstance) { RestoreState(); } // If the user navigates back to this page and it has remained in // memory, this value will continue to be false. _isNewPageInstance = false; } protected override void OnNavigatedFrom(NavigationEventArgs e) { // On back navigation there is no need to save state. if (e.NavigationMode != System.Windows.Navigation.NavigationMode.Back) { StoreState(); } else { // Navigating back // Dispose the filters foreach (var group in _effects) { foreach (AbstractFilter filter in group) { filter.Dispose(); } } _editingStream.Dispose(); } base.OnNavigatedFrom(e); } /// <summary> /// Store the page state in case application gets tombstoned. /// </summary> private void StoreState() { // Save the currently filtered image into isolated app storage. IsolatedStorageFile myStore = IsolatedStorageFile.GetUserStoreForApplication(); myStore.CreateDirectory(TombstoneImageDir); try { using (var isoFileStream = new IsolatedStorageFileStream( TombstoneImageFile, FileMode.OpenOrCreate, myStore)) { _editingStream.Position = 0; _editingStream.CopyTo(isoFileStream); isoFileStream.Flush(); } } catch { MessageBox.Show("Error while trying to store temporary image."); } // Save also the current preview index State[EffectGroupIndexKey] = _selectedEffect.EffectIdx; State[FilterIndexKey] = _selectedEffect.FilterIdx; } /// <summary> /// Restores the page state if application was tombstoned. /// </summary> private async void RestoreState() { // Load also the preview index which was last used if (State.ContainsKey(EffectGroupIndexKey) && State.ContainsKey(FilterIndexKey)) { _selectedEffect.EffectIdx = (int)State[EffectGroupIndexKey]; _selectedEffect.FilterIdx = (int)State[FilterIndexKey]; } // Load the image which was filtered from isolated app storage. IsolatedStorageFile myStore = IsolatedStorageFile.GetUserStoreForApplication(); try { if (myStore.FileExists(TombstoneImageFile)) { using (var isoFileStream = new IsolatedStorageFileStream( TombstoneImageFile, FileMode.Open, myStore)) { // Load image asynchronously at application launch await isoFileStream.CopyToAsync(_editingStream); Dispatcher.BeginInvoke(() => { EffectGroup<AbstractFilter> group = _effects[_selectedEffect.EffectIdx]; AbstractFilter filter = group[_selectedEffect.FilterIdx]; filter.Buffer = _editingStream.GetWindowsRuntimeBuffer(); filter.Apply(); CurrentEditImage.Source = filter.PreviewImageSource; }); } } } catch { MessageBox.Show("Error while trying to restore temporary image."); } // Remove temporary file from isolated storage try { if (myStore.FileExists(TombstoneImageFile)) { myStore.DeleteFile(TombstoneImageFile); } } catch (IsolatedStorageException /*ex*/) { MessageBox.Show("Error while trying to delete temporary image."); } } private void CancelButton_Click(object sender, RoutedEventArgs e) { NavigationService.GoBack(); } private void SaveButton_Click(object sender, RoutedEventArgs e) { } private void EffectButton_Click(object sender, RoutedEventArgs e) { /*HideEffectLayoutButton.Visibility = System.Windows.Visibility.Visible; CancelEffectButton.Visibility = System.Windows.Visibility.Collapsed; EffectTitleTextBlock.Visibility = System.Windows.Visibility.Collapsed; ApplyEffectButton.Visibility = System.Windows.Visibility.Collapsed;*/ PreviewImageGrid.Tap += PreviewImageGrid_Tap; EffectButton.IsHitTestVisible = false; EffectLayoutSlideIn.Begin(); } private void HideEffectLayoutButton_Click(object sender, RoutedEventArgs e) { HideEffectLayoutButton.IsHitTestVisible = false; EffectLayoutSlideOut.Begin(); } private void EffectLayoutSlideOut_Completed(object sender, EventArgs e) { PreviewImageGrid.Tap -= PreviewImageGrid_Tap; HintText.Visibility = System.Windows.Visibility.Collapsed; EffectButton.IsHitTestVisible = true; CancelEffectButton.IsHitTestVisible = true; ApplyEffectButton.IsHitTestVisible = true; } private void EffectLayoutSlideIn_Completed(object sender, EventArgs e) { HideEffectLayoutButton.IsHitTestVisible = true; } private void InitEffectPanel() { if (_effects != null) { EffectStackPanel.Children.Clear(); for (int i = 0; i < _effects.Count; i++) { EffectGroup<AbstractFilter> group = _effects[i]; Button btn = new Button() { Style = (Style)Application.Current.Resources["ButtonStyleNoBorder"], Margin = new Thickness(10, 0, 0, 0), Height = 130, Width = 97, Background = new ImageBrush() { ImageSource = new BitmapImage(group.ThumbnailUri), Stretch = Stretch.Uniform }, Tag = i, ContentTemplate = (DataTemplate)Application.Current.Resources["ButtonContentWrap"], Content = group.Name, FontSize = 20, FontWeight = FontWeights.Light }; EffectStackPanel.Children.Add(btn); btn.Click += EffectGroup_Click; } EffectStackPanel.Width = _effects.Count * 97 + (_effects.Count + 1) * 10; } } void EffectGroup_Click(object sender, RoutedEventArgs e) { HideEffectLayoutButton.Visibility = System.Windows.Visibility.Collapsed; CancelEffectButton.Visibility = System.Windows.Visibility.Visible; EffectTitleTextBlock.Visibility = System.Windows.Visibility.Visible; ApplyEffectButton.Visibility = System.Windows.Visibility.Visible; FilterStackPanel.Children.Clear(); if (_effects != null) { Button clickedbtn = sender as Button; int idx = (int)clickedbtn.Tag; Button backBtn = new Button() { Style = (Style)Application.Current.Resources["ButtonStyleNoBorder"], Margin = new Thickness(10, 0, 0, 0), Height = 130, Width = 60, Background = new ImageBrush() { ImageSource = new BitmapImage(new Uri("/Assets/BackToEffectButton.png", UriKind.Relative)), Stretch = Stretch.Uniform } }; FilterStackPanel.Children.Add(backBtn); backBtn.Click += BackToEffect_Click; if (idx >= 0 && idx < _effects.Count) { EffectGroup<AbstractFilter> group = _effects[idx]; for (int i = 0; i < group.Count; i++) { AbstractFilter filter = group[i]; Button btn = new Button() { Style = (Style)Application.Current.Resources["ButtonStyleNoBorder"], Margin = new Thickness(10, 0, 0, 0), Height = 130, Width = 97, Background = new ImageBrush() { ImageSource = new BitmapImage(filter.ThumbnailUri), Stretch = Stretch.Uniform }, Tag = i, ContentTemplate = (DataTemplate)Application.Current.Resources["ButtonContentWrap"], Content = filter.Name, FontSize = 20, FontWeight = FontWeights.Light }; FilterStackPanel.Children.Add(btn); btn.Click += FilterButton_Click; } FilterStackPanel.Width = group.Count * 97 + (group.Count + 1) * 10 + 70; } _selectedEffect.EffectIdx = idx; FilterPanelSlideIn.Begin(); } } void BackToEffect_Click(object sender, RoutedEventArgs e) { ApplyEditIndicator.Visibility = System.Windows.Visibility.Visible; PreviewImageGrid.Tap -= PreviewImageGrid_Tap; HintText.Visibility = System.Windows.Visibility.Collapsed; Dispatcher.BeginInvoke(() => { CancelEffectButton.IsHitTestVisible = false; BitmapImage img = new BitmapImage(); img.SetSource(_editingStream); CurrentEditImage.Source = img; ApplyEditIndicator.Visibility = System.Windows.Visibility.Collapsed; }); FilterPanelSlideOut.Begin(); HideEffectLayoutButton.Visibility = System.Windows.Visibility.Visible; CancelEffectButton.Visibility = System.Windows.Visibility.Collapsed; EffectTitleTextBlock.Visibility = System.Windows.Visibility.Collapsed; ApplyEffectButton.Visibility = System.Windows.Visibility.Collapsed; } private void ShowHint() { Debug.WriteLine(DebugTag + "FilterPreviewPivot_SelectionChanged()"); EffectGroup<AbstractFilter> group = _effects[_selectedEffect.EffectIdx]; AbstractFilter filter = group[_selectedEffect.FilterIdx]; if (filter.Control != null) { HintText.Visibility = Visibility.Visible; } else if (HintText.Visibility == Visibility.Visible) { HintText.Visibility = Visibility.Collapsed; } ShowControlsAnimationStoryBoard.Completed -= ShowControlsAnimationStoryBoard_Completed; HideControlsAnimation.Completed -= HideControlsAnimation_Completed; ShowControlsAnimationStoryBoard.Stop(); HideControlsAnimationStoryBoard.Stop(); if (_controlToHide != null) { _controlToHide.Visibility = Visibility.Collapsed; _controlToHide.Opacity = 0; _controlToHide = null; } } void FilterButton_Click(object sender, RoutedEventArgs e) { if (_editSemaphore.WaitOne(500)) { var clickedBtn = sender as Button; _selectedEffect.FilterIdx = (int)clickedBtn.Tag; ShowHint(); if (_editingPicture != null) { if (_lastSelectedFilter != null) { _lastSelectedFilter.ReleaseBitmapMemory(); } EffectGroup<AbstractFilter> group = _effects[_selectedEffect.EffectIdx]; AbstractFilter filter = group[_selectedEffect.FilterIdx]; _lastSelectedFilter = filter; filter.CreateBimapMemory(); _editingStream.Position = 0; filter.Buffer = _editingStream.GetWindowsRuntimeBuffer(); filter.Apply(); CurrentEditImage.Source = filter.PreviewImageSource; } _editSemaphore.Release(); } } /// <summary> /// Constructs the filters and the pivot items. /// </summary> private void CreateComponents() { CreateFilters(); // Create a pivot item with an image for each filter. The image // content is added later. In addition, create the preview bitmaps // and associate them with the images. foreach (var group in _effects) { foreach (var filter in group) { FilterPropertiesControl control = new FilterPropertiesControl(); String name = FilterPropertyControlNamePrefix + filter.Name; control.Name = name; if (filter.AttachControl(control)) { control.VerticalAlignment = VerticalAlignment.Bottom; control.Opacity = 0; control.Visibility = Visibility.Collapsed; control.ControlBackground.Fill = AppUtils.ThemeBackgroundBrush; PreviewImageGrid.Children.Add(control); control.Manipulated += OnControlManipulated; } Windows.Foundation.Size previewSize = new Windows.Foundation.Size(); previewSize.Width = DefaultOutputResolutionWidth; previewSize.Height = _editingPicture.Height * previewSize.Width / _editingPicture.Width; //filter.PreviewResolution = new Windows.Foundation.Size(DefaultOutputResolutionWidth, DefaultOutputResolutionHeight); filter.PreviewResolution = previewSize; } } HintTextBackground.Fill = AppUtils.ThemeBackgroundBrush; InitEffectPanel(); } /// <summary> /// Constructs the filters. /// </summary> private void CreateFilters() { _effects = new List<EffectGroup<AbstractFilter>>(); var group = new EffectGroup<AbstractFilter> { new OriginalImageFilter(), new SixthGearFilter(), new SadHipsterFilter(), new EightiesPopSongFilter(), new MarvelFilter(), new SurroundedFilter() }; group.Name = "Filters"; group.ThumbnailUri = new Uri("/Assets/EffectThumbnails/NoEffect.png", UriKind.Relative); _effects.Add(group); CreateMagicSkinGroup(); CreateArtisticGroup(); CreateEnhanceGroup(); CreateHDRGroup(); CreateLightColorGroup(); CreateLOFTGroup(); CreateSketchGroup(); CreateLOMOGroup(); CreateRetroGroup(); CreateFunnyGroup(); } /// <summary> /// Shows the filter property controls. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void PreviewImageGrid_Tap(object sender, System.Windows.Input.GestureEventArgs e) { if (sender is Grid) { Grid grid = (Grid)sender; EffectGroup<AbstractFilter> group = _effects[_selectedEffect.EffectIdx]; AbstractFilter filter = group[_selectedEffect.FilterIdx]; foreach (UIElement element in grid.Children) { if (element is FilterPropertiesControl) { if ((element.Visibility == Visibility.Collapsed || element.Opacity < 1) && element == filter.Control) { Debug.WriteLine(DebugTag + "ShowPropertiesControls()"); if (HintText.Visibility == Visibility.Visible) { HintText.Visibility = Visibility.Collapsed; } HideControlsAnimation.Completed -= HideControlsAnimation_Completed; HideControlsAnimationStoryBoard.Stop(); if (_timer != null) { _timer.Tick -= HidePropertiesControls; _timer.Stop(); _timer = null; } _controlToHide = (FilterPropertiesControl)element; _controlToHide.Visibility = Visibility.Visible; try { Storyboard.SetTargetName(ShowControlsAnimation, _controlToHide.Name); ShowControlsAnimation.From = _controlToHide.Opacity; ShowControlsAnimationStoryBoard.Completed += ShowControlsAnimationStoryBoard_Completed; ShowControlsAnimationStoryBoard.Begin(); } catch (InvalidOperationException ex) { Debug.WriteLine(ex.ToString()); } _timer = new DispatcherTimer { Interval = new TimeSpan(0, 0, 0, HideControlsDelay) }; _timer.Tick += HidePropertiesControls; _timer.Start(); break; } } } } } /// <summary> /// Makes sure that the controls stay visible after the animation is /// completed. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void ShowControlsAnimationStoryBoard_Completed(object sender, EventArgs e) { _controlToHide.Opacity = 1; ShowControlsAnimationStoryBoard.Completed -= ShowControlsAnimationStoryBoard_Completed; } /// <summary> /// Hides the filter property controls. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void HidePropertiesControls(object sender, EventArgs e) { ShowControlsAnimationStoryBoard.Stop(); if (_controlToHide != null) { Debug.WriteLine(DebugTag + "HidePropertiesControls()"); Storyboard.SetTargetName(HideControlsAnimation, _controlToHide.Name); HideControlsAnimation.From = _controlToHide.Opacity; HideControlsAnimationStoryBoard.Begin(); HideControlsAnimation.Completed += HideControlsAnimation_Completed; } if (_timer != null) { _timer.Tick -= HidePropertiesControls; _timer.Stop(); _timer = null; } } /// <summary> /// Completes the actions when HideControlsAnimation has finished. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void HideControlsAnimation_Completed(object sender, EventArgs e) { HideControlsAnimation.Completed -= HideControlsAnimation_Completed; _controlToHide.Visibility = Visibility.Collapsed; _controlToHide.Opacity = 0; _controlToHide = null; } /// <summary> /// Restarts the timer responsible for hiding the filter property /// controls. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void OnControlManipulated(object sender, EventArgs e) { Debug.WriteLine(DebugTag + "OnControlManipulated(): " + sender); if (_timer != null) { _timer.Stop(); _timer.Start(); } } private void CancelEffectButton_Click(object sender, RoutedEventArgs e) { ApplyEditIndicator.Visibility = System.Windows.Visibility.Visible; Dispatcher.BeginInvoke(() => { CancelEffectButton.IsHitTestVisible = false; EffectLayoutSlideOut.Begin(); BitmapImage img = new BitmapImage(); img.SetSource(_editingStream); CurrentEditImage.Source = img; ApplyEditIndicator.Visibility = System.Windows.Visibility.Collapsed; }); } private async void ApplyEffectButton_Click(object sender, RoutedEventArgs e) { ApplyEditIndicator.Visibility = System.Windows.Visibility.Visible; EffectGroup<AbstractFilter> group = _effects[_selectedEffect.EffectIdx]; AbstractFilter filter = group[_selectedEffect.FilterIdx]; _editingStream.Position = 0; IBuffer buffer = await filter.RenderJpegAsync(_editingStream.GetWindowsRuntimeBuffer()); _editingStream.Position = 0; Stream stream = buffer.AsStream(); stream.CopyTo(_editingStream); ApplyEditIndicator.Visibility = System.Windows.Visibility.Collapsed; ApplyEffectButton.IsHitTestVisible = false; EffectLayoutSlideOut.Begin(); } private void CreateMagicSkinGroup() { EffectGroup<AbstractFilter> group = new EffectGroup<AbstractFilter>() { new MagicSkinNaturalFilter() }; group.Name = "Magic Skin"; group.ThumbnailUri = new Uri("/Assets/EffectThumbnails/NoEffect.png", UriKind.Relative); _effects.Add(group); } private void CreateArtisticGroup() { EffectGroup<AbstractFilter> group = new EffectGroup<AbstractFilter> { new AntiqueWrapperFilter(), new CartoonWrapperFilter(), new ColorSwapWrapperFilter(), new EmbossWrapperFilter(), new FogWrapperFilter(), new FoundationWrapperFilter(), new GrayscaleNegativeWrapperFilter(), new MagicPenWrapperFilter(), new MilkyWrapperFilter() }; group.Name = "Artistic"; group.ThumbnailUri = new Uri("/Assets/EffectThumbnails/NoEffect.png", UriKind.Relative); _effects.Add(group); } private void CreateLightColorGroup() { EffectGroup<AbstractFilter> group = new EffectGroup<AbstractFilter>(); group.Name = "Light Color"; group.ThumbnailUri = new Uri("/Assets/EffectThumbnails/NoEffect.png", UriKind.Relative); _effects.Add(group); } private void CreateEnhanceGroup() { EffectGroup<AbstractFilter> group = new EffectGroup<AbstractFilter>(); group.Name = "Enhance"; group.ThumbnailUri = new Uri("/Assets/EffectThumbnails/NoEffect.png", UriKind.Relative); _effects.Add(group); } private void CreateHDRGroup() { EffectGroup<AbstractFilter> group = new EffectGroup<AbstractFilter>(); group.Name = "HDR"; group.ThumbnailUri = new Uri("/Assets/EffectThumbnails/NoEffect.png", UriKind.Relative); _effects.Add(group); } private void CreateLOFTGroup() { EffectGroup<AbstractFilter> group = new EffectGroup<AbstractFilter>(); group.Name = "LOFT"; group.ThumbnailUri = new Uri("/Assets/EffectThumbnails/NoEffect.png", UriKind.Relative); _effects.Add(group); } private void CreateSketchGroup() { EffectGroup<AbstractFilter> group = new EffectGroup<AbstractFilter>(); group.Name = "Sketch"; group.ThumbnailUri = new Uri("/Assets/EffectThumbnails/NoEffect.png", UriKind.Relative); _effects.Add(group); } private void CreateLOMOGroup() { EffectGroup<AbstractFilter> group = new EffectGroup<AbstractFilter>() { new LomoNeutralFilter(), new LomoRedFilter(), new LomoGreenFilter(), new LomoBlueFilter(), new LomoYellowFilter() }; group.Name = "LOMO"; group.ThumbnailUri = new Uri("/Assets/EffectThumbnails/NoEffect.png", UriKind.Relative); _effects.Add(group); } private void CreateRetroGroup() { EffectGroup<AbstractFilter> group = new EffectGroup<AbstractFilter>() { new RetroPurpleFilter(), new VintageFilter(), new RetroBloomFilter(), new RetroGoldenFilter(), new RetroLightFilter(), //new RetroCleanFilter(), new RetroFadedFilter(), new RetroEmeraldFilter(), new RetroDiffuseFilter() }; group.Name = "Retro"; group.ThumbnailUri = new Uri("/Assets/EffectThumbnails/NoEffect.png", UriKind.Relative); _effects.Add(group); } private void CreateFunnyGroup() { EffectGroup<AbstractFilter> group = new EffectGroup<AbstractFilter>() { new MirrorAboveFilter(), new MirrorBelowFilter(), new MirrorLeftFilter(), new MirrorRightFilter(), new FishEyeFilter(), new OrangeWrapperFilter(), new RoseWrapperFilter(), new GreenWrapperFilter(), new BlueWrapperFilter() }; group.Name = "Funny"; group.ThumbnailUri = new Uri("/Assets/EffectThumbnails/NoEffect.png", UriKind.Relative); _effects.Add(group); } private void OriginalImageHolder_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e) { CurrentEditImage.Visibility = System.Windows.Visibility.Collapsed; } private void OriginalImageHolder_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e) { CurrentEditImage.Visibility = System.Windows.Visibility.Visible; } private void PreviewImageGrid_Hold(object sender, System.Windows.Input.GestureEventArgs e) { CurrentEditImage.Visibility = System.Windows.Visibility.Collapsed; } private void PreviewImageGrid_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e) { CurrentEditImage.Visibility = System.Windows.Visibility.Visible; } private void PreviewImageGrid_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e) { CurrentEditImage.Visibility = System.Windows.Visibility.Visible; } } }
38.719298
139
0.534783
[ "MIT" ]
KayNag/LumiaImagingSDKSample
PerfectCamera/EditPage.xaml.cs
33,107
C#
using System; namespace Core.Math.Matrixes.Generics.Implementation.Memory { /// <summary> /// /// </summary> /// <see cref="https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/multidimensional-arrays"/> /// <see cref="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/operator-overloading"/> /// <typeparam name="T"></typeparam> public partial class Matrix<T> where T : System.INumber<T> { /// <summary> /// Matrix constructor (ctor) /// </summary> /// <param name="count_rows"></param> /// <param name="count_columns"></param> public Matrix ( int count_rows = 1, int count_columns = 1 ) { this.CountRows = count_rows; this.CountColumns = count_columns; T[] data_array = new T[count_rows * count_columns]; this.data = new Memory<T>(data_array, 0, count_rows * count_columns - 1); return; } /// <summary> /// Matrix copy constructor (cctor) /// </summary> /// <param name="m"></param> public Matrix ( Matrix<T> m ) { int count_rows = m.CountRows; int count_columns = m.CountColumns; this.CountRows = count_rows; this.CountColumns = count_columns; T[] data_array = new T[count_rows * count_columns]; this.data = new Memory<T>(data_array, 0, count_rows * count_columns - 1); int index; for (int r = 1; r <= count_rows; r++) { for (int c = 1; c <= count_columns; c++) { index = (r - 1) * CountColumns + (c - 1); data.Span[index] = m[r, c]; } } return; } } }
32.214286
118
0.427938
[ "MIT" ]
HolisticWare/HolisticWare.Core.Math.Matrix
source/HolisticWare.Core.Math.Matrixes.Generic/Core.Math.Matrixes/Memory/Matrix.cs
2,257
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; using Microsoft.ApplicationInsights.Channel; using Microsoft.ApplicationInsights.DataContracts; using Microsoft.ApplicationInsights.Extensibility.Implementation; using Microsoft.Azure.WebJobs.Host; using Microsoft.Azure.WebJobs.Logging; using Microsoft.Azure.WebJobs.Script.Diagnostics; using Microsoft.Azure.WebJobs.Script.WebHost.Diagnostics; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.WebJobs.Script.Tests; using Newtonsoft.Json.Linq; using Xunit; namespace Microsoft.Azure.WebJobs.Script.Tests.ApplicationInsights { public abstract class ApplicationInsightsEndToEndTestsBase<TTestFixture> : IClassFixture<TTestFixture> where TTestFixture : ApplicationInsightsTestFixture, new() { private ApplicationInsightsTestFixture _fixture; public ApplicationInsightsEndToEndTestsBase(ApplicationInsightsTestFixture fixture) { _fixture = fixture; } [Fact] public async Task Validate_Manual() { string functionName = "Scenarios"; int invocationCount = 5; List<string> functionTraces = new List<string>(); // We want to invoke this multiple times specifically to make sure Node invocationIds // are correctly being set. Invoke them all first, then come back and validate all. for (int i = 0; i < invocationCount; i++) { string functionTrace = $"Function trace: {Guid.NewGuid().ToString()}"; functionTraces.Add(functionTrace); JObject input = new JObject() { { "scenario", "appInsights" }, { "container", "not-used" }, { "value", functionTrace } }; await _fixture.TestHost.BeginFunctionAsync(functionName, input); } // Now validate each function invocation. foreach (string functionTrace in functionTraces) { await WaitForFunctionTrace(functionName, functionTrace); string invocationId = await ValidateEndToEndTestAsync(functionName, functionTrace, true); // TODO: Remove this check when metrics are supported in Node: // https://github.com/Azure/azure-functions-host/issues/2189 if (this is ApplicationInsightsCSharpEndToEndTests) { // Do some additional metric validation MetricTelemetry metric = _fixture.Channel.Telemetries .OfType<MetricTelemetry>() .Where(t => GetInvocationId(t) == invocationId) .Single(); ValidateMetric(metric, invocationId, functionName); } } // App Insights logs first, so wait until this metric appears string metricKey = MetricsEventManager.GetAggregateKey(MetricEventNames.FunctionUserLog, functionName); IEnumerable<string> GetMetrics() => _fixture.MetricsLogger.LoggedEvents.Where(p => p == metricKey); // TODO: Remove this check when metrics are supported in Node: // https://github.com/Azure/azure-functions-host/issues/2189 int expectedCount = this is ApplicationInsightsCSharpEndToEndTests ? 10 : 5; await TestHelpers.Await(() => GetMetrics().Count() == expectedCount, timeout: 15000, userMessageCallback: () => string.Join(Environment.NewLine, GetMetrics().Select(p => p.ToString()))); } [Fact] public async Task Validate_Http_Success() { await RunHttpTest("HttpTrigger-Scenarios", "appInsights-Success", HttpStatusCode.OK, true); } [Fact] public async Task Validate_Http_Failure() { await RunHttpTest("HttpTrigger-Scenarios", "appInsights-Failure", HttpStatusCode.Conflict, true); } [Fact] public async Task Validate_Http_Throw() { await RunHttpTest("HttpTrigger-Scenarios", "appInsights-Throw", HttpStatusCode.InternalServerError, false); } private async Task RunHttpTest(string functionName, string scenario, HttpStatusCode expectedStatusCode, bool functionSuccess) { HttpRequestMessage request = new HttpRequestMessage { RequestUri = new Uri($"https://localhost/api/{functionName}"), Method = HttpMethod.Post, }; string functionTrace = $"Function trace: {Guid.NewGuid().ToString()}"; JObject input = new JObject() { { "scenario", scenario }, { "container", "not-used" }, { "value", functionTrace }, }; request.Content = new StringContent(input.ToString()); request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); request.Content.Headers.ContentLength = input.ToString().Length; HttpResponseMessage response = await _fixture.HttpClient.SendAsync(request); Assert.Equal(expectedStatusCode, response.StatusCode); string invocationId = await ValidateEndToEndTestAsync(functionName, functionTrace, functionSuccess); // Perform some additional validation on HTTP properties RequestTelemetry requestTelemetry = _fixture.Channel.Telemetries .OfType<RequestTelemetry>() .Where(t => GetInvocationId(t) == invocationId) .Single(); Assert.Equal(((int)expectedStatusCode).ToString(), requestTelemetry.ResponseCode); Assert.Equal("POST", requestTelemetry.Properties["HttpMethod"]); Assert.Equal(request.RequestUri, requestTelemetry.Url); Assert.Equal(functionSuccess, requestTelemetry.Success); } private async Task<string> ValidateEndToEndTestAsync(string functionName, string functionTrace, bool functionSuccess) { // Look for the trace that matches the GUID we passed in. That's how we'll find the // function's invocation id. TraceTelemetry trace = _fixture.Channel.Telemetries .OfType<TraceTelemetry>() .Where(t => t.Message.Contains(functionTrace)) .Single(); // functions need to log JSON that contains the invocationId and trace JObject logPayload = JObject.Parse(trace.Message); string logInvocationId = logPayload["invocationId"].ToString(); string invocationId = trace.Properties[LogConstants.InvocationIdKey]; // make sure they match Assert.Equal(logInvocationId, invocationId); // Find the Info traces. TraceTelemetry[] traces = _fixture.Channel.Telemetries .OfType<TraceTelemetry>() .Where(t => GetInvocationId(t) == invocationId) .Where(t => !t.Message.StartsWith("Exception")) // we'll verify the exception message separately .Where(t => t.Properties[LogConstants.CategoryNameKey] == LogCategories.CreateFunctionCategory(functionName)) .OrderBy(t => t.Message) .ToArray(); string expectedMessage = functionSuccess ? $"Executed 'Functions.{functionName}' (Succeeded, Id=" : $"Executed 'Functions.{functionName}' (Failed, Id="; SeverityLevel expectedLevel = functionSuccess ? SeverityLevel.Information : SeverityLevel.Error; ValidateTrace(traces[0], expectedMessage + invocationId, LogCategories.CreateFunctionCategory(functionName), functionName, invocationId, expectedLevel); ValidateTrace(traces[1], $"Executing 'Functions.{functionName}' (Reason='This function was programmatically called via the host APIs.', Id=" + invocationId, LogCategories.CreateFunctionCategory(functionName), functionName, invocationId); if (!functionSuccess) { // We see two exceptions: // - 1 with the RequestTelemetry // - 1 with the TraceTelemetry that "Function Executed (Failure...") ExceptionTelemetry[] exceptions = _fixture.Channel.Telemetries .OfType<ExceptionTelemetry>() .Where(t => GetInvocationId(t) == invocationId) .OrderBy(t => t.Properties[LogConstants.CategoryNameKey]) .ToArray(); Assert.Equal(2, exceptions.Length); ValidateException(exceptions[0], invocationId, functionName, LogCategories.CreateFunctionCategory(functionName)); ValidateException(exceptions[1], invocationId, functionName, LogCategories.Results); } // The Request is written separately by App Insights so we need to wait for it RequestTelemetry requestTelemetry = null; await TestHelpers.Await(() => { requestTelemetry = _fixture.Channel.Telemetries .OfType<RequestTelemetry>() .Where(t => GetInvocationId(t) == invocationId) .SingleOrDefault(); return requestTelemetry != null; }); ValidateRequest(requestTelemetry, invocationId, functionName, "req", functionSuccess); // Make sure all the operationIds match var operationId = requestTelemetry.Context.Operation.Id; Assert.Equal(operationId, traces[0].Context.Operation.Id); Assert.Equal(operationId, traces[1].Context.Operation.Id); return invocationId; } private async Task WaitForFunctionTrace(string functionName, string functionTrace) { // watch for the specific user log, then make sure the request telemetry has flushed, which // indicates all logging is done for this function invocation await TestHelpers.Await(() => { bool done = false; TraceTelemetry logTrace = _fixture.Channel.Telemetries.OfType<TraceTelemetry>().SingleOrDefault(p => p.Message.Contains(functionTrace) && p.Properties[LogConstants.CategoryNameKey] == LogCategories.CreateFunctionUserCategory(functionName)); if (logTrace != null) { string invocationId = logTrace.Properties[LogConstants.InvocationIdKey]; RequestTelemetry request = _fixture.Channel.Telemetries.OfType<RequestTelemetry>().SingleOrDefault(p => GetInvocationId(p) == invocationId); done = request != null; } return done; }, userMessageCallback: _fixture.TestHost.GetLog); } private void ValidateException(ExceptionTelemetry telemetry, string expectedInvocationId, string expectedOperationName, string expectedCategory) { Assert.IsType<FunctionInvocationException>(telemetry.Exception); ValidateTelemetry(telemetry, expectedInvocationId, expectedOperationName, expectedCategory, SeverityLevel.Error); } [Fact] public async Task Validate_HostLogs() { // Validate the host startup traces. Order by message string as the requests may come in // slightly out-of-order or on different threads TraceTelemetry[] traces = null; await TestHelpers.Await(() => { traces = _fixture.Channel.Telemetries .OfType<TraceTelemetry>() .Where(t => t.Properties[LogConstants.CategoryNameKey].ToString().StartsWith("Host.")) .OrderBy(t => t.Message) .ToArray(); // When these two messages are logged, we know we've completed initialization. return traces .Where(t => t.Message.Contains("Host lock lease acquired by instance ID") || t.Message.Contains("Job host started")) .Count() == 2; }, userMessageCallback: () => string.Join(Environment.NewLine, _fixture.Channel.Telemetries.OfType<TraceTelemetry>().Select(t => t.Message))); // Excluding Node buffer deprecation warning for now // TODO: Remove this once the issue https://github.com/Azure/azure-functions-nodejs-worker/issues/98 is resolved // We may have any number of "Host Status" calls as we wait for startup. Let's ignore them. traces = traces.Where(t => !t.Message.Contains("[DEP0005]") && !t.Message.StartsWith("Host Status") ).ToArray(); int expectedCount = 12; Assert.True(traces.Length == expectedCount, $"Expected {expectedCount} messages, but found {traces.Length}. Actual logs:{Environment.NewLine}{string.Join(Environment.NewLine, traces.Select(t => t.Message))}"); int idx = 0; ValidateTrace(traces[idx++], "2 functions loaded", LogCategories.Startup); ValidateTrace(traces[idx++], "A function whitelist has been specified", LogCategories.Startup); ValidateTrace(traces[idx++], "Found the following functions:\r\n", LogCategories.Startup); ValidateTrace(traces[idx++], "Generating 2 job function(s)", LogCategories.Startup); ValidateTrace(traces[idx++], "Host initialization: ConsecutiveErrors=0, StartupCount=1", LogCategories.Startup); ValidateTrace(traces[idx++], "Host initialized (", LogCategories.Startup); ValidateTrace(traces[idx++], "Host lock lease acquired by instance ID", ScriptConstants.LogCategoryHostGeneral); ValidateTrace(traces[idx++], "Host started (", LogCategories.Startup); ValidateTrace(traces[idx++], "Initializing Host", LogCategories.Startup); ValidateTrace(traces[idx++], "Job host started", LogCategories.Startup); ValidateTrace(traces[idx++], "Loading functions metadata", LogCategories.Startup); ValidateTrace(traces[idx++], "Starting Host (HostId=", LogCategories.Startup); } [Fact] public void Validate_BeginScope() { var hostBuilder = new HostBuilder() .ConfigureAppConfiguration(c => { c.AddInMemoryCollection(new Dictionary<string, string> { { "APPINSIGHTS_INSTRUMENTATIONKEY", "some_key" }, }); }) .ConfigureDefaultTestWebScriptHost(b => { b.Services.AddSingleton<ITelemetryChannel>(_fixture.Channel); }); using (var host = hostBuilder.Build()) { ILoggerFactory loggerFactory = host.Services.GetService<ILoggerFactory>(); // Create a logger and try out the configured factory. We need to pretend that it is coming from a // function, so set the function name and the category appropriately. ILogger logger = loggerFactory.CreateLogger(LogCategories.CreateFunctionCategory("Test")); string customGuid = Guid.NewGuid().ToString(); using (logger.BeginScope(new Dictionary<string, object> { [ScriptConstants.LogPropertyFunctionNameKey] = "Test", ["parentId"] = customGuid // use a parent id so we can pull all our traces out })) { // Now log as if from within a function. // Test that both dictionaries and structured logs work as state // and that nesting works as expected. using (logger.BeginScope("{customKey1}", "customValue1")) { logger.LogInformation("1"); using (logger.BeginScope(new Dictionary<string, object> { ["customKey2"] = "customValue2" })) { logger.LogInformation("2"); } logger.LogInformation("3"); } using (logger.BeginScope("should not throw")) { logger.LogInformation("4"); } } TraceTelemetry[] traces = _fixture.Channel.Telemetries.OfType<TraceTelemetry>() .Where(t => t.Properties.TryGetValue("prop__parentId", out string value) && value == customGuid) .OrderBy(t => t.Message).ToArray(); Assert.Equal(4, traces.Length); // Every telemetry will have {originalFormat}, Category, Level, but we validate those elsewhere. // We're only interested in the custom properties. Assert.Equal("1", traces[0].Message); Assert.Equal(6, traces[0].Properties.Count); Assert.Equal("customValue1", traces[0].Properties["prop__customKey1"]); Assert.Equal("2", traces[1].Message); Assert.Equal(7, traces[1].Properties.Count); Assert.Equal("customValue1", traces[1].Properties["prop__customKey1"]); Assert.Equal("customValue2", traces[1].Properties["prop__customKey2"]); Assert.Equal("3", traces[2].Message); Assert.Equal(6, traces[2].Properties.Count); Assert.Equal("customValue1", traces[2].Properties["prop__customKey1"]); Assert.Equal("4", traces[3].Message); Assert.Equal(5, traces[3].Properties.Count); } } private static void ValidateMetric(MetricTelemetry telemetry, string expectedInvocationId, string expectedOperationName) { ValidateTelemetry(telemetry, expectedInvocationId, expectedOperationName, LogCategories.CreateFunctionUserCategory(expectedOperationName), SeverityLevel.Information); Assert.Equal("TestMetric", telemetry.Name); Assert.Equal(1234, telemetry.Sum); Assert.Equal(50, telemetry.Count); Assert.Equal(10.4, telemetry.Min); Assert.Equal(23, telemetry.Max); Assert.Equal("100", telemetry.Properties[$"{LogConstants.CustomPropertyPrefix}MyCustomMetricProperty"]); ValidateSdkVersion(telemetry, "af_"); } protected static void ValidateTrace(TraceTelemetry telemetry, string expectedMessageContains, string expectedCategory, string expectedOperationName = null, string expectedInvocationId = null, SeverityLevel expectedLevel = SeverityLevel.Information) { Assert.Contains(expectedMessageContains, telemetry.Message); Assert.Equal(expectedLevel, telemetry.SeverityLevel); Assert.Equal(expectedCategory, telemetry.Properties[LogConstants.CategoryNameKey]); if (expectedCategory.StartsWith("Function.")) { ValidateTelemetry(telemetry, expectedInvocationId, expectedOperationName, expectedCategory, expectedLevel); } else { Assert.Null(telemetry.Context.Operation.Name); Assert.Null(telemetry.Context.Operation.Id); } ValidateSdkVersion(telemetry); } private static void ValidateTelemetry(ITelemetry telemetry, string expectedInvocationId, string expectedOperationName, string expectedCategory, SeverityLevel expectedLevel) { Assert.Equal(expectedInvocationId, ((ISupportProperties)telemetry).Properties[LogConstants.InvocationIdKey]); Assert.Equal(expectedOperationName, telemetry.Context.Operation.Name); ISupportProperties properties = (ISupportProperties)telemetry; Assert.Equal(expectedCategory, properties.Properties[LogConstants.CategoryNameKey]); Assert.Equal(expectedLevel.ToString(), properties.Properties[LogConstants.LogLevelKey]); } private static void ValidateRequest(RequestTelemetry telemetry, string expectedInvocationId, string expectedOperationName, string inputParamName, bool success) { SeverityLevel expectedLevel = success ? SeverityLevel.Information : SeverityLevel.Error; ValidateTelemetry(telemetry, expectedInvocationId, expectedOperationName, LogCategories.Results, expectedLevel); Assert.NotNull(telemetry.Id); Assert.NotNull(telemetry.Duration); Assert.Equal(success, telemetry.Success); AssertHasKey(telemetry.Properties, "FullName", $"Functions.{expectedOperationName}"); AssertHasKey(telemetry.Properties, "TriggerReason", "This function was programmatically called via the host APIs."); ValidateSdkVersion(telemetry); } private static void AssertHasKey(IDictionary<string, string> dict, string keyName, string expectedValue = null) { if (!dict.TryGetValue(keyName, out string actualValue)) { string msg = $"Missing key '{keyName}'. Keys = " + string.Join(", ", dict.Keys); Assert.True(false, msg); } if (expectedValue != null) { Assert.Equal(expectedValue, actualValue); } } private static void ValidateSdkVersion(ITelemetry telemetry, string prefix = null) { Assert.StartsWith($"{prefix}azurefunctions: ", telemetry.Context.GetInternalContext().SdkVersion); } private static string GetInvocationId(ISupportProperties telemetry) { telemetry.Properties.TryGetValue(LogConstants.InvocationIdKey, out string id); return id; } } }
48.577586
256
0.618146
[ "Apache-2.0", "MIT" ]
AtOMiCNebula/azure-functions-host
test/WebJobs.Script.Tests.Integration/ApplicationInsights/ApplicationInsightsEndToEndTestsBase.cs
22,542
C#
using System; namespace DishWasher { class Program { static void Main(string[] args) { int bottles = int.Parse(Console.ReadLine()); string command = Console.ReadLine(); int dishes = 0; int pans = 0; int inputCounter = 0; int vero = bottles * 750; int dishesVero = 0; int pansVero = 0; int veroNeeded = dishesVero + pansVero; while (command != "End") { inputCounter++; if (inputCounter == 3) { pans += int.Parse(command); inputCounter = 0; pansVero = pans * 15; } else { dishes += int.Parse(command); dishesVero = dishes * 5; } veroNeeded = dishesVero + pansVero; if (vero < veroNeeded) { Console.WriteLine($"Not enough detergent, {veroNeeded - vero} ml. more necessary!"); break; } command = Console.ReadLine(); } if (vero >= veroNeeded) { Console.WriteLine("Detergent was enough!"); Console.WriteLine($"{dishes} dishes and {pans} pots were washed."); Console.WriteLine($"Leftover detergent {vero - veroNeeded} ml."); } } } }
26.540984
104
0.399629
[ "MIT" ]
Rongusha/cShardStudy
ProgramingBasics/WhileLoopExersice/DishWasher/Program.cs
1,621
C#
using UncommonSense.CBreeze.Common; using UncommonSense.CBreeze.Core.Code.Variable; using UncommonSense.CBreeze.Core.Contracts; using UncommonSense.CBreeze.Core.Property; using UncommonSense.CBreeze.Core.Property.Enumeration; using UncommonSense.CBreeze.Core.Property.Implementation; namespace UncommonSense.CBreeze.Core.XmlPort { public class XmlPortFieldElementProperties : Properties { private NullableBooleanProperty autoCalcField = new NullableBooleanProperty("AutoCalcField"); private XmlPortNodeDataTypeProperty dataType = new XmlPortNodeDataTypeProperty("DataType"); private NullableBooleanProperty fieldValidate = new NullableBooleanProperty("FieldValidate"); private MaxOccursProperty maxOccurs = new MaxOccursProperty("MaxOccurs"); private MinOccursProperty minOccurs = new MinOccursProperty("MinOccurs"); #if NAV2016 private StringProperty namespacePrefix = new StringProperty("NamespacePrefix"); #endif private ScopedTriggerProperty onAfterAssignField = new ScopedTriggerProperty("OnAfterAssignField"); private ScopedTriggerProperty onBeforePassField = new ScopedTriggerProperty("OnBeforePassField"); private SourceFieldProperty sourceField = new SourceFieldProperty("SourceField"); #if NAV2013R2 private NullableBooleanProperty unbound = new NullableBooleanProperty("Unbound"); #endif private NullableIntegerProperty width = new NullableIntegerProperty("Width"); internal XmlPortFieldElementProperties(XmlPortFieldElement xmlPortFieldElement) { XmlPortFieldElement = xmlPortFieldElement; innerList.Add(dataType); innerList.Add(fieldValidate); innerList.Add(autoCalcField); innerList.Add(sourceField); #if NAV2016 innerList.Add(namespacePrefix); #endif innerList.Add(minOccurs); innerList.Add(maxOccurs); #if NAV2013R2 innerList.Add(unbound); #endif innerList.Add(onAfterAssignField); innerList.Add(onBeforePassField); innerList.Add(width); } public XmlPortFieldElement XmlPortFieldElement { get; protected set; } public override INode ParentNode => XmlPortFieldElement; public bool? AutoCalcField { get { return this.autoCalcField.Value; } set { this.autoCalcField.Value = value; } } public XmlPortNodeDataType? DataType { get { return this.dataType.Value; } set { this.dataType.Value = value; } } public bool? FieldValidate { get { return this.fieldValidate.Value; } set { this.fieldValidate.Value = value; } } public MaxOccurs? MaxOccurs { get { return this.maxOccurs.Value; } set { this.maxOccurs.Value = value; } } public MinOccurs? MinOccurs { get { return this.minOccurs.Value; } set { this.minOccurs.Value = value; } } #if NAV2016 public string NamespacePrefix { get { return this.namespacePrefix.Value; } set { this.namespacePrefix.Value = value; } } #endif public Trigger OnAfterAssignField { get { return this.onAfterAssignField.Value; } } public Trigger OnBeforePassField { get { return this.onBeforePassField.Value; } } public SourceField SourceField { get { return this.sourceField.Value; } } #if NAV2013R2 public bool? Unbound { get { return this.unbound.Value; } set { this.unbound.Value = value; } } #endif public int? Width { get { return this.width.Value; } set { this.width.Value = value; } } } }
26.325843
107
0.54012
[ "MIT" ]
FSharpCSharp/UncommonSense.CBreeze
CBreeze/UncommonSense.CBreeze.Core/XmlPort/XmlPortFieldElementProperties.cs
4,686
C#
// Copyright (c) Dolittle. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Linq; using System.Reflection; using Dolittle.Runtime.Assemblies; using Dolittle.Runtime.Assemblies.Rules; using Dolittle.Runtime.Collections; using Microsoft.Extensions.Logging; using Dolittle.Runtime.Types; namespace Dolittle.Runtime.Booting.Stages { /// <summary> /// Represents the <see cref="BootStage.Discovery"/> stage of booting. /// </summary> public class Discovery : ICanPerformBootStage<DiscoverySettings> { /// <inheritdoc/> public BootStage BootStage => BootStage.Discovery; /// <inheritdoc/> public void Perform(DiscoverySettings settings, IBootStageBuilder builder) { var entryAssembly = builder.GetAssociation<Assembly>(WellKnownAssociations.EntryAssembly); var loggerFactory = builder.GetAssociation<ILoggerFactory>(WellKnownAssociations.LoggerFactory); var logger = loggerFactory.CreateLogger<Discovery>(); logger.LogDebug(" Discovery"); var assemblies = Assemblies.Bootstrap.Boot.Start(logger, entryAssembly, settings.AssemblyProvider, _ => { if (settings.IncludeAssembliesStartWith?.Count() > 0) { settings.IncludeAssembliesStartWith.ForEach(name => logger.LogTrace("Including assemblies starting with '{name}'", name)); _.ExceptAssembliesStartingWith(settings.IncludeAssembliesStartWith.ToArray()); } }); logger.LogDebug(" Set up type system for discovery"); var typeFinder = Types.Bootstrap.Boot.Start(assemblies, logger, entryAssembly); logger.LogDebug(" Type system ready"); builder.Bindings.Bind<IAssemblies>().To(assemblies); builder.Bindings.Bind<ITypeFinder>().To(typeFinder); builder.Associate(WellKnownAssociations.Assemblies, assemblies); builder.Associate(WellKnownAssociations.TypeFinder, typeFinder); } } }
43.693878
142
0.677254
[ "MIT" ]
dolittle/Runtime
Source/Booting/Stages/04-Discovery/Discovery.cs
2,141
C#
using System.Text.RegularExpressions; using JetBrains.Annotations; using static BinaryFog.NameParser.RegexNameComponents; using static BinaryFog.NameParser.NameComponentSets; namespace BinaryFog.NameParser.Patterns { [UsedImplicitly] public class FirstIrishLastPattern : IFullNamePattern { private static readonly Regex Rx = new Regex( @"^" + First + Space + @"(?<irishPrefix>O'|Mc|Mac)" + Last + @"$", CommonPatternRegexOptions); public ParsedFullName Parse(string rawName) { if (rawName == null) return null; var match = Rx!.Match(rawName); if (!match.Success) return null; var firstName = match.Groups["first"].Value; var irishPrefix = match.Groups["irishPrefix"].Value; var lastPart = match.Groups["last"].Value; var lastName = $"{irishPrefix}{lastPart}"; var scoreMod = 0; ModifyScoreExpectedFirstName(ref scoreMod, firstName); ModifyScoreExpectedLastName(ref scoreMod, lastPart); var pn = new ParsedFullName { FirstName = firstName, LastName = lastName, DisplayName = $"{firstName} {lastName}", Score = 300 + scoreMod }; return pn; } } }
30.756757
69
0.702988
[ "Apache-2.0" ]
JaminQuimby/NameParser
BinaryFog.NameParser/Patterns/FirstIrishLastPattern.cs
1,140
C#
using System; using System.Diagnostics; using System.Numerics; namespace Nethermind.Decompose.Numerics { public class UInt32MontgomeryReduction : IReductionAlgorithm<uint> { private class Reducer : Reducer<UInt32MontgomeryReduction, uint> { private class Residue : Residue<Reducer, uint, uint> { public override bool IsZero { get { return r == 0; } } public override bool IsOne { get { if (reducer.oneRep == 0) reducer.oneRep = reducer.Reduce(1, reducer.rSquaredModN); return r == reducer.oneRep; } } public Residue(Reducer reducer) : base(reducer) { } public Residue(Reducer reducer, uint x) : base(reducer) { Set(x); } public override IResidue<uint> Set(uint x) { r = reducer.Reduce(x % reducer.modulus, reducer.rSquaredModN); return this; } public override IResidue<uint> Set(IResidue<uint> x) { r = GetRep(x); return this; } public override IResidue<uint> Copy() { var residue = new Residue(reducer); residue.r = r; return residue; } public override IResidue<uint> Multiply(IResidue<uint> x) { r = reducer.Reduce(r, GetRep(x)); return this; } public override IResidue<uint> Power(uint exponent) { if (exponent == 0) return One(); var value = r; var result = r; --exponent; while (exponent != 0) { if ((exponent & 1) != 0) result = reducer.Reduce(result, value); if (exponent != 1) value = reducer.Reduce(value, value); exponent >>= 1; } r = result; return this; } private IResidue<uint> One() { if (reducer.oneRep == 0) reducer.oneRep = reducer.Reduce(1, reducer.rSquaredModN); r = reducer.oneRep; return this; } public override IResidue<uint> Add(IResidue<uint> x) { r = IntegerMath.ModularSum(r, GetRep(x), reducer.modulus); return this; } public override IResidue<uint> Subtract(IResidue<uint> x) { r = IntegerMath.ModularDifference(r, GetRep(x), reducer.modulus); return this; } public override uint Value { get { return reducer.Reduce(r, 1); } } } private uint k0; private uint rSquaredModN; private uint oneRep; public Reducer(UInt32MontgomeryReduction reduction, uint modulus) : base(reduction, modulus) { if ((modulus & 1) == 0) throw new InvalidOperationException("not relatively prime"); var nInv = IntegerMath.ModularInversePowerOfTwoModulus(modulus, 32); k0 = IntegerMath.TwosComplement(nInv); var rModN = uint.MaxValue % modulus + 1; rSquaredModN = IntegerMath.ModularProduct(rModN, rModN, modulus); } public override IResidue<uint> ToResidue(uint x) { return new Residue(this, x); } private uint Reduce(uint u, uint v) { Debug.Assert(MontgomeryHelper.Reduce(u, v, modulus, k0) < modulus); return MontgomeryHelper.Reduce(u, v, modulus, k0); } } public IReducer<uint> GetReducer(uint modulus) { return new Reducer(this, modulus); } } }
32.884892
85
0.428571
[ "Apache-2.0" ]
NethermindEth/Dirichlet
Nethermind.Decompose.Numerics/Reduction/Performance/UInt32MontgomeryReduction.cs
4,573
C#
using System.Runtime.CompilerServices; namespace NodeJS.CryptoModule { [Imported] [ModuleName("crypto")] [IgnoreNamespace] public class Hmac { private Hmac() {} public void Update(string data) {} public string Digest() { return null; } public string Digest(Encoding encoding) { return null; } } }
20.8
58
0.717949
[ "Apache-2.0" ]
n9/SaltarelleNodeJS
NodeJS/CryptoModule/Hmac.cs
312
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Corvalius.Identity.RavenDB { /// <summary> /// The default implementation of <see cref="IdentityRole{TKey}"/> which uses a string as the primary key. /// </summary> public class IdentityRole : IdentityRole<string> { /// <summary> /// Initializes a new instance of <see cref="IdentityRole"/>. /// </summary> /// <remarks> /// The Id property is initialized to from a new GUID string value. /// </remarks> public IdentityRole() { Id = Guid.NewGuid().ToString(); } /// <summary> /// Initializes a new instance of <see cref="IdentityRole"/>. /// </summary> /// <param name="roleName">The role name.</param> /// <remarks> /// The Id property is initialized to from a new GUID string value. /// </remarks> public IdentityRole(string roleName) : this() { Name = roleName; } } /// <summary> /// Represents a role in the identity system /// </summary> /// <typeparam name="TKey">The type used for the primary key for the role.</typeparam> public class IdentityRole<TKey> where TKey : IEquatable<TKey> { /// <summary> /// Initializes a new instance of <see cref="IdentityRole{TKey}"/>. /// </summary> public IdentityRole() { } /// <summary> /// Initializes a new instance of <see cref="IdentityRole{TKey}"/>. /// </summary> /// <param name="roleName">The role name.</param> public IdentityRole(string roleName) : this() { Name = roleName; } /// <summary> /// Navigation property for claims in this role. /// </summary> public virtual ICollection<IdentityRoleClaim> Claims { get; internal set; } = new List<IdentityRoleClaim>(); /// <summary> /// Gets or sets the primary key for this role. /// </summary> public virtual TKey Id { get; set; } /// <summary> /// Gets or sets the name for this role. /// </summary> public virtual string Name { get; set; } /// <summary> /// Gets or sets the normalized name for this role. /// </summary> public virtual string NormalizedName { get; set; } /// <summary> /// Returns the name of the role. /// </summary> /// <returns>The name of the role.</returns> public override string ToString() { return Name; } public static string CreateId ( string normalizedName ) { return $"roles/{normalizedName}"; } } }
30.543478
116
0.549822
[ "Apache-2.0" ]
Corvalius/Membership-ravendb
Source/Corvalius.Identity.RavenDB/IdentityRole.cs
2,812
C#
// <auto-generated> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/bigquery/storage/v1/table.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 Google.Cloud.BigQuery.Storage.V1 { /// <summary>Holder for reflection information generated from google/cloud/bigquery/storage/v1/table.proto</summary> public static partial class TableReflection { #region Descriptor /// <summary>File descriptor for google/cloud/bigquery/storage/v1/table.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static TableReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Cixnb29nbGUvY2xvdWQvYmlncXVlcnkvc3RvcmFnZS92MS90YWJsZS5wcm90", "bxIgZ29vZ2xlLmNsb3VkLmJpZ3F1ZXJ5LnN0b3JhZ2UudjEaH2dvb2dsZS9h", "cGkvZmllbGRfYmVoYXZpb3IucHJvdG8iUQoLVGFibGVTY2hlbWESQgoGZmll", "bGRzGAEgAygLMjIuZ29vZ2xlLmNsb3VkLmJpZ3F1ZXJ5LnN0b3JhZ2UudjEu", "VGFibGVGaWVsZFNjaGVtYSKFBQoQVGFibGVGaWVsZFNjaGVtYRIRCgRuYW1l", "GAEgASgJQgPgQQISSgoEdHlwZRgCIAEoDjI3Lmdvb2dsZS5jbG91ZC5iaWdx", "dWVyeS5zdG9yYWdlLnYxLlRhYmxlRmllbGRTY2hlbWEuVHlwZUID4EECEkoK", "BG1vZGUYAyABKA4yNy5nb29nbGUuY2xvdWQuYmlncXVlcnkuc3RvcmFnZS52", "MS5UYWJsZUZpZWxkU2NoZW1hLk1vZGVCA+BBARJHCgZmaWVsZHMYBCADKAsy", "Mi5nb29nbGUuY2xvdWQuYmlncXVlcnkuc3RvcmFnZS52MS5UYWJsZUZpZWxk", "U2NoZW1hQgPgQQESGAoLZGVzY3JpcHRpb24YBiABKAlCA+BBARIXCgptYXhf", "bGVuZ3RoGAcgASgDQgPgQQESFgoJcHJlY2lzaW9uGAggASgDQgPgQQESEgoF", "c2NhbGUYCSABKANCA+BBASLVAQoEVHlwZRIUChBUWVBFX1VOU1BFQ0lGSUVE", "EAASCgoGU1RSSU5HEAESCQoFSU5UNjQQAhIKCgZET1VCTEUQAxIKCgZTVFJV", "Q1QQBBIJCgVCWVRFUxAFEggKBEJPT0wQBhINCglUSU1FU1RBTVAQBxIICgRE", "QVRFEAgSCAoEVElNRRAJEgwKCERBVEVUSU1FEAoSDQoJR0VPR1JBUEhZEAsS", "CwoHTlVNRVJJQxAMEg4KCkJJR05VTUVSSUMQDRIMCghJTlRFUlZBTBAOEggK", "BEpTT04QDyJGCgRNb2RlEhQKEE1PREVfVU5TUEVDSUZJRUQQABIMCghOVUxM", "QUJMRRABEgwKCFJFUVVJUkVEEAISDAoIUkVQRUFURUQQA0LDAQokY29tLmdv", "b2dsZS5jbG91ZC5iaWdxdWVyeS5zdG9yYWdlLnYxQgpUYWJsZVByb3RvUAFa", "R2dvb2dsZS5nb2xhbmcub3JnL2dlbnByb3RvL2dvb2dsZWFwaXMvY2xvdWQv", "YmlncXVlcnkvc3RvcmFnZS92MTtzdG9yYWdlqgIgR29vZ2xlLkNsb3VkLkJp", "Z1F1ZXJ5LlN0b3JhZ2UuVjHKAiBHb29nbGVcQ2xvdWRcQmlnUXVlcnlcU3Rv", "cmFnZVxWMWIGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Google.Api.FieldBehaviorReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.BigQuery.Storage.V1.TableSchema), global::Google.Cloud.BigQuery.Storage.V1.TableSchema.Parser, new[]{ "Fields" }, null, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.BigQuery.Storage.V1.TableFieldSchema), global::Google.Cloud.BigQuery.Storage.V1.TableFieldSchema.Parser, new[]{ "Name", "Type", "Mode", "Fields", "Description", "MaxLength", "Precision", "Scale" }, null, new[]{ typeof(global::Google.Cloud.BigQuery.Storage.V1.TableFieldSchema.Types.Type), typeof(global::Google.Cloud.BigQuery.Storage.V1.TableFieldSchema.Types.Mode) }, null, null) })); } #endregion } #region Messages /// <summary> /// Schema of a table. /// </summary> public sealed partial class TableSchema : pb::IMessage<TableSchema> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<TableSchema> _parser = new pb::MessageParser<TableSchema>(() => new TableSchema()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<TableSchema> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.BigQuery.Storage.V1.TableReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public TableSchema() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public TableSchema(TableSchema other) : this() { fields_ = other.fields_.Clone(); _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public TableSchema Clone() { return new TableSchema(this); } /// <summary>Field number for the "fields" field.</summary> public const int FieldsFieldNumber = 1; private static readonly pb::FieldCodec<global::Google.Cloud.BigQuery.Storage.V1.TableFieldSchema> _repeated_fields_codec = pb::FieldCodec.ForMessage(10, global::Google.Cloud.BigQuery.Storage.V1.TableFieldSchema.Parser); private readonly pbc::RepeatedField<global::Google.Cloud.BigQuery.Storage.V1.TableFieldSchema> fields_ = new pbc::RepeatedField<global::Google.Cloud.BigQuery.Storage.V1.TableFieldSchema>(); /// <summary> /// Describes the fields in a table. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::Google.Cloud.BigQuery.Storage.V1.TableFieldSchema> Fields { get { return fields_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as TableSchema); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(TableSchema other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if(!fields_.Equals(other.fields_)) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; hash ^= fields_.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 !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else fields_.WriteTo(output, _repeated_fields_codec); if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { fields_.WriteTo(ref output, _repeated_fields_codec); if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; size += fields_.CalculateSize(_repeated_fields_codec); if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(TableSchema other) { if (other == null) { return; } fields_.Add(other.fields_); _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { fields_.AddEntriesFrom(input, _repeated_fields_codec); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { fields_.AddEntriesFrom(ref input, _repeated_fields_codec); break; } } } } #endif } /// <summary> /// TableFieldSchema defines a single field/column within a table schema. /// </summary> public sealed partial class TableFieldSchema : pb::IMessage<TableFieldSchema> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<TableFieldSchema> _parser = new pb::MessageParser<TableFieldSchema>(() => new TableFieldSchema()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<TableFieldSchema> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.BigQuery.Storage.V1.TableReflection.Descriptor.MessageTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public TableFieldSchema() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public TableFieldSchema(TableFieldSchema other) : this() { name_ = other.name_; type_ = other.type_; mode_ = other.mode_; fields_ = other.fields_.Clone(); description_ = other.description_; maxLength_ = other.maxLength_; precision_ = other.precision_; scale_ = other.scale_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public TableFieldSchema Clone() { return new TableFieldSchema(this); } /// <summary>Field number for the "name" field.</summary> public const int NameFieldNumber = 1; private string name_ = ""; /// <summary> /// Required. The field name. The name must contain only letters (a-z, A-Z), /// numbers (0-9), or underscores (_), and must start with a letter or /// underscore. The maximum length is 128 characters. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Name { get { return name_; } set { name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "type" field.</summary> public const int TypeFieldNumber = 2; private global::Google.Cloud.BigQuery.Storage.V1.TableFieldSchema.Types.Type type_ = global::Google.Cloud.BigQuery.Storage.V1.TableFieldSchema.Types.Type.Unspecified; /// <summary> /// Required. The field data type. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Cloud.BigQuery.Storage.V1.TableFieldSchema.Types.Type Type { get { return type_; } set { type_ = value; } } /// <summary>Field number for the "mode" field.</summary> public const int ModeFieldNumber = 3; private global::Google.Cloud.BigQuery.Storage.V1.TableFieldSchema.Types.Mode mode_ = global::Google.Cloud.BigQuery.Storage.V1.TableFieldSchema.Types.Mode.Unspecified; /// <summary> /// Optional. The field mode. The default value is NULLABLE. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Cloud.BigQuery.Storage.V1.TableFieldSchema.Types.Mode Mode { get { return mode_; } set { mode_ = value; } } /// <summary>Field number for the "fields" field.</summary> public const int FieldsFieldNumber = 4; private static readonly pb::FieldCodec<global::Google.Cloud.BigQuery.Storage.V1.TableFieldSchema> _repeated_fields_codec = pb::FieldCodec.ForMessage(34, global::Google.Cloud.BigQuery.Storage.V1.TableFieldSchema.Parser); private readonly pbc::RepeatedField<global::Google.Cloud.BigQuery.Storage.V1.TableFieldSchema> fields_ = new pbc::RepeatedField<global::Google.Cloud.BigQuery.Storage.V1.TableFieldSchema>(); /// <summary> /// Optional. Describes the nested schema fields if the type property is set to STRUCT. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::Google.Cloud.BigQuery.Storage.V1.TableFieldSchema> Fields { get { return fields_; } } /// <summary>Field number for the "description" field.</summary> public const int DescriptionFieldNumber = 6; private string description_ = ""; /// <summary> /// Optional. The field description. The maximum length is 1,024 characters. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Description { get { return description_; } set { description_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "max_length" field.</summary> public const int MaxLengthFieldNumber = 7; private long maxLength_; /// <summary> /// Optional. Maximum length of values of this field for STRINGS or BYTES. /// /// If max_length is not specified, no maximum length constraint is imposed /// on this field. /// /// If type = "STRING", then max_length represents the maximum UTF-8 /// length of strings in this field. /// /// If type = "BYTES", then max_length represents the maximum number of /// bytes in this field. /// /// It is invalid to set this field if type is not "STRING" or "BYTES". /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public long MaxLength { get { return maxLength_; } set { maxLength_ = value; } } /// <summary>Field number for the "precision" field.</summary> public const int PrecisionFieldNumber = 8; private long precision_; /// <summary> /// Optional. Precision (maximum number of total digits in base 10) and scale /// (maximum number of digits in the fractional part in base 10) constraints /// for values of this field for NUMERIC or BIGNUMERIC. /// /// It is invalid to set precision or scale if type is not "NUMERIC" or /// "BIGNUMERIC". /// /// If precision and scale are not specified, no value range constraint is /// imposed on this field insofar as values are permitted by the type. /// /// Values of this NUMERIC or BIGNUMERIC field must be in this range when: /// /// * Precision (P) and scale (S) are specified: /// [-10^(P-S) + 10^(-S), 10^(P-S) - 10^(-S)] /// * Precision (P) is specified but not scale (and thus scale is /// interpreted to be equal to zero): /// [-10^P + 1, 10^P - 1]. /// /// Acceptable values for precision and scale if both are specified: /// /// * If type = "NUMERIC": /// 1 &lt;= precision - scale &lt;= 29 and 0 &lt;= scale &lt;= 9. /// * If type = "BIGNUMERIC": /// 1 &lt;= precision - scale &lt;= 38 and 0 &lt;= scale &lt;= 38. /// /// Acceptable values for precision if only precision is specified but not /// scale (and thus scale is interpreted to be equal to zero): /// /// * If type = "NUMERIC": 1 &lt;= precision &lt;= 29. /// * If type = "BIGNUMERIC": 1 &lt;= precision &lt;= 38. /// /// If scale is specified but not precision, then it is invalid. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public long Precision { get { return precision_; } set { precision_ = value; } } /// <summary>Field number for the "scale" field.</summary> public const int ScaleFieldNumber = 9; private long scale_; /// <summary> /// Optional. See documentation for precision. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public long Scale { get { return scale_; } set { scale_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as TableFieldSchema); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(TableFieldSchema other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; if (Type != other.Type) return false; if (Mode != other.Mode) return false; if(!fields_.Equals(other.fields_)) return false; if (Description != other.Description) return false; if (MaxLength != other.MaxLength) return false; if (Precision != other.Precision) return false; if (Scale != other.Scale) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); if (Type != global::Google.Cloud.BigQuery.Storage.V1.TableFieldSchema.Types.Type.Unspecified) hash ^= Type.GetHashCode(); if (Mode != global::Google.Cloud.BigQuery.Storage.V1.TableFieldSchema.Types.Mode.Unspecified) hash ^= Mode.GetHashCode(); hash ^= fields_.GetHashCode(); if (Description.Length != 0) hash ^= Description.GetHashCode(); if (MaxLength != 0L) hash ^= MaxLength.GetHashCode(); if (Precision != 0L) hash ^= Precision.GetHashCode(); if (Scale != 0L) hash ^= Scale.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 !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } if (Type != global::Google.Cloud.BigQuery.Storage.V1.TableFieldSchema.Types.Type.Unspecified) { output.WriteRawTag(16); output.WriteEnum((int) Type); } if (Mode != global::Google.Cloud.BigQuery.Storage.V1.TableFieldSchema.Types.Mode.Unspecified) { output.WriteRawTag(24); output.WriteEnum((int) Mode); } fields_.WriteTo(output, _repeated_fields_codec); if (Description.Length != 0) { output.WriteRawTag(50); output.WriteString(Description); } if (MaxLength != 0L) { output.WriteRawTag(56); output.WriteInt64(MaxLength); } if (Precision != 0L) { output.WriteRawTag(64); output.WriteInt64(Precision); } if (Scale != 0L) { output.WriteRawTag(72); output.WriteInt64(Scale); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } if (Type != global::Google.Cloud.BigQuery.Storage.V1.TableFieldSchema.Types.Type.Unspecified) { output.WriteRawTag(16); output.WriteEnum((int) Type); } if (Mode != global::Google.Cloud.BigQuery.Storage.V1.TableFieldSchema.Types.Mode.Unspecified) { output.WriteRawTag(24); output.WriteEnum((int) Mode); } fields_.WriteTo(ref output, _repeated_fields_codec); if (Description.Length != 0) { output.WriteRawTag(50); output.WriteString(Description); } if (MaxLength != 0L) { output.WriteRawTag(56); output.WriteInt64(MaxLength); } if (Precision != 0L) { output.WriteRawTag(64); output.WriteInt64(Precision); } if (Scale != 0L) { output.WriteRawTag(72); output.WriteInt64(Scale); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } if (Type != global::Google.Cloud.BigQuery.Storage.V1.TableFieldSchema.Types.Type.Unspecified) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Type); } if (Mode != global::Google.Cloud.BigQuery.Storage.V1.TableFieldSchema.Types.Mode.Unspecified) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Mode); } size += fields_.CalculateSize(_repeated_fields_codec); if (Description.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Description); } if (MaxLength != 0L) { size += 1 + pb::CodedOutputStream.ComputeInt64Size(MaxLength); } if (Precision != 0L) { size += 1 + pb::CodedOutputStream.ComputeInt64Size(Precision); } if (Scale != 0L) { size += 1 + pb::CodedOutputStream.ComputeInt64Size(Scale); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(TableFieldSchema other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } if (other.Type != global::Google.Cloud.BigQuery.Storage.V1.TableFieldSchema.Types.Type.Unspecified) { Type = other.Type; } if (other.Mode != global::Google.Cloud.BigQuery.Storage.V1.TableFieldSchema.Types.Mode.Unspecified) { Mode = other.Mode; } fields_.Add(other.fields_); if (other.Description.Length != 0) { Description = other.Description; } if (other.MaxLength != 0L) { MaxLength = other.MaxLength; } if (other.Precision != 0L) { Precision = other.Precision; } if (other.Scale != 0L) { Scale = other.Scale; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { Name = input.ReadString(); break; } case 16: { Type = (global::Google.Cloud.BigQuery.Storage.V1.TableFieldSchema.Types.Type) input.ReadEnum(); break; } case 24: { Mode = (global::Google.Cloud.BigQuery.Storage.V1.TableFieldSchema.Types.Mode) input.ReadEnum(); break; } case 34: { fields_.AddEntriesFrom(input, _repeated_fields_codec); break; } case 50: { Description = input.ReadString(); break; } case 56: { MaxLength = input.ReadInt64(); break; } case 64: { Precision = input.ReadInt64(); break; } case 72: { Scale = input.ReadInt64(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { Name = input.ReadString(); break; } case 16: { Type = (global::Google.Cloud.BigQuery.Storage.V1.TableFieldSchema.Types.Type) input.ReadEnum(); break; } case 24: { Mode = (global::Google.Cloud.BigQuery.Storage.V1.TableFieldSchema.Types.Mode) input.ReadEnum(); break; } case 34: { fields_.AddEntriesFrom(ref input, _repeated_fields_codec); break; } case 50: { Description = input.ReadString(); break; } case 56: { MaxLength = input.ReadInt64(); break; } case 64: { Precision = input.ReadInt64(); break; } case 72: { Scale = input.ReadInt64(); break; } } } } #endif #region Nested types /// <summary>Container for nested types declared in the TableFieldSchema message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static partial class Types { public enum Type { /// <summary> /// Illegal value /// </summary> [pbr::OriginalName("TYPE_UNSPECIFIED")] Unspecified = 0, /// <summary> /// 64K, UTF8 /// </summary> [pbr::OriginalName("STRING")] String = 1, /// <summary> /// 64-bit signed /// </summary> [pbr::OriginalName("INT64")] Int64 = 2, /// <summary> /// 64-bit IEEE floating point /// </summary> [pbr::OriginalName("DOUBLE")] Double = 3, /// <summary> /// Aggregate type /// </summary> [pbr::OriginalName("STRUCT")] Struct = 4, /// <summary> /// 64K, Binary /// </summary> [pbr::OriginalName("BYTES")] Bytes = 5, /// <summary> /// 2-valued /// </summary> [pbr::OriginalName("BOOL")] Bool = 6, /// <summary> /// 64-bit signed usec since UTC epoch /// </summary> [pbr::OriginalName("TIMESTAMP")] Timestamp = 7, /// <summary> /// Civil date - Year, Month, Day /// </summary> [pbr::OriginalName("DATE")] Date = 8, /// <summary> /// Civil time - Hour, Minute, Second, Microseconds /// </summary> [pbr::OriginalName("TIME")] Time = 9, /// <summary> /// Combination of civil date and civil time /// </summary> [pbr::OriginalName("DATETIME")] Datetime = 10, /// <summary> /// Geography object /// </summary> [pbr::OriginalName("GEOGRAPHY")] Geography = 11, /// <summary> /// Numeric value /// </summary> [pbr::OriginalName("NUMERIC")] Numeric = 12, /// <summary> /// BigNumeric value /// </summary> [pbr::OriginalName("BIGNUMERIC")] Bignumeric = 13, /// <summary> /// Interval /// </summary> [pbr::OriginalName("INTERVAL")] Interval = 14, /// <summary> /// JSON, String /// </summary> [pbr::OriginalName("JSON")] Json = 15, } public enum Mode { /// <summary> /// Illegal value /// </summary> [pbr::OriginalName("MODE_UNSPECIFIED")] Unspecified = 0, [pbr::OriginalName("NULLABLE")] Nullable = 1, [pbr::OriginalName("REQUIRED")] Required = 2, [pbr::OriginalName("REPEATED")] Repeated = 3, } } #endregion } #endregion } #endregion Designer generated code
36.855362
450
0.640706
[ "Apache-2.0" ]
Mattlk13/google-cloud-dotnet
apis/Google.Cloud.BigQuery.Storage.V1/Google.Cloud.BigQuery.Storage.V1/Table.g.cs
29,558
C#
using System; namespace ConsoleApp1.Model { internal class KeyAttribute : Attribute { } }
12.875
43
0.679612
[ "MIT" ]
WillHomS/Hom2021
ConsoleApp1/Model/KeyAttribute.cs
105
C#
using System; using System.IO; using ICSharpCode.SharpZipLib.Checksum; class Cmd_Checksum { static void ShowHelp() { Console.Error.WriteLine("Compress or uncompress FILEs (by default, compress FILES in-place)."); Console.Error.WriteLine("Version {0} using SharpZipLib {1}", typeof(Cmd_Checksum).Assembly.GetName().Version, typeof(IChecksum).Assembly.GetName().Version); Console.Error.WriteLine(""); Console.Error.WriteLine("Mandatory arguments to long options are mandatory for short options too."); Console.Error.WriteLine(""); Console.Error.WriteLine(" -a, --adler decompress"); Console.Error.WriteLine(" -b, --bzip2 give this help"); Console.Error.WriteLine(" -c, --crc32 compress"); Console.Error.WriteLine(" -1, --fast compress faster"); Console.Error.WriteLine(" -9, --best compress better"); } #region Instance Fields private static Command command_ = Command.Nothing; private static string file_; #endregion #region Command parsing enum Command { Nothing, Help, Adler, BZip2, Crc32, Stop } class ArgumentParser { public ArgumentParser(string[] args) { foreach (string argument in args) { switch (argument) { case "-?": // for backwards compatibility case "-h": case "--help": SetCommand(Command.Help); break; case "--adler32": SetCommand(Command.Adler); break; case "--bzip2": SetCommand(Command.BZip2); break; case "--crc32": SetCommand(Command.Crc32); break; default: if (argument[0] == '-') { Console.Error.WriteLine("Unknown argument {0}", argument); command_ = Command.Stop; } else if (file_ == null) { file_ = argument; if (!System.IO.File.Exists(file_)) { Console.Error.WriteLine("File not found '{0}'", file_); command_ = Command.Stop; } } else { Console.Error.WriteLine("File has already been specified"); command_ = Command.Stop; } break; } } if (command_ == Command.Nothing) { if (file_ == null) { command_ = Command.Help; } else { command_ = Command.Crc32; } } } void SetCommand(Command command) { if ((command_ != Command.Nothing) && (command_ != Command.Stop)) { Console.Error.WriteLine("Command already specified"); command_ = Command.Stop; } else { command_ = command; } } public string Source { get { return file_; } } public Command Command { get { return command_; } } } #endregion public static int Main(string[] args) { if (args.Length == 0) { ShowHelp(); return 1; } var parser = new ArgumentParser(args); if (!File.Exists(file_)) { Console.Error.WriteLine("Cannot find file {0}", file_); ShowHelp(); return 1; } using (FileStream checksumStream = File.OpenRead(file_)) { byte[] buffer = new byte[4096]; int bytesRead; switch (parser.Command) { case Command.Help: ShowHelp(); break; case Command.Crc32: var currentCrc = new Crc32(); while ((bytesRead = checksumStream.Read(buffer, 0, buffer.Length)) > 0) { currentCrc.Update(buffer, 0, bytesRead); } Console.WriteLine("CRC32 for {0} is 0x{1:X8}", args[0], currentCrc.Value); break; case Command.BZip2: var currentBZip2Crc = new BZip2Crc(); while ((bytesRead = checksumStream.Read(buffer, 0, buffer.Length)) > 0) { currentBZip2Crc.Update(buffer, 0, bytesRead); } Console.WriteLine("BZip2CRC32 for {0} is 0x{1:X8}", args[0], currentBZip2Crc.Value); break; case Command.Adler: var currentAdler = new Adler32(); while ((bytesRead = checksumStream.Read(buffer, 0, buffer.Length)) > 0) { currentAdler.Update(buffer, 0, bytesRead); } Console.WriteLine("Adler32 for {0} is 0x{1:X8}", args[0], currentAdler.Value); break; } } return 0; } }
24.546584
102
0.624747
[ "MIT" ]
0patch/SharpZipLib
samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_Checksum/Cmd_Checksum.cs
3,952
C#
// // System.Collections.Generic.List // // Authors: // Ben Maurer (bmaurer@ximian.com) // Martin Baulig (martin@ximian.com) // Carlos Alberto Cortez (calberto.cortez@gmail.com) // David Waite (mass@akuma.org) // Marek Safar (marek.safar@gmail.com) // // Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com) // Copyright (C) 2005 David Waite // Copyright (C) 2011,2012 Xamarin, Inc (http://www.xamarin.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System.Collections.ObjectModel; using System.Runtime.InteropServices; using System.Diagnostics; using System.Runtime.CompilerServices; namespace System.Collections.Generic { [Serializable] [DebuggerDisplay ("Count={Count}")] [DebuggerTypeProxy (typeof (CollectionDebuggerView<>))] public class List<T> : IList<T>, IList #if NET_4_5 , IReadOnlyList<T> #endif { T [] _items; int _size; int _version; const int DefaultCapacity = 4; public List () { _items = EmptyArray<T>.Value; } public List (IEnumerable <T> collection) { if (collection == null) throw new ArgumentNullException ("collection"); // initialize to needed size (if determinable) ICollection <T> c = collection as ICollection <T>; if (c == null) { _items = EmptyArray<T>.Value;; AddEnumerable (collection); } else { _size = c.Count; _items = new T [_size]; c.CopyTo (_items, 0); } } public List (int capacity) { if (capacity < 0) throw new ArgumentOutOfRangeException ("capacity"); _items = new T [capacity]; } internal List (T [] data, int size) { _items = data; _size = size; } public void Add (T item) { // If we check to see if we need to grow before trying to grow // we can speed things up by 25% if (_size == _items.Length) GrowIfNeeded (1); _items [_size++] = item; _version++; } void GrowIfNeeded (int newCount) { int minimumSize = _size + newCount; if (minimumSize > _items.Length) Capacity = Math.Max (Math.Max (Capacity * 2, DefaultCapacity), minimumSize); } void CheckRange (int idx, int count) { if (idx < 0) throw new ArgumentOutOfRangeException ("index"); if (count < 0) throw new ArgumentOutOfRangeException ("count"); if ((uint) idx + (uint) count > (uint) _size) throw new ArgumentException ("index and count exceed length of list"); } void CheckRangeOutOfRange (int idx, int count) { if (idx < 0) throw new ArgumentOutOfRangeException ("index"); if (count < 0) throw new ArgumentOutOfRangeException ("count"); if ((uint) idx + (uint) count > (uint) _size) throw new ArgumentOutOfRangeException ("index and count exceed length of list"); } void AddCollection (ICollection <T> collection) { int collectionCount = collection.Count; if (collectionCount == 0) return; GrowIfNeeded (collectionCount); collection.CopyTo (_items, _size); _size += collectionCount; } void AddEnumerable (IEnumerable <T> enumerable) { foreach (T t in enumerable) { Add (t); } } public void AddRange (IEnumerable <T> collection) { if (collection == null) throw new ArgumentNullException ("collection"); ICollection <T> c = collection as ICollection <T>; if (c != null) AddCollection (c); else AddEnumerable (collection); _version++; } public ReadOnlyCollection <T> AsReadOnly () { return new ReadOnlyCollection <T> (this); } public int BinarySearch (T item) { return Array.BinarySearch <T> (_items, 0, _size, item); } public int BinarySearch (T item, IComparer <T> comparer) { return Array.BinarySearch <T> (_items, 0, _size, item, comparer); } public int BinarySearch (int index, int count, T item, IComparer <T> comparer) { CheckRange (index, count); return Array.BinarySearch <T> (_items, index, count, item, comparer); } public void Clear () { Array.Clear (_items, 0, _items.Length); _size = 0; _version++; } public bool Contains (T item) { return Array.IndexOf<T>(_items, item, 0, _size) != -1; } public List <TOutput> ConvertAll <TOutput> (Converter <T, TOutput> converter) { if (converter == null) throw new ArgumentNullException ("converter"); List <TOutput> u = new List <TOutput> (_size); for (int i = 0; i < _size; i++) u._items[i] = converter(_items[i]); u._size = _size; return u; } public void CopyTo (T [] array) { Array.Copy (_items, 0, array, 0, _size); } public void CopyTo (T [] array, int arrayIndex) { Array.Copy (_items, 0, array, arrayIndex, _size); } public void CopyTo (int index, T [] array, int arrayIndex, int count) { CheckRange (index, count); Array.Copy (_items, index, array, arrayIndex, count); } public bool Exists (Predicate <T> match) { CheckMatch(match); for (int i = 0; i < _size; i++) { var item = _items [i]; if (match (item)) return true; } return false; } public T Find (Predicate <T> match) { CheckMatch(match); for (int i = 0; i < _size; i++) { var item = _items [i]; if (match (item)) return item; } return default (T); } static void CheckMatch (Predicate <T> match) { if (match == null) throw new ArgumentNullException ("match"); } public List <T> FindAll (Predicate <T> match) { CheckMatch (match); #if !BRAILLE if (this._size <= 0x10000) // <= 8 * 1024 * 8 (8k in stack) return this.FindAllStackBits (match); else #endif return this.FindAllList (match); } #if !BRAILLE private List <T> FindAllStackBits (Predicate <T> match) { unsafe { uint *bits = stackalloc uint [(this._size / 32) + 1]; uint *ptr = bits; int found = 0; uint bitmask = 0x80000000; for (int i = 0; i < this._size; i++) { if (match (this._items [i])) { (*ptr) = (*ptr) | bitmask; found++; } bitmask = bitmask >> 1; if (bitmask == 0) { ptr++; bitmask = 0x80000000; } } T [] results = new T [found]; bitmask = 0x80000000; ptr = bits; int j = 0; for (int i = 0; i < this._size && j < found; i++) { if (((*ptr) & bitmask) == bitmask) results [j++] = this._items [i]; bitmask = bitmask >> 1; if (bitmask == 0) { ptr++; bitmask = 0x80000000; } } return new List <T> (results, found); } } #endif private List <T> FindAllList (Predicate <T> match) { List <T> results = new List <T> (); for (int i = 0; i < this._size; i++) if (match (this._items [i])) results.Add (this._items [i]); return results; } public int FindIndex (Predicate <T> match) { CheckMatch (match); return Array.GetIndex (_items, 0, _size, match); } public int FindIndex (int startIndex, Predicate <T> match) { CheckMatch (match); CheckStartIndex (startIndex); return Array.GetIndex (_items, startIndex, _size - startIndex, match); } public int FindIndex (int startIndex, int count, Predicate <T> match) { CheckMatch (match); CheckRangeOutOfRange (startIndex, count); return Array.GetIndex (_items, startIndex, count, match); } public T FindLast (Predicate <T> match) { CheckMatch (match); int i = Array.GetLastIndex (_items, 0, _size, match); return i == -1 ? default (T) : this [i]; } public int FindLastIndex (Predicate <T> match) { CheckMatch (match); return Array.GetLastIndex (_items, 0, _size, match); } public int FindLastIndex (int startIndex, Predicate <T> match) { CheckMatch (match); CheckStartIndex (startIndex); return Array.GetLastIndex (_items, 0, startIndex + 1, match); } public int FindLastIndex (int startIndex, int count, Predicate <T> match) { CheckMatch (match); CheckStartIndex (startIndex); if (count < 0) throw new ArgumentOutOfRangeException ("count"); if (startIndex - count + 1 < 0) throw new ArgumentOutOfRangeException ("count must refer to a location within the collection"); return Array.GetLastIndex (_items, startIndex - count + 1, count, match); } public void ForEach (Action <T> action) { if (action == null) throw new ArgumentNullException ("action"); for(int i=0; i < _size; i++) action(_items[i]); } public Enumerator GetEnumerator () { return new Enumerator (this); } public List <T> GetRange (int index, int count) { CheckRange (index, count); T [] tmpArray = new T [count]; Array.Copy (_items, index, tmpArray, 0, count); return new List <T> (tmpArray, count); } public int IndexOf (T item) { return Array.IndexOf<T> (_items, item, 0, _size); } public int IndexOf (T item, int index) { CheckIndex (index); return Array.IndexOf<T> (_items, item, index, _size - index); } public int IndexOf (T item, int index, int count) { if (index < 0) throw new ArgumentOutOfRangeException ("index"); if (count < 0) throw new ArgumentOutOfRangeException ("count"); if ((uint) index + (uint) count > (uint) _size) throw new ArgumentOutOfRangeException ("index and count exceed length of list"); return Array.IndexOf<T> (_items, item, index, count); } void Shift (int start, int delta) { if (delta < 0) start -= delta; if (start < _size) Array.Copy (_items, start, _items, start + delta, _size - start); _size += delta; if (delta < 0) Array.Clear (_items, _size, -delta); } void CheckIndex (int index) { if (index < 0 || (uint) index > (uint) _size) throw new ArgumentOutOfRangeException ("index"); } void CheckStartIndex (int index) { if (index < 0 || (uint) index > (uint) _size) throw new ArgumentOutOfRangeException ("startIndex"); } public void Insert (int index, T item) { CheckIndex (index); if (_size == _items.Length) GrowIfNeeded (1); Shift (index, 1); _items[index] = item; _version++; } public void InsertRange (int index, IEnumerable <T> collection) { if (collection == null) throw new ArgumentNullException ("collection"); CheckIndex (index); if (collection == this) { T[] buffer = new T[_size]; CopyTo (buffer, 0); GrowIfNeeded (_size); Shift (index, buffer.Length); Array.Copy (buffer, 0, _items, index, buffer.Length); } else { ICollection <T> c = collection as ICollection <T>; if (c != null) InsertCollection (index, c); else InsertEnumeration (index, collection); } _version++; } void InsertCollection (int index, ICollection <T> collection) { int collectionCount = collection.Count; GrowIfNeeded (collectionCount); Shift (index, collectionCount); collection.CopyTo (_items, index); } void InsertEnumeration (int index, IEnumerable <T> enumerable) { foreach (T t in enumerable) Insert (index++, t); } public int LastIndexOf (T item) { if (_size == 0) return -1; return Array.LastIndexOf<T> (_items, item, _size - 1, _size); } public int LastIndexOf (T item, int index) { CheckIndex (index); return Array.LastIndexOf<T> (_items, item, index, index + 1); } public int LastIndexOf (T item, int index, int count) { if (index < 0) throw new ArgumentOutOfRangeException ("index", index, "index is negative"); if (count < 0) throw new ArgumentOutOfRangeException ("count", count, "count is negative"); if (index - count + 1 < 0) throw new ArgumentOutOfRangeException ("cound", count, "count is too large"); return Array.LastIndexOf<T> (_items, item, index, count); } public bool Remove (T item) { int loc = IndexOf (item); if (loc != -1) RemoveAt (loc); return loc != -1; } public int RemoveAll (Predicate <T> match) { CheckMatch(match); int i = 0; int j = 0; // Find the first item to remove for (i = 0; i < _size; i++) if (match(_items[i])) break; if (i == _size) return 0; _version++; // Remove any additional items for (j = i + 1; j < _size; j++) { if (!match(_items[j])) _items[i++] = _items[j]; } if (j - i > 0) Array.Clear (_items, i, j - i); _size = i; return (j - i); } public void RemoveAt (int index) { if (index < 0 || (uint)index >= (uint)_size) throw new ArgumentOutOfRangeException("index"); Shift (index, -1); Array.Clear (_items, _size, 1); _version++; } public void RemoveRange (int index, int count) { CheckRange (index, count); if (count > 0) { Shift (index, -count); Array.Clear (_items, _size, count); _version++; } } public void Reverse () { Array.Reverse (_items, 0, _size); _version++; } public void Reverse (int index, int count) { CheckRange (index, count); Array.Reverse (_items, index, count); _version++; } public void Sort () { Array.Sort<T> (_items, 0, _size); _version++; } public void Sort (IComparer <T> comparer) { Array.Sort<T> (_items, 0, _size, comparer); _version++; } public void Sort (Comparison <T> comparison) { if (comparison == null) throw new ArgumentNullException ("comparison"); Array.SortImpl<T> (_items, _size, comparison); _version++; } public void Sort (int index, int count, IComparer <T> comparer) { CheckRange (index, count); Array.Sort<T> (_items, index, count, comparer); _version++; } public T [] ToArray () { T [] t = new T [_size]; Array.Copy (_items, t, _size); return t; } public void TrimExcess () { Capacity = _size; } public bool TrueForAll (Predicate <T> match) { CheckMatch (match); for (int i = 0; i < _size; i++) if (!match(_items[i])) return false; return true; } public int Capacity { get { return _items.Length; } set { if ((uint) value < (uint) _size) throw new ArgumentOutOfRangeException (); Array.Resize (ref _items, value); } } public int Count { get { return _size; } } public T this [int index] { [MethodImpl ((MethodImplOptions)256)] get { if ((uint) index >= (uint) _size) throw new ArgumentOutOfRangeException ("index"); return Array.UnsafeLoad (_items, index); } [MethodImpl ((MethodImplOptions)256)] set { if ((uint) index >= (uint) _size) throw new ArgumentOutOfRangeException ("index"); _items [index] = value; _version++; } } #region Interface implementations. IEnumerator <T> IEnumerable <T>.GetEnumerator () { return GetEnumerator (); } void ICollection.CopyTo (Array array, int arrayIndex) { if (array == null) throw new ArgumentNullException ("array"); if (array.Rank > 1 || array.GetLowerBound (0) != 0) throw new ArgumentException ("Array must be zero based and single dimentional", "array"); Array.Copy (_items, 0, array, arrayIndex, _size); } IEnumerator IEnumerable.GetEnumerator () { return GetEnumerator (); } int IList.Add (object item) { try { Add ((T) item); return _size - 1; } catch (NullReferenceException) { } catch (InvalidCastException) { } throw new ArgumentException ("item"); } bool IList.Contains (object item) { try { return Contains ((T) item); } catch (NullReferenceException) { } catch (InvalidCastException) { } return false; } int IList.IndexOf (object item) { try { return IndexOf ((T) item); } catch (NullReferenceException) { } catch (InvalidCastException) { } return -1; } void IList.Insert (int index, object item) { // We need to check this first because, even if the // item is null or not the correct type, we need to // return an ArgumentOutOfRange exception if the // index is out of range CheckIndex (index); try { Insert (index, (T) item); return; } catch (NullReferenceException) { } catch (InvalidCastException) { } throw new ArgumentException ("item"); } void IList.Remove (object item) { try { Remove ((T) item); return; } catch (NullReferenceException) { } catch (InvalidCastException) { } // Swallow the exception--if we can't cast to the // correct type then we've already "succeeded" in // removing the item from the List. } bool ICollection <T>.IsReadOnly { get { return false; } } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { return this; } } bool IList.IsFixedSize { get { return false; } } bool IList.IsReadOnly { get { return false; } } object IList.this [int index] { get { return this [index]; } set { try { this [index] = (T) value; return; } catch (NullReferenceException) { // can happen when 'value' is null and T is a valuetype } catch (InvalidCastException) { } throw new ArgumentException ("value"); } } #endregion [Serializable] public struct Enumerator : IEnumerator <T>, IDisposable { readonly List<T> l; int next; readonly int ver; T current; internal Enumerator (List <T> l) : this () { this.l = l; ver = l._version; } public void Dispose () { } public bool MoveNext () { var list = l; if ((uint)next < (uint)list._size && ver == list._version) { current = list._items [next++]; return true; } if (ver != l._version) throw new InvalidOperationException ("Collection was modified; enumeration operation may not execute."); next = -1; return false; } public T Current { get { return current; } } void IEnumerator.Reset () { if (ver != l._version) throw new InvalidOperationException ("Collection was modified; enumeration operation may not execute."); next = 0; current = default (T); } object IEnumerator.Current { get { if (ver != l._version) throw new InvalidOperationException ("Collection was modified; enumeration operation may not execute."); if (next <= 0) throw new InvalidOperationException (); return current; } } } } }
22.846063
110
0.621387
[ "Apache-2.0" ]
markusjohnsson/mono
mcs/class/corlib/System.Collections.Generic/List.cs
19,442
C#
// Instance generated by TankLibHelper.InstanceBuilder // ReSharper disable All namespace TankLib.STU.Types { [STUAttribute(0xE59D458B)] public class STU_E59D458B : STU_6440565A { [STUFieldAttribute(0xA53100D5, ReaderType = typeof(EmbeddedInstanceFieldReader))] public STUConfigVar m_A53100D5; } }
29.727273
89
0.749235
[ "MIT" ]
Mike111177/OWLib
TankLib/STU/Types/STU_E59D458B.cs
327
C#
using System; using System.Globalization; using System.Xml.Serialization; namespace FIM.MARE { public enum DateType { [XmlEnum(Name = "BestGuess")] BestGuess, [XmlEnum(Name = "DateTime")] DateTime, [XmlEnum(Name = "FileTimeUTC")] FileTimeUTC } public class FormatDate : Transform { [XmlAttribute("DateType")] [XmlTextAttribute()] public DateType DateType { get; set; } [XmlAttribute("FromFormat")] public string FromFormat { get; set; } [XmlAttribute("ToFormat")] public string ToFormat { get; set; } public override object Convert(object value) { if (value == null) return value; string returnValue = value.ToString(); Tracer.TraceInformation("formatdate-from {0} / {1}", DateType, returnValue); if (DateType.Equals(DateType.FileTimeUTC)) { returnValue = DateTime.FromFileTimeUtc(long.Parse(value.ToString())).ToString(ToFormat); return returnValue; } if (DateType.Equals(DateType.BestGuess)) { returnValue = DateTime.Parse(value.ToString(), CultureInfo.InvariantCulture).ToString(ToFormat); return returnValue; } if (DateType.Equals(DateType.DateTime)) { returnValue = DateTime.ParseExact(value.ToString(), FromFormat, CultureInfo.InvariantCulture).ToString(ToFormat); return returnValue; } return returnValue; } } }
31.901961
129
0.575907
[ "MIT" ]
ruliane/mare
fim.mare/Model/Transforms/Transform.FormatDate.cs
1,629
C#
using System; using System.Collections.Generic; namespace study { public partial class Request { public int Ordinal { get; set; } public string Content { get; set; } public string Ip { get; set; } public string Method { get; set; } public DateTime Time { get; set; } } }
21.666667
43
0.596923
[ "Apache-2.0" ]
FinchYang/study
teststudy/Request.cs
327
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace Scene_Maker.MVVM.View { /// <summary> /// Interaction logic for SceneSettingsView.xaml /// </summary> public partial class SceneSettingsView : UserControl { public SceneSettingsView() { InitializeComponent(); } } }
23.068966
56
0.726457
[ "Apache-2.0" ]
MattS8/SceneMaker
MVVM/View/SceneSettings/SceneSettingsView.xaml.cs
671
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace dp2.KernelService { /// <summary> /// 表现一个资源树节点的路径中 服务器 和 下级路径 2部分 /// </summary> public class ResPath { public string Url = ""; // 服务器URL部分 public string Path = ""; // 服务器内的资源节点路径。第一级是库名 public ResPath() { // // TODO: Add constructor logic here // } public ResPath Clone() { ResPath newobj = new ResPath(); newobj.Url = this.Url; newobj.Path = this.Path; return newobj; } #if REMOVED // 根据树节点构造,把第一级作为Url内容,以下其它级合并起来当作Path,间隔以'/' public ResPath(TreeNode node) { string strFullPath = ""; while (node != null) { if (node.Parent == null) { Url = node.Text; break; } else { if (strFullPath != "") strFullPath = "/" + strFullPath; strFullPath = node.Text + strFullPath; } node = node.Parent; } Path = strFullPath; } #endif // 以全路径构造 public ResPath(string strFullPath) { SetFullPath(strFullPath); } // 只留下数据库名部分 public void MakeDbName() { this.Path = GetDbName(this.Path); } // 2009/3/2 public string GetDbName() { return GetDbName(this.Path); } // 从一个纯路径(不含url部分)中截取库名部分 public static string GetDbName(string strLongPath) { // 2016/11/7 if (string.IsNullOrEmpty(strLongPath)) return ""; int nRet = strLongPath.IndexOf("/"); if (nRet == -1) return strLongPath; else return strLongPath.Substring(0, nRet); } // 从一个纯路径(不含url部分)中截取记录id部分 public static string GetRecordId(string strLongPath) { // 2014/10/23 if (string.IsNullOrEmpty(strLongPath) == true) return null; int nRet = strLongPath.IndexOf("/"); if (nRet == -1) { // return strLongPath; return null; // 2009/11/1 changed } else return strLongPath.Substring(nRet + 1).Trim(); } // 2017/3/8 // 判断路径最后一级是否为问号或者空,也就是追加的方式 public static bool IsAppendRecPath(string strBiblioRecPath) { if (string.IsNullOrEmpty(strBiblioRecPath)) return false; string strTargetRecId = ResPath.GetRecordId(strBiblioRecPath); if (strTargetRecId == "?" || String.IsNullOrEmpty(strTargetRecId) == true) return true; return false; } // 2017/3/8 // 规范追加形态的路径为 "中文图书/?" public static bool CannoicalizeAppendRecPath(ref string strBiblioRecPath) { if (string.IsNullOrEmpty(strBiblioRecPath)) return false; string strTargetRecId = ResPath.GetRecordId(strBiblioRecPath); if (strTargetRecId == "?") return false; if (String.IsNullOrEmpty(strTargetRecId) == true) { strBiblioRecPath = ResPath.GetDbName(strBiblioRecPath) + "/?"; return true; } return false; } // 提取纯粹路径中的id部分。例如 this.Path为"数据库/1",应提取出"1" public string GetRecordId() { string[] aPart = this.Path.Split(new char[] { '/' }); if (aPart.Length < 2) return null; return aPart[1]; } // 提取纯粹路径中的object id部分。例如 this.Path为"数据库/1/object/0",应提取出"1" public string GetObjectId() { string[] aPart = this.Path.Split(new char[] { '/' }); if (aPart.Length < 4) return null; return aPart[3]; } // parameters: // strPath 这是服务器URL和库以及其下路径合成的,中间间隔'?' public void SetFullPath(string strPath) { int nRet = strPath.IndexOf('?'); if (nRet == -1) { Url = strPath.Trim(); Path = ""; return; } Url = strPath.Substring(0, nRet).Trim(); Path = strPath.Substring(nRet + 1).Trim(); } // 将反序的全路径灌入本对象 // parameters: // strPath 这是库以及其下路径 和 服务器URL 合成的,中间间隔'@' public void SetReverseFullPath(string strPath) { int nRet = strPath.IndexOf('@'); if (nRet == -1) { Path = strPath.Trim(); Url = ""; return; } Path = strPath.Substring(0, nRet).Trim(); Url = strPath.Substring(nRet + 1).Trim(); } // 全路径。这是服务器URL和库以及其下路径合成的,中间间隔'?' public string FullPath { get { if (this.Path != "") return this.Url + "?" + this.Path; return this.Url; } set { SetFullPath(value); } } public string ReverseFullPath { get { return this.Path + " @" + this.Url; } set { SetReverseFullPath(value); } } // 把反序全路径加工为正序全路径形态 public static string GetRegularRecordPath(string strReverseRecordPath) { int nRet = strReverseRecordPath.IndexOf("@"); if (nRet == -1) return strReverseRecordPath; return strReverseRecordPath.Substring(nRet + 1).Trim() + "?" + strReverseRecordPath.Substring(0, nRet).Trim(); } // 把正序全路径形态加工为反序全路径形态 public static string GetReverseRecordPath(string strRegularRecordPath) { int nRet = strRegularRecordPath.IndexOf("?"); if (nRet == -1) return strRegularRecordPath; return strRegularRecordPath.Substring(nRet + 1).Trim() + " @" + strRegularRecordPath.Substring(0, nRet).Trim(); } } }
26.921162
123
0.471023
[ "Apache-2.0" ]
DigitalPlatform/dp2core
dp2.KernelService/ResPath.cs
7,130
C#
using System.Text; using MLAgents; using UnityEditor; /// <summary> /// Renders a custom UI for Demonstration Scriptable Object. /// </summary> [CustomEditor(typeof(Demonstration))] [CanEditMultipleObjects] public class DemonstrationEditor : Editor { SerializedProperty m_BrainParameters; SerializedProperty m_DemoMetaData; void OnEnable() { m_BrainParameters = serializedObject.FindProperty("brainParameters"); m_DemoMetaData = serializedObject.FindProperty("metaData"); } /// <summary> /// Renders Inspector UI for Demonstration metadata. /// </summary> void MakeMetaDataProperty(SerializedProperty property) { var nameProp = property.FindPropertyRelative("demonstrationName"); var expProp = property.FindPropertyRelative("numberExperiences"); var epiProp = property.FindPropertyRelative("numberEpisodes"); var rewProp = property.FindPropertyRelative("meanReward"); var nameLabel = nameProp.displayName + ": " + nameProp.stringValue; var expLabel = expProp.displayName + ": " + expProp.intValue; var epiLabel = epiProp.displayName + ": " + epiProp.intValue; var rewLabel = rewProp.displayName + ": " + rewProp.floatValue; EditorGUILayout.LabelField(nameLabel); EditorGUILayout.LabelField(expLabel); EditorGUILayout.LabelField(epiLabel); EditorGUILayout.LabelField(rewLabel); } /// <summary> /// Constructs label for action size array. /// </summary> static string BuildActionArrayLabel(SerializedProperty actionSizeProperty) { var actionSize = actionSizeProperty.arraySize; var actionLabel = new StringBuilder("[ "); for (var i = 0; i < actionSize; i++) { actionLabel.Append(actionSizeProperty.GetArrayElementAtIndex(i).intValue); if (i < actionSize - 1) { actionLabel.Append(", "); } } actionLabel.Append(" ]"); return actionLabel.ToString(); } /// <summary> /// Renders Inspector UI for Brain Parameters of Demonstration. /// </summary> void MakeBrainParametersProperty(SerializedProperty property) { var vecObsSizeProp = property.FindPropertyRelative("vectorObservationSize"); var numStackedProp = property.FindPropertyRelative("numStackedVectorObservations"); var actSizeProperty = property.FindPropertyRelative("vectorActionSize"); var actSpaceTypeProp = property.FindPropertyRelative("vectorActionSpaceType"); var vecObsSizeLabel = vecObsSizeProp.displayName + ": " + vecObsSizeProp.intValue; var numStackedLabel = numStackedProp.displayName + ": " + numStackedProp.intValue; var vecActSizeLabel = actSizeProperty.displayName + ": " + BuildActionArrayLabel(actSizeProperty); var actSpaceTypeLabel = actSpaceTypeProp.displayName + ": " + (SpaceType)actSpaceTypeProp.enumValueIndex; EditorGUILayout.LabelField(vecObsSizeLabel); EditorGUILayout.LabelField(numStackedLabel); EditorGUILayout.LabelField(vecActSizeLabel); EditorGUILayout.LabelField(actSpaceTypeLabel); } public override void OnInspectorGUI() { serializedObject.Update(); EditorGUILayout.LabelField("Meta Data", EditorStyles.boldLabel); MakeMetaDataProperty(m_DemoMetaData); EditorGUILayout.LabelField("Brain Parameters", EditorStyles.boldLabel); MakeBrainParametersProperty(m_BrainParameters); serializedObject.ApplyModifiedProperties(); } }
38.168421
91
0.688913
[ "Apache-2.0" ]
107587084/ml-agents
com.unity.ml-agents/Editor/DemonstrationDrawer.cs
3,626
C#
#if NETFRAMEWORK using Celeste.Mod.CelesteNet.DataTypes; using Mono.Cecil; using Mono.Options; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Reflection; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Celeste.Mod.CelesteNet.Server { public partial class CelesteNetServerModuleWrapper { private static readonly Dictionary<string, string> AssemblyNameMap = new Dictionary<string, string>(); private AssemblyName? AssemblyNameReal; private AssemblyName? AssemblyNameNew; private void LoadAssembly() { long stamp = DateTime.UtcNow.Ticks / TimeSpan.TicksPerMillisecond; string dir = Path.Combine(Path.GetTempPath(), "CelesteNetServerModuleCache"); if (!Directory.Exists(dir)) Directory.CreateDirectory(dir); string path = Path.Combine(dir, $"{Path.GetFileNameWithoutExtension(AssemblyPath)}.{stamp}.dll"); using (ModuleDefinition module = ModuleDefinition.ReadModule(AssemblyPath)) { AssemblyNameReal = new AssemblyName(module.Assembly.Name.FullName); module.Name += "." + stamp; module.Assembly.Name.Name += "." + stamp; foreach (AssemblyNameReference reference in module.AssemblyReferences) if (AssemblyNameMap.TryGetValue(reference.Name, out string referenceNew)) reference.Name = referenceNew; module.Write(path); AssemblyNameNew = new AssemblyName(module.Assembly.Name.FullName); AssemblyNameMap[AssemblyNameReal.Name] = AssemblyNameNew.Name; } Assembly = Assembly.LoadFrom(path); AppDomain.CurrentDomain.AssemblyResolve += OnAssemblyResolve; } private Assembly? OnAssemblyResolve(object sender, ResolveEventArgs args) { if (AssemblyNameReal == null || AssemblyNameNew == null) return null; AssemblyName name = new AssemblyName(args.Name); if (name.FullName == AssemblyNameReal.FullName || name.FullName == AssemblyNameNew.FullName || name.Name == AssemblyNameReal.Name || name.Name == AssemblyNameNew.Name) return Assembly; return null; } private void UnloadAssembly() { AppDomain.CurrentDomain.AssemblyResolve -= OnAssemblyResolve; } } } #endif
34.12987
110
0.644216
[ "MIT" ]
Cruor/CelesteNet
CelesteNet.Server/CelesteNetServerModuleWrapper.Framework.cs
2,630
C#
//this code is taken from https://github.com/microsoft/cntk using CNTK; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NNetwork.Core.network { public class LSTMClassifier { /// <summary> /// This class shows how to build a recurrent neural network model from ground up and train the model. /// </summary> public class LSTMSequenceClassifier { /// <summary> /// Execution folder is: CNTK/x64/BuildFolder /// Data folder is: CNTK/Tests/EndToEndTests/Text/SequenceClassification/Data /// </summary> public static string DataFolder = "Data"; /// <summary> /// Build and train a RNN model. /// </summary> /// <param name="device">CPU or GPU device to train and run the model</param> public static void Train(DeviceDescriptor device) { const int inputDim = 2000; const int cellDim = 25; const int hiddenDim = 25; const int embeddingDim = 50; const int numOutputClasses = 5; // build the model var featuresName = "features"; var features = Variable.InputVariable(new int[] { inputDim }, DataType.Float, featuresName, null, true /*isSparse*/); var labelsName = "labels"; var labels = Variable.InputVariable(new int[] { numOutputClasses }, DataType.Float, labelsName, new List<Axis>() { Axis.DefaultBatchAxis() }, true); var classifierOutput = LSTMSequenceClassifierNet(features, numOutputClasses, embeddingDim, hiddenDim, cellDim, device, "classifierOutput"); Function trainingLoss = CNTKLib.CrossEntropyWithSoftmax(classifierOutput, labels, "lossFunction"); Function prediction = CNTKLib.ClassificationError(classifierOutput, labels, "classificationError"); // prepare training data IList<StreamConfiguration> streamConfigurations = new StreamConfiguration[] { new StreamConfiguration(featuresName, inputDim, true, "x"), new StreamConfiguration(labelsName, numOutputClasses, false, "y") }; var minibatchSource = MinibatchSource.TextFormatMinibatchSource( Path.Combine(DataFolder, "Train.ctf"), streamConfigurations, MinibatchSource.InfinitelyRepeat, true); var featureStreamInfo = minibatchSource.StreamInfo(featuresName); var labelStreamInfo = minibatchSource.StreamInfo(labelsName); // prepare for training TrainingParameterScheduleDouble learningRatePerSample = new TrainingParameterScheduleDouble( 0.0005, 1); TrainingParameterScheduleDouble momentumTimeConstant = CNTKLib.MomentumAsTimeConstantSchedule(256); IList<Learner> parameterLearners = new List<Learner>() { Learner.MomentumSGDLearner(classifierOutput.Parameters(), learningRatePerSample, momentumTimeConstant, /*unitGainMomentum = */true) }; var trainer = Trainer.CreateTrainer(classifierOutput, trainingLoss, prediction, parameterLearners); // train the model uint minibatchSize = 200; // int outputFrequencyInMinibatches = 20; // int miniBatchCount = 0; int numEpochs = 5; while (numEpochs > 0) { var minibatchData = minibatchSource.GetNextMinibatch(minibatchSize, device); var arguments = new Dictionary<Variable, MinibatchData> { { features, minibatchData[featureStreamInfo] }, { labels, minibatchData[labelStreamInfo] } }; trainer.TrainMinibatch(arguments, device); //TestHelper.PrintTrainingProgress(trainer, miniBatchCount++, outputFrequencyInMinibatches); //// Because minibatchSource is created with MinibatchSource.InfinitelyRepeat, //// batching will not end. Each time minibatchSource completes an sweep (epoch), //// the last minibatch data will be marked as end of a sweep. We use this flag //// to count number of epochs. //if (TestHelper.MiniBatchDataIsSweepEnd(minibatchData.Values)) { numEpochs--; } } } static Function Stabilize<ElementType>(Variable x, DeviceDescriptor device) { bool isFloatType = typeof(ElementType).Equals(typeof(float)); Constant f, fInv; if (isFloatType) { f = Constant.Scalar(4.0f, device); fInv = Constant.Scalar(f.DataType, 1.0 / 4.0f); } else { f = Constant.Scalar(4.0, device); fInv = Constant.Scalar(f.DataType, 1.0 / 4.0f); } var beta = CNTKLib.ElementTimes( fInv, CNTKLib.Log( Constant.Scalar(f.DataType, 1.0) + CNTKLib.Exp(CNTKLib.ElementTimes(f, new Parameter(new NDShape(), f.DataType, 0.99537863 /* 1/f*ln (e^f-1) */, device,"_stabilize"))))); return CNTKLib.ElementTimes(beta, x); } static Tuple<Function, Function> LSTMPCellWithSelfStabilization<ElementType>( Variable input, Variable prevOutput, Variable prevCellState, DeviceDescriptor device) { int outputDim = prevOutput.Shape[0]; int cellDim = prevCellState.Shape[0]; bool isFloatType = typeof(ElementType).Equals(typeof(float)); DataType dataType = isFloatType ? DataType.Float : DataType.Double; Func<int, Parameter> createBiasParam; if (isFloatType) createBiasParam = (dim) => new Parameter(new int[] { dim }, 0.01f, device, "_b"); else createBiasParam = (dim) => new Parameter(new int[] { dim }, 0.01, device, "_b"); uint seed2 = 1; Func<int,string, Parameter> createProjectionParam = (oDim,name) => new Parameter(new int[] { oDim, NDShape.InferredDimension }, dataType, CNTKLib.GlorotUniformInitializer(1.0, 1, 0, seed2++), device,name==""?"_u":name); Func<int, Parameter> createDiagWeightParam = (dim) => new Parameter(new int[] { dim }, dataType, CNTKLib.GlorotUniformInitializer(1.0, 1, 0, seed2++), device,"_peep"); Function stabilizedPrevOutput = Stabilize<ElementType>(prevOutput, device); Function stabilizedPrevCellState = Stabilize<ElementType>(prevCellState, device); Func<Variable> projectInput = () => createBiasParam(cellDim) + (createProjectionParam(cellDim,"_w") * input); // Input gate var tanH = CNTKLib.Tanh(projectInput() + (createProjectionParam(cellDim,"") * stabilizedPrevOutput)); Function it = CNTKLib.Sigmoid( (Variable)(projectInput() + (createProjectionParam(cellDim,"") * stabilizedPrevOutput)) + CNTKLib.ElementTimes(createDiagWeightParam(cellDim), stabilizedPrevCellState)); Function bit = CNTKLib.ElementTimes(it, tanH); // Forget-me-not gate Function ft = CNTKLib.Sigmoid( (Variable)( projectInput() + (createProjectionParam(cellDim,"") * stabilizedPrevOutput)) + CNTKLib.ElementTimes(createDiagWeightParam(cellDim), stabilizedPrevCellState)); Function bft = CNTKLib.ElementTimes(ft, prevCellState); Function ct = (Variable)bft + bit; // Output gate Function ot = CNTKLib.Sigmoid( (Variable)(projectInput() + (createProjectionParam(cellDim,"") * stabilizedPrevOutput)) + CNTKLib.ElementTimes(createDiagWeightParam(cellDim), Stabilize<ElementType>(ct, device))); Function ht = CNTKLib.ElementTimes(ot, CNTKLib.Tanh(ct)); Function c = ct; Function h = (outputDim != cellDim) ? (createProjectionParam(outputDim,"") * Stabilize<ElementType>(ht, device)) : ht; return new Tuple<Function, Function>(h, c); } static Tuple<Function, Function> LSTMPComponentWithSelfStabilization<ElementType>(Variable input, NDShape outputShape, NDShape cellShape, Func<Variable, Function> recurrenceHookH, Func<Variable, Function> recurrenceHookC, DeviceDescriptor device) { var dh = Variable.PlaceholderVariable(outputShape, input.DynamicAxes); var dc = Variable.PlaceholderVariable(cellShape, input.DynamicAxes); var LSTMCell = LSTMPCellWithSelfStabilization<ElementType>(input, dh, dc, device); var actualDh = recurrenceHookH(LSTMCell.Item1); var actualDc = recurrenceHookC(LSTMCell.Item2); // Form the recurrence loop by replacing the dh and dc placeholders with the actualDh and actualDc (LSTMCell.Item1).ReplacePlaceholders(new Dictionary<Variable, Variable> { { dh, actualDh }, { dc, actualDc } }); return new Tuple<Function, Function>(LSTMCell.Item1, LSTMCell.Item2); } private static Function Embedding(Variable input, int embeddingDim, DeviceDescriptor device) { System.Diagnostics.Debug.Assert(input.Shape.Rank == 1); int inputDim = input.Shape[0]; var embeddingParameters = new Parameter(new int[] { embeddingDim, inputDim }, DataType.Float, CNTKLib.GlorotUniformInitializer(), device); return CNTKLib.Times(embeddingParameters, input); } /// <summary> /// Build a one direction recurrent neural network (RNN) with long-short-term-memory (LSTM) cells. /// http://colah.github.io/posts/2015-08-Understanding-LSTMs/ /// </summary> /// <param name="input">the input variable</param> /// <param name="numOutputClasses">number of output classes</param> /// <param name="embeddingDim">dimension of the embedding layer</param> /// <param name="LSTMDim">LSTM output dimension</param> /// <param name="cellDim">cell dimension</param> /// <param name="device">CPU or GPU device to run the model</param> /// <param name="outputName">name of the model output</param> /// <returns>the RNN model</returns> static Function LSTMSequenceClassifierNet(Variable input, int numOutputClasses, int embeddingDim, int LSTMDim, int cellDim, DeviceDescriptor device, string outputName) { Function embeddingFunction = Embedding(input, embeddingDim, device); Func<Variable, Function> pastValueRecurrenceHook = (x) => CNTKLib.PastValue(x); Function LSTMFunction = LSTMPComponentWithSelfStabilization<float>( embeddingFunction, new int[] { LSTMDim }, new int[] { cellDim }, pastValueRecurrenceHook, pastValueRecurrenceHook, device).Item1; Function thoughtVectorFunction = CNTKLib.SequenceLast(LSTMFunction); return null;//TestHelper.FullyConnectedLinearLayer(thoughtVectorFunction, numOutputClasses, device, outputName); } public static Function LSTMNet(Variable input, int outDim, DeviceDescriptor device, string outputName) { var LSTMDim = outDim; var cellDim = outDim; Func<Variable, Function> pastValueRecurrenceHook = (x) => CNTKLib.PastValue(x); Function LSTMFunction = LSTMPComponentWithSelfStabilization<float>( input, new int[] { LSTMDim }, new int[] { cellDim }, pastValueRecurrenceHook, pastValueRecurrenceHook, device).Item1; Function thoughtVectorFunction = CNTKLib.SequenceLast(LSTMFunction); return thoughtVectorFunction; } } } }
51.519841
160
0.581684
[ "MIT" ]
amphil123/anndotnet
src/core/nnetwork.core/oldimplementation/LSTMClassifier.cs
12,985
C#
/* Copyright (C) 2021 Kevin Boronka * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ using sar.Tools; using System.IO; namespace sar.Base { public abstract class Configuration { protected string path; protected bool readOnly; public Configuration() { // check if local read-only configuration file exists var localPath = ApplicationInfo.CurrentDirectory + sar.Tools.AssemblyInfo.Name + ".xml"; var standardPath = ApplicationInfo.CommonDataDirectory + sar.Tools.AssemblyInfo.Name + ".xml"; if (File.Exists(localPath)) { this.path = localPath; readOnly = true; } else { this.path = standardPath; readOnly = false; } // read the file if (File.Exists(this.path)) { var reader = new XML.Reader(this.path); this.Deserialize(reader); reader.Close(); } else { this.InitDefaults(); this.Save(); } } public Configuration(string path) { this.path = path; this.readOnly = true; if (File.Exists(this.path)) { var reader = new XML.Reader(this.path); try { this.Deserialize(reader); } catch { } reader.Close(); } } public void Save() { if (!readOnly) { this.Save(this.path); } } public void Save(string path) { if (!readOnly) { this.path = path; var writer = new XML.Writer(path); try { this.Serialize(writer); } catch { } writer.Close(); } } protected abstract void Deserialize(XML.Reader reader); protected abstract void Serialize(XML.Writer writer); protected abstract void InitDefaults(); } }
22.25
98
0.637239
[ "BSD-2-Clause" ]
kboronka/sar-tool
sar/Base/Configuration.cs
2,492
C#
using System.Threading.Tasks; using Discord.WebSocket; using Microsoft.AspNetCore.Mvc; using Modix.Data.Models.Core; using Modix.Data.Repositories; using Modix.Models; using Modix.Services.Core; namespace Modix.Controllers { [Route("~/api/config/claims")] public class ClaimsController : ModixController { private IClaimMappingRepository ClaimMappingRepository { get; } public ClaimsController(DiscordSocketClient client, IAuthorizationService modixAuth, IClaimMappingRepository claimMappingRepository) : base(client, modixAuth) { ClaimMappingRepository = claimMappingRepository; } [HttpGet] public async Task<IActionResult> RoleClaims() { var found = await ClaimMappingRepository.SearchBriefsAsync(new ClaimMappingSearchCriteria { IsDeleted = false }); return Ok(found); } [HttpPatch] public async Task<IActionResult> ModifyRole([FromBody]RoleClaimModifyData modifyData) { await ModixAuth.ModifyClaimMappingAsync(modifyData.RoleId, modifyData.Claim, modifyData.MappingType); return Ok(); } [HttpDelete("{id}")] public async Task<IActionResult> DeleteClaim(int id) { using (var transaction = await ClaimMappingRepository.BeginDeleteTransactionAsync()) { if (!await ClaimMappingRepository.TryDeleteAsync(id, SocketUser.Id)) return NotFound(); transaction.Commit(); } return Ok(); } } }
30.886792
166
0.639585
[ "MIT" ]
333fred/MODiX
Modix/Controllers/ClaimsController.cs
1,639
C#
#if UNITY_2019_3_OR_NEWER using System; using System.Collections.Generic; using UnityEditor.Build.Content; using UnityEditor.Build.Pipeline.Injector; using UnityEditor.Build.Pipeline.Interfaces; using UnityEditor.Build.Pipeline.Utilities; namespace UnityEditor.Build.Pipeline.Tasks { /// <summary> /// Build Task that calculates teh included objects and references objects for custom assets not tracked by the AssetDatabase. /// <seealso cref="IBuildTask"/> /// </summary> public class CalculateCustomDependencyData : IBuildTask { /// <inheritdoc /> public int Version { get { return 2; } } #pragma warning disable 649 [InjectContext(ContextUsage.In)] IBuildParameters m_Parameters; [InjectContext(ContextUsage.InOut)] IBundleBuildContent m_Content; [InjectContext(ContextUsage.InOut)] IDependencyData m_DependencyData; [InjectContext(ContextUsage.Out, true)] ICustomAssets m_CustomAssets; [InjectContext(ContextUsage.In, true)] IProgressTracker m_Tracker; #pragma warning restore 649 BuildUsageTagGlobal m_GlobalUsage; /// <inheritdoc /> public ReturnCode Run() { m_CustomAssets = new CustomAssets(); m_GlobalUsage = m_DependencyData.GlobalUsage; foreach (SceneDependencyInfo sceneInfo in m_DependencyData.SceneInfo.Values) m_GlobalUsage |= sceneInfo.globalUsage; foreach (CustomContent info in m_Content.CustomAssets) { if (!m_Tracker.UpdateInfoUnchecked(info.Asset.ToString())) return ReturnCode.Canceled; info.Processor(info.Asset, this); } return ReturnCode.Success; } /// <summary> /// Returns the Object Identifiers and Types in a raw Unity Serialized File. The resulting arrays will be empty if a non-serialized file path was used. /// </summary> /// <param name="path">Path to the Unity Serialized File</param> /// <param name="objectIdentifiers">Object Identifiers for all the objects in the serialized file</param> /// <param name="types">Types for all the objects in the serialized file</param> public void GetObjectIdentifiersAndTypesForSerializedFile(string path, out ObjectIdentifier[] objectIdentifiers, out Type[] types) { objectIdentifiers = ContentBuildInterface.GetPlayerObjectIdentifiersInSerializedFile(path, m_Parameters.Target); types = ContentBuildInterface.GetTypeForObjects(objectIdentifiers); } /// <summary> /// Adds mapping and bundle information for a custom asset that contains a set of unity objects. /// </summary> /// <param name="includedObjects">Object Identifiers that belong to this custom asset</param> /// <param name="path">Path on disk for this custom asset</param> /// <param name="bundleName">Asset Bundle name where to add this custom asset</param> /// <param name="address">Load address to used to load this asset from the Asset Bundle</param> /// <param name="mainAssetType">Type of the main object for this custom asset</param> public void CreateAssetEntryForObjectIdentifiers(ObjectIdentifier[] includedObjects, string path, string bundleName, string address, Type mainAssetType) { AssetLoadInfo assetInfo = new AssetLoadInfo(); BuildUsageTagSet usageTags = new BuildUsageTagSet(); assetInfo.asset = HashingMethods.Calculate(address).ToGUID(); assetInfo.address = address; if (m_DependencyData.AssetInfo.ContainsKey(assetInfo.asset)) throw new ArgumentException(string.Format("Custom Asset '{0}' already exists. Building duplicate asset entries is not supported.", address)); assetInfo.includedObjects = new List<ObjectIdentifier>(includedObjects); var referencedObjects = ContentBuildInterface.GetPlayerDependenciesForObjects(includedObjects, m_Parameters.Target, m_Parameters.ScriptInfo); assetInfo.referencedObjects = new List<ObjectIdentifier>(referencedObjects); ContentBuildInterface.CalculateBuildUsageTags(referencedObjects, includedObjects, m_GlobalUsage, usageTags, m_DependencyData.DependencyUsageCache); SetOutputInformation(bundleName, assetInfo, usageTags); } void SetOutputInformation(string bundleName, AssetLoadInfo assetInfo, BuildUsageTagSet usageTags) { List<GUID> assets; m_Content.BundleLayout.GetOrAdd(bundleName, out assets); assets.Add(assetInfo.asset); m_Content.Addresses.Add(assetInfo.asset, assetInfo.address); m_DependencyData.AssetInfo.Add(assetInfo.asset, assetInfo); m_DependencyData.AssetUsage.Add(assetInfo.asset, usageTags); m_CustomAssets.Assets.Add(assetInfo.asset); } } } #endif
46.564815
160
0.688606
[ "MIT" ]
TalipSalihoglu/Endless-Run-Game
Covid-Run/Library/PackageCache/com.unity.scriptablebuildpipeline@1.7.3/Editor/Tasks/CalculateCustomDependencyData.cs
5,031
C#
/*Copyright (c) 2014, Flip van Toly All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.*/ //Namespace Declaration using System; using System.IO; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; using KSP.UI.Screens; using Contracts; using CommercialOfferings.MissionData; namespace CommercialOfferings { [KSPAddon(KSPAddon.Startup.Flight, false)] public partial class RMMModule : PartModule { List<Mission> OfferingsList = new List<Mission>(); //current mission [KSPField(isPersistant = true, guiActive = false)] public bool missionUnderway = false; [KSPField(isPersistant = true, guiActive = false)] public string missionFolderName = ""; [KSPField(isPersistant = true, guiActive = false)] public float missionArrivalTime = 0; [KSPField(isPersistant = true, guiActive = false)] public int missionCrewCount = 0; private Mission missionOffering = new Mission(); [KSPField(isPersistant = true, guiActive = false)] public bool missionRepeat = false; [KSPField(isPersistant = true, guiActive = false)] public int missionRepeatDelay = 0; [KSPField(isPersistant = true, guiActive = false)] public string missionPreferedCrew = ""; //values to save orbit [KSPField(isPersistant = true, guiActive = false)] public float SMAsave = 0; [KSPField(isPersistant = true, guiActive = false)] public float ECCsave = 0; [KSPField(isPersistant = true, guiActive = false)] public float INCsave = 0; //arrival transaction public double nextLogicTime = 0; public bool completeArrival = false; private int ArrivalStage = 0; Vessel transactionVessel = null; private string tempID = ""; private uint missionFlightIDDockPart = 0; //Port Code [KSPField(isPersistant = true, guiActive = true, guiActiveEditor = true, guiName = "Port Code", guiUnits = "")] public string PortCode = ""; [KSPField(isPersistant = true, guiActive = false)] public bool OrderingEnabled = true; //GUI Main private bool renderGUIMain = false; private static Rect windowPosGUIMain = new Rect(200, 200, 200, 450); private Vector2 scrollPositionAvailableCommercialOfferings; public float windowGUIMainX = 1; public float windowGUIMainY = 1; public float windowGUIMainWidth = 10; Mission selectedOffering = new Mission(); //GUI Offering private bool renderGUIOffering = false; private static Rect windowPosGUIOffering = new Rect(300, 100, 100, 100); Mission GUIOffering = new Mission(); //GUI Order private bool renderGUIMission = false; private static Rect windowPosGUIMission = new Rect(500, 400, 300, 75); Mission GUIMission = new Mission(); private int intCrewCount = 0; private string strCrewCount = ""; //private string strGUIerrmess = ""; //GUI Pref Crew private bool renderGUIPrefCrew = false; private static Rect windowPosGUIPrefCrew = new Rect(700, 200, 200, 600); List<ProtoCrewMember> preferredCrewList = new List<ProtoCrewMember>(); private Vector2 scrollPositionPreferredCrew; private Vector2 scrollPositionAvailableCrew; //GUI Register Port private bool renderGUIRegister = false; private static Rect windowPosGUIRegister = new Rect(300, 300, 240, 100); public string StrPortCode = ""; //commercialvehiclemode [KSPField(isPersistant = true, guiActive = false)] public bool commercialvehiclemode = false; [KSPField(isPersistant = true, guiActive = false)] public bool vehicleAutoDepart = false; [KSPField(isPersistant = true, guiActive = false)] public string commercialvehicleFolderName = ""; [KSPField(isPersistant = true, guiActive = false)] public float commercialvehiclePartCount = 0.0f; private Mission commercialvehicleOffering = new Mission(); private bool commercialvehicleOfferingLoaded = false; private bool handleCommercialVehicleMode() { if (commercialvehiclemode && !commercialvehicleOfferingLoaded && commercialvehicleFolderName != "") { loadOfferings(); foreach (Mission Off in OfferingsList) { if (commercialvehicleFolderName == Off.FolderPath) { commercialvehicleOffering = Off; commercialvehicleOfferingLoaded = true; return false; } } return (true); } if (commercialvehiclemode) { if (vehicleAutoDepart && !RmmUtil.IsDocked(vessel, part)) { if (!vessel.isActiveVessel) { handleAutoDepart(); return false; } else { foreach (Vessel ves in FlightGlobals.Vessels) { if (!ves.packed && ves.loaded && ves.id.ToString() != vessel.id.ToString()) { FlightGlobals.SetActiveVessel(ves); nextLogicTime = Planetarium.GetUniversalTime() + 1; return false; } } vehicleAutoDepart = false; nextLogicTime = 0; ScreenMessages.PostScreenMessage("no other asset in vicinity", 4, ScreenMessageStyle.UPPER_CENTER); } } } return true; } private void handleArrivalCompletion() { if (ArrivalStage == 0) { if (missionUnderway && missionArrivalTime < Planetarium.GetUniversalTime()) { if (!otherModulesCompletingArrival()) { ArrivalStage = 1; completeArrival = true; nextLogicTime = Planetarium.GetUniversalTime(); } else { ArrivalStage = 0; nextLogicTime = Planetarium.GetUniversalTime() + 1.25; } } else { ArrivalStage = -1; nextLogicTime = 0; } } if (completeArrival) { switch (ArrivalStage) { case 1: dockStage1(); break; case 2: dockStage2(); break; case 3: dockStage3(); break; case 4: if (transactionVessel == null || vessel.packed || !vessel.loaded || transactionVessel.packed || !transactionVessel.loaded) { nextLogicTime = Planetarium.GetUniversalTime(); return; } dockStage4(); break; case 5: dockStage5(); break; } } } private void dockStage1() { loadOfferings(); foreach (Mission Off in OfferingsList) { if (missionFolderName == Off.FolderPath) { missionOffering = Off; } } if (missionOffering == null) { abortArrival(); return; } //load Offering of current mission if (offeringAllowed(missionOffering) && crewAvailable(missionOffering)) { nextLogicTime = Planetarium.GetUniversalTime(); ArrivalStage = 2; } else { Funding.Instance.AddFunds(missionOffering.Price, TransactionReasons.VesselRecovery); missionUnderway = false; completeArrival = false; nextLogicTime = 0; ArrivalStage = -1; } } private void dockStage2() { RmmUtil.ToMapView(); ProtoVessel ProtoFlightVessel = loadVessel(missionFolderName); if (ProtoFlightVessel == null) { abortArrival(); return; } if (loadVesselForRendezvous(ProtoFlightVessel, vessel)) { nextLogicTime = Planetarium.GetUniversalTime(); ArrivalStage = 3; } } private void dockStage3() { //search for the vessel for five seconds, else abort if (nextLogicTime < (Planetarium.GetUniversalTime() - 5)) { logreport(); abortArrival(); return; } foreach (Vessel ve in FlightGlobals.Vessels) { if (ve.vesselName == tempID) { transactionVessel = ve; transactionVessel.vesselName = missionOffering.VehicleName; placeVesselForRendezvous(transactionVessel, vessel); nextLogicTime = Planetarium.GetUniversalTime(); ArrivalStage = 4; return; } } } private void logreport() { print("i'm at stage " + ArrivalStage + " and can not find vessel " + tempID + ". the vessels i can find are:"); foreach (Vessel ve in FlightGlobals.Vessels) { print(ve.vesselName); } print("--test run"); foreach (Vessel ve in FlightGlobals.Vessels) { if (ve.vesselName == tempID) { print("test 1"); transactionVessel = ve; print("test 2"); transactionVessel.vesselName = missionOffering.VehicleName; print("test 3"); placeVesselForRendezvous(transactionVessel, vessel); print("test 4"); nextLogicTime = Planetarium.GetUniversalTime(); ArrivalStage = 4; return; } } } private void dockStage4() { RmmUtil.ToMapView(); Part placePort = new Part(); // int portNumber = 0; foreach (Part p in transactionVessel.parts) { if (p.flightID == missionFlightIDDockPart) { placePort = p; } foreach (PartModule pm in p.Modules) { //if (pm.GetType() == typeof(ModuleDockingNode)) //{ // RMMModule ComOffMod = p.Modules.OfType<RMMModule>().FirstOrDefault(); // if (ComOffMod.trackingPrimary == true) // { // placePort = p; // if (missionOffering.ReturnEnabled) // { // ComOffMod.commercialvehiclemode = true; // ComOffMod.commercialvehicleFolderName = missionOffering.FolderPath; // ComOffMod.commercialvehiclePartCount = (float)RmmUtil.CountVesselParts(transactionVessel); // ComOffMod.trackingPrimary = false; // } // } // portNumber = portNumber + 1; // // ComOffMod.trackingActive = false; // ComOffMod.returnMission = false; // ComOffMod.trackMissionId = ""; // ComOffMod.PortCode = ""; //} // empty all science if (pm.GetType() == typeof(ModuleScienceContainer)) { ModuleScienceContainer moduleScienceContainer = (ModuleScienceContainer)pm; var scienceDatas = moduleScienceContainer.GetData(); for (int i = 0; i < scienceDatas.Count(); i++) { moduleScienceContainer.RemoveData(scienceDatas[i]); } } } } transactionVessel.targetObject = null; handleLoadCrew(transactionVessel, missionCrewCount, missionOffering.MinimumCrew); RmmContract.HandleContracts(transactionVessel, true, false); if (!RmmUtil.IsDocked(vessel, part) && checkDockingPortCompatibility(placePort, part)) { placeVesselForDock(transactionVessel, placePort, vessel, part, RmmUtil.GetDockingDistance(placePort)); nextLogicTime = Planetarium.GetUniversalTime(); ArrivalStage = 5; } else { ScreenMessages.PostScreenMessage(missionOffering.VehicleName + " rendezvoused", 4, ScreenMessageStyle.UPPER_CENTER); finishArrival(); } } private void dockStage5() { RmmUtil.ToMapView(); if (RmmUtil.IsDocked(vessel, part) || (nextLogicTime < (Planetarium.GetUniversalTime() - 8))) { ScreenMessages.PostScreenMessage(missionOffering.VehicleName + " docked", 4, ScreenMessageStyle.UPPER_CENTER); finishArrival(); } } private ProtoVessel loadVessel(string folderName) { ConfigNode loadnode = null; if (!File.Exists(RmmUtil.GamePath + folderName + "/vesselfile")) { abortArrival(); return null; } loadnode = ConfigNode.Load(RmmUtil.GamePath + folderName + "/vesselfile"); if (loadnode == null) { abortArrival(); return null; } ProtoVessel loadprotovessel = new ProtoVessel(loadnode, HighLogic.CurrentGame); return loadprotovessel; } private bool loadVesselForRendezvous(ProtoVessel placeVessel, Vessel targetVessel) { targetVessel.BackupVessel(); placeVessel.orbitSnapShot = targetVessel.protoVessel.orbitSnapShot; placeVessel.orbitSnapShot.epoch = 0.0; tempID = RmmUtil.Rand.Next(1000000000).ToString(); //rename any vessels present with "AdministativeDockingName" foreach (Vessel ve in FlightGlobals.Vessels) { if (ve.vesselName == tempID) { Vessel NameVessel = null; NameVessel = ve; NameVessel.vesselName = "1"; } } placeVessel.vesselID = Guid.NewGuid(); placeVessel.vesselName = tempID; foreach (ProtoPartSnapshot p in placeVessel.protoPartSnapshots) { uint newFlightID = (UInt32)RmmUtil.Rand.Next(1000000000, 2147483647); // save flight ID of part which should dock if (p.flightID == missionOffering.flightIDDockPart) { missionFlightIDDockPart = newFlightID; } // update flight ID of each part and vessel reference transform id. if (placeVessel.refTransform == p.flightID) { p.flightID = newFlightID; placeVessel.refTransform = p.flightID; } else { p.flightID = newFlightID; } // clear out all crew if (p.protoModuleCrew != null && p.protoModuleCrew.Count() != 0) { List<ProtoCrewMember> cl = p.protoModuleCrew; List<ProtoCrewMember> clc = new List<ProtoCrewMember>(cl); foreach (ProtoCrewMember c in clc) { p.RemoveCrew(c); } } foreach (ProtoPartModuleSnapshot pm in p.modules) { if (pm.moduleName == "RMMModule") { pm.moduleValues.SetValue("trackingPrimary", false); pm.moduleValues.SetValue("trackingActive", false); } } } try { placeVessel.Load(HighLogic.CurrentGame.flightState); return true; } catch { return true; } } private void placeVesselForRendezvous(Vessel placeVessel, Vessel targetVessel) { Vector3d offset = new Vector3d(); if (!determineRendezvousOffset(placeVessel, targetVessel, ref offset)) { completeArrival = false; nextLogicTime = 0; ArrivalStage = -1; return; } placeVessel.orbit.UpdateFromStateVectors(targetVessel.orbit.pos + offset, targetVessel.orbit.vel, targetVessel.orbit.referenceBody, Planetarium.GetUniversalTime()); } private bool determineRendezvousOffset(Vessel placeVessel, Vessel targetVessel, ref Vector3d offset) { int rendezvousDistance = vesselScale(placeVessel); //determine max scale of al vessels involved foreach (Vessel ves in FlightGlobals.Vessels) { if (!ves.packed && ves.loaded) { int scale = vesselScale(ves); if (scale > rendezvousDistance) { rendezvousDistance = scale; } } } bool good; int attempts = 0; do { good = true; attempts = attempts + 1; if (rendezvousDistance > 115) { rendezvousDistance = 115; } if (rendezvousDistance <= 0) { rendezvousDistance = 100; } ///make a random offset double x = 0; double y = 0; double z = 0; int ra = RmmUtil.Rand.Next(3); switch (ra) { case 0: x = (double)rendezvousDistance; y = (double)RmmUtil.Rand.Next(rendezvousDistance); z = (double)RmmUtil.Rand.Next(rendezvousDistance); break; case 1: x = (double)RmmUtil.Rand.Next(rendezvousDistance); y = (double)rendezvousDistance; z = (double)RmmUtil.Rand.Next(rendezvousDistance); break; case 2: x = (double)RmmUtil.Rand.Next(rendezvousDistance); y = (double)RmmUtil.Rand.Next(rendezvousDistance); z = (double)rendezvousDistance; break; } if (RmmUtil.Rand.Next(0, 2) == 1) { x = x * -1; } if (RmmUtil.Rand.Next(0, 2) == 1) { y = y * -1; } if (RmmUtil.Rand.Next(0, 2) == 1) { z = z * -1; } offset.x = x; offset.y = y; offset.z = z; // check if offset is far enough from all vessels in area foreach (Vessel ves in FlightGlobals.Vessels) { if (!ves.packed && ves.loaded && ves.id != placeVessel.id ) { var dist = Vector3.Distance(ves.orbit.pos, targetVessel.orbit.pos + offset); if (dist < rendezvousDistance) { good = false; } } } } while(!good && attempts < 100); return (good); } private bool checkDockingPortCompatibility(Part placePort, Part targetPort) { ModuleDockingNode placeDockingNode = placePort.Modules.OfType<ModuleDockingNode>().FirstOrDefault(); ModuleDockingNode targetDockingNode = targetPort.Modules.OfType<ModuleDockingNode>().FirstOrDefault(); return (placeDockingNode.nodeType == targetDockingNode.nodeType); } private int vesselScale(Vessel ves) { float longestdistance = 0f; foreach (Part p in ves.parts) { if (Math.Abs(p.orgPos[0] - ves.rootPart.orgPos[0]) > longestdistance) { longestdistance = Math.Abs(p.orgPos[0] - ves.rootPart.orgPos[0]); } if (Math.Abs(p.orgPos[1] - ves.rootPart.orgPos[1]) > longestdistance) { longestdistance = Math.Abs(p.orgPos[1] - ves.rootPart.orgPos[1]); } if (Math.Abs(p.orgPos[2] - ves.rootPart.orgPos[2]) > longestdistance) { longestdistance = Math.Abs(p.orgPos[2] - ves.rootPart.orgPos[2]); } } return (((int)(longestdistance * 4 + 10))); } private void placeVesselForDock(Vessel placeVessel, Part placePort, Vessel targetVessel, Part targetPort, float distanceFactor) { ModuleDockingNode placeDockingNode = placePort.Modules.OfType<ModuleDockingNode>().FirstOrDefault(); ModuleDockingNode targetDockingNode = targetPort.Modules.OfType<ModuleDockingNode>().FirstOrDefault(); QuaternionD placeVesselRotation = targetDockingNode.controlTransform.rotation * Quaternion.Euler(180f, (float)RmmUtil.Rand.Next(0, 360), 0); placeVessel.SetRotation(placeVesselRotation); placeVessel.SetRotation(placeDockingNode.controlTransform.rotation * Quaternion.Euler(0, (float)RmmUtil.Rand.Next(0, 360), 0)); float anglePlaceDock = angleNormal(placeDockingNode.nodeTransform.forward.normalized, placeVessel.vesselTransform.forward.normalized, placeVessel.vesselTransform.up.normalized); float angleTargetDock = angleNormal(-targetDockingNode.nodeTransform.forward.normalized, placeVessel.vesselTransform.forward.normalized, placeVessel.vesselTransform.up.normalized); placeVessel.SetRotation(placeVessel.vesselTransform.rotation * Quaternion.Euler(0, (anglePlaceDock - angleTargetDock), 0)); //position vessel Vector3d placePortLocation = targetDockingNode.nodeTransform.position + (targetDockingNode.nodeTransform.forward.normalized * distanceFactor); Vector3d placeVesselPosition = placePortLocation + (placeVessel.vesselTransform.position - placeDockingNode.nodeTransform.position); placeVessel.SetPosition(placeVesselPosition); } //Thanks to NavyFish's Docking Port Alignment Indicator for showing how to calculate an angle private float angleNormal(Vector3 measure, Vector3 reference, Vector3 axis) { //in contrast to NavyFish's Docking Port Alignment Indicator we need a 0-360 value return (angleSigned(Vector3.Cross(measure, axis), Vector3.Cross(reference, axis), axis) + 180); } //-180 to 180 angle private float angleSigned(Vector3 measureAngle, Vector3 referenceAngle, Vector3 axis) { if (Vector3.Dot(Vector3.Cross(measureAngle, referenceAngle), axis) < 0) //greater than 90 i.e v1 left of v2 return -Vector3.Angle(measureAngle, referenceAngle); return Vector3.Angle(measureAngle, referenceAngle); } private void finishArrival() { missionUnderway = false; completeArrival = false; nextLogicTime = 0; ArrivalStage = -1; if (missionRepeat) { procureOffering(missionOffering, true); } } private void abortArrival() { missionUnderway = false; completeArrival = false; missionRepeat = false; nextLogicTime = 0; ArrivalStage = -1; } //Thanks to sarbian's Kerbal Crew Manifest for showing all this crew handling stuff private void handleLoadCrew(Vessel ves, int crewCount, int minCrew) { if (ves.GetCrewCapacity() < crewCount) crewCount = ves.GetCrewCapacity(); string[] prefCrewNames = new string[0]; getPreferredCrewNames (ref prefCrewNames); foreach (Part p in ves.parts) { if (p.CrewCapacity > p.protoModuleCrew.Count) { for (int i = 0; i < p.CrewCapacity && crewCount > 0; i++) { bool added = false; //tourist if (minCrew <= 0) { foreach (String name in prefCrewNames) { if (!added) { foreach (ProtoCrewMember cr in HighLogic.CurrentGame.CrewRoster.Tourist) { if (name == cr.name && cr.rosterStatus == ProtoCrewMember.RosterStatus.Available) { if (AddCrew(p, cr)) { crewCount = crewCount - 1; added = true; } } } } } } //preferred crew foreach (String name in prefCrewNames) { if (!added) { foreach (ProtoCrewMember cr in HighLogic.CurrentGame.CrewRoster.Crew) { if (name == cr.name && cr.rosterStatus == ProtoCrewMember.RosterStatus.Available) { if (AddCrew(p, cr)) { crewCount = crewCount - 1; minCrew = minCrew - 1; added = true; } } } } } //next crew or new crew //print("one crew start"); //print("crew" + kerbal.name); if (!added) { ProtoCrewMember crew = null; crew = HighLogic.CurrentGame.CrewRoster.GetNextAvailableKerbal(); if (crew != null) { if (AddCrew(p, crew)) { crewCount = crewCount - 1; minCrew = minCrew - 1; added = true; } } } } } } ves.SpawnCrew(); } private bool crewAvailable(Mission Off) { int availableCrew = 0; foreach (ProtoCrewMember cr in HighLogic.CurrentGame.CrewRoster.Crew) { if (cr.rosterStatus == ProtoCrewMember.RosterStatus.Available) { availableCrew++; } } if (availableCrew < Off.MinimumCrew) { ScreenMessages.PostScreenMessage("not enough crew was available for mission", 4, ScreenMessageStyle.UPPER_CENTER); return false; } return true; } private bool AddCrew(Part p, ProtoCrewMember kerbal) { p.AddCrewmember(kerbal); kerbal.rosterStatus = ProtoCrewMember.RosterStatus.Assigned; if (kerbal.seat != null) kerbal.seat.SpawnCrew(); return (true); } private void handleUnloadCrew(Vessel ves, bool savereturn) { foreach (Part p in ves.parts) { if (p.CrewCapacity > 0 && p.protoModuleCrew.Count > 0) { for (int i = p.protoModuleCrew.Count - 1; i >= 0; i--) { unloadCrew(p.protoModuleCrew[i], p, savereturn); } } } ves.DespawnCrew(); } private void unloadCrew(ProtoCrewMember crew, Part p, bool savereturn) { p.RemoveCrewmember(crew); if (savereturn) { crew.rosterStatus = ProtoCrewMember.RosterStatus.Available; } else { if (HighLogic.CurrentGame.Parameters.Difficulty.MissingCrewsRespawn) { crew.rosterStatus = ProtoCrewMember.RosterStatus.Missing; } else { crew.rosterStatus = ProtoCrewMember.RosterStatus.Dead; } } } private bool staticorbit() { //Determine deviation between saved values and current values if they don't changed to much update the staticTime and return staticTime if not return zero. //the parameter AnomalyAtEpoch changes over time and must be excluded from analysis float MaxDeviationValue = 10; bool[] parameters = new bool[5]; parameters[0] = false; parameters[1] = false; parameters[2] = false; //lenght if (MaxDeviationValue / 100 > Math.Abs(((vessel.orbit.semiMajorAxis - SMAsave) / SMAsave))) { parameters[0] = true; } //ratio if (MaxDeviationValue / 100 > Math.Abs(vessel.orbit.eccentricity - ECCsave)) { parameters[1] = true; } float angleD = MaxDeviationValue; //angle if (angleD > Math.Abs(vessel.orbit.inclination - INCsave) || angleD > Math.Abs(Math.Abs(vessel.orbit.inclination - INCsave) - 360)) { parameters[2] = true; } if (parameters[0] == false || parameters[1] == false || parameters[2] == false) { return (false); } else { return (true); } } private void handleAutoDepart() { if (autoDepartAllowed(commercialvehicleOffering) && vesselClean(vessel) && returnResourcesAvailable(commercialvehicleOffering) && minimalCrewPresent(commercialvehicleOffering)) { RmmUtil.ToMapView(); RmmContract.HandleContracts(vessel, false, true); if (commercialvehicleOffering.SafeReturn && HighLogic.CurrentGame.Mode == Game.Modes.CAREER) { Funding.Instance.AddFunds(commercialvehicleOffering.VehicleReturnFee + cargoFee(), TransactionReasons.VesselRecovery); } handleUnloadCrew(vessel, commercialvehicleOffering.SafeReturn); vessel.Unload(); vessel.Die(); ScreenMessages.PostScreenMessage(commercialvehicleOffering.VehicleName + " returned to " + RmmUtil.HomeBodyName(), 4, ScreenMessageStyle.UPPER_CENTER); } else { vehicleAutoDepart = false; } } private double cargoFee() { double fee = 0.0; if (commercialvehicleOffering.ReturnCargoMass == 0) { return 0; } double cargoMass = commercialvehicleOffering.ReturnCargoMass; string[] cargoArray = new string[0]; //RmmUtil.GetCargoArray(vessel, commercialvehicleOffering.ReturnResources, ref cargoArray); orderCargoArray(ref cargoArray); foreach (String s in cargoArray) { foreach (Part p in vessel.parts) { foreach (PartResource r in p.Resources) { if (r.info.name == s) { if (r.amount != 0) { if (RmmUtil.Mass(r.info.name, r.amount) <= cargoMass) { fee = fee + RmmUtil.Cost(r.info.name, r.amount); cargoMass = cargoMass - RmmUtil.Mass(r.info.name, r.amount); } else { fee = fee + ((cargoMass / RmmUtil.Mass(r.info.name, r.amount)) * RmmUtil.Cost(r.info.name, r.amount)); return fee; } } } } } } return fee; } private void orderCargoArray(ref string[] cargoArray) { string[] unorderCargoArray = new string[cargoArray.Length]; double[] costPerMass = new double[cargoArray.Length]; for (int i = 0; i < cargoArray.Length; i++) { unorderCargoArray[i] = cargoArray[i]; PartResourceDefinition prd = PartResourceLibrary.Instance.GetDefinition(cargoArray[i]); costPerMass[i] = prd.unitCost / prd.density; } for (int u = 0; u < cargoArray.Length; u++) { int highestCargoResource = -1; for (int i = 0; i < cargoArray.Length; i++) { if (unorderCargoArray[i] != "") { if (highestCargoResource != -1) { if (costPerMass[i] > costPerMass[highestCargoResource]) highestCargoResource = i; } else { highestCargoResource = i; } } } if (highestCargoResource != -1) { cargoArray[u] = unorderCargoArray[highestCargoResource]; unorderCargoArray[highestCargoResource] = ""; } } } private bool otherModulesCompletingArrival() { foreach (Part p in vessel.parts) { if (p.flightID != part.flightID) { foreach (PartModule pm in p.Modules) { if (pm.ClassName == "RMMModule") { RMMModule otherComOffMod = p.Modules.OfType<RMMModule>().FirstOrDefault(); if (otherComOffMod.completeArrival) { return (true); } } } } } return (false); } private bool autoDepartAllowed(Mission Off) { if (offeringAllowed(Off)) { return (true); } else { ScreenMessages.PostScreenMessage("not rated for this orbit", 4, ScreenMessageStyle.UPPER_CENTER); return (false); } } private bool vesselClean(Vessel ves) { if (commercialvehiclePartCount >= RmmUtil.CountVesselParts(ves)) { return (true); } else { ScreenMessages.PostScreenMessage("vessel in unknown configuration for return", 4, ScreenMessageStyle.UPPER_CENTER); return (false); } } private bool minimalCrewPresent(Mission Off) { if (Off.MinimumCrew == 0) { return (true); } if (Off.MinimumCrew > RmmUtil.AstronautCrewCount(vessel)) { ScreenMessages.PostScreenMessage("not enough crew for return", 4, ScreenMessageStyle.UPPER_CENTER); return (false); } if (!Off.SafeReturn && RmmUtil.CrewCount(vessel) > 0) { ScreenMessages.PostScreenMessage("not rated for safe crew return", 4, ScreenMessageStyle.UPPER_CENTER); return (false); } return (true); } private bool returnResourcesAvailable(Mission Off) { if (Off.ReturnResources == "") { return (true); } string[] SplitArray = Off.ReturnResources.Split(','); string[] arrResource = new string[0]; //RmmUtil.DetermineProppellantArray(vessel, ref arrResource); foreach (String st in SplitArray) { string[] SplatArray = st.Split(':'); string resourceName = SplatArray[0].Trim(); double amount = Convert.ToDouble(SplatArray[1].Trim()); if (!arrResource.Contains(resourceName)) { ScreenMessages.PostScreenMessage("vessel in unknown configuration for return", 4, ScreenMessageStyle.UPPER_CENTER); return (false); } if (amount * 0.99 > RmmUtil.ReadResource(vessel, resourceName)) { ScreenMessages.PostScreenMessage("not enough resources for return", 4, ScreenMessageStyle.UPPER_CENTER); return (false); } } return (true); } private bool returnCargoMassNotExceeded(Mission Off) { //if (Off.ReturnCargoMass == 0.0 || RmmUtil.GetCargoMass(vessel, Off.ReturnResources) <= Off.ReturnCargoMass * 1.1) //{ // return true; //} //else //{ // ScreenMessages.PostScreenMessage("cargo mass exceeds rated amount", 4, ScreenMessageStyle.UPPER_CENTER); // return false; //} return true; } /// <summary> /// GUI Main /// </summary> /// <param name="windowID"></param> private void WindowGUIMain(int windowID) { GUI.DragWindow(new Rect(0, 0, 200, 30)); GUILayout.BeginVertical(); GUILayout.BeginHorizontal(); GUILayout.BeginVertical(); GUILayout.Label("Current:", RmmStyle.Instance.LabelStyle, GUILayout.Width(200)); if (GUILayout.Button(selectedOffering.Name, RmmStyle.Instance.ButtonStyle, GUILayout.Width(200), GUILayout.Height(22))) { GUIOffering = selectedOffering; intCrewCount = missionCrewCount; openGUIOffering(); } if (missionUnderway) { GUILayout.BeginHorizontal(); GUILayout.Label("Underway", RmmStyle.Instance.LabelStyle, GUILayout.Width(100)); if (GUILayout.Button("Cancel", RmmStyle.Instance.ButtonStyle, GUILayout.Width(100), GUILayout.Height(22))) { if (HighLogic.CurrentGame.Mode == Game.Modes.CAREER) { if (Planetarium.GetUniversalTime() < missionArrivalTime - selectedOffering.Time + 3600) { if (Funding.Instance.Funds > GUIOffering.Price) { Funding.Instance.AddFunds(GUIOffering.Price, TransactionReasons.VesselRecovery); } } } missionUnderway = false; } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.Label("ETA:", RmmStyle.Instance.LabelStyle, GUILayout.Width(35)); GUILayout.Label(timeETAString(missionArrivalTime - Planetarium.GetUniversalTime()), RmmStyle.Instance.LabelStyle, GUILayout.Width(165)); GUILayout.EndHorizontal(); } else { GUILayout.Label("", RmmStyle.Instance.LabelStyle, GUILayout.Width(100)); } GUILayout.EndVertical(); GUILayout.Label(" ", RmmStyle.Instance.LabelStyle, GUILayout.Width(10)); GUILayout.BeginVertical(); missionRepeat = GUILayout.Toggle(missionRepeat, "Repeat"); GUILayout.Label("Repeat Delay:", RmmStyle.Instance.LabelStyle, GUILayout.Width(100)); GUILayout.BeginHorizontal(); if (GUILayout.Button("<", RmmStyle.Instance.ButtonStyle, GUILayout.Width(15), GUILayout.Height(15))) { if (missionRepeatDelay >= 1) { missionRepeatDelay -= (missionRepeatDelay / 10 > 1 ? missionRepeatDelay/10 : 1); } } GUILayout.Label( missionRepeatDelay.ToString(), RmmStyle.Instance.LabelStyle, GUILayout.Width(25)); if (GUILayout.Button(">", RmmStyle.Instance.ButtonStyle, GUILayout.Width(15), GUILayout.Height(15))) { if (missionRepeatDelay <= 999) { missionRepeatDelay += (missionRepeatDelay / 10 > 1 ? missionRepeatDelay / 10 : 1); } if (missionRepeatDelay > 999) { missionRepeatDelay = 999; } } GUILayout.Label("days", RmmStyle.Instance.LabelStyle, GUILayout.Width(30)); GUILayout.EndHorizontal(); GUILayout.EndVertical(); GUILayout.EndHorizontal(); scrollPositionAvailableCommercialOfferings = GUILayout.BeginScrollView(scrollPositionAvailableCommercialOfferings, false, true, GUILayout.Width(200), GUILayout.Height(300)); foreach (Mission Off in OfferingsList) { if (GUILayout.Button(Off.Name, RmmStyle.Instance.ButtonStyle, GUILayout.Width(165), GUILayout.Height(22))) { GUIOffering = Off; if (GUIOffering.MinimumCrew > 0) { if (GUIOffering.MinimumCrew < GUIOffering.MaximumCrew) { intCrewCount = GUIOffering.MaximumCrew; } else { intCrewCount = GUIOffering.MinimumCrew; } } else if (GUIOffering.MinimumCrew < GUIOffering.MaximumCrew) { intCrewCount = GUIOffering.MaximumCrew; } else if (GUIOffering.MinimumCrew == 0 && GUIOffering.MaximumCrew == 0) { intCrewCount = 0; } openGUIOffering(); } } GUILayout.EndScrollView(); //development mode buttons if (DevMode) { if (GUILayout.Button("Docking Stage 2")) { dockStage2(); } if (GUILayout.Button("Docking Stage 3")) { dockStage3(); } if (GUILayout.Button("Save vessel")) { ConfigNode savenode = new ConfigNode(); vessel.BackupVessel(); vessel.protoVessel.Save(savenode); savenode.Save(RmmUtil.GamePath + RmmUtil.CommercialOfferingsPath + Path.DirectorySeparatorChar + "Missions" + Path.DirectorySeparatorChar + "DevMode" + Path.DirectorySeparatorChar + "vesselfile"); } } // if (GUILayout.Button("Close", RmmStyle.Instance.ButtonStyle, GUILayout.Width(200), GUILayout.Height(22))) { closeGUIMain(); } GUILayout.EndVertical(); } // [KSPEvent(name = "ordering", isDefault = false, guiActive = true, guiName = "Available Missions")] public void ordering() { openGUIMain(); } private void drawGUIMain() { windowPosGUIMain.xMin = windowGUIMainX; windowPosGUIMain.yMin = windowGUIMainY; windowPosGUIMain.width = windowGUIMainWidth; windowPosGUIMain.height = 450; windowPosGUIMain = GUILayout.Window(3404, windowPosGUIMain, WindowGUIMain, "Docking Port " + PortCode, RmmStyle.Instance.WindowStyle); } public void openGUIMain() { loadOfferings(); renderGUIMain = true; } public void closeGUIMain() { renderGUIMain = false; } public void loadOfferings() { OfferingsList.Clear(); loadOfferingsDirectory(RmmUtil.GamePath + Path.DirectorySeparatorChar + "GameData"); if (missionFolderName != "") { foreach (Mission Off in OfferingsList) { if (Off.FolderPath == missionFolderName) { selectedOffering = Off; } } } } private void loadOfferingsDirectory(string searchDirectory) { if (File.Exists(searchDirectory + Path.DirectorySeparatorChar + "CommercialOfferingsPackMarkerFile")) { string[] directoryOfferings = Directory.GetDirectories(searchDirectory); foreach (String dir in directoryOfferings) { if (File.Exists(dir + Path.DirectorySeparatorChar + Mission.MISSION_FILE)) { string folderPath = dir.Substring(RmmUtil.GamePath.ToString().Length, dir.Length - RmmUtil.GamePath.ToString().Length); Mission Off = Mission.GetMissionByPath(folderPath); if (offeringAllowed(Off)) { OfferingsList.Add(Off); } } } } else { string[] searchDirectories = Directory.GetDirectories(searchDirectory); foreach (String dir in searchDirectories) { loadOfferingsDirectory(dir); } } } private bool isCurrentCampaign(Mission off) { if (isACampaign(off)) { if (off.CompanyName.Length >= 14 && off.CompanyName.Substring(14) == HighLogic.SaveFolder) { return (true); } } else { return (true); } return (false); } private bool isACampaign(Mission off) { if (off.CompanyName.Length >= 14 && off.CompanyName.Substring(0, 14) == "KSPCAMPAIGN:::") return (true); return (false); } /// <summary> /// GUI Offering /// </summary> /// <param name="windowID"></param> private void WindowGUIOffering(int windowID) { GUI.DragWindow(new Rect(0, 0, 500, 30)); GUILayout.BeginVertical(); if (!isACampaign(GUIOffering)) { GUILayout.BeginHorizontal(); GUILayout.Label("Company:", RmmStyle.Instance.LabelStyle, GUILayout.Width(100)); GUILayout.Label(GUIOffering.CompanyName, RmmStyle.Instance.LabelStyle, GUILayout.Width(200)); GUILayout.EndHorizontal(); } GUILayout.BeginHorizontal(); GUILayout.Label("Vehicle:", RmmStyle.Instance.LabelStyle, GUILayout.Width(100)); GUILayout.Label(GUIOffering.VehicleName, RmmStyle.Instance.LabelStyle, GUILayout.Width(200)); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.Label("Launch System:", RmmStyle.Instance.LabelStyle, GUILayout.Width(100)); GUILayout.Label(GUIOffering.LaunchSystemName, RmmStyle.Instance.LabelStyle, GUILayout.Width(200)); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.Label("Price:", RmmStyle.Instance.LabelStyle, GUILayout.Width(100)); GUILayout.Label(GUIOffering.Price.ToString() + ((GUIOffering.VehicleReturnFee > 0) ? " (" + (GUIOffering.Price - GUIOffering.VehicleReturnFee).ToString() + " with vehicle return)" : ""), RmmStyle.Instance.LabelStyle, GUILayout.Width(250)); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.Label("Arrival in:", RmmStyle.Instance.LabelStyle, GUILayout.Width(100)); GUILayout.Label(timeString(GUIOffering.Time), RmmStyle.Instance.LabelStyle, GUILayout.Width(200)); GUILayout.EndHorizontal(); if (GUIOffering.MinimumCrew > 0) { if (GUIOffering.MinimumCrew < GUIOffering.MaximumCrew) { GUILayout.BeginHorizontal(); GUILayout.Label("Minimal crew required:", RmmStyle.Instance.LabelStyle, GUILayout.Width(150)); GUILayout.Label(GUIOffering.MinimumCrew.ToString(), RmmStyle.Instance.LabelStyle, GUILayout.Width(200)); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.Label("Maximum crew capacity:", RmmStyle.Instance.LabelStyle, GUILayout.Width(150)); GUILayout.Label(GUIOffering.MaximumCrew.ToString(), RmmStyle.Instance.LabelStyle, GUILayout.Width(200)); GUILayout.EndHorizontal(); } else { GUILayout.BeginHorizontal(); GUILayout.Label("Crew:", RmmStyle.Instance.LabelStyle, GUILayout.Width(100)); GUILayout.Label(GUIOffering.MinimumCrew.ToString(), RmmStyle.Instance.LabelStyle, GUILayout.Width(200)); GUILayout.EndHorizontal(); } } else if (GUIOffering.MinimumCrew < GUIOffering.MaximumCrew) { GUILayout.BeginHorizontal(); GUILayout.Label("Crew capacity:", RmmStyle.Instance.LabelStyle, GUILayout.Width(100)); GUILayout.Label(GUIOffering.MaximumCrew.ToString(), RmmStyle.Instance.LabelStyle, GUILayout.Width(200)); GUILayout.EndHorizontal(); } else if (GUIOffering.MinimumCrew == 0 && GUIOffering.MaximumCrew == 0) { GUILayout.BeginHorizontal(); GUILayout.Label("Unmanned", RmmStyle.Instance.LabelStyle, GUILayout.Width(100)); GUILayout.EndHorizontal(); } if (!GUIOffering.ReturnEnabled) { GUILayout.BeginHorizontal(); GUILayout.Label("No return mission", RmmStyle.Instance.LabelStyle, GUILayout.Width(300)); GUILayout.EndHorizontal(); } else if (!GUIOffering.SafeReturn) { GUILayout.BeginHorizontal(); GUILayout.Label("No safe return mission", RmmStyle.Instance.LabelStyle, GUILayout.Width(300)); GUILayout.EndHorizontal(); } if (GUIOffering.ReturnResources != "") { GUILayout.Label("Required return resources: ", RmmStyle.Instance.LabelStyle, GUILayout.Width(300)); string[] SplitArray = GUIOffering.ReturnResources.Split(','); foreach (String st in SplitArray) { string[] SplatArray = st.Split(':'); string resourceName = SplatArray[0].Trim(); double amount = Convert.ToDouble(SplatArray[1].Trim()); GUILayout.Label(" " + resourceName + ": " + RoundToSignificantDigits(amount,4).ToString(), RmmStyle.Instance.LabelStyle, GUILayout.Width(300)); } } if (GUIOffering.ReturnCargoMass != 0.0) { GUILayout.BeginHorizontal(); GUILayout.Label("Return cargo mass: " + RoundToSignificantDigits(GUIOffering.ReturnCargoMass,3).ToString(), RmmStyle.Instance.LabelStyle, GUILayout.Width(300)); GUILayout.EndHorizontal(); } GUILayout.BeginHorizontal(); GUILayout.Label("", RmmStyle.Instance.RedLabelStyle, GUILayout.Width(430)); if (GUILayout.Button("Delete", RmmStyle.Instance.ButtonStyle, GUILayout.Width(70), GUILayout.Height(22))) { if (Directory.Exists(RmmUtil.GamePath + GUIOffering.FolderPath)) { DeleteDirectory(RmmUtil.GamePath + GUIOffering.FolderPath); closeGUIOffering(); loadOfferings(); } } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); if (!missionUnderway) { if (GUILayout.Button("Procure", RmmStyle.Instance.ButtonStyle, GUILayout.Width(300), GUILayout.Height(22))) { if (!missionUnderway) { GUIMission = GUIOffering; openGUIMission(); } } } if (GUILayout.Button("Close", RmmStyle.Instance.ButtonStyle, GUILayout.Width(200), GUILayout.Height(22))) { closeGUIOffering(); } GUILayout.EndHorizontal(); GUILayout.EndVertical(); } private void drawGUIOffering() { windowPosGUIOffering = GUILayout.Window(3414, windowPosGUIOffering, WindowGUIOffering, GUIOffering.Name, RmmStyle.Instance.WindowStyle); } public void openGUIOffering() { print(GUIOffering.Name + " in folder: " + GUIOffering.FolderPath); renderGUIOffering = true; } public void closeGUIOffering() { renderGUIOffering = false; renderGUIMission = false; renderGUIPrefCrew = false; } /// <summary> /// GUI Order /// </summary> /// <param name="windowID"></param> private void WindowGUIMission(int windowID) { GUI.DragWindow(new Rect(0, 0, 300, 30)); GUILayout.BeginVertical(); if (!isACampaign(GUIMission)) { GUILayout.BeginHorizontal(); GUILayout.Label("Mission:", RmmStyle.Instance.LabelStyle, GUILayout.Width(100)); GUILayout.Label(GUIMission.Name, RmmStyle.Instance.LabelStyle, GUILayout.Width(200)); GUILayout.EndHorizontal(); } if (GUIOffering.MinimumCrew < GUIOffering.MaximumCrew) { GUILayout.BeginHorizontal(); GUILayout.Label("Planned crew:", RmmStyle.Instance.LabelStyle, GUILayout.Width(100)); GUILayout.Label(intCrewCount.ToString(), RmmStyle.Instance.LabelStyle, GUILayout.Width(50)); strCrewCount = GUILayout.TextField(strCrewCount, 3, GUILayout.Width(50)); if (GUILayout.Button("set", RmmStyle.Instance.ButtonStyle, GUILayout.Width(50), GUILayout.Height(22))) { int.TryParse(strCrewCount, out intCrewCount); if (intCrewCount < GUIOffering.MinimumCrew) { intCrewCount = GUIOffering.MinimumCrew; } if (intCrewCount > GUIOffering.MaximumCrew) { intCrewCount = GUIOffering.MaximumCrew; } } GUILayout.EndHorizontal(); } if (GUIOffering.MaximumCrew > 0) { GUILayout.BeginHorizontal(); if (GUILayout.Button("set preferred crew", RmmStyle.Instance.ButtonStyle, GUILayout.Width(300), GUILayout.Height(20))) { openGUIPrefCrew(); } GUILayout.EndHorizontal(); GUILayout.Label(" ", RmmStyle.Instance.LabelStyle, GUILayout.Width(100)); } if (GUILayout.Button("Confirm", RmmStyle.Instance.ButtonStyle, GUILayout.Width(300), GUILayout.Height(22))) { procureOffering(GUIOffering,false); } if (GUILayout.Button("Close", RmmStyle.Instance.ButtonStyle, GUILayout.Width(300), GUILayout.Height(22))) { closeGUIMission(); } GUILayout.EndVertical(); } private void drawGUIMission() { windowPosGUIMission = GUILayout.Window(3444, windowPosGUIMission, WindowGUIMission, "Mission", RmmStyle.Instance.WindowStyle); } public void openGUIMission() { renderGUIMission = true; } public void closeGUIMission() { renderGUIMission = false; renderGUIPrefCrew = false; } public void procureOffering(Mission Off,bool repeat) { if (missionUnderway == true) { ScreenMessages.PostScreenMessage("already a mission underway", 4, ScreenMessageStyle.UPPER_CENTER); return; } if (!offeringAllowed(Off)) { ScreenMessages.PostScreenMessage("not rated for this orbit", 4, ScreenMessageStyle.UPPER_CENTER); return; } if (HighLogic.CurrentGame.Mode == Game.Modes.CAREER) { if (Funding.Instance.Funds > Off.Price) { Funding.Instance.AddFunds(-Off.Price, TransactionReasons.VesselRollout); } else { ScreenMessages.PostScreenMessage("insufficient funds", 4, ScreenMessageStyle.UPPER_CENTER); return; } } missionUnderway = true; missionFolderName = Off.FolderPath; if (!repeat) { missionArrivalTime = (float)(Planetarium.GetUniversalTime() + Off.Time); missionCrewCount = intCrewCount; } else { missionArrivalTime = (float)(Planetarium.GetUniversalTime() + (Off.Time > (missionRepeatDelay * 21600) ? Off.Time : (missionRepeatDelay * 21600))); } SMAsave = (float)vessel.orbit.semiMajorAxis; ECCsave = (float)vessel.orbit.eccentricity; INCsave = (float)vessel.orbit.inclination; selectedOffering = Off; closeGUIOffering(); } /// <summary> /// GUI PrefCrew /// </summary> /// <param name="windowID"></param> private void WindowGUIPrefCrew(int windowID) { GUI.DragWindow(new Rect(0, 0, 200, 30)); GUILayout.BeginVertical(); GUILayout.Label("Preferred:", RmmStyle.Instance.LabelStyle, GUILayout.Width(100)); scrollPositionPreferredCrew = GUILayout.BeginScrollView(scrollPositionPreferredCrew, false, true, GUILayout.Width(200), GUILayout.Height(200)); foreach (ProtoCrewMember cr in preferredCrewList) { if (GUILayout.Button(cr.type == ProtoCrewMember.KerbalType.Tourist ? cr.name + " T" : cr.name, RmmStyle.Instance.ButtonStyle, GUILayout.Width(165), GUILayout.Height(22))) { preferredCrewList.Remove(cr); } } GUILayout.EndScrollView(); GUILayout.Label("Roster:", RmmStyle.Instance.LabelStyle, GUILayout.Width(100)); scrollPositionAvailableCrew = GUILayout.BeginScrollView(scrollPositionAvailableCrew, false, true, GUILayout.Width(200), GUILayout.Height(300)); foreach (ProtoCrewMember cr in HighLogic.CurrentGame.CrewRoster.Crew) { if (cr.rosterStatus != ProtoCrewMember.RosterStatus.Dead) { if (GUILayout.Button(cr.name, RmmStyle.Instance.ButtonStyle, GUILayout.Width(165), GUILayout.Height(22))) { bool alreadyAdded = false; foreach (ProtoCrewMember cre in preferredCrewList) { if (cre.name == cr.name) { alreadyAdded = true; } } if (!alreadyAdded) { preferredCrewList.Add(cr); } } } } foreach (ProtoCrewMember to in HighLogic.CurrentGame.CrewRoster.Tourist) { if (GUILayout.Button(to.name + " T", RmmStyle.Instance.ButtonStyle, GUILayout.Width(165), GUILayout.Height(22))) { bool alreadyAdded = false; foreach (ProtoCrewMember cre in preferredCrewList) { if (cre.name == to.name) { alreadyAdded = true; } } if (!alreadyAdded) { preferredCrewList.Add(to); } } } GUILayout.EndScrollView(); GUILayout.BeginHorizontal(); if (GUILayout.Button("Set", RmmStyle.Instance.ButtonStyle, GUILayout.Width(100), GUILayout.Height(22))) { missionPreferedCrew = ""; foreach (ProtoCrewMember cr in preferredCrewList) { missionPreferedCrew = missionPreferedCrew + cr.name + ","; } closeGUIPrefCrew(); } if (GUILayout.Button("Close", RmmStyle.Instance.ButtonStyle, GUILayout.Width(100), GUILayout.Height(22))) { closeGUIPrefCrew(); } GUILayout.EndHorizontal(); GUILayout.EndVertical(); } private void drawGUIPrefCrew() { windowPosGUIPrefCrew = GUILayout.Window(3447, windowPosGUIPrefCrew, WindowGUIPrefCrew, "Crew", RmmStyle.Instance.WindowStyle); } public void openGUIPrefCrew() { preferredCrewList.Clear(); string[] prefCrewNames = new string[0]; getPreferredCrewNames(ref prefCrewNames); foreach (String name in prefCrewNames) { foreach (ProtoCrewMember cr in HighLogic.CurrentGame.CrewRoster.Crew) { if (name == cr.name) { preferredCrewList.Add(cr); } } foreach (ProtoCrewMember to in HighLogic.CurrentGame.CrewRoster.Tourist) { if (name == to.name) { preferredCrewList.Add(to); } } } renderGUIPrefCrew = true; } public void closeGUIPrefCrew() { renderGUIPrefCrew = false; } private void getPreferredCrewNames(ref string[] names) { string[] SplitArray = missionPreferedCrew.Split(','); Array.Resize(ref names, SplitArray.Length); Array.Copy(SplitArray, names, SplitArray.Length); } private double RoundToSignificantDigits(double d, int digits) { if (d == 0) return 0; double scale = Math.Pow(10, Math.Floor(Math.Log10(Math.Abs(d))) + 1); return scale * Math.Round(d / scale, digits); } public static void DeleteDirectory(string target_dir) { string[] files = Directory.GetFiles(target_dir); string[] dirs = Directory.GetDirectories(target_dir); foreach (string file in files) { File.SetAttributes(file, FileAttributes.Normal); File.Delete(file); } foreach (string dir in dirs) { DeleteDirectory(dir); } Directory.Delete(target_dir, false); } /// <summary> /// depart /// </summary> [KSPEvent(name = "setAutoDepart", isDefault = false, guiActive = false, guiName = "Commence Return")] public void setAutoDepart() { if (RmmUtil.IsDocked(vessel, part)) { ModuleDockingNode DockNode = part.Modules.OfType<ModuleDockingNode>().FirstOrDefault(); DockNode.Undock(); } vehicleAutoDepart = true; nextLogicTime = Planetarium.GetUniversalTime() + 2; } /// <summary> /// general functions /// </summary> /// <returns></returns> /// private bool offeringAllowed(Mission Off) { if (vessel.mainBody.name == Off.Body && (RmmUtil.OrbitAltitude(vessel) < 4 || Off.MaxOrbitAltitude == 0) && isCurrentCampaign(Off) && vessel.situation == Vessel.Situations.ORBITING) { return (true); } else { return (false); } } //return a day-hour-minute-seconds-time format for the time public string timeString(double time) { int days = 0; int hours = 0; int minutes = 0; int seconds = 0; string strT = ""; bool positive; if (time >= 0) { positive = true; } else { positive = false; } days = (int)Math.Floor(time / 21600); time = time - (days * 21600); hours = (int)Math.Floor(time / 3600); time = time - (hours * 3600); minutes = (int)Math.Floor(time / 60); time = time - (minutes * 60); seconds = (int)Math.Floor(time); if (days > 0) { strT = days.ToString() + "d"; strT = (hours != 0) ? strT + hours.ToString() + "h" : strT; strT = (minutes != 0) ? strT + minutes.ToString() + "m" : strT; strT = (seconds != 0) ? strT + seconds.ToString() + "s" : strT; } else if (hours > 0) { strT = hours.ToString() + "h"; strT = (minutes != 0) ? strT + minutes.ToString() + "m" : strT; strT = (seconds != 0) ? strT + seconds.ToString() + "s" : strT; } else if (minutes > 0) { strT = minutes.ToString() + "m"; strT = (seconds != 0) ? strT + seconds.ToString() + "s" : strT; } else if (seconds > 0) { strT = seconds.ToString() + "s"; } //strT = days.ToString() + "d" + hours.ToString() + "h" + minutes.ToString() + "m" + seconds + "s"; if (positive) return (strT); else return ("-" + strT); } public string timeETAString(double time) { int days = 0; int hours = 0; int minutes = 0; int seconds = 0; string strT = ""; if (time >= 0) { days = (int)Math.Floor(time / 21600); time = time - (days * 21600); hours = (int)Math.Floor(time / 3600); time = time - (hours * 3600); minutes = (int)Math.Floor(time / 60); time = time - (minutes * 60); seconds = (int)Math.Floor(time); if (days > 1) { strT = days.ToString() + "d"; } else if (days > 0) { strT = days.ToString() + "d" + hours.ToString() + "h"; } else if (hours > 0) { strT = hours.ToString() + "h"; } else { strT = "soon(TM)"; } } else { if (time > -3600) { strT = "come back later"; } else { strT = "maybe later"; } } return (strT); } /// <summary> /// Register Port Code logic /// </summary> [KSPEvent(name = "register", isDefault = false, guiActive = true, guiName = "Register Docking Port")] public void register() { openGUIRegister(); } private void WindowGUIRegister(int windowID) { GUILayout.BeginHorizontal(); GUILayout.Label("Docking Port Code"); StrPortCode = GUILayout.TextField(StrPortCode, 15, GUILayout.Width(100)); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); if (GUILayout.Button("Register", GUILayout.Width(60))) { if (StrPortCode != "") { PortCode = StrPortCode; closeGUIRegister(); } } if (GUILayout.Button("Cancel", GUILayout.Width(60))) { closeGUIRegister(); } GUILayout.EndHorizontal(); } private void drawGUIRegister() { windowPosGUIRegister = GUI.Window(157, windowPosGUIRegister, WindowGUIRegister, "Register", RmmStyle.Instance.WindowStyle); } public void openGUIRegister() { renderGUIRegister = true; } public void closeGUIRegister() { renderGUIRegister = false; } } }
37.988607
251
0.504908
[ "BSD-2-Clause" ]
PrivateFlip/RoutineMissionManager
GameData/RoutineMissionManager/licences and source/CommercialOfferings/Routine.cs
73,358
C#
using System.Collections.Generic; using SSSGroup.Utilites.FormulaProcessor.DataTypes; namespace SSSGroup.Utilites.FormulaProcessor { public static class Calculator { public static string Evaluate(IEnumerable<Token> expression) { var stack = new Stack<Token>(); foreach (var token in expression) { if(token.Type==TokenType.Variable) stack.Push(token); var ft = new FormatTranslator(); if (token.Type != TokenType.Operator) continue; { var op2 = stack.Pop().ToString(); string smallRes; if (token.Value == "!") { smallRes = BaseMath.DoMath(ft.Factory(op2), token.Value); } else { var op1 = stack.Pop().ToString(); smallRes = BaseMath.DoMath(ft.Factory(op1), ft.Factory(op2), token.Value); } var v = new Token(TokenType.Variable, smallRes); stack.Push(v); } } return stack.Pop().ToString(); } } }
34.621622
98
0.459016
[ "MIT" ]
3sgr/DatacapOS
3sgrMath/3sgrMath/FormulaProcessor/Calculator.cs
1,283
C#
// (c) Copyright HutongGames, LLC 2010-2013. All rights reserved. #if !(UNITY_FLASH || UNITY_METRO) using System; using UnityEngine; namespace HutongGames.PlayMaker.Actions { [ActionCategory(ActionCategory.Application)] [Tooltip("Saves a Screenshot. NOTE: Does nothing in Web Player. On Android, the resulting screenshot is available some time later.")] public class TakeScreenshot : FsmStateAction { public enum Destination { MyPictures, PersistentDataPath, CustomPath } [Tooltip("Where to save the screenshot.")] public Destination destination; [Tooltip("Path used with Custom Path Destination option.")] public FsmString customPath; [RequiredField] public FsmString filename; [Tooltip("Add an auto-incremented number to the filename.")] public FsmBool autoNumber; [Tooltip("Factor by which to increase resolution.")] public FsmInt superSize; [Tooltip("Log saved file info in Unity console.")] public FsmBool debugLog; private int screenshotCount; public override void Reset() { destination = Destination.MyPictures; filename = ""; autoNumber = null; superSize = null; debugLog = null; } public override void OnEnter() { if (string.IsNullOrEmpty(filename.Value)) return; string screenshotPath; switch (destination) { case Destination.MyPictures: screenshotPath = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures); break; case Destination.PersistentDataPath: screenshotPath = Application.persistentDataPath; break; case Destination.CustomPath: screenshotPath = customPath.Value; break; default: screenshotPath = ""; break; } screenshotPath = screenshotPath.Replace("\\","/") + "/"; var screenshotFullPath = screenshotPath + filename.Value + ".png"; if (autoNumber.Value) { while (System.IO.File.Exists(screenshotFullPath)) { screenshotCount++; screenshotFullPath = screenshotPath + filename.Value + screenshotCount + ".png"; } } if (debugLog.Value) { Debug.Log("TakeScreenshot: " + screenshotFullPath); } Application.CaptureScreenshot(screenshotFullPath, superSize.Value); Finish(); } } } #endif
27.831579
138
0.596067
[ "Apache-2.0" ]
Drestat/ARfun
ARfun/Assets/PlayMaker/Actions/TakeScreenshot.cs
2,644
C#
using System; using System.Collections.Generic; using System.Text; namespace Application.Hosts.Ports.Events { public class TaskAddedEvent { public string Description { get; } public TaskAddedEvent(string description) { Description = description; } } }
18.294118
49
0.646302
[ "MIT" ]
alvesdm/HexagonalDDDMicroserviceCombo
src/Application.Hosts.Ports/Events/TaskAddedEvent.cs
313
C#
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using Xunit; namespace WebIntegration.Tests { // This project can output the Class library as a NuGet Package. // To enable this option, right-click on the project and select the Properties menu item. In the Build tab select "Produce outputs on build". public class PrimeTests { private readonly TestServer _server; private readonly HttpClient _client; public PrimeTests() { // Arrange _server = new TestServer(new WebHostBuilder() .UseStartup<Startup>()); _client = _server.CreateClient(); } [Fact] public async Task ReturnHelloWorld() { // Act var response = await _client.GetAsync("/"); response.EnsureSuccessStatusCode(); var responseString = await response.Content.ReadAsStringAsync(); // Assert Assert.Equal("Hello World!", responseString); } private async Task<string> GetCheckPrimeResponseString( string querystring = "") { var request = "/checkprime"; if (!string.IsNullOrEmpty(querystring)) { request += "?" + querystring; } var response = await _client.GetAsync(request); response.EnsureSuccessStatusCode(); return await response.Content.ReadAsStringAsync(); } [Fact] public async Task ReturnInstructionsGivenEmptyQueryString() { // Act var responseString = await GetCheckPrimeResponseString(); // Assert Assert.Equal("Pass in a number to check in the form /checkprime?5", responseString); } [Fact] public async Task ReturnPrimeGiven5() { // Act var responseString = await GetCheckPrimeResponseString("5"); // Assert Assert.Equal("5 is prime!", responseString); } [Fact] public async Task ReturnNotPrimeGiven6() { // Act var responseString = await GetCheckPrimeResponseString("6"); // Assert Assert.Equal("6 is NOT prime!", responseString); } } }
28.359551
145
0.56775
[ "MIT" ]
shahedc/MinimalCore2Web
WebIntegration/Tests/PrimeTests.cs
2,526
C#
namespace ReferenceAnalyzer.Core.Models { public record Project(string Name, string Path, ReferencesReport? Report = null, EAnalysisStage AnalysisStage = EAnalysisStage.NotStarted) { public ReferencesReport Report { get; set; } = Report ?? ReferencesReport.Empty; public static Project Empty => new("", "", ReferencesReport.Empty); } }
36.5
142
0.715068
[ "MIT" ]
OptiNav/ReferenceAnalyzer
src/ReferenceAnalyzer.Core/Models/Project.cs
365
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace ProceduralModeling { [RequireComponent (typeof(MeshFilter), typeof(MeshRenderer))] [ExecuteInEditMode] public abstract class ProceduralModelingBase : MonoBehaviour { public Material material; public MeshFilter Filter { get { if(filter == null) { filter = GetComponent<MeshFilter>(); } return filter; } } public MeshRenderer Renderer { get { if(renderer == null) { renderer = GetComponent<MeshRenderer>(); } return renderer; } } MeshFilter filter; new MeshRenderer renderer; //[SerializeField] protected ProceduralModelingMaterial materialType = ProceduralModelingMaterial.UV; protected virtual void Start () { Rebuild(); } public void Rebuild() { if(Filter.sharedMesh != null) { if(Application.isPlaying) { Destroy(Filter.sharedMesh); } else { DestroyImmediate(Filter.sharedMesh); } } Filter.sharedMesh = Build(); Renderer.sharedMaterial = material; } //protected virtual Material LoadMaterial(ProceduralModelingMaterial type) { // switch(type) { // case ProceduralModelingMaterial.UV: // return Resources.Load<Material>("Materials/UV"); // case ProceduralModelingMaterial.Normal: // return Resources.Load<Material>("Materials/Normal"); // } // return Resources.Load<Material>("Materials/Standard"); //} protected abstract Mesh Build(); } }
21.867647
103
0.691325
[ "MIT" ]
kaiware007/UnityCloudOfSea
Assets/ProceduralModeling/Scripts/ProceduralModelingBase.cs
1,489
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.DataFactory.V20180601.Inputs { /// <summary> /// SAP Business Warehouse Open Hub Destination Linked Service. /// </summary> public sealed class SapOpenHubLinkedServiceArgs : Pulumi.ResourceArgs { [Input("annotations")] private InputList<object>? _annotations; /// <summary> /// List of tags that can be used for describing the linked service. /// </summary> public InputList<object> Annotations { get => _annotations ?? (_annotations = new InputList<object>()); set => _annotations = value; } /// <summary> /// Client ID of the client on the BW system where the open hub destination is located. (Usually a three-digit decimal number represented as a string) Type: string (or Expression with resultType string). /// </summary> [Input("clientId")] public Input<object>? ClientId { get; set; } /// <summary> /// The integration runtime reference. /// </summary> [Input("connectVia")] public Input<Inputs.IntegrationRuntimeReferenceArgs>? ConnectVia { get; set; } /// <summary> /// Linked service description. /// </summary> [Input("description")] public Input<string>? Description { get; set; } /// <summary> /// The encrypted credential used for authentication. Credentials are encrypted using the integration runtime credential manager. Type: string (or Expression with resultType string). /// </summary> [Input("encryptedCredential")] public Input<object>? EncryptedCredential { get; set; } /// <summary> /// Language of the BW system where the open hub destination is located. The default value is EN. Type: string (or Expression with resultType string). /// </summary> [Input("language")] public Input<object>? Language { get; set; } /// <summary> /// The Logon Group for the SAP System. Type: string (or Expression with resultType string). /// </summary> [Input("logonGroup")] public Input<object>? LogonGroup { get; set; } /// <summary> /// The hostname of the SAP Message Server. Type: string (or Expression with resultType string). /// </summary> [Input("messageServer")] public Input<object>? MessageServer { get; set; } /// <summary> /// The service name or port number of the Message Server. Type: string (or Expression with resultType string). /// </summary> [Input("messageServerService")] public Input<object>? MessageServerService { get; set; } [Input("parameters")] private InputMap<Inputs.ParameterSpecificationArgs>? _parameters; /// <summary> /// Parameters for linked service. /// </summary> public InputMap<Inputs.ParameterSpecificationArgs> Parameters { get => _parameters ?? (_parameters = new InputMap<Inputs.ParameterSpecificationArgs>()); set => _parameters = value; } /// <summary> /// Password to access the SAP BW server where the open hub destination is located. /// </summary> [Input("password")] public InputUnion<Inputs.AzureKeyVaultSecretReferenceArgs, Inputs.SecureStringArgs>? Password { get; set; } /// <summary> /// Host name of the SAP BW instance where the open hub destination is located. Type: string (or Expression with resultType string). /// </summary> [Input("server")] public Input<object>? Server { get; set; } /// <summary> /// SystemID of the SAP system where the table is located. Type: string (or Expression with resultType string). /// </summary> [Input("systemId")] public Input<object>? SystemId { get; set; } /// <summary> /// System number of the BW system where the open hub destination is located. (Usually a two-digit decimal number represented as a string.) Type: string (or Expression with resultType string). /// </summary> [Input("systemNumber")] public Input<object>? SystemNumber { get; set; } /// <summary> /// Type of linked service. /// Expected value is 'SapOpenHub'. /// </summary> [Input("type", required: true)] public Input<string> Type { get; set; } = null!; /// <summary> /// Username to access the SAP BW server where the open hub destination is located. Type: string (or Expression with resultType string). /// </summary> [Input("userName")] public Input<object>? UserName { get; set; } public SapOpenHubLinkedServiceArgs() { } } }
38.992424
211
0.613561
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/DataFactory/V20180601/Inputs/SapOpenHubLinkedServiceArgs.cs
5,147
C#
using Razor.Models; using System.Web.Mvc; namespace Razor.Controllers { public class HomeController : Controller { Product myProduct = new Product { ProductID = 1, Name = "Kayak", Description = "A boat for one person", Category = "Watersports", Price = 275M }; // GET: Home public ActionResult Index() { return View(myProduct); } public ActionResult NameAndPrice() { return View(myProduct); } public ActionResult DemoExpression() { ViewBag.ProductCount = 1; ViewBag.ExpressShip = true; ViewBag.ApplyDiscount = false; ViewBag.Supplier = null; return View(myProduct); } public ActionResult DemoArray() { Product[] array = { new Product {Name = "Kayak", Price = 275M }, new Product {Name = "Lifejacket", Price = 48.95M }, new Product {Name = "Soccer ball", Price = 19.50M }, new Product {Name = "Corner flag", Price = 34.95M } }; return View(array); } } }
24.627451
68
0.488057
[ "MIT" ]
plamenti/ProAsp.NetMvc5
5 - Working with Razor/Razor/Razor/Controllers/HomeController.cs
1,258
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using DotVVM.Framework.Configuration; namespace DotVVM.Framework.Hosting { public class AggregateMarkupFileLoader : IMarkupFileLoader { public List<IMarkupFileLoader> Loaders { get; private set; } = new List<IMarkupFileLoader>(); public AggregateMarkupFileLoader() { Loaders.Add(new DefaultMarkupFileLoader()); Loaders.Add(new EmbeddedMarkupFileLoader()); } /// <summary> /// Gets the markup file for the specified virtual path. /// </summary> public MarkupFile? GetMarkup(DotvvmConfiguration configuration, string virtualPath) { for (int i = 0; i < Loaders.Count; i++) { var result = Loaders[i].GetMarkup(configuration, virtualPath); if (result != null) { return result; } } return null; } /// <summary> /// Gets the markup file virtual path from the current request URL. /// </summary> public string GetMarkupFileVirtualPath(IDotvvmRequestContext context) { return context.Route!.VirtualPath; } } }
28.911111
101
0.582629
[ "Apache-2.0" ]
riganti/dotvvm
src/Framework/Framework/Hosting/AggregateMarkupFileLoader.cs
1,303
C#
using RMMVCookTool.CLI.Properties; using RMMVCookTool.Core.Compiler; using RMMVCookTool.Core.Utilities; using Spectre.Console; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.InteropServices; namespace RMMVCookTool.CLI { class Program { private static readonly Lazy<CompilerProject> newProject = new(() => new CompilerProject(), true); private static bool _testProject; private static int _compressProject = 3; private static string _sdkLocation; private static bool _settingsSet; private static int _checkDeletion = 1; private static void Main(string[] args) { #region Print App Info CompilerUtilities.StartEngineLogger("CompilerCLI", false); Console.WriteLine(Resources.SpilterText); Console.WriteLine(Resources.ProgramNameText); Console.WriteLine(Resources.ProgramVersionString, Assembly.GetExecutingAssembly().GetName().Version); Console.WriteLine(Resources.ProgramAuthorText); Console.WriteLine(Resources.ProgramLicenseText); Console.WriteLine(Resources.SpilterText); CompilerUtilities.RecordToLog($"Cook Tool CLI, version {Assembly.GetExecutingAssembly().GetName().Version} started.", 0); #endregion #region Command line arguments if (args.Length >= 1) { Rule argsTab = new(); argsTab.Title = Resources.CommandLineArgsTitle; argsTab.Alignment = Justify.Left; AnsiConsole.Write(argsTab); Table argsTable = new(); argsTable.AddColumn(Resources.SettingTitle); argsTable.AddColumn(Resources.ValueTitle); argsTable.Border = TableBorder.Rounded; CompilerUtilities.RecordToLog("Command Line Arguments loaded. Processing...", 0); for (int argnum = 0; argnum < args.Length; argnum++) { string stringBuffer; switch (args[argnum]) { //Set the SDK Location case "--SDKLocation": stringBuffer = args[argnum + 1]; _sdkLocation = stringBuffer.Replace("\"", ""); if (argnum <= args.Length - 1 && Directory.Exists(_sdkLocation) && File.Exists(Path.Combine(_sdkLocation, RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "nwjc.exe" : "nwjc"))) { CompilerUtilities.RecordToLog($"NW.js compiler found at {_sdkLocation}.", 0); argsTable.AddRow(Resources.SDKLocationEntry, _sdkLocation); Console.ResetColor(); } else { CompilerUtilities.RecordToLog($"NW.js compiler not found at {_sdkLocation}. Double check that the the nwjc executable is there.", 2); Console.ForegroundColor = ConsoleColor.DarkRed; Console.WriteLine(!Directory.Exists(_sdkLocation) ? Resources.SDKLocationInexistantText : Resources.CompilerMissingErrorText); Console.ResetColor(); Console.WriteLine(Resources.PushEnterToExitText); Console.ReadLine(); Environment.Exit(1); } break; //Set the Project Location. case "--ProjectLocation": stringBuffer = args[argnum + 1]; newProject.Value.ProjectLocation = stringBuffer.Replace("\"", ""); if (argnum <= args.Length - 1 && (Directory.Exists(newProject.Value.ProjectLocation) && File.Exists(Path.Combine(newProject.Value.ProjectLocation, "package.json")))) { CompilerUtilities.RecordToLog($"RPG Maker MV/MZ project found at {newProject.Value.ProjectLocation}.", 0); argsTable.AddRow(Resources.ProjectLocationEntry, newProject.Value.ProjectLocation); Console.ResetColor(); } else { CompilerUtilities.RecordToLog($"RPG Maker MV/MZ project was not found at {newProject.Value.ProjectLocation}.", 2); Console.ForegroundColor = ConsoleColor.DarkRed; Console.WriteLine(!File.Exists(Path.Combine(newProject.Value.ProjectLocation, "project.json")) ? Resources.JsonFileMissingErrorText : Resources.ProjectLocationInexistantText); Console.ResetColor(); Console.WriteLine(Resources.PushEnterToExitText); Console.ReadLine(); Environment.Exit(1); } break; //Set the File Extension. case "--FileExtension": //Check if the next variable in the args array is a command line argument or it's the end of the array. if (argnum >= args.Length - 1 && args[argnum].Contains("--")) CompilerUtilities.RecordToLog($"File extension not set. Keeping the extension to .bin.", 1); else { newProject.Value.FileExtension = args[argnum + 1]; CompilerUtilities.RecordToLog($"File extension set to .{newProject.Value.FileExtension}.", 0); argsTable.AddRow(Resources.FileExtensionEntry, newProject.Value.FileExtension); Console.ResetColor(); } break; //This command line argument is for packaging the app after compressing (if the --ReleaseMode flag is active. case "--PackageApp": // Check that test mode is active. Since this ain't working, it will show this message and close. if (_testProject) { CompilerUtilities.RecordToLog($"Cannot package the app when test mode is turned on. Aborting job.", 2); Console.ForegroundColor = ConsoleColor.DarkRed; Console.WriteLine(Resources.CannotCompressAndTestErrorText); Console.ResetColor(); Console.WriteLine(Resources.PushEnterToExitText); Console.ReadLine(); Environment.Exit(1); } //Else, either just compress or compress and delete the files. else { CompilerUtilities.RecordToLog($"The project will be compressed after compiling.", 0); if (_checkDeletion == 2) { if (argnum + 1 <= args.Length - 1) { _compressProject = args[argnum + 1] == "Final" ? 1 : 2; argsTable.AddRow(Resources.CompressionEntry, ((argnum + 1 <= args.Length - 1) && args[argnum + 1] == "Final") ? Resources.CompressAndRemoveEntry : Resources.CompressOnlyEntry); Console.ForegroundColor = ConsoleColor.DarkGreen; Console.WriteLine((argnum + 1 <= args.Length - 1) && args[argnum + 1] == "Final" ? Resources.ProjectFilesRemovalAfterCompressionText : Resources.ProjectFilesCompressionConfirmText); CompilerUtilities.RecordToLog(((argnum + 1 <= args.Length - 1) && args[argnum + 1] == "Final") ? $"The source files will be removed." : $"Only compression will occur.", 0); Console.ResetColor(); } else { CompilerUtilities.RecordToLog($"Only compression will occur.", 0); argsTable.AddRow(Resources.CompressionEntry, Resources.CompressOnlyEntry); _compressProject = 2; Console.ForegroundColor = ConsoleColor.DarkGreen; Console.WriteLine(Resources.ProjectFilesCompressionConfirmText); Console.ResetColor(); } } else { CompilerUtilities.RecordToLog($"Compression cannot occur if --ReleaseApp isn't specified. Skipping.", 0); Console.ForegroundColor = ConsoleColor.DarkYellow; Console.WriteLine(Resources.CompressionNotPermittedText); Console.ResetColor(); } } break; //This command line argument deletes the JavaScript files after compiling. case "--ReleaseMode": _checkDeletion = 2; CompilerUtilities.RecordToLog($"JS files will be removed.", 0); newProject.Value.RemoveSourceCodeAfterCompiling = true; Console.ResetColor(); break; //This command line argument starts the nwjs app to test the project. case "--TestMode": if (_compressProject <= 2) { CompilerUtilities.RecordToLog("Cannot test the app when the packaging option is turned on. Aborting job.", 2); Console.ForegroundColor = ConsoleColor.DarkRed; Console.WriteLine(Resources.CannotCompressAndTestErrorText); Console.ResetColor(); Console.WriteLine(Resources.PushEnterToExitText); Console.ReadLine(); Environment.Exit(1); } else { CompilerUtilities.RecordToLog("Test mode is turned on.", 0); argsTable.AddRow(Resources.TestAfterCompilingEntry, Resources.CommonWordYes); _testProject = true; Console.ForegroundColor = ConsoleColor.DarkGreen; Console.WriteLine(Resources.nwjsTestStartingText); Console.ResetColor(); } break; case "--SetCompressionLevel": if (argnum + 1 <= args.Length - 1 && !args[argnum].Contains("--")) { switch (argnum + 1) { case 2: CompilerUtilities.RecordToLog($"Compression is set to No Compression.", 0); newProject.Value.CompressionModeLevel = 2; Console.ForegroundColor = ConsoleColor.DarkGreen; Console.WriteLine(Resources.NoCompressionConfirmationText); Console.ResetColor(); break; case 1: CompilerUtilities.RecordToLog($"Compression is set to Fastest.", 0); newProject.Value.CompressionModeLevel = 1; Console.ForegroundColor = ConsoleColor.DarkGreen; Console.WriteLine(Resources.FastestCompressionConfirmationText); Console.ResetColor(); break; default: CompilerUtilities.RecordToLog($"Compression is set to Optimal.", 0); newProject.Value.CompressionModeLevel = 0; Console.ForegroundColor = ConsoleColor.DarkGreen; Console.WriteLine(Resources.OptimalCompressionCOnfirmationText); Console.ResetColor(); break; } } break; } } if (_compressProject < 3) switch (newProject.Value.CompressionModeLevel) { case 2: argsTable.AddRow(Resources.CompressionLevelEntry, Resources.NoCompression); break; case 1: argsTable.AddRow(Resources.CompressionLevelEntry, Resources.FastestCompression); break; case 0: argsTable.AddRow(Resources.CompressionLevelEntry, Resources.OptimalCompression); break; } if (_checkDeletion == 2) argsTable.AddRow(Resources.RemoveSourceFilesEntry, Resources.CommonWordYes); else argsTable.AddRow(Resources.RemoveSourceFilesEntry, Resources.CommonWordNo); #endregion #region Workload Check //Check if both the _projectLocation and _sdkLocation variables are not null. if (newProject.Value.ProjectLocation != null && _sdkLocation != null) { AnsiConsole.Write(argsTable); CompilerUtilities.RecordToLog("Settings set. Starting the job...", 0); _settingsSet = true; } else if (newProject.Value.ProjectLocation == null && _sdkLocation != null) { CompilerUtilities.RecordToLog("Project location not set. Aborting job.", 2); Console.ForegroundColor = ConsoleColor.DarkRed; Console.WriteLine(Resources.ProjectNotSetErrorText); Console.ResetColor(); Console.WriteLine(Resources.PushEnterToExitText); Console.ReadLine(); Environment.Exit(1); } else if (_sdkLocation == null && newProject.Value.ProjectLocation != null) { CompilerUtilities.RecordToLog("NW.js compiler location not set. Aborting job.", 2); Console.ForegroundColor = ConsoleColor.DarkRed; Console.WriteLine(Resources.SDKLocationNotSetErrorText); Console.ResetColor(); Console.WriteLine(Resources.PushEnterToExitText); Console.ReadLine(); Environment.Exit(1); } Console.WriteLine(""); } if (!_settingsSet) { Rule setupTab = new(); setupTab.Title = RMMVCookTool.CLI.Properties.Resources.SetupTitle; setupTab.Alignment = Justify.Left; AnsiConsole.Write(setupTab); do { //Ask the user where is the SDK. Check if the folder's there. _sdkLocation = AnsiConsole.Prompt(new TextPrompt<string>(Resources.SDKLocationQuestion)); if (_sdkLocation == null) Console.WriteLine(Resources.SDKLocationIsNullText); else if (!Directory.Exists(_sdkLocation)) Console.Write(Resources.SDKDirectoryMissing); } while (_sdkLocation == null || !Directory.Exists(_sdkLocation)); #endregion #region Workload Questionaire do { //Ask the user what project to compile. Check if the folder is there and there's a js folder. newProject.Value.ProjectLocation = AnsiConsole.Prompt(new TextPrompt<string>(Resources.ProjectLocationQuestion)); if (newProject.Value.ProjectLocation == null) Console.WriteLine(Resources.ProjectLocationIsNullText); else if (!Directory.Exists(newProject.Value.ProjectLocation)) Console.WriteLine(Resources.ProjetDirectoryMissingErrorText); else if (!Directory.Exists(Path.Combine(newProject.Value.ProjectLocation, "www", "js"))) Console.WriteLine(Resources.ProjectJsFolderMissing); else if (!File.Exists(Path.Combine(newProject.Value.ProjectLocation, "package.json"))) Console.WriteLine(Resources.JsonFileMissingErrorText); } while (newProject.Value.ProjectLocation == null || !Directory.Exists(newProject.Value.ProjectLocation) || !Directory.Exists(Path.Combine(newProject.Value.ProjectLocation, "www", "js"))); //Ask the user for the file extension. newProject.Value.FileExtension = AnsiConsole.Prompt(new TextPrompt<string>(Resources.FileExtensionQuestion).DefaultValue(".bin").AllowEmpty()); //This is the check if the tool should delete the JS files. _checkDeletion = AnsiConsole.Prompt(new TextPrompt<int>(Resources.WorkloadQuestion) .DefaultValue(1) .Validate(choice => { return choice switch { > 2 => ValidationResult.Error(), < 1 => ValidationResult.Error(), _ => ValidationResult.Success() }; })); newProject.Value.RemoveSourceCodeAfterCompiling = _checkDeletion == 2; if (_checkDeletion == 2) { _compressProject = AnsiConsole.Prompt(new TextPrompt<int>(Resources.CompressionQuestion) .DefaultValue(3) .Validate(choice => { return choice switch { > 3 => ValidationResult.Error(), < 1 => ValidationResult.Error(), _ => ValidationResult.Success() }; })); } else { //Ask if the user would like to test with nwjs. if (AnsiConsole.Confirm(Resources.TestProjectQuestion)) _testProject = true; } CompilerUtilities.RecordToLog($"Current setup of the job:\nCompiler Location:{_sdkLocation}\nProject Location:{newProject.Value.ProjectLocation}\nFile Extension:{newProject.Value.FileExtension}\nRemove Source Files? {newProject.Value.RemoveSourceCodeAfterCompiling}\nPackage game?:{newProject.Value.CompressFilesToPackage}\nRemove game files after packaging?:{newProject.Value.RemoveFilesAfterCompression}\nCompression Mode:{newProject.Value.CompressionModeLevel}", 0); } #endregion #region Workload Code Rule workTab = new(); workTab.Title = Resources.WorkTitle; workTab.Alignment = Justify.Left; AnsiConsole.Write(workTab); //Find the game folder. Stopwatch timer = new(); Stopwatch totalTime = new(); timer.Start(); totalTime.Start(); CompilerUtilities.RecordToLog("Attempting to read the package.json file.", 0); newProject.Value.GameFilesLocation = CompilerUtilities.GetProjectFilesLocation(Path.Combine(newProject.Value.ProjectLocation, "package.json")); if (newProject.Value.GameFilesLocation == "Null" || newProject.Value.GameFilesLocation == "Unknown") { timer.Stop(); totalTime.Stop(); //If the Json read returns nothing, throw an error to tell the user to double check their json file. Console.ForegroundColor = ConsoleColor.DarkRed; Console.WriteLine(Resources.JsonReferenceError); Console.ResetColor(); } else //If the read returned a valid folder, start the compiler process. { //Finding all the JS files. CompilerUtilities.RecordToLog("Preparing project...", 0); newProject.Value.FileMap ??= new List<string>(CompilerUtilities.FileFinder(Path.Combine(newProject.Value.ProjectLocation), "*.js")); CompilerUtilities.RecordToLog($"Found {newProject.Value.FileMap.Count} JS files.", 0); AnsiConsole.Status() .Start("[darkcyan]" + Resources.BinaryRemovalText + "[/]", spinny => { CompilerUtilities.RemoveDebugFiles(newProject.Value.ProjectLocation); CompilerUtilities.CleanupBin(newProject.Value.FileMap); }); //Preparing the compiler task. newProject.Value.CompilerInfo.Value.FileName = Path.Combine(_sdkLocation, RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "nwjc.exe" : "nwjc"); timer.Stop(); CompilerUtilities.RecordToLog($"Completed preparations. (Time to prepare:{timer.Elapsed}/Total Time (so far):{totalTime.Elapsed})", 0); timer.Reset(); try { timer.Start(); AnsiConsole.Progress() .Start(progress => { var compilerTask = progress.AddTask(RMMVCookTool.CLI.Properties.Resources.DarkcyanCompilingJSFilesText); compilerTask.MaxValue = 131; while (!progress.IsFinished) { for (var i = 0; i < newProject.Value.FileMap.Count; i++) { CompilerUtilities.RecordToLog($"Compiling {newProject.Value.FileMap[i]}...", 0); newProject.Value.CompileFile(i); CompilerUtilities.RecordToLog($"Compiled {newProject.Value.FileMap[i]}.", 0); compilerTask.Increment(1); } compilerTask.StopTask(); } }); timer.Stop(); CompilerUtilities.RecordToLog($"Completed the compilation. (Time elapsed:{timer.Elapsed}/Total Time (so far):{totalTime.Elapsed}", 0); timer.Reset(); if (_testProject) { Console.WriteLine(Resources.NwjsStartingTestNotificationText); newProject.Value.RunTest(_sdkLocation); } else if (_compressProject < 3 && _checkDeletion == 2) { CompilerUtilities.RecordToLog(Resources.PackagingGameText, 0); timer.Start(); AnsiConsole.Status() .Start(Resources.FileCompressionText, spin => { newProject.Value.CompressFiles(); }); timer.Stop(); CompilerUtilities.RecordToLog($"Packaged the game. (Time to package:{timer.Elapsed}/Total Time (so far):{totalTime.Elapsed}", 0); } totalTime.Stop(); CompilerUtilities.RecordToLog($"Task completed in {totalTime.Elapsed}", 0); Console.WriteLine(Resources.TaskCompleteText); } catch (ArgumentNullException e) { CompilerUtilities.RecordToLog(e); AnsiConsole.WriteException(e); throw; } catch (Exception e) { //TODO Improve the handling of the errors. CompilerUtilities.RecordToLog(e); AnsiConsole.WriteException(e); throw; } } //Ask the user to press Enter (or Return). if (!_settingsSet) { Console.WriteLine(Resources.PushEnterToExitText); Console.ReadLine(); CompilerUtilities.CloseLog(); } } #endregion } }
58.649554
485
0.491646
[ "MIT" ]
FirehawkV21/RMMVCookTool
RMMVCookTool.CLI/Program.cs
26,277
C#
namespace EasySql.Databases.TypeMappings { public class DoubleTypeMapping : TypeMappingBase { public DoubleTypeMapping() : base(typeof(double), System.Data.DbType.Double) { } } }
21.6
84
0.652778
[ "MIT" ]
jxnkwlp/EasySql
src/EasySql.Core/Databases/TypeMappings/DoubleTypeMapping.cs
218
C#
// <auto-generated /> using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using MainApp.EntityFrameworkCore; using Volo.Abp.EntityFrameworkCore; namespace MainApp.Migrations { [DbContext(typeof(UnifiedDbContext))] partial class UnifiedDbContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("_Abp_DatabaseProvider", EfCoreDatabaseProvider.SqlServer) .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("ProductVersion", "5.0.6") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Volo.Abp.AuditLogging.AuditLog", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("ApplicationName") .HasMaxLength(96) .HasColumnType("nvarchar(96)") .HasColumnName("ApplicationName"); b.Property<string>("BrowserInfo") .HasMaxLength(512) .HasColumnType("nvarchar(512)") .HasColumnName("BrowserInfo"); b.Property<string>("ClientId") .HasMaxLength(64) .HasColumnType("nvarchar(64)") .HasColumnName("ClientId"); b.Property<string>("ClientIpAddress") .HasMaxLength(64) .HasColumnType("nvarchar(64)") .HasColumnName("ClientIpAddress"); b.Property<string>("ClientName") .HasMaxLength(128) .HasColumnType("nvarchar(128)") .HasColumnName("ClientName"); b.Property<string>("Comments") .HasMaxLength(256) .HasColumnType("nvarchar(256)") .HasColumnName("Comments"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasMaxLength(40) .HasColumnType("nvarchar(40)") .HasColumnName("ConcurrencyStamp"); b.Property<string>("CorrelationId") .HasMaxLength(64) .HasColumnType("nvarchar(64)") .HasColumnName("CorrelationId"); b.Property<string>("Exceptions") .HasColumnType("nvarchar(max)"); b.Property<int>("ExecutionDuration") .HasColumnType("int") .HasColumnName("ExecutionDuration"); b.Property<DateTime>("ExecutionTime") .HasColumnType("datetime2"); b.Property<string>("ExtraProperties") .HasColumnType("nvarchar(max)") .HasColumnName("ExtraProperties"); b.Property<string>("HttpMethod") .HasMaxLength(16) .HasColumnType("nvarchar(16)") .HasColumnName("HttpMethod"); b.Property<int?>("HttpStatusCode") .HasColumnType("int") .HasColumnName("HttpStatusCode"); b.Property<Guid?>("ImpersonatorTenantId") .HasColumnType("uniqueidentifier") .HasColumnName("ImpersonatorTenantId"); b.Property<Guid?>("ImpersonatorUserId") .HasColumnType("uniqueidentifier") .HasColumnName("ImpersonatorUserId"); b.Property<Guid?>("TenantId") .HasColumnType("uniqueidentifier") .HasColumnName("TenantId"); b.Property<string>("TenantName") .HasColumnType("nvarchar(max)"); b.Property<string>("Url") .HasMaxLength(256) .HasColumnType("nvarchar(256)") .HasColumnName("Url"); b.Property<Guid?>("UserId") .HasColumnType("uniqueidentifier") .HasColumnName("UserId"); b.Property<string>("UserName") .HasMaxLength(256) .HasColumnType("nvarchar(256)") .HasColumnName("UserName"); b.HasKey("Id"); b.HasIndex("TenantId", "ExecutionTime"); b.HasIndex("TenantId", "UserId", "ExecutionTime"); b.ToTable("AbpAuditLogs"); }); modelBuilder.Entity("Volo.Abp.AuditLogging.AuditLogAction", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<Guid>("AuditLogId") .HasColumnType("uniqueidentifier") .HasColumnName("AuditLogId"); b.Property<int>("ExecutionDuration") .HasColumnType("int") .HasColumnName("ExecutionDuration"); b.Property<DateTime>("ExecutionTime") .HasColumnType("datetime2") .HasColumnName("ExecutionTime"); b.Property<string>("ExtraProperties") .HasColumnType("nvarchar(max)") .HasColumnName("ExtraProperties"); b.Property<string>("MethodName") .HasMaxLength(128) .HasColumnType("nvarchar(128)") .HasColumnName("MethodName"); b.Property<string>("Parameters") .HasMaxLength(2000) .HasColumnType("nvarchar(2000)") .HasColumnName("Parameters"); b.Property<string>("ServiceName") .HasMaxLength(256) .HasColumnType("nvarchar(256)") .HasColumnName("ServiceName"); b.Property<Guid?>("TenantId") .HasColumnType("uniqueidentifier") .HasColumnName("TenantId"); b.HasKey("Id"); b.HasIndex("AuditLogId"); b.HasIndex("TenantId", "ServiceName", "MethodName", "ExecutionTime"); b.ToTable("AbpAuditLogActions"); }); modelBuilder.Entity("Volo.Abp.AuditLogging.EntityChange", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<Guid>("AuditLogId") .HasColumnType("uniqueidentifier") .HasColumnName("AuditLogId"); b.Property<DateTime>("ChangeTime") .HasColumnType("datetime2") .HasColumnName("ChangeTime"); b.Property<byte>("ChangeType") .HasColumnType("tinyint") .HasColumnName("ChangeType"); b.Property<string>("EntityId") .IsRequired() .HasMaxLength(128) .HasColumnType("nvarchar(128)") .HasColumnName("EntityId"); b.Property<Guid?>("EntityTenantId") .HasColumnType("uniqueidentifier"); b.Property<string>("EntityTypeFullName") .IsRequired() .HasMaxLength(128) .HasColumnType("nvarchar(128)") .HasColumnName("EntityTypeFullName"); b.Property<string>("ExtraProperties") .HasColumnType("nvarchar(max)") .HasColumnName("ExtraProperties"); b.Property<Guid?>("TenantId") .HasColumnType("uniqueidentifier") .HasColumnName("TenantId"); b.HasKey("Id"); b.HasIndex("AuditLogId"); b.HasIndex("TenantId", "EntityTypeFullName", "EntityId"); b.ToTable("AbpEntityChanges"); }); modelBuilder.Entity("Volo.Abp.AuditLogging.EntityPropertyChange", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<Guid>("EntityChangeId") .HasColumnType("uniqueidentifier"); b.Property<string>("NewValue") .HasMaxLength(512) .HasColumnType("nvarchar(512)") .HasColumnName("NewValue"); b.Property<string>("OriginalValue") .HasMaxLength(512) .HasColumnType("nvarchar(512)") .HasColumnName("OriginalValue"); b.Property<string>("PropertyName") .IsRequired() .HasMaxLength(128) .HasColumnType("nvarchar(128)") .HasColumnName("PropertyName"); b.Property<string>("PropertyTypeFullName") .IsRequired() .HasMaxLength(64) .HasColumnType("nvarchar(64)") .HasColumnName("PropertyTypeFullName"); b.Property<Guid?>("TenantId") .HasColumnType("uniqueidentifier") .HasColumnName("TenantId"); b.HasKey("Id"); b.HasIndex("EntityChangeId"); b.ToTable("AbpEntityPropertyChanges"); }); modelBuilder.Entity("Volo.Abp.FeatureManagement.FeatureValue", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("Name") .IsRequired() .HasMaxLength(128) .HasColumnType("nvarchar(128)"); b.Property<string>("ProviderKey") .HasMaxLength(64) .HasColumnType("nvarchar(64)"); b.Property<string>("ProviderName") .HasMaxLength(64) .HasColumnType("nvarchar(64)"); b.Property<string>("Value") .IsRequired() .HasMaxLength(128) .HasColumnType("nvarchar(128)"); b.HasKey("Id"); b.HasIndex("Name", "ProviderName", "ProviderKey"); b.ToTable("AbpFeatureValues"); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityClaimType", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasMaxLength(40) .HasColumnType("nvarchar(40)") .HasColumnName("ConcurrencyStamp"); b.Property<string>("Description") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<string>("ExtraProperties") .HasColumnType("nvarchar(max)") .HasColumnName("ExtraProperties"); b.Property<bool>("IsStatic") .HasColumnType("bit"); b.Property<string>("Name") .IsRequired() .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<string>("Regex") .HasMaxLength(512) .HasColumnType("nvarchar(512)"); b.Property<string>("RegexDescription") .HasMaxLength(128) .HasColumnType("nvarchar(128)"); b.Property<bool>("Required") .HasColumnType("bit"); b.Property<int>("ValueType") .HasColumnType("int"); b.HasKey("Id"); b.ToTable("AbpClaimTypes"); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityLinkUser", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<Guid?>("SourceTenantId") .HasColumnType("uniqueidentifier"); b.Property<Guid>("SourceUserId") .HasColumnType("uniqueidentifier"); b.Property<Guid?>("TargetTenantId") .HasColumnType("uniqueidentifier"); b.Property<Guid>("TargetUserId") .HasColumnType("uniqueidentifier"); b.HasKey("Id"); b.HasIndex("SourceUserId", "SourceTenantId", "TargetUserId", "TargetTenantId") .IsUnique() .HasFilter("[SourceTenantId] IS NOT NULL AND [TargetTenantId] IS NOT NULL"); b.ToTable("AbpLinkUsers"); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityRole", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasMaxLength(40) .HasColumnType("nvarchar(40)") .HasColumnName("ConcurrencyStamp"); b.Property<string>("ExtraProperties") .HasColumnType("nvarchar(max)") .HasColumnName("ExtraProperties"); b.Property<bool>("IsDefault") .HasColumnType("bit") .HasColumnName("IsDefault"); b.Property<bool>("IsPublic") .HasColumnType("bit") .HasColumnName("IsPublic"); b.Property<bool>("IsStatic") .HasColumnType("bit") .HasColumnName("IsStatic"); b.Property<string>("Name") .IsRequired() .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<string>("NormalizedName") .IsRequired() .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<Guid?>("TenantId") .HasColumnType("uniqueidentifier") .HasColumnName("TenantId"); b.HasKey("Id"); b.HasIndex("NormalizedName"); b.ToTable("AbpRoles"); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityRoleClaim", b => { b.Property<Guid>("Id") .HasColumnType("uniqueidentifier"); b.Property<string>("ClaimType") .IsRequired() .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<string>("ClaimValue") .HasMaxLength(1024) .HasColumnType("nvarchar(1024)"); b.Property<Guid>("RoleId") .HasColumnType("uniqueidentifier"); b.Property<Guid?>("TenantId") .HasColumnType("uniqueidentifier") .HasColumnName("TenantId"); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AbpRoleClaims"); }); modelBuilder.Entity("Volo.Abp.Identity.IdentitySecurityLog", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("Action") .HasMaxLength(96) .HasColumnType("nvarchar(96)"); b.Property<string>("ApplicationName") .HasMaxLength(96) .HasColumnType("nvarchar(96)"); b.Property<string>("BrowserInfo") .HasMaxLength(512) .HasColumnType("nvarchar(512)"); b.Property<string>("ClientId") .HasMaxLength(64) .HasColumnType("nvarchar(64)"); b.Property<string>("ClientIpAddress") .HasMaxLength(64) .HasColumnType("nvarchar(64)"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasMaxLength(40) .HasColumnType("nvarchar(40)") .HasColumnName("ConcurrencyStamp"); b.Property<string>("CorrelationId") .HasMaxLength(64) .HasColumnType("nvarchar(64)"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<string>("ExtraProperties") .HasColumnType("nvarchar(max)") .HasColumnName("ExtraProperties"); b.Property<string>("Identity") .HasMaxLength(96) .HasColumnType("nvarchar(96)"); b.Property<Guid?>("TenantId") .HasColumnType("uniqueidentifier") .HasColumnName("TenantId"); b.Property<string>("TenantName") .HasMaxLength(64) .HasColumnType("nvarchar(64)"); b.Property<Guid?>("UserId") .HasColumnType("uniqueidentifier"); b.Property<string>("UserName") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.HasKey("Id"); b.HasIndex("TenantId", "Action"); b.HasIndex("TenantId", "ApplicationName"); b.HasIndex("TenantId", "Identity"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpSecurityLogs"); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityUser", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<int>("AccessFailedCount") .ValueGeneratedOnAdd() .HasColumnType("int") .HasDefaultValue(0) .HasColumnName("AccessFailedCount"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasMaxLength(40) .HasColumnType("nvarchar(40)") .HasColumnName("ConcurrencyStamp"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2") .HasColumnName("CreationTime"); b.Property<Guid?>("CreatorId") .HasColumnType("uniqueidentifier") .HasColumnName("CreatorId"); b.Property<Guid?>("DeleterId") .HasColumnType("uniqueidentifier") .HasColumnName("DeleterId"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2") .HasColumnName("DeletionTime"); b.Property<string>("Email") .IsRequired() .HasMaxLength(256) .HasColumnType("nvarchar(256)") .HasColumnName("Email"); b.Property<bool>("EmailConfirmed") .ValueGeneratedOnAdd() .HasColumnType("bit") .HasDefaultValue(false) .HasColumnName("EmailConfirmed"); b.Property<string>("ExtraProperties") .HasColumnType("nvarchar(max)") .HasColumnName("ExtraProperties"); b.Property<bool>("IsDeleted") .ValueGeneratedOnAdd() .HasColumnType("bit") .HasDefaultValue(false) .HasColumnName("IsDeleted"); b.Property<bool>("IsExternal") .ValueGeneratedOnAdd() .HasColumnType("bit") .HasDefaultValue(false) .HasColumnName("IsExternal"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2") .HasColumnName("LastModificationTime"); b.Property<Guid?>("LastModifierId") .HasColumnType("uniqueidentifier") .HasColumnName("LastModifierId"); b.Property<bool>("LockoutEnabled") .ValueGeneratedOnAdd() .HasColumnType("bit") .HasDefaultValue(false) .HasColumnName("LockoutEnabled"); b.Property<DateTimeOffset?>("LockoutEnd") .HasColumnType("datetimeoffset"); b.Property<string>("Name") .HasMaxLength(64) .HasColumnType("nvarchar(64)") .HasColumnName("Name"); b.Property<string>("NormalizedEmail") .IsRequired() .HasMaxLength(256) .HasColumnType("nvarchar(256)") .HasColumnName("NormalizedEmail"); b.Property<string>("NormalizedUserName") .IsRequired() .HasMaxLength(256) .HasColumnType("nvarchar(256)") .HasColumnName("NormalizedUserName"); b.Property<string>("PasswordHash") .HasMaxLength(256) .HasColumnType("nvarchar(256)") .HasColumnName("PasswordHash"); b.Property<string>("PhoneNumber") .HasMaxLength(16) .HasColumnType("nvarchar(16)") .HasColumnName("PhoneNumber"); b.Property<bool>("PhoneNumberConfirmed") .ValueGeneratedOnAdd() .HasColumnType("bit") .HasDefaultValue(false) .HasColumnName("PhoneNumberConfirmed"); b.Property<string>("SecurityStamp") .IsRequired() .HasMaxLength(256) .HasColumnType("nvarchar(256)") .HasColumnName("SecurityStamp"); b.Property<string>("Surname") .HasMaxLength(64) .HasColumnType("nvarchar(64)") .HasColumnName("Surname"); b.Property<Guid?>("TenantId") .HasColumnType("uniqueidentifier") .HasColumnName("TenantId"); b.Property<bool>("TwoFactorEnabled") .ValueGeneratedOnAdd() .HasColumnType("bit") .HasDefaultValue(false) .HasColumnName("TwoFactorEnabled"); b.Property<string>("UserName") .IsRequired() .HasMaxLength(256) .HasColumnType("nvarchar(256)") .HasColumnName("UserName"); b.HasKey("Id"); b.HasIndex("Email"); b.HasIndex("NormalizedEmail"); b.HasIndex("NormalizedUserName"); b.HasIndex("UserName"); b.ToTable("AbpUsers"); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityUserClaim", b => { b.Property<Guid>("Id") .HasColumnType("uniqueidentifier"); b.Property<string>("ClaimType") .IsRequired() .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<string>("ClaimValue") .HasMaxLength(1024) .HasColumnType("nvarchar(1024)"); b.Property<Guid?>("TenantId") .HasColumnType("uniqueidentifier") .HasColumnName("TenantId"); b.Property<Guid>("UserId") .HasColumnType("uniqueidentifier"); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AbpUserClaims"); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityUserLogin", b => { b.Property<Guid>("UserId") .HasColumnType("uniqueidentifier"); b.Property<string>("LoginProvider") .HasMaxLength(64) .HasColumnType("nvarchar(64)"); b.Property<string>("ProviderDisplayName") .HasMaxLength(128) .HasColumnType("nvarchar(128)"); b.Property<string>("ProviderKey") .IsRequired() .HasMaxLength(196) .HasColumnType("nvarchar(196)"); b.Property<Guid?>("TenantId") .HasColumnType("uniqueidentifier") .HasColumnName("TenantId"); b.HasKey("UserId", "LoginProvider"); b.HasIndex("LoginProvider", "ProviderKey"); b.ToTable("AbpUserLogins"); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityUserOrganizationUnit", b => { b.Property<Guid>("OrganizationUnitId") .HasColumnType("uniqueidentifier"); b.Property<Guid>("UserId") .HasColumnType("uniqueidentifier"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2") .HasColumnName("CreationTime"); b.Property<Guid?>("CreatorId") .HasColumnType("uniqueidentifier") .HasColumnName("CreatorId"); b.Property<Guid?>("TenantId") .HasColumnType("uniqueidentifier") .HasColumnName("TenantId"); b.HasKey("OrganizationUnitId", "UserId"); b.HasIndex("UserId", "OrganizationUnitId"); b.ToTable("AbpUserOrganizationUnits"); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityUserRole", b => { b.Property<Guid>("UserId") .HasColumnType("uniqueidentifier"); b.Property<Guid>("RoleId") .HasColumnType("uniqueidentifier"); b.Property<Guid?>("TenantId") .HasColumnType("uniqueidentifier") .HasColumnName("TenantId"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId", "UserId"); b.ToTable("AbpUserRoles"); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityUserToken", b => { b.Property<Guid>("UserId") .HasColumnType("uniqueidentifier"); b.Property<string>("LoginProvider") .HasMaxLength(64) .HasColumnType("nvarchar(64)"); b.Property<string>("Name") .HasMaxLength(128) .HasColumnType("nvarchar(128)"); b.Property<Guid?>("TenantId") .HasColumnType("uniqueidentifier") .HasColumnName("TenantId"); b.Property<string>("Value") .HasColumnType("nvarchar(max)"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AbpUserTokens"); }); modelBuilder.Entity("Volo.Abp.Identity.OrganizationUnit", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("Code") .IsRequired() .HasMaxLength(95) .HasColumnType("nvarchar(95)") .HasColumnName("Code"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasMaxLength(40) .HasColumnType("nvarchar(40)") .HasColumnName("ConcurrencyStamp"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2") .HasColumnName("CreationTime"); b.Property<Guid?>("CreatorId") .HasColumnType("uniqueidentifier") .HasColumnName("CreatorId"); b.Property<Guid?>("DeleterId") .HasColumnType("uniqueidentifier") .HasColumnName("DeleterId"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2") .HasColumnName("DeletionTime"); b.Property<string>("DisplayName") .IsRequired() .HasMaxLength(128) .HasColumnType("nvarchar(128)") .HasColumnName("DisplayName"); b.Property<string>("ExtraProperties") .HasColumnType("nvarchar(max)") .HasColumnName("ExtraProperties"); b.Property<bool>("IsDeleted") .ValueGeneratedOnAdd() .HasColumnType("bit") .HasDefaultValue(false) .HasColumnName("IsDeleted"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2") .HasColumnName("LastModificationTime"); b.Property<Guid?>("LastModifierId") .HasColumnType("uniqueidentifier") .HasColumnName("LastModifierId"); b.Property<Guid?>("ParentId") .HasColumnType("uniqueidentifier"); b.Property<Guid?>("TenantId") .HasColumnType("uniqueidentifier") .HasColumnName("TenantId"); b.HasKey("Id"); b.HasIndex("Code"); b.HasIndex("ParentId"); b.ToTable("AbpOrganizationUnits"); }); modelBuilder.Entity("Volo.Abp.Identity.OrganizationUnitRole", b => { b.Property<Guid>("OrganizationUnitId") .HasColumnType("uniqueidentifier"); b.Property<Guid>("RoleId") .HasColumnType("uniqueidentifier"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2") .HasColumnName("CreationTime"); b.Property<Guid?>("CreatorId") .HasColumnType("uniqueidentifier") .HasColumnName("CreatorId"); b.Property<Guid?>("TenantId") .HasColumnType("uniqueidentifier") .HasColumnName("TenantId"); b.HasKey("OrganizationUnitId", "RoleId"); b.HasIndex("RoleId", "OrganizationUnitId"); b.ToTable("AbpOrganizationUnitRoles"); }); modelBuilder.Entity("Volo.Abp.PermissionManagement.PermissionGrant", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("Name") .IsRequired() .HasMaxLength(128) .HasColumnType("nvarchar(128)"); b.Property<string>("ProviderKey") .IsRequired() .HasMaxLength(64) .HasColumnType("nvarchar(64)"); b.Property<string>("ProviderName") .IsRequired() .HasMaxLength(64) .HasColumnType("nvarchar(64)"); b.Property<Guid?>("TenantId") .HasColumnType("uniqueidentifier") .HasColumnName("TenantId"); b.HasKey("Id"); b.HasIndex("Name", "ProviderName", "ProviderKey"); b.ToTable("AbpPermissionGrants"); }); modelBuilder.Entity("Volo.Abp.SettingManagement.Setting", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("Name") .IsRequired() .HasMaxLength(128) .HasColumnType("nvarchar(128)"); b.Property<string>("ProviderKey") .HasMaxLength(64) .HasColumnType("nvarchar(64)"); b.Property<string>("ProviderName") .HasMaxLength(64) .HasColumnType("nvarchar(64)"); b.Property<string>("Value") .IsRequired() .HasMaxLength(2048) .HasColumnType("nvarchar(2048)"); b.HasKey("Id"); b.HasIndex("Name", "ProviderName", "ProviderKey"); b.ToTable("AbpSettings"); }); modelBuilder.Entity("Volo.Abp.TenantManagement.Tenant", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasMaxLength(40) .HasColumnType("nvarchar(40)") .HasColumnName("ConcurrencyStamp"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2") .HasColumnName("CreationTime"); b.Property<Guid?>("CreatorId") .HasColumnType("uniqueidentifier") .HasColumnName("CreatorId"); b.Property<Guid?>("DeleterId") .HasColumnType("uniqueidentifier") .HasColumnName("DeleterId"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2") .HasColumnName("DeletionTime"); b.Property<string>("ExtraProperties") .HasColumnType("nvarchar(max)") .HasColumnName("ExtraProperties"); b.Property<bool>("IsDeleted") .ValueGeneratedOnAdd() .HasColumnType("bit") .HasDefaultValue(false) .HasColumnName("IsDeleted"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2") .HasColumnName("LastModificationTime"); b.Property<Guid?>("LastModifierId") .HasColumnType("uniqueidentifier") .HasColumnName("LastModifierId"); b.Property<string>("Name") .IsRequired() .HasMaxLength(64) .HasColumnType("nvarchar(64)"); b.HasKey("Id"); b.HasIndex("Name"); b.ToTable("AbpTenants"); }); modelBuilder.Entity("Volo.Abp.TenantManagement.TenantConnectionString", b => { b.Property<Guid>("TenantId") .HasColumnType("uniqueidentifier"); b.Property<string>("Name") .HasMaxLength(64) .HasColumnType("nvarchar(64)"); b.Property<string>("Value") .IsRequired() .HasMaxLength(1024) .HasColumnType("nvarchar(1024)"); b.HasKey("TenantId", "Name"); b.ToTable("AbpTenantConnectionStrings"); }); modelBuilder.Entity("Volo.Abp.AuditLogging.AuditLogAction", b => { b.HasOne("Volo.Abp.AuditLogging.AuditLog", null) .WithMany("Actions") .HasForeignKey("AuditLogId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.AuditLogging.EntityChange", b => { b.HasOne("Volo.Abp.AuditLogging.AuditLog", null) .WithMany("EntityChanges") .HasForeignKey("AuditLogId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.AuditLogging.EntityPropertyChange", b => { b.HasOne("Volo.Abp.AuditLogging.EntityChange", null) .WithMany("PropertyChanges") .HasForeignKey("EntityChangeId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityRoleClaim", b => { b.HasOne("Volo.Abp.Identity.IdentityRole", null) .WithMany("Claims") .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityUserClaim", b => { b.HasOne("Volo.Abp.Identity.IdentityUser", null) .WithMany("Claims") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityUserLogin", b => { b.HasOne("Volo.Abp.Identity.IdentityUser", null) .WithMany("Logins") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityUserOrganizationUnit", b => { b.HasOne("Volo.Abp.Identity.OrganizationUnit", null) .WithMany() .HasForeignKey("OrganizationUnitId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Volo.Abp.Identity.IdentityUser", null) .WithMany("OrganizationUnits") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityUserRole", b => { b.HasOne("Volo.Abp.Identity.IdentityRole", null) .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Volo.Abp.Identity.IdentityUser", null) .WithMany("Roles") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityUserToken", b => { b.HasOne("Volo.Abp.Identity.IdentityUser", null) .WithMany("Tokens") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.Identity.OrganizationUnit", b => { b.HasOne("Volo.Abp.Identity.OrganizationUnit", null) .WithMany() .HasForeignKey("ParentId"); }); modelBuilder.Entity("Volo.Abp.Identity.OrganizationUnitRole", b => { b.HasOne("Volo.Abp.Identity.OrganizationUnit", null) .WithMany("Roles") .HasForeignKey("OrganizationUnitId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Volo.Abp.Identity.IdentityRole", null) .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.TenantManagement.TenantConnectionString", b => { b.HasOne("Volo.Abp.TenantManagement.Tenant", null) .WithMany("ConnectionStrings") .HasForeignKey("TenantId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.AuditLogging.AuditLog", b => { b.Navigation("Actions"); b.Navigation("EntityChanges"); }); modelBuilder.Entity("Volo.Abp.AuditLogging.EntityChange", b => { b.Navigation("PropertyChanges"); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityRole", b => { b.Navigation("Claims"); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityUser", b => { b.Navigation("Claims"); b.Navigation("Logins"); b.Navigation("OrganizationUnits"); b.Navigation("Roles"); b.Navigation("Tokens"); }); modelBuilder.Entity("Volo.Abp.Identity.OrganizationUnit", b => { b.Navigation("Roles"); }); modelBuilder.Entity("Volo.Abp.TenantManagement.Tenant", b => { b.Navigation("ConnectionStrings"); }); #pragma warning restore 612, 618 } } }
38.21493
117
0.437747
[ "MIT" ]
antosubash/abp-add-module-bug
host/MainApp.Web.Unified/Migrations/UnifiedDbContextModelSnapshot.cs
46,586
C#
// *********************************************************************** // Assembly : GuiStracini.Mandae // Author : Guilherme Branco Stracini // Created : 03/10/2017 // // Last Modified By : Guilherme Branco Stracini // Last Modified On : 03/10/2017 // *********************************************************************** // <copyright file="MockOrdersRepository.cs" company="Guilherme Branco Stracini"> // Copyright © 2017 Guilherme Branco Stracini // </copyright> // <summary></summary> // *********************************************************************** using GuiStracini.Mandae.Enums; using GuiStracini.Mandae.Models; using GuiStracini.Mandae.ValueObject; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace GuiStracini.Mandae.Test.V2 { /// <summary> /// The mock orders repository /// </summary> internal sealed class MockOrdersRepository { /// <summary> /// The orders /// </summary> private readonly MockOrders _orders; /// <summary> /// The orders items /// </summary> private readonly MockOrdersItems _ordersItems; /// <summary> /// Initializes a new instance of the <see cref="MockOrdersRepository"/> class. /// </summary> public MockOrdersRepository() { _orders = JsonConvert.DeserializeObject<MockOrders>(File.ReadAllText("orders.json")); _ordersItems = JsonConvert.DeserializeObject<MockOrdersItems>(File.ReadAllText("items.json")); } /// <summary> /// Gets the order. /// </summary> /// <param name="orderId">The order identifier.</param> /// <returns></returns> public MockOrder GetOrder(int orderId) { return _orders.Orders.SingleOrDefault(o => o.OrderId == orderId); } /// <summary> /// Gets the order items. /// </summary> /// <param name="orderId">The order identifier.</param> /// <returns></returns> public IEnumerable<MockOrderItem> GetOrderItems(int orderId) { return _ordersItems.Items.Where(i => i.OrderId == orderId); } /// <summary> /// Gets the sample order model for test proposes. /// </summary> /// <returns>An <see cref="OrderModel"/> instance populated with fake information</returns> public static OrderModel GetSampleOrderModel() { return new OrderModel { CustomerId = "182AC0ECDE0CA08A8B729733EBE8197D", PartnerOrderId = "teste-123456789", Observation = "Test order - GuiStracini.Mandae.Test assembly", Sender = new Sender { Address = new Address { PostalCode = "03137020", Number = "527", City = "São Paulo", Country = "BR", Neighborhood = "Vila Prudente", State = "SP", Street = "Rua Itanháem" }, FullName = "Editora Inovação" }, Items = new[] { new Item { Id= new Random().Next(10000,99999), TrackingId = $"VTR{DateTime.Now:ddMMyyHHmmssffff}", //The VTR prefix must be registred with Mandaê (sending null trackingId will force Mandaê to use it's onw tracking id sequence) Dimensions = new Dimensions { Length = 30, Width = 30, Weight = 2.6, Height = 30 }, Invoice = new Invoice { Id = "606620", Key = "35170805944298000101550010006066201623434877" }, PartnerItemId = "5607547", Recipient = new Recipient { Address = new Address { PostalCode = "22041080", Number = "110", Neighborhood = "Copacabana", City = "Rio de Janeiro", State = "RJ", Street = "Rua Anita Garibaild", Country = "BR" }, FullName = "João destinatário", Email = "exemplo-contato@mandae.com.br", Phone = "(11) 3382-2031", Document = "24580580001" }, Observation = "Sample order test - 5607547", Skus = new[] { new Sku { Description = "Caneta Acrilpen", Ean = "7891153044392", Price = new decimal(4.47), Freight = new decimal(1.2), Quantity = 2, SkuId = "3583" }, new Sku { Description = "Tecido algodão crú sem risco", Ean = "789100031550", Price = new decimal(15.43), Freight = new decimal(6.8), Quantity = 2, SkuId = "7522" } } } }, Vehicle = Vehicle.CAR, Scheduling = DateTime.Today.AddDays(1) }; } /// <summary> /// The mock orders class /// </summary> public sealed class MockOrders { /// <summary> /// Gets or sets the orders. /// </summary> /// <value> /// The orders. /// </value> public MockOrder[] Orders { get; set; } } /// <summary> /// The mock orders items class /// </summary> public sealed class MockOrdersItems { /// <summary> /// Gets or sets the items. /// </summary> /// <value> /// The items. /// </value> public MockOrderItem[] Items { get; set; } } /// <summary> /// The mock order class /// </summary> public sealed class MockOrder { /// <summary> /// Gets or sets the order identifier. /// </summary> /// <value> /// The order identifier. /// </value> public int OrderId { get; set; } /// <summary> /// Gets or sets the value. /// </summary> /// <value> /// The value. /// </value> public decimal Value { get; set; } /// <summary> /// Gets or sets the invoice number. /// </summary> /// <value> /// The invoice number. /// </value> public string InvoiceNumber { get; set; } /// <summary> /// Gets or sets the invoice key. /// </summary> /// <value> /// The invoice key. /// </value> public string InvoiceKey { get; set; } /// <summary> /// Gets or sets the weight. /// </summary> /// <value> /// The weight. /// </value> public int Weight { get; set; } /// <summary> /// Gets or sets the width. /// </summary> /// <value> /// The width. /// </value> public int Width { get; set; } /// <summary> /// Gets or sets the height. /// </summary> /// <value> /// The height. /// </value> public int Height { get; set; } /// <summary> /// Gets or sets the length. /// </summary> /// <value> /// The length. /// </value> public int Length { get; set; } /// <summary> /// Gets or sets the full name. /// </summary> /// <value> /// The full name. /// </value> public string FullName { get; set; } /// <summary> /// Gets or sets the document. /// </summary> /// <value> /// The document. /// </value> public string Document { get; set; } /// <summary> /// Gets or sets the telephone. /// </summary> /// <value> /// The telephone. /// </value> public string Telephone { get; set; } /// <summary> /// Gets or sets the email. /// </summary> /// <value> /// The email. /// </value> public string Email { get; set; } /// <summary> /// Gets or sets the zip code. /// </summary> /// <value> /// The zip code. /// </value> public string ZipCode { get; set; } /// <summary> /// Gets or sets the street. /// </summary> /// <value> /// The street. /// </value> public string Street { get; set; } /// <summary> /// Gets or sets the neighborhood. /// </summary> /// <value> /// The neighborhood. /// </value> public string Neighborhood { get; set; } /// <summary> /// Gets or sets the number. /// </summary> /// <value> /// The number. /// </value> public int Number { get; set; } /// <summary> /// Gets or sets the complement. /// </summary> /// <value> /// The complement. /// </value> public string Complement { get; set; } /// <summary> /// Gets or sets the city. /// </summary> /// <value> /// The city. /// </value> public string City { get; set; } /// <summary> /// Gets or sets the state initials. /// </summary> /// <value> /// The state initials. /// </value> public string StateInitials { get; set; } } /// <summary> /// The mock order item class /// </summary> public sealed class MockOrderItem { /// <summary> /// Gets or sets the order identifier. /// </summary> /// <value> /// The order identifier. /// </value> public int OrderId { get; set; } /// <summary> /// Gets or sets the sku identifier. /// </summary> /// <value> /// The sku identifier. /// </value> public int SkuId { get; set; } /// <summary> /// Gets or sets the price. /// </summary> /// <value> /// The price. /// </value> public decimal Price { get; set; } /// <summary> /// Gets or sets the price freight. /// </summary> /// <value> /// The price freight. /// </value> public decimal PriceFreight { get; set; } /// <summary> /// Gets or sets the ean. /// </summary> /// <value> /// The ean. /// </value> public string Ean { get; set; } /// <summary> /// Gets or sets the name. /// </summary> /// <value> /// The name. /// </value> public string Name { get; set; } /// <summary> /// Gets or sets the quantity. /// </summary> /// <value> /// The quantity. /// </value> public int Quantity { get; set; } } } }
34.125326
203
0.388217
[ "MIT" ]
guibranco/GuiStracini.Mandae
GuiStracini.Mandae.Tests/V2/MockOrdersRepository.cs
13,083
C#
/* * Copyright(c) 2019 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using Tizen.NUI.BaseComponents; using System.ComponentModel; using Tizen.NUI.Binding; namespace Tizen.NUI { /// <summary> /// Layers provide a mechanism for overlaying groups of actors on top of each other. /// </summary> /// <since_tizen> 3 </since_tizen> public class Layer : Container { private Window window; /// <summary> /// Creates a Layer object. /// </summary> /// <since_tizen> 3 </since_tizen> public Layer() : this(Interop.Layer.New(), true) { if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); this.SetAnchorPoint(Tizen.NUI.PivotPoint.TopLeft); this.SetResizePolicy(ResizePolicyType.FillToParent, DimensionType.AllDimensions); } internal Layer(global::System.IntPtr cPtr, bool cMemoryOwn) : base(cPtr, cMemoryOwn) { } /// <summary> /// Enumeration for the behavior of the layer. /// </summary> /// <since_tizen> 3 </since_tizen> public enum LayerBehavior { /// <summary> /// UI control rendering mode (default mode). /// This mode is designed for UI controls that can overlap. In this /// mode renderer order will be respective to the tree hierarchy of /// Actors.<br /> /// The rendering order is depth first, so for the following actor tree, /// A will be drawn first, then B, D, E, then C, F. This ensures that /// overlapping actors are drawn as expected (whereas, with breadth first /// traversal, the actors would interleave).<br /> /// </summary> /// <since_tizen> 3 </since_tizen> LayerUI, /// <summary> /// Layer will use depth test. /// This mode is designed for a 3 dimensional scene where actors in front /// of other actors will obscure them, i.e. the actors are sorted by the /// distance from the camera.<br /> /// When using this mode, a depth test will be used. A depth clear will /// happen for each layer, which means actors in a layer "above" other /// layers will be rendered in front of actors in those layers regardless /// of their Z positions (see Layer::Raise() and Layer::Lower()).<br /> /// Opaque renderers are drawn first and write to the depth buffer. Then /// transparent renderers are drawn with depth test enabled but depth /// write switched off. Transparent renderers are drawn based on their /// distance from the camera. A renderer's DEPTH_INDEX property is used to /// offset the distance to the camera when ordering transparent renderers. /// This is useful if you want to define the draw order of two or more /// transparent renderers that are equal distance from the camera. Unlike /// LAYER_UI, parent-child relationship does not affect rendering order at /// all. /// </summary> /// <since_tizen> 3 </since_tizen> Layer3D } internal enum TreeDepthMultiplier { TREE_DEPTH_MULTIPLIER = 10000 } /// <summary> /// Layer behavior, type String (Layer.LayerBehavior). /// </summary> /// <since_tizen> 3 </since_tizen> public Layer.LayerBehavior Behavior { get { return GetBehavior(); } set { SetBehavior(value); } } /// <summary> /// Sets the viewport (in window coordinates), type rectangle. /// The contents of the layer will not be visible outside this box, when ViewportEnabled is true. /// </summary> /// <since_tizen> 4 </since_tizen> public Rectangle Viewport { get { if (ClippingEnabled) { Rectangle ret = new Rectangle(Interop.Layer.GetClippingBox(SwigCPtr), true); if (NDalicPINVOKE.SWIGPendingException.Pending) throw new InvalidOperationException("FATAL: get Exception", NDalicPINVOKE.SWIGPendingException.Retrieve()); return ret; } else { // Clipping not enabled so return the window size Size2D windowSize = window?.Size; Rectangle ret = new Rectangle(0, 0, windowSize.Width, windowSize.Height); return ret; } } set { Interop.Layer.SetClippingBox(SwigCPtr, Rectangle.getCPtr(value)); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); ClippingEnabled = true; } } /// <summary> /// Retrieves and sets the layer's opacity.<br /> /// </summary> /// <since_tizen> 3 </since_tizen> public float Opacity { get { float temp = 0.0f; var pValue = GetProperty(View.Property.OPACITY); pValue.Get(out temp); pValue.Dispose(); return temp; } set { var temp = new Tizen.NUI.PropertyValue(value); SetProperty(View.Property.OPACITY, temp); temp.Dispose(); } } /// <summary> /// Retrieves and sets the layer's visibility. /// </summary> /// <since_tizen> 3 </since_tizen> public bool Visibility { get { bool temp = false; var pValue = GetProperty(View.Property.VISIBLE); pValue.Get(out temp); pValue.Dispose(); return temp; } set { var temp = new Tizen.NUI.PropertyValue(value); SetProperty(View.Property.VISIBLE, temp); temp.Dispose(); } } /// <summary> /// Get the number of children held by the layer. /// </summary> /// <since_tizen> 3 </since_tizen> public new uint ChildCount { get { return Convert.ToUInt32(Children.Count); } } /// <summary> /// Gets or sets the layer's name. /// </summary> /// <since_tizen> 3 </since_tizen> public string Name { get { return GetName(); } set { SetName(value); } } /// <summary> /// Queries the depth of the layer.<br /> /// 0 is the bottommost layer, higher number is on the top.<br /> /// </summary> /// <since_tizen> 3 </since_tizen> public uint Depth { get { return GetDepth(); } } /// <summary> /// Internal only property to enable or disable clipping, type boolean. /// By default, this is false, i.e., the viewport of the layer is the entire window. /// </summary> internal bool ClippingEnabled { get { bool ret = Interop.Layer.IsClipping(SwigCPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } set { Interop.Layer.SetClipping(SwigCPtr, value); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } } /// This will be public opened in tizen_next after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public ResourceDictionary XamlResources { get { return Application.Current.XamlResources; } set { Application.Current.XamlResources = value; } } /// <summary> /// Gets the Layer's ID /// Readonly /// </summary> /// <remarks>Hidden-API</remarks> [EditorBrowsable(EditorBrowsableState.Never)] public uint ID { get { return GetId(); } } /// From the Container base class. /// <summary> /// Adds a child view to this layer. /// </summary> /// <seealso cref="Container.Add"> /// </seealso> /// <exception cref="ArgumentNullException"> Thrown when child is null. </exception> /// <since_tizen> 4 </since_tizen> public override void Add(View child) { if (null == child) { throw new ArgumentNullException(nameof(child)); } Container oldParent = child.GetParent(); if (oldParent != this) { if (oldParent != null) { oldParent.Remove(child); } else { child.InternalParent = this; } Interop.Actor.Add(SwigCPtr, View.getCPtr(child)); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); Children.Add(child); BindableObject.SetInheritedBindingContext(child, this?.BindingContext); } } /// <summary> /// Removes a child view from this layer. If the view was not a child of this layer, this is a no-op. /// </summary> /// <seealso cref="Container.Remove"> /// </seealso> /// <exception cref="ArgumentNullException"> Thrown when child is null. </exception> /// <since_tizen> 4 </since_tizen> public override void Remove(View child) { if (null == child) { throw new ArgumentNullException(nameof(child)); } Interop.Actor.Remove(SwigCPtr, View.getCPtr(child)); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); Children.Remove(child); child.InternalParent = null; } /// <summary> /// Retrieves a child view by the index. /// </summary> /// <pre>The view has been initialized.</pre> /// <param name="index">The index of the child to retrieve.</param> /// <returns>The view for the given index or empty handle if children not initialized.</returns> /// <since_tizen> 4 </since_tizen> public override View GetChildAt(uint index) { if (index < Children.Count) { return Children[Convert.ToInt32(index)]; } else { return null; } } /// <summary> /// Get parent of the layer. /// </summary> /// <returns>The view's container</returns> /// <since_tizen> 4 </since_tizen> public override Container GetParent() { return null; } /// <summary> /// Get the child count of the layer. /// </summary> /// <returns>The child count of the layer.</returns> /// <since_tizen> 4 </since_tizen> [Obsolete("Deprecated in API9, will be removed in API11. Please use ChildCount property instead!")] public override uint GetChildCount() { return Convert.ToUInt32(Children.Count); } /// <summary> /// Downcasts a handle to layer handle. /// </summary> /// <exception cref="ArgumentNullException"> Thrown when handle is null. </exception> /// <since_tizen> 3 </since_tizen> /// Please do not use! this will be deprecated! /// Instead please use as keyword. [Obsolete("Please do not use! This will be deprecated! Please use as keyword instead!")] [EditorBrowsable(EditorBrowsableState.Never)] public static Layer DownCast(BaseHandle handle) { if (null == handle) { throw new ArgumentNullException(nameof(handle)); } Layer ret = Registry.GetManagedBaseHandleFromNativePtr(handle) as Layer; if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Search through this layer's hierarchy for a view with the given unique ID. /// </summary> /// <pre>This layer (the parent) has been initialized.</pre> /// <remarks>The actor itself is also considered in the search.</remarks> /// <param name="id">The id of the child to find</param> /// <returns> A handle to the view if found, or an empty handle if not. </returns> /// <since_tizen> 3 </since_tizen> public View FindChildById(uint id) { //to fix memory leak issue, match the handle count with native side. IntPtr cPtr = Interop.Actor.FindChildById(SwigCPtr, id); View ret = this.GetInstanceSafely<View>(cPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } internal override View FindCurrentChildById(uint id) { return FindChildById(id); } /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public View FindChildByName(string viewName) { //to fix memory leak issue, match the handle count with native side. IntPtr cPtr = Interop.Actor.FindChildByName(SwigCPtr, viewName); View ret = this.GetInstanceSafely<View>(cPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Increments the depth of the layer. /// </summary> /// <since_tizen> 3 </since_tizen> public void Raise() { var parentChildren = window?.LayersChildren; if (parentChildren != null) { int currentIdx = parentChildren.IndexOf(this); if (currentIdx >= 0 && currentIdx < parentChildren.Count - 1) { var upper = parentChildren[currentIdx + 1]; RaiseAbove(upper); } } } /// <summary> /// Decrements the depth of the layer. /// </summary> /// <since_tizen> 3 </since_tizen> public void Lower() { var parentChildren = window?.LayersChildren; if (parentChildren != null) { int currentIdx = parentChildren.IndexOf(this); if (currentIdx > 0 && currentIdx < parentChildren.Count) { var low = parentChildren[currentIdx - 1]; LowerBelow(low); } } } /// <summary> /// Raises the layer to the top. /// </summary> /// <since_tizen> 3 </since_tizen> public void RaiseToTop() { var parentChildren = window?.LayersChildren; if (parentChildren != null) { parentChildren.Remove(this); parentChildren.Add(this); Interop.Layer.RaiseToTop(SwigCPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } } /// <summary> /// Lowers the layer to the bottom. /// </summary> /// <since_tizen> 3 </since_tizen> public void LowerToBottom() { var parentChildren = window?.LayersChildren; if (parentChildren != null) { parentChildren.Remove(this); parentChildren.Insert(0, this); Interop.Layer.LowerToBottom(SwigCPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } } /// <summary> /// Moves the layer directly above the given layer.<br /> /// After the call, this layer's depth will be immediately above target.<br /> /// </summary> /// <param name="target">The layer to get on top of.</param> /// <since_tizen> 3 </since_tizen> public void MoveAbove(Layer target) { Interop.Layer.MoveAbove(SwigCPtr, Layer.getCPtr(target)); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Moves the layer directly below the given layer.<br /> /// After the call, this layer's depth will be immediately below target.<br /> /// </summary> /// <param name="target">The layer to get below of.</param> /// <since_tizen> 3 </since_tizen> public void MoveBelow(Layer target) { Interop.Layer.MoveBelow(SwigCPtr, Layer.getCPtr(target)); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// This will be public opened in next tizen after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public void SetAnchorPoint(Vector3 anchorPoint) { Interop.Actor.SetAnchorPoint(SwigCPtr, Vector3.getCPtr(anchorPoint)); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// This will be public opened in next tizen after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public void SetSize(float width, float height) { Interop.ActorInternal.SetSize(SwigCPtr, width, height); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// This will be public opened in next tizen after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public void SetParentOrigin(Vector3 parentOrigin) { Interop.ActorInternal.SetParentOrigin(SwigCPtr, Vector3.getCPtr(parentOrigin)); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// This will be public opened in next tizen after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public void SetResizePolicy(ResizePolicyType policy, DimensionType dimension) { Interop.Actor.SetResizePolicy(SwigCPtr, (int)policy, (int)dimension); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Inhouse API. /// This allows the user to specify whether this layer should consume touch (including gestures). /// If set, any layers behind this layer will not be hit-test. /// </summary> /// <param name="consume">Whether the layer should consume touch (including gestures).</param> [EditorBrowsable(EditorBrowsableState.Never)] public void SetTouchConsumed(bool consume) { Interop.Layer.SetTouchConsumed(SwigCPtr, consume); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Inhouse API. /// This allows the user to specify whether this layer should consume hover. /// If set, any layers behind this layer will not be hit-test. /// </summary> /// <param name="consume">Whether the layer should consume hover</param> [EditorBrowsable(EditorBrowsableState.Never)] public void SetHoverConsumed(bool consume) { Interop.Layer.SetHoverConsumed(SwigCPtr, consume); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } internal uint GetDepth() { var parentChildren = window?.LayersChildren; if (parentChildren != null) { int idx = parentChildren.IndexOf(this); if (idx >= 0) { return Convert.ToUInt32(idx); ; } } return 0u; } internal void RaiseAbove(Layer target) { var parentChildren = window?.LayersChildren; if (parentChildren != null) { int currentIndex = parentChildren.IndexOf(this); int targetIndex = parentChildren.IndexOf(target); if (currentIndex < 0 || targetIndex < 0 || currentIndex >= parentChildren.Count || targetIndex >= parentChildren.Count) { NUILog.Error("index should be bigger than 0 and less than children of layer count"); return; } // If the currentIndex is less than the target index and the target has the same parent. if (currentIndex < targetIndex) { parentChildren.Remove(this); parentChildren.Insert(targetIndex, this); Interop.Layer.MoveAbove(SwigCPtr, Layer.getCPtr(target)); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } } } internal void LowerBelow(Layer target) { var parentChildren = window?.LayersChildren; if (parentChildren != null) { int currentIndex = parentChildren.IndexOf(this); int targetIndex = parentChildren.IndexOf(target); if (currentIndex < 0 || targetIndex < 0 || currentIndex >= parentChildren.Count || targetIndex >= parentChildren.Count) { NUILog.Error("index should be bigger than 0 and less than children of layer count"); return; } // If the currentIndex is not already the 0th index and the target has the same parent. if ((currentIndex != 0) && (targetIndex != -1) && (currentIndex > targetIndex)) { parentChildren.Remove(this); parentChildren.Insert(targetIndex, this); Interop.Layer.MoveBelow(SwigCPtr, Layer.getCPtr(target)); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } } } internal void SetSortFunction(SWIGTYPE_p_f_r_q_const__Dali__Vector3__float function) { Interop.Layer.SetSortFunction(SwigCPtr, SWIGTYPE_p_f_r_q_const__Dali__Vector3__float.getCPtr(function)); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } internal bool IsTouchConsumed() { bool ret = Interop.Layer.IsTouchConsumed(SwigCPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } internal bool IsHoverConsumed() { bool ret = Interop.Layer.IsHoverConsumed(SwigCPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } internal void AddViewToLayerList(View view) { Children.Add(view); } internal void RemoveViewFromLayerList(View view) { Children.Remove(view); } internal string GetName() { string ret = Interop.Actor.GetName(SwigCPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } internal void SetName(string name) { Interop.Actor.SetName(SwigCPtr, name); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } internal void SetWindow(Window win) { window = win; } internal uint GetId() { uint ret = Interop.Actor.GetId(SwigCPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// This will not be public opened. [EditorBrowsable(EditorBrowsableState.Never)] protected override void ReleaseSwigCPtr(System.Runtime.InteropServices.HandleRef swigCPtr) { Interop.Layer.DeleteLayer(swigCPtr); } private void SetBehavior(LayerBehavior behavior) { Interop.Layer.SetBehavior(SwigCPtr, (int)behavior); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } private LayerBehavior GetBehavior() { Layer.LayerBehavior ret = (Layer.LayerBehavior)Interop.Layer.GetBehavior(SwigCPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } internal class Property { internal static readonly int BEHAVIOR = Interop.Layer.BehaviorGet(); } } }
37.377717
175
0.560851
[ "Apache-2.0", "MIT" ]
Inhong/TizenFX
src/Tizen.NUI/src/public/Common/Layer.cs
27,510
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Text.RegularExpressions; using DateObject = System.DateTime; namespace Microsoft.Recognizers.Text.DateTime { public interface IHolidayParserConfiguration : IDateTimeOptionsConfiguration { IImmutableDictionary<string, string> VariableHolidaysTimexDictionary { get; } IImmutableDictionary<string, Func<int, DateObject>> HolidayFuncDictionary { get; } IImmutableDictionary<string, IEnumerable<string>> HolidayNames { get; } IEnumerable<Regex> HolidayRegexList { get; } int GetSwiftYear(string text); string SanitizeHolidayToken(string holiday); } }
31.961538
91
0.731649
[ "MIT" ]
17000cyh/Recognizers-Text
.NET/Microsoft.Recognizers.Text.DateTime/Parsers/IHolidayParserConfiguration.cs
833
C#
namespace SubtitleEvaluation.Web.Services { public class HostingOptions { public HostingOptions() { VirtualApplicationRootPath = ""; } public string VirtualApplicationRootPath { get; set; } } }
19.307692
62
0.609562
[ "MIT" ]
gvas/subtitle-quality-checker
Services/HostingOptions.cs
251
C#
/* * SmartThings API * * # Overview This is the reference documentation for the SmartThings API. The SmartThings API supports [REST](https://en.wikipedia.org/wiki/Representational_state_transfer), resources are protected with [OAuth 2.0 Bearer Tokens](https://tools.ietf.org/html/rfc6750#section-2.1), and all responses are sent as [JSON](http://www.json.org/). # Authentication All SmartThings resources are protected with [OAuth 2.0 Bearer Tokens](https://tools.ietf.org/html/rfc6750#section-2.1) sent on the request as an `Authorization: Bearer <TOKEN>` header, and operations require specific OAuth scopes that specify the exact permissions authorized by the user. ## Token types There are two types of tokens: SmartApp tokens, and personal access tokens. SmartApp tokens are used to communicate between third-party integrations, or SmartApps, and the SmartThings API. When a SmartApp is called by the SmartThings platform, it is sent an authorization token that can be used to interact with the SmartThings API. Personal access tokens are used to interact with the API for non-SmartApp use cases. They can be created and managed on the [personal access tokens page](https://account.smartthings.com/tokens). ## OAuth2 scopes Operations may be protected by one or more OAuth security schemes, which specify the required permissions. Each scope for a given scheme is required. If multiple schemes are specified (not common), you may use either scheme. SmartApp token scopes are derived from the permissions requested by the SmartApp and granted by the end-user during installation. Personal access token scopes are associated with the specific permissions authorized when creating them. Scopes are generally in the form `permission:entity-type:entity-id`. **An `*` used for the `entity-id` specifies that the permission may be applied to all entities that the token type has access to, or may be replaced with a specific ID.** For more information about authrization and permissions, please see the [Authorization and permissions guide](https://smartthings.developer.samsung.com/develop/guides/smartapps/auth-and-permissions.html). <!- - ReDoc-Inject: <security-definitions> - -> # Errors The SmartThings API uses conventional HTTP response codes to indicate the success or failure of a request. In general, a `2XX` response code indicates success, a `4XX` response code indicates an error given the inputs for the request, and a `5XX` response code indicates a failure on the SmartThings platform. API errors will contain a JSON response body with more information about the error: ```json { \"requestId\": \"031fec1a-f19f-470a-a7da-710569082846\" \"error\": { \"code\": \"ConstraintViolationError\", \"message\": \"Validation errors occurred while process your request.\", \"details\": [ { \"code\": \"PatternError\", \"target\": \"latitude\", \"message\": \"Invalid format.\" }, { \"code\": \"SizeError\", \"target\": \"name\", \"message\": \"Too small.\" }, { \"code\": \"SizeError\", \"target\": \"description\", \"message\": \"Too big.\" } ] } } ``` ## Error Response Body The error response attributes are: | Property | Type | Required | Description | | - -- | - -- | - -- | - -- | | requestId | String | No | A request identifier that can be used to correlate an error to additional logging on the SmartThings servers. | error | Error | **Yes** | The Error object, documented below. ## Error Object The Error object contains the following attributes: | Property | Type | Required | Description | | - -- | - -- | - -- | - -- | | code | String | **Yes** | A SmartThings-defined error code that serves as a more specific indicator of the error than the HTTP error code specified in the response. See [SmartThings Error Codes](#section/Errors/SmartThings-Error-Codes) for more information. | message | String | **Yes** | A description of the error, intended to aid developers in debugging of error responses. | target | String | No | The target of the particular error. For example, it could be the name of the property that caused the error. | details | Error[] | No | An array of Error objects that typically represent distinct, related errors that occurred during the request. As an optional attribute, this may be null or an empty array. ## Standard HTTP Error Codes The following table lists the most common HTTP error response: | Code | Name | Description | | - -- | - -- | - -- | | 400 | Bad Request | The client has issued an invalid request. This is commonly used to specify validation errors in a request payload. | 401 | Unauthorized | Authorization for the API is required, but the request has not been authenticated. | 403 | Forbidden | The request has been authenticated but does not have appropriate permissions, or a requested resource is not found. | 404 | Not Found | Specifies the requested path does not exist. | 406 | Not Acceptable | The client has requested a MIME type via the Accept header for a value not supported by the server. | 415 | Unsupported Media Type | The client has defined a contentType header that is not supported by the server. | 422 | Unprocessable Entity | The client has made a valid request, but the server cannot process it. This is often used for APIs for which certain limits have been exceeded. | 429 | Too Many Requests | The client has exceeded the number of requests allowed for a given time window. | 500 | Internal Server Error | An unexpected error on the SmartThings servers has occurred. These errors should be rare. | 501 | Not Implemented | The client request was valid and understood by the server, but the requested feature has yet to be implemented. These errors should be rare. ## SmartThings Error Codes SmartThings specifies several standard custom error codes. These provide more information than the standard HTTP error response codes. The following table lists the standard SmartThings error codes and their description: | Code | Typical HTTP Status Codes | Description | | - -- | - -- | - -- | | PatternError | 400, 422 | The client has provided input that does not match the expected pattern. | ConstraintViolationError | 422 | The client has provided input that has violated one or more constraints. | NotNullError | 422 | The client has provided a null input for a field that is required to be non-null. | NullError | 422 | The client has provided an input for a field that is required to be null. | NotEmptyError | 422 | The client has provided an empty input for a field that is required to be non-empty. | SizeError | 400, 422 | The client has provided a value that does not meet size restrictions. | Unexpected Error | 500 | A non-recoverable error condition has occurred. Indicates a problem occurred on the SmartThings server that is no fault of the client. | UnprocessableEntityError | 422 | The client has sent a malformed request body. | TooManyRequestError | 429 | The client issued too many requests too quickly. | LimitError | 422 | The client has exceeded certain limits an API enforces. | UnsupportedOperationError | 400, 422 | The client has issued a request to a feature that currently isn't supported by the SmartThings platform. These should be rare. ## Custom Error Codes An API may define its own error codes where appropriate. These custom error codes are documented as part of that specific API's documentation. # Warnings The SmartThings API issues warning messages via standard HTTP Warning headers. These messages do not represent a request failure, but provide additional information that the requester might want to act upon. For instance a warning will be issued if you are using an old API version. # API Versions The SmartThings API supports both path and header-based versioning. The following are equivalent: - https://api.smartthings.com/v1/locations - https://api.smartthings.com/locations with header `Accept: application/vnd.smartthings+json;v=1` Currently, only version 1 is available. # Paging Operations that return a list of objects return a paginated response. The `_links` object contains the items returned, and links to the next and previous result page, if applicable. ```json { \"items\": [ { \"locationId\": \"6b3d1909-1e1c-43ec-adc2-5f941de4fbf9\", \"name\": \"Home\" }, { \"locationId\": \"6b3d1909-1e1c-43ec-adc2-5f94d6g4fbf9\", \"name\": \"Work\" } .... ], \"_links\": { \"next\": { \"href\": \"https://api.smartthings.com/v1/locations?page=3\" }, \"previous\": { \"href\": \"https://api.smartthings.com/v1/locations?page=1\" } } } ``` # Localization Some SmartThings API's support localization. Specific information regarding localization endpoints are documented in the API itself. However, the following should apply to all endpoints that support localization. ## Fallback Patterns When making a request with the `Accept-Language` header, this fallback pattern is observed. * Response will be translated with exact locale tag. * If a translation does not exist for the requested language and region, the translation for the language will be returned. * If a translation does not exist for the language, English (en) will be returned. * Finally, an untranslated response will be returned in the absense of the above translations. ## Accept-Language Header The format of the `Accept-Language` header follows what is defined in [RFC 7231, section 5.3.5](https://tools.ietf.org/html/rfc7231#section-5.3.5) ## Content-Language The `Content-Language` header should be set on the response from the server to indicate which translation was given back to the client. The absense of the header indicates that the server did not recieve a request with the `Accept-Language` header set. * * The version of the OpenAPI document: 1.0-PREVIEW * * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Net; using System.Net.Mime; using SmartThingsNet.Client; using SmartThingsNet.Model; namespace SmartThingsNet.Api { /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public interface IScenesApiSync : IApiAccessor { #region Synchronous Operations /// <summary> /// Execute Scene /// </summary> /// <remarks> /// Execute a Scene by id for the logged in user and given locationId /// </remarks> /// <exception cref="SmartThingsNet.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="sceneId">The ID of the Scene.</param> /// <param name="locationId">The location of a scene. (optional)</param> /// <returns>StandardSuccessResponse</returns> StandardSuccessResponse ExecuteScene (string sceneId, string locationId = default(string)); /// <summary> /// Execute Scene /// </summary> /// <remarks> /// Execute a Scene by id for the logged in user and given locationId /// </remarks> /// <exception cref="SmartThingsNet.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="sceneId">The ID of the Scene.</param> /// <param name="locationId">The location of a scene. (optional)</param> /// <returns>ApiResponse of StandardSuccessResponse</returns> ApiResponse<StandardSuccessResponse> ExecuteSceneWithHttpInfo (string sceneId, string locationId = default(string)); /// <summary> /// List Scenes /// </summary> /// <remarks> /// Fetch a list of Scenes for the logged in user filtered by locationIds. If no locationId is sent, return scenes for all available locations /// </remarks> /// <exception cref="SmartThingsNet.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="locationId">The location of a scene. (optional)</param> /// <returns>ScenePagedResult</returns> PagedScene ListScenes (string locationId = default(string)); /// <summary> /// List Scenes /// </summary> /// <remarks> /// Fetch a list of Scenes for the logged in user filtered by locationIds. If no locationId is sent, return scenes for all available locations /// </remarks> /// <exception cref="SmartThingsNet.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="locationId">The location of a scene. (optional)</param> /// <returns>ApiResponse of ScenePagedResult</returns> ApiResponse<PagedScene> ListScenesWithHttpInfo (string locationId = default(string)); #endregion Synchronous Operations } /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public interface IScenesApiAsync : IApiAccessor { #region Asynchronous Operations /// <summary> /// Execute Scene /// </summary> /// <remarks> /// Execute a Scene by id for the logged in user and given locationId /// </remarks> /// <exception cref="SmartThingsNet.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="sceneId">The ID of the Scene.</param> /// <param name="locationId">The location of a scene. (optional)</param> /// <returns>Task of StandardSuccessResponse</returns> System.Threading.Tasks.Task<StandardSuccessResponse> ExecuteSceneAsync (string sceneId, string locationId = default(string)); /// <summary> /// Execute Scene /// </summary> /// <remarks> /// Execute a Scene by id for the logged in user and given locationId /// </remarks> /// <exception cref="SmartThingsNet.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="sceneId">The ID of the Scene.</param> /// <param name="locationId">The location of a scene. (optional)</param> /// <returns>Task of ApiResponse (StandardSuccessResponse)</returns> System.Threading.Tasks.Task<ApiResponse<StandardSuccessResponse>> ExecuteSceneAsyncWithHttpInfo (string sceneId, string locationId = default(string)); /// <summary> /// List Scenes /// </summary> /// <remarks> /// Fetch a list of Scenes for the logged in user filtered by locationIds. If no locationId is sent, return scenes for all available locations /// </remarks> /// <exception cref="SmartThingsNet.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="locationId">The location of a scene. (optional)</param> /// <returns>Task of ScenePagedResult</returns> System.Threading.Tasks.Task<PagedScene> ListScenesAsync (string locationId = default(string)); /// <summary> /// List Scenes /// </summary> /// <remarks> /// Fetch a list of Scenes for the logged in user filtered by locationIds. If no locationId is sent, return scenes for all available locations /// </remarks> /// <exception cref="SmartThingsNet.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="locationId">The location of a scene. (optional)</param> /// <returns>Task of ApiResponse (ScenePagedResult)</returns> System.Threading.Tasks.Task<ApiResponse<PagedScene>> ListScenesAsyncWithHttpInfo (string locationId = default(string)); #endregion Asynchronous Operations } /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public interface IScenesApi : IScenesApiSync, IScenesApiAsync { } /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public partial class ScenesApi : IScenesApi { private SmartThingsNet.Client.ExceptionFactory _exceptionFactory = (name, response) => null; /// <summary> /// Initializes a new instance of the <see cref="ScenesApi"/> class. /// </summary> /// <returns></returns> public ScenesApi() : this((string) null) { } /// <summary> /// Initializes a new instance of the <see cref="ScenesApi"/> class. /// </summary> /// <returns></returns> public ScenesApi(String basePath) { this.Configuration = SmartThingsNet.Client.Configuration.MergeConfigurations( SmartThingsNet.Client.GlobalConfiguration.Instance, new SmartThingsNet.Client.Configuration { BasePath = basePath } ); this.Client = new SmartThingsNet.Client.ApiClient(this.Configuration.BasePath); this.AsynchronousClient = new SmartThingsNet.Client.ApiClient(this.Configuration.BasePath); this.ExceptionFactory = SmartThingsNet.Client.Configuration.DefaultExceptionFactory; } /// <summary> /// Initializes a new instance of the <see cref="ScenesApi"/> class /// using Configuration object /// </summary> /// <param name="configuration">An instance of Configuration</param> /// <returns></returns> public ScenesApi(SmartThingsNet.Client.Configuration configuration) { if (configuration == null) throw new ArgumentNullException("configuration"); this.Configuration = SmartThingsNet.Client.Configuration.MergeConfigurations( SmartThingsNet.Client.GlobalConfiguration.Instance, configuration ); this.Client = new SmartThingsNet.Client.ApiClient(this.Configuration.BasePath); this.AsynchronousClient = new SmartThingsNet.Client.ApiClient(this.Configuration.BasePath); ExceptionFactory = SmartThingsNet.Client.Configuration.DefaultExceptionFactory; } /// <summary> /// Initializes a new instance of the <see cref="ScenesApi"/> class /// using a Configuration object and client instance. /// </summary> /// <param name="client">The client interface for synchronous API access.</param> /// <param name="asyncClient">The client interface for asynchronous API access.</param> /// <param name="configuration">The configuration object.</param> public ScenesApi(SmartThingsNet.Client.ISynchronousClient client,SmartThingsNet.Client.IAsynchronousClient asyncClient, SmartThingsNet.Client.IReadableConfiguration configuration) { if(client == null) throw new ArgumentNullException("client"); if(asyncClient == null) throw new ArgumentNullException("asyncClient"); if(configuration == null) throw new ArgumentNullException("configuration"); this.Client = client; this.AsynchronousClient = asyncClient; this.Configuration = configuration; this.ExceptionFactory = SmartThingsNet.Client.Configuration.DefaultExceptionFactory; } /// <summary> /// The client for accessing this underlying API asynchronously. /// </summary> public SmartThingsNet.Client.IAsynchronousClient AsynchronousClient { get; set; } /// <summary> /// The client for accessing this underlying API synchronously. /// </summary> public SmartThingsNet.Client.ISynchronousClient Client { get; set; } /// <summary> /// Gets the base path of the API client. /// </summary> /// <value>The base path</value> public String GetBasePath() { return this.Configuration.BasePath; } /// <summary> /// Gets or sets the configuration object /// </summary> /// <value>An instance of the Configuration</value> public SmartThingsNet.Client.IReadableConfiguration Configuration {get; set;} /// <summary> /// Provides a factory method hook for the creation of exceptions. /// </summary> public SmartThingsNet.Client.ExceptionFactory ExceptionFactory { get { if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1) { throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported."); } return _exceptionFactory; } set { _exceptionFactory = value; } } /// <summary> /// Execute Scene Execute a Scene by id for the logged in user and given locationId /// </summary> /// <exception cref="SmartThingsNet.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="sceneId">The ID of the Scene.</param> /// <param name="locationId">The location of a scene. (optional)</param> /// <returns>StandardSuccessResponse</returns> public StandardSuccessResponse ExecuteScene (string sceneId, string locationId = default(string)) { SmartThingsNet.Client.ApiResponse<StandardSuccessResponse> localVarResponse = ExecuteSceneWithHttpInfo(sceneId, locationId); return localVarResponse.Data; } /// <summary> /// Execute Scene Execute a Scene by id for the logged in user and given locationId /// </summary> /// <exception cref="SmartThingsNet.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="sceneId">The ID of the Scene.</param> /// <param name="locationId">The location of a scene. (optional)</param> /// <returns>ApiResponse of StandardSuccessResponse</returns> public SmartThingsNet.Client.ApiResponse< StandardSuccessResponse > ExecuteSceneWithHttpInfo (string sceneId, string locationId = default(string)) { // verify the required parameter 'sceneId' is set if (sceneId == null) throw new SmartThingsNet.Client.ApiException(400, "Missing required parameter 'sceneId' when calling ScenesApi->ExecuteScene"); SmartThingsNet.Client.RequestOptions localVarRequestOptions = new SmartThingsNet.Client.RequestOptions(); String[] _contentTypes = new String[] { "application/json" }; // to determine the Accept header String[] _accepts = new String[] { "application/json" }; var localVarContentType = SmartThingsNet.Client.ClientUtils.SelectHeaderContentType(_contentTypes); if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); var localVarAccept = SmartThingsNet.Client.ClientUtils.SelectHeaderAccept(_accepts); if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); localVarRequestOptions.PathParameters.Add("sceneId", SmartThingsNet.Client.ClientUtils.ParameterToString(sceneId)); // path parameter if (locationId != null) { localVarRequestOptions.QueryParameters.Add(SmartThingsNet.Client.ClientUtils.ParameterToMultiMap("", "locationId", locationId)); } // authentication (Bearer) required // oauth required if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } // make the HTTP request var localVarResponse = this.Client.Post< StandardSuccessResponse >("/scenes/{sceneId}/execute", localVarRequestOptions, this.Configuration); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("ExecuteScene", localVarResponse); if (_exception != null) throw _exception; } return localVarResponse; } /// <summary> /// Execute Scene Execute a Scene by id for the logged in user and given locationId /// </summary> /// <exception cref="SmartThingsNet.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="sceneId">The ID of the Scene.</param> /// <param name="locationId">The location of a scene. (optional)</param> /// <returns>Task of StandardSuccessResponse</returns> public async System.Threading.Tasks.Task<StandardSuccessResponse> ExecuteSceneAsync (string sceneId, string locationId = default(string)) { SmartThingsNet.Client.ApiResponse<StandardSuccessResponse> localVarResponse = await ExecuteSceneAsyncWithHttpInfo(sceneId, locationId); return localVarResponse.Data; } /// <summary> /// Execute Scene Execute a Scene by id for the logged in user and given locationId /// </summary> /// <exception cref="SmartThingsNet.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="sceneId">The ID of the Scene.</param> /// <param name="locationId">The location of a scene. (optional)</param> /// <returns>Task of ApiResponse (StandardSuccessResponse)</returns> public async System.Threading.Tasks.Task<SmartThingsNet.Client.ApiResponse<StandardSuccessResponse>> ExecuteSceneAsyncWithHttpInfo (string sceneId, string locationId = default(string)) { // verify the required parameter 'sceneId' is set if (sceneId == null) throw new SmartThingsNet.Client.ApiException(400, "Missing required parameter 'sceneId' when calling ScenesApi->ExecuteScene"); SmartThingsNet.Client.RequestOptions localVarRequestOptions = new SmartThingsNet.Client.RequestOptions(); String[] _contentTypes = new String[] { "application/json" }; // to determine the Accept header String[] _accepts = new String[] { "application/json" }; foreach (var _contentType in _contentTypes) localVarRequestOptions.HeaderParameters.Add("Content-Type", _contentType); foreach (var _accept in _accepts) localVarRequestOptions.HeaderParameters.Add("Accept", _accept); localVarRequestOptions.PathParameters.Add("sceneId", SmartThingsNet.Client.ClientUtils.ParameterToString(sceneId)); // path parameter if (locationId != null) { localVarRequestOptions.QueryParameters.Add(SmartThingsNet.Client.ClientUtils.ParameterToMultiMap("", "locationId", locationId)); } // authentication (Bearer) required // oauth required if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } // make the HTTP request var localVarResponse = await this.AsynchronousClient.PostAsync<StandardSuccessResponse>("/scenes/{sceneId}/execute", localVarRequestOptions, this.Configuration); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("ExecuteScene", localVarResponse); if (_exception != null) throw _exception; } return localVarResponse; } /// <summary> /// List Scenes Fetch a list of Scenes for the logged in user filtered by locationIds. If no locationId is sent, return scenes for all available locations /// </summary> /// <exception cref="SmartThingsNet.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="locationId">The location of a scene. (optional)</param> /// <returns>ScenePagedResult</returns> public PagedScene ListScenes (string locationId = default(string)) { SmartThingsNet.Client.ApiResponse<PagedScene> localVarResponse = ListScenesWithHttpInfo(locationId); return localVarResponse.Data; } /// <summary> /// List Scenes Fetch a list of Scenes for the logged in user filtered by locationIds. If no locationId is sent, return scenes for all available locations /// </summary> /// <exception cref="SmartThingsNet.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="locationId">The location of a scene. (optional)</param> /// <returns>ApiResponse of ScenePagedResult</returns> public SmartThingsNet.Client.ApiResponse< PagedScene > ListScenesWithHttpInfo (string locationId = default(string)) { SmartThingsNet.Client.RequestOptions localVarRequestOptions = new SmartThingsNet.Client.RequestOptions(); String[] _contentTypes = new String[] { "application/json" }; // to determine the Accept header String[] _accepts = new String[] { "application/vnd.smartthings+json", "application/json", }; var localVarContentType = SmartThingsNet.Client.ClientUtils.SelectHeaderContentType(_contentTypes); if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); var localVarAccept = SmartThingsNet.Client.ClientUtils.SelectHeaderAccept(_accepts); if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); if (locationId != null) { localVarRequestOptions.QueryParameters.Add(SmartThingsNet.Client.ClientUtils.ParameterToMultiMap("", "locationId", locationId)); } // authentication (Bearer) required // oauth required if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } // make the HTTP request var localVarResponse = this.Client.Get< PagedScene >("/scenes", localVarRequestOptions, this.Configuration); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("ListScenes", localVarResponse); if (_exception != null) throw _exception; } return localVarResponse; } /// <summary> /// List Scenes Fetch a list of Scenes for the logged in user filtered by locationIds. If no locationId is sent, return scenes for all available locations /// </summary> /// <exception cref="SmartThingsNet.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="locationId">The location of a scene. (optional)</param> /// <returns>Task of ScenePagedResult</returns> public async System.Threading.Tasks.Task<PagedScene> ListScenesAsync (string locationId = default(string)) { SmartThingsNet.Client.ApiResponse<PagedScene> localVarResponse = await ListScenesAsyncWithHttpInfo(locationId); return localVarResponse.Data; } /// <summary> /// List Scenes Fetch a list of Scenes for the logged in user filtered by locationIds. If no locationId is sent, return scenes for all available locations /// </summary> /// <exception cref="SmartThingsNet.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="locationId">The location of a scene. (optional)</param> /// <returns>Task of ApiResponse (ScenePagedResult)</returns> public async System.Threading.Tasks.Task<SmartThingsNet.Client.ApiResponse<PagedScene>> ListScenesAsyncWithHttpInfo (string locationId = default(string)) { SmartThingsNet.Client.RequestOptions localVarRequestOptions = new SmartThingsNet.Client.RequestOptions(); String[] _contentTypes = new String[] { "application/json" }; // to determine the Accept header String[] _accepts = new String[] { "application/vnd.smartthings+json", "application/json", }; foreach (var _contentType in _contentTypes) localVarRequestOptions.HeaderParameters.Add("Content-Type", _contentType); foreach (var _accept in _accepts) localVarRequestOptions.HeaderParameters.Add("Accept", _accept); if (locationId != null) { localVarRequestOptions.QueryParameters.Add(SmartThingsNet.Client.ClientUtils.ParameterToMultiMap("", "locationId", locationId)); } // authentication (Bearer) required // oauth required if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } // make the HTTP request var localVarResponse = await this.AsynchronousClient.GetAsync<PagedScene>("/scenes", localVarRequestOptions, this.Configuration); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("ListScenes", localVarResponse); if (_exception != null) throw _exception; } return localVarResponse; } } }
64.076923
9,753
0.670512
[ "MIT" ]
KenKilty/SmartThingsNet
src/Api/ScenesApi.cs
34,153
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using KanimLib; namespace KanimExplorer.Wizard { public partial class BuildingPlaceholderGeneratorPage : UserControl, IWizardPage { public BuildingPlaceholderGeneratorPage() { InitializeComponent(); } public IWizardPage Next() { string buildingName = textBoxName.Text; int buildingWidth = (int)numericUpDownWidth.Value; int buildingHeight = (int)numericUpDownHeight.Value; string outDir = textBoxOutputPath.Text; if (string.IsNullOrWhiteSpace(buildingName)) throw new Exception("Building name must not be empty."); if (buildingWidth < 1) throw new Exception("Building width must not be less than 1."); if (buildingHeight < 1) throw new Exception("Building height must not be less than 1."); if (string.IsNullOrWhiteSpace(outDir) || !Directory.Exists(outDir)) throw new Exception("Output directory is not valid."); string texFile = Path.Combine(outDir, $"{buildingName}_0.png"); string buildFile = Path.Combine(outDir, $"{buildingName}_build.bytes"); string animFile = Path.Combine(outDir, $"{buildingName}_anim.bytes"); try { AnimFactory.MakePlaceholderBuilding(buildingName, buildingWidth, buildingHeight, out Bitmap tex, out KBuild build, out KAnim anim); tex.Save(texFile, ImageFormat.Png); KAnimUtils.WriteBuild(buildFile, build); KAnimUtils.WriteAnim(animFile, anim); } catch (Exception ex) { throw new Exception("Failed to generate building data.", ex); } return null; } public void Cancel() { } private void buttonBrowse_Click(object sender, EventArgs e) { FolderBrowserDialog dlg = new FolderBrowserDialog(); dlg.ShowNewFolderButton = true; dlg.Description = "Select a folder to save the kanim files to:"; if (dlg.ShowDialog(this) == DialogResult.OK) { textBoxOutputPath.Text = dlg.SelectedPath; } } } }
30.1
135
0.736592
[ "MIT" ]
SanchozzDeponianin/kanim-explorer
src/KanimExplorer/Wizard/BuildingPlaceholderGeneratorPage.cs
2,109
C#
using System; using System.Text; using Sandbox; using Sandbox.Graphics.GUI; using Shared.Plugin; using VRage; using VRage.Utils; using VRageMath; namespace ClientPlugin.GUI { public class MyPluginConfigDialog : MyGuiScreenBase { private const string Caption = "PluginTemplate Configuration"; public override string GetFriendlyName() => "MyPluginConfigDialog"; private MyLayoutTable layoutTable; private MyGuiControlLabel enabledLabel; private MyGuiControlCheckbox enabledCheckbox; // TODO: Add member variables for your UI controls here private MyGuiControlMultilineText infoText; private MyGuiControlButton closeButton; public MyPluginConfigDialog() : base(new Vector2(0.5f, 0.5f), MyGuiConstants.SCREEN_BACKGROUND_COLOR, new Vector2(0.5f, 0.7f), false, null, MySandboxGame.Config.UIBkOpacity, MySandboxGame.Config.UIOpacity) { EnabledBackgroundFade = true; m_closeOnEsc = true; m_drawEvenWithoutFocus = true; CanHideOthers = true; CanBeHidden = true; CloseButtonEnabled = true; } public override void LoadContent() { base.LoadContent(); RecreateControls(true); } public override void RecreateControls(bool constructor) { base.RecreateControls(constructor); CreateControls(); LayoutControls(); } private void CreateControls() { AddCaption(Caption); var config = Common.Config; CreateCheckbox(out enabledLabel, out enabledCheckbox, config.Enabled, value => config.Enabled = value, "Enabled", "Enables the plugin"); // TODO: Create your UI controls here infoText = new MyGuiControlMultilineText { Name = "InfoText", OriginAlign = MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_TOP, TextAlign = MyGuiDrawAlignEnum.HORISONTAL_LEFT_AND_VERTICAL_TOP, TextBoxAlign = MyGuiDrawAlignEnum.HORISONTAL_LEFT_AND_VERTICAL_TOP, // TODO: Add 2 short lines of text here if the player needs to know something. Ask for feedback here. Etc. Text = new StringBuilder("\r\nTODO") }; closeButton = new MyGuiControlButton(originAlign: MyGuiDrawAlignEnum.HORISONTAL_RIGHT_AND_VERTICAL_CENTER, text: MyTexts.Get(MyCommonTexts.Ok), onButtonClick: OnOk); } private void OnOk(MyGuiControlButton _) => CloseScreen(); private void CreateCheckbox(out MyGuiControlLabel labelControl, out MyGuiControlCheckbox checkboxControl, bool value, Action<bool> store, string label, string tooltip) { labelControl = new MyGuiControlLabel { Text = label, OriginAlign = MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_TOP }; checkboxControl = new MyGuiControlCheckbox(toolTip: tooltip) { OriginAlign = MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_TOP, Enabled = true, IsChecked = value }; checkboxControl.IsCheckedChanged += cb => store(cb.IsChecked); } private void LayoutControls() { var size = Size ?? Vector2.One; layoutTable = new MyLayoutTable(this, -0.3f * size, 0.6f * size); layoutTable.SetColumnWidths(400f, 100f); // TODO: Add more row heights here as needed layoutTable.SetRowHeights(90f, /* TODO */ 150f, 60f); var row = 0; layoutTable.Add(enabledLabel, MyAlignH.Left, MyAlignV.Center, row, 0); layoutTable.Add(enabledCheckbox, MyAlignH.Left, MyAlignV.Center, row, 1); row++; // TODO: Layout your UI controls here layoutTable.Add(infoText, MyAlignH.Left, MyAlignV.Top, row, 0, colSpan: 2); row++; layoutTable.Add(closeButton, MyAlignH.Center, MyAlignV.Center, row, 0, colSpan: 2); // row++; } } }
36.347826
213
0.626077
[ "MIT" ]
ComputerErika/MoreInput
ClientPlugin/GUI/MyPluginConfigDialog.cs
4,180
C#
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Linq; using System.Threading; using ICSharpCode.Core; using ICSharpCode.NRefactory.CSharp; using ICSharpCode.NRefactory.Editor; using ICSharpCode.SharpDevelop; using ICSharpCode.SharpDevelop.Parser; using ICSharpCode.SharpDevelop.Project; using ICSharpCode.SharpDevelop.Workbench; using ICSharpCode.XmlEditor; using NUnit.Framework; using System.IO; using Rhino.Mocks; namespace ICSharpCode.XamlBinding.Tests { [TestFixture] [RequiresSTA] public class ResolveContextTests : TextEditorBasedTests { void SetUpWithCode(FileName fileName, ITextSource textSource) { IProject project = MockRepository.GenerateStrictMock<IProject>(); var parseInfo = new XamlParser() { TaskListTokens = TaskListTokens }.Parse(fileName, textSource, true, project, CancellationToken.None); var pc = new CSharpProjectContent().AddOrUpdateFiles(parseInfo.UnresolvedFile); pc = pc.AddAssemblyReferences(new[] { Corlib, PresentationCore, PresentationFramework, SystemXaml }); var compilation = pc.CreateCompilation(); SD.Services.AddService(typeof(IParserService), MockRepository.GenerateStrictMock<IParserService>()); SD.ParserService.Stub(p => p.GetCachedParseInformation(fileName)).Return(parseInfo); SD.ParserService.Stub(p => p.GetCompilation(project)).Return(compilation); SD.ParserService.Stub(p => p.GetCompilationForFile(fileName)).Return(compilation); SD.ParserService.Stub(p => p.Parse(fileName, textSource)).WhenCalled( i => { i.ReturnValue = new XamlParser() { TaskListTokens = TaskListTokens }.Parse(fileName, textSource, true, project, CancellationToken.None); }).Return(parseInfo); // fake Return to make it work SD.Services.AddService(typeof(IFileService), MockRepository.GenerateStrictMock<IFileService>()); IViewContent view = MockRepository.GenerateStrictMock<IViewContent>(); SD.FileService.Stub(f => f.OpenFile(fileName, false)).Return(view); } XamlContext TestContext(string xaml, int offset) { var fileName = new FileName("test.xaml"); var textSource = new StringTextSource(xaml); SetUpWithCode(fileName, textSource); return XamlContextResolver.ResolveContext(fileName, textSource, offset); } [Test] public void ContextNoneDescriptionTest() { string xaml = "<Grid>\n\t<CheckBox x:Name=\"asdf\" Background=\"Aqua\" Content=\"{x:Static Cursors.Arrow}\" />\n</Grid>"; int offset = "<Grid>\n".Length; XamlContext context = TestContext(xaml, offset); Assert.AreEqual(XamlContextDescription.None, context.Description); } [Test] public void ContextNoneDescriptionTest2() { string xaml = "<Grid>\n\t<CheckBox x:Name=\"asdf\" Background=\"Aqua\" Content=\"{x:Static Cursors.Arrow}\" />\n</Grid>"; int offset = "<Grid>".Length; XamlContext context = TestContext(xaml, offset); Assert.AreEqual(XamlContextDescription.None, context.Description); } [Test] public void ContextNoneDescriptionTest3() { string xaml = "<Grid>\n\t<CheckBox x:Name=\"asdf\" Background=\"Aqua\" Content=\"{x:Static Cursors.Arrow}\" />\n</Grid>"; int offset = "<Grid>\n\t<CheckBox x:Name=\"asdf\" Background=\"Aqua\" Content=\"{x:Static Cursors.Arrow}\" />\n".Length; XamlContext context = TestContext(xaml, offset); Assert.AreEqual(XamlContextDescription.None, context.Description); } [Test] public void ContextAtTagDescriptionTest() { string xaml = "<Grid>\n\t<CheckBox x:Name=\"asdf\" Background=\"Aqua\" Content=\"{x:Static Cursors.Arrow}\" />\n</Grid>"; int offset = "<G".Length; XamlContext context = TestContext(xaml, offset); Assert.AreEqual(XamlContextDescription.AtTag, context.Description); } [Test] public void ContextAtTagDescriptionTest1() { string xaml = "<Grid>\n\t<CheckBox x:Name=\"asdf\" Background=\"Aqua\" Content=\"{x:Static Cursors.Arrow}\" /> <\n</Grid>"; int offset = "<Grid>\n\t<CheckBox x:Name=\"asdf\" Background=\"Aqua\" Content=\"{x:Static Cursors.Arrow}\" /> <".Length; XamlContext context = TestContext(xaml, offset); Assert.AreEqual(XamlContextDescription.AtTag, context.Description); } [Test] public void ContextAtTagDescriptionTest2() { string xaml = "<Grid>\n\t<CheckBox x:Name=\"asdf\" Background=\"Aqua\" Content=\"{x:Static Cursors.Arrow}\" />\n</Grid>"; int offset = "<Grid>\n".Length + 10; XamlContext context = TestContext(xaml, offset); Assert.AreEqual(XamlContextDescription.AtTag, context.Description); } [Test] public void ContextAtTagDescriptionTest4() { string xaml = "<Grid>\n\t<\n</Grid>"; int offset = "<Grid>\n\t<".Length; XamlContext context = TestContext(xaml, offset); Assert.AreEqual(XamlContextDescription.AtTag, context.Description); } [Test] public void ContextInTagDescriptionTest() { string xaml = "<Grid>\n\t<CheckBox x:Name=\"asdf\" Background=\"Aqua\" Content=\"{x:Static Cursors.Arrow}\" />\n</Grid>"; int offset = "<Grid>\n".Length + 26; XamlContext context = TestContext(xaml, offset); Assert.AreEqual(XamlContextDescription.InTag, context.Description); } [Test] public void ContextInTagDescriptionTest2() { string xaml = @"<Window x:Class='Vokabeltrainer.Window1' xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' Title=''> <Grid> <StackPanel> <RadioButton </StackPanel> </Grid> </Window>"; int offset = @"<Window x:Class='Vokabeltrainer.Window1' xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' Title=''> <Grid> <StackPanel> <RadioButton ".Length; XamlContext context = TestContext(xaml, offset); Assert.AreEqual(XamlContextDescription.InTag, context.Description); } [Test] public void ContextAtTagDescriptionTest5() { string xaml = @"<Window x:Class='Vokabeltrainer.Window1' xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' Title=''> <Grid> <StackPanel> <RadioButton </StackPanel> </Grid> </Window>"; int offset = @"<Window x:Class='Vokabeltrainer.Window1' xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' Title=''> <Grid> <StackPanel> <RadioButton </Stack".Length; XamlContext context = TestContext(xaml, offset); Assert.AreEqual(XamlContextDescription.AtTag, context.Description); } [Test] public void ElementNameWithDotTest1() { string xaml = "<Grid>\n\t<Grid.ColumnDefinitions />\n</Grid>"; int offset = "<Grid>\n".Length + 12; XamlContext context = TestContext(xaml, offset); Assert.AreEqual("Grid.ColumnDefinitions", context.ActiveElement.Name); } [Test] public void ContextAtTagDescriptionTest3() { string xaml = File.ReadAllText("Test4.xaml"); int offset = 413; XamlContext context = TestContext(xaml, offset); Assert.AreEqual(XamlContextDescription.AtTag, context.Description); } [Test] public void ContextInMarkupExtensionTest() { string xaml = "<Test attr=\"{Test}\" />"; int offset = "<Test attr=\"{Te".Length; XamlContext context = TestContext(xaml, offset); Assert.AreEqual(XamlContextDescription.InMarkupExtension, context.Description); } [Test] public void ContextInAttributeValueTest() { string xaml = "<Test attr=\"Test\" />"; int offset = "<Test attr=\"Te".Length; XamlContext context = TestContext(xaml, offset); Assert.AreEqual(XamlContextDescription.InAttributeValue, context.Description); } [Test] public void ContextInMarkupExtensionTest2() { string xaml = "<Test attr=\"{}{Test}\" />"; int offset = "<Test attr=\"{}{Te".Length; XamlContext context = TestContext(xaml, offset); Assert.AreEqual(XamlContextDescription.InAttributeValue, context.Description); } [Test] public void ContextInAttributeValueTest2() { string xaml = "<Test attr=\"Test />"; int offset = "<Test attr=\"Te".Length; XamlContext context = TestContext(xaml, offset); Assert.AreEqual(XamlContextDescription.InAttributeValue, context.Description); } [Test] public void ContextInAttributeValueTest3() { string xaml = "<Test attr=\"Test />"; int offset = "<Test attr=\"".Length; XamlContext context = TestContext(xaml, offset); Assert.AreEqual(XamlContextDescription.InAttributeValue, context.Description); } [Test] public void ParentElementTestSimple1() { string xaml = File.ReadAllText("Test1.xaml"); int offset = 272; XamlContext context = TestContext(xaml, offset); Assert.AreEqual("CheckBox", context.ActiveElement.Name); Assert.AreEqual("Grid", context.ParentElement.Name); } [Test] public void ParentElementTestSimple2() { string xaml = File.ReadAllText("Test4.xaml"); int offset = 413; XamlContext context = TestContext(xaml, offset); Assert.AreEqual("Grid", context.ActiveElement.Name); Assert.AreEqual("Grid", context.ParentElement.Name); } [Test] public void RootElementTest() { string xaml = File.ReadAllText("Test1.xaml"); int offset = 31; XamlContext context = TestContext(xaml, offset); Assert.AreEqual("Window", context.ActiveElement.Name); Assert.AreEqual(null, context.ParentElement); } [Test] public void IgnoredXmlnsTest1() { string xaml = File.ReadAllText("Test2.xaml"); int offset = 447; XamlContext context = TestContext(xaml, offset); Assert.AreEqual(1, context.IgnoredXmlns.Count); Assert.AreEqual("d", context.IgnoredXmlns[0]); } [Test] public void AncestorDetectionTest1() { string xaml = File.ReadAllText("Test5.xaml"); int offset = 881; XamlContext context = TestContext(xaml, offset); string[] ancestors = new string[] { "DoubleAnimation", "Storyboard", "BeginStoryboard", "EventTrigger", "Button.Triggers", "Button", "Grid", "Window" }; Assert.AreEqual("DoubleAnimation", context.ActiveElement.Name); Assert.AreEqual("Storyboard", context.ParentElement.Name); Assert.AreEqual(8, context.Ancestors.Count); Assert.AreEqual(ancestors, context.Ancestors.Select(item => item.Name).ToArray()); } [Test] public void InValueTestWithOpenValue() { string fileHeader = @"<Window x:Class='ICSharpCode.XamlBinding.Tests.CompletionTestsBase' xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width='"; string fileFooter = @" <Button AllowDrop='True' Grid.Row='0' /> </Grid> </Window>"; XamlContext context = TestContext(fileHeader + fileFooter, fileHeader.Length); Assert.AreEqual(XamlContextDescription.InAttributeValue, context.Description); } } }
33.183562
141
0.710122
[ "MIT" ]
TetradogOther/SharpDevelop
src/AddIns/BackendBindings/XamlBinding/XamlBinding.Tests/ResolveContextTests.cs
12,114
C#
using System.Xml.Serialization; using Wps.Client.Utils; namespace Wps.Client.Models.Ows { /// <summary> /// Information for contacting the service provider. /// </summary> [XmlRoot("ServiceContact", Namespace = ModelNamespaces.Ows)] public class ServiceContact { /// <summary> /// Name of the responsible person. /// </summary> [XmlElement("IndividualName", Namespace = ModelNamespaces.Ows)] public string IndividualName { get; set; } /// <summary> /// Role or position of the responsible person. /// </summary> [XmlElement("PositionName", Namespace = ModelNamespaces.Ows)] public string PositionName { get; set; } /// <summary> /// Address of the responsible party. /// </summary> [XmlElement("ContactInfo", Namespace = ModelNamespaces.Ows)] public ContactInfo ContactInfo { get; set; } /// <summary> /// Function performed by the responsible party. /// </summary> [XmlElement("Role", Namespace = ModelNamespaces.Ows)] public string Role { get; set; } } }
29.538462
71
0.601563
[ "Apache-2.0" ]
52North/wps.net
src/Wps/Wps.Client/Models/Ows/ServiceContact.cs
1,154
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("05.DecodeRadioFrequencies")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("05.DecodeRadioFrequencies")] [assembly: AssemblyCopyright("Copyright © 2017")] [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("abc8a9dd-aaba-4086-9427-2e717f797d74")] // 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")]
38.459459
84
0.748419
[ "MIT" ]
dgeshev/-Programming-Fundamentals
Extended mode/08.Array-and-List-Algorithms-Exercises/05.DecodeRadioFrequencies/Properties/AssemblyInfo.cs
1,426
C#
using System; using System.Collections.Generic; using System.ComponentModel; using BannerlordTwitch; using BannerlordTwitch.Helpers; using BannerlordTwitch.Util; using JetBrains.Annotations; using TaleWorlds.CampaignSystem; using TaleWorlds.CampaignSystem.SandBox.CampaignBehaviors.Towns; using TaleWorlds.Core; using Xceed.Wpf.Toolkit.PropertyGrid.Attributes; namespace BLTAdoptAHero { [UsedImplicitly] [Description("Improve adopted heroes skills")] internal class SkillXP : ImproveAdoptedHero { protected class SkillXPSettings : SettingsBase, IDocumentable { [Description("What to improve"), PropertyOrder(1), UsedImplicitly] public SkillsEnum Skills { get; set; } [Description("Chooses a random skill to add XP to, prefering class skills, " + "then skills for current equipment, then other skills. " + "Skills setting is ignored when auto is used."), PropertyOrder(2), UsedImplicitly] public bool Auto { get; set; } = true; public void GenerateDocumentation(IDocumentationGenerator generator) { generator.PropertyValuePair("Skills", $"{(Auto ? "Automatic, based on class, equipment, and existing skills" : Skills)}"); generator.PropertyValuePair("XP", $"{AmountLow}" + (AmountLow == AmountHigh ? $"" : $" to {AmountHigh}")); if (GoldCost != 0) { generator.PropertyValuePair("Costs", $"{GoldCost}{Naming.Gold}"); } } } protected override Type ConfigType => typeof(SkillXPSettings); protected override (bool success, string description) Improve(string userName, Hero adoptedHero, int amount, SettingsBase baseSettings, string args) { var settings = (SkillXPSettings) baseSettings; return ImproveSkill(adoptedHero, amount, settings.Skills, settings.Auto); } public static (bool success, string description) ImproveSkill(Hero hero, int amount, SkillsEnum skills, bool auto) { var skill = GetSkill(hero, skills, auto, so => BLTAdoptAHeroModule.CommonConfig.UseRawXP && hero.GetSkillValue(so) < BLTAdoptAHeroModule.CommonConfig.RawXPSkillCap || hero.HeroDeveloper.GetFocusFactor(so) > 0); if (skill == null) return (false, $"Couldn't find a skill to improve"); float prevSkill = hero.HeroDeveloper.GetPropertyValue(skill); int prevLevel = hero.GetSkillValue(skill); hero.HeroDeveloper.AddSkillXp(skill, amount, isAffectedByFocusFactor: !BLTAdoptAHeroModule.CommonConfig.UseRawXP); // Force this immediately instead of waiting for the daily campaign tick #if e159 || e1510 CharacterDevelopmentCampaignBehaivor.DevelopCharacterStats(hero); #else Campaign.Current?.GetCampaignBehavior<CharacterDevelopmentCampaignBehavior>()?.DevelopCharacterStats(hero); #endif float newXp = hero.HeroDeveloper.GetPropertyValue(skill); float realGainedXp = newXp - prevSkill; int newLevel = hero.GetSkillValue(skill); int gainedLevels = newLevel - prevLevel; return realGainedXp < 1f ? (false, $"{skill.Name} capped, get more focus points") : gainedLevels > 0 ? (true, $"{Naming.Inc}{gainedLevels} lvl {GetShortSkillName(skill)}{Naming.To}{newLevel}") : (true, $"{Naming.Inc}{realGainedXp:0} xp {GetShortSkillName(skill)}{Naming.To}{newXp}"); } public static string GetShortSkillName(SkillObject skill) { return SkillMapping.TryGetValue(skill.StringId, out string shortSkillName) ? shortSkillName : skill.Name.ToString(); } private static readonly Dictionary<string, string> SkillMapping = new() { {"OneHanded", "1H"}, {"TwoHanded", "2H"}, {"Polearm", "PA"}, {"Bow", "Bow"}, {"Crossbow", "Xb"}, {"Throwing", "Thr"}, {"Riding", "Rid"}, {"Athletics", "Ath"}, {"Crafting", "Smt"}, {"Tactics", "Tac"}, {"Scouting", "Sct"}, {"Roguery", "Rog"}, {"Charm", "Cha"}, {"Trade", "Trd"}, {"Steward", "Stw"}, {"Leadership", "Ldr"}, {"Medicine", "Med"}, {"Engineering", "Eng"}, }; } }
44.028302
138
0.592886
[ "MIT" ]
GoryMoon/Bannerlord-Twitch
BannerlordTwitch/BLTAdoptAHero/Actions/SkillXP.cs
4,667
C#
using System; using System.ComponentModel; using EfsTools.Attributes; using EfsTools.Utils; using Newtonsoft.Json; namespace EfsTools.Items.Nv { [Serializable] [NvItemId(2014)] [Attributes(9)] public class WcdmaTxLinVsTemp3 { [ElementsCount(8)] [ElementType("int8")] [Description("")] public sbyte[] Value { get; set; } } }
19.52381
43
0.597561
[ "MIT" ]
HomerSp/EfsTools
EfsTools/Items/Nv/WcdmaTxLinVsTemp3I.cs
410
C#
using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; namespace Umbraco.Cms.Core.HealthChecks { /// <summary> /// The status returned for a health check when it performs it check /// TODO: This model will be used in the WebApi result so needs attributes for JSON usage /// </summary> [DataContract(Name = "healthCheckStatus", Namespace = "")] public class HealthCheckStatus { public HealthCheckStatus(string message) { Message = message; Actions = Enumerable.Empty<HealthCheckAction>(); } /// <summary> /// The status message /// </summary> [DataMember(Name = "message")] public string Message { get; private set; } /// <summary> /// The status description if one is necessary /// </summary> [DataMember(Name = "description")] public string? Description { get; set; } /// <summary> /// This is optional but would allow a developer to specify a path to an angular HTML view /// in order to either show more advanced information and/or to provide input for the admin /// to configure how an action is executed /// </summary> [DataMember(Name = "view")] public string? View { get; set; } /// <summary> /// The status type /// </summary> [DataMember(Name = "resultType")] public StatusResultType ResultType { get; set; } /// <summary> /// The potential actions to take (in any) /// </summary> [DataMember(Name = "actions")] public IEnumerable<HealthCheckAction> Actions { get; set; } /// <summary> /// This is optional but would allow a developer to specify a link that is shown as a "read more" button. /// </summary> [DataMember(Name = "readMoreLink")] public string? ReadMoreLink { get; set; } } }
33.491525
113
0.592105
[ "MIT" ]
Lantzify/Umbraco-CMS
src/Umbraco.Core/HealthChecks/HealthCheckStatus.cs
1,978
C#
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.CosmosDB { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// RestorableGremlinResourcesOperations operations. /// </summary> internal partial class RestorableGremlinResourcesOperations : IServiceOperations<CosmosDBManagementClient>, IRestorableGremlinResourcesOperations { /// <summary> /// Initializes a new instance of the RestorableGremlinResourcesOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal RestorableGremlinResourcesOperations(CosmosDBManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the CosmosDBManagementClient /// </summary> public CosmosDBManagementClient Client { get; private set; } /// <summary> /// Return a list of gremlin database and graphs combo that exist on the /// account at the given timestamp and location. This helps in scenarios to /// validate what resources exist at given timestamp and location. This API /// requires /// 'Microsoft.DocumentDB/locations/restorableDatabaseAccounts/.../read' /// permission. /// </summary> /// <param name='location'> /// Cosmos DB region, with spaces between words and each word capitalized. /// </param> /// <param name='instanceId'> /// The instanceId GUID of a restorable database account. /// </param> /// <param name='restoreLocation'> /// The location where the restorable resources are located. /// </param> /// <param name='restoreTimestampInUtc'> /// The timestamp when the restorable resources existed. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// 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<AzureOperationResponse<IEnumerable<GremlinDatabaseRestoreResource>>> ListWithHttpMessagesAsync(string location, string instanceId, string restoreLocation = default(string), string restoreTimestampInUtc = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.ApiVersion != null) { if (Client.ApiVersion.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "Client.ApiVersion", 1); } } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (Client.SubscriptionId != null) { if (Client.SubscriptionId.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "Client.SubscriptionId", 1); } } if (location == null) { throw new ValidationException(ValidationRules.CannotBeNull, "location"); } if (instanceId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "instanceId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("location", location); tracingParameters.Add("instanceId", instanceId); tracingParameters.Add("restoreLocation", restoreLocation); tracingParameters.Add("restoreTimestampInUtc", restoreTimestampInUtc); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.DocumentDB/locations/{location}/restorableDatabaseAccounts/{instanceId}/restorableGremlinResources").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{location}", System.Uri.EscapeDataString(location)); _url = _url.Replace("{instanceId}", System.Uri.EscapeDataString(instanceId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (restoreLocation != null) { _queryParameters.Add(string.Format("restoreLocation={0}", System.Uri.EscapeDataString(restoreLocation))); } if (restoreTimestampInUtc != null) { _queryParameters.Add(string.Format("restoreTimestampInUtc={0}", System.Uri.EscapeDataString(restoreTimestampInUtc))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + 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 (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } 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 CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IEnumerable<GremlinDatabaseRestoreResource>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<GremlinDatabaseRestoreResource>>(_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.716783
367
0.577606
[ "MIT" ]
AikoBB/azure-sdk-for-net
sdk/cosmosdb/Microsoft.Azure.Management.CosmosDB/src/Generated/RestorableGremlinResourcesOperations.cs
12,789
C#
using Microsoft.ServiceBus.Messaging; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IEventProcessorHost { class SimpleEventProcessor : IEventProcessor { Stopwatch checkpointStopWatch; async Task IEventProcessor.CloseAsync(PartitionContext context, CloseReason reason) { Console.WriteLine("Processor Shutting Down. Partition '{0}', Reason: '{1}'.", context.Lease.PartitionId, reason); if (reason == CloseReason.Shutdown) { await context.CheckpointAsync(); } } Task IEventProcessor.OpenAsync(PartitionContext context) { Console.WriteLine("SimpleEventProcessor initialized. Partition: '{0}', Offset: '{1}'", context.Lease.PartitionId, context.Lease.Offset); this.checkpointStopWatch = new Stopwatch(); this.checkpointStopWatch.Start(); return Task.FromResult<object>(null); } async Task IEventProcessor.ProcessEventsAsync(PartitionContext context, IEnumerable<EventData> messages) { foreach (EventData eventData in messages) { string data = Encoding.UTF8.GetString(eventData.GetBytes()); Console.WriteLine(string.Format("Message received. Partition: '{0}', Data: '{1}'", context.Lease.PartitionId, data)); } //Call checkpoint every 5 minutes, so that worker can resume processing from 5 minutes back if it restarts. if (this.checkpointStopWatch.Elapsed > TimeSpan.FromMinutes(5)) { await context.CheckpointAsync(); this.checkpointStopWatch.Restart(); } } } }
36.137255
149
0.630494
[ "MIT" ]
tkopacz/2016windowsiot-iothub-genericsender
SamplePCClient/IoTClient/IEventProcessorHost/SimpleEventProcessor.cs
1,845
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/projectedfslib.h in the Windows SDK for Windows 10.0.19041.0 // Original source is Copyright © Microsoft. All rights reserved. using System; namespace TerraFX.Interop { public unsafe partial struct PRJ_CALLBACK_DATA { [NativeTypeName("UINT32")] public uint Size; public PRJ_CALLBACK_DATA_FLAGS Flags; [NativeTypeName("PRJ_NAMESPACE_VIRTUALIZATION_CONTEXT")] public IntPtr NamespaceVirtualizationContext; [NativeTypeName("INT32")] public int CommandId; [NativeTypeName("GUID")] public Guid FileId; [NativeTypeName("GUID")] public Guid DataStreamId; [NativeTypeName("PCWSTR")] public ushort* FilePathName; [NativeTypeName("PRJ_PLACEHOLDER_VERSION_INFO *")] public PRJ_PLACEHOLDER_VERSION_INFO* VersionInfo; [NativeTypeName("UINT32")] public uint TriggeringProcessId; [NativeTypeName("PCWSTR")] public ushort* TriggeringProcessImageFileName; [NativeTypeName("void *")] public void* InstanceContext; } }
27.933333
145
0.683373
[ "MIT" ]
Perksey/terrafx.interop.windows
sources/Interop/Windows/um/projectedfslib/PRJ_CALLBACK_DATA.cs
1,259
C#