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 |
|---|---|---|---|---|---|---|---|---|
// <copyright file="AssertedTableFormLine.cs" company="Automate The Planet Ltd.">
// Copyright 2021 Automate The Planet 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.
// </copyright>
// <author>Anton Angelov</author>
// <site>https://bellatrix.solutions/</site>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Azure.AI.FormRecognizer.Models;
using Bellatrix.Assertions;
namespace Bellatrix.CognitiveServices.services
{
public class AssertedTableFormLine
{
public static event EventHandler<string> TableFormLineAsserted;
private readonly FormLine _formLine;
public AssertedTableFormLine(FormLine formLine)
{
_formLine = formLine;
}
public List<string> Words => _formLine.Words.Select(x => x.Text).ToList();
public FieldBoundingBox BoundingBox => _formLine.BoundingBox;
public FormLine WrappedFormLine => _formLine;
public void AssertWordsCount(int expectedWordsCount)
{
TableFormLineAsserted?.Invoke(this, $"Assert line words' count = {expectedWordsCount}");
Assert.AreEqual(expectedWordsCount, _formLine.Words.Count, $"Line words' count != {expectedWordsCount}");
}
public void AssertWordsEqual(params string[] expectedWords)
{
TableFormLineAsserted?.Invoke(this, $"Assert line words are {expectedWords}");
CollectionAssert.AreEqual(expectedWords, Words, "Expected words are different than the actual ones present on the line.");
}
public void AssertWordsContain(params string[] expectedWords)
{
TableFormLineAsserted?.Invoke(this, $"Assert line words contain the words: {expectedWords}");
CollectionAssert.IsSubsetOf(expectedWords, Words, "Expected words are different than the actual ones present on the line.");
}
}
}
| 42.701754 | 136 | 0.712818 | [
"Apache-2.0"
] | 48x16/BELLATRIX | src/Bellatrix.CognitiveServices/services/AssertedTableFormLine.cs | 2,436 | 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/MsHTML.h in the Windows SDK for Windows 10.0.22000.0
// Original source is Copyright © Microsoft. All rights reserved.
using NUnit.Framework;
using System;
using System.Runtime.InteropServices;
using static TerraFX.Interop.Windows.IID;
namespace TerraFX.Interop.Windows.UnitTests;
/// <summary>Provides validation of the <see cref="IDOMTextEvent" /> struct.</summary>
public static unsafe partial class IDOMTextEventTests
{
/// <summary>Validates that the <see cref="Guid" /> of the <see cref="IDOMTextEvent" /> struct is correct.</summary>
[Test]
public static void GuidOfTest()
{
Assert.That(typeof(IDOMTextEvent).GUID, Is.EqualTo(IID_IDOMTextEvent));
}
/// <summary>Validates that the <see cref="IDOMTextEvent" /> struct is blittable.</summary>
[Test]
public static void IsBlittableTest()
{
Assert.That(Marshal.SizeOf<IDOMTextEvent>(), Is.EqualTo(sizeof(IDOMTextEvent)));
}
/// <summary>Validates that the <see cref="IDOMTextEvent" /> struct has the right <see cref="LayoutKind" />.</summary>
[Test]
public static void IsLayoutSequentialTest()
{
Assert.That(typeof(IDOMTextEvent).IsLayoutSequential, Is.True);
}
/// <summary>Validates that the <see cref="IDOMTextEvent" /> struct has the correct size.</summary>
[Test]
public static void SizeOfTest()
{
if (Environment.Is64BitProcess)
{
Assert.That(sizeof(IDOMTextEvent), Is.EqualTo(8));
}
else
{
Assert.That(sizeof(IDOMTextEvent), Is.EqualTo(4));
}
}
}
| 34.392157 | 145 | 0.68073 | [
"MIT"
] | reflectronic/terrafx.interop.windows | tests/Interop/Windows/Windows/um/MsHTML/IDOMTextEventTests.cs | 1,756 | C# |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace LumiSoft.Net.HTTP.Server
{
/// <summary>
/// HTTP server component.
/// </summary>
public class HTTP_Server : SocketServer
{
/// <summary>
/// Defalut constructor.
/// </summary>
public HTTP_Server() : base()
{
this.BindInfo = new BindInfo[]{new BindInfo(IPAddress.Any,80,false,null)};
}
#region override InitNewSession
/// <summary>
/// Initialize and start new session here. Session isn't added to session list automatically,
/// session must add itself to server session list by calling AddSession().
/// </summary>
/// <param name="socket">Connected client socket.</param>
/// <param name="bindInfo">BindInfo what accepted socket.</param>
protected override void InitNewSession(Socket socket,BindInfo bindInfo)
{/*
// Check maximum conncurent connections from 1 IP.
if(m_MaxConnectionsPerIP > 0){
lock(this.Sessions){
int nSessions = 0;
foreach(SocketServerSession s in this.Sessions){
IPEndPoint ipEndpoint = s.RemoteEndPoint;
if(ipEndpoint != null){
if(ipEndpoint.Address.Equals(((IPEndPoint)socket.RemoteEndPoint).Address)){
nSessions++;
}
}
// Maximum allowed exceeded
if(nSessions >= m_MaxConnectionsPerIP){
socket.Send(System.Text.Encoding.ASCII.GetBytes("-ERR Maximum connections from your IP address is exceeded, try again later !\r\n"));
socket.Shutdown(SocketShutdown.Both);
socket.Close();
return;
}
}
}
}*/
string sessionID = Guid.NewGuid().ToString();
SocketEx socketEx = new SocketEx(socket);
if(LogCommands){
//socketEx.Logger = new SocketLogger(socket,this.SessionLog);
//socketEx.Logger.SessionID = sessionID;
}
HTTP_Session session = new HTTP_Session(sessionID,socketEx,bindInfo,this);
}
#endregion
}
}
| 34.813953 | 161 | 0.592518 | [
"ECL-2.0",
"Apache-2.0",
"MIT"
] | ONLYOFFICE/CommunityServer | module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/HTTP/Server/HTTP_Server.cs | 2,994 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Linq;
using Xunit;
namespace Microsoft.Framework.FileSystemGlobbing.Tests.TestUtility
{
internal class FileSystemGlobbingTestContext
{
private readonly string _basePath;
private readonly FileSystemOperationRecorder _recorder;
private readonly Matcher _patternMatching;
private MockDirectoryInfo _directoryInfo;
private PatternMatchingResult _result;
public FileSystemGlobbingTestContext(string basePath, Matcher matcher)
{
_basePath = basePath;
_recorder = new FileSystemOperationRecorder();
_patternMatching = matcher;
_directoryInfo = new MockDirectoryInfo(
recorder: _recorder,
parentDirectory: null,
fullName: _basePath,
name: ".",
paths: new string[0]);
}
public FileSystemGlobbingTestContext Include(params string[] patterns)
{
foreach (var pattern in patterns)
{
_patternMatching.AddInclude(pattern);
}
return this;
}
public FileSystemGlobbingTestContext Exclude(params string[] patterns)
{
foreach (var pattern in patterns)
{
_patternMatching.AddExclude(pattern);
}
return this;
}
public FileSystemGlobbingTestContext Files(params string[] files)
{
_directoryInfo = new MockDirectoryInfo(
_directoryInfo.Recorder,
_directoryInfo.ParentDirectory,
_directoryInfo.FullName,
_directoryInfo.Name,
_directoryInfo.Paths.Concat(files.Select(file => _basePath + file)).ToArray());
return this;
}
public FileSystemGlobbingTestContext Execute()
{
_result = _patternMatching.Execute(_directoryInfo);
return this;
}
public FileSystemGlobbingTestContext AssertExact(params string[] files)
{
Assert.Equal(files.OrderBy(file => file), _result.Files.OrderBy(file => file));
return this;
}
public FileSystemGlobbingTestContext SubDirectory(string name)
{
_directoryInfo = (MockDirectoryInfo)_directoryInfo.GetDirectory(name);
return this;
}
}
}
| 30.388235 | 111 | 0.606659 | [
"Apache-2.0"
] | mj1856/FileSystem | test/Microsoft.Framework.FileSystemGlobbing.Tests/TestUtility/FileSystemGlobbingTestContext.cs | 2,583 | C# |
namespace Hotel_Yavin
{
partial class Restaurar_copia_de_seguridad
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.btn_restaurar = new System.Windows.Forms.Button();
this.dgv_listadoBackups = new System.Windows.Forms.DataGridView();
this.HelpProviderHG = new System.Windows.Forms.HelpProvider();
((System.ComponentModel.ISupportInitialize)(this.dgv_listadoBackups)).BeginInit();
this.SuspendLayout();
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(24, 20);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(159, 13);
this.label1.TabIndex = 0;
this.label1.Text = "Seleccionar Copia de Seguridad";
//
// btn_restaurar
//
this.HelpProviderHG.SetHelpKeyword(this.btn_restaurar, "Restaurar_copia_de_seguridad.htm#btn_restaurar");
this.HelpProviderHG.SetHelpNavigator(this.btn_restaurar, System.Windows.Forms.HelpNavigator.Topic);
this.btn_restaurar.Location = new System.Drawing.Point(256, 200);
this.btn_restaurar.Name = "btn_restaurar";
this.HelpProviderHG.SetShowHelp(this.btn_restaurar, true);
this.btn_restaurar.Size = new System.Drawing.Size(75, 23);
this.btn_restaurar.TabIndex = 3;
this.btn_restaurar.Text = "Restaurar";
this.btn_restaurar.UseVisualStyleBackColor = true;
this.btn_restaurar.Click += new System.EventHandler(this.btn_restaurar_Click);
//
// dgv_listadoBackups
//
this.dgv_listadoBackups.AllowUserToAddRows = false;
this.dgv_listadoBackups.AllowUserToDeleteRows = false;
this.dgv_listadoBackups.AllowUserToOrderColumns = true;
this.dgv_listadoBackups.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.HelpProviderHG.SetHelpKeyword(this.dgv_listadoBackups, "Restaurar_copia_de_seguridad.htm#dgv_listadoBackups");
this.HelpProviderHG.SetHelpNavigator(this.dgv_listadoBackups, System.Windows.Forms.HelpNavigator.Topic);
this.dgv_listadoBackups.Location = new System.Drawing.Point(27, 44);
this.dgv_listadoBackups.MultiSelect = false;
this.dgv_listadoBackups.Name = "dgv_listadoBackups";
this.dgv_listadoBackups.ReadOnly = true;
this.dgv_listadoBackups.RowHeadersVisible = false;
this.dgv_listadoBackups.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
this.HelpProviderHG.SetShowHelp(this.dgv_listadoBackups, true);
this.dgv_listadoBackups.Size = new System.Drawing.Size(304, 150);
this.dgv_listadoBackups.TabIndex = 4;
//
// HelpProviderHG
//
this.HelpProviderHG.HelpNamespace = "Hotel_Yavin_manual.chm";
//
// Restaurar_copia_de_seguridad
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(356, 238);
this.Controls.Add(this.dgv_listadoBackups);
this.Controls.Add(this.btn_restaurar);
this.Controls.Add(this.label1);
this.HelpProviderHG.SetHelpKeyword(this, "Restaurar_copia_de_seguridad.htm");
this.HelpProviderHG.SetHelpNavigator(this, System.Windows.Forms.HelpNavigator.Topic);
this.Name = "Restaurar_copia_de_seguridad";
this.HelpProviderHG.SetShowHelp(this, true);
this.Text = "Restaurar copia de seguridad";
this.Load += new System.EventHandler(this.Restaurar_copia_de_seguridad_Load);
((System.ComponentModel.ISupportInitialize)(this.dgv_listadoBackups)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button btn_restaurar;
private System.Windows.Forms.DataGridView dgv_listadoBackups;
private System.Windows.Forms.HelpProvider HelpProviderHG;
}
} | 48.614679 | 136 | 0.639932 | [
"MIT"
] | AAGODOY/hotel_yavin | src/Hotel Yavin/Restaurar copia de seguridad.Designer.cs | 5,301 | C# |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using UIBuildIt.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Globalization;
using UIBuildIt.Common.UseCases;
using System.Web.Http.Description;
using UIBuildIt.Security;
using UIBuildIt.Common.Authentication;
using UIBuildIt.Common.Base;
using UIBuildIt.Common.Tasks;
namespace UIBuildIt.WebService.Controllers.API.Tasks
{
public class MethodController : APIControllerBase<Method, MethodData>
{
protected override ICollection<MethodData> GetEntities(User user)
{
Item.SetProjectDetails(false);
return (from p in db.Projects
join m in db.Modules on p.Id equals m.ParentId
join c in db.Components on m.Id equals c.ParentId
join me in db.Methods on c.Id equals me.ParentId
where p.Owner.Id == user.Id
select me).ToList().Select(entity => CreateData(entity, entity.Id)).ToList();
}
protected override Project GetProject(Method entity)
{
return (from p in db.Projects
join m in db.Modules on p.Id equals m.ParentId
join c in db.Components on m.Id equals c.ParentId
where c.Id == entity.ParentId
select p).FirstOrDefault();
}
protected override IHttpActionResult Validate(Method entity)
{
var user = (User)Request.Properties["user"];
var component = db.Components.FirstOrDefault(c => c.Id == entity.ParentId);
if (component == null)
{
return Content<string>(HttpStatusCode.NotFound, string.Format("failed to get parent"));
}
if (!ModelState.IsValid)
{
return Content<string>(HttpStatusCode.BadRequest, ModelState.ToString());
}
return null;
}
protected override MethodData CreateData(Method u, int id)
{
var data = new MethodData(db, u);
return data;
}
protected override void ClearEntity(Method source)
{
ClearMethod(source);
}
}
} | 33.914286 | 103 | 0.611205 | [
"Apache-2.0"
] | ShyAlon/DeepDev | WebService/Controllers/API/Tasks/MethodController.cs | 2,376 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PolinomTask;
namespace ConsoleApp24
{
class Program
{
static void Main(string[] args)
{
var test = new Polinom("test.txt");
}
}
}
| 18.388889 | 48 | 0.58006 | [
"MIT"
] | Fiwer/Polinom | Polinom/Program.cs | 333 | C# |
using GloboCrypto.Models.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace GloboCrypto.PWA.Models
{
public class CoinTrackerCache
{
public DateTimeOffset CacheTime { get; set; }
public IEnumerable<CoinPriceInfo> CoinPrices { get; set; }
}
}
| 22.266667 | 66 | 0.727545 | [
"MIT"
] | steve-reteamlabs/GloboCrypto | GloboCrypto/GloboCrypto.PWA/Models/CoinTrackerCache.cs | 336 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace Ploeh.AutoFixture.Kernel
{
/// <summary>
/// Relays a request for an <see cref="IList{T}" /> to a request for a
/// <see cref="List{T}"/> and retuns the result.
/// </summary>
public class ListRelay : ISpecimenBuilder
{
/// <summary>
/// Creates a new specimen based on a request.
/// </summary>
/// <param name="request">The request that describes what to create.</param>
/// <param name="context">A context that can be used to create other specimens.</param>
/// <returns>
/// A populated <see cref="IList{T}"/> of the appropriate item type if possible; otherwise
/// a <see cref="NoSpecimen"/> instance.
/// </returns>
/// <remarks>
/// <para>
/// If <paramref name="request"/> is a request for an <see cref="IList{T}"/> and
/// <paramref name="context"/> can satisfy a request for a populated specimen of that type,
/// this value will be returned. If not, the return value is a <see cref="NoSpecimen"/>
/// instance.
/// </para>
/// </remarks>
public object Create(object request, ISpecimenContext context)
{
if (context == null)
throw new ArgumentNullException("context");
var t = request as Type;
if (t == null)
return new NoSpecimen(request);
var typeArguments = t.GetGenericArguments();
if (typeArguments.Length != 1 ||
typeof(IList<>) != t.GetGenericTypeDefinition())
return new NoSpecimen(request);
return context.Resolve(
typeof(List<>).MakeGenericType(typeArguments));
}
}
}
| 37.918367 | 100 | 0.553821 | [
"MIT"
] | amarant/AutoFixture | Src/AutoFixture/Kernel/ListRelay.cs | 1,860 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LineRenderExtend : MonoBehaviour {
public AtkRangeEffect rangeEffect;
public LineRenderer linerender;
public AnimationCurve anim_alpha;
public Color color_alpha = Color.white;
public float m_time;
public float width_rate = 3.0f;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
UpdateTime();
UpdateAlpha();
UpdateWidth();
}
public void UpdateTime() {
m_time = rangeEffect.br/1.2f;
}
public void UpdateAlpha() {
color_alpha.a = anim_alpha.Evaluate(m_time);
linerender.startColor = color_alpha;
linerender.endColor = color_alpha;
}
public void UpdateWidth() {
linerender.widthMultiplier = anim_alpha.Evaluate(m_time) / width_rate;
}
}
| 15.648148 | 72 | 0.72071 | [
"MIT"
] | Canvastudio/Prometheus | Code/Prometheus/Assets/Art/Fx/Scripts/Effect/LineRenderExtend.cs | 847 | C# |
namespace Nancy.Metadata.Modules
{
using System;
using Nancy.Routing;
/// <summary>
/// Defines facilities for obtaining metadata for a given <see cref="RouteDescription"/>.
/// </summary>
public interface IMetadataModule
{
/// <summary>
/// Gets the <see cref="Type"/> of metadata the <see cref="IMetadataModule"/> returns.
/// </summary>
Type MetadataType { get; }
/// <summary>
/// Returns metadata for the given <see cref="RouteDescription"/>.
/// </summary>
/// <param name="description">The route to obtain metadata for.</param>
/// <returns>An instance of <see cref="MetadataType"/> if one exists, otherwise null.</returns>
object GetMetadata(RouteDescription description);
}
} | 34.291667 | 104 | 0.596598 | [
"MIT"
] | 0x414c49/Nancy | src/Nancy.Metadata.Modules/IMetadataModule.cs | 825 | C# |
namespace Yetibyte.Unity.SpeechRecognition.Serialization
{
public interface IVoskResultDeserializer
{
IVoskResult Deserialize(string input);
}
}
| 18.555556 | 57 | 0.736527 | [
"MIT"
] | Yeti47/Vosk4Unity | Assets/Src/Yetibyte.Unity.SpeechRecognition/IVoskResultDeserializer.cs | 169 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace EasyDotNet.LinQ
{
/// <summary>
/// 扩展LinQ.Distinct方法
/// var list = list.Distinct(m=>m.variableName);//去掉variableName重复的数据
/// </summary>
public static class DistinctExtensions
{
public static IEnumerable<T> Distinct<T, V>(this IEnumerable<T> source, Func<T, V> keySelector)
{
return source.Distinct(new CommonEqualityComparer<T, V>(keySelector));
}
}
public class CommonEqualityComparer<T, V> : IEqualityComparer<T>
{
private Func<T, V> keySelector;
public CommonEqualityComparer(Func<T, V> keySelector)
{
this.keySelector = keySelector;
}
public bool Equals(T x, T y)
{
return EqualityComparer<V>.Default.Equals(keySelector(x), keySelector(y));
}
public int GetHashCode(T obj)
{
return EqualityComparer<V>.Default.GetHashCode(keySelector(obj));
}
}
}
| 26.3 | 103 | 0.61597 | [
"Apache-2.0"
] | FB208/Easy.Net | EasyDotNet/EasyDotNet/LinQ/DistinctExtensions.cs | 1,076 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace GeolocatorTests.UWP
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage
{
public MainPage()
{
this.InitializeComponent();
LoadApplication(new GeolocatorTests.App());
}
}
}
| 27.4375 | 107 | 0.722096 | [
"MIT"
] | AuriR/GeolocatorPlugin | tests/GeolocatorTests.UWP/MainPage.xaml.cs | 880 | C# |
using Prism.Services.Dialogs;
using System;
using SystemMonitor.Interfaces.Ioc;
namespace SystemMonitor.Infrastructure.Interfaces.Dialogs
{
/// <summary>
/// Extending Prism.Services.Dialogs.IDialogService
/// </summary>
public interface IDialogService
: Prism.Services.Dialogs.IDialogService
, ISingletonDependency
{
IDialog Create(string name, IDialogParameters parameters, Action<IDialogResult> callback);
}
}
| 27.294118 | 98 | 0.726293 | [
"MIT"
] | omahost/SystemMonitor | SystemMonitor.Infrastructure.Interfaces/Dialogs/IDialogService.cs | 466 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OddOrEven
{
class Program
{
static void Main(string[] args)
{
var number = int.Parse(Console.ReadLine());
if (number % 2 == 0)
{
Console.WriteLine("even");
}
else if (number % 2 != 0)
{
Console.WriteLine("odd");
}
}
}
}
| 20 | 55 | 0.488 | [
"MIT"
] | vesopk/Programming-Basics-Problems | SimpleConditions/OddOrEven/Program.cs | 502 | C# |
using IExpress.Core.Data;
using IExpress.Pagamentos.Domain.DomainObjects;
namespace IExpress.Pagamentos.Domain.Repositories
{
public interface IPagamentoRepository : IRepository<Pagamento>
{
void AdicionarTransacao(Transacao transacao);
}
}
| 22 | 66 | 0.768939 | [
"MIT"
] | OdairDantas/IExpress | src/IExpress.Pagamentos.Domain/Repositories/IPagamentoRepository.cs | 266 | C# |
using System;
using System.Data;
using System.Data.SqlTypes;
using System.Globalization;
using NUnit.Framework;
using BLToolkit.Data;
using BLToolkit.Mapping;
namespace Mapping
{
[TestFixture]
public class MemberMapperTest
{
public class Object1
{
public int Int32;
public float Float;
public DayOfWeek Dow1;
public DayOfWeek Dow2;
}
[Test]
public void PrimitiveMemberTest()
{
ObjectMapper om = Map.GetObjectMapper(typeof(Object1));
Object1 o = new Object1();
DayOfWeek de = DayOfWeek.Thursday;
short di = (short)de;
om.SetValue(o, "Int32", 123.56);
om.SetValue(o, "Float", 123.57.ToString());
om.SetValue(o, "Dow1", de);
om.SetValue(o, "Dow2", di);
Assert.AreEqual(123, om.GetValue(o, "Int32"));
Assert.AreEqual(de, om.GetValue(o, "Dow1"));
Assert.AreEqual(de, om.GetValue(o, "Dow2"));
Assert.IsTrue (Math.Abs(123.57 - (float)om.GetValue(o, "Float")) < 0.0001);
Assert.IsNull(om.GetValue(o, "blah-blah-blah"));
}
public class AnsiStringObject
{
[MemberMapper(typeof(AnsiStringNumberMapper))]
public string ansi;
public string unicode;
}
internal class AnsiStringNumberMapper : MemberMapper
{
public override void Init(MapMemberInfo mapMemberInfo)
{
mapMemberInfo.DbType = DbType.AnsiString;
base.Init(mapMemberInfo);
}
}
#if !SQLCE
[Test]
#endif
public void ProvideCustomDBTypeTest()
{
AnsiStringObject obj = new AnsiStringObject();
obj.ansi = "ansi";
obj.unicode = "unicode";
IDbDataParameter[] parametrs = new DbManager().CreateParameters( obj );
Assert.AreEqual(2, parametrs.Length);
Assert.AreEqual(DbType.String, parametrs[1].DbType);
#if !FIREBIRD
// AnsiString is not supported by FB.
//
Assert.AreEqual(DbType.AnsiString, parametrs[0].DbType);
#endif
}
public class Object2
{
public short? Int16;
public int? Int32;
public long? Int64;
public float? Float;
public Guid? Guid;
public DayOfWeek? Dow1;
public DayOfWeek? Dow2;
}
[Test]
public void NullableMemberTest()
{
Object2 o = new Object2();
short? s = 125;
Guid g = Guid.NewGuid();
DayOfWeek de = DayOfWeek.Thursday;
int di = (int)de;
ObjectMapper<Object2>.SetValue(o, "Int16", s);
ObjectMapper<Object2>.SetValue(o, "Int32", 123.56);
ObjectMapper<Object2>.SetValue(o, "Int64", null);
ObjectMapper<Object2>.SetValue(o, "Float", 123.57.ToString());
ObjectMapper<Object2>.SetValue(o, "Guid", (Guid?)g);
ObjectMapper<Object2>.SetValue(o, "Guid", g);
ObjectMapper<Object2>.SetValue(o, "Dow1", de);
ObjectMapper<Object2>.SetValue(o, "Dow1", (DayOfWeek?)de);
ObjectMapper<Object2>.SetValue(o, "Dow2", di);
Assert.AreEqual(125, o.Int16);
Assert.AreEqual(123, o.Int32);
Assert.IsNull ( o.Int64);
Assert.AreEqual(g, o.Guid);
Assert.AreEqual(de, o.Dow1);
Assert.AreEqual(de, o.Dow2);
Assert.IsTrue (Math.Abs(123.57 - o.Float.Value) < 0.0001);
Assert.AreEqual(125, ObjectMapper<Object2>.GetValue(o, "Int16"));
Assert.AreEqual(123, ObjectMapper<Object2>.GetValue(o, "Int32"));
Assert.IsNull ( ObjectMapper<Object2>.GetValue(o, "Int64"));
Assert.AreEqual(g, ObjectMapper<Object2>.GetValue(o, "Guid"));
Assert.AreEqual(de, ObjectMapper<Object2>.GetValue(o, "Dow1"));
Assert.AreEqual(de, ObjectMapper<Object2>.GetValue(o, "Dow2"));
Assert.IsTrue (Math.Abs(123.57 - (float)ObjectMapper<Object2>.GetValue(o, "Float")) < 0.0001);
}
public class Object3
{
public SqlInt32 Int32;
public SqlSingle Single;
}
[Test]
// fixes test fail due to use of "," vs "." in numbers parsing for some cultures
[SetCulture("")]
public void SqlTypeMemberTest()
{
ObjectMapper om = Map.GetObjectMapper(typeof(Object3));
Object3 o = new Object3();
om.SetValue(o, "Int32", 123.56);
om.SetValue(o, "Single", 123.57.ToString(CultureInfo.InvariantCulture));
Assert.AreEqual(123, o.Int32. Value);
Assert.AreEqual(123.57f, o.Single.Value);
Assert.AreEqual(123, om.GetValue(o, "Int32"));
Assert.AreEqual(123.57f, om.GetValue(o, "Single"));
}
public interface IClassInterface
{
IClassInterface classInterface { get; set;}
}
public class ClassInterface : IClassInterface
{
private IClassInterface _ici;
[MapIgnore(false)]
public IClassInterface classInterface
{
get { return _ici; }
set { _ici = value; }
}
}
[Test]
public void DerivedTypeTest()
{
IClassInterface ici = new ClassInterface();
ObjectMapper om = Map.GetObjectMapper(ici.GetType());
MemberMapper mm = om["classInterface"];
mm.SetValue(ici, new ClassInterface());
}
public class Class1
{
int _int32 = 0;
[MapField(Storage = "_int32")]
public int Int32
{
get { return _int32; }
}
}
[Test]
public void MapToStorageTest()
{
Class1 o = new Class1();
ObjectMapper om = Map.GetObjectMapper(o.GetType());
MemberMapper mm = om["Int32"];
mm.SetValue(o, 5);
Assert.AreEqual(5, o.Int32);
}
}
}
| 25.936893 | 99 | 0.631293 | [
"MIT"
] | igor-tkachev/bltoolkit | UnitTests/CS/Mapping/MemberMapperTest.cs | 5,343 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Reflection;
using Microsoft.Win32;
using Xunit;
using static Interop.User32;
namespace System
{
public static class SystemEventsHelper
{
private static IntPtr GetHWnd()
{
// locate the hwnd used by SystemEvents in this domain
FieldInfo windowClassNameField = typeof(SystemEvents).GetField("s_className", BindingFlags.Static | BindingFlags.NonPublic) ?? // runtime
typeof(SystemEvents).GetField("className", BindingFlags.Static | BindingFlags.NonPublic); // desktop
Assert.NotNull(windowClassNameField);
string windowClassName = windowClassNameField.GetValue(null) as string;
Assert.NotNull(windowClassName);
IntPtr window = FindWindowW(windowClassName, null);
return window;
}
public static void SendMessageOnUserPreferenceChanged(UserPreferenceCategory category)
{
IntPtr window = GetHWnd();
WM msg;
IntPtr wParam;
if (category == UserPreferenceCategory.Color)
{
msg = WM.SYSCOLORCHANGE;
wParam = IntPtr.Zero;
}
else
{
msg = WM.SETTINGCHANGE;
if (category == UserPreferenceCategory.Accessibility)
{
wParam = (IntPtr)SPI.SETHIGHCONTRAST;
}
else if (category == UserPreferenceCategory.Desktop)
{
wParam = (IntPtr)SPI.SETDESKWALLPAPER;
}
else if (category == UserPreferenceCategory.Icon)
{
wParam = (IntPtr)SPI.ICONHORIZONTALSPACING;
}
else if (category == UserPreferenceCategory.Mouse)
{
wParam = (IntPtr)SPI.SETDOUBLECLICKTIME;
}
else if (category == UserPreferenceCategory.Keyboard)
{
wParam = (IntPtr)SPI.SETKEYBOARDDELAY;
}
else if (category == UserPreferenceCategory.Menu)
{
wParam = (IntPtr)SPI.SETMENUDROPALIGNMENT;
}
else if (category == UserPreferenceCategory.Power)
{
wParam = (IntPtr)SPI.SETLOWPOWERACTIVE;
}
else if (category == UserPreferenceCategory.Screensaver)
{
wParam = (IntPtr)SPI.SETMENUDROPALIGNMENT;
}
else if (category == UserPreferenceCategory.Window)
{
wParam = (IntPtr)SPI.SETMENUDROPALIGNMENT;
}
else
{
throw new NotImplementedException($"Not implemented category {category}.");
}
}
// Call with reflect to immediately send the message.
SendMessageW(window, msg | WM.REFLECT, wParam, IntPtr.Zero);
}
}
}
| 37.179775 | 150 | 0.532487 | [
"MIT"
] | ArtemTatarinov/winforms | src/System.Windows.Forms/tests/TestUtilities/SystemEventsHelper.cs | 3,311 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace prograV.UI.Pages.Vuelos {
public partial class AgregarVuelos {
/// <summary>
/// AlertMensaje control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlGenericControl AlertMensaje;
/// <summary>
/// textoMensaje control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlGenericControl textoMensaje;
/// <summary>
/// mensajeError control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlGenericControl mensajeError;
/// <summary>
/// textoMensajeError control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlGenericControl textoMensajeError;
/// <summary>
/// txtAerolinea control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtAerolinea;
/// <summary>
/// ddlCiudadOrigen control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.DropDownList ddlCiudadOrigen;
/// <summary>
/// ddlCiudadDestino control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.DropDownList ddlCiudadDestino;
/// <summary>
/// ddlClase control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.DropDownList ddlClase;
/// <summary>
/// FechaSalida control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Calendar FechaSalida;
/// <summary>
/// FechaLlegada control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Calendar FechaLlegada;
/// <summary>
/// txtCapacidad control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtCapacidad;
/// <summary>
/// FilteredTextBoxExtender2 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::AjaxControlToolkit.FilteredTextBoxExtender FilteredTextBoxExtender2;
/// <summary>
/// txtPrecioBase control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtPrecioBase;
/// <summary>
/// txtEscala control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox txtEscala;
/// <summary>
/// txtNumeroEscalas control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtNumeroEscalas;
/// <summary>
/// TextBox1_FilteredTextBoxExtender control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::AjaxControlToolkit.FilteredTextBoxExtender TextBox1_FilteredTextBoxExtender;
/// <summary>
/// btnAgregarVuelo control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button btnAgregarVuelo;
/// <summary>
/// btnActualizarVuelo control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button btnActualizarVuelo;
}
}
| 36.544944 | 102 | 0.558955 | [
"MIT"
] | dicarix/prograV | backend/prograV/prograV.UI/Pages/Vuelos/AgregarVuelos.aspx.designer.cs | 6,507 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HealthUi : MonoBehaviour
{
[SerializeField]
private GameObject healthBlockPrefab;
[SerializeField]
private HealthBlock[] healthBlocks;
[SerializeField]
private float instantiationDelay;
private float positionShift;
private int currentHealth = 0;
private void Start()
{
positionShift = healthBlockPrefab.GetComponent<HealthBlock>().standardSize * 1.5f;
}
public void SetHealthTo(int max, int current)
{
currentHealth = current;
StartCoroutine(SetHealthCoroutine(max, current));
}
public void ReduceHealthTo(int health)
{
for (int i = currentHealth - 1; i >= health; i--)
{
healthBlocks[i].Deplete();
}
currentHealth = health;
}
private IEnumerator SetHealthCoroutine(int max, int current)
{
healthBlocks = new HealthBlock[max];
Vector2 currentPosition = new Vector2(transform.position.x + positionShift, transform.position.y - positionShift);
for (int i = 0; i < max; i++)
{
// isntantiate new block at current position
GameObject newBlock = Instantiate(healthBlockPrefab, currentPosition, Quaternion.identity);
newBlock.transform.SetParent(gameObject.transform);
healthBlocks[i] = newBlock.GetComponent<HealthBlock>();
// define new position
currentPosition = new Vector2(currentPosition.x + positionShift, currentPosition.y);
}
for (int i = 0; i < current; i++)
{
healthBlocks[i].Gain();
yield return new WaitForSeconds(instantiationDelay);
}
for (int i = current; i < max; i++)
{
healthBlocks[i].Deplete();
yield return new WaitForSeconds(instantiationDelay);
}
}
}
| 31.129032 | 122 | 0.627979 | [
"MIT"
] | pzharkov/2D-Platformer | 2d Platformer/Assets/Scripts/UI Scripts/HealthUi.cs | 1,930 | C# |
using System;
using System.Collections.Generic;
using UnityEngine;
public abstract class BaseVariableAsset : ScriptableObject
{
#if UNITY_EDITOR
protected abstract void RaiseOnChange();
[UnityEditor.CustomEditor(typeof(BaseVariableAsset), true)]
public class BaseVariableAssetEditor : UnityEditor.Editor
{
public override void OnInspectorGUI()
{
DrawDefaultInspector();
if (Application.isPlaying && GUILayout.Button("Raise OnChange"))
{
((BaseVariableAsset)target).RaiseOnChange();
}
}
}
#endif
}
public class BaseVariableAsset<T> : BaseVariableAsset, IEquatable<T>
{
public delegate void Change(T current, T previous);
public event Change OnChange;
[SerializeField] protected T value;
public void Set(T newValue)
{
if (Equals(newValue))
return;
var previous = value;
value = newValue;
OnChange?.Invoke(value, previous);
}
public T Get()
{
return value;
}
public static implicit operator T(BaseVariableAsset<T> value) => value.value;
public virtual bool Equals(T other)
{
//NOTE(Brian): According to benchmarks I made, this statement costs about twice than == operator for structs.
// However, its way more costly for primitives (tested only against float).
// Left here only for fallback purposes. Optimally this method should be always overriden.
return EqualityComparer<T>.Default.Equals(value, other);
}
#if UNITY_EDITOR
protected sealed override void RaiseOnChange() => OnChange?.Invoke(value, value);
private void OnEnable()
{
Application.quitting -= CleanUp;
Application.quitting += CleanUp;
}
private void CleanUp()
{
Application.quitting -= CleanUp;
if (UnityEditor.AssetDatabase.Contains(this)) //It could happen that the base variable has been created in runtime
Resources.UnloadAsset(this);
}
#endif
} | 27.573333 | 122 | 0.648453 | [
"Apache-2.0"
] | Marguelgtz/explorer | unity-client/Assets/Scripts/MainScripts/DCL/ScriptableObject/Variables/BaseVariableAsset.cs | 2,070 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("DMPServerReportingReceiver")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("darklight")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("1.0.*")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
| 43.304348 | 82 | 0.752008 | [
"Unlicense"
] | godarklight/DMPServerListReportingReceiver | DMPServerReportingReceiver/Properties/AssemblyInfo.cs | 996 | C# |
using System;
using System.Collections.Generic;
using RestSharp;
namespace HelloSign
{
/// <summary>
/// Base class for Template-based and File-based Signature Request classes.
/// </summary>
public class BaseSignatureRequest
{
public string SignatureRequestId { get; set; }
public string Title { get; set; }
public string Subject { get; set; }
public string Message { get; set; }
public bool TestMode { get; set; }
public Dictionary<String, String> Metadata { get; set; }
public bool IsComplete { get; set; }
public bool HasError { get; set; }
public List<CustomField> CustomFields { get; set; }
public List<FieldResponse> ResponseData { get; set; }
public string SigningUrl { get; set; }
public string SigningRedirectUrl { get; set; }
public string RequestingRedirectUrl { get; set; }
public bool IsForEmbeddedSigning { get; set; }
public string DetailsUrl { get; set; }
public string RequesterEmailAddress { get; set; }
public bool AllowDecline { get; set; }
public bool SkipMeNow { get; set; }
public bool HoldRequest { get; set; }
public List<Signature> Signatures { get; set; }
public List<string> CcEmailAddresses { get; set; }
public SigningOptions SigningOptions { get; set; }
public List<Signer> Signers = new List<Signer>();
public BaseSignatureRequest()
{
Metadata = new Dictionary<String, String>();
CustomFields = new List<CustomField>();
CcEmailAddresses = new List<string>();
AllowDecline = false;
}
/// <summary>
/// Convenience method for creating and adding a Signer.
/// </summary>
/// <param name="emailAddress"></param>
/// <param name="name"></param>
/// <param name="order"></param>
/// <param name="pin"></param>
public void AddSigner(string emailAddress, string name, int? order = null, string pin = null)
{
Signers.Add(new Signer(emailAddress, name, order, pin));
}
/// <summary>
/// Get the Custom Field with a specified name, or null.
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public CustomField GetCustomField(string name)
{
foreach (var customField in CustomFields)
{
if (customField.Name.Equals(name))
{
return customField;
}
}
return null;
}
}
}
| 35.546667 | 101 | 0.570893 | [
"MIT"
] | durgeshpatel-hs/hellosign-dotnet-sdk | src/HelloSign/Models/BaseSignatureRequest.cs | 2,668 | C# |
namespace Tarea11
{
partial class FRMTIEMPO
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.TXTTIEMPO = new System.Windows.Forms.TextBox();
this.CMDSALIDA = new System.Windows.Forms.Button();
this.CMDTIEMPO = new System.Windows.Forms.Button();
this.LBLTIEMPO = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// TXTTIEMPO
//
this.TXTTIEMPO.Location = new System.Drawing.Point(164, 220);
this.TXTTIEMPO.Name = "TXTTIEMPO";
this.TXTTIEMPO.ReadOnly = true;
this.TXTTIEMPO.Size = new System.Drawing.Size(100, 20);
this.TXTTIEMPO.TabIndex = 3;
//
// CMDSALIDA
//
this.CMDSALIDA.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.CMDSALIDA.Location = new System.Drawing.Point(276, 118);
this.CMDSALIDA.Name = "CMDSALIDA";
this.CMDSALIDA.Size = new System.Drawing.Size(100, 57);
this.CMDSALIDA.TabIndex = 2;
this.CMDSALIDA.Text = "&Salida";
this.CMDSALIDA.UseVisualStyleBackColor = true;
this.CMDSALIDA.Click += new System.EventHandler(this.CMDSALIDA_Click);
//
// CMDTIEMPO
//
this.CMDTIEMPO.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.CMDTIEMPO.Location = new System.Drawing.Point(48, 118);
this.CMDTIEMPO.Name = "CMDTIEMPO";
this.CMDTIEMPO.Size = new System.Drawing.Size(100, 57);
this.CMDTIEMPO.TabIndex = 1;
this.CMDTIEMPO.Text = "&Tiempo";
this.CMDTIEMPO.UseVisualStyleBackColor = true;
this.CMDTIEMPO.Click += new System.EventHandler(this.CMDTIEMPO_Click);
//
// LBLTIEMPO
//
this.LBLTIEMPO.AutoSize = true;
this.LBLTIEMPO.Location = new System.Drawing.Point(184, 65);
this.LBLTIEMPO.Name = "LBLTIEMPO";
this.LBLTIEMPO.Size = new System.Drawing.Size(42, 13);
this.LBLTIEMPO.TabIndex = 0;
this.LBLTIEMPO.Text = "Tiempo";
//
// FRMTIEMPO
//
this.AcceptButton = this.CMDTIEMPO;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.CancelButton = this.CMDSALIDA;
this.ClientSize = new System.Drawing.Size(534, 294);
this.Controls.Add(this.TXTTIEMPO);
this.Controls.Add(this.CMDSALIDA);
this.Controls.Add(this.CMDTIEMPO);
this.Controls.Add(this.LBLTIEMPO);
this.Name = "FRMTIEMPO";
this.Text = " Tiempo de floripondio";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TextBox TXTTIEMPO;
private System.Windows.Forms.Button CMDSALIDA;
private System.Windows.Forms.Button CMDTIEMPO;
private System.Windows.Forms.Label LBLTIEMPO;
}
}
| 38.854369 | 107 | 0.569965 | [
"Apache-2.0"
] | Luissf1/Programas-C- | Tarea11/Tarea11/Form1.Designer.cs | 4,004 | C# |
using Nwazet.Commerce.Models;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace Nwazet.Commerce.ViewModels {
public class ProductEditorViewModel {
public ProductPart Product { get; set; }
public bool AllowProductOverrides { get; set; }
public ICollection<PriceTierViewModel> PriceTiers { get; set; }
public decimal? DiscountPrice { get; set; }
}
public class PriceTierViewModel {
public int Quantity { get; set; }
[RegularExpression(@"^\$?\d+(,\d{3})*(\.\d*)?%?$", ErrorMessage = "Tier price is not valid")]
public string Price { get; set; }
}
}
| 35.684211 | 102 | 0.644543 | [
"BSD-3-Clause"
] | LaserSrl/Nwazet.Commerce | ViewModels/ProductEditorViewModel.cs | 680 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.34014
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace CircularGauge.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "12.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;
}
}
}
}
| 39.555556 | 151 | 0.582397 | [
"MIT"
] | PrzemekBurczyk/MonitoringSystem | CircularGauge/Properties/Settings.Designer.cs | 1,070 | C# |
using Evol.Domain.Commands;
using Evol.TMovie.Domain.Commands.Dto;
using System;
using System.Collections.Generic;
using System.Text;
namespace Evol.TMovie.Domain.Commands
{
public class RolePermissionShipUpdateCommand : Command
{
public RolePermissionShipUpdateDto Input { get; set; }
}
}
| 22.285714 | 62 | 0.75641 | [
"Apache-2.0"
] | supernebula/evol-core | src/Evol.TMovie.Domain/Commands/Role/RolePermissionShipUpdateCommand.cs | 314 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Linq;
using System.Threading.Tasks;
using NuGet.Common;
using NuGet.Frameworks;
using NuGet.ProjectModel;
using NuGet.Test.Utility;
using Test.Utility;
using Xunit;
namespace NuGet.CommandLine.Test
{
public class RestoreMessageTest
{
[Fact]
public async Task GivenAProjectIsUsedOverAPackageVerifyNoDowngradeWarningAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("NETStandard1.5"));
var projectB = SimpleTestProjectContext.CreateNETCore(
"b",
pathContext.SolutionRoot,
NuGetFramework.Parse("NETStandard1.5"));
// A -> B
projectA.AddProjectToAllFrameworks(projectB);
var packageX = new SimpleTestPackageContext("x", "9.0.0");
var packageB = new SimpleTestPackageContext("b", "9.0.0");
packageX.Dependencies.Add(packageB);
await SimpleTestPackageUtility.CreatePackagesAsync(pathContext.PackageSource, packageX, packageB);
// PackageB will be overridden by ProjectB
projectA.AddPackageToAllFrameworks(packageX);
solution.Projects.Add(projectA);
solution.Projects.Add(projectB);
solution.Create(pathContext.SolutionRoot);
// Act
var r = Util.Restore(pathContext, projectA.ProjectPath);
var output = r.Item2 + " " + r.Item3;
var reader = new LockFileFormat();
var lockFileObj = reader.Read(projectA.AssetsFileOutputPath);
// Assert
Assert.NotNull(lockFileObj);
Assert.Equal(0, lockFileObj.LogMessages.Count());
Assert.DoesNotContain("downgrade", output, StringComparison.OrdinalIgnoreCase);
}
}
[Fact]
public async Task GivenAPackageDowngradeVerifyDowngradeWarningAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("NETStandard1.5"));
var packageB = new SimpleTestPackageContext("b", "9.0.0");
var packageI1 = new SimpleTestPackageContext("i", "9.0.0");
var packageI2 = new SimpleTestPackageContext("i", "1.0.0");
packageB.Dependencies.Add(packageI1);
await SimpleTestPackageUtility.CreatePackagesAsync(pathContext.PackageSource, packageB, packageI1, packageI2);
projectA.AddPackageToAllFrameworks(packageB);
projectA.AddPackageToAllFrameworks(packageI2);
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
// Act
var r = Util.Restore(pathContext, projectA.ProjectPath);
var output = r.Item2 + " " + r.Item3;
var reader = new LockFileFormat();
var lockFileObj = reader.Read(projectA.AssetsFileOutputPath);
// Assert
Assert.NotNull(lockFileObj);
Assert.Equal(1, lockFileObj.LogMessages.Count());
Assert.Contains("Detected package downgrade: i from 9.0.0 to 1.0.0",
lockFileObj.LogMessages.First().Message,
StringComparison.OrdinalIgnoreCase);
Assert.Contains("Detected package downgrade: i from 9.0.0 to 1.0.0",
output,
StringComparison.OrdinalIgnoreCase);
}
}
[Fact]
public void GivenAnUnknownPackageVerifyError()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("NETStandard1.5"));
var packageB = new SimpleTestPackageContext("b", "9.0.0");
projectA.AddPackageToAllFrameworks(packageB);
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
// Act
var r = Util.Restore(pathContext, projectA.ProjectPath, expectedExitCode: 1);
var output = r.Item2 + " " + r.Item3;
var reader = new LockFileFormat();
var lockFileObj = reader.Read(projectA.AssetsFileOutputPath);
// Assert
Assert.NotNull(lockFileObj);
Assert.Equal(1, lockFileObj.LogMessages.Count());
Assert.Contains("Unable to find package b. No packages exist with this id in source(s): source",
lockFileObj.LogMessages.First().Message,
StringComparison.OrdinalIgnoreCase);
Assert.Contains("Unable to find package b. No packages exist with this id in source(s): source",
output,
StringComparison.OrdinalIgnoreCase);
}
}
[Fact]
public async Task GivenAPackageWithAHigherMinClientVersionVerifyErrorCodeDisplayedAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("NETStandard1.5"));
var packageB = new SimpleTestPackageContext("b", "1.0.0")
{
MinClientVersion = "99.0.0"
};
await SimpleTestPackageUtility.CreatePackagesAsync(pathContext.PackageSource, packageB);
projectA.AddPackageToAllFrameworks(packageB);
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
// Act
var r = Util.Restore(pathContext, projectA.ProjectPath, expectedExitCode: 1);
var output = r.Item2 + " " + r.Item3;
// Assert
Assert.Contains("NU1401", output, StringComparison.OrdinalIgnoreCase);
}
}
}
}
| 39.941176 | 126 | 0.571964 | [
"Apache-2.0"
] | BdDsl/NuGet.Client | test/NuGet.Clients.Tests/NuGet.CommandLine.Test/RestoreMessageTest.cs | 7,469 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Abp.Domain.Entities;
using Abp.Domain.Repositories;
using Abp.Domain.Uow;
using Abp.MongoDb.Uow;
using MongoDB.Driver;
using MongoDB.Driver.Linq;
namespace Abp.MongoDb.Repositories
{
/* IMPORTANT: MongoDB implementation is experimental and trial purposes for now.
*/
public class MongoDbRepositoryBase<TEntity> : MongoDbRepositoryBase<TEntity, int>, IRepository<TEntity>
where TEntity : class, IEntity<int>
{
}
//TODO: Test & Check all methods
public class MongoDbRepositoryBase<TEntity, TPrimaryKey> : IRepository<TEntity, TPrimaryKey> where TEntity : class, IEntity<TPrimaryKey>
{
protected MongoCollection<TEntity> Collection
{
get
{
throw new NotImplementedException();
//return ((MongoDbUnitOfWork)UnitOfWorkScope.Current).Database.GetCollection<TEntity>(typeof(TEntity).Name);
}
}
public IQueryable<TEntity> GetAll()
{
return Collection.AsQueryable();
}
public List<TEntity> GetAllList()
{
return GetAll().ToList();
}
public Task<List<TEntity>> GetAllListAsync()
{
throw new NotImplementedException();
}
public List<TEntity> GetAllList(Expression<Func<TEntity, bool>> predicate)
{
return GetAll().Where(predicate).ToList();
}
public Task<List<TEntity>> GetAllListAsync(Expression<Func<TEntity, bool>> predicate)
{
throw new NotImplementedException();
}
public T Query<T>(Func<IQueryable<TEntity>, T> queryMethod)
{
return queryMethod(GetAll());
}
public TEntity Get(TPrimaryKey id)
{
var query = MongoDB.Driver.Builders.Query<TEntity>.EQ(e => e.Id, id);
return Collection.FindOne(query); //TODO: What if no entity with id?
}
public Task<TEntity> GetAsync(TPrimaryKey id)
{
throw new NotImplementedException();
}
public TEntity Single(Expression<Func<TEntity, bool>> predicate)
{
return GetAll().Single(predicate);
}
public Task<TEntity> SingleAsync(Expression<Func<TEntity, bool>> predicate)
{
throw new NotImplementedException();
}
public TEntity FirstOrDefault(TPrimaryKey id)
{
var query = MongoDB.Driver.Builders.Query<TEntity>.EQ(e => e.Id, id);
return Collection.FindOne(query); //TODO: What if no entity with id?
}
public Task<TEntity> FirstOrDefaultAsync(TPrimaryKey id)
{
throw new NotImplementedException();
}
public TEntity FirstOrDefault(Expression<Func<TEntity, bool>> predicate)
{
return GetAll().FirstOrDefault(predicate);
}
public Task<TEntity> FirstOrDefaultAsync(Expression<Func<TEntity, bool>> predicate)
{
throw new NotImplementedException();
}
public TEntity Load(TPrimaryKey id)
{
return Get(id);
}
public TEntity Insert(TEntity entity)
{
Collection.Insert(entity);
return entity;
}
public Task<TEntity> InsertAsync(TEntity entity)
{
Collection.Insert(entity);
return Task.FromResult(entity);
}
public TPrimaryKey InsertAndGetId(TEntity entity)
{
Collection.Insert(entity);
return entity.Id;
}
public Task<TPrimaryKey> InsertAndGetIdAsync(TEntity entity)
{
throw new NotImplementedException();
}
public TEntity InsertOrUpdate(TEntity entity)
{
return EqualityComparer<TPrimaryKey>.Default.Equals(entity.Id, default(TPrimaryKey))
? Insert(entity)
: Update(entity);
}
public Task<TEntity> InsertOrUpdateAsync(TEntity entity)
{
throw new NotImplementedException();
}
public TPrimaryKey InsertOrUpdateAndGetId(TEntity entity)
{
entity = InsertOrUpdate(entity);
if (EqualityComparer<TPrimaryKey>.Default.Equals(entity.Id, default(TPrimaryKey)))
{
//UnitOfWorkScope.Current.SaveChanges();
throw new NotImplementedException();
}
return entity.Id;
}
public Task<TPrimaryKey> InsertOrUpdateAndGetIdAsync(TEntity entity)
{
throw new NotImplementedException();
}
public TEntity Update(TEntity entity)
{
Collection.Save(entity);
return entity;
}
public Task<TEntity> UpdateAsync(TEntity entity)
{
throw new NotImplementedException();
}
public void Delete(TEntity entity)
{
Delete(entity.Id);
}
public Task DeleteAsync(TEntity entity)
{
throw new NotImplementedException();
}
public void Delete(TPrimaryKey id)
{
var query = MongoDB.Driver.Builders.Query<TEntity>.EQ(e => e.Id, id);
Collection.Remove(query);
}
public Task DeleteAsync(TPrimaryKey id)
{
throw new NotImplementedException();
}
public void Delete(Expression<Func<TEntity, bool>> predicate)
{
throw new NotImplementedException();
}
public Task DeleteAsync(Expression<Func<TEntity, bool>> predicate)
{
throw new NotImplementedException();
}
public int Count()
{
return GetAll().Count();
}
public Task<int> CountAsync()
{
throw new NotImplementedException();
}
public int Count(Expression<Func<TEntity, bool>> predicate)
{
return GetAll().Count(predicate);
}
public Task<int> CountAsync(Expression<Func<TEntity, bool>> predicate)
{
throw new NotImplementedException();
}
public long LongCount()
{
return GetAll().LongCount();
}
public Task<long> LongCountAsync()
{
throw new NotImplementedException();
}
public long LongCount(Expression<Func<TEntity, bool>> predicate)
{
return GetAll().LongCount(predicate);
}
public Task<long> LongCountAsync(Expression<Func<TEntity, bool>> predicate)
{
throw new NotImplementedException();
}
}
} | 27.512097 | 140 | 0.579364 | [
"MIT"
] | ZayaPro/aspnetboilerplate | src/Abp.MongoDB/MongoDb/Repositories/MongoDbRepositoryBase.cs | 6,823 | C# |
using UnityEngine;
public class InputController : MonoBehaviour
{
public Vector2 MoveInput()
{
float x = Input.GetAxis("Horizontal");
float y = Input.GetAxis("Vertical");
return new Vector2(x, y);
}
}
| 18.230769 | 46 | 0.628692 | [
"MIT"
] | YolandaMC/Save-Me- | Assets/Scripts/InputController.cs | 237 | C# |
using Prism.Commands;
using Prism.Mvvm;
using Prism.Navigation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
namespace Prism700p5Try.ViewModels
{
public class MainPageViewModel : ViewModelBase
{
public ICommand TryRealmCommand { get; }
public MainPageViewModel(INavigationService navigationService)
: base (navigationService)
{
Title = "Main Page";
TryRealmCommand = new DelegateCommand(async () =>
{
await navigationService.NavigateAsync("StaffListPage");
});
}
}
}
| 23.607143 | 71 | 0.647504 | [
"MIT"
] | case-k/Prism700p5Try | Prism700p5Try/Prism700p5Try/ViewModels/MainPageViewModel.cs | 663 | C# |
using System.Collections.Generic;
using System.Threading.Tasks;
namespace UrhoSharp.Pages
{
public class NavigationStack
{
private readonly ICurrentPageContainer _container;
private readonly object _gate = new object();
private readonly Stack<IScenePage> _stack = new Stack<IScenePage>();
public NavigationStack(ICurrentPageContainer container)
{
_container = container;
}
public int StackSize
{
get
{
lock (_gate)
{
return _stack.Count;
}
}
}
/// <summary>
/// Asynchronously removes the top Page from the navigation stack if the page isn't the root page.
/// </summary>
public async Task<bool> GoBackAsync()
{
IScenePage top = null;
lock (_gate)
{
if (_stack.Count <= 1)
return false;
_stack.Pop();
top = _stack.Peek();
}
await _container.SetCurrentPageAsync(top);
return true;
}
/// <summary>
/// Asynchronously removes the top Page from the navigation stack.
/// </summary>
public async Task<IScenePage> PopAsync()
{
IScenePage top = null;
IScenePage res = null;
lock (_gate)
{
if (_stack.Count > 0)
{
res = _stack.Pop();
if (_stack.Count > 0) top = _stack.Peek();
}
}
await _container.SetCurrentPageAsync(top);
return res;
}
/// <summary>
/// Pops all but the root Page off the navigation stack.
/// </summary>
public async Task PopToRootAsync()
{
IScenePage top = null;
IScenePage res = null;
lock (_gate)
{
while (_stack.Count > 1) _stack.Pop();
if (_stack.Count > 0) top = _stack.Peek();
}
await _container.SetCurrentPageAsync(top);
}
/// <summary>
/// Presents a Page modally.
/// </summary>
public async Task PushAsync(IScenePage page)
{
lock (_gate)
{
if (_stack.Count > 0)
if (_stack.Peek() == page)
return;
_stack.Push(page);
}
await _container.SetCurrentPageAsync(page);
}
public async Task ResetTo(IScenePage page)
{
lock (_gate)
{
_stack.Clear();
if (page != null) _stack.Push(page);
}
await _container.SetCurrentPageAsync(page);
}
}
} | 26.527273 | 110 | 0.460247 | [
"MIT"
] | gleblebedev/UrhoSharpToolkit | src/UrhoSharp.Pages/NavigationStack.cs | 2,920 | 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.AzureNextGen.Migrate.V20210101.Inputs
{
/// <summary>
/// Gets or sets the virtual machine resource settings.
/// </summary>
public sealed class VirtualMachineResourceSettingsArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The resource type. For example, the value can be Microsoft.Compute/virtualMachines.
/// Expected value is 'Microsoft.Compute/virtualMachines'.
/// </summary>
[Input("resourceType", required: true)]
public Input<string> ResourceType { get; set; } = null!;
/// <summary>
/// Gets or sets the target availability set id for virtual machines not in an availability set at source.
/// </summary>
[Input("targetAvailabilitySetId")]
public Input<string>? TargetAvailabilitySetId { get; set; }
/// <summary>
/// Gets or sets the target availability zone.
/// </summary>
[Input("targetAvailabilityZone")]
public InputUnion<string, Pulumi.AzureNextGen.Migrate.V20210101.TargetAvailabilityZone>? TargetAvailabilityZone { get; set; }
/// <summary>
/// Gets or sets the target Resource name.
/// </summary>
[Input("targetResourceName", required: true)]
public Input<string> TargetResourceName { get; set; } = null!;
/// <summary>
/// Gets or sets the target virtual machine size.
/// </summary>
[Input("targetVmSize")]
public Input<string>? TargetVmSize { get; set; }
public VirtualMachineResourceSettingsArgs()
{
}
}
}
| 35.314815 | 133 | 0.639224 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/Migrate/V20210101/Inputs/VirtualMachineResourceSettingsArgs.cs | 1,907 | C# |
namespace QOAM.Website.ViewModels.Profiles
{
using System.Collections.Generic;
using QOAM.Core;
using QOAM.Website.Models;
public class EditViewModel
{
public UserProfile UserProfile { get; set; }
public bool IsAdmin { get; set; }
public bool IsInstitutionAdmin { get; set; }
public bool IsDataAdmin { get; set; }
public bool IsDeveloper { get; set; }
public string ReturnUrl { get; set; }
public IEnumerable<string> Roles
{
get
{
if (this.IsAdmin)
{
yield return ApplicationRole.Admin;
}
if (this.IsInstitutionAdmin)
{
yield return ApplicationRole.InstitutionAdmin;
}
if (this.IsDataAdmin)
{
yield return ApplicationRole.DataAdmin;
}
if (this.IsDeveloper)
{
yield return ApplicationRole.Developer;
}
}
}
}
} | 26.023256 | 66 | 0.485255 | [
"MIT"
] | QOAM/qoam | src/Website/ViewModels/Profiles/EditViewModel.cs | 1,121 | C# |
// -----------------------------------------------------------------------
// <copyright file="AbstractDataSource.cs" company="Jolyon Suthers">
// Copyright (c) Jolyon Suthers. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// </copyright>
// -----------------------------------------------------------------------
namespace VisioCleanup.Core.Services;
using System;
using System.Collections.Generic;
using System.Globalization;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using VisioCleanup.Core.Models;
using VisioCleanup.Core.Models.Config;
/// <summary>Abstract data source.</summary>
public class AbstractDataSource
{
/// <summary>Initialises a new instance of the <see cref="AbstractDataSource" /> class.</summary>
/// <param name="logger">Logging instance.</param>
/// <param name="options">Application configuration settings.</param>
protected AbstractDataSource(ILogger logger, IOptions<AppConfig> options)
{
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
this.Logger = logger ?? throw new ArgumentNullException(nameof(logger));
this.AppConfig = options.Value;
}
/// <summary>Gets logging environment.</summary>
/// <value>Logger.</value>
internal ILogger Logger { get; }
/// <summary>Gets application configuration.</summary>
/// <value>Configuration.</value>
protected AppConfig AppConfig { get; }
/// <summary>Create a new shape object.</summary>
/// <param name="rowResult">Data set row.</param>
/// <param name="allShapes">set of all shapes.</param>
/// <param name="previousShape">Parent shape.</param>
/// <returns>New shape object.</returns>
protected DiagramShape? CreateShape(IReadOnlyDictionary<FieldType, string> rowResult, IDictionary<string, DiagramShape> allShapes, DiagramShape? previousShape)
{
if (rowResult == null)
{
throw new ArgumentNullException(nameof(rowResult));
}
if (allShapes == null)
{
throw new ArgumentNullException(nameof(allShapes));
}
var shapeType = rowResult.ContainsKey(FieldType.ShapeType) ? rowResult[FieldType.ShapeType] : string.Empty;
var shapeText = rowResult.ContainsKey(FieldType.ShapeText) ? rowResult[FieldType.ShapeText] : string.Empty;
var sortValue = rowResult.ContainsKey(FieldType.SortValue) ? rowResult[FieldType.SortValue] : shapeText;
if (string.IsNullOrEmpty(shapeText))
{
return null;
}
var shapeIdentifier = string.Format(CultureInfo.CurrentCulture, "{0} {1}:{2}", previousShape?.ShapeIdentifier, shapeText, shapeType).Trim();
if (!allShapes.ContainsKey(shapeIdentifier))
{
this.Logger.LogDebug("Creating shape for: {ShapeText}", shapeText);
allShapes.Add(
shapeIdentifier,
new DiagramShape(0)
{
ShapeText = shapeText,
ShapeType = ShapeType.NewShape,
SortValue = sortValue,
Master = shapeType,
ShapeIdentifier = shapeIdentifier,
});
}
var shape = allShapes[shapeIdentifier];
previousShape?.AddChildShape(shape);
return shape;
}
}
| 36.755319 | 163 | 0.620839 | [
"MIT"
] | fenrick/VisioCleanup | VisioCleanup.Core/Services/AbstractDataSource.cs | 3,457 | 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 meteringmarketplace-2016-01-14.normal.json service model.
*/
using System;
using Amazon.Runtime;
using Amazon.Util.Internal;
namespace Amazon.AWSMarketplaceMetering
{
/// <summary>
/// Configuration for accessing Amazon AWSMarketplaceMetering service
/// </summary>
public partial class AmazonAWSMarketplaceMeteringConfig : ClientConfig
{
private static readonly string UserAgentString =
InternalSDKUtils.BuildUserAgentString("3.7.0.116");
private string _userAgent = UserAgentString;
/// <summary>
/// Default constructor
/// </summary>
public AmazonAWSMarketplaceMeteringConfig()
{
this.AuthenticationServiceName = "aws-marketplace";
}
/// <summary>
/// The constant used to lookup in the region hash the endpoint.
/// </summary>
public override string RegionEndpointServiceName
{
get
{
return "metering.marketplace";
}
}
/// <summary>
/// Gets the ServiceVersion property.
/// </summary>
public override string ServiceVersion
{
get
{
return "2016-01-14";
}
}
/// <summary>
/// Gets the value of UserAgent property.
/// </summary>
public override string UserAgent
{
get
{
return _userAgent;
}
}
}
} | 27.0625 | 117 | 0.601386 | [
"Apache-2.0"
] | raz2017/aws-sdk-net | sdk/src/Services/AWSMarketplaceMetering/Generated/AmazonAWSMarketplaceMeteringConfig.cs | 2,165 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public abstract class ObjectData_Origin : PEIKnifer_Origin
{
public abstract void Clear();
}
| 19.777778 | 58 | 0.797753 | [
"MIT"
] | PEIKnifer/PEIMEN_Frame | Assets/PEIMEN_Frame/Script/FrameWork/ObjectPool/ObjectData_Origin.cs | 180 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the workspaces-2015-04-08.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.WorkSpaces.Model
{
/// <summary>
/// This is the response object from the RebuildWorkspaces operation.
/// </summary>
public partial class RebuildWorkspacesResponse : AmazonWebServiceResponse
{
private List<FailedWorkspaceChangeRequest> _failedRequests = new List<FailedWorkspaceChangeRequest>();
/// <summary>
/// Gets and sets the property FailedRequests.
/// <para>
/// Information about the WorkSpace if it could not be rebuilt.
/// </para>
/// </summary>
public List<FailedWorkspaceChangeRequest> FailedRequests
{
get { return this._failedRequests; }
set { this._failedRequests = value; }
}
// Check to see if FailedRequests property is set
internal bool IsSetFailedRequests()
{
return this._failedRequests != null && this._failedRequests.Count > 0;
}
}
} | 32.678571 | 110 | 0.681421 | [
"Apache-2.0"
] | GitGaby/aws-sdk-net | sdk/src/Services/WorkSpaces/Generated/Model/RebuildWorkspacesResponse.cs | 1,830 | C# |
using System;
using Newtonsoft.Json;
namespace FunctionApp1
{
// Class to store daily survey data points for a user collected from DCI Mobile App
public class DailySurveyData
{
[JsonProperty(PropertyName = "id")]
public String Id { get; set; }
public String PatientId { get; set; }
[JsonProperty(PropertyName = "entrydate")]
public String EntryDate { get; set; }
public String GeneralFeeling { get; set; }
public String Fever_Y_N { get; set; }
public String Fever_Rating { get; set; }
public String HighestTemperature { get; set; }
public String Cough_Y_N { get; set; }
public String Cough_Rating { get; set; }
public String BodyAches_Y_N { get; set; }
public String BodyAches_Rating { get; set; }
public String ShortnessOfBreath_Y_N { get; set; }
public String ShortnessOfBreath_Rating { get; set; }
public String SoreThroat_Y_N { get; set; }
public String SoreThroat_Rating { get; set; }
public String Tired_Y_N { get; set; }
public String Tired_Rating { get; set; }
public String Chills_Y_N { get; set; }
public String Chills_Rating { get; set; }
public String RunnyOrStuffyNose_Y_N { get; set; }
public String RunnyOrStuffyNose_Rating { get; set; }
public String NauseaOrVomiting_Y_N { get; set; }
public String NauseaOrVomiting_Rating { get; set; }
public String AbdominalPain_Y_N { get; set; }
public String AbdominalPain_Rating { get; set; }
public String Diarrhea_Y_N { get; set; }
public String Diarrhea_Rating { get; set; }
public String DiarrheaEpisodes { get; set; }
public String LostSmellTasteSense_Y_N { get; set; }
public String LostSmellTasteSense_Rating { get; set; }
public String Headache_Y_N { get; set; }
public String Headache_Rating { get; set; }
public String Other { get; set; }
}
} | 44.911111 | 87 | 0.637308 | [
"MIT"
] | microsoft/DailyCheckIn | backend/DailyCheckInAPIs/DailySurveyData.cs | 2,021 | C# |
using dnlib.DotNet;
using dnlib.DotNet.Emit;
using Uskr.Attributes;
using Uskr.Core;
using Uskr.IR;
namespace Uskr.Opcodes
{
[Handler(Code.Conv_Ovf_I2)]
public class Conv_Ovf_I2 : IOpcodeProcessor
{
public void Handel(IRAssembly assembly, IRMethod meth, UskrContext context, Instruction instruction)
{//
Logger.Debug($"Not Implemented: {instruction.OpCode.Code}");
}
}
} | 24.888889 | 108 | 0.649554 | [
"MIT"
] | Myvar/Uskr | Uskr/Opcodes/Conv_Ovf_I2.cs | 448 | C# |
using Applications.BusinessLogic.Managers;
using Applications.Model;
using Microsoft.AspNetCore.Mvc;
using HIJK.SOA.SOAServices;
using System.Collections.Generic;
namespace Services.Controllers
{
/// <summary>
/// This class exposes the APIs related to Employee's document in HR Database
/// </summary>
[Route("api/[controller]")]
public class DocumentController : Controller
{
private SOAContext soaContext;
private IDocumentManager _manager;
public DocumentController(IDocumentManager documentManager)
{
_manager = documentManager;
}
/// <summary>
/// Gets the list of all documents
/// Usage: GET api/document
/// Type: Information Service
/// </summary>
/// <returns>List of Documents</returns>
[HttpGet]
public IEnumerable<Document> Get()
{
soaContext = new SOAContext();
soaContext.Initialize();
var retVal = _manager.GetAllDocuments();
soaContext.Close();
return retVal;
}
/// <summary>
/// Gets the list of all documents
/// Usage: GET api/document/2
/// Type: Information Service
/// </summary>
/// <returns>Document
/// </returns>
[HttpGet("{id}")]
public Document Get(int id)
{
soaContext = new SOAContext();
soaContext.Initialize();
var retVal = _manager.GetAnEmployeesDocument(id);
soaContext.Close();
return retVal;
}
// GET api/document/about
[HttpGet("About")]
public ContentResult About()
{
return Content("APIs for Employee's documents in the HR Database.");
}
}
}
| 25.928571 | 81 | 0.569697 | [
"MIT"
] | wagnerhsu/packt-Enterprise-Application-Architecture-with-NET-Core | Chapter07/src/HR/Services/Controllers/DocumentController.cs | 1,817 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System.Collections.Generic;
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.Core.Utils;
using Aliyun.Acs.Cdn;
using Aliyun.Acs.Cdn.Transform;
using Aliyun.Acs.Cdn.Transform.V20180510;
namespace Aliyun.Acs.Cdn.Model.V20180510
{
public class DescribeConfigOfVersionRequest : RpcAcsRequest<DescribeConfigOfVersionResponse>
{
public DescribeConfigOfVersionRequest()
: base("Cdn", "2018-05-10", "DescribeConfigOfVersion")
{
if (this.GetType().GetProperty("ProductEndpointMap") != null && this.GetType().GetProperty("ProductEndpointType") != null)
{
this.GetType().GetProperty("ProductEndpointMap").SetValue(this, Aliyun.Acs.Cdn.Endpoint.endpointMap, null);
this.GetType().GetProperty("ProductEndpointType").SetValue(this, Aliyun.Acs.Cdn.Endpoint.endpointRegionalType, null);
}
Method = MethodType.POST;
}
private string versionId;
private string securityToken;
private string functionName;
private long? groupId;
private long? ownerId;
private int? functionId;
public string VersionId
{
get
{
return versionId;
}
set
{
versionId = value;
DictionaryUtil.Add(QueryParameters, "VersionId", value);
}
}
public string SecurityToken
{
get
{
return securityToken;
}
set
{
securityToken = value;
DictionaryUtil.Add(QueryParameters, "SecurityToken", value);
}
}
public string FunctionName
{
get
{
return functionName;
}
set
{
functionName = value;
DictionaryUtil.Add(QueryParameters, "FunctionName", value);
}
}
public long? GroupId
{
get
{
return groupId;
}
set
{
groupId = value;
DictionaryUtil.Add(QueryParameters, "GroupId", value.ToString());
}
}
public long? OwnerId
{
get
{
return ownerId;
}
set
{
ownerId = value;
DictionaryUtil.Add(QueryParameters, "OwnerId", value.ToString());
}
}
public int? FunctionId
{
get
{
return functionId;
}
set
{
functionId = value;
DictionaryUtil.Add(QueryParameters, "FunctionId", value.ToString());
}
}
public override DescribeConfigOfVersionResponse GetResponse(UnmarshallerContext unmarshallerContext)
{
return DescribeConfigOfVersionResponseUnmarshaller.Unmarshall(unmarshallerContext);
}
}
}
| 24.185714 | 134 | 0.661252 | [
"Apache-2.0"
] | AxiosCros/aliyun-openapi-net-sdk | aliyun-net-sdk-cdn/Cdn/Model/V20180510/DescribeConfigOfVersionRequest.cs | 3,386 | C# |
/////////////////////////////////////////////////////////////////////////////
//
// Script : TweenQuaternionBase.cs
// Info : Quaternion插值类基类
// Author : ls9512 2019
// E-mail : ls9512@vip.qq.com
//
/////////////////////////////////////////////////////////////////////////////
using UnityEngine;
namespace Aya.Tween
{
public abstract class TweenQuaternionBase<TComponent> : Tweener<Quaternion, TComponent> where TComponent : Component
{
public override Quaternion From
{
get => Param.FromQuaternion;
set => Param.FromQuaternion = value;
}
public override Quaternion To
{
get => Param.ToQuaternion;
set => Param.ToQuaternion = value;
}
public override bool SupportSpeedBased => false;
public override float GetSpeedBasedDuration()
{
return Duration;
}
public override Quaternion Evaluate(float factor)
{
var from = FromGetter();
var to = ToGetter();
var result = Quaternion.LerpUnclamped(from, to, factor);
if (Curve != null && CurveTarget == CurveTargetType.Value)
{
var euler = result.eulerAngles * Curve.Evaluate(factor);
result = Quaternion.Euler(euler);
}
return result;
}
public override void TweenUpdate()
{
base.TweenUpdate();
OnValueQuaternion.InvokeIfNeed(CurrentValue);
}
}
}
| 27.290909 | 118 | 0.52032 | [
"MIT"
] | H-man/UTween | Core/Script/_Base/TweenValue/TweenQuaternionBase.cs | 1,513 | C# |
#region License
// Copyright (c) 2018-2021, exomia
// All rights reserved.
//
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree.
#endregion
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
using System.Runtime.InteropServices;
// ReSharper disable UnusedMember.Global
// ReSharper disable once CheckNamespace
namespace Exomia.Vulkan.Api.Core
{
[StructLayout(LayoutKind.Sequential)]
public unsafe struct VkGraphicsPipelineCreateInfo
{
public const VkStructureType STYPE = VkStructureType.GRAPHICS_PIPELINE_CREATE_INFO;
public VkStructureType sType;
public void* pNext;
public VkPipelineCreateFlagBits flags;
public uint stageCount;
public VkPipelineShaderStageCreateInfo* pStages;
public VkPipelineVertexInputStateCreateInfo* pVertexInputState;
public VkPipelineInputAssemblyStateCreateInfo* pInputAssemblyState;
public VkPipelineTessellationStateCreateInfo* pTessellationState;
public VkPipelineViewportStateCreateInfo* pViewportState;
public VkPipelineRasterizationStateCreateInfo* pRasterizationState;
public VkPipelineMultisampleStateCreateInfo* pMultisampleState;
public VkPipelineDepthStencilStateCreateInfo* pDepthStencilState;
public VkPipelineColorBlendStateCreateInfo* pColorBlendState;
public VkPipelineDynamicStateCreateInfo* pDynamicState;
public VkPipelineLayout layout;
public VkRenderPass renderPass;
public uint subpass;
public VkPipeline basePipelineHandle;
public int basePipelineIndex;
}
} | 49.674419 | 115 | 0.617978 | [
"BSD-3-Clause"
] | exomia/vulkan-api | src/Exomia.Vulkan.Api.Core/Structs/VkGraphicsPipelineCreateInfo.cs | 2,138 | 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("ArcanumTextureSlicer.Console")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Console")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("8d83f596-37cf-4683-ba03-51596b348a40")]
// 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.054054 | 84 | 0.746449 | [
"MIT"
] | evgeniy-polyakov/arcanum-texture-slicer | ArcanumTextureSlicer/ArcanumTextureSlicer.Console/Properties/AssemblyInfo.cs | 1,411 | C# |
using System;
namespace CreateAndFake.Toolbox.RandomizerTool
{
/// <summary>Handles generation of collection types for the randomizer.</summary>
public abstract class CreateCollectionHint : CreateHint
{
/// <param name="type">Type to generate.</param>
/// <param name="size">Number of items to generate.</param>
/// <param name="randomizer">Handles callback behavior for child values.</param>
/// <inheritdoc cref="CreateHint.TryCreate(Type,RandomizerChainer)"/>
protected internal abstract (bool, object) TryCreate(Type type, int size, RandomizerChainer randomizer);
}
}
| 42.866667 | 113 | 0.685848 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | CreateAndFake/CreateAndFake | src/CreateAndFake/Toolbox/RandomizerTool/CreateCollectionHint.cs | 643 | 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>
//------------------------------------------------------------------------------
// Generation date: 11/28/2021 8:55:09 PM
namespace Microsoft.Dynamics.DataEntities
{
/// <summary>
/// There are no comments for LedgerEliminationRuleSingle in the schema.
/// </summary>
public partial class LedgerEliminationRuleSingle : global::Microsoft.OData.Client.DataServiceQuerySingle<LedgerEliminationRule>
{
/// <summary>
/// Initialize a new LedgerEliminationRuleSingle object.
/// </summary>
public LedgerEliminationRuleSingle(global::Microsoft.OData.Client.DataServiceContext context, string path)
: base(context, path) {}
/// <summary>
/// Initialize a new LedgerEliminationRuleSingle object.
/// </summary>
public LedgerEliminationRuleSingle(global::Microsoft.OData.Client.DataServiceContext context, string path, bool isComposable)
: base(context, path, isComposable) {}
/// <summary>
/// Initialize a new LedgerEliminationRuleSingle object.
/// </summary>
public LedgerEliminationRuleSingle(global::Microsoft.OData.Client.DataServiceQuerySingle<LedgerEliminationRule> query)
: base(query) {}
/// <summary>
/// There are no comments for LegalEntity in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
public virtual global::Microsoft.Dynamics.DataEntities.LegalEntitySingle LegalEntity
{
get
{
if (!this.IsComposable)
{
throw new global::System.NotSupportedException("The previous function is not composable.");
}
if ((this._LegalEntity == null))
{
this._LegalEntity = new global::Microsoft.Dynamics.DataEntities.LegalEntitySingle(this.Context, GetPath("LegalEntity"));
}
return this._LegalEntity;
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private global::Microsoft.Dynamics.DataEntities.LegalEntitySingle _LegalEntity;
/// <summary>
/// There are no comments for LedgerEliminationRuleLine in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
public virtual global::Microsoft.OData.Client.DataServiceQuery<global::Microsoft.Dynamics.DataEntities.LedgerEliminationRuleLine> LedgerEliminationRuleLine
{
get
{
if (!this.IsComposable)
{
throw new global::System.NotSupportedException("The previous function is not composable.");
}
if ((this._LedgerEliminationRuleLine == null))
{
this._LedgerEliminationRuleLine = Context.CreateQuery<global::Microsoft.Dynamics.DataEntities.LedgerEliminationRuleLine>(GetPath("LedgerEliminationRuleLine"));
}
return this._LedgerEliminationRuleLine;
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private global::Microsoft.OData.Client.DataServiceQuery<global::Microsoft.Dynamics.DataEntities.LedgerEliminationRuleLine> _LedgerEliminationRuleLine;
}
/// <summary>
/// There are no comments for LedgerEliminationRule in the schema.
/// </summary>
/// <KeyProperties>
/// dataAreaId
/// RuleId
/// </KeyProperties>
[global::Microsoft.OData.Client.Key("dataAreaId", "RuleId")]
[global::Microsoft.OData.Client.EntitySet("LedgerEliminationRules")]
public partial class LedgerEliminationRule : global::Microsoft.OData.Client.BaseEntityType, global::System.ComponentModel.INotifyPropertyChanged
{
/// <summary>
/// Create a new LedgerEliminationRule object.
/// </summary>
/// <param name="dataAreaId">Initial value of dataAreaId.</param>
/// <param name="ruleId">Initial value of RuleId.</param>
/// <param name="dateLastRun">Initial value of DateLastRun.</param>
/// <param name="effectiveStartDate">Initial value of EffectiveStartDate.</param>
/// <param name="effectiveEndDate">Initial value of EffectiveEndDate.</param>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
public static LedgerEliminationRule CreateLedgerEliminationRule(string dataAreaId, string ruleId, global::System.DateTimeOffset dateLastRun, global::System.DateTimeOffset effectiveStartDate, global::System.DateTimeOffset effectiveEndDate)
{
LedgerEliminationRule ledgerEliminationRule = new LedgerEliminationRule();
ledgerEliminationRule.dataAreaId = dataAreaId;
ledgerEliminationRule.RuleId = ruleId;
ledgerEliminationRule.DateLastRun = dateLastRun;
ledgerEliminationRule.EffectiveStartDate = effectiveStartDate;
ledgerEliminationRule.EffectiveEndDate = effectiveEndDate;
return ledgerEliminationRule;
}
/// <summary>
/// There are no comments for Property dataAreaId in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
[global::System.ComponentModel.DataAnnotations.RequiredAttribute(ErrorMessage = "dataAreaId is required.")]
public virtual string dataAreaId
{
get
{
return this._dataAreaId;
}
set
{
this.OndataAreaIdChanging(value);
this._dataAreaId = value;
this.OndataAreaIdChanged();
this.OnPropertyChanged("dataAreaId");
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private string _dataAreaId;
partial void OndataAreaIdChanging(string value);
partial void OndataAreaIdChanged();
/// <summary>
/// There are no comments for Property RuleId in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
[global::System.ComponentModel.DataAnnotations.RequiredAttribute(ErrorMessage = "RuleId is required.")]
public virtual string RuleId
{
get
{
return this._RuleId;
}
set
{
this.OnRuleIdChanging(value);
this._RuleId = value;
this.OnRuleIdChanged();
this.OnPropertyChanged("RuleId");
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private string _RuleId;
partial void OnRuleIdChanging(string value);
partial void OnRuleIdChanged();
/// <summary>
/// There are no comments for Property JournalName in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
public virtual string JournalName
{
get
{
return this._JournalName;
}
set
{
this.OnJournalNameChanging(value);
this._JournalName = value;
this.OnJournalNameChanged();
this.OnPropertyChanged("JournalName");
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private string _JournalName;
partial void OnJournalNameChanging(string value);
partial void OnJournalNameChanged();
/// <summary>
/// There are no comments for Property Active in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
public virtual global::System.Nullable<global::Microsoft.Dynamics.DataEntities.NoYes> Active
{
get
{
return this._Active;
}
set
{
this.OnActiveChanging(value);
this._Active = value;
this.OnActiveChanged();
this.OnPropertyChanged("Active");
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private global::System.Nullable<global::Microsoft.Dynamics.DataEntities.NoYes> _Active;
partial void OnActiveChanging(global::System.Nullable<global::Microsoft.Dynamics.DataEntities.NoYes> value);
partial void OnActiveChanged();
/// <summary>
/// There are no comments for Property DateLastRun in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
[global::System.ComponentModel.DataAnnotations.RequiredAttribute(ErrorMessage = "DateLastRun is required.")]
public virtual global::System.DateTimeOffset DateLastRun
{
get
{
return this._DateLastRun;
}
set
{
this.OnDateLastRunChanging(value);
this._DateLastRun = value;
this.OnDateLastRunChanged();
this.OnPropertyChanged("DateLastRun");
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private global::System.DateTimeOffset _DateLastRun;
partial void OnDateLastRunChanging(global::System.DateTimeOffset value);
partial void OnDateLastRunChanged();
/// <summary>
/// There are no comments for Property DestinationCompany in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
public virtual string DestinationCompany
{
get
{
return this._DestinationCompany;
}
set
{
this.OnDestinationCompanyChanging(value);
this._DestinationCompany = value;
this.OnDestinationCompanyChanged();
this.OnPropertyChanged("DestinationCompany");
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private string _DestinationCompany;
partial void OnDestinationCompanyChanging(string value);
partial void OnDestinationCompanyChanged();
/// <summary>
/// There are no comments for Property Description in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
public virtual string Description
{
get
{
return this._Description;
}
set
{
this.OnDescriptionChanging(value);
this._Description = value;
this.OnDescriptionChanged();
this.OnPropertyChanged("Description");
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private string _Description;
partial void OnDescriptionChanging(string value);
partial void OnDescriptionChanged();
/// <summary>
/// There are no comments for Property EffectiveStartDate in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
[global::System.ComponentModel.DataAnnotations.RequiredAttribute(ErrorMessage = "EffectiveStartDate is required.")]
public virtual global::System.DateTimeOffset EffectiveStartDate
{
get
{
return this._EffectiveStartDate;
}
set
{
this.OnEffectiveStartDateChanging(value);
this._EffectiveStartDate = value;
this.OnEffectiveStartDateChanged();
this.OnPropertyChanged("EffectiveStartDate");
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private global::System.DateTimeOffset _EffectiveStartDate;
partial void OnEffectiveStartDateChanging(global::System.DateTimeOffset value);
partial void OnEffectiveStartDateChanged();
/// <summary>
/// There are no comments for Property EffectiveEndDate in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
[global::System.ComponentModel.DataAnnotations.RequiredAttribute(ErrorMessage = "EffectiveEndDate is required.")]
public virtual global::System.DateTimeOffset EffectiveEndDate
{
get
{
return this._EffectiveEndDate;
}
set
{
this.OnEffectiveEndDateChanging(value);
this._EffectiveEndDate = value;
this.OnEffectiveEndDateChanged();
this.OnPropertyChanged("EffectiveEndDate");
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private global::System.DateTimeOffset _EffectiveEndDate;
partial void OnEffectiveEndDateChanging(global::System.DateTimeOffset value);
partial void OnEffectiveEndDateChanged();
/// <summary>
/// There are no comments for Property LegalEntity in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
public virtual global::Microsoft.Dynamics.DataEntities.LegalEntity LegalEntity
{
get
{
return this._LegalEntity;
}
set
{
this.OnLegalEntityChanging(value);
this._LegalEntity = value;
this.OnLegalEntityChanged();
this.OnPropertyChanged("LegalEntity");
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private global::Microsoft.Dynamics.DataEntities.LegalEntity _LegalEntity;
partial void OnLegalEntityChanging(global::Microsoft.Dynamics.DataEntities.LegalEntity value);
partial void OnLegalEntityChanged();
/// <summary>
/// There are no comments for Property LedgerEliminationRuleLine in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
public virtual global::Microsoft.OData.Client.DataServiceCollection<global::Microsoft.Dynamics.DataEntities.LedgerEliminationRuleLine> LedgerEliminationRuleLine
{
get
{
return this._LedgerEliminationRuleLine;
}
set
{
this.OnLedgerEliminationRuleLineChanging(value);
this._LedgerEliminationRuleLine = value;
this.OnLedgerEliminationRuleLineChanged();
this.OnPropertyChanged("LedgerEliminationRuleLine");
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private global::Microsoft.OData.Client.DataServiceCollection<global::Microsoft.Dynamics.DataEntities.LedgerEliminationRuleLine> _LedgerEliminationRuleLine = new global::Microsoft.OData.Client.DataServiceCollection<global::Microsoft.Dynamics.DataEntities.LedgerEliminationRuleLine>(null, global::Microsoft.OData.Client.TrackingMode.None);
partial void OnLedgerEliminationRuleLineChanging(global::Microsoft.OData.Client.DataServiceCollection<global::Microsoft.Dynamics.DataEntities.LedgerEliminationRuleLine> value);
partial void OnLedgerEliminationRuleLineChanged();
/// <summary>
/// This event is raised when the value of the property is changed
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
public event global::System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// The value of the property is changed
/// </summary>
/// <param name="property">property name</param>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
protected virtual void OnPropertyChanged(string property)
{
if ((this.PropertyChanged != null))
{
this.PropertyChanged(this, new global::System.ComponentModel.PropertyChangedEventArgs(property));
}
}
}
}
| 47.041344 | 345 | 0.628838 | [
"MIT"
] | NathanClouseAX/AAXDataEntityPerfTest | Projects/AAXDataEntityPerfTest/ODataUtility/Connected Services/D365/LedgerEliminationRule.cs | 18,207 | 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 WpfApp1 {
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window {
public MainWindow() {
InitializeComponent();
}
}
}
| 22.346154 | 43 | 0.771084 | [
"MIT"
] | Team-on/works | 0_homeworks/C#/TAO Framework/WpfApp1/MainWindow.xaml.cs | 583 | C# |
// *** WARNING: this file was generated by crd2pulumi. ***
// *** 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.Kubernetes.Types.Inputs.Scheduling.V1Alpha1
{
public class ReplicaSchedulingPreferenceSpecArgs : Pulumi.ResourceArgs
{
[Input("clusters")]
private InputMap<object>? _clusters;
/// <summary>
/// A mapping between cluster names and preferences regarding a local workload object (dep, rs, .. ) in these clusters. "*" (if provided) applies to all clusters if an explicit mapping is not provided. If omitted, clusters without explicit preferences should not have any replicas scheduled.
/// </summary>
public InputMap<object> Clusters
{
get => _clusters ?? (_clusters = new InputMap<object>());
set => _clusters = value;
}
/// <summary>
/// If set to true then already scheduled and running replicas may be moved to other clusters in order to match current state to the specified preferences. Otherwise, if set to false, up and running replicas will not be moved.
/// </summary>
[Input("rebalance")]
public Input<bool>? Rebalance { get; set; }
/// <summary>
/// TODO (@irfanurrehman); upgrade this to label selector only if need be. The idea of this API is to have a a set of preferences which can be used for a target FederatedDeployment or FederatedReplicaset. Although the set of preferences in question can be applied to multiple target objects using label selectors, but there are no clear advantages of doing that as of now. To keep the implementation and usage simple, matching ns/name of RSP resource to the target resource is sufficient and only additional information needed in RSP resource is a target kind (FederatedDeployment or FederatedReplicaset).
/// </summary>
[Input("targetKind", required: true)]
public Input<string> TargetKind { get; set; } = null!;
/// <summary>
/// Total number of pods desired across federated clusters. Replicas specified in the spec for target deployment template or replicaset template will be discarded/overridden when scheduling preferences are specified.
/// </summary>
[Input("totalReplicas", required: true)]
public Input<int> TotalReplicas { get; set; } = null!;
public ReplicaSchedulingPreferenceSpecArgs()
{
}
}
}
| 52.28 | 613 | 0.693573 | [
"Apache-2.0"
] | pulumi/pulumi-kubernetes-crds | operators/kubefed/dotnet/Kubernetes/Crds/Operators/Kubefed/Scheduling/V1Alpha1/Inputs/ReplicaSchedulingPreferenceSpecArgs.cs | 2,614 | C# |
using System;
using System.Linq;
using SampleProjects.EntityFrameworkApp.V1.WeatherForecast;
using Xtz.StronglyTyped.BuiltinTypes.Address;
using Xtz.StronglyTyped.BuiltinTypes.Internet;
namespace SampleProjects.EntityFrameworkApp.Data
{
// NOTE: `DbInitializer` is only for demo purposes. It's not required to have any
internal class DbInitializer
{
public static void Initialize(AppDbContext context)
{
context.Database.EnsureDeleted();
context.Database.EnsureCreated();
if (context.WeatherForecasts.Any())
{
return;
}
var summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
var rng = new Random();
var entities = Enumerable.Range(1, 5)
.Select(index =>
{
var city = new City("Amsterdam");
return new WeatherForecast
{
// NOTE: Calling `WeatherForecastId` (class) constructor without parameter will create a random Guid
Id = new WeatherForecastId(),
// NOTE: `WeatherForecastStructId` is a struct, calling empty constructor would initialize all properties with default values
// NOTE: To create a new Guid we call custom static method `WeatherForecastStructId.New()`
StructId = WeatherForecastStructId.New(),
City = city,
Email = new Email("bob@example.com"),
Date = DateTime.Now.AddDays(index),
// NOTE: You can cast to `DegreesCelsius` explicitly
TemperatureC = (DegreesCelsius)rng.Next(-20, 55),
Summary = summaries[rng.Next(summaries.Length)]
};
})
.ToArray();
context.WeatherForecasts.AddRange(entities);
context.SaveChanges();
}
}
} | 40.566038 | 149 | 0.537209 | [
"MIT"
] | dev-experience/Xtz.StronglyTyped.SampleProjects | src/SampleProjects.EntityFrameworkApp/Data/DbInitializer.cs | 2,150 | C# |
using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
namespace Xabe
{
internal class LockModel
{
private readonly string _path;
public LockModel(string path)
{
_path = path;
}
internal async Task<bool> TrySetReleaseDate(DateTime date)
{
try
{
using(var fs = new FileStream(_path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
{
using(var sr = new StreamWriter(fs, Encoding.UTF8))
{
await sr.WriteAsync(date.ToUniversalTime()
.Ticks.ToString());
}
}
}
catch(Exception)
{
return false;
}
return true;
}
internal async Task<DateTime> GetReleaseDate(string path = "")
{
try
{
using(var fs = new FileStream(string.IsNullOrWhiteSpace(path) ? _path : path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using(var sr = new StreamReader(fs, Encoding.UTF8))
{
string text = await sr.ReadToEndAsync();
long ticks = long.Parse(text);
return new DateTime(ticks, DateTimeKind.Utc);
}
}
}
catch(Exception)
{
return DateTime.MaxValue;
}
}
}
}
| 28.155172 | 147 | 0.448255 | [
"MIT"
] | tomaszzmuda/Xabe.FileLock | Xabe.FileLock/LockModel.cs | 1,635 | C# |
// *** WARNING: this file was generated by crd2pulumi. ***
// *** 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.Kubernetes.Types.Inputs.Jaegertracing.V1
{
public class JaegerSpecVolumesGitRepoArgs : Pulumi.ResourceArgs
{
[Input("directory")]
public Input<string>? Directory { get; set; }
[Input("repository", required: true)]
public Input<string> Repository { get; set; } = null!;
[Input("revision")]
public Input<string>? Revision { get; set; }
public JaegerSpecVolumesGitRepoArgs()
{
}
}
}
| 26.551724 | 81 | 0.662338 | [
"Apache-2.0"
] | pulumi/pulumi-kubernetes-crds | operators/jaeger/dotnet/Kubernetes/Crds/Operators/Jaeger/Jaegertracing/V1/Inputs/JaegerSpecVolumesGitRepoArgs.cs | 770 | C# |
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http.Features;
namespace MockApi.Server.Handlers
{
internal class BulkSetupHandler : RequestHandler
{
public BulkSetupHandler(RouteCache routeCache) : base(routeCache)
{
}
public override async Task<MockApiResponse> ProcessRequest(IHttpRequestFeature request)
{
var routesDocument = await request.Body.ReadAsTextAsync();
RouteCache.LoadRoutes(routesDocument);
return new MockApiResponse
{
StatusCode = 200,
Payload = $"Bulk setup complete",
ContentType = "text"
};
}
}
}
| 26.884615 | 95 | 0.609442 | [
"MIT"
] | vincentcrowe4airelogic/MockApi | Server/Handlers/BulkSetupHandler.cs | 699 | C# |
using System.Text.Json.Serialization;
namespace Essensoft.AspNetCore.Payment.Alipay.Response
{
/// <summary>
/// AlipayCommerceEducateCampusIdentityQueryResponse.
/// </summary>
public class AlipayCommerceEducateCampusIdentityQueryResponse : AlipayResponse
{
/// <summary>
/// 查询用户是否目前是大学生
/// </summary>
[JsonPropertyName("college_online_tag")]
public string CollegeOnlineTag { get; set; }
}
}
| 27.117647 | 82 | 0.672451 | [
"MIT"
] | LuohuaRain/payment | src/Essensoft.AspNetCore.Payment.Alipay/Response/AlipayCommerceEducateCampusIdentityQueryResponse.cs | 487 | C# |
#region License
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="TypeInfoTests.cs" company="MorseCode Software">
// Copyright (c) 2015 MorseCode Software
// </copyright>
// <summary>
// The MIT License (MIT)
//
// Copyright (c) 2015 MorseCode Software
//
// 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.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
#endregion
namespace MorseCode.BetterReflection.Tests
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization.Formatters.Binary;
using MorseCode.FrameworkExtensions;
using NUnit.Framework;
[TestFixture]
public class TypeInfoTests
{
#region Public Methods and Operators
[Test]
public void FullName()
{
ITypeInfo<DateTime> typeInfo = TypeInfoFactory.GetTypeInfo<DateTime>();
Assert.AreEqual(typeof(DateTime).FullName, typeInfo.FullName);
}
[Test]
public void GetMethod()
{
ITypeInfo<DateTime> typeInfo = TypeInfoFactory.GetTypeInfo<DateTime>();
IMethodInfo<DateTime, char, IFormatProvider, string[]> getDateTimeFormatsMethod = typeInfo.GetMethod(o => (Func<char, IFormatProvider, string[]>)o.GetDateTimeFormats);
Assert.IsNotNull(getDateTimeFormatsMethod);
Assert.AreSame(typeof(DateTime).GetMethod("GetDateTimeFormats", new[] { typeof(char), typeof(IFormatProvider) }), getDateTimeFormatsMethod.MethodInfo);
}
[Test]
public void GetMethodByName()
{
ITypeInfo<DateTime> typeInfo = TypeInfoFactory.GetTypeInfo<DateTime>();
IMethodInfo<DateTime> addMethod = typeInfo.GetMethod("Add");
Assert.IsNotNull(addMethod);
Assert.AreSame(typeof(DateTime).GetMethod("Add"), addMethod.MethodInfo);
}
[Test]
public void GetMethodByNameAndTypes()
{
ITypeInfo<DateTime> typeInfo = TypeInfoFactory.GetTypeInfo<DateTime>();
IMethodInfo<DateTime> getDateTimeFormatsMethod = typeInfo.GetMethod("GetDateTimeFormats", new[] { typeof(char), typeof(IFormatProvider) });
Assert.IsNotNull(getDateTimeFormatsMethod);
Assert.AreSame(typeof(DateTime).GetMethod("GetDateTimeFormats", new[] { typeof(char), typeof(IFormatProvider) }), getDateTimeFormatsMethod.MethodInfo);
}
[Test]
public void GetMethodByNameAndTypesWithWrongName()
{
ITypeInfo<DateTime> typeInfo = TypeInfoFactory.GetTypeInfo<DateTime>();
ArgumentException actual = null;
try
{
typeInfo.GetMethod("GetDateTimeFormats2", new[] { typeof(char), typeof(IFormatProvider) });
}
catch (ArgumentException e)
{
actual = e;
}
Assert.IsNotNull(actual);
Assert.AreEqual("No public instance method was found with name GetDateTimeFormats2 and types { " + typeof(char).FullName + ", " + typeof(IFormatProvider).FullName + " } on type " + typeof(DateTime).FullName + ".", actual.Message);
}
[Test]
public void GetMethodByNameAndTypesWithWrongTypes()
{
ITypeInfo<DateTime> typeInfo = TypeInfoFactory.GetTypeInfo<DateTime>();
ArgumentException actual = null;
try
{
typeInfo.GetMethod("GetDateTimeFormats", new[] { typeof(int), typeof(IFormatProvider) });
}
catch (ArgumentException e)
{
actual = e;
}
Assert.IsNotNull(actual);
Assert.AreEqual("No public instance method was found with name GetDateTimeFormats and types { " + typeof(int).FullName + ", " + typeof(IFormatProvider).FullName + " } on type " + typeof(DateTime).FullName + ".", actual.Message);
}
[Test]
public void GetMethodByNameWithWrongName()
{
ITypeInfo<DateTime> typeInfo = TypeInfoFactory.GetTypeInfo<DateTime>();
ArgumentException actual = null;
try
{
typeInfo.GetMethod("Add2");
}
catch (ArgumentException e)
{
actual = e;
}
Assert.IsNotNull(actual);
Assert.AreEqual("No public instance method was found with name Add2 on type " + typeof(DateTime).FullName + ".", actual.Message);
}
[Test]
public void GetMethodWithEightParameters()
{
ITypeInfo<Test> typeInfo = TypeInfoFactory.GetTypeInfo<Test>();
IMethodInfo<Test, int, int, int, int, int, int, int, int, string> method = typeInfo.GetMethod(o => (Func<int, int, int, int, int, int, int, int, string>)o.TestMethod);
Assert.IsNotNull(method);
Assert.AreSame(typeof(Test).GetMethod("TestMethod", Enumerable.Range(0, 8).Select(_ => typeof(int)).ToArray()), method.MethodInfo);
}
[Test]
public void GetMethodWithFiveParameters()
{
ITypeInfo<Test> typeInfo = TypeInfoFactory.GetTypeInfo<Test>();
IMethodInfo<Test, int, int, int, int, int, string> method = typeInfo.GetMethod(o => (Func<int, int, int, int, int, string>)o.TestMethod);
Assert.IsNotNull(method);
Assert.AreSame(typeof(Test).GetMethod("TestMethod", Enumerable.Range(0, 5).Select(_ => typeof(int)).ToArray()), method.MethodInfo);
}
[Test]
public void GetMethodWithFourParameters()
{
ITypeInfo<Test> typeInfo = TypeInfoFactory.GetTypeInfo<Test>();
IMethodInfo<Test, int, int, int, int, string> method = typeInfo.GetMethod(o => (Func<int, int, int, int, string>)o.TestMethod);
Assert.IsNotNull(method);
Assert.AreSame(typeof(Test).GetMethod("TestMethod", Enumerable.Range(0, 4).Select(_ => typeof(int)).ToArray()), method.MethodInfo);
}
[Test]
public void GetMethodWithNoParameters()
{
ITypeInfo<Test> typeInfo = TypeInfoFactory.GetTypeInfo<Test>();
IMethodInfo<Test, string> method = typeInfo.GetMethod(o => (Func<string>)o.TestMethod);
Assert.IsNotNull(method);
Assert.AreSame(typeof(Test).GetMethod("TestMethod", System.Type.EmptyTypes), method.MethodInfo);
}
[Test]
public void GetMethodWithOneParameter()
{
ITypeInfo<Test> typeInfo = TypeInfoFactory.GetTypeInfo<Test>();
IMethodInfo<Test, int, string> method = typeInfo.GetMethod(o => (Func<int, string>)o.TestMethod);
Assert.IsNotNull(method);
Assert.AreSame(typeof(Test).GetMethod("TestMethod", Enumerable.Range(0, 1).Select(_ => typeof(int)).ToArray()), method.MethodInfo);
}
[Test]
public void GetMethodWithOutParameterByName()
{
ITypeInfo<Test> typeInfo = TypeInfoFactory.GetTypeInfo<Test>();
IMethodInfo<Test> testMethodMethod = typeInfo.GetMethod("TestMethodWithOutParameter");
Assert.IsNotNull(testMethodMethod);
Assert.AreSame(typeof(Test).GetMethod("TestMethodWithOutParameter"), testMethodMethod.MethodInfo);
}
[Test]
public void GetMethodWithRefParameterByName()
{
ITypeInfo<Test> typeInfo = TypeInfoFactory.GetTypeInfo<Test>();
IMethodInfo<Test> testMethodMethod = typeInfo.GetMethod("TestMethodWithRefParameter");
Assert.IsNotNull(testMethodMethod);
Assert.AreSame(typeof(Test).GetMethod("TestMethodWithRefParameter"), testMethodMethod.MethodInfo);
}
[Test]
public void GetMethodWithSevenParameters()
{
ITypeInfo<Test> typeInfo = TypeInfoFactory.GetTypeInfo<Test>();
IMethodInfo<Test, int, int, int, int, int, int, int, string> method = typeInfo.GetMethod(o => (Func<int, int, int, int, int, int, int, string>)o.TestMethod);
Assert.IsNotNull(method);
Assert.AreSame(typeof(Test).GetMethod("TestMethod", Enumerable.Range(0, 7).Select(_ => typeof(int)).ToArray()), method.MethodInfo);
}
[Test]
public void GetMethodWithSixParameters()
{
ITypeInfo<Test> typeInfo = TypeInfoFactory.GetTypeInfo<Test>();
IMethodInfo<Test, int, int, int, int, int, int, string> method = typeInfo.GetMethod(o => (Func<int, int, int, int, int, int, string>)o.TestMethod);
Assert.IsNotNull(method);
Assert.AreSame(typeof(Test).GetMethod("TestMethod", Enumerable.Range(0, 6).Select(_ => typeof(int)).ToArray()), method.MethodInfo);
}
[Test]
public void GetMethodWithThreeParameters()
{
ITypeInfo<Test> typeInfo = TypeInfoFactory.GetTypeInfo<Test>();
IMethodInfo<Test, int, int, int, string> method = typeInfo.GetMethod(o => (Func<int, int, int, string>)o.TestMethod);
Assert.IsNotNull(method);
Assert.AreSame(typeof(Test).GetMethod("TestMethod", Enumerable.Range(0, 3).Select(_ => typeof(int)).ToArray()), method.MethodInfo);
}
[Test]
public void GetMethodWithTwoParameters()
{
ITypeInfo<Test> typeInfo = TypeInfoFactory.GetTypeInfo<Test>();
IMethodInfo<Test, int, int, string> method = typeInfo.GetMethod(o => (Func<int, int, string>)o.TestMethod);
Assert.IsNotNull(method);
Assert.AreSame(typeof(Test).GetMethod("TestMethod", Enumerable.Range(0, 2).Select(_ => typeof(int)).ToArray()), method.MethodInfo);
}
[Test]
public void GetMethods()
{
ITypeInfo<DateTime> typeInfo = TypeInfoFactory.GetTypeInfo<DateTime>();
IReadOnlyList<IMethodInfo<DateTime>> methods = typeInfo.GetMethods().ToArray();
IReadOnlyList<MethodInfo> expectedMethods = typeof(DateTime).GetMethods(BindingFlags.Instance | BindingFlags.Public);
Assert.IsNotNull(methods);
Assert.IsNotNull(expectedMethods);
Assert.IsTrue(methods.Select(m => m.MethodInfo).SetEqual(expectedMethods, ReferenceEqualityComparer.Instance));
}
[Test]
public void GetProperties()
{
ITypeInfo<DateTime> typeInfo = TypeInfoFactory.GetTypeInfo<DateTime>();
IReadOnlyList<IPropertyInfo<DateTime>> properties = typeInfo.GetProperties().ToArray();
IReadOnlyList<PropertyInfo> expectedProperties = typeof(DateTime).GetProperties(BindingFlags.Instance | BindingFlags.Public);
Assert.IsNotNull(properties);
Assert.IsNotNull(expectedProperties);
Assert.IsTrue(properties.Select(m => m.PropertyInfo).SetEqual(expectedProperties, ReferenceEqualityComparer.Instance));
}
[Test]
public void GetPropertyByName()
{
ITypeInfo<DateTime> typeInfo = TypeInfoFactory.GetTypeInfo<DateTime>();
IPropertyInfo<DateTime> addProperty = typeInfo.GetProperty("Day");
Assert.IsNotNull(addProperty);
Assert.AreSame(typeof(DateTime).GetProperty("Day"), addProperty.PropertyInfo);
}
[Test]
public void GetPropertyByNameWithWrongName()
{
ITypeInfo<DateTime> typeInfo = TypeInfoFactory.GetTypeInfo<DateTime>();
ArgumentException actual = null;
try
{
typeInfo.GetProperty("Day2");
}
catch (ArgumentException e)
{
actual = e;
}
Assert.IsNotNull(actual);
Assert.AreEqual("No public instance property was found with name Day2 on type " + typeof(DateTime).FullName + ".", actual.Message);
}
[Test]
public void UntypedGetProperties()
{
ITypeInfo typeInfo = TypeInfoFactory.GetTypeInfo(typeof(DateTime));
IReadOnlyList<IPropertyInfo> properties = typeInfo.GetProperties().ToArray();
IReadOnlyList<PropertyInfo> expectedProperties = typeof(DateTime).GetProperties(BindingFlags.Instance | BindingFlags.Public);
Assert.IsNotNull(properties);
Assert.IsNotNull(expectedProperties);
Assert.IsTrue(properties.Select(m => m.PropertyInfo).SetEqual(expectedProperties, ReferenceEqualityComparer.Instance));
}
[Test]
public void UntypedGetPropertyByName()
{
ITypeInfo typeInfo = TypeInfoFactory.GetTypeInfo(typeof(DateTime));
IPropertyInfo addProperty = typeInfo.GetProperty("Day");
Assert.IsNotNull(addProperty);
Assert.AreSame(typeof(DateTime).GetProperty("Day"), addProperty.PropertyInfo);
}
[Test]
public void UntypedGetPropertyByNameWithWrongName()
{
ITypeInfo typeInfo = TypeInfoFactory.GetTypeInfo(typeof(DateTime));
ArgumentException actual = null;
try
{
typeInfo.GetProperty("Day2");
}
catch (ArgumentException e)
{
actual = e;
}
Assert.IsNotNull(actual);
Assert.AreEqual("No public instance property was found with name Day2 on type " + typeof(DateTime).FullName + ".", actual.Message);
}
[Test]
public void Name()
{
ITypeInfo<Test> typeInfo = TypeInfoFactory.GetTypeInfo<Test>();
Assert.AreEqual(typeof(Test).Name, typeInfo.Name);
}
[Test]
public void Type()
{
ITypeInfo<Test> typeInfo = TypeInfoFactory.GetTypeInfo<Test>();
Assert.AreEqual(typeof(Test), typeInfo.Type);
}
[Test]
public void GetReadWriteProperty()
{
ITypeInfo<Test> typeInfo = TypeInfoFactory.GetTypeInfo<Test>();
IWritablePropertyInfo<Test, int> readWritePropertyProperty = typeInfo.GetReadWriteProperty(o => o.ReadWriteProperty);
Assert.IsNotNull(readWritePropertyProperty);
Assert.AreSame(typeof(Test).GetProperty("ReadWriteProperty"), readWritePropertyProperty.PropertyInfo);
}
[Test]
public void GetReadWritePropertyNotWritable()
{
ITypeInfo<Test> typeInfo = TypeInfoFactory.GetTypeInfo<Test>();
InvalidOperationException actual = null;
try
{
typeInfo.GetReadWriteProperty(o => o.ReadableProperty);
}
catch (InvalidOperationException e)
{
actual = e;
}
Assert.IsNotNull(actual);
Assert.IsNotNull("Property with name ReadableProperty on type " + typeof(Test).FullName + " is not readable and writable.", actual.Message);
}
[Test]
public void GetReadableProperty()
{
ITypeInfo<Test> typeInfo = TypeInfoFactory.GetTypeInfo<Test>();
IReadablePropertyInfo<Test, int> readablePropertyProperty = typeInfo.GetReadableProperty(o => o.ReadableProperty);
Assert.IsNotNull(readablePropertyProperty);
Assert.AreSame(typeof(Test).GetProperty("ReadableProperty"), readablePropertyProperty.PropertyInfo);
}
[Test]
public void GetReadablePropertyOnField()
{
ITypeInfo<Test> typeInfo = TypeInfoFactory.GetTypeInfo<Test>();
InvalidOperationException actual = null;
try
{
typeInfo.GetReadableProperty(o => o.Field);
}
catch (InvalidOperationException e)
{
actual = e;
}
Assert.IsNotNull(actual);
Assert.AreEqual("Expression is not a property.", actual.Message);
}
[Test]
public void GetReadablePropertyOnReadWriteProperty()
{
ITypeInfo<Test> typeInfo = TypeInfoFactory.GetTypeInfo<Test>();
IReadablePropertyInfo<Test, int> readablePropertyProperty = typeInfo.GetReadableProperty(o => o.ReadWriteProperty);
Assert.IsNotNull(readablePropertyProperty);
Assert.AreSame(typeof(Test).GetProperty("ReadWriteProperty"), readablePropertyProperty.PropertyInfo);
}
[Test]
public void Serialization()
{
ITypeInfo<Test> typeInfo = TypeInfoFactory.GetTypeInfo<Test>();
BinaryFormatter formatter = new BinaryFormatter();
MemoryStream memoryStream = new MemoryStream();
formatter.Serialize(memoryStream, typeInfo);
memoryStream.Position = 0;
ITypeInfo<Test> result = (ITypeInfo<Test>)formatter.Deserialize(memoryStream);
Assert.AreEqual(typeInfo.FullName, result.FullName);
Assert.AreEqual(typeInfo.Name, result.Name);
Assert.AreEqual(typeInfo.Type, result.Type);
}
[Test]
public void GetVoidMethod()
{
ITypeInfo<List<string>> typeInfo = TypeInfoFactory.GetTypeInfo<List<string>>();
IVoidMethodInfo<List<string>, int, int, IComparer<string>> sortMethod = typeInfo.GetVoidMethod(o => (Action<int, int, IComparer<string>>)o.Sort);
Assert.IsNotNull(sortMethod);
Assert.AreSame(typeof(List<string>).GetMethod("Sort", new[] { typeof(int), typeof(int), typeof(IComparer<string>) }), sortMethod.MethodInfo);
}
[Test]
public void GetVoidMethodWithEightParameters()
{
ITypeInfo<Test> typeInfo = TypeInfoFactory.GetTypeInfo<Test>();
IVoidMethodInfo<Test, int, int, int, int, int, int, int, int> method = typeInfo.GetVoidMethod(o => (Action<int, int, int, int, int, int, int, int>)o.TestVoidMethod);
Assert.IsNotNull(method);
Assert.AreSame(typeof(Test).GetMethod("TestVoidMethod", Enumerable.Range(0, 8).Select(_ => typeof(int)).ToArray()), method.MethodInfo);
}
[Test]
public void GetVoidMethodWithFiveParameters()
{
ITypeInfo<Test> typeInfo = TypeInfoFactory.GetTypeInfo<Test>();
IVoidMethodInfo<Test, int, int, int, int, int> method = typeInfo.GetVoidMethod(o => (Action<int, int, int, int, int>)o.TestVoidMethod);
Assert.IsNotNull(method);
Assert.AreSame(typeof(Test).GetMethod("TestVoidMethod", Enumerable.Range(0, 5).Select(_ => typeof(int)).ToArray()), method.MethodInfo);
}
[Test]
public void GetVoidMethodWithFourParameters()
{
ITypeInfo<Test> typeInfo = TypeInfoFactory.GetTypeInfo<Test>();
IVoidMethodInfo<Test, int, int, int, int> method = typeInfo.GetVoidMethod(o => (Action<int, int, int, int>)o.TestVoidMethod);
Assert.IsNotNull(method);
Assert.AreSame(typeof(Test).GetMethod("TestVoidMethod", Enumerable.Range(0, 4).Select(_ => typeof(int)).ToArray()), method.MethodInfo);
}
[Test]
public void GetVoidMethodWithNoParameters()
{
ITypeInfo<Test> typeInfo = TypeInfoFactory.GetTypeInfo<Test>();
IVoidMethodInfo<Test> method = typeInfo.GetVoidMethod(o => (Action)o.TestVoidMethod);
Assert.IsNotNull(method);
Assert.AreSame(typeof(Test).GetMethod("TestVoidMethod", System.Type.EmptyTypes), method.MethodInfo);
}
[Test]
public void GetVoidMethodWithOneParameter()
{
ITypeInfo<Test> typeInfo = TypeInfoFactory.GetTypeInfo<Test>();
IVoidMethodInfo<Test, int> method = typeInfo.GetVoidMethod(o => (Action<int>)o.TestVoidMethod);
Assert.IsNotNull(method);
Assert.AreSame(typeof(Test).GetMethod("TestVoidMethod", Enumerable.Range(0, 1).Select(_ => typeof(int)).ToArray()), method.MethodInfo);
}
[Test]
public void GetVoidMethodWithSevenParameters()
{
ITypeInfo<Test> typeInfo = TypeInfoFactory.GetTypeInfo<Test>();
IVoidMethodInfo<Test, int, int, int, int, int, int, int> method = typeInfo.GetVoidMethod(o => (Action<int, int, int, int, int, int, int>)o.TestVoidMethod);
Assert.IsNotNull(method);
Assert.AreSame(typeof(Test).GetMethod("TestVoidMethod", Enumerable.Range(0, 7).Select(_ => typeof(int)).ToArray()), method.MethodInfo);
}
[Test]
public void GetVoidMethodWithSixParameters()
{
ITypeInfo<Test> typeInfo = TypeInfoFactory.GetTypeInfo<Test>();
IVoidMethodInfo<Test, int, int, int, int, int, int> method = typeInfo.GetVoidMethod(o => (Action<int, int, int, int, int, int>)o.TestVoidMethod);
Assert.IsNotNull(method);
Assert.AreSame(typeof(Test).GetMethod("TestVoidMethod", Enumerable.Range(0, 6).Select(_ => typeof(int)).ToArray()), method.MethodInfo);
}
[Test]
public void GetVoidMethodWithThreeParameters()
{
ITypeInfo<Test> typeInfo = TypeInfoFactory.GetTypeInfo<Test>();
IVoidMethodInfo<Test, int, int, int> method = typeInfo.GetVoidMethod(o => (Action<int, int, int>)o.TestVoidMethod);
Assert.IsNotNull(method);
Assert.AreSame(typeof(Test).GetMethod("TestVoidMethod", Enumerable.Range(0, 3).Select(_ => typeof(int)).ToArray()), method.MethodInfo);
}
[Test]
public void GetVoidMethodWithTwoParameters()
{
ITypeInfo<Test> typeInfo = TypeInfoFactory.GetTypeInfo<Test>();
IVoidMethodInfo<Test, int, int> method = typeInfo.GetVoidMethod(o => (Action<int, int>)o.TestVoidMethod);
Assert.IsNotNull(method);
Assert.AreSame(typeof(Test).GetMethod("TestVoidMethod", Enumerable.Range(0, 2).Select(_ => typeof(int)).ToArray()), method.MethodInfo);
}
[Test]
public void GetWritableProperty()
{
ITypeInfo<Test> typeInfo = TypeInfoFactory.GetTypeInfo<Test>();
IWritablePropertyInfo<Test, int> writablePropertyProperty = typeInfo.GetWritableProperty(o => o.ReadWriteProperty);
Assert.IsNotNull(writablePropertyProperty);
Assert.AreSame(typeof(Test).GetProperty("ReadWriteProperty"), writablePropertyProperty.PropertyInfo);
}
[Test]
public void GetWritablePropertyNotWritable()
{
ITypeInfo<Test> typeInfo = TypeInfoFactory.GetTypeInfo<Test>();
InvalidOperationException actual = null;
try
{
typeInfo.GetWritableProperty(o => o.ReadableProperty);
}
catch (InvalidOperationException e)
{
actual = e;
}
Assert.IsNotNull(actual);
Assert.IsNotNull("Property with name ReadableProperty on type " + typeof(Test).FullName + " is not writable.", actual.Message);
}
[Test]
public void TypeInfoFactoryGetTypeInfo()
{
ITypeInfo<DateTime> typeInfo = TypeInfoFactory.GetTypeInfo<DateTime>();
Assert.IsNotNull(typeInfo);
}
[Test]
public void TypeInfoFactoryGetTypeInfoUntyped()
{
ITypeInfo typeInfoUntyped = TypeInfoFactory.GetTypeInfo(typeof(DateTime));
ITypeInfo<DateTime> typeInfo = TypeInfoFactory.GetTypeInfo<DateTime>();
Assert.IsNotNull(typeInfoUntyped);
Assert.IsNotNull(typeInfo);
Assert.AreSame(typeInfoUntyped, typeInfo);
}
[Test]
public void TypeInfoFactoryGetTypeInfoUntypedForNull()
{
ArgumentNullException actual = null;
try
{
TypeInfoFactory.GetTypeInfo(null);
}
catch (ArgumentNullException e)
{
actual = e;
}
Assert.IsNotNull(actual);
Assert.AreEqual("type", actual.ParamName);
}
[Test]
public void UntypedGetMethodByName()
{
ITypeInfo typeInfo = TypeInfoFactory.GetTypeInfo(typeof(DateTime));
IMethodInfo addMethod = typeInfo.GetMethod("Add");
Assert.IsNotNull(addMethod);
Assert.AreSame(typeof(DateTime).GetMethod("Add"), addMethod.MethodInfo);
}
[Test]
public void UntypedGetMethodByNameAndTypes()
{
ITypeInfo typeInfo = TypeInfoFactory.GetTypeInfo(typeof(DateTime));
IMethodInfo getDateTimeFormatsMethod = typeInfo.GetMethod("GetDateTimeFormats", new[] { typeof(char), typeof(IFormatProvider) });
Assert.IsNotNull(getDateTimeFormatsMethod);
Assert.AreSame(typeof(DateTime).GetMethod("GetDateTimeFormats", new[] { typeof(char), typeof(IFormatProvider) }), getDateTimeFormatsMethod.MethodInfo);
}
[Test]
public void UntypedGetMethodByNameAndTypesWithWrongName()
{
ITypeInfo typeInfo = TypeInfoFactory.GetTypeInfo(typeof(DateTime));
ArgumentException actual = null;
try
{
typeInfo.GetMethod("GetDateTimeFormats2", new[] { typeof(char), typeof(IFormatProvider) });
}
catch (ArgumentException e)
{
actual = e;
}
Assert.IsNotNull(actual);
Assert.AreEqual("No public instance method was found with name GetDateTimeFormats2 and types { " + typeof(char).FullName + ", " + typeof(IFormatProvider).FullName + " } on type " + typeof(DateTime).FullName + ".", actual.Message);
}
[Test]
public void UntypedGetMethodByNameAndTypesWithWrongTypes()
{
ITypeInfo typeInfo = TypeInfoFactory.GetTypeInfo(typeof(DateTime));
ArgumentException actual = null;
try
{
typeInfo.GetMethod("GetDateTimeFormats", new[] { typeof(int), typeof(IFormatProvider) });
}
catch (ArgumentException e)
{
actual = e;
}
Assert.IsNotNull(actual);
Assert.AreEqual("No public instance method was found with name GetDateTimeFormats and types { " + typeof(int).FullName + ", " + typeof(IFormatProvider).FullName + " } on type " + typeof(DateTime).FullName + ".", actual.Message);
}
[Test]
public void UntypedGetMethodByNameWithWrongName()
{
ITypeInfo typeInfo = TypeInfoFactory.GetTypeInfo(typeof(DateTime));
ArgumentException actual = null;
try
{
typeInfo.GetMethod("Add2");
}
catch (ArgumentException e)
{
actual = e;
}
Assert.IsNotNull(actual);
Assert.AreEqual("No public instance method was found with name Add2 on type " + typeof(DateTime).FullName + ".", actual.Message);
}
[Test]
public void UntypedGetMethodWithOutParameterByName()
{
ITypeInfo<Test> typeInfo = TypeInfoFactory.GetTypeInfo<Test>();
IMethodInfo<Test> testMethodMethod = typeInfo.GetMethod("TestMethodWithOutParameter");
Assert.IsNotNull(testMethodMethod);
Assert.AreSame(typeof(Test).GetMethod("TestMethodWithOutParameter"), testMethodMethod.MethodInfo);
}
[Test]
public void UntypedGetMethodWithRefParameterByName()
{
ITypeInfo<Test> typeInfo = TypeInfoFactory.GetTypeInfo<Test>();
IMethodInfo<Test> testMethodMethod = typeInfo.GetMethod("TestMethodWithRefParameter");
Assert.IsNotNull(testMethodMethod);
Assert.AreSame(typeof(Test).GetMethod("TestMethodWithRefParameter"), testMethodMethod.MethodInfo);
}
[Test]
public void UntypedGetMethods()
{
ITypeInfo typeInfo = TypeInfoFactory.GetTypeInfo(typeof(DateTime));
IReadOnlyList<IMethodInfo> methods = typeInfo.GetMethods().ToArray();
IReadOnlyList<MethodInfo> expectedMethods = typeof(DateTime).GetMethods(BindingFlags.Instance | BindingFlags.Public);
Assert.IsNotNull(methods);
Assert.IsNotNull(expectedMethods);
Assert.IsTrue(methods.Select(m => m.MethodInfo).SetEqual(expectedMethods, ReferenceEqualityComparer.Instance));
}
#endregion
private class Test
{
#pragma warning disable 649
public int Field;
#pragma warning restore 649
// ReSharper disable UnusedMember.Local
// ReSharper disable UnusedAutoPropertyAccessor.Local
#region Public Properties
public int ReadWriteProperty { get; set; }
// ReSharper restore UnusedAutoPropertyAccessor.Local
// ReSharper disable UnusedAutoPropertyAccessor.Local
public int ReadableProperty { get; private set; }
// ReSharper restore UnusedAutoPropertyAccessor.Local
// ReSharper restore UnusedAutoPropertyAccessor.Local
// ReSharper disable UnusedMember.Local
public int WritableProperty { private get; set; }
#endregion
#region Public Methods and Operators
public string TestMethod()
{
return null;
}
// ReSharper disable UnusedParameter.Local
public string TestMethod(int parameter1)
{
return null;
}
public string TestMethod(int parameter1, int parameter2)
{
return null;
}
public string TestMethod(int parameter1, int parameter2, int parameter3)
{
return null;
}
public string TestMethod(int parameter1, int parameter2, int parameter3, int parameter4)
{
return null;
}
public string TestMethod(int parameter1, int parameter2, int parameter3, int parameter4, int parameter5)
{
return null;
}
public string TestMethod(int parameter1, int parameter2, int parameter3, int parameter4, int parameter5, int parameter6)
{
return null;
}
public string TestMethod(int parameter1, int parameter2, int parameter3, int parameter4, int parameter5, int parameter6, int parameter7)
{
return null;
}
public string TestMethod(int parameter1, int parameter2, int parameter3, int parameter4, int parameter5, int parameter6, int parameter7, int parameter8)
{
return null;
}
public void TestMethodWithOutParameter(out string value)
// ReSharper restore UnusedMember.Local
{
value = "test";
}
// ReSharper disable UnusedMember.Local
// ReSharper disable UnusedParameter.Local
public void TestMethodWithRefParameter(ref string value)
// ReSharper restore UnusedParameter.Local
// ReSharper restore UnusedMember.Local
{
}
public void TestVoidMethod()
{
}
public void TestVoidMethod(int parameter1)
{
}
public void TestVoidMethod(int parameter1, int parameter2)
{
}
public void TestVoidMethod(int parameter1, int parameter2, int parameter3)
{
}
public void TestVoidMethod(int parameter1, int parameter2, int parameter3, int parameter4)
{
}
public void TestVoidMethod(int parameter1, int parameter2, int parameter3, int parameter4, int parameter5)
{
}
public void TestVoidMethod(int parameter1, int parameter2, int parameter3, int parameter4, int parameter5, int parameter6)
{
}
public void TestVoidMethod(int parameter1, int parameter2, int parameter3, int parameter4, int parameter5, int parameter6, int parameter7)
{
}
public void TestVoidMethod(int parameter1, int parameter2, int parameter3, int parameter4, int parameter5, int parameter6, int parameter7, int parameter8)
{
}
#endregion
// ReSharper restore UnusedParameter.Local
// ReSharper restore UnusedMember.Local
}
}
} | 39.411628 | 242 | 0.611937 | [
"MIT"
] | jam40jeff/BetterReflection | Source/MorseCode.BetterReflection/Tests/TypeInfoTests.cs | 33,896 | C# |
// Copyright 2020 New Relic, Inc. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
using System.Collections.Generic;
using NewRelic.Agent.Core.WireModels;
using NewRelic.Testing.Assertions;
using NUnit.Framework;
namespace NewRelic.Agent.Core.Transformers
{
public static class MetricTestHelpers
{
public static void CompareMetric(Dictionary<string, MetricDataWireModel> generatedMetrics, string metricName, float expectedValue)
{
NrAssert.Multiple(
() => Assert.AreEqual(1, generatedMetrics[metricName].Value0),
() => Assert.AreEqual(expectedValue, generatedMetrics[metricName].Value1),
() => Assert.AreEqual(expectedValue, generatedMetrics[metricName].Value2),
() => Assert.AreEqual(expectedValue, generatedMetrics[metricName].Value3),
() => Assert.AreEqual(expectedValue, generatedMetrics[metricName].Value4),
() => Assert.AreEqual(expectedValue * expectedValue, generatedMetrics[metricName].Value5)
);
}
}
}
| 41.576923 | 138 | 0.681776 | [
"Apache-2.0"
] | JoshuaColeman/newrelic-dotnet-agent | tests/Agent/UnitTests/Core.UnitTest/Transformers/MetricTestHelpers.cs | 1,081 | C# |
// <copyright file="HttpWebRequestInstrumentationOptions.netfx.cs" company="OpenTelemetry Authors">
// Copyright The OpenTelemetry Authors
//
// 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.
// </copyright>
#if NETFRAMEWORK
using System;
using System.Net;
using OpenTelemetry.Context.Propagation;
using OpenTelemetry.Trace;
namespace OpenTelemetry.Instrumentation.Http
{
/// <summary>
/// Options for dependencies instrumentation.
/// </summary>
public class HttpWebRequestInstrumentationOptions
{
/// <summary>
/// Gets or sets a value indicating whether or not the HTTP version should be added as the <see cref="SemanticConventions.AttributeHttpFlavor"/> tag. Default value: False.
/// </summary>
public bool SetHttpFlavor { get; set; } = false;
/// <summary>
/// Gets or sets <see cref="ITextFormat"/> for context propagation. Default value: <see cref="TraceContextFormat"/>.
/// </summary>
public ITextFormat TextFormat { get; set; } = new TraceContextFormat();
/// <summary>
/// Gets or sets an optional callback method for filtering <see cref="HttpWebRequest"/> requests that are sent through the instrumentation.
/// </summary>
public Func<HttpWebRequest, bool> FilterFunc { get; set; }
internal bool EventFilter(HttpWebRequest request)
{
Uri requestUri;
if (request.Method == "POST"
&& (requestUri = request.RequestUri) != null
&& HttpClientInstrumentationOptions.IsInternalUrl(requestUri))
{
return false;
}
return this.FilterFunc?.Invoke(request) ?? true;
}
}
}
#endif
| 38.016949 | 179 | 0.667856 | [
"Apache-2.0"
] | Place1/opentelemetry-dotnet | src/OpenTelemetry.Instrumentation.Http/HttpWebRequestInstrumentationOptions.netfx.cs | 2,245 | C# |
using System;
using System.Collections.Generic;
namespace CourseCrawler
{
public static class Consts
{
public static readonly string CoursePagePath = "https://aps.ntut.edu.tw/course/tw/Subj.jsp?format=-4&year=110&sem=1&code=";
public static readonly string[] StringSplitSeperators = new[] { "\r\n", "\r", "\n", " ", "\n\r" };
public static readonly List<string> CourseSymbols = new() { "", "○", "△", "☆", "●", "▲", "★" };
public static readonly List<string> LanguageSymbols = new() { "", "中文", "英語" };
public static readonly string NewLineChar = "\n";
public static readonly string SpaceChar = " ";
public static readonly string DiamondChar = "◆";
public static readonly string Monday = "一";
public static readonly string Tuesday = "二";
public static readonly string Wednesday = "三";
public static readonly string Thursday = "四";
public static readonly string Friday = "五";
public static readonly string Saturday = "六";
public static readonly string Sunday = "日";
public static readonly string Comma = ",";
public static readonly string IdeographicComma = "、";
public static readonly string Dash = "-";
public static readonly string UpperQuoteTw = "「";
public static readonly string LowerQuoteTw = "」";
public static readonly string NameConflictErrMsgHead = "課程名稱相同:";
public static readonly string TimeConflictErrMsgHead = "衝堂:";
public static readonly string SuccessfullySelectCourse = "加選成功";
public static readonly string SuccessfullySaveCourse = "儲存成功";
public static readonly string FailToSelectCourse = "加選失敗";
public static readonly string UnselectCourse = "退選";
public static readonly string SelectedCourse = "SelectedCourse";
public static readonly string TabPageNameTitle = "tabPage";
public static readonly string AllCourses = "AllCourses";
public static readonly string AllDepartments = "AllDepartments";
public static readonly int Big5EncodingCodePage = 950;
public static readonly int CourseAmountPerDay = 14;
public static readonly string MsgCourseDayTimeStringArraySizeNotAllowed = "Time string array has invalid length.";
public static readonly string MsgArrayLengthMustBeNonnegative = "Array length must be nonnegative";
public static readonly string CourseTimePeriodNameChars = "1234N56789ABCD";
public static readonly string MsgElementNotFound = "Member Not Found!";
public static readonly string MsgElementShouldNotBeFound = "Member Should Not Be Found!";
public static readonly string MsgDeadArea = "This area should not be proccessed!";
public static readonly string MsgFailToFetchResources = "Fail to fetch resources. Is the Internet works normally??";
public static readonly int CourseHourComboBoxMaxSelectIndex = 5;
public static readonly string NameCourseCrawlerTest = "CourseCrawlerTest";
public static readonly string PathExecutableRoot = "\\bin";
public static readonly string PathExecutableDebug = "\\bin\\Debug\\CourseCrawler.exe";
public static readonly string PathExecutableDRelease = "\\bin\\Release\\CourseCrawler.exe";
public static readonly string NewClasses = "NewClasses";
}
}
| 62.666667 | 131 | 0.694444 | [
"MIT"
] | Xanonymous-GitHub/course-crawler-hw | src/Consts.cs | 3,478 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BWMemoryEdit
{
public enum SpriteType : ushort
{
SPR_2_38_Ash = 0,
SPR_2_39_Ash,
SPR_2_41_Ash,
SPR_2_40_Ash,
SPR_2_42_Ash,
SPR_2_43_Ash,
SPR_2_44_Ash_,
SPR_2_1_Ash,
SPR_2_4_Ash,
SPR_2_5_Ash,
SPR_2_30_Ash,
SPR_2_28_Ash,
SPR_2_29_Ash,
SPR_4_1_Ash_,
SPR_4_2_Ash,
SPR_4_3_Ash,
SPR_4_56_Jungle,
SPR_4_57_Jungle,
SPR_4_58_Jungle,
SPR_4_59_Jungle,
SPR_9_5_Jungle,
SPR_9_6_Jungle,
SPR_9_7_Jungle,
SPR_4_51_Jungle,
SPR_4_52_Jungle,
SPR_4_54_Jungle,
SPR_4_53_Jungle,
SPR_BADLANDS_TREE01,
SPR_BADLANDS_TREE02,
SPR_BADLANDS_TREE03,
SPR_BADLANDS_TREE04,
SPR_4_12_Jungle,
SPR_4_13_Jungle,
SPR_4_1_Jungle,
SPR_4_3_Jungle,
SPR_4_2_Jungle,
SPR_4_5_Jungle,
SPR_4_4_Jungle,
SPR_4_9_Jungle,
SPR_4_10_Jungle,
SPR_5_5_Jungle,
SPR_5_7_Jungle,
SPR_5_6_Jungle,
SPR_5_9_Jungle,
SPR_5_8_Jungle,
SPR_4_6_Jungle,
SPR_4_7_Jungle,
SPR_4_17_Jungle,
SPR_13_4_Jungle,
SPR_11_5_Jungle,
SPR_11_6_Jungle,
SPR_11_7_Jungle,
SPR_11_8_Jungle,
SPR_11_10_Jungle,
SPR_11_11_Jungle,
SPR_11_12_Jungle,
SPR_7_4_Platform,
SPR_7_5_Platform,
SPR_7_6_Platform,
SPR_7_1_Platform,
SPR_7_2_Platform,
SPR_7_3_Platform,
SPR_7_9_Platform,
SPR_PLATFORM_TREE01,
SPR_PLATFORM_TREE02,
SPR_7_7_Platform,
SPR_7_26_Platform,
SPR_7_24_Platform,
SPR_7_28_Platform,
SPR_7_27_Platform,
SPR_7_25_Platform,
SPR_7_29_Platform,
SPR_7_30_Platform,
SPR_7_31_Platform,
SPR_12_1_Platform,
SPR_9_27_Platform,
SPR_5_54_Badlands,
SPR_5_55_Badlands,
SPR_5_56_Badlands,
SPR_5_57_Badlands,
SPR_6_16_Badlands,
SPR_6_17_Badlands,
SPR_6_20_Badlands,
SPR_6_21_Badlands,
SPR_5_10_Badlands,
SPR_5_50_Badlands,
SPR_5_52_Badlands,
SPR_5_53_Badlands,
SPR_5_51_Badlands,
SPR_6_3_Badlands,
SPR_11_3_Badlands,
SPR_11_8_Badlands,
SPR_11_6_Badlands,
SPR_11_7_Badlands,
SPR_11_9_Badlands,
SPR_11_10_Badlands,
SPR_11_11_Badlands,
SPR_11_12_Badlands,
SPR_11_13_Badlands,
SPR_11_14_Badlands,
SPR_1_13_Badlands,
SPR_1_9_Badlands,
SPR_1_11_Badlands,
SPR_1_14_Badlands,
SPR_1_10_Badlands,
SPR_1_12_Badlands,
SPR_1_15_Badlands,
SPR_1_7_Badlands,
SPR_1_5_Badlands,
SPR_1_16_Badlands,
SPR_1_8_Badlands,
SPR_1_6_Badlands1,
SPR_1_6_Badlands2,
SPR_1_6_Badlands3,
SPR_1_6_Badlands4,
SPR_1_6_Badlands5,
SPR_1_6_Badlands6,
SPR_1_6_Badlands7,
SPR_1_6_Badlands8,
SPR_4_15_Installation1,
SPR_4_15_Installation2,
SPR_3_9_Installation,
SPR_3_10_Installation,
SPR_3_11_Installation,
SPR_3_12_Installation,
SPR_1_6_Badlands9,
SPR_1_6_Badlands10,
SPR_3_1_Installation,
SPR_3_2_Installation,
SPR_1_6_Badlands11,
SPR_Scourge,
SPR_Scourge_Death,
SPR_Scourge_Explosion,
SPR_Broodling,
SPR_Broodling_Remnants,
SPR_Infested_Terran,
SPR_Infested_Terran_Explosion,
SPR_Guardian_Cocoon,
SPR_Defiler,
SPR_Defiler_Remnants,
SPR_Drone,
SPR_Drone_Remnants,
SPR_Egg,
SPR_Egg_Remnants,
SPR_Guardian,
SPR_Guardian_Death,
SPR_Hydralisk,
SPR_Hydralisk_Remnants,
SPR_Infested_Kerrigan,
SPR_Larva,
SPR_Larva_Remnants,
SPR_Mutalisk,
SPR_Mutalisk_Death,
SPR_Overlord,
SPR_Overlord_Death,
SPR_Queen,
SPR_Queen_Death,
SPR_Ultralisk,
SPR_Ultralisk_Remnants,
SPR_Zergling,
SPR_Zergling_Remnants,
SPR_Cerebrate,
SPR_Infested_Command_Center,
SPR_Spawning_Pool,
SPR_Mature_Chrysalis,
SPR_Evolution_Chamber,
SPR_Creep_Colony,
SPR_Hatchery,
SPR_Hive,
SPR_Lair,
SPR_Sunken_Colony,
SPR_Greater_Spire,
SPR_Defiler_Mound,
SPR_Queens_Nest,
SPR_Nydus_Canal,
SPR_Overmind_With_Shell,
SPR_Overmind_Without_Shell,
SPR_Ultralisk_Cavern,
SPR_Extractor,
SPR_Hydralisk_Den,
SPR_Spire,
SPR_Spore_Colony,
SPR_Zerg_Building_Spawn_Small,
SPR_Zerg_Building_Spawn_Medium,
SPR_Zerg_Building_Spawn_Large,
SPR_Zerg_Building_Explosion,
SPR_Zerg_Building_Rubble_Small,
SPR_Zerg_Building_Rubble_Large,
SPR_Arbiter,
SPR_Archon_Energy,
SPR_Carrier,
SPR_Dragoon,
SPR_Dragoon_Remnants,
SPR_Interceptor,
SPR_Probe,
SPR_Scout,
SPR_Shuttle,
SPR_High_Templar,
SPR_Dark_Templar_Hero,
SPR_Reaver,
SPR_Scarab,
SPR_Zealot,
SPR_Observer,
SPR_Templar_Archives,
SPR_Assimilator,
SPR_Observatory,
SPR_Citadel_of_Adun,
SPR_Forge,
SPR_Gateway,
SPR_Cybernetics_Core,
SPR_Khaydarin_Crystal_Formation,
SPR_Nexus,
SPR_Photon_Cannon,
SPR_Arbiter_Tribunal,
SPR_Pylon,
SPR_Robotics_Facility,
SPR_Shield_Battery,
SPR_Stargate,
SPR_Stasis_Cell_Prison,
SPR_Robotics_Support_Bay,
SPR_Protoss_Temple,
SPR_Fleet_Beacon,
SPR_Explosion_Large,
SPR_Protoss_Building_Rubble_Small,
SPR_Protoss_Building_Rubble_Large,
SPR_Battlecruiser,
SPR_Civilian,
SPR_Dropship,
SPR_Firebat,
SPR_Ghost,
SPR_Ghost_Remnants,
SPR_Nuke_Target_Dot,
SPR_Goliath_Base,
SPR_Goliath_Turret,
SPR_Sarah_Kerrigan,
SPR_Marine,
SPR_Marine_Remnants,
SPR_Scanner_Sweep,
SPR_Wraith,
SPR_SCV,
SPR_Siege_Tank_Tank_Base,
SPR_Siege_Tank_Tank_Turret,
SPR_Siege_Tank_Siege_Base,
SPR_Siege_Tank_Siege_Turret,
SPR_Vulture,
SPR_Spider_Mine,
SPR_Science_Vessel_Base,
SPR_Science_Vessel_Turret,
SPR_Terran_Academy,
SPR_Barracks,
SPR_Armory,
SPR_Comsat_Station,
SPR_Command_Center,
SPR_Supply_Depot,
SPR_Control_Tower,
SPR_Factory,
SPR_Covert_Ops,
SPR_Ion_Cannon,
SPR_Machine_Shop,
SPR_Missile_Turret_Base,
SPR_Crashed_Batlecruiser,
SPR_Physics_Lab,
SPR_Bunker,
SPR_Refinery,
SPR_Science_Facility,
SPR_Nuclear_Silo,
SPR_Nuclear_Missile,
SPR_Nuke_Hit,
SPR_Starport,
SPR_Engineering_Bay,
SPR_Terran_Construction_Large,
SPR_Terran_Construction_Small,
SPR_Building_Explosion_Large,
SPR_Terran_Building_Rubble_Small,
SPR_Terran_Building_Rubble_Large,
SPR_Vespene_Geyser,
SPR_Ragnasaur_Ash,
SPR_Rhynadon_Badlands,
SPR_Bengalaas_Jungle,
SPR_Mineral_Field_Type1,
SPR_Mineral_Field_Type2,
SPR_Mineral_Field_Type3,
SPR_Independent_Starport_Unused,
SPR_Zerg_Beacon,
SPR_Terran_Beacon,
SPR_Protoss_Beacon,
SPR_Dark_Swarm,
SPR_Flag,
SPR_Young_Chrysalis,
SPR_Psi_Emitter,
SPR_Data_Disc,
SPR_Khaydarin_Crystal,
SPR_Mineral_Chunk_Type1,
SPR_Mineral_Chunk_Type2,
SPR_Protoss_Gas_Orb_Type1,
SPR_Protoss_Gas_Orb_Type2,
SPR_Zerg_Gas_Sac_Type1,
SPR_Zerg_Gas_Sac_Type2,
SPR_Terran_Gas_Tank_Type1,
SPR_Terran_Gas_Tank_Type2,
SPR_White_Circle_Invisible,
SPR_Start_Location,
SPR_Map_Revealer,
SPR_Floor_Gun_Trap,
SPR_Wall_Missile_Trap,
SPR_Wall_Missile_Trap2,
SPR_Wall_Flame_Trap,
SPR_Wall_Flame_Trap2,
SPR_Floor_Missile_Trap,
SPR_Longbolt_Gemini_Missiles_Trail,
SPR_Grenade_Shot_Smoke,
SPR_Vespene_Geyser_Smoke1,
SPR_Vespene_Geyser_Smoke2,
SPR_Vespene_Geyser_Smoke3,
SPR_Vespene_Geyser_Smoke4,
SPR_Vespene_Geyser_Smoke5,
SPR_Small_Explosion_Unused,
SPR_Double_Explosion,
SPR_Cursor_Marker,
SPR_Egg_Spawn,
SPR_High_Templar_Glow,
SPR_Psi_Field_Right_Upper,
SPR_Burrowing_Dust,
SPR_Building_Landing_Dust_Type1,
SPR_Building_Landing_Dust_Type2,
SPR_Building_Landing_Dust_Type3,
SPR_Building_Landing_Dust_Type4,
SPR_Building_Landing_Dust_Type5,
SPR_Building_Lifting_Dust_Type1,
SPR_Building_Lifting_Dust_Type2,
SPR_Building_Lifting_Dust_Type3,
SPR_Building_Lifting_Dust_Type4,
SPR_Needle_Spines,
SPR_Dual_Photon_Blasters_Hit,
SPR_Particle_Beam_Hit,
SPR_Anti_Matter_Missile,
SPR_Pulse_Cannon,
SPR_Phase_Disruptor,
SPR_STA_STS_Photon_Cannon_Overlay,
SPR_Psionic_Storm,
SPR_Fusion_Cutter_Hit,
SPR_Gauss_Rifle_Hit,
SPR_Gemini_Missiles,
SPR_Fragmentation_Grenade,
SPR_Magna_Pulse_Unused,
SPR_Lockdown_LongBolt_Hellfire_Missile,
SPR_C_10_Canister_Rifle_Hit,
SPR_ATS_ATA_Laser_Battery,
SPR_Burst_Lasers,
SPR_Arclite_Shock_Cannon_Hit,
SPR_Yamato_Gun,
SPR_Yamato_Gun_Trail,
SPR_EMP_Shockwave_Missile,
SPR_Needle_Spine_Hit,
SPR_Plasma_Drip_Hit_Unused,
SPR_Sunken_Colony_Tentacle,
SPR_Venom_Unused_Zerg_Weapon,
SPR_Acid_Spore,
SPR_Glave_Wurm,
SPR_Seeker_Spores,
SPR_Queen_Spell_Holder,
SPR_Stasis_Field_Hit,
SPR_Plague_Cloud,
SPR_Consume,
SPR_Ensnare,
SPR_Glave_Wurm_Seeker_Spores_Hit,
SPR_Psionic_Shockwave_Hit,
SPR_Glave_Wurm_Trail,
SPR_Seeker_Spores_Overlay,
SPR_Phase_Disruptor_Unused,
SPR_White_Circle,
SPR_Acid_Spray_Unused,
SPR_Plasma_Drip_Unused,
SPR_Scarab_Anti_Matter_Missile_Overlay,
SPR_Hallucination_Death1,
SPR_Hallucination_Death2,
SPR_Hallucination_Death3,
SPR_Bunker_Overlay,
SPR_FlameThrower,
SPR_Recall_Field,
SPR_Scanner_Sweep_Hit,
SPR_Left_Upper_Level_Door,
SPR_Right_Upper_Level_Door,
SPR_Substructure_Left_Door,
SPR_Substructure_Right_Door,
SPR_Substructure_Opening_Hole,
SPR_7_13_Twilight,
SPR_7_14_Twilight,
SPR_7_16_Twilight,
SPR_7_15_Twilight,
SPR_7_19_Twilight,
SPR_7_20_Twilight,
SPR_7_21_Twilight,
SPR_Unknown_Twilight,
SPR_7_17_Twilight,
SPR_6_1_Twilight,
SPR_6_2_Twilight,
SPR_6_3_Twilight,
SPR_6_4_Twilight,
SPR_6_5_Twilight,
SPR_8_3_Twilight,
SPR_8_4_Twilight,
SPR_9_29_Ice,
SPR_9_28_Ice,
SPR_12_38_Ice_,
SPR_12_37_Ice,
SPR_12_33_Ice,
SPR_9_21_Ice,
SPR_9_15_Ice,
SPR_9_16_Ice,
SPR_Unknown410,
SPR_Unknown411,
SPR_12_9_Ice1,
SPR_12_10_Ice,
SPR_9_24_Ice_,
SPR_9_23_Ice,
SPR_Unknown416,
SPR_12_7_Ice,
SPR_12_8_Ice,
SPR_12_9_Ice2,
SPR_12_11_Ice,
SPR_12_40_Ice,
SPR_12_41_Ice,
SPR_12_42_Ice,
SPR_12_5_Ice,
SPR_12_6_Ice_,
SPR_12_36_Ice,
SPR_12_32_Ice,
SPR_12_35_Ice,
SPR_12_34_Ice,
SPR_12_24_Ice,
SPR_12_25_Ice,
SPR_9_22_Ice,
SPR_12_31_Ice,
SPR_12_20_Ice,
SPR_12_26_Ice,
SPR_12_27_Ice,
SPR_12_30_Ice,
SPR_12_39_Ice,
SPR_Unknown439,
SPR_4_1_Ice,
SPR_6_1_Ice,
SPR_5_6_Ice_,
SPR_5_7_Ice_,
SPR_5_8_Ice_,
SPR_5_9_Ice,
SPR_10_10_Desert1,
SPR_10_12_Desert1,
SPR_10_8_Desert,
SPR_10_9_Desert1,
SPR_6_10_Desert,
SPR_6_13_Desert,
SPR_Unknown_Desert,
SPR_10_12_Desert2,
SPR_10_9_Desert2,
SPR_10_10_Desert2,
SPR_10_11_Desert,
SPR_10_14_Desert,
SPR_10_41_Desert,
SPR_10_39_Desert,
SPR_10_9_Desert,
SPR_10_6_Desert,
SPR_10_7_Desert,
SPR_4_6_Desert,
SPR_4_11_Desert,
SPR_4_10_Desert,
SPR_4_9_Desert,
SPR_4_7_Desert,
SPR_4_12_Desert,
SPR_4_8_Desert,
SPR_4_13_Desert,
SPR_6_14_Desert,
SPR_4_17_Desert,
SPR_6_20_Desert,
SPR_4_15_Desert1,
SPR_4_15_Desert2,
SPR_10_23_Desert,
SPR_8_23_Desert,
SPR_10_5_Desert,
SPR_12_1_Desert_Overlay,
SPR_11_3_Desert,
SPR_Lurker_Egg,
SPR_Devourer,
SPR_Devourer_Death,
SPR_Lurker_Remnants,
SPR_Lurker,
SPR_Dark_Archon_Energy,
SPR_Corsair,
SPR_Dark_Templar_Unit,
SPR_Medic,
SPR_Medic_Remnants,
SPR_Valkyrie,
SPR_Scantid_Desert,
SPR_Kakaru_Twilight,
SPR_Ursadon_Ice,
SPR_Overmind_Cocoon,
SPR_Power_Generator,
SPR_XelNaga_Temple,
SPR_Psi_Disrupter,
SPR_Warp_Gate,
SPR_Feedback_Hit_Small,
SPR_Feedback_Hit_Medium,
SPR_Feedback_Hit_Large,
SPR_Disruption_Web,
SPR_White_Circle2,
SPR_Halo_Rockets_Trail,
SPR_Neutron_Flare,
SPR_Neutron_Flare_Overlay_Unused,
SPR_Optical_Flare_Grenade,
SPR_Halo_Rockets,
SPR_Subterranean_Spines_Hit,
SPR_Subterranean_Spines,
SPR_Corrosive_Acid_Shot,
SPR_Corrosive_Acid_Hit,
SPR_Maelstrom_Hit,
SPR_Uraj,
SPR_Khalis,
SPR_None
}
}
| 27.269303 | 47 | 0.638605 | [
"MIT"
] | WoodoLee/TorchCraft | 3rdparty/openbw/bwapi/bwapi/BWMemoryEdit/Enums/SpriteType.cs | 14,482 | 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.
// Copied from https://github.com/dotnet/coreclr/blob/16697076c0a6af47fbcce75e11c45d35a12b7d4e/src/System.Private.CoreLib/shared/System/Diagnostics/CodeAnalysis/NullableAttributes.cs
#if NET461 || NETSTANDARD
// ReSharper disable once CheckNamespace
namespace System.Diagnostics.CodeAnalysis
{
/// <summary>Specifies that null is allowed as an input even if the corresponding type disallows it.</summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property, Inherited = false)]
internal sealed class AllowNullAttribute : Attribute { }
/// <summary>Specifies that null is disallowed as an input even if the corresponding type allows it.</summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property, Inherited = false)]
internal sealed class DisallowNullAttribute : Attribute { }
/// <summary>Specifies that an output may be null even if the corresponding type disallows it.</summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, Inherited = false)]
internal sealed class MaybeNullAttribute : Attribute { }
/// <summary>Specifies that an output will not be null even if the corresponding type allows it.</summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, Inherited = false)]
internal sealed class NotNullAttribute : Attribute { }
/// <summary>Specifies that when a method returns <see cref="ReturnValue"/>, the parameter may be null even if the corresponding type disallows it.</summary>
[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
internal sealed class MaybeNullWhenAttribute : Attribute
{
/// <summary>Initializes the attribute with the specified return value condition.</summary>
/// <param name="returnValue">
/// The return value condition. If the method returns this value, the associated parameter may be null.
/// </param>
public MaybeNullWhenAttribute(bool returnValue) => ReturnValue = returnValue;
/// <summary>Gets the return value condition.</summary>
public bool ReturnValue { get; }
}
/// <summary>Specifies that when a method returns <see cref="ReturnValue"/>, the parameter will not be null even if the corresponding type allows it.</summary>
[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
internal sealed class NotNullWhenAttribute : Attribute
{
/// <summary>Initializes the attribute with the specified return value condition.</summary>
/// <param name="returnValue">
/// The return value condition. If the method returns this value, the associated parameter will not be null.
/// </param>
public NotNullWhenAttribute(bool returnValue) => ReturnValue = returnValue;
/// <summary>Gets the return value condition.</summary>
public bool ReturnValue { get; }
}
/// <summary>Specifies that the output will be non-null if the named parameter is non-null.</summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)]
internal sealed class NotNullIfNotNullAttribute : Attribute
{
/// <summary>Initializes the attribute with the associated parameter name.</summary>
/// <param name="parameterName">
/// The associated parameter name. The output will be non-null if the argument to the parameter specified is non-null.
/// </param>
public NotNullIfNotNullAttribute(string parameterName) => ParameterName = parameterName;
/// <summary>Gets the associated parameter name.</summary>
public string ParameterName { get; }
}
/// <summary>Applied to a method that will never return under any circumstance.</summary>
[AttributeUsage(AttributeTargets.Method, Inherited = false)]
internal sealed class DoesNotReturnAttribute : Attribute { }
/// <summary>Specifies that the method will not return if the associated Boolean parameter is passed the specified value.</summary>
[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
internal sealed class DoesNotReturnIfAttribute : Attribute
{
/// <summary>Initializes the attribute with the specified parameter value.</summary>
/// <param name="parameterValue">
/// The condition parameter value. Code after the method will be considered unreachable by diagnostics if the argument to
/// the associated parameter matches this value.
/// </param>
public DoesNotReturnIfAttribute(bool parameterValue) => ParameterValue = parameterValue;
/// <summary>Gets the condition parameter value.</summary>
public bool ParameterValue { get; }
}
}
#endif
| 56.879121 | 182 | 0.731839 | [
"MIT"
] | DanHarltey/Scrutor | src/Scrutor/NullableAttributes.cs | 5,178 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.ML.Core.Data;
using Microsoft.ML.Data;
using Microsoft.ML.Runtime;
using Microsoft.ML.Runtime.Data;
using Microsoft.ML.Runtime.Internal.Utilities;
using Microsoft.ML.Transforms;
using System.Collections.Generic;
using System.Linq;
namespace Microsoft.ML.StaticPipe.Runtime
{
/// <summary>
/// General purpose reconciler for a typical case with trainers, where they accept some generally
/// fixed number of inputs, and produce some outputs where the names of the outputs are fixed.
/// Authors of components that want to produce columns can subclass this directly, or use one of the
/// common nested subclasses.
/// </summary>
public abstract class TrainerEstimatorReconciler : EstimatorReconciler
{
protected readonly PipelineColumn[] Inputs;
private readonly string[] _outputNames;
/// <summary>
/// The output columns. Note that subclasses should return exactly the same items each time,
/// and the items should correspond to the output names passed into the constructor.
/// </summary>
protected abstract IEnumerable<PipelineColumn> Outputs { get; }
/// <summary>
/// Constructor for the base class.
/// </summary>
/// <param name="inputs">The set of inputs</param>
/// <param name="outputNames">The names of the outputs, which we assume cannot be changed</param>
protected TrainerEstimatorReconciler(PipelineColumn[] inputs, string[] outputNames)
{
Contracts.CheckValue(inputs, nameof(inputs));
Contracts.CheckValue(outputNames, nameof(outputNames));
Inputs = inputs;
_outputNames = outputNames;
}
/// <summary>
/// Produce the training estimator.
/// </summary>
/// <param name="env">The host environment to use to create the estimator.</param>
/// <param name="inputNames">The names of the inputs, which corresponds exactly to the input columns
/// fed into the constructor.</param>
/// <returns>An estimator, which should produce the additional columns indicated by the output names
/// in the constructor.</returns>
protected abstract IEstimator<ITransformer> ReconcileCore(IHostEnvironment env, string[] inputNames);
/// <summary>
/// Produces the estimator. Note that this is made out of <see cref="ReconcileCore(IHostEnvironment, string[])"/>'s
/// return value, plus whatever usages of <see cref="ColumnCopyingEstimator"/> are necessary to avoid collisions with
/// the output names fed to the constructor. This class provides the implementation, and subclasses should instead
/// override <see cref="ReconcileCore(IHostEnvironment, string[])"/>.
/// </summary>
public sealed override IEstimator<ITransformer> Reconcile(IHostEnvironment env,
PipelineColumn[] toOutput,
IReadOnlyDictionary<PipelineColumn, string> inputNames,
IReadOnlyDictionary<PipelineColumn, string> outputNames,
IReadOnlyCollection<string> usedNames)
{
Contracts.AssertValue(env);
env.AssertValue(toOutput);
env.AssertValue(inputNames);
env.AssertValue(outputNames);
env.AssertValue(usedNames);
// The reconciler should have been called with all the input columns having names.
env.Assert(inputNames.Keys.All(Inputs.Contains) && Inputs.All(inputNames.Keys.Contains));
// The output name map should contain only outputs as their keys. Yet, it is possible not all
// outputs will be required in which case these will both be subsets of those outputs indicated
// at construction.
env.Assert(outputNames.Keys.All(Outputs.Contains));
env.Assert(toOutput.All(Outputs.Contains));
env.Assert(Outputs.Count() == _outputNames.Length);
IEstimator<ITransformer> result = null;
// In the case where we have names used that conflict with the fixed output names, we must have some
// renaming logic.
var collisions = new HashSet<string>(_outputNames);
collisions.IntersectWith(usedNames);
var old2New = new Dictionary<string, string>();
if (collisions.Count > 0)
{
// First get the old names to some temporary names.
int tempNum = 0;
foreach (var c in collisions)
old2New[c] = $"#TrainTemp{tempNum++}";
// In the case where the input names have anything that is used, we must reconstitute the input mapping.
if (inputNames.Values.Any(old2New.ContainsKey))
{
var newInputNames = new Dictionary<PipelineColumn, string>();
foreach (var p in inputNames)
newInputNames[p.Key] = old2New.ContainsKey(p.Value) ? old2New[p.Value] : p.Value;
inputNames = newInputNames;
}
result = new ColumnCopyingEstimator(env, old2New.Select(p => (p.Key, p.Value)).ToArray());
}
// Map the inputs to the names.
string[] mappedInputNames = Inputs.Select(c => inputNames[c]).ToArray();
// Finally produce the trainer.
var trainerEst = ReconcileCore(env, mappedInputNames);
if (result == null)
result = trainerEst;
else
result = result.Append(trainerEst);
// OK. Now handle the final renamings from the fixed names, to the desired names, in the case
// where the output was desired, and a renaming is even necessary.
var toRename = new List<(string source, string name)>();
foreach ((PipelineColumn outCol, string fixedName) in Outputs.Zip(_outputNames, (c, n) => (c, n)))
{
if (outputNames.TryGetValue(outCol, out string desiredName))
toRename.Add((fixedName, desiredName));
else
env.Assert(!toOutput.Contains(outCol));
}
// Finally if applicable handle the renaming back from the temp names to the original names.
foreach (var p in old2New)
toRename.Add((p.Value, p.Key));
if (toRename.Count > 0)
result = result.Append(new ColumnCopyingEstimator(env, toRename.ToArray()));
return result;
}
/// <summary>
/// A reconciler for regression capable of handling the most common cases for regression.
/// </summary>
public sealed class Regression : TrainerEstimatorReconciler
{
/// <summary>
/// The delegate to create the regression trainer instance.
/// </summary>
/// <param name="env">The environment with which to create the estimator</param>
/// <param name="label">The label column name</param>
/// <param name="features">The features column name</param>
/// <param name="weights">The weights column name, or <c>null</c> if the reconciler was constructed with <c>null</c> weights</param>
/// <returns>A estimator producing columns with the fixed name <see cref="DefaultColumnNames.Score"/>.</returns>
public delegate IEstimator<ITransformer> EstimatorFactory(IHostEnvironment env, string label, string features, string weights);
private readonly EstimatorFactory _estFact;
/// <summary>
/// The output score column for the regression. This will have this instance as its reconciler.
/// </summary>
public Scalar<float> Score { get; }
protected override IEnumerable<PipelineColumn> Outputs => Enumerable.Repeat(Score, 1);
private static readonly string[] _fixedOutputNames = new[] { DefaultColumnNames.Score };
/// <summary>
/// Constructs a new general regression reconciler.
/// </summary>
/// <param name="estimatorFactory">The delegate to create the training estimator. It is assumed that this estimator
/// will produce a single new scalar <see cref="float"/> column named <see cref="DefaultColumnNames.Score"/>.</param>
/// <param name="label">The input label column.</param>
/// <param name="features">The input features column.</param>
/// <param name="weights">The input weights column, or <c>null</c> if there are no weights.</param>
public Regression(EstimatorFactory estimatorFactory, Scalar<float> label, Vector<float> features, Scalar<float> weights)
: base(MakeInputs(Contracts.CheckRef(label, nameof(label)), Contracts.CheckRef(features, nameof(features)), weights),
_fixedOutputNames)
{
Contracts.CheckValue(estimatorFactory, nameof(estimatorFactory));
_estFact = estimatorFactory;
Contracts.Assert(Inputs.Length == 2 || Inputs.Length == 3);
Score = new Impl(this);
}
private static PipelineColumn[] MakeInputs(Scalar<float> label, Vector<float> features, Scalar<float> weights)
=> weights == null ? new PipelineColumn[] { label, features } : new PipelineColumn[] { label, features, weights };
protected override IEstimator<ITransformer> ReconcileCore(IHostEnvironment env, string[] inputNames)
{
Contracts.AssertValue(env);
env.Assert(Utils.Size(inputNames) == Inputs.Length);
return _estFact(env, inputNames[0], inputNames[1], inputNames.Length > 2 ? inputNames[2] : null);
}
private sealed class Impl : Scalar<float>
{
public Impl(Regression rec) : base(rec, rec.Inputs) { }
}
}
/// <summary>
/// A reconciler capable of handling the most common cases for binary classification with calibrated outputs.
/// </summary>
public sealed class BinaryClassifier : TrainerEstimatorReconciler
{
/// <summary>
/// The delegate to create the binary classifier trainer instance.
/// </summary>
/// <param name="env">The environment with which to create the estimator.</param>
/// <param name="label">The label column name.</param>
/// <param name="features">The features column name.</param>
/// <param name="weights">The weights column name, or <c>null</c> if the reconciler was constructed with <c>null</c> weights.</param>
/// <returns>A binary classification trainer estimator.</returns>
public delegate IEstimator<ITransformer> EstimatorFactory(IHostEnvironment env, string label, string features, string weights);
private readonly EstimatorFactory _estFact;
private static readonly string[] _fixedOutputNames = new[] { DefaultColumnNames.Score, DefaultColumnNames.Probability, DefaultColumnNames.PredictedLabel };
/// <summary>
/// The general output for binary classifiers.
/// </summary>
public (Scalar<float> score, Scalar<float> probability, Scalar<bool> predictedLabel) Output { get; }
protected override IEnumerable<PipelineColumn> Outputs => new PipelineColumn[] { Output.score, Output.probability, Output.predictedLabel };
/// <summary>
/// Constructs a new general regression reconciler.
/// </summary>
/// <param name="estimatorFactory">The delegate to create the training estimator. It is assumed that this estimator
/// will produce a single new scalar <see cref="float"/> column named <see cref="DefaultColumnNames.Score"/>.</param>
/// <param name="label">The input label column.</param>
/// <param name="features">The input features column.</param>
/// <param name="weights">The input weights column, or <c>null</c> if there are no weights.</param>
public BinaryClassifier(EstimatorFactory estimatorFactory, Scalar<bool> label, Vector<float> features, Scalar<float> weights)
: base(MakeInputs(Contracts.CheckRef(label, nameof(label)), Contracts.CheckRef(features, nameof(features)), weights),
_fixedOutputNames)
{
Contracts.CheckValue(estimatorFactory, nameof(estimatorFactory));
_estFact = estimatorFactory;
Contracts.Assert(Inputs.Length == 2 || Inputs.Length == 3);
Output = (new Impl(this), new Impl(this), new ImplBool(this));
}
private static PipelineColumn[] MakeInputs(Scalar<bool> label, Vector<float> features, Scalar<float> weights)
=> weights == null ? new PipelineColumn[] { label, features } : new PipelineColumn[] { label, features, weights };
protected override IEstimator<ITransformer> ReconcileCore(IHostEnvironment env, string[] inputNames)
{
Contracts.AssertValue(env);
env.Assert(Utils.Size(inputNames) == Inputs.Length);
return _estFact(env, inputNames[0], inputNames[1], inputNames.Length > 2 ? inputNames[2] : null);
}
private sealed class Impl : Scalar<float>
{
public Impl(BinaryClassifier rec) : base(rec, rec.Inputs) { }
}
private sealed class ImplBool : Scalar<bool>
{
public ImplBool(BinaryClassifier rec) : base(rec, rec.Inputs) { }
}
}
/// <summary>
/// A reconciler capable of handling the most common cases for binary classification that does not
/// necessarily have calibrated outputs.
/// </summary>
public sealed class BinaryClassifierNoCalibration : TrainerEstimatorReconciler
{
/// <summary>
/// The delegate to create the binary classifier trainer instance.
/// </summary>
/// <param name="env">The environment with which to create the estimator</param>
/// <param name="label">The label column name.</param>
/// <param name="features">The features column name.</param>
/// <param name="weights">The weights column name, or <c>null</c> if the reconciler was constructed with <c>null</c> weights.</param>
/// <returns>A binary classification trainer estimator.</returns>
public delegate IEstimator<ITransformer> EstimatorFactory(IHostEnvironment env, string label, string features, string weights);
private readonly EstimatorFactory _estFact;
private static readonly string[] _fixedOutputNamesProb = new[] { DefaultColumnNames.Score, DefaultColumnNames.Probability, DefaultColumnNames.PredictedLabel };
private static readonly string[] _fixedOutputNames = new[] { DefaultColumnNames.Score, DefaultColumnNames.PredictedLabel };
/// <summary>
/// The general output for binary classifiers.
/// </summary>
public (Scalar<float> score, Scalar<bool> predictedLabel) Output { get; }
/// <summary>
/// The output columns, which will contain at least the columns produced by <see cref="Output"/> and may contain an
/// additional <see cref="DefaultColumnNames.Probability"/> column if at runtime we determine the predictor actually
/// is calibrated.
/// </summary>
protected override IEnumerable<PipelineColumn> Outputs { get; }
/// <summary>
/// Constructs a new general binary classifier reconciler.
/// </summary>
/// <param name="estimatorFactory">The delegate to create the training estimator. It is assumed that this estimator
/// will produce a single new scalar <see cref="float"/> column named <see cref="DefaultColumnNames.Score"/>.</param>
/// <param name="label">The input label column.</param>
/// <param name="features">The input features column.</param>
/// <param name="weights">The input weights column, or <c>null</c> if there are no weights.</param>
/// <param name="hasProbs">While this type is a compile time construct, it may be that at runtime we have determined that we will have probabilities,
/// and so ought to do the renaming of the <see cref="DefaultColumnNames.Probability"/> column anyway if appropriate. If this is so, then this should
/// be set to true.</param>
public BinaryClassifierNoCalibration(EstimatorFactory estimatorFactory, Scalar<bool> label, Vector<float> features, Scalar<float> weights, bool hasProbs)
: base(MakeInputs(Contracts.CheckRef(label, nameof(label)), Contracts.CheckRef(features, nameof(features)), weights),
hasProbs ? _fixedOutputNamesProb : _fixedOutputNames)
{
Contracts.CheckValue(estimatorFactory, nameof(estimatorFactory));
_estFact = estimatorFactory;
Contracts.Assert(Inputs.Length == 2 || Inputs.Length == 3);
Output = (new Impl(this), new ImplBool(this));
if (hasProbs)
Outputs = new PipelineColumn[] { Output.score, new Impl(this), Output.predictedLabel };
else
Outputs = new PipelineColumn[] { Output.score, Output.predictedLabel };
}
private static PipelineColumn[] MakeInputs(Scalar<bool> label, Vector<float> features, Scalar<float> weights)
=> weights == null ? new PipelineColumn[] { label, features } : new PipelineColumn[] { label, features, weights };
protected override IEstimator<ITransformer> ReconcileCore(IHostEnvironment env, string[] inputNames)
{
Contracts.AssertValue(env);
env.Assert(Utils.Size(inputNames) == Inputs.Length);
return _estFact(env, inputNames[0], inputNames[1], inputNames.Length > 2 ? inputNames[2] : null);
}
private sealed class Impl : Scalar<float>
{
public Impl(BinaryClassifierNoCalibration rec) : base(rec, rec.Inputs) { }
}
private sealed class ImplBool : Scalar<bool>
{
public ImplBool(BinaryClassifierNoCalibration rec) : base(rec, rec.Inputs) { }
}
}
/// <summary>
/// A reconciler capable of handling clustering.
/// </summary>
public sealed class Clustering : TrainerEstimatorReconciler
{
/// <summary>
/// The delegate to create the clustering trainer instance.
/// </summary>
/// <param name="env">The environment with which to create the estimator.</param>
/// <param name="features">The features column name.</param>
/// <param name="weights">The weights column name, or <c>null</c> if the reconciler was constructed with <c>null</c> weights.</param>
/// <returns>A clustering trainer estimator.</returns>
public delegate IEstimator<ITransformer> EstimatorFactory(IHostEnvironment env, string features, string weights);
private readonly EstimatorFactory _estFact;
private static readonly string[] _fixedOutputNames = new[] { DefaultColumnNames.Score, DefaultColumnNames.PredictedLabel };
/// <summary>
/// The general output for clustering.
/// </summary>
public (Vector<float> score, Key<uint> predictedLabel) Output { get; }
/// <summary>
/// The output columns, which will contain the columns produced by <see cref="Output"/>.
/// </summary>
protected override IEnumerable<PipelineColumn> Outputs => new PipelineColumn[] { Output.score, Output.predictedLabel };
/// <summary>
/// Constructs a new general clustering reconciler.
/// </summary>
/// <param name="estimatorFactory">The delegate to create the training estimator. It is assumed that this estimator
/// will produce a new scalar <see cref="float"/> column named <see cref="DefaultColumnNames.Score"/> and a <see cref="Key{UInt32}"/>
/// named PredictedLabel.</param>
/// <param name="features">The input features column.</param>
/// <param name="weights">The input weights column, or <c>null</c> if there are no weights.</param>
public Clustering(EstimatorFactory estimatorFactory, Vector<float> features, Scalar<float> weights)
: base(MakeInputs(Contracts.CheckRef(features, nameof(features)), weights),
_fixedOutputNames)
{
Contracts.CheckValue(estimatorFactory, nameof(estimatorFactory));
_estFact = estimatorFactory;
Contracts.Assert(Inputs.Length == 1 || Inputs.Length == 2);
Output = (new ImplScore(this), new ImplLabel(this));
}
private static PipelineColumn[] MakeInputs(Vector<float> features, Scalar<float> weights)
=> weights == null ? new PipelineColumn[] { features } : new PipelineColumn[] { features, weights };
protected override IEstimator<ITransformer> ReconcileCore(IHostEnvironment env, string[] inputNames)
{
Contracts.AssertValue(env);
env.Assert(Utils.Size(inputNames) == Inputs.Length);
return _estFact(env, inputNames[0], inputNames.Length > 1 ? inputNames[1] : null);
}
private sealed class ImplScore : Vector<float>
{
public ImplScore(Clustering rec) : base(rec, rec.Inputs) { }
}
private sealed class ImplLabel : Key<uint>
{
public ImplLabel(Clustering rec) : base(rec, rec.Inputs) { }
}
}
/// <summary>
/// A reconciler for regression capable of handling the most common cases for regression.
/// </summary>
public sealed class MulticlassClassifier<TVal> : TrainerEstimatorReconciler
{
/// <summary>
/// The delegate to create the multiclass classifier trainer instance.
/// </summary>
/// <param name="env">The environment with which to create the estimator</param>
/// <param name="label">The label column name</param>
/// <param name="features">The features column name</param>
/// <param name="weights">The weights column name, or <c>null</c> if the reconciler was constructed with <c>null</c> weights</param>
/// <returns>A estimator producing columns with the fixed name <see cref="DefaultColumnNames.Score"/> and <see cref="DefaultColumnNames.PredictedLabel"/>.</returns>
public delegate IEstimator<ITransformer> EstimatorFactory(IHostEnvironment env, string label, string features, string weights);
private readonly EstimatorFactory _estFact;
/// <summary>
/// The general output for multiclass classifiers.
/// </summary>
public (Vector<float> score, Key<uint, TVal> predictedLabel) Output { get; }
protected override IEnumerable<PipelineColumn> Outputs => new PipelineColumn[] { Output.score, Output.predictedLabel };
private static readonly string[] _fixedOutputNames = new[] { DefaultColumnNames.Score, DefaultColumnNames.PredictedLabel };
/// <summary>
/// Constructs a new general multiclass classifier reconciler.
/// </summary>
/// <param name="estimatorFactory">The delegate to create the training estimator. It is assumed that this estimator
/// will produce a vector <see cref="float"/> column named <see cref="DefaultColumnNames.Score"/> and a scalar
/// key column named <see cref="DefaultColumnNames.PredictedLabel"/>.</param>
/// <param name="label">The input label column.</param>
/// <param name="features">The input features column.</param>
/// <param name="weights">The input weights column, or <c>null</c> if there are no weights.</param>
public MulticlassClassifier(EstimatorFactory estimatorFactory, Key<uint, TVal> label, Vector<float> features, Scalar<float> weights)
: base(MakeInputs(Contracts.CheckRef(label, nameof(label)), Contracts.CheckRef(features, nameof(features)), weights),
_fixedOutputNames)
{
Contracts.CheckValue(estimatorFactory, nameof(estimatorFactory));
_estFact = estimatorFactory;
Contracts.Assert(Inputs.Length == 2 || Inputs.Length == 3);
Output = (new ImplScore(this), new ImplLabel(this));
}
private static PipelineColumn[] MakeInputs(Key<uint, TVal> label, Vector<float> features, Scalar<float> weights)
=> weights == null ? new PipelineColumn[] { label, features } : new PipelineColumn[] { label, features, weights };
protected override IEstimator<ITransformer> ReconcileCore(IHostEnvironment env, string[] inputNames)
{
Contracts.AssertValue(env);
env.Assert(Utils.Size(inputNames) == Inputs.Length);
return _estFact(env, inputNames[0], inputNames[1], inputNames.Length > 2 ? inputNames[2] : null);
}
private sealed class ImplLabel : Key<uint, TVal>
{
public ImplLabel(MulticlassClassifier<TVal> rec) : base(rec, rec.Inputs) { }
}
private sealed class ImplScore : Vector<float>
{
public ImplScore(MulticlassClassifier<TVal> rec) : base(rec, rec.Inputs) { }
}
}
/// <summary>
/// A reconciler for ranking capable of handling the most common cases for ranking.
/// </summary>
public sealed class Ranker<TVal> : TrainerEstimatorReconciler
{
/// <summary>
/// The delegate to create the ranking trainer instance.
/// </summary>
/// <param name="env">The environment with which to create the estimator</param>
/// <param name="label">The label column name</param>
/// <param name="features">The features column name</param>
/// <param name="weights">The weights column name, or <c>null</c> if the reconciler was constructed with <c>null</c> weights</param>
/// <param name="groupId">The groupId column name.</param>
/// <returns>A estimator producing columns with the fixed name <see cref="DefaultColumnNames.Score"/>.</returns>
public delegate IEstimator<ITransformer> EstimatorFactory(IHostEnvironment env, string label, string features, string weights, string groupId);
private readonly EstimatorFactory _estFact;
/// <summary>
/// The output score column for ranking. This will have this instance as its reconciler.
/// </summary>
public Scalar<float> Score { get; }
protected override IEnumerable<PipelineColumn> Outputs => Enumerable.Repeat(Score, 1);
private static readonly string[] _fixedOutputNames = new[] { DefaultColumnNames.Score };
/// <summary>
/// Constructs a new general ranker reconciler.
/// </summary>
/// <param name="estimatorFactory">The delegate to create the training estimator. It is assumed that this estimator
/// will produce a single new scalar <see cref="float"/> column named <see cref="DefaultColumnNames.Score"/>.</param>
/// <param name="label">The input label column.</param>
/// <param name="features">The input features column.</param>
/// <param name="weights">The input weights column, or <c>null</c> if there are no weights.</param>
/// <param name="groupId">The input groupId column.</param>
public Ranker(EstimatorFactory estimatorFactory, Scalar<float> label, Vector<float> features, Key<uint, TVal> groupId, Scalar<float> weights)
: base(MakeInputs(Contracts.CheckRef(label, nameof(label)),
Contracts.CheckRef(features, nameof(features)),
Contracts.CheckRef(groupId, nameof(groupId)),
weights),
_fixedOutputNames)
{
Contracts.CheckValue(estimatorFactory, nameof(estimatorFactory));
_estFact = estimatorFactory;
Contracts.Assert(Inputs.Length == 3 || Inputs.Length == 4);
Score = new Impl(this);
}
private static PipelineColumn[] MakeInputs(Scalar<float> label, Vector<float> features, Key<uint, TVal> groupId, Scalar<float> weights)
=> weights == null ? new PipelineColumn[] { label, features, groupId } : new PipelineColumn[] { label, features, groupId, weights };
protected override IEstimator<ITransformer> ReconcileCore(IHostEnvironment env, string[] inputNames)
{
Contracts.AssertValue(env);
env.Assert(Utils.Size(inputNames) == Inputs.Length);
return _estFact(env, inputNames[0], inputNames[1], inputNames[2], inputNames.Length > 3 ? inputNames[3] : null);
}
private sealed class Impl : Scalar<float>
{
public Impl(Ranker<TVal> rec) : base(rec, rec.Inputs) { }
}
}
}
}
| 55.998152 | 176 | 0.616702 | [
"MIT"
] | Jungmaus/machinelearning | src/Microsoft.ML.Data/StaticPipe/TrainerEstimatorReconciler.cs | 30,297 | C# |
//******************************************************************************************************
// AssemblyInfo.cs - Gbtc
//
// Copyright © 2013, Grid Protection Alliance. All Rights Reserved.
//
// Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See
// the NOTICE file distributed with this work for additional information regarding copyright ownership.
// The GPA licenses this file to you under the MIT License (MIT), 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.opensource.org/licenses/MIT
//
// Unless agreed to in writing, the subject software distributed under the License is distributed on an
// "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the
// License for the specific language governing permissions and limitations.
//
// Code Modification History:
// ----------------------------------------------------------------------------------------------------
// 05/09/2013 - J. Ritchie Carroll
// Generated original version of source code.
//
//******************************************************************************************************
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("DynamicCalculator")]
[assembly: AssemblyDescription("Adapter used for Calculations via Dynamic Expression Evaluation")]
[assembly: AssemblyCompany("Grid Protection Alliance")]
[assembly: AssemblyProduct("Grid Solutions Framework")]
[assembly: AssemblyCopyright("Copyright © GPA, 2013. All Rights Reserved.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
#if DEBUG
[assembly: AssemblyConfiguration("Debug Build")]
#else
[assembly: AssemblyConfiguration("Release Build")]
#endif
// 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("e710ca66-2222-464b-99f9-cbb5b7f0ecd9")]
// 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("2.3.504.0")]
[assembly: AssemblyVersion("2.3.504.0")]
[assembly: AssemblyFileVersion("2.3.504.0")]
[assembly: AssemblyInformationalVersion("2.3.504-beta")]
| 45.015385 | 105 | 0.669856 | [
"MIT"
] | SRM256/gsf | Source/Libraries/Adapters/DynamicCalculator/Properties/AssemblyInfo.cs | 2,930 | C# |
using Inshapardaz.Api.Tests.Asserts;
using Inshapardaz.Api.Tests.Dto;
using Inshapardaz.Api.Views.Library;
using Inshapardaz.Domain.Models;
using NUnit.Framework;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
namespace Inshapardaz.Api.Tests.Library.Book.GetBooksBySeries
{
[TestFixture(Role.Admin)]
[TestFixture(Role.LibraryAdmin)]
[TestFixture(Role.Writer)]
public class WhenGettingBooksBySeriesWithWritePermission
: TestBase
{
private HttpResponseMessage _response;
private PagingAssert<BookView> _assert;
private SeriesDto _series;
private IEnumerable<BookDto> _seriesBooks;
public WhenGettingBooksBySeriesWithWritePermission(Role role)
: base(role)
{
}
[OneTimeSetUp]
public async Task Setup()
{
_series = SeriesBuilder.WithLibrary(LibraryId).Build();
_seriesBooks = BookBuilder.WithLibrary(LibraryId).WithSeries(_series).IsPublic().Build(5);
SeriesBuilder.WithLibrary(LibraryId).WithBooks(3).Build();
_response = await Client.GetAsync($"/libraries/{LibraryId}/books?pageNumber=1&pageSize=10&seriesid={_series.Id}");
_assert = new PagingAssert<BookView>(_response);
}
[OneTimeTearDown]
public void Teardown()
{
Cleanup();
}
[Test]
public void ShouldReturnOk()
{
_response.ShouldBeOk();
}
[Test]
public void ShouldHaveSelfLink()
{
_assert.ShouldHaveSelfLink($"/libraries/{LibraryId}/books", 1, 10,
new KeyValuePair<string, string>("seriesId", _series.Id.ToString()));
}
[Test]
public void ShouldNotHaveNextLink()
{
_assert.ShouldNotHaveNextLink();
}
[Test]
public void ShouldNotHavePreviousLink()
{
_assert.ShouldNotHavePreviousLink();
}
[Test]
public void ShouldNotHaveCreateLink()
{
_assert.ShouldHaveCreateLink($"/libraries/{LibraryId}/books");
}
[Test]
public void ShouldReturnCorrectPage()
{
_assert.ShouldHavePage(1)
.ShouldHavePageSize(10)
.ShouldHaveTotalCount(_seriesBooks.Count())
.ShouldHaveItems(5);
}
[Test]
public void ShouldReturnExpectedBooks()
{
var expectedItems = _seriesBooks.OrderBy(a => a.Title).Take(10).ToArray();
for (int i = 0; i < _assert.Data.Count(); i++)
{
var actual = _assert.Data.ElementAt(i);
var expected = expectedItems[i];
actual.ShouldMatch(expected, DatabaseConnection, LibraryId)
.InLibrary(LibraryId)
.ShouldHaveCorrectLinks()
.ShouldHaveSeriesLink()
.ShouldHaveEditLinks()
.ShouldHaveImageUpdateLink()
.ShouldHaveCreateChaptersLink()
.ShouldHaveAddContentLink()
.ShouldHaveChaptersLink()
.ShouldHavePublicImageLink();
}
}
}
}
| 31.444444 | 126 | 0.569494 | [
"Apache-2.0"
] | inshapardaz/api | src/Inshapardaz.Api.Tests/Library/Book/GetBooksBySeries/WhenGettingBooksBySeriesWithWritePermission.cs | 3,396 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using BneDev.TimesheetNinja.Bot.Api;
using BneDev.TimesheetNinja.Bot.Api.Models;
namespace BneDev.TimesheetNinjaBot.Models
{
public class Project : IProject
{
public int SortOrder { get; set; }
public string Code { get; set; }
public string Description { get; set; }
}
} | 24.5625 | 47 | 0.70229 | [
"MIT"
] | kierenh/TimesheetNinjaBot | TimesheetNinjaBot/BneDev.TimesheetNinja.Bot/Models/Project.cs | 395 | C# |
/*
* Copyright © 2016 - 2017 EDDiscovery development team
*
* 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.
*
* EDDiscovery is not affiliated with Frontier Developments plc.
*/
using EDDiscovery.Forms;
using EliteDangerousCore;
using EliteDangerousCore.DB;
using EliteDangerousCore.JournalEvents;
using ExtendedControls;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using static System.Math;
namespace EDDiscovery.UserControls
{
public partial class UserControlCompass : UserControlCommonBase
{
string DbLatSave { get { return DBName("CompassLatTarget" ); } }
string DbLongSave { get { return DBName("CompassLongTarget" ); } }
string DbHideSave { get { return DBName("CompassAutoHide" ); } }
double? latitude = null;
double? longitude = null;
double? heading = null;
double? altitude = null;
double? bodyRadius = null;
bool autoHideTargetCoords = false;
HistoryEntry last_he;
BookmarkClass currentBookmark;
bool externallyForcedBookmark = false;
PlanetMarks.Location externalLocation;
string externalLocationName;
#region Init
public UserControlCompass()
{
InitializeComponent();
}
public override void Init()
{
discoveryform.OnNewEntry += OnNewEntry;
discoveryform.OnNewUIEvent += OnNewUIEvent;
discoveryform.OnHistoryChange += Discoveryform_OnHistoryChange;
numberBoxTargetLatitude.ValueNoChange = UserDatabase.Instance.GetSettingDouble(DbLatSave, 0);
numberBoxTargetLongitude.ValueNoChange = UserDatabase.Instance.GetSettingDouble(DbLongSave, 0);
autoHideTargetCoords = UserDatabase.Instance.GetSettingBool(DbHideSave, false);
checkBoxHideTransparent.Checked = autoHideTargetCoords;
comboBoxBookmarks.Text = "";
GlobalBookMarkList.Instance.OnBookmarkChange += GlobalBookMarkList_OnBookmarkChange;
compassControl.SlewRateDegreesSec = 40;
compassControl.AutoSetStencilTicks = true;
buttonNewBookmark.Enabled = false;
checkBoxHideTransparent.Visible = IsFloatingWindow;
BaseUtils.Translator.Instance.Translate(this);
BaseUtils.Translator.Instance.Translate(toolTip, this);
}
public override void Closing()
{
UserDatabase.Instance.PutSettingDouble(DbLatSave, numberBoxTargetLatitude.Value);
UserDatabase.Instance.PutSettingDouble(DbLongSave, numberBoxTargetLongitude.Value);
UserDatabase.Instance.PutSettingBool(DbHideSave, autoHideTargetCoords);
discoveryform.OnNewEntry -= OnNewEntry;
discoveryform.OnNewUIEvent -= OnNewUIEvent;
discoveryform.OnHistoryChange -= Discoveryform_OnHistoryChange;
GlobalBookMarkList.Instance.OnBookmarkChange -= GlobalBookMarkList_OnBookmarkChange;
}
public override Color ColorTransparency { get { return Color.Green; } }
public override void SetTransparency(bool on, Color curbackcol)
{
numberBoxTargetLatitude.BackColor = numberBoxTargetLongitude.BackColor = curbackcol;
numberBoxTargetLatitude.ControlBackground = numberBoxTargetLongitude.ControlBackground = curbackcol;
labelTargetLat.TextBackColor = curbackcol;
labelBookmark.TextBackColor = curbackcol;
flowLayoutPanelTop.BackColor = curbackcol;
flowLayoutPanelBookmarks.BackColor = curbackcol;
checkBoxHideTransparent.BackColor = curbackcol;
comboBoxBookmarks.DisableBackgroundDisabledShadingGradient = on;
comboBoxBookmarks.BackColor = curbackcol;
buttonNewBookmark.BackColor = curbackcol;
BackColor = curbackcol;
Color fore = on ? discoveryform.theme.SPanelColor : discoveryform.theme.LabelColor;
compassControl.ForeColor = fore;
compassControl.StencilColor = fore;
compassControl.CentreTickColor = fore.Multiply(1.2F);
compassControl.BugColor = fore.Multiply(0.8F);
compassControl.BackColor = on ? Color.Transparent : BackColor;
compassControl.Font = discoveryform.theme.GetScaledFont(0.8f);
if (autoHideTargetCoords)
{
flowLayoutPanelBookmarks.Visible = flowLayoutPanelTop.Visible = !on;
}
}
#endregion
#region Display
private void Discoveryform_OnHistoryChange(HistoryList obj) // need to handle this in case commander changed..
{
last_he = discoveryform.history.GetLast;
currentBookmark = null;
PopulateBookmarkCombo();
OnNewEntry(last_he, discoveryform.history);
}
public override void InitialDisplay() // on start up, this will have an empty history
{
last_he = discoveryform.history.GetLast;
PopulateBookmarkCombo();
DisplayCompass();
}
private void OnNewEntry(HistoryEntry he, HistoryList hl)
{
last_he = he;
if (last_he != null)
{
// hmm. not checking EDSM for scan data.. do we want to ? prob not.
JournalScan sd = discoveryform.history.GetScans(he.System.Name).Where(sc => sc.BodyName == he.WhereAmI).FirstOrDefault();
bodyRadius = sd?.nRadius;
switch (he.journalEntry.EventTypeID)
{
case JournalTypeEnum.Screenshot:
JournalScreenshot js = he.journalEntry as JournalScreenshot;
latitude = js.nLatitude;
longitude = js.nLongitude;
altitude = js.nAltitude;
break;
case JournalTypeEnum.Touchdown:
JournalTouchdown jt = he.journalEntry as JournalTouchdown;
if (jt.PlayerControlled.HasValue && jt.PlayerControlled.Value)
{
latitude = jt.Latitude;
longitude = jt.Longitude;
altitude = 0;
}
break;
case JournalTypeEnum.Location:
JournalLocation jl = he.journalEntry as JournalLocation;
latitude = jl.Latitude;
longitude = jl.Longitude;
altitude = null;
break;
case JournalTypeEnum.Liftoff:
JournalLiftoff jlo = he.journalEntry as JournalLiftoff;
if (jlo.PlayerControlled.HasValue && jlo.PlayerControlled.Value)
{
latitude = jlo.Latitude;
longitude = jlo.Longitude;
altitude = 0;
}
break;
case JournalTypeEnum.LeaveBody:
latitude = null;
longitude = null;
altitude = null;
break;
case JournalTypeEnum.FSDJump: // to allow us to do PopulateBookmark..
break;
default:
return;
}
PopulateBookmarkCombo();
DisplayCompass();
}
}
private void OnNewUIEvent(UIEvent uievent) // UI event in, see if we want to hide. UI events come before any onNew
{
EliteDangerousCore.UIEvents.UIPosition up = uievent as EliteDangerousCore.UIEvents.UIPosition;
if ( up != null )
{
if (up.Location.ValidPosition)
{
latitude = up.Location.Latitude;
longitude = up.Location.Longitude;
altitude = up.Location.Altitude;
heading = up.Heading;
}
else
latitude = longitude = heading = altitude = null;
}
DisplayCompass();
}
private void DisplayCompass()
{
double? targetlat = numberBoxTargetLatitude.Value;
double? targetlong = numberBoxTargetLongitude.Value;
double? targetDistance = CalculateDistance(targetlat, targetlong);
double? targetSlope = CalculateGlideslope(targetDistance);
if ( targetDistance.HasValue)
{
if (targetDistance.Value < 1000)
compassControl.DistanceFormat = "{0:0.#}m";
else if (targetDistance.Value < 1000000)
{
targetDistance = targetDistance.Value / 1000;
compassControl.DistanceFormat = "{0:0.#}km";
}
else
{
targetDistance = targetDistance.Value / 1000000;
compassControl.DistanceFormat = "{0:0.#}Mm";
}
}
if (targetSlope.HasValue)
{
compassControl.GlideSlope = targetSlope.Value;
}
else
{
compassControl.GlideSlope = double.NaN;
}
double? targetBearing = CalculateBearing(targetlat, targetlong);
try
{
compassControl.Set(heading.HasValue ? heading.Value : double.NaN,
targetBearing.HasValue ? targetBearing.Value : double.NaN,
targetDistance.HasValue ? targetDistance.Value : double.NaN, true);
}
catch { } // unlikely but Status.JSON could send duff values, trap out the exception on bad values
}
private double? CalculateBearing(double? targetLat, double? targetLong)
{
if (!(latitude.HasValue && longitude.HasValue && targetLat.HasValue && targetLong.HasValue))
return null;
// turn degrees to radians
double long1 = longitude.Value * PI / 180;
double lat1 = latitude.Value * PI / 180;
double long2 = targetLong.Value * PI / 180;
double lat2 = targetLat.Value * PI / 180;
double y = Sin(long2 - long1) * Cos(lat2);
double x = Cos(lat1) * Sin(lat2) -
Sin(lat1) * Cos(lat2) * Cos(long2 - long1);
// back to degrees again
double bearing = Atan2(y, x) / PI * 180;
//bearing in game HUD is 0-360, not -180 to 180
return bearing > 0 ? bearing : 360 + bearing;
}
private double? CalculateDistance(double? targetLat, double? targetLong)
{
if (!(latitude.HasValue && longitude.HasValue && targetLat.HasValue && targetLong.HasValue && bodyRadius.HasValue))
return null;
double lat1 = latitude.Value * PI / 180;
double lat2 = targetLat.Value * PI / 180;
double deltaLong = (targetLong.Value - longitude.Value) * PI / 180;
double deltaLat = (targetLat.Value - latitude.Value) * PI / 180;
double a = Sin(deltaLat / 2) * Sin(deltaLat / 2) + Cos(lat1) * Cos(lat2) * Sin(deltaLong / 2) * Sin(deltaLong / 2);
double c = 2 * Atan2(Sqrt(a), Sqrt(1 - a));
return bodyRadius.Value * c;
}
private double? CalculateGlideslope(double? distance)
{
if (!(distance.HasValue && altitude.HasValue && bodyRadius.HasValue))
return null;
if (altitude.Value < 10000 || distance.Value < 10000) // Don't return a slope if less than 10km out or below 10km
return null;
double theta = distance.Value / bodyRadius.Value;
double rad = 1 + altitude.Value / bodyRadius.Value;
double dist2 = 1 + rad * rad - 2 * rad * Cos(theta);
// a = radius, b = distance, c = altitude + radius
// c^2 = a^2 + b^2 - 2.a.b.cos(C) -> cos(C) = (a^2 + b^2 - c^2) / (2.a.b)
double sintgtslope = (1 + dist2 - rad * rad) / (2 * Sqrt(dist2));
if (sintgtslope > -0.2588) // Don't return a slope if it would be > -15deg at the target
return null;
// a = altitude + radius, b = distance, c = radius
double slope = -Asin((rad * rad + dist2 - 1) / (2 * rad * Sqrt(dist2))) * 180 / PI;
return slope;
}
private void PopulateBookmarkCombo()
{
if (last_he == null)
{
buttonNewBookmark.Enabled = false;
return;
}
buttonNewBookmark.Enabled = true;
if (currentBookmark != null && currentBookmark.StarName == last_he.System.Name)
{
return;
}
string selection = externallyForcedBookmark ? externalLocationName : comboBoxBookmarks.Text;
comboBoxBookmarks.Items.Clear();
currentBookmark = GlobalBookMarkList.Instance.FindBookmarkOnSystem(last_he.System.Name);
if (currentBookmark != null)
{
List<PlanetMarks.Planet> planetMarks = currentBookmark.PlanetaryMarks?.Planets;
if (heading.HasValue)
{
// orbital flight or landed, just do this body
labelBookmark.Text = "Planet Bookmarks";
planetMarks = planetMarks?.Where(p => p.Name == last_he.WhereAmI)?.ToList();
}
else
{
// add whole system
labelBookmark.Text = "System Bookmarks";
}
if (planetMarks != null)
{
foreach (PlanetMarks.Planet pl in planetMarks)
{
if (pl.Locations != null && pl.Locations.Any())
{
foreach (PlanetMarks.Location loc in pl.Locations.OrderBy(l => l.Name))
{
comboBoxBookmarks.Items.Add($"{loc.Name} ({pl.Name})");
}
}
}
}
}
if (externallyForcedBookmark && !comboBoxBookmarks.Items.Contains(externalLocationName))
{
comboBoxBookmarks.Items.Add(externalLocationName);
}
if (!String.IsNullOrEmpty(selection) && comboBoxBookmarks.Items.Contains(selection))
{
comboBoxBookmarks.Text = selection;
}
else
{
comboBoxBookmarks.Text = "";
}
}
#endregion
private void checkBoxHideTransparent_CheckedChanged(object sender, EventArgs e)
{
autoHideTargetCoords = ((ExtCheckBox)sender).Checked;
// SetTransparency(IsTransparent, BackColor);
}
private void comboBoxBookmarks_SelectedIndexChanged(object sender, EventArgs e)
{
if (currentBookmark == null || currentBookmark.PlanetaryMarks == null || currentBookmark.PlanetaryMarks.Planets == null) return;
foreach (PlanetMarks.Planet pl in currentBookmark.PlanetaryMarks.Planets)
{
if (pl.Locations != null && pl.Locations.Any())
{
foreach (PlanetMarks.Location loc in pl.Locations.OrderBy(l => l.Name))
{
if ($"{loc.Name} ({pl.Name})" == comboBoxBookmarks.Text)
{
numberBoxTargetLatitude.Value = loc.Latitude;
numberBoxTargetLongitude.Value = loc.Longitude;
if (externallyForcedBookmark && comboBoxBookmarks.Text != externalLocationName)
{
comboBoxBookmarks.Items.Remove(externalLocationName);
externallyForcedBookmark = false;
externalLocationName = "";
externalLocation = null;
}
DisplayCompass();
return;
}
}
}
}
}
private void buttonNewBookmark_Click(object sender, EventArgs e)
{
if (last_he == null)
return;
BookmarkForm frm = new BookmarkForm();
DateTime tme = DateTime.Now;
if (currentBookmark == null)
{
if (latitude.HasValue)
{
frm.NewSystemBookmark(last_he.System, "", tme, last_he.WhereAmI, latitude.Value, longitude.Value);
}
else
{
frm.NewSystemBookmark(last_he.System, "", tme);
}
}
else
{
if (latitude.HasValue)
{
frm.Update(currentBookmark, last_he.WhereAmI, latitude.Value, longitude.Value);
}
else
{
frm.Update(currentBookmark);
}
}
frm.StartPosition = FormStartPosition.CenterScreen;
DialogResult dr = frm.ShowDialog();
if (dr == DialogResult.OK)
{
currentBookmark = GlobalBookMarkList.Instance.AddOrUpdateBookmark(currentBookmark, true, frm.StarHeading, double.Parse(frm.x), double.Parse(frm.y), double.Parse(frm.z), tme, frm.Notes, frm.SurfaceLocations);
}
if (dr == DialogResult.Abort)
{
GlobalBookMarkList.Instance.Delete(currentBookmark);
currentBookmark = null;
}
PopulateBookmarkCombo();
DisplayCompass();
}
private void GlobalBookMarkList_OnBookmarkChange(BookmarkClass bk, bool deleted)
{
if (currentBookmark != null && currentBookmark.id == bk.id)
currentBookmark = null;
PopulateBookmarkCombo();
DisplayCompass();
}
public void SetSurfaceBookmark(BookmarkClass bk, string planetName, string locName)
{
externallyForcedBookmark = true;
externalLocation = bk.PlanetaryMarks.Planets.Where(pl => pl.Name == planetName).FirstOrDefault()?.Locations.Where(l => l.Name == locName).FirstOrDefault();
if (externalLocation != null)
{
externalLocationName = $"{locName} ({planetName})";
numberBoxTargetLatitude.Value = externalLocation.Latitude;
numberBoxTargetLongitude.Value = externalLocation.Longitude;
}
PopulateBookmarkCombo();
DisplayCompass();
}
private void numberBoxTargetLatitude_ValueChanged(object sender, EventArgs e)
{
DisplayCompass();
}
private void numberBoxTargetLongitude_ValueChanged(object sender, EventArgs e)
{
DisplayCompass();
}
}
}
| 41.342685 | 224 | 0.53364 | [
"Apache-2.0"
] | phwoelfel/EDDiscovery | EDDiscovery/UserControls/Overlays/UserControlCompass.cs | 20,135 | C# |
using MeetingWebsite.Controllers;
using MeetingWebsite.Models;
using MeetingWebsite.ModelsView.Messages;
using MeetingWebsite.Repositories;
using Microsoft.AspNetCore.Mvc;
using MockQueryable.Moq;
using Moq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace MeetingWebsite.Tests.Controllers
{
public class MessagesControllerTests
{
Mock<DBContext> dbContext;
//Repos
Mock<DialogsRepository> dialogsRepositoryMock;
Mock<UsersRepository> usersRepositoryMock;
Mock<MessagesRepository> messagesRepositoryMock;
//DialogsApiController
MessagesController messagesController;
public MessagesControllerTests()
{
dbContext = new Mock<DBContext>();
//Dialogs
dialogsRepositoryMock = new Mock<DialogsRepository>(dbContext.Object);
var dialogs = new List<Dialog>()
{
new Dialog()
{
Id = 1,
DialogsUsers = new List<DialogsUsers>()
{
new DialogsUsers()
{
DialogId = 1,
UserId = -1
}
}
}
};
dialogsRepositoryMock.Setup(repo => repo.GetList()).Returns(dialogs.AsQueryable().BuildMock().Object);
dialogsRepositoryMock.Setup(repo => repo.Add(It.IsAny<Dialog>())).Returns(Task.FromResult(true));
dialogsRepositoryMock.Setup(repo => repo.Update(It.IsAny<Dialog>())).Returns(Task.FromResult(true));
dialogsRepositoryMock.Setup(repo => repo.Remove(It.IsAny<Dialog>())).Returns(Task.FromResult(true));
dialogsRepositoryMock.Setup(repo => repo.Any(p => p.Id == 1)).Returns(Task.FromResult(true));
//Users
usersRepositoryMock = new Mock<UsersRepository>(dbContext.Object);
var users = new List<User>() {
new User() { Id = -1 },
new User() { Id = 1 },
new User() { Id = 2 },
new User() { Id = 3 },
};
usersRepositoryMock.Setup(repo => repo.GetList()).Returns(users.AsQueryable().BuildMock().Object);
//Messages
messagesRepositoryMock = new Mock<MessagesRepository>(dbContext.Object);
messagesRepositoryMock.Setup(repo => repo.Add(It.IsAny<Message>())).Returns(Task.FromResult(true));
messagesRepositoryMock.Setup(repo => repo.Update(It.IsAny<Message>())).Returns(Task.FromResult(true));
messagesRepositoryMock.Setup(repo => repo.Remove(It.IsAny<Message>())).Returns(Task.FromResult(true));
//Controller
messagesController = new MessagesController(usersRepositoryMock.Object, messagesRepositoryMock.Object, dialogsRepositoryMock.Object);
}
/// <summary>
/// Получение списка сообщений диалога
/// </summary>
[Fact]
public void GetListMessages()
{
// Arrange
// Act
var result = messagesController.GetList(1).Result;
// Assert
Assert.IsType<OkObjectResult>(result);
var okResult = result as OkObjectResult;
Assert.IsType<List<MessageView>>(okResult.Value);
Assert.Empty((okResult.Value as List<MessageView>));
}
/// <summary>
/// Создание сообщения
/// </summary>
/// <param name="usersId">Идентификаторы пользователей</param>
/// <param name="statusCode">Возвращаемый результат</param>
[Theory]
[InlineData(1, 200)]
[InlineData(1000, 404)]
public void CreateMessage(int dialogId, int statusCode)
{
// Arrange
// Act
var result = messagesController.Create(dialogId, "Message body").Result as ObjectResult;
// Assert
Assert.Equal(statusCode, result.StatusCode);
if (statusCode == 200)
Assert.IsType<int>(result.Value);
else
{
Assert.IsType<string>(result.Value);
Assert.NotEmpty(result.Value as string);
}
}
/// <summary>
/// Изменение сообщения
/// </summary>
[Theory]
[InlineData(1, 200, -1)]
[InlineData(2, 404, -1)]
[InlineData(1, 401, 1)]
public void ChangeMessage(int messageId, int statusCode, int messageUserId)
{
// Arrange
messagesRepositoryMock.Setup(r => r.Find(1)).Returns(Task.FromResult(new Message() { Id = 1, Text = "Old text", UserId = messageUserId, DateCreate = DateTime.Now }));
// Act
var result = messagesController.Update(0, messageId, "new body message").Result;
// Assert
if (statusCode == 200)
Assert.IsType<OkResult>(result);
else
{
Assert.NotNull(result);
Assert.Equal(statusCode, (result as ObjectResult).StatusCode);
}
}
/// <summary>
/// Удаление сообщения
/// </summary>
[Theory]
[InlineData(1, 401, 1)]
[InlineData(1, 200, -1)]
[InlineData(2, 200, -1)]
public void DeleteMessage(int messageId, int statusCode, int messageUserId)
{
// Arrange
messagesRepositoryMock.Setup(r => r.Find(1)).Returns(Task.FromResult(new Message() { Id = 1, Text = "Old text", UserId = messageUserId, DateCreate = DateTime.Now }));
// Act
var result = messagesController.Delete(1, 1).Result;
// Assert
if (statusCode == 200)
Assert.IsType<OkResult>(result);
else
{
Assert.NotNull(result);
Assert.Equal(statusCode, (result as ObjectResult).StatusCode);
}
}
}
}
| 35.789474 | 178 | 0.556863 | [
"MIT"
] | kirill20123456/MeetingWebsite | MeetingWebsite/MeetingWebsite/MeetingWebsite.Tests/Controllers/MessagesControllerTests.cs | 6,253 | C# |
// <auto-generated />
using System;
using E_Store.DataAccess;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace E_Store.DataAccess.Migrations
{
[DbContext(typeof(EStoreDbContext))]
[Migration("20210831134741_Init")]
partial class Init
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("ProductVersion", "5.0.9")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("E_Store.Domain.Models.Order", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<bool>("Delivered")
.HasColumnType("bit");
b.Property<int>("PaymentMethod")
.HasColumnType("int");
b.Property<double>("Price")
.HasColumnType("float");
b.Property<int?>("ProductId")
.HasColumnType("int");
b.Property<int>("UserId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ProductId");
b.HasIndex("UserId");
b.ToTable("Orders");
b.HasData(
new
{
Id = 1,
Delivered = false,
PaymentMethod = 1,
Price = 100.0,
UserId = 1
},
new
{
Id = 2,
Delivered = true,
PaymentMethod = 1,
Price = 150.0,
UserId = 2
},
new
{
Id = 3,
Delivered = false,
PaymentMethod = 2,
Price = 200.0,
UserId = 3
});
});
modelBuilder.Entity("E_Store.Domain.Models.Product", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<int>("Category")
.HasColumnType("int");
b.Property<string>("Description")
.HasColumnType("nvarchar(max)");
b.Property<string>("Image")
.HasColumnType("nvarchar(max)");
b.Property<string>("Name")
.HasColumnType("nvarchar(max)");
b.Property<double>("Price")
.HasColumnType("float");
b.Property<bool>("Promotion")
.HasColumnType("bit");
b.Property<string>("Review")
.HasColumnType("nvarchar(max)");
b.Property<int>("TypeOfPromotion")
.HasColumnType("int");
b.HasKey("Id");
b.ToTable("Products");
b.HasData(
new
{
Id = 1,
Category = 1,
Description = "New Phone",
Image = "1.jpeg",
Name = "Samsung Galaxy M32",
Price = 200.0,
Promotion = false,
Review = "4 stars",
TypeOfPromotion = 3
},
new
{
Id = 2,
Category = 2,
Description = "New Laptop",
Image = "2.jpeg",
Name = "Lenovo G500S",
Price = 250.0,
Promotion = true,
Review = "4 stars",
TypeOfPromotion = 1
},
new
{
Id = 3,
Category = 4,
Description = "New Headphones",
Image = "3.jpeg",
Name = "JBL 100",
Price = 100.0,
Promotion = true,
Review = "4 stars",
TypeOfPromotion = 2
},
new
{
Id = 4,
Category = 5,
Description = "New Monitor",
Image = "4.jpeg",
Name = "LG M6700",
Price = 200.0,
Promotion = false,
Review = "2 stars",
TypeOfPromotion = 3
},
new
{
Id = 5,
Category = 3,
Description = "New PC",
Image = "5.jpeg",
Name = "PC 123",
Price = 500.0,
Promotion = true,
Review = "5 stars",
TypeOfPromotion = 1
});
});
modelBuilder.Entity("E_Store.Domain.Models.ProductOrder", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<int>("OrderId")
.HasColumnType("int");
b.Property<int>("ProductId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("OrderId");
b.HasIndex("ProductId");
b.ToTable("ProductOrder");
});
modelBuilder.Entity("E_Store.Domain.Models.User", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("AccountName")
.HasColumnType("nvarchar(max)");
b.Property<string>("Address")
.HasColumnType("nvarchar(max)");
b.Property<string>("Email")
.HasColumnType("nvarchar(max)");
b.Property<string>("FirstName")
.HasColumnType("nvarchar(max)");
b.Property<string>("LastName")
.HasColumnType("nvarchar(max)");
b.Property<long>("PhoneNumber")
.HasColumnType("bigint");
b.HasKey("Id");
b.ToTable("Users");
b.HasData(
new
{
Id = 1,
AccountName = "JoeB",
Address = "Street 1",
Email = "joeb@gmail.com",
FirstName = "Joe",
LastName = "Black",
PhoneNumber = 123456L
},
new
{
Id = 2,
AccountName = "MarryW",
Address = "Street 2",
Email = "marryw@gmail.com",
FirstName = "Mary",
LastName = "White",
PhoneNumber = 654321L
},
new
{
Id = 3,
AccountName = "RayB",
Address = "Street 3",
Email = "rayb@gmail.com",
FirstName = "Ray",
LastName = "Brown",
PhoneNumber = 321456L
});
});
modelBuilder.Entity("E_Store.Domain.Models.Order", b =>
{
b.HasOne("E_Store.Domain.Models.Product", "Product")
.WithMany()
.HasForeignKey("ProductId");
b.HasOne("E_Store.Domain.Models.User", "User")
.WithMany("Orders")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Product");
b.Navigation("User");
});
modelBuilder.Entity("E_Store.Domain.Models.ProductOrder", b =>
{
b.HasOne("E_Store.Domain.Models.Order", "Order")
.WithMany("ProductOrders")
.HasForeignKey("OrderId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("E_Store.Domain.Models.Product", "Product")
.WithMany("ProductOrders")
.HasForeignKey("ProductId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Order");
b.Navigation("Product");
});
modelBuilder.Entity("E_Store.Domain.Models.Order", b =>
{
b.Navigation("ProductOrders");
});
modelBuilder.Entity("E_Store.Domain.Models.Product", b =>
{
b.Navigation("ProductOrders");
});
modelBuilder.Entity("E_Store.Domain.Models.User", b =>
{
b.Navigation("Orders");
});
#pragma warning restore 612, 618
}
}
}
| 36.507886 | 125 | 0.364728 | [
"MIT"
] | martinst93/ASP.NET-MVC | E-StoreSolution/E-Store.DataAccess/Migrations/20210831134741_Init.Designer.cs | 11,575 | C# |
#if BRIDGE
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace System.Data
{
public class DataColumnCollection
{
public DataTable Table {get;}
internal List<DataColumn> Columns;
public int GetColumnIndex(string name)
{
for (int i = 0; i < Columns.Count; i++)
{
if (Columns[i].Name == name)
return i;
}
return -1;
}
public int Count => Columns.Count;
internal DataColumnCollection(DataTable table)
{
Table = table;
Columns = new List<DataColumn>();
}
public DataColumn Add(string columnName, Type type)
{
var data = new DataColumn(Table, columnName);
Columns.Add(data);
return data;
}
public DataColumn Add(string columnName)
{
var data = new DataColumn(Table, columnName);
Columns.Add(data);
return data;
}
}
}
#endif | 20.178571 | 59 | 0.526549 | [
"Apache-2.0"
] | samuelGrahame/ExpressCraft | ExpressCraft.Forms/Data/DataColumnCollection.cs | 1,132 | C# |
// <copyright file="EmailStore.cs" company="Microsoft Corporation">
// Copyright (c) Microsoft Corporation.// Licensed under the MIT license.
// </copyright>
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Core.EntityClient;
using System.Data.SqlClient;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Azure.EngagementFabric.Common.Collection;
using Microsoft.Azure.EngagementFabric.Common.Pagination;
using Microsoft.Azure.EngagementFabric.DispatcherInterface.Contract;
using Microsoft.Azure.EngagementFabric.Email.Common.Contract;
using Microsoft.Azure.EngagementFabric.EmailProvider.Credential;
using Microsoft.Azure.EngagementFabric.EmailProvider.EntityFramework;
using Microsoft.Azure.EngagementFabric.EmailProvider.Model;
using Newtonsoft.Json;
using Group = Microsoft.Azure.EngagementFabric.EmailProvider.Model.Group;
namespace Microsoft.Azure.EngagementFabric.EmailProvider.Store
{
public class EmailStore : IEmailStore
{
private readonly string connectionString;
public EmailStore(string connectionString)
{
var connectionStringBuilder = new SqlConnectionStringBuilder(connectionString);
var entityStringBuilder = new EntityConnectionStringBuilder
{
Provider = "System.Data.SqlClient",
Metadata = "res://*/EntityFramework.EmailServiceDataModel.csdl|res://*/EntityFramework.EmailServiceDataModel.ssdl|res://*/EntityFramework.EmailServiceDataModel.msl",
ProviderConnectionString = connectionStringBuilder.ToString()
};
this.connectionString = entityStringBuilder.ConnectionString;
}
#region Connector Metadata
public async Task<ConnectorMetadata> GetConnectorMetadataAsync(string connectorName)
{
using (var ctx = new EmailServiceDbEntities(this.connectionString))
{
var entity = await ctx.ConnectorMetadata.SingleOrDefaultAsync(c => c.Provider == connectorName);
return entity?.ToModel();
}
}
#endregion
#region Connector Credential
public async Task CreateOrUpdateCredentialAsync(EmailConnectorCredential credential)
{
using (var ctx = new EmailServiceDbEntities(this.connectionString))
{
var entity = await ctx.ConnectorCredentials.SingleOrDefaultAsync(
c => c.Provider == credential.ConnectorName &&
c.Id == credential.ConnectorId);
if (entity == null)
{
entity = new ConnectorCredentialEntity();
entity.Provider = credential.ConnectorName;
entity.Id = credential.ConnectorId;
entity.Data = JsonConvert.SerializeObject(credential);
entity.Created = entity.Modified = DateTime.UtcNow;
entity.Enabled = true;
ctx.ConnectorCredentials.Add(entity);
}
else
{
entity.Data = JsonConvert.SerializeObject(credential);
entity.Modified = DateTime.UtcNow;
entity.Enabled = true;
}
await ctx.SaveChangesAsync();
}
}
public async Task<EmailConnectorCredential> GetConnectorCredentialByIdAsync(ConnectorIdentifier identifier)
{
using (var ctx = new EmailServiceDbEntities(this.connectionString))
{
var entity = await ctx.ConnectorCredentials.SingleOrDefaultAsync(
c => c.Provider == identifier.ConnectorName &&
c.Id == identifier.ConnectorId);
return entity != null && entity.Enabled ? JsonConvert.DeserializeObject<EmailConnectorCredential>(entity.Data) : null;
}
}
public async Task DeleteConnectorCredentialAsync(ConnectorIdentifier identifier)
{
using (var ctx = new EmailServiceDbEntities(this.connectionString))
{
var entity = await ctx.ConnectorCredentials.SingleOrDefaultAsync(
c => c.Provider == identifier.ConnectorName &&
c.Id == identifier.ConnectorId);
if (entity != null)
{
ctx.ConnectorCredentials.Remove(entity);
await ctx.SaveChangesAsync();
}
}
}
#endregion
#region Connector Credential Assignment
public async Task CreateOrUpdateCredentialAssignmentAsync(CredentialAssignment credentialAssignment)
{
using (var ctx = new EmailServiceDbEntities(this.connectionString))
{
var entities = await ctx.ConnectorCredentialAssignments.Where(
c => c.EngagementAccount == credentialAssignment.EngagementAccount).ToListAsync();
var entity = entities?.SingleOrDefault(
e => e.Provider == credentialAssignment.Provider &&
e.Id == credentialAssignment.ConnectorId);
if (entity != null)
{
entity.Enabled = credentialAssignment.Enabled;
entity.Active = credentialAssignment.Active;
entity.Modified = DateTime.UtcNow;
}
else
{
entity = new ConnectorCredentialAssignmentEntity();
entity.EngagementAccount = credentialAssignment.EngagementAccount;
entity.Provider = credentialAssignment.Provider;
entity.Id = credentialAssignment.ConnectorId;
entity.Enabled = credentialAssignment.Enabled;
entity.Active = credentialAssignment.Active;
entity.Created = entity.Modified = DateTime.UtcNow;
ctx.ConnectorCredentialAssignments.Add(entity);
}
// Make sure at most 1 active credential
if (credentialAssignment.Active)
{
foreach (var entry in entities.Where(e => e != entity))
{
entry.Active = false;
}
}
await ctx.SaveChangesAsync();
}
}
public async Task DeleteCredentialAssignmentsAsync(string engagementAccount, ConnectorIdentifier identifier)
{
using (var ctx = new EmailServiceDbEntities(this.connectionString))
{
var entities = await ctx.ConnectorCredentialAssignments.Where(c => c.EngagementAccount == engagementAccount).ToListAsync();
entities = entities.Where(e => identifier == null || (e.Provider.Equals(identifier.ConnectorName, StringComparison.OrdinalIgnoreCase) && e.Id.Equals(identifier.ConnectorId, StringComparison.OrdinalIgnoreCase))).ToList();
if (entities != null)
{
ctx.ConnectorCredentialAssignments.RemoveRange(entities);
await ctx.SaveChangesAsync();
}
}
}
public async Task<List<CredentialAssignment>> ListCredentialAssignmentsByAccountAsync(string engagementAccount, bool activeOnly)
{
using (var ctx = new EmailServiceDbEntities(this.connectionString))
{
var entities = await ctx.ConnectorCredentialAssignments.Where(
c => c.EngagementAccount == engagementAccount &&
(!activeOnly || c.Active)).ToListAsync();
return entities?.Select(e => e.ToModel()).ToList();
}
}
public async Task<List<CredentialAssignment>> ListCredentialAssignmentsById(ConnectorIdentifier identifier, bool activeOnly = true)
{
using (var ctx = new EmailServiceDbEntities(this.connectionString))
{
var entities = await ctx.ConnectorCredentialAssignments.Where(
c => c.Provider == identifier.ConnectorName &&
c.Id == identifier.ConnectorId &&
(!activeOnly || c.Active)).ToListAsync();
return entities?.Select(e => e.ToModel()).ToList();
}
}
#endregion
#region Account
public async Task<Account> CreateOrUpdateAccountAsync(Account account)
{
using (var ctx = new EmailServiceDbEntities(this.connectionString))
{
var entity = await ctx.EngagementAccounts.SingleOrDefaultAsync(a => a.EngagementAccount == account.EngagementAccount);
if (entity == null)
{
entity = new EngagementAccountEntity();
entity.EngagementAccount = account.EngagementAccount;
entity.Properties = JsonConvert.SerializeObject(account.Properties);
entity.Created = entity.Modified = DateTime.UtcNow;
entity.SubscriptionId = account.SubscriptionId;
ctx.EngagementAccounts.Add(entity);
}
else
{
entity.Properties = JsonConvert.SerializeObject(account.Properties);
entity.SubscriptionId = account.SubscriptionId;
entity.Modified = DateTime.UtcNow;
}
await ctx.SaveChangesAsync();
return entity.ToModel();
}
}
public async Task<Account> GetAccountAsync(string engagementAccount)
{
using (var ctx = new EmailServiceDbEntities(this.connectionString))
{
var entity = await ctx.EngagementAccounts.SingleOrDefaultAsync(a => a.EngagementAccount == engagementAccount);
return entity?.ToModel();
}
}
public async Task DeleteAccountAsync(string engagementAccount)
{
using (var ctx = new EmailServiceDbEntities(this.connectionString))
{
var entity = await ctx.EngagementAccounts.SingleOrDefaultAsync(a => a.EngagementAccount == engagementAccount);
if (entity != null)
{
ctx.EngagementAccounts.Remove(entity);
await ctx.SaveChangesAsync();
}
}
}
#endregion
#region Domain
public async Task<Domain> CreateOrUpdateDomainAsync(Domain domain)
{
using (var ctx = new EmailServiceDbEntities(this.connectionString))
{
var entity = await ctx.Domains.SingleOrDefaultAsync(
s => s.EngagementAccount == domain.EngagementAccount &&
s.Domain == domain.Value);
if (entity == null)
{
entity = new DomainEntity();
entity.Domain = domain.Value;
entity.EngagementAccount = domain.EngagementAccount;
entity.State = domain.State.ToString();
entity.Message = domain.Message;
entity.Created = entity.Modified = DateTime.UtcNow;
ctx.Domains.Add(entity);
}
else
{
entity.State = domain.State.ToString();
entity.Message = domain.Message;
entity.Modified = DateTime.UtcNow;
}
await ctx.SaveChangesAsync();
return entity.ToModel();
}
}
public async Task<List<Domain>> GetDomainsByNameAsync(string domain)
{
using (var ctx = new EmailServiceDbEntities(this.connectionString))
{
var entities = await ctx.Domains.Where(s => s.Domain == domain).ToListAsync();
return entities?.Select(e => e.ToModel()).ToList();
}
}
public async Task<Domain> GetDomainAsync(string engagementAccount, string domain)
{
using (var ctx = new EmailServiceDbEntities(this.connectionString))
{
var entity = await ctx.Domains.SingleOrDefaultAsync(
s => s.EngagementAccount == engagementAccount &&
s.Domain == domain);
return entity?.ToModel();
}
}
public async Task<DomainList> ListDomainsByAccountAsync(string engagementAccount, DbContinuationToken continuationToken, int count)
{
using (var ctx = new EmailServiceDbEntities(this.connectionString))
{
var result = new DomainList();
var domains = ctx.Domains.Where(s => s.EngagementAccount == engagementAccount).OrderBy(s => s.Created);
result.Total = domains.Count();
if (result.Total <= 0)
{
return result;
}
var taken = count >= 0 ?
await domains.Skip(continuationToken.Skip).Take(count).ToListAsync() :
await domains.Skip(continuationToken.Skip).ToListAsync();
result.Domains = new List<Domain>();
foreach (var entity in taken)
{
result.Domains.Add(entity.ToModel());
}
if (result.Total > continuationToken.Skip + count)
{
result.NextLink = new DbContinuationToken(continuationToken.DatabaseId, continuationToken.Skip + count);
}
return result;
}
}
public async Task DeleteDomainAsync(string engagementAccount, string domain)
{
using (var ctx = new EmailServiceDbEntities(this.connectionString))
{
var entity = await ctx.Domains.SingleOrDefaultAsync(
s => s.EngagementAccount == engagementAccount &&
s.Domain == domain);
if (entity != null)
{
ctx.Domains.Remove(entity);
await ctx.SaveChangesAsync();
}
}
}
public async Task DeleteDomainsAsync(string engagementAccount)
{
using (var ctx = new EmailServiceDbEntities(this.connectionString))
{
var entities = await ctx.Domains.Where(s => s.EngagementAccount == engagementAccount).ToListAsync();
if (entities != null && entities.Count > 0)
{
ctx.Domains.RemoveRange(entities);
await ctx.SaveChangesAsync();
}
}
}
#endregion
#region Group
public async Task<Group> CreateOrUpdateGroupAsync(Group group)
{
using (var ctx = new EmailServiceDbEntities(this.connectionString))
{
var entity = await ctx.Groups.SingleOrDefaultAsync(
s => s.EngagementAccount == group.EngagementAccount &&
s.Name == group.Name);
if (entity == null)
{
entity = new GroupEntity();
entity.Name = group.Name;
entity.EngagementAccount = group.EngagementAccount;
entity.Description = group.Description;
entity.Properties = JsonConvert.SerializeObject(group.Properties);
entity.Created = entity.Modified = DateTime.UtcNow;
ctx.Groups.Add(entity);
}
else
{
entity.Description = group.Description;
entity.Properties = JsonConvert.SerializeObject(group.Properties);
entity.Modified = DateTime.UtcNow;
}
await ctx.SaveChangesAsync();
return entity.ToModel();
}
}
public async Task<Group> GetGroupAsync(string engagementAccount, string group)
{
using (var ctx = new EmailServiceDbEntities(this.connectionString))
{
var entity = await ctx.Groups.SingleOrDefaultAsync(
s => s.EngagementAccount == engagementAccount &&
s.Name == group);
return entity?.ToModel();
}
}
public async Task<GroupList> ListGroupsAsync(string engagementAccount, DbContinuationToken continuationToken, int count)
{
using (var ctx = new EmailServiceDbEntities(this.connectionString))
{
var result = new GroupList();
var groups = ctx.Groups.Where(s => s.EngagementAccount == engagementAccount).OrderBy(s => s.Created);
result.Total = groups.Count();
if (result.Total <= 0)
{
return result;
}
var taken = count >= 0 ?
await groups.Skip(continuationToken.Skip).Take(count).ToListAsync() :
await groups.Skip(continuationToken.Skip).ToListAsync();
result.Groups = new List<Group>();
foreach (var entity in taken)
{
result.Groups.Add(entity.ToModel());
}
if (result.Total > continuationToken.Skip + count)
{
result.NextLink = new DbContinuationToken(continuationToken.DatabaseId, continuationToken.Skip + count);
}
return result;
}
}
public async Task DeleteGroupAsync(string engagementAccount, string group)
{
using (var ctx = new EmailServiceDbEntities(this.connectionString))
{
var entity = await ctx.Groups.SingleOrDefaultAsync(
s => s.EngagementAccount == engagementAccount &&
s.Name == group);
if (entity != null)
{
ctx.Groups.Remove(entity);
await ctx.SaveChangesAsync();
}
}
}
public async Task DeleteGroupsAsync(string engagementAccount)
{
using (var ctx = new EmailServiceDbEntities(this.connectionString))
{
var entities = await ctx.Groups.Where(s => s.EngagementAccount == engagementAccount).ToListAsync();
if (entities != null && entities.Count > 0)
{
ctx.Groups.RemoveRange(entities);
await ctx.SaveChangesAsync();
}
}
}
#endregion
#region Sender
public async Task<Sender> CreateOrUpdateSenderAsync(Sender sender)
{
using (var ctx = new EmailServiceDbEntities(this.connectionString))
{
var entity = sender.SenderAddrID != null ? await ctx.SenderAddresses.SingleOrDefaultAsync(
s => s.EngagementAccount == sender.EngagementAccount &&
s.Id == new Guid(sender.SenderAddrID)) : null;
if (entity == null)
{
entity = new SenderAddressEntity();
entity.Id = Guid.NewGuid();
entity.Name = sender.SenderEmailAddress.Address;
entity.Domain = sender.SenderEmailAddress.Host;
entity.EngagementAccount = sender.EngagementAccount;
entity.ForwardAddress = sender.ForwardEmailAddress.Address;
entity.Properties = JsonConvert.SerializeObject(sender.Properties);
entity.Created = entity.Modified = DateTime.UtcNow;
ctx.SenderAddresses.Add(entity);
}
else
{
entity.Name = sender.SenderEmailAddress.Address;
entity.Domain = sender.SenderEmailAddress.Host;
entity.ForwardAddress = sender.ForwardEmailAddress.Address;
entity.Properties = JsonConvert.SerializeObject(sender.Properties);
entity.Modified = DateTime.UtcNow;
}
await ctx.SaveChangesAsync();
return entity.ToModel();
}
}
public async Task<Sender> GetSenderByIdAsync(string engagementAccount, Guid senderId)
{
using (var ctx = new EmailServiceDbEntities(this.connectionString))
{
var entity = await ctx.SenderAddresses.SingleOrDefaultAsync(
s => s.EngagementAccount == engagementAccount &&
s.Id == senderId);
return entity?.ToModel();
}
}
public async Task<Sender> GetSenderByNameAsync(string engagementAccount, string senderAddr)
{
using (var ctx = new EmailServiceDbEntities(this.connectionString))
{
var entity = await ctx.SenderAddresses.SingleOrDefaultAsync(
s => s.EngagementAccount == engagementAccount &&
s.Name == senderAddr);
return entity?.ToModel();
}
}
public async Task<SenderList> ListSendersAsync(string engagementAccount, DbContinuationToken continuationToken, int count)
{
using (var ctx = new EmailServiceDbEntities(this.connectionString))
{
var result = new SenderList();
var senders = ctx.SenderAddresses.Where(s => s.EngagementAccount == engagementAccount).OrderBy(s => s.Created);
result.Total = senders.Count();
if (result.Total <= 0)
{
return result;
}
var taken = count >= 0 ?
await senders.Skip(continuationToken.Skip).Take(count).ToListAsync() :
await senders.Skip(continuationToken.Skip).ToListAsync();
result.SenderAddresses = new List<Sender>();
foreach (var entity in taken)
{
result.SenderAddresses.Add(entity.ToModel());
}
if (result.Total > continuationToken.Skip + count)
{
result.NextLink = new DbContinuationToken(continuationToken.DatabaseId, continuationToken.Skip + count);
}
return result;
}
}
public async Task DeleteSenderAsync(string engagementAccount, Guid senderId)
{
using (var ctx = new EmailServiceDbEntities(this.connectionString))
{
var entity = await ctx.SenderAddresses.SingleOrDefaultAsync(
s => s.EngagementAccount == engagementAccount &&
s.Id == senderId);
if (entity != null)
{
ctx.SenderAddresses.Remove(entity);
await ctx.SaveChangesAsync();
}
}
}
public async Task DeleteSendersAsync(string engagementAccount)
{
using (var ctx = new EmailServiceDbEntities(this.connectionString))
{
var entities = await ctx.SenderAddresses.Where(s => s.EngagementAccount == engagementAccount).ToListAsync();
if (entities != null && entities.Count > 0)
{
ctx.SenderAddresses.RemoveRange(entities);
await ctx.SaveChangesAsync();
}
}
}
public async Task<List<Sender>> GetSendersByDomainAsync(string engagementAccount, string domain)
{
using (var ctx = new EmailServiceDbEntities(this.connectionString))
{
var entities = await ctx.SenderAddresses.Where(
s => s.EngagementAccount == engagementAccount &&
s.Domain == domain).ToListAsync();
return entities?.Select(e => e.ToModel()).ToList();
}
}
public async Task DeleteSendersByDomainAsync(string engagementAccount, string domain)
{
using (var ctx = new EmailServiceDbEntities(this.connectionString))
{
var entities = await ctx.SenderAddresses.Where(
s => s.EngagementAccount == engagementAccount &&
s.Domain == domain).ToListAsync();
if (entities != null && entities.Count > 0)
{
ctx.SenderAddresses.RemoveRange(entities);
await ctx.SaveChangesAsync();
}
}
}
#endregion
#region Template
public async Task<Template> CreateOrUpdateTemplateAsync(Template template, Sender sender)
{
using (var ctx = new EmailServiceDbEntities(this.connectionString))
{
var entity = await ctx.Templates.SingleOrDefaultAsync(
t => t.EngagementAccount == template.EngagementAccount &&
t.Name == template.Name);
if (entity == null)
{
entity = new TemplateEntity();
entity.Name = template.Name;
entity.EngagementAccount = template.EngagementAccount;
entity.Domain = sender.Domain;
entity.SenderAddressId = template.SenderId;
entity.SenderAlias = template.SenderAlias;
entity.ReplyAddress = string.Empty;
entity.Subject = template.Subject;
entity.MessageBody = template.HtmlMsg;
entity.EnableUnSubscribe = template.EnableUnSubscribe;
entity.State = template.State.ToString();
entity.StateMessage = template.StateMessage;
entity.Created = entity.Modified = DateTime.UtcNow;
ctx.Templates.Add(entity);
}
else
{
entity.Domain = sender.Domain;
entity.SenderAddressId = template.SenderId;
entity.SenderAlias = template.SenderAlias;
entity.ReplyAddress = string.Empty;
entity.Subject = template.Subject;
entity.MessageBody = template.HtmlMsg;
entity.EnableUnSubscribe = template.EnableUnSubscribe;
entity.State = template.State.ToString();
entity.StateMessage = template.StateMessage;
entity.Modified = DateTime.UtcNow;
}
await ctx.SaveChangesAsync();
return entity.ToModel();
}
}
public async Task<Template> GetTemplateAsync(string engagementAccount, string template)
{
using (var ctx = new EmailServiceDbEntities(this.connectionString))
{
var entity = await ctx.Templates.SingleOrDefaultAsync(
t => t.EngagementAccount == engagementAccount &&
t.Name == template);
return entity?.ToModel();
}
}
public async Task<TemplateList> ListTemplatesAsync(string engagementAccount, DbContinuationToken continuationToken, int count)
{
using (var ctx = new EmailServiceDbEntities(this.connectionString))
{
var result = new TemplateList();
var templates = ctx.Templates.Where(t => t.EngagementAccount == engagementAccount).OrderBy(t => t.Created);
result.Total = templates.Count();
if (result.Total <= 0)
{
return result;
}
var taken = count >= 0 ?
await templates.Skip(continuationToken.Skip).Take(count).ToListAsync() :
await templates.Skip(continuationToken.Skip).ToListAsync();
result.Templates = new List<Template>();
foreach (var entity in taken)
{
result.Templates.Add(entity.ToModel());
}
if (result.Total > continuationToken.Skip + count)
{
result.NextLink = new DbContinuationToken(continuationToken.DatabaseId, continuationToken.Skip + count);
}
return result;
}
}
public async Task DeleteTemplateAsync(string engagementAccount, string template)
{
using (var ctx = new EmailServiceDbEntities(this.connectionString))
{
var entity = await ctx.Templates.SingleOrDefaultAsync(
t => t.EngagementAccount == engagementAccount &&
t.Name == template);
if (entity != null)
{
ctx.Templates.Remove(entity);
await ctx.SaveChangesAsync();
}
}
}
public async Task DeleteTemplatesAsync(string engagementAccount)
{
using (var ctx = new EmailServiceDbEntities(this.connectionString))
{
var entities = await ctx.Templates.Where(
t => t.EngagementAccount == engagementAccount).ToListAsync();
if (entities != null && entities.Count > 0)
{
ctx.Templates.RemoveRange(entities);
await ctx.SaveChangesAsync();
}
}
}
public async Task DeleteTemplatesByDomainAsync(string engagementAccount, string domain)
{
using (var ctx = new EmailServiceDbEntities(this.connectionString))
{
var entities = await ctx.Templates.Where(
t => t.EngagementAccount == engagementAccount &&
t.Domain == domain).ToListAsync();
if (entities != null && entities.Count > 0)
{
ctx.Templates.RemoveRange(entities);
await ctx.SaveChangesAsync();
}
}
}
public async Task DeleteTemplatesBySenderAsync(string engagementAccount, Guid senderId)
{
using (var ctx = new EmailServiceDbEntities(this.connectionString))
{
var entities = await ctx.Templates.Where(
t => t.EngagementAccount == engagementAccount &&
t.SenderAddressId == senderId).ToListAsync();
if (entities != null && entities.Count > 0)
{
ctx.Templates.RemoveRange(entities);
await ctx.SaveChangesAsync();
}
}
}
public async Task UpdateTemplateStateByDomainAsync(string account, string domain, ResourceState fromState, ResourceState toState, string message = null)
{
using (var ctx = new EmailServiceDbEntities(this.connectionString))
{
var entities = await ctx.Templates.Where(
t => t.EngagementAccount == account &&
t.Domain == domain &&
t.State == fromState.ToString()).ToListAsync();
if (entities != null && entities.Count > 0)
{
foreach (var entity in entities)
{
entity.State = toState.ToString();
entity.StateMessage = message;
}
await ctx.SaveChangesAsync();
}
}
}
#endregion
#region EmailAccount
public async Task<EmailAccount> GetEmailAccountAsync(string engagementAccount)
{
using (var ctx = new EmailServiceDbEntities(this.connectionString))
{
var account = await ctx.EngagementAccounts.SingleOrDefaultAsync(a => a.EngagementAccount == engagementAccount);
if (account == null)
{
return null;
}
var domains = await ctx.Domains.Where(
d => d.EngagementAccount == engagementAccount &&
d.State == ResourceState.Active.ToString()).OrderBy(s => s.Created).ToListAsync();
return new EmailAccount
{
EngagementAccount = engagementAccount,
Domains = domains?.Select(d => d.Domain).ToList(),
Properties = JsonConvert.DeserializeObject<PropertyCollection<string>>(account.Properties)
};
}
}
public async Task<EmailAccount> UpdateEmailAccountAsync(EmailAccount emailAccount)
{
using (var ctx = new EmailServiceDbEntities(this.connectionString))
{
var account = await ctx.EngagementAccounts.SingleOrDefaultAsync(a => a.EngagementAccount == emailAccount.EngagementAccount);
if (account == null)
{
return null;
}
account.Properties = JsonConvert.SerializeObject(emailAccount.Properties);
account.Modified = DateTime.UtcNow;
await ctx.SaveChangesAsync();
return emailAccount;
}
}
#endregion
}
}
| 39.742389 | 236 | 0.54287 | [
"MIT"
] | Azure/azure-cef | src/product/ServiceProvider/Email/Microsoft.Azure.EngagementFabric.EmailProvider/Store/EmailStore.cs | 33,942 | C# |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace SoapCore
{
public static class CachedXmlSerializer
{
private static readonly ConcurrentDictionary<string, XmlSerializer> CachedSerializers = new ConcurrentDictionary<string, XmlSerializer>();
public static XmlSerializer GetXmlSerializer(Type elementType, string parameterName, string parameterNs)
{
var key = $"{elementType}|{parameterName}|{parameterNs}";
return CachedSerializers.GetOrAdd(key, _ => new XmlSerializer(elementType, null, new Type[0], new XmlRootAttribute(parameterName), parameterNs));
}
}
}
| 32.863636 | 148 | 0.79668 | [
"MIT"
] | 0be1/SoapCore | src/SoapCore/CachedXmlSerializer.cs | 723 | C# |
using System;
using System.Diagnostics;
namespace CassandraPrimitives.Tests.Commons.Speed
{
public class OperationsSpeed : IComparable<OperationsSpeed>
{
public OperationsSpeed(double operationsPerSecond)
{
this.OperationsPerSecond = operationsPerSecond;
}
public int CompareTo(OperationsSpeed other)
{
return OperationsPerSecond.CompareTo(other.OperationsPerSecond);
}
public static OperationsSpeed PerSecond(int operationsPerSecond)
{
return new OperationsSpeed(operationsPerSecond);
}
public static OperationsSpeed PerTimeSpan(int operationCount, TimeSpan timeSpan)
{
return new OperationsSpeed(operationCount / timeSpan.TotalSeconds);
}
public static OperationsSpeed SingeOperationPerTimeSpan(TimeSpan timeSpan)
{
return PerTimeSpan(1, timeSpan);
}
public TimeSpan TimeoutToGetDesiredSpeed(OperationsSpeed desiredSpeed, int operationsPerAttempt)
{
return desiredSpeed.GetTimeSpanToExecuteOperations(operationsPerAttempt) - GetTimeSpanToExecuteOperations(operationsPerAttempt);
}
public static OperationsSpeed FromBatchAction(Action action, int batchSize)
{
var stopwatch = Stopwatch.StartNew();
try
{
action();
}
finally
{
stopwatch.Stop();
}
return PerTimeSpan(batchSize, stopwatch.Elapsed);
}
public override string ToString()
{
return $"Speed: {OperationsPerSecond} ops";
}
public static bool operator <(OperationsSpeed speed1, OperationsSpeed speed2)
{
return speed1.CompareTo(speed2) < 0;
}
public static bool operator >(OperationsSpeed speed1, OperationsSpeed speed2)
{
return speed1.CompareTo(speed2) > 0;
}
public static bool operator <=(OperationsSpeed speed1, OperationsSpeed speed2)
{
return speed1.CompareTo(speed2) <= 0;
}
public static bool operator >=(OperationsSpeed speed1, OperationsSpeed speed2)
{
return speed1.CompareTo(speed2) >= 0;
}
public static OperationsSpeed operator /(OperationsSpeed speed1, int speed2)
{
return new OperationsSpeed(speed1.OperationsPerSecond / speed2);
}
public static OperationsSpeed operator +(OperationsSpeed speed1, OperationsSpeed speed2)
{
return new OperationsSpeed(speed1.OperationsPerSecond + speed2.OperationsPerSecond);
}
public double OperationsPerSecond { get; }
private TimeSpan GetTimeSpanToExecuteOperations(int operationsPerAttempt)
{
return TimeSpan.FromSeconds(operationsPerAttempt / OperationsPerSecond);
}
}
} | 31.638298 | 140 | 0.63349 | [
"MIT"
] | skbkontur/cassandra-primitives | CassandraPrimitives.Tests/Commons/Speed/OperationsSpeed.cs | 2,974 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Xml;
using WinSW.Native;
using WinSW.Util;
using WMI;
using YamlDotNet.Serialization;
using static WinSW.Download;
namespace WinSW.Configuration
{
public class YamlConfiguration : IWinSWConfiguration
{
public DefaultWinSWSettings Defaults { get; } = new DefaultWinSWSettings();
[YamlMember(Alias = "id")]
public string? IdYaml { get; set; }
[YamlMember(Alias = "name")]
public string? NameYaml { get; set; }
[YamlMember(Alias = "description")]
public string? DescriptionYaml { get; set; }
[YamlMember(Alias = "executable")]
public string? ExecutableYaml { get; set; }
[YamlMember(Alias = "executablePath")]
public string? ExecutablePathYaml { get; set; }
[YamlMember(Alias = "hideWindow")]
public bool? HideWindowYaml { get; set; }
[YamlMember(Alias = "workingdirectory")]
public string? WorkingDirectoryYaml { get; set; }
[YamlMember(Alias = "serviceaccount")]
public ServiceAccount? ServiceAccountYaml { get; set; }
[YamlMember(Alias = "log")]
public YamlLog? YAMLLog { get; set; }
[YamlMember(Alias = "download")]
public List<YamlDownload>? DownloadsYaml { get; set; }
[YamlMember(Alias = "arguments")]
public string? ArgumentsYaml { get; set; }
[YamlMember(Alias = "startArguments")]
public string? StartArgumentsYaml { get; set; }
[YamlMember(Alias = "stopArguments")]
public string? StopArgumentsYaml { get; set; }
[YamlMember(Alias = "stopExecutable")]
public string? StopExecutableYaml { get; set; }
[YamlMember(Alias = "stopParentProcessFirst")]
public bool? StopParentProcessFirstYaml { get; set; }
[YamlMember(Alias = "resetFailureAfter")]
public string? ResetFailureAfterYaml { get; set; }
[YamlMember(Alias = "stopTimeout")]
public string? StopTimeoutYaml { get; set; }
[YamlMember(Alias = "startMode")]
public string? StartModeYaml { get; set; }
[YamlMember(Alias = "serviceDependencies")]
public string[]? ServiceDependenciesYaml { get; set; }
[YamlMember(Alias = "waitHint")]
public string? WaitHintYaml { get; set; }
[YamlMember(Alias = "sleepTime")]
public string? SleepTimeYaml { get; set; }
[YamlMember(Alias = "interactive")]
public bool? InteractiveYaml { get; set; }
[YamlMember(Alias = "priority")]
public string? PriorityYaml { get; set; }
[YamlMember(Alias = "beepOnShutdown")]
public bool BeepOnShutdown { get; set; }
[YamlMember(Alias = "env")]
public List<YamlEnv>? EnvironmentVariablesYaml { get; set; }
[YamlMember(Alias = "onFailure")]
public List<YamlFailureAction>? YamlFailureActions { get; set; }
[YamlMember(Alias = "delayedAutoStart")]
public bool DelayedAutoStart { get; set; }
[YamlMember(Alias = "securityDescriptor")]
public string? SecurityDescriptorYaml { get; set; }
[YamlMember(Alias = "extensions")]
public List<string>? YamlExtensionIds { get; set; }
public class YamlEnv
{
[YamlMember(Alias = "name")]
public string? Name { get; set; }
[YamlMember(Alias = "value")]
public string? Value { get; set; }
}
public class YamlLog : Log
{
private readonly YamlConfiguration configs;
public YamlLog()
{
this.configs = new YamlConfiguration();
}
[YamlMember(Alias = "mode")]
public string? ModeYamlLog { get; set; }
[YamlMember(Alias = "name")]
public string? NameYamlLog { get; set; }
[YamlMember(Alias = "sizeThreshold")]
public int? SizeThresholdYamlLog { get; set; }
[YamlMember(Alias = "keepFiles")]
public int? KeepFilesYamlLog { get; set; }
[YamlMember(Alias = "pattern")]
public string? PatternYamlLog { get; set; }
[YamlMember(Alias = "period")]
public int? PeriodYamlLog { get; set; }
[YamlMember(Alias = "logpath")]
public string? LogPathYamlLog { get; set; }
// Filters
[YamlMember(Alias = "outFileDisabled")]
public bool? OutFileDisabledYamlLog { get; set; }
[YamlMember(Alias = "errFileDisabled")]
public bool? ErrFileDisabledYamlLog { get; set; }
[YamlMember(Alias = "outFilePattern")]
public string? OutFilePatternYamlLog { get; set; }
[YamlMember(Alias = "errFilePattern")]
public string? ErrFilePatternYamlLog { get; set; }
// Zip options
[YamlMember(Alias = "autoRollAtTime")]
public string? AutoRollAtTimeYamlLog { get; set; }
[YamlMember(Alias = "zipOlderThanNumDays")]
public int? ZipOlderThanNumDaysYamlLog { get; set; }
[YamlMember(Alias = "zipDateFormat")]
public string? ZipDateFormatYamlLog { get; set; }
public override string Mode => this.ModeYamlLog is null ?
DefaultWinSWSettings.DefaultLogSettings.Mode :
this.ModeYamlLog;
public override string Name
{
get
{
return this.NameYamlLog is null ?
DefaultWinSWSettings.DefaultLogSettings.Name :
ExpandEnv(this.NameYamlLog);
}
}
public override string Directory
{
get
{
return this.LogPathYamlLog is null ?
DefaultWinSWSettings.DefaultLogSettings.Directory :
ExpandEnv(this.LogPathYamlLog);
}
}
public override int? SizeThreshold
{
get
{
return this.SizeThresholdYamlLog is null ?
DefaultWinSWSettings.DefaultLogSettings.SizeThreshold :
this.SizeThresholdYamlLog * RollingSizeTimeLogAppender.BytesPerKB;
}
}
public override int? KeepFiles
{
get
{
return this.KeepFilesYamlLog is null ?
DefaultWinSWSettings.DefaultLogSettings.KeepFiles :
this.KeepFilesYamlLog;
}
}
public override string Pattern
{
get
{
if (this.PatternYamlLog != null)
{
return this.PatternYamlLog;
}
return DefaultWinSWSettings.DefaultLogSettings.Pattern;
}
}
public override int? Period => this.PeriodYamlLog is null ? 1 : this.PeriodYamlLog;
public override bool OutFileDisabled
{
get
{
return this.OutFileDisabledYamlLog is null ?
DefaultWinSWSettings.DefaultLogSettings.OutFileDisabled :
(bool)this.OutFileDisabledYamlLog;
}
}
public override bool ErrFileDisabled
{
get
{
return this.ErrFileDisabledYamlLog is null ?
this.configs.Defaults.ErrFileDisabled :
(bool)this.ErrFileDisabledYamlLog;
}
}
public override string OutFilePattern
{
get
{
return this.OutFilePatternYamlLog is null ?
DefaultWinSWSettings.DefaultLogSettings.OutFilePattern :
ExpandEnv(this.OutFilePatternYamlLog);
}
}
public override string ErrFilePattern
{
get
{
return this.ErrFilePatternYamlLog is null ?
DefaultWinSWSettings.DefaultLogSettings.ErrFilePattern :
ExpandEnv(this.ErrFilePatternYamlLog);
}
}
public override string? AutoRollAtTime
{
get
{
return this.AutoRollAtTimeYamlLog is null ?
DefaultWinSWSettings.DefaultLogSettings.AutoRollAtTime :
this.AutoRollAtTimeYamlLog;
}
}
public override int? ZipOlderThanNumDays
{
get
{
if (this.ZipOlderThanNumDaysYamlLog != null)
{
return this.ZipOlderThanNumDaysYamlLog;
}
return DefaultWinSWSettings.DefaultLogSettings.ZipOlderThanNumDays;
}
}
public override string? ZipDateFormat
{
get
{
return this.ZipDateFormatYamlLog is null ?
DefaultWinSWSettings.DefaultLogSettings.ZipDateFormat :
this.ZipDateFormatYamlLog;
}
}
}
public class YamlDownload
{
[YamlMember(Alias = "from")]
public string FromYamlDownload { get; set; } = string.Empty;
[YamlMember(Alias = "to")]
public string ToYamlDownload { get; set; } = string.Empty;
[YamlMember(Alias = "auth")]
public string? AuthYamlDownload { get; set; }
[YamlMember(Alias = "username")]
public string? UsernameYamlDownload { get; set; }
[YamlMember(Alias = "password")]
public string? PasswordYamlDownload { get; set; }
[YamlMember(Alias = "unsecureAuth")]
public bool UnsecureAuthYamlDownload { get; set; }
[YamlMember(Alias = "failOnError")]
public bool FailOnErrorYamlDownload { get; set; }
[YamlMember(Alias = "proxy")]
public string? ProxyYamlDownload { get; set; }
public string FromDownload => ExpandEnv(this.FromYamlDownload);
public string ToDownload => ExpandEnv(this.ToYamlDownload);
public string? UsernameDownload => this.UsernameYamlDownload is null ? null : ExpandEnv(this.UsernameYamlDownload);
public string? PasswordDownload => this.PasswordYamlDownload is null ? null : ExpandEnv(this.PasswordYamlDownload);
public string? ProxyDownload => this.ProxyYamlDownload is null ? null : ExpandEnv(this.ProxyYamlDownload);
public AuthType AuthDownload
{
get
{
if (this.AuthYamlDownload is null)
{
return AuthType.None;
}
var auth = ExpandEnv(this.AuthYamlDownload);
try
{
return (AuthType)Enum.Parse(typeof(AuthType), auth, true);
}
catch
{
Console.WriteLine("Auth type in YAML must be one of the following:");
foreach (string at in Enum.GetNames(typeof(AuthType)))
{
Console.WriteLine(at);
}
throw;
}
}
}
}
public class YamlFailureAction
{
[YamlMember(Alias = "action")]
public string? FailureAction { get; set; }
[YamlMember(Alias = "delay")]
public string? FailureActionDelay { get; set; }
public SC_ACTION_TYPE Type
{
get
{
SC_ACTION_TYPE actionType = this.FailureAction switch
{
"restart" => SC_ACTION_TYPE.SC_ACTION_RESTART,
"none" => SC_ACTION_TYPE.SC_ACTION_NONE,
"reboot" => SC_ACTION_TYPE.SC_ACTION_REBOOT,
_ => throw new InvalidDataException("Invalid failure action: " + this.FailureAction)
};
return actionType;
}
}
public TimeSpan Delay => this.FailureActionDelay is null ? TimeSpan.Zero : ConfigHelper.ParseTimeSpan(this.FailureActionDelay);
}
private string? GetArguments(string? args, ArgType type)
{
if (args is null)
{
switch (type)
{
case ArgType.Arg:
return this.Defaults.Arguments;
case ArgType.Startarg:
return this.Defaults.StartArguments;
case ArgType.Stoparg:
return this.Defaults.StopArguments;
default:
return string.Empty;
}
}
return ExpandEnv(args);
}
private enum ArgType
{
Arg = 0,
Startarg = 1,
Stoparg = 2
}
private List<Download> GetDownloads(List<YamlDownload>? downloads)
{
if (downloads is null)
{
return this.Defaults.Downloads;
}
var result = new List<Download>(downloads.Count);
foreach (var item in downloads)
{
result.Add(new Download(
item.FromDownload,
item.ToDownload,
item.FailOnErrorYamlDownload,
item.AuthDownload,
item.UsernameDownload,
item.PasswordDownload,
item.UnsecureAuthYamlDownload,
item.ProxyDownload));
}
return result;
}
internal static string ExpandEnv(string str)
{
return Environment.ExpandEnvironmentVariables(str);
}
public string Id => this.IdYaml is null ? this.Defaults.Id : ExpandEnv(this.IdYaml);
public string Description => this.DescriptionYaml is null ? this.Defaults.Description : ExpandEnv(this.DescriptionYaml);
public string Executable => this.ExecutableYaml is null ? this.Defaults.Executable : ExpandEnv(this.ExecutableYaml);
public string ExecutablePath => this.ExecutablePathYaml is null ?
this.Defaults.ExecutablePath :
ExpandEnv(this.ExecutablePathYaml);
public string Caption => this.NameYaml is null ? this.Defaults.Caption : ExpandEnv(this.NameYaml);
public bool HideWindow => this.HideWindowYaml is null ? this.Defaults.HideWindow : (bool)this.HideWindowYaml;
public bool StopParentProcessFirst
{
get
{
return this.StopParentProcessFirstYaml is null ?
this.Defaults.StopParentProcessFirst :
(bool)this.StopParentProcessFirstYaml;
}
}
public StartMode StartMode
{
get
{
if (this.StartModeYaml is null)
{
return this.Defaults.StartMode;
}
var p = ExpandEnv(this.StartModeYaml);
try
{
return (StartMode)Enum.Parse(typeof(StartMode), p, true);
}
catch
{
Console.WriteLine("Start mode in YAML must be one of the following:");
foreach (string sm in Enum.GetNames(typeof(StartMode)))
{
Console.WriteLine(sm);
}
throw;
}
}
}
public string Arguments
{
get
{
var args = this.GetArguments(this.ArgumentsYaml, ArgType.Arg);
return args is null ? this.Defaults.Arguments : args;
}
}
public string? StartArguments => this.GetArguments(this.StartArgumentsYaml, ArgType.Startarg);
public string? StopArguments => this.GetArguments(this.StopArgumentsYaml, ArgType.Stoparg);
public string? StopExecutable
{
get
{
return this.StopExecutableYaml is null ?
this.Defaults.StopExecutable :
ExpandEnv(this.StopExecutableYaml);
}
}
public SC_ACTION[] FailureActions
{
get
{
if (this.YamlFailureActions is null)
{
return new SC_ACTION[0];
}
var arr = new List<SC_ACTION>();
foreach (var item in this.YamlFailureActions)
{
arr.Add(new SC_ACTION(item.Type, item.Delay));
}
return arr.ToArray();
}
}
public TimeSpan ResetFailureAfter => this.ResetFailureAfterYaml is null ?
this.Defaults.ResetFailureAfter :
ConfigHelper.ParseTimeSpan(this.ResetFailureAfterYaml);
public string WorkingDirectory => this.WorkingDirectoryYaml is null ?
this.Defaults.WorkingDirectory :
ExpandEnv(this.WorkingDirectoryYaml);
public ProcessPriorityClass Priority
{
get
{
if (this.PriorityYaml is null)
{
return this.Defaults.Priority;
}
var p = ExpandEnv(this.PriorityYaml);
try
{
return (ProcessPriorityClass)Enum.Parse(typeof(ProcessPriorityClass), p, true);
}
catch
{
Console.WriteLine("Priority in YAML must be one of the following:");
foreach (string pr in Enum.GetNames(typeof(ProcessPriorityClass)))
{
Console.WriteLine(pr);
}
throw;
}
}
}
public TimeSpan StopTimeout => this.StopTimeoutYaml is null ? this.Defaults.StopTimeout : ConfigHelper.ParseTimeSpan(this.StopTimeoutYaml);
public string[] ServiceDependencies
{
get
{
if (this.ServiceDependenciesYaml is null)
{
return this.Defaults.ServiceDependencies;
}
var result = new List<string>(0);
foreach (var item in this.ServiceDependenciesYaml)
{
result.Add(ExpandEnv(item));
}
return result.ToArray();
}
}
public TimeSpan WaitHint => this.WaitHintYaml is null ? this.Defaults.WaitHint : ConfigHelper.ParseTimeSpan(this.WaitHintYaml);
public TimeSpan SleepTime => this.SleepTimeYaml is null ? this.Defaults.SleepTime : ConfigHelper.ParseTimeSpan(this.SleepTimeYaml);
public bool Interactive => this.InteractiveYaml is null ? this.Defaults.Interactive : (bool)this.InteractiveYaml;
public List<Download> Downloads => this.GetDownloads(this.DownloadsYaml);
public Dictionary<string, string> EnvironmentVariables { get; set; } = new Dictionary<string, string>();
public void LoadEnvironmentVariables()
{
if (this.EnvironmentVariablesYaml is null)
{
this.EnvironmentVariables = this.Defaults.EnvironmentVariables;
}
else
{
foreach (var item in this.EnvironmentVariablesYaml)
{
if (item.Name is null || item.Value is null)
{
continue;
}
var key = item.Name;
var value = ExpandEnv(item.Value);
this.EnvironmentVariables[key] = value;
Environment.SetEnvironmentVariable(key, value);
}
}
}
public ServiceAccount ServiceAccount => this.ServiceAccountYaml is null ? this.Defaults.ServiceAccount : this.ServiceAccountYaml;
public Log Log => this.YAMLLog is null ? this.Defaults.Log : this.YAMLLog;
public string LogDirectory => this.Log.Directory;
public string LogMode => this.Log.Mode is null ? this.Defaults.LogMode : this.Log.Mode;
// TODO - Extensions
XmlNode? IWinSWConfiguration.ExtensionsConfiguration => throw new NotImplementedException();
public List<string> ExtensionIds => this.YamlExtensionIds ?? this.Defaults.ExtensionIds;
public string BaseName => this.Defaults.BaseName;
public string BasePath => this.Defaults.BasePath;
public string? SecurityDescriptor
{
get
{
if (this.SecurityDescriptorYaml is null)
{
return this.Defaults.SecurityDescriptor;
}
return ExpandEnv(this.SecurityDescriptorYaml);
}
}
}
}
| 32.788606 | 147 | 0.521079 | [
"MIT"
] | Create-it-cn/winsw | src/Core/WinSWCore/Configuration/YamlConfiguration.cs | 21,870 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
namespace KERBALISM
{
/*
- Storm / local radiation raycasting :
- RaycastAll between emitter and receiver, save "from" hits
- RaycastAll between receiver and emitter, save "to" hits
- foreach hit :
- build a list of hitted parts and affect from and to hits
- the good "from" hit is the one closest from the emitter
- the good "to" hit is the one closest from the receiver
- distance from / to is the thickness
- determine wall thickness the ray has gone through by using the hits normals
- Occluder stats :
- At minimum, a part has 2 occluder "materials" : walls and core
- The "wall" occluder has a thickness enclosing the part.
- Half the part mass is considered to be walls of aluminium density, giving a "wall volume"
- The wall thickness is the "wall volume" divided by the part surface
- HVL values are derived from aluminium properties
- A "core" occluder that is derived from the part volume and half the part mass
- A "density factor" is derived from the difference between the part volume and the volume of half the part mass at aluminum density
- HVL values are derived from aluminium properties, scaled down by the "density factor"
- By default, resources are additional "core" occluders using the same formula, but with the density and HVL parameters from the resource instead of aluminium
- A RESOURCE_HVL node in the profile can be used to define the resource occlusion stats (wall/core, HVL values)
- Resources that don't have a definition are considered as "core", with HVL values derived from the resource density.
- Radiation is computed as follow :
- "Ambiant" radiation (bodies, belts...) :
- Is blocked by the part "wall" occluder materials, according to the material "low" energy HVL value
- Is blocked by coil array fields enclosing the part
- "Storm" radiation (sun) :
- Is blocked by the part "wall" occluder materials
- Is blocked by all occluder materials from all parts in between
- According to the material "high" energy HVL value
- Parts in between produce secondary radiation (bremsstrahlung)
- Bremsstrahlung is also blocked, but using the "low" energy HVL value
- "Local" radiation (emitters)
- Is blocked by the part "wall" occluder materials, and by all occluder materials from all parts in between
- Is blocked by all occluder materials from all parts in between
- According to the material "high" or "low" energy HVL value depending on the emitter
- TODO :
- IRadiationEmitter is currently only implemented in ModuleKsmRadiationEmitter. An implementation in ModuleKsmProcessController would make sense.
- Also, ModuleKsmRadiationEmitter could benefit from a config-defined reflection based system allowing to watch another module state to
determine if the emitter should be enabled, and eventually to scale the radiation level.
- Currently there is a set of heuristics used to determine if a part can or can't be an occluder, to exclude small parts.
An option to override the automatic choice with per-part configs would be nice
- Occlusion computations accuracy heavily rely on a static library of part volume/surface stats currently computed at prefab compilation.
This is problematic for deployable / procedural parts. Ideally we should have volume/surface stats stored in PartData, with hooks /
events watching for "shape changes", either triggering a volume/surface reevaluation (might need to investigate how to do that in a separate thread,
this too heavy to be done in real time) or acquiring volume/surface from external sources (procedural parts ?)
- Planner / flight UI info for radiation need a bit of love. Some info (tooltip) about the radiation level per source would be nice.
Also an ETA on radiation poisonning at current level.
- The coil array system is a bit dumb and unrealistic. Ideally the field should be cylindrical and be an occluder for storm/emitters,
only providing "direct" protection for "ambiant" radiation. In any case, the whole system is very WIP and in dire need of debugging and balancing.
- Ideally, planetary (and sun) radiation should be directional, like storms and emitters. The only "ambiant" radiation should happen in belts (and maybe
when close from a body surface)
- An "auto-shelter" feature would be nice : when external radiation exceed a player defined level, a set of player defined habitats are disabled,
and re-enabled when the storm is over. Require implementing unloaded crew transfer (relatively easy).
*/
public partial class PartRadiationData
{
public const string NODENAME_RADIATION = "RADIATION";
public const string NODENAME_EMITTERS = "EMITTERS";
public const string NODENAME_COILSARRAYS = "COILSARRAYS";
#region TYPES
private class CoilArrayShielding
{
private RadiationCoilHandler coilData;
private int coilDataId;
private double protectionFactor;
public double RadiationRemoved => coilData.effectData.RadiationRemoved * protectionFactor;
public CoilArrayShielding(RadiationCoilHandler coilData, double protectionFactor)
{
this.coilData = coilData;
this.protectionFactor = protectionFactor;
//coilDataId = coilData.FlightId;
}
private CoilArrayShielding(ConfigNode.Value value)
{
coilDataId = int.Parse(value.name);
protectionFactor = Lib.Parse.ToDouble(value.value, 0.0);
}
public void CheckChangedAndUpdate(RadiationCoilHandler coilData, double protectionFactor)
{
if (coilData != this.coilData)
{
this.coilData = coilData;
//coilDataId = coilData.FlightId;
}
this.protectionFactor = protectionFactor;
}
public static void OnUnloadedPostInstantiate(List<CoilArrayShielding> coilArrays)
{
for (int i = coilArrays.Count - 1; i >= 0; i--)
{
//if (ModuleHandler.TryGetPersistentFlightHandler<ModuleKsmRadiationCoil, RadiationCoilHandler, RadiationCoilDefinition>(coilArrays[i].coilDataId, out RadiationCoilHandler coilData))
//{
// coilArrays[i].coilData = coilData;
//}
//else
//{
// coilArrays.RemoveAt(i);
//}
}
}
public static void Save(VesselDataBase vd, List<CoilArrayShielding> coilArrays, ConfigNode radiationNode)
{
if (coilArrays != null && coilArrays.Count > 0)
{
ConfigNode arraysNode = new ConfigNode(NODENAME_COILSARRAYS);
foreach (CoilArrayShielding coilArray in coilArrays)
{
// save foreign arrays only if both vessels are landed
if (coilArray.coilData.VesselData != vd && (!vd.EnvLanded || !coilArray.coilData.VesselData.EnvLanded))
continue;
arraysNode.AddValue(coilArray.coilDataId.ToString(), coilArray.protectionFactor);
}
if (arraysNode.CountValues > 0)
{
radiationNode.AddNode(arraysNode);
}
}
}
public static void Load(PartRadiationData partRadiationData, ConfigNode radiationNode)
{
ConfigNode arraysNode = radiationNode.GetNode(NODENAME_COILSARRAYS);
if (arraysNode != null)
{
partRadiationData.coilArrays = new List<CoilArrayShielding>();
foreach (ConfigNode.Value coilArray in arraysNode.values)
{
partRadiationData.coilArrays.Add(new CoilArrayShielding(coilArray));
}
}
}
}
#endregion
#region FIELDS
/// <summary> while this is false, prevent that part raycast tasks to be added to the task queue </summary>
private bool raycastDone = true;
/// <summary> total radiation dose received since launch. Currently unused </summary>
public double accumulatedRadiation;
/// <summary> time elapsed since that part last update </summary>
private double elapsedSecSinceLastUpdate;
/// <summary> all active radiation shields whose protecting field include this part. Null on non-receivers parts </summary>
private List<CoilArrayShielding> coilArrays;
/// <summary> occluding stats for the part structural mass. Null on non-occluders parts </summary>
private PartStructuralOcclusion structuralOcclusion;
/// <summary> occluding stats for the part resources. Null on non-occluders parts </summary>
private List<ResourceOcclusion> resourcesOcclusion;
/// <summary> The storm occlusion raycasting task. Null on non-receivers parts </summary>
private SunRaycastTask sunRaycastTask;
/// <summary> Occlusion from local emitters raycasting task. Null on non-receivers parts </summary>
private List<EmitterRaycastTask> emitterRaycastTasks;
#endregion
#region PROPERTIES
/// <summary> PartData reference </summary>
public PartData PartData { get; private set; }
/// <summary> The current radiation rate received in rad/s. Only updated on receivers </summary>
public double RadiationRate { get; private set; }
/// <summary> The current radiation rate received in rad/s. Only updated on receivers </summary>
public double EmittersRadiation { get; private set; }
/// <summary> The current radiation rate received in rad/s. Only updated on receivers </summary>
public double EmittersOcclusion { get; private set; }
/// <summary> The current radiation rate received in rad/s. Only updated on receivers </summary>
public double AmbiantOcclusion { get; private set; }
/// <summary> The current radiation rate received in rad/s. Only updated on receivers </summary>
public double ActiveShielding { get; private set; }
/// <summary> % of storm / solar wind radiation getting trough</summary>
public double SunRadiationFactor => sunRaycastTask?.sunRadiationFactor ?? 1.0;
/// <summary>
/// Should the part should be considered for occlusion in raycasting tasks.
/// Only available for parts whose surface/volume stats have been computed (see PartVolumeAndSurface.EvaluatePrefabAtCompilation())
/// </summary>
public bool IsOccluder { get; private set; } = false;
/// <summary>
/// Should the part be considered for radiation rate evaluation.
/// True if the part has at least one module implementing IRadiationReceiver with IRadiationReceiver.EnableInterface returning true
/// </summary>
public bool IsReceiver { get; private set; } = false;
/// <summary>
/// Should the part be considered for local emission in raycasting tasks
/// True if the part has at least one module implementing IRadiationEmitter with IRadiationEmitter.EnableInterface returning true
/// </summary>
public bool IsEmitter { get; private set; } = false;
/// <summary> All emitters modules on that part. Null on non-emitter parts </summary>
public List<IRadiationEmitter> RadiationEmitters { get; private set; }
#endregion
#region LIFECYLE
public PartRadiationData(PartData partData)
{
PartData = partData;
}
public void PostInstantiateSetup()
{
IsOccluder = PartData.volumeAndSurface != null;
foreach (ModuleHandler md in PartData.modules)
{
if (md is IRadiationReceiver receiver && receiver.EnableInterface)
{
IsReceiver = true;
}
else if (md is IRadiationEmitter emitter && emitter.EnableInterface)
{
if (RadiationEmitters == null)
RadiationEmitters = new List<IRadiationEmitter>();
RadiationEmitters.Add(emitter);
IsEmitter = true;
}
}
if (IsReceiver)
{
if (sunRaycastTask == null)
sunRaycastTask = new SunRaycastTask(this);
if (emitterRaycastTasks == null)
emitterRaycastTasks = new List<EmitterRaycastTask>();
else if (!PartData.vesselData.LoadedOrEditor)
EmitterRaycastTask.OnUnloadedPostInstantiate(emitterRaycastTasks);
if (coilArrays == null)
coilArrays = new List<CoilArrayShielding>();
else if (!PartData.vesselData.LoadedOrEditor)
CoilArrayShielding.OnUnloadedPostInstantiate(coilArrays);
Lib.LogDebug($"{PartData.vesselData.VesselName} - {PartData} - shields:{coilArrays.Count}");
}
if (IsOccluder)
{
structuralOcclusion = new PartStructuralOcclusion();
resourcesOcclusion = new List<ResourceOcclusion>();
}
SetupDebugPAWInfo();
}
public static void Load(PartData partData, ConfigNode partDataNode)
{
ConfigNode radNode = partDataNode.GetNode(NODENAME_RADIATION);
if (radNode == null)
return;
partData.radiationData.RadiationRate = Lib.ConfigValue(radNode, "radRate", 0.0);
partData.radiationData.accumulatedRadiation = Lib.ConfigValue(radNode, "radAcc", 0.0);
if (radNode.HasValue("sunFactor"))
{
partData.radiationData.sunRaycastTask = new SunRaycastTask(partData.radiationData);
partData.radiationData.sunRaycastTask.sunRadiationFactor = Lib.ConfigValue(radNode, "sunFactor", 1.0);
}
EmitterRaycastTask.Load(partData.radiationData, radNode);
CoilArrayShielding.Load(partData.radiationData, radNode);
}
public static bool Save(PartData partData, ConfigNode partDataNode)
{
if (!partData.radiationData.IsReceiver)
return false;
ConfigNode radiationNode = partDataNode.AddNode(NODENAME_RADIATION);
radiationNode.AddValue("radRate", partData.radiationData.RadiationRate);
radiationNode.AddValue("radAcc", partData.radiationData.accumulatedRadiation);
if (partData.radiationData.sunRaycastTask != null)
{
radiationNode.AddValue("sunFactor", partData.radiationData.sunRaycastTask.sunRadiationFactor);
}
EmitterRaycastTask.Save(partData.vesselData, partData.radiationData.emitterRaycastTasks, radiationNode);
CoilArrayShielding.Save(partData.vesselData, partData.radiationData.coilArrays, radiationNode) ;
return true;
}
#endregion
#region EVALUATION
public void AddElapsedTime(double elapsedSec) => elapsedSecSinceLastUpdate += elapsedSec;
public void EnqueueRaycastTasks(Queue<RaycastTask> raycastTasks)
{
if (raycastDone)
{
raycastDone = false;
raycastTasks.Enqueue(sunRaycastTask);
foreach (EmitterRaycastTask emitterRaycastTask in emitterRaycastTasks)
{
raycastTasks.Enqueue(emitterRaycastTask);
}
}
}
// debug receiver info
private double radiationRateDbg;
private double stormRadiationFactorDbg;
private double stormRadiationDbg;
private double emittersRadiationDbg;
// debug occluder info
private string lastRaycastDbg;
private double rayPenetrationDbg;
private double blockedRadDbg;
private double bremsstrahlungDbg;
private double crossSectionFactorDbg;
public void Update()
{
UnityEngine.Profiling.Profiler.BeginSample("Kerbalism.PartRadiationData.Update");
// TODO: make this work on loaded and unloaded vessels
if (IsOccluder)
{
GetOccluderStats();
if (PartData.vesselData.LoadedOrEditor)
{
UpdateOcclusionStats();
}
}
if (IsReceiver)
{
EmittersRadiation = 0.0;
ActiveShielding = 0.0;
EmittersOcclusion = 0.0;
stormRadiationDbg = 0.0;
emittersRadiationDbg = 0.0;
// add "ambiant" radiation (background, belts, bodies...)
// TODO : apply sunRadiationFactor to solar wind component (vd.EnvRadiationSolar)
// also : maybe we could raycast to nearby bodies emitting significant radiation
// also : we should scale up radiation from raycasted bodies when the vessel is on or close to the surface
AmbiantOcclusion = OcclusionFactor(false, true, false);
RadiationRate = PartData.vesselData.EnvRadiation * AmbiantOcclusion;
AmbiantOcclusion = 1.0 - AmbiantOcclusion;
// add storm radiation, if there is a storm
stormRadiationFactorDbg = sunRaycastTask.sunRadiationFactor;
if (PartData.vesselData.EnvStorm)
{
RadiationRate += PartData.vesselData.EnvStormRadiation * sunRaycastTask.sunRadiationFactor;
stormRadiationDbg = PartData.vesselData.EnvStormRadiation * sunRaycastTask.sunRadiationFactor;
}
// synchronize emitters references and add their radiation
if (PartData.vesselData.LoadedOrEditor)
{
int vesselEmittersCount = PartData.vesselData.Synchronizer.AllRadiationEmittersCount;
int tasksCount = emitterRaycastTasks.Count;
if (tasksCount > vesselEmittersCount)
{
emitterRaycastTasks.RemoveRange(vesselEmittersCount, tasksCount - vesselEmittersCount);
}
for (int i = 0; i < vesselEmittersCount; i++)
{
if (i + 1 > tasksCount)
{
emitterRaycastTasks.Add(new EmitterRaycastTask(this, PartData.vesselData.Synchronizer.RadiationEmitterAtIndex(i)));
}
else
{
emitterRaycastTasks[i].CheckEmitterHasChanged(PartData.vesselData.Synchronizer.RadiationEmitterAtIndex(i));
}
EmittersRadiation += emitterRaycastTasks[i].Radiation();
EmittersOcclusion += emitterRaycastTasks[i].ReductionFactor;
}
EmittersOcclusion /= vesselEmittersCount;
EmittersOcclusion = 1.0 - EmittersOcclusion;
RadiationRate += EmittersRadiation;
emittersRadiationDbg = EmittersRadiation;
int coilsCount = coilArrays.Count;
int coilIndex = 0;
foreach (RadiationCoilHandler coilData in PartData.vesselData.Synchronizer.AllRadiationCoilDatas)
{
double protectionFactor = coilData.loadedModule.GetPartProtectionFactor(PartData.LoadedPart);
if (protectionFactor > 0.0)
{
if (coilIndex + 1 > coilsCount)
{
coilArrays.Add(new CoilArrayShielding(coilData, protectionFactor));
}
else
{
coilArrays[coilIndex].CheckChangedAndUpdate(coilData, protectionFactor);
}
ActiveShielding += coilArrays[coilIndex].RadiationRemoved;
coilIndex++;
}
}
RadiationRate -= ActiveShielding;
if (coilsCount > coilIndex + 1)
{
coilArrays.RemoveRange(coilIndex + 1, coilsCount - coilIndex + 1);
}
}
else
{
// Note : we don't check if the parts still exist. In case another unloaded vessel
// with emitters or coil arrays affecting the part is destroyed, the changes won't be
// applied until the next scene change. The is quite a corner case and would require a
// lot of extra checks, so I don't care.
// apply coil arrays protection
for (int i = 0; i < emitterRaycastTasks.Count; i++)
{
EmittersRadiation += emitterRaycastTasks[i].Radiation();
}
RadiationRate += EmittersRadiation;
// apply coil arrays protection
for (int i = 0; i < coilArrays.Count; i++)
{
ActiveShielding += coilArrays[i].RadiationRemoved;
}
RadiationRate -= ActiveShielding;
}
// Lib.LogDebug($"{PartData.vesselData.VesselName} - {PartData} - vesselEmitters:{vesselEmittersCount} - emitters:{emitterRaycastTasks.Count} - shields:{coilArrays.Count}");
// clamp to positive
RadiationRate = Math.Max(RadiationRate, 0.0);
radiationRateDbg = RadiationRate;
// accumulate total radiation received by this part
accumulatedRadiation += RadiationRate * elapsedSecSinceLastUpdate;
}
elapsedSecSinceLastUpdate = 0.0;
UnityEngine.Profiling.Profiler.EndSample();
}
// TODO : use the actual part mass, not the prefab mass
// Since the part can be unloaded, this require either storing the protopart reference in PartData, or storing the mass independently (a bit silly)
public void GetOccluderStats()
{
structuralOcclusion.Update(PartData.PartPrefab.mass, PartData.volumeAndSurface.surface, PartData.volumeAndSurface.volume);
}
private void UpdateOcclusionStats()
{
int listCapacity = resourcesOcclusion.Count;
int occluderIndex = -1;
if (PartData.LoadedPart == null)
{
for (int i = 0; i < PartData.LoadedPart.Resources.Count; i++)
{
PartResource res = PartData.LoadedPart.Resources[i];
if (res.info.density == 0.0)
continue;
occluderIndex++;
if (occluderIndex >= listCapacity)
{
resourcesOcclusion.Add(new ResourceOcclusion(res.info));
listCapacity++;
}
resourcesOcclusion[occluderIndex].UpdateOcclusion(res, PartData.volumeAndSurface.surface, PartData.volumeAndSurface.volume);
}
}
for (int i = 0; i < PartData.LoadedPart.Resources.Count; i++)
{
PartResource res = PartData.LoadedPart.Resources[i];
if (res.info.density == 0.0)
continue;
occluderIndex++;
if (occluderIndex >= listCapacity)
{
resourcesOcclusion.Add(new ResourceOcclusion(res.info));
listCapacity++;
}
resourcesOcclusion[occluderIndex].UpdateOcclusion(res, PartData.volumeAndSurface.surface, PartData.volumeAndSurface.volume);
}
while (listCapacity > occluderIndex + 1)
{
resourcesOcclusion.RemoveAt(listCapacity - 1);
listCapacity--;
}
}
private double OcclusionFactor(bool highPowerRad, bool wallOnly = false, bool crossing = true)
{
if (!IsOccluder)
{
return 0.0;
}
double rad = 1.0;
rad *= PartWallOcclusion.RadiationFactor(highPowerRad, crossing);
if (!wallOnly)
{
rad *= structuralOcclusion.RadiationFactor(hitPenetration, highPowerRad);
}
foreach (ResourceOcclusion occlusion in resourcesOcclusion)
{
if (occlusion.IsWallOccluder)
{
rad *= occlusion.WallRadiationFactor(highPowerRad, crossing);
}
else if (!wallOnly)
{
rad *= occlusion.VolumeRadiationFactor(hitPenetration, highPowerRad);
}
}
return 1.0 - rad;
}
[Conditional("DEBUG_RADIATION")]
private void SetupDebugPAWInfo()
{
if (PartData.vesselData.VesselName == null)
return;
if (PartData.vesselData.LoadedOrEditor)
{
if (IsReceiver)
{
PartData.LoadedPart.Fields.Add(new BaseField(new UI_Label(), GetType().GetField(nameof(radiationRateDbg), System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance), this));
PartData.LoadedPart.Fields[nameof(radiationRateDbg)].guiName = "Radiation";
PartData.LoadedPart.Fields[nameof(radiationRateDbg)].guiFormat = "F10";
PartData.LoadedPart.Fields[nameof(radiationRateDbg)].guiUnits = " rad/s";
PartData.LoadedPart.Fields.Add(new BaseField(new UI_Label(), GetType().GetField(nameof(emittersRadiationDbg), System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance), this));
PartData.LoadedPart.Fields[nameof(emittersRadiationDbg)].guiName = "Emitters";
PartData.LoadedPart.Fields[nameof(emittersRadiationDbg)].guiFormat = "F10";
PartData.LoadedPart.Fields[nameof(emittersRadiationDbg)].guiUnits = " rad/s";
PartData.LoadedPart.Fields.Add(new BaseField(new UI_Label(), GetType().GetField(nameof(stormRadiationDbg), System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance), this));
PartData.LoadedPart.Fields[nameof(stormRadiationDbg)].guiName = "Storm";
PartData.LoadedPart.Fields[nameof(stormRadiationDbg)].guiFormat = "F10";
PartData.LoadedPart.Fields[nameof(stormRadiationDbg)].guiUnits = " rad/s";
PartData.LoadedPart.Fields.Add(new BaseField(new UI_Label(), GetType().GetField(nameof(stormRadiationFactorDbg), System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance), this));
PartData.LoadedPart.Fields[nameof(stormRadiationFactorDbg)].guiName = "Storm rad factor";
PartData.LoadedPart.Fields[nameof(stormRadiationFactorDbg)].guiFormat = "P6";
}
if (IsOccluder)
{
PartData.LoadedPart.Fields.Add(new BaseField(new UI_Label(), GetType().GetField(nameof(lastRaycastDbg), System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance), this));
PartData.LoadedPart.Fields.Add(new BaseField(new UI_Label(), GetType().GetField(nameof(rayPenetrationDbg), System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance), this));
PartData.LoadedPart.Fields[nameof(rayPenetrationDbg)].guiName = "rayPenetration";
PartData.LoadedPart.Fields[nameof(rayPenetrationDbg)].guiFormat = "F3";
PartData.LoadedPart.Fields[nameof(rayPenetrationDbg)].guiUnits = "m";
PartData.LoadedPart.Fields.Add(new BaseField(new UI_Label(), GetType().GetField(nameof(blockedRadDbg), System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance), this));
PartData.LoadedPart.Fields[nameof(blockedRadDbg)].guiName = "blockedRad";
PartData.LoadedPart.Fields[nameof(blockedRadDbg)].guiFormat = "P6";
PartData.LoadedPart.Fields.Add(new BaseField(new UI_Label(), GetType().GetField(nameof(bremsstrahlungDbg), System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance), this));
PartData.LoadedPart.Fields[nameof(bremsstrahlungDbg)].guiName = "bremsstrahlung";
PartData.LoadedPart.Fields[nameof(bremsstrahlungDbg)].guiFormat = "P6";
PartData.LoadedPart.Fields.Add(new BaseField(new UI_Label(), GetType().GetField(nameof(crossSectionFactorDbg), System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance), this));
PartData.LoadedPart.Fields[nameof(crossSectionFactorDbg)].guiName = "crossSectionFactor";
PartData.LoadedPart.Fields[nameof(crossSectionFactorDbg)].guiFormat = "P6";
}
}
}
#endregion
}
}
| 39.431644 | 211 | 0.716634 | [
"Unlicense"
] | Kerbalism/Kerbalism4 | src/Kerbalism/Database/PartData/PartRadiationData.cs | 25,022 | C# |
using System;
using NewLife.Data;
namespace NewLife.Net
{
/// <summary>安全沙箱</summary>
public class SandBoxServer : NetServer
{
#region 属性
private String _Policy = "<cross-domain-policy><allow-access-from domain=\"*\" to-ports=\"*\" /></cross-domain-policy>\0";
/// <summary>安全策略文件内容</summary>
public String Policy { get { return _Policy; } set { _Policy = value; } }
#endregion
/// <summary>实例化一个安全沙箱服务器</summary>
public SandBoxServer()
{
Port = 843;
ProtocolType = NetType.Tcp;
}
/// <summary>数据返回</summary>
/// <param name="session"></param>
/// <param name="pk"></param>
protected override void OnReceive(INetSession session, Packet pk)
{
var sss = pk.ToStr();
if (sss == "<policy-file-request/>\0")
{
session.Send(System.Text.Encoding.UTF8.GetBytes(_Policy.ToCharArray()));
}
session.Dispose();
return;
}
}
}
| 30.527778 | 131 | 0.516833 | [
"MIT"
] | 3781100649/NewLife.Net | NewLife.Net/Flash/SandBoxServer.cs | 1,161 | C# |
// Copyright (c) Microsoft. All rights reserved.
namespace Microsoft.Azure.Devices.Routing.Core.Query
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text.RegularExpressions;
using Antlr4.Runtime;
using Microsoft.Azure.Devices.Routing.Core.Query.Builtins;
using Microsoft.Azure.Devices.Routing.Core.Query.Types;
using Microsoft.Azure.Devices.Routing.Core.Util;
public class ConditionVisitor : ConditionBaseVisitor<Expression>
{
static readonly Expression[] NoArgs = new Expression[0];
static readonly Expression UndefinedExpression = Expression.Constant(Undefined.Instance);
readonly ParameterExpression message;
readonly ErrorListener errors;
readonly Route route;
readonly RouteCompilerFlags routeCompilerFlags;
static readonly IDictionary<string, IBuiltin> Builtins = new Dictionary<string, IBuiltin>(StringComparer.OrdinalIgnoreCase)
{
// math
{ "abs", new Abs() },
{ "exp", new Exp() },
{ "power", new Power() },
{ "square", new Square() },
{ "ceiling", new Ceiling() },
{ "floor", new Floor() },
{ "sign", new Sign() },
{ "sqrt", new Sqrt() },
// type checking
{ "as_number", new AsNumber() },
{ "is_bool", new IsBool() },
{ "is_defined", new IsDefined() },
{ "is_null", new IsNull() },
{ "is_number", new IsNumber() },
{ "is_string", new IsString() },
// strings
{ "concat", new Concat() },
{ "length", new Length() },
{ "lower", new Lower() },
{ "upper", new Upper() },
{ "substring", new Substring() },
{ "index_of", new IndexOf() },
{ "starts_with", new StartsWith() },
{ "ends_with", new EndsWith() },
{ "contains", new Contains() },
// body query
{ "twin_change_includes", new TwinChangeIncludes() },
};
public ConditionVisitor(ParameterExpression message, ErrorListener errors, Route route, RouteCompilerFlags routeCompilerFlags)
{
this.message = Preconditions.CheckNotNull(message);
this.errors = Preconditions.CheckNotNull(errors);
this.route = Preconditions.CheckNotNull(route);
this.routeCompilerFlags = routeCompilerFlags;
}
// Literals
public override Expression VisitBool(ConditionParser.BoolContext context)
{
bool result;
return bool.TryParse(context.GetText(), out result) ? Expression.Constant((Bool)result) : UndefinedExpression;
}
public override Expression VisitHex(ConditionParser.HexContext context)
{
long result;
return long.TryParse(context.GetText().Substring(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out result) ? Expression.Constant((double)result) : UndefinedExpression;
}
public override Expression VisitInteger(ConditionParser.IntegerContext context)
{
double result;
return double.TryParse(context.GetText(), NumberStyles.Any, CultureInfo.InvariantCulture, out result) ? Expression.Constant(result) : UndefinedExpression;
}
public override Expression VisitReal(ConditionParser.RealContext context)
{
double result;
return double.TryParse(context.GetText(), NumberStyles.Any, CultureInfo.InvariantCulture, out result) ? Expression.Constant(result) : UndefinedExpression;
}
public override Expression VisitString(ConditionParser.StringContext context)
{
// strip the quotes in order to escape the contents of the string
string input = context.GetText().Substring(1, context.GetText().Length - 2);
string value = Unescape(input);
return Expression.Constant(value);
}
public override Expression VisitUndefined(ConditionParser.UndefinedContext context)
{
return UndefinedExpression;
}
public override Expression VisitNull(ConditionParser.NullContext context)
{
return Expression.Constant(Null.Instance);
}
// Member Access
public override Expression VisitProperty(ConditionParser.PropertyContext context)
{
string property = context.GetText();
return this.GetProperty(Expression.Property(this.message, "Properties"), Expression.Constant(property));
}
public override Expression VisitSysProperty(ConditionParser.SysPropertyContext context)
{
// called if the property starts with a '$', it can be an app property or system property or a body query
// the app property takes precedence
// We must check whether the property first exists as a user property. If it does, return it, else
// try to get it from the body query or the system properties
string propertyName = context.GetText();
Expression alternative;
bool isBodyQuery = false;
if (this.IsBodyQueryExpression(propertyName, context.SYS_PROP().Symbol, out alternative))
{
isBodyQuery = alternative.Type != typeof(Undefined);
}
// Property names do not support '[' or ']'. Return body query in this case
if (propertyName.Contains("[") || propertyName.Contains("]"))
{
return alternative;
}
if (!isBodyQuery)
{
alternative = this.GetSysProperty(propertyName.Substring(1));
}
Expression property = Expression.Constant(propertyName);
Expression propertyBag = Expression.Property(this.message, "Properties");
return this.GetPropertyOrElse(propertyBag, property, alternative, isBodyQuery);
}
public override Expression VisitSysPropertyEscaped(ConditionParser.SysPropertyEscapedContext context)
{
// Handles escaped system property `{$<propname>}`
string propertyName = context.prop.Text;
Expression sysPropertyExpression;
if (!this.IsBodyQueryExpression(propertyName, context.SYS_PROP().Symbol, out sysPropertyExpression))
{
sysPropertyExpression = this.GetSysProperty(propertyName.Substring(1));
}
return sysPropertyExpression;
}
Expression GetProperty(Expression propertyBag, Expression property)
{
return this.GetPropertyOrElse(propertyBag, property, UndefinedExpression, false);
}
Expression GetPropertyOrElse(Expression propertyBag, Expression property, Expression alternative, bool isBodyQuery)
{
Expression expression;
if (propertyBag.Type != typeof(Undefined))
{
MethodInfo method = typeof(IReadOnlyDictionary<string, string>).GetMethod("ContainsKey");
MethodCallExpression contains = Expression.Call(propertyBag, method, property);
IndexExpression value = Expression.Property(propertyBag, "Item", property);
// NOTE: Arguments to Expression.Condition need to be of the same type. So we will wrap to QueryValue if it could be a bodyquery
// Review following cases before making changes here -
// 1. It is an app property with no conflict => Convert to String and return value and alternative
// 2. It is a system property with no conflict => Same as case 1. Property bag supplied by caller is sys property
// 3. It is a Body query with no conflict => ifFalse Expression will be returned. Type is already QueryValue.
// 4. It looks like a body query but is an app property ($body.propertyname) =>
// ifTrue will be evaluated. Just wrap contents to QueryValue so that Expression.Condition does not complain.
// 5. Body Query and a conflicting app property => App property wins
// 6. Body Query escaped and a conflicting app property => Body Query wins
Expression ifTrue = isBodyQuery ? Expression.Convert(value, typeof(QueryValue)) : Expression.Convert(value, typeof(string));
Expression ifFalse = isBodyQuery ? alternative : Expression.Convert(alternative, typeof(string));
expression = Expression.Condition(
contains,
ifTrue,
ifFalse);
}
else
{
expression = UndefinedExpression;
}
return expression;
}
Expression GetSysProperty(string propertyName)
{
// SystemProperty name containing '[' or ']' can reach here if it looked like body query, and was parsed successfully using Condition.g4.
// In this case, return Undefined because it is not a supported SystemProperty.
if (propertyName.Contains("[") || propertyName.Contains("]"))
{
return UndefinedExpression;
}
Expression propertyBag = Expression.Property(this.message, "SystemProperties");
Expression property = Expression.Constant(propertyName);
return this.GetProperty(propertyBag, property);
}
// Functions
public override Expression VisitFunc(ConditionParser.FuncContext context)
{
IToken funcToken = context.fcall().func;
string funcText = funcToken.Text;
IBuiltin builtin;
if (!this.TryGetSupportedBuiltin(funcText, out builtin))
{
this.errors.InvalidBuiltinError(funcToken);
return UndefinedExpression;
}
else
{
Expression[] args;
Expression[] contextArgs = null;
if (builtin.IsBodyQuery)
{
args = new Expression[]
{
Expression.Constant(context.fcall().exprList()?.GetText() ?? string.Empty)
};
contextArgs = new Expression[]
{
this.message,
Expression.Constant(this.route)
};
}
else
{
args = context.fcall().exprList() != null ? context.fcall().exprList().expr().Select(expr => this.Visit(expr)).ToArray() : NoArgs;
}
return builtin.Get(funcToken, args, contextArgs, this.errors);
}
}
// Unary Ops
public override Expression VisitNegate(ConditionParser.NegateContext context)
{
Expression expr = this.Visit(context.expr());
return this.CheckOperand(context.op, typeof(double), expr)
? Expression.Negate(expr)
: UndefinedExpression;
}
public override Expression VisitNot(ConditionParser.NotContext context)
{
Expression expr = this.Visit(context.expr());
// "not null" is a valid expression. We check for null and assume
// the operand is a bool if it's not null.
Type type = expr.Type == typeof(Null) ? typeof(Null) : typeof(Bool);
return this.CheckOperand(context.op, type, expr)
? Expression.Convert(Expression.Not(expr), typeof(Bool))
: UndefinedExpression;
}
// Binary Ops
public override Expression VisitMulDivMod(ConditionParser.MulDivModContext context)
{
Expression result;
Expression left = this.Visit(context.left);
Expression right = this.Visit(context.right);
if (this.CheckOperands(context.op, typeof(double), ref left, ref right))
{
switch (context.op.Type)
{
case ConditionParser.OP_MUL:
result = Expression.Multiply(left, right);
break;
case ConditionParser.OP_DIV:
result = Expression.Divide(left, right);
break;
case ConditionParser.OP_MOD:
result = Expression.Modulo(left, right);
break;
default:
throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Unrecognized op token: {0}", context.op.Text));
}
}
else
{
result = UndefinedExpression;
}
return result;
}
public override Expression VisitAddSubConcat(ConditionParser.AddSubConcatContext context)
{
Expression result;
Expression left = this.Visit(context.left);
Expression right = this.Visit(context.right);
switch (context.op.Type)
{
case ConditionParser.PLUS:
result = this.CheckOperands(context.op, typeof(double), ref left, ref right) ? Expression.Add(left, right) : UndefinedExpression;
break;
case ConditionParser.MINUS:
result = this.CheckOperands(context.op, typeof(double), ref left, ref right) ? Expression.Subtract(left, right) : UndefinedExpression;
break;
case ConditionParser.OP_CONCAT:
result = this.CheckOperands(context.op, typeof(string), ref left, ref right) ? this.GetBuiltin("concat", context.op, left, right) : UndefinedExpression;
break;
default:
throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Unrecognized op token: {0}", context.op.Text));
}
return result;
}
public override Expression VisitCompare(ConditionParser.CompareContext context)
{
Expression result;
Expression left = this.Visit(context.left);
Expression right = this.Visit(context.right);
if (this.CheckOperands(context.op, left.Type, ref left, ref right))
{
MethodInfo method = typeof(ComparisonOperators).GetMethod("Compare", new[] { typeof(CompareOp), left.Type, right.Type });
switch (context.op.Type)
{
case ConditionParser.OP_LT:
result = Expression.Call(method, Expression.Constant(CompareOp.Lt), left, right);
break;
case ConditionParser.OP_LE:
result = Expression.Call(method, Expression.Constant(CompareOp.Le), left, right);
break;
case ConditionParser.OP_GT:
result = Expression.Call(method, Expression.Constant(CompareOp.Gt), left, right);
break;
case ConditionParser.OP_GE:
result = Expression.Call(method, Expression.Constant(CompareOp.Ge), left, right);
break;
default:
throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Unrecognized op token: {0}", context.op.Text));
}
}
else
{
result = UndefinedExpression;
}
return result;
}
public override Expression VisitEquality(ConditionParser.EqualityContext context)
{
Expression result;
Expression left = this.Visit(context.left);
Expression right = this.Visit(context.right);
if (this.CheckOperands(context.op, left.Type, ref left, ref right))
{
MethodInfo method = typeof(ComparisonOperators).GetMethod("Compare", new[] { typeof(CompareOp), left.Type, right.Type });
switch (context.op.Type)
{
case ConditionParser.OP_EQ:
result = Expression.Call(method, Expression.Constant(CompareOp.Eq), left, right);
break;
case ConditionParser.OP_NE1:
case ConditionParser.OP_NE2:
result = Expression.Call(method, Expression.Constant(CompareOp.Ne), left, right);
break;
default:
throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Unrecognized op token: {0}", context.op.Text));
}
}
else
{
result = UndefinedExpression;
}
return result;
}
public override Expression VisitAnd(ConditionParser.AndContext context)
{
Expression left = this.Visit(context.left);
Expression right = this.Visit(context.right);
Type type = left.Type == typeof(Null) || right.Type == typeof(Null) ? typeof(Null) : typeof(Bool);
return this.CheckBooleanOperands(context.op, ref left, ref right)
? Expression.Convert(Expression.And(left, right), type)
: UndefinedExpression;
}
public override Expression VisitOr(ConditionParser.OrContext context)
{
Expression left = this.Visit(context.left);
Expression right = this.Visit(context.right);
Type type = left.Type == typeof(Null) && right.Type == typeof(Null) ? typeof(Null) : typeof(Bool);
return this.CheckBooleanOperands(context.op, ref left, ref right)
? Expression.Convert(Expression.Or(left, right), type)
: UndefinedExpression;
}
public override Expression VisitCoalesce(ConditionParser.CoalesceContext context)
{
Expression result;
Expression left = this.Visit(context.left);
Expression right = this.Visit(context.right);
if (this.CheckOperands(context.op, left.Type, ref left, ref right))
{
Expression isDefined = Expression.Convert(this.GetBuiltin("is_defined", context.op, left), typeof(bool));
result = left.Type != typeof(Undefined) ? Expression.Condition(isDefined, left, right) : right;
}
else
{
result = UndefinedExpression;
}
return result;
}
public override Expression VisitNested(ConditionParser.NestedContext context)
{
return this.Visit(context.nested_expr().expr());
}
public override Expression VisitEof(ConditionParser.EofContext context)
{
return UndefinedExpression;
}
// Errors
public override Expression VisitSyntaxError(ConditionParser.SyntaxErrorContext context)
{
this.errors.UnrecognizedSymbolError(context.token.UNKNOWN_CHAR().Symbol);
return UndefinedExpression;
}
public override Expression VisitSyntaxErrorUnaryOp(ConditionParser.SyntaxErrorUnaryOpContext context)
{
this.errors.UnrecognizedSymbolError(context.token.UNKNOWN_CHAR().Symbol);
return UndefinedExpression;
}
public override Expression VisitSyntaxErrorBinaryOp(ConditionParser.SyntaxErrorBinaryOpContext context)
{
this.errors.UnrecognizedSymbolError(context.token.UNKNOWN_CHAR().Symbol);
return UndefinedExpression;
}
public override Expression VisitSyntaxErrorExtraParens(ConditionParser.SyntaxErrorExtraParensContext context)
{
this.errors.SyntaxError(context.paren, "unmatched closing ')'");
return UndefinedExpression;
}
public override Expression VisitSyntaxErrorExtraParensFunc(ConditionParser.SyntaxErrorExtraParensFuncContext context)
{
this.errors.SyntaxError(context.paren, "unmatched closing ')'");
return UndefinedExpression;
}
public override Expression VisitSyntaxErrorMissingParen(ConditionParser.SyntaxErrorMissingParenContext context)
{
this.errors.SyntaxError(context.paren, "missing closing ')'");
return UndefinedExpression;
}
public override Expression VisitUnterminatedString(ConditionParser.UnterminatedStringContext context)
{
this.errors.SyntaxError(context.UNTERMINATED_STRING().Symbol, "unterminated string");
// strip the leading quote in order to escape the contents of the string
string input = context.GetText().Substring(1);
string value = Unescape(input);
return Expression.Constant(value);
}
static string Unescape(string input)
{
string result1 = Regex.Replace(input, @"\\[Uu]([0-9A-Fa-f]{4})", m => char.ToString((char)ushort.Parse(m.Groups[1].Value, NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture)));
string result2 = Regex.Replace(result1, @"\\([""'\\])", m => m.Groups[1].Value);
return result2;
}
Expression GetBuiltin(string name, IToken token, params Expression[] args)
{
IBuiltin builtin;
if (!this.TryGetSupportedBuiltin(name, out builtin))
{
this.errors.InvalidBuiltinError(token);
return UndefinedExpression;
}
else
{
return builtin.Get(token, args, null, this.errors);
}
}
bool TryGetSupportedBuiltin(string name, out IBuiltin builtin)
{
return Builtins.TryGetValue(name, out builtin) &&
builtin.IsEnabled(this.routeCompilerFlags) &&
builtin.IsValidMessageSource(this.route.Source);
}
bool CheckOperand(IToken token, Type expected, Expression expr)
{
var required = new Args(expected);
Type[] given = new[] { expr.Type };
bool isValid = required.Match(given, true);
if (!isValid)
{
this.errors.OperandError(token, required, given);
}
return isValid;
}
bool CheckOperands(IToken token, Type expected, ref Expression left, ref Expression right)
{
var required = new Args(expected, expected);
Type[] given = new[] { left.Type, right.Type };
bool isValid = required.Match(given, true);
if (!isValid)
{
this.errors.OperandError(token, required, given);
}
if (left.Type == typeof(QueryValue) && right.Type != typeof(QueryValue))
{
right = Expression.Convert(right, typeof(QueryValue));
}
if (right.Type == typeof(QueryValue) && left.Type != typeof(QueryValue))
{
left = Expression.Convert(left, typeof(QueryValue));
}
return isValid;
}
bool CheckBooleanOperands(IToken token, ref Expression left, ref Expression right)
{
bool leftValid = left.Type == typeof(Null) || left.Type == typeof(Bool) || left.Type == typeof(Undefined) || left.Type == typeof(QueryValue);
bool rightValid = right.Type == typeof(Null) || right.Type == typeof(Bool) || right.Type == typeof(Undefined) || left.Type == typeof(QueryValue);
bool isValid = leftValid && rightValid;
if (!isValid)
{
var required = new Args(typeof(Bool), typeof(Bool));
Type[] given = new[] { left.Type, right.Type };
this.errors.OperandError(token, required, given);
}
if (left.Type == typeof(QueryValue) && right.Type != typeof(QueryValue))
{
right = Expression.Convert(right, typeof(QueryValue));
}
if (right.Type == typeof(QueryValue) && left.Type != typeof(QueryValue))
{
left = Expression.Convert(left, typeof(QueryValue));
}
return isValid;
}
bool IsBodyQueryExpression(string query, IToken token, out Expression queryValueExpression)
{
const string BodyQueryPrefix = "$body.";
queryValueExpression = UndefinedExpression;
if (query.StartsWith(BodyQueryPrefix, StringComparison.OrdinalIgnoreCase))
{
var bodyQueryBuiltin = new BodyQuery();
if (bodyQueryBuiltin.IsEnabled(this.routeCompilerFlags))
{
string bodyQuery = query.Substring(BodyQueryPrefix.Length);
var args = new Expression[]
{
Expression.Constant(bodyQuery)
};
var contextArgs = new Expression[]
{
this.message,
Expression.Constant(this.route)
};
queryValueExpression = bodyQueryBuiltin.Get(token, args, contextArgs, this.errors);
return true;
}
}
return false;
}
}
}
| 41.952998 | 198 | 0.578404 | [
"MIT"
] | DaveEM/iotedge | edge-hub/src/Microsoft.Azure.Devices.Routing.Core/query/ConditionVisitor.cs | 25,885 | C# |
// ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by EntityNetwork CodeGenerator.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.Serialization;
using System.Linq;
using System.Text;
using EntityNetwork;
using TrackableData;
using ProtoBuf;
using TypeAlias;
using System.ComponentModel;
#region IBullet
namespace Domain
{
[PayloadTableForEntity(typeof(IBullet))]
public static class IBullet_PayloadTable
{
public static Type[] GetPayloadTypes()
{
return new Type[] {
typeof(Hit_Invoke),
};
}
[ProtoContract, TypeAlias]
public class Hit_Invoke : IInvokePayload
{
[ProtoMember(1), DefaultValue(0f)] public float x = 0f;
[ProtoMember(2), DefaultValue(0f)] public float y = 0f;
public PayloadFlags Flags { get { return 0; } }
public void InvokeServer(IEntityServerHandler target)
{
((IBulletServerHandler)target).OnHit(x, y);
}
public void InvokeClient(IEntityClientHandler target)
{
((IBulletClientHandler)target).OnHit(x, y);
}
}
}
public interface IBulletServerHandler : IEntityServerHandler
{
void OnHit(float x = 0f, float y = 0f);
}
public abstract class BulletServerBase : ServerEntity
{
public override int TrackableDataCount { get { return 0; } }
public override ITrackable GetTrackableData(int index)
{
return null;
}
public override void SetTrackableData(int index, ITrackable trackable)
{
}
public void Hit(float x = 0f, float y = 0f)
{
var payload = new IBullet_PayloadTable.Hit_Invoke { x = x, y = y };
SendInvoke(payload);
}
}
public interface IBulletClientHandler : IEntityClientHandler
{
void OnHit(float x = 0f, float y = 0f);
}
public abstract class BulletClientBase : ClientEntity
{
public override int TrackableDataCount { get { return 0; } }
public override ITrackable GetTrackableData(int index)
{
return null;
}
public override void SetTrackableData(int index, ITrackable trackable)
{
}
public void Hit(float x = 0f, float y = 0f)
{
var payload = new IBullet_PayloadTable.Hit_Invoke { x = x, y = y };
SendInvoke(payload);
}
}
}
#endregion
#region ISpaceShip
namespace Domain
{
[PayloadTableForEntity(typeof(ISpaceShip))]
public static class ISpaceShip_PayloadTable
{
public static Type[] GetPayloadTypes()
{
return new Type[] {
typeof(Hit_Invoke),
typeof(Move_Invoke),
typeof(Say_Invoke),
typeof(Shoot_Invoke),
typeof(Stop_Invoke),
};
}
[ProtoContract, TypeAlias]
public class Hit_Invoke : IInvokePayload
{
[ProtoMember(1), DefaultValue(0f)] public float x = 0f;
[ProtoMember(2), DefaultValue(0f)] public float y = 0f;
public PayloadFlags Flags { get { return PayloadFlags.ToServer; } }
public void InvokeServer(IEntityServerHandler target)
{
}
public void InvokeClient(IEntityClientHandler target)
{
((ISpaceShipClientHandler)target).OnHit(x, y);
}
}
[ProtoContract, TypeAlias]
public class Move_Invoke : IInvokePayload
{
[ProtoMember(1)] public float x;
[ProtoMember(2)] public float y;
[ProtoMember(3)] public float dx;
[ProtoMember(4)] public float dy;
public PayloadFlags Flags { get { return PayloadFlags.PassThrough; } }
public void InvokeServer(IEntityServerHandler target)
{
}
public void InvokeClient(IEntityClientHandler target)
{
((ISpaceShipClientHandler)target).OnMove(x, y, dx, dy);
}
}
[ProtoContract, TypeAlias]
public class Say_Invoke : IInvokePayload
{
[ProtoMember(1)] public string msg;
public PayloadFlags Flags { get { return 0; } }
public void InvokeServer(IEntityServerHandler target)
{
((ISpaceShipServerHandler)target).OnSay(msg);
}
public void InvokeClient(IEntityClientHandler target)
{
((ISpaceShipClientHandler)target).OnSay(msg);
}
}
[ProtoContract, TypeAlias]
public class Shoot_Invoke : IInvokePayload
{
[ProtoMember(1)] public float x;
[ProtoMember(2)] public float y;
[ProtoMember(3)] public float dx;
[ProtoMember(4)] public float dy;
public PayloadFlags Flags { get { return PayloadFlags.ToClient; } }
public void InvokeServer(IEntityServerHandler target)
{
((ISpaceShipServerHandler)target).OnShoot(x, y, dx, dy);
}
public void InvokeClient(IEntityClientHandler target)
{
}
}
[ProtoContract, TypeAlias]
public class Stop_Invoke : IInvokePayload
{
[ProtoMember(1)] public float x;
[ProtoMember(2)] public float y;
public PayloadFlags Flags { get { return PayloadFlags.PassThrough; } }
public void InvokeServer(IEntityServerHandler target)
{
}
public void InvokeClient(IEntityClientHandler target)
{
((ISpaceShipClientHandler)target).OnStop(x, y);
}
}
[ProtoContract, TypeAlias]
public class Spawn : ISpawnPayload
{
[ProtoMember(1)] public TrackableSpaceShipData Data;
[ProtoMember(2)] public SpaceShipSnapshot Snapshot;
public void Gather(IServerEntity entity)
{
var e = (SpaceShipServerBase)entity;
Data = e.Data;
Snapshot = e.OnSnapshot();
}
public void Notify(IClientEntity entity)
{
var e = (SpaceShipClientBase)entity;
e.Data = Data;
e.OnSnapshot(Snapshot);
}
}
[ProtoContract, TypeAlias]
public class UpdateChange : IUpdateChangePayload
{
[ProtoMember(1)] public TrackablePocoTracker<ISpaceShipData> DataTracker;
public void Gather(IServerEntity entity)
{
var e = (SpaceShipServerBase)entity;
if (e.Data.Changed)
{
DataTracker = (TrackablePocoTracker<ISpaceShipData>)e.Data.Tracker;
}
}
public void Notify(IClientEntity entity)
{
var e = (SpaceShipClientBase)entity;
if (DataTracker != null)
{
e.OnTrackableDataChanging(0, DataTracker);
DataTracker.ApplyTo(e.Data);
e.OnTrackableDataChanged(0, DataTracker);
}
}
}
}
public interface ISpaceShipServerHandler : IEntityServerHandler
{
void OnSay(string msg);
void OnShoot(float x, float y, float dx, float dy);
}
public abstract class SpaceShipServerBase : ServerEntity
{
public TrackableSpaceShipData Data { get; set; }
protected SpaceShipServerBase()
{
Data = new TrackableSpaceShipData();
}
public override object Snapshot { get { return OnSnapshot(); } }
public abstract SpaceShipSnapshot OnSnapshot();
public override int TrackableDataCount { get { return 1; } }
public override ITrackable GetTrackableData(int index)
{
if (index == 0) return Data;
return null;
}
public override void SetTrackableData(int index, ITrackable trackable)
{
if (index == 0) Data = (TrackableSpaceShipData)trackable;
}
public override ISpawnPayload GetSpawnPayload()
{
var payload = new ISpaceShip_PayloadTable.Spawn();
payload.Gather(this);
return payload;
}
public override IUpdateChangePayload GetUpdateChangePayload()
{
var payload = new ISpaceShip_PayloadTable.UpdateChange();
payload.Gather(this);
return payload;
}
public void Hit(float x = 0f, float y = 0f)
{
var payload = new ISpaceShip_PayloadTable.Hit_Invoke { x = x, y = y };
SendInvoke(payload);
}
public void Move(float x, float y, float dx, float dy)
{
var payload = new ISpaceShip_PayloadTable.Move_Invoke { x = x, y = y, dx = dx, dy = dy };
SendInvoke(payload);
}
public void Say(string msg)
{
var payload = new ISpaceShip_PayloadTable.Say_Invoke { msg = msg };
SendInvoke(payload);
}
public void Stop(float x, float y)
{
var payload = new ISpaceShip_PayloadTable.Stop_Invoke { x = x, y = y };
SendInvoke(payload);
}
}
public interface ISpaceShipClientHandler : IEntityClientHandler
{
void OnHit(float x = 0f, float y = 0f);
void OnMove(float x, float y, float dx, float dy);
void OnSay(string msg);
void OnStop(float x, float y);
}
public abstract class SpaceShipClientBase : ClientEntity
{
public TrackableSpaceShipData Data { get; set; }
protected SpaceShipClientBase()
{
Data = new TrackableSpaceShipData();
}
public override object Snapshot { set { OnSnapshot((SpaceShipSnapshot)value); } }
public abstract void OnSnapshot(SpaceShipSnapshot snapshot);
public override int TrackableDataCount { get { return 1; } }
public override ITrackable GetTrackableData(int index)
{
if (index == 0) return Data;
return null;
}
public override void SetTrackableData(int index, ITrackable trackable)
{
if (index == 0) Data = (TrackableSpaceShipData)trackable;
}
public void Move(float x, float y, float dx, float dy)
{
var payload = new ISpaceShip_PayloadTable.Move_Invoke { x = x, y = y, dx = dx, dy = dy };
SendInvoke(payload);
}
public void Say(string msg)
{
var payload = new ISpaceShip_PayloadTable.Say_Invoke { msg = msg };
SendInvoke(payload);
}
public void Shoot(float x, float y, float dx, float dy)
{
var payload = new ISpaceShip_PayloadTable.Shoot_Invoke { x = x, y = y, dx = dx, dy = dy };
SendInvoke(payload);
}
public void Stop(float x, float y)
{
var payload = new ISpaceShip_PayloadTable.Stop_Invoke { x = x, y = y };
SendInvoke(payload);
}
}
}
#endregion
| 29.2925 | 102 | 0.555603 | [
"MIT"
] | SaladLab/EntityNetwork | samples/Unity/Domain/Properties/EntityNetwork.CodeGen.cs | 11,719 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GlobalHost.Modelo
{
class Login
{
private int id;
private string usuario;
private string senha;
private int nivel;
public Login()
{
}
public Login(int id, string usuario, string senha, int nivel)
{
this.id = id;
this.usuario = usuario;
this.senha = senha;
this.nivel = nivel;
}
public Login(string usuario, string senha, int nivel)
{
this.usuario = usuario;
this.senha = senha;
this.nivel = nivel;
}
public int Id { get => id; set => id = value; }
public string Usuario { get => usuario; set => usuario = value; }
public string Senha { get => senha; set => senha = value; }
public int Nivel { get => nivel; set => nivel = value; }
public override string ToString()
{
return this.usuario;
}
}
}
| 23.804348 | 73 | 0.534247 | [
"MIT"
] | Krauzy/GlobalHost | GlobalHost/GlobalHost/Modelo/Login.cs | 1,097 | C# |
using System;
using System.Threading.Tasks;
using Autofac;
using Common.Log;
using JetBrains.Annotations;
using Lykke.Common.Log;
using Lykke.Job.MarketProfile.Domain.Services;
using Lykke.Job.QuotesProducer.Contract;
using Lykke.RabbitMqBroker;
using Lykke.RabbitMqBroker.Subscriber;
namespace Lykke.Job.MarketProfile.RabbitMqSubscribers
{
[UsedImplicitly]
public class QuotesSubscriber : IStartable, IDisposable
{
private readonly string _connectionString;
private readonly string _exchangeName;
private readonly string _queueSuffix;
private readonly IAssetPairsCacheService _cacheService;
private readonly ILogFactory _logFactory;
private readonly ILog _log;
private RabbitMqSubscriber<QuoteMessage> _subscriber;
public QuotesSubscriber(
string connectionString,
string exchangeName,
string queueSuffix,
IAssetPairsCacheService cacheService,
ILogFactory logFactory)
{
_connectionString = connectionString;
_exchangeName = exchangeName;
_queueSuffix = queueSuffix;
_cacheService = cacheService;
_logFactory = logFactory;
_log = logFactory.CreateLog(this);
}
public void Start()
{
try
{
var settings = RabbitMqSubscriptionSettings
.ForSubscriber(_connectionString, "lykke", _exchangeName, "lykke", $"marketprofilejob{_queueSuffix}");
_subscriber = new RabbitMqSubscriber<QuoteMessage>(_logFactory, settings,
new ResilientErrorHandlingStrategy(_logFactory, settings,
retryTimeout: TimeSpan.FromSeconds(10),
retryNum: 10,
next: new DeadQueueErrorHandlingStrategy(_logFactory, settings)))
.SetMessageDeserializer(new JsonMessageDeserializer<QuoteMessage>())
.SetMessageReadStrategy(new MessageReadQueueStrategy())
.Subscribe(ProcessQuote)
.CreateDefaultBinding()
.Start();
}
catch (Exception ex)
{
_log.Error(ex);
throw;
}
}
private async Task ProcessQuote(QuoteMessage entry)
{
try
{
await _cacheService.UpdatePairAsync(entry);
}
catch (Exception ex)
{
_log.Error(ex);
}
}
public void Dispose()
{
_subscriber?.Stop();
}
}
}
| 32.73494 | 122 | 0.5841 | [
"MIT"
] | LykkeCity/Lykke.Job.MarketProfile | src/Lykke.Job.MarketProfile/RabbitMqSubscribers/QuotesSubscriber.cs | 2,717 | C# |
using System;
using System.Text;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using PasswordVault.Data;
using PasswordVault.Services;
using PasswordVault.Models;
using PasswordVault.Desktop.Winforms;
namespace PasswordVault.ServicesTests
{
/// <summary>
/// Summary description for PasswordServiceTests
/// </summary>
[TestClass]
public class PasswordServiceTests
{
IDatabase db;
IDesktopServiceWrapper passwordService;
AddUserResult createUserResult;
AuthenticateResult loginResult;
LogOutResult logoutResult;
User user;
public PasswordServiceTests()
{
}
private TestContext testContextInstance;
/// <summary>
///Gets or sets the test context which provides
///information about and functionality for the current test run.
///</summary>
public TestContext TestContext
{
get
{
return testContextInstance;
}
set
{
testContextInstance = value;
}
}
#region Additional test attributes
//
// You can use the following additional attributes as you write your tests:
//
// Use ClassInitialize to run code before running the first test in the class
// [ClassInitialize()]
// public static void MyClassInitialize(TestContext testContext) { }
//
// Use ClassCleanup to run code after all tests in a class have run
// [ClassCleanup()]
// public static void MyClassCleanup() { }
[TestInitialize()]
public void MyTestInitialize()
{
db = DatabaseFactory.GetDatabase(Database.InMemory);
passwordService = DesktopPasswordServiceBuilder.BuildDesktopServiceWrapper(db);
user = new User("testAccount", "testPassword1@aaaaaaaaa", "testFirstName", "testLastName", "222-111-1111", "test@test.com");
createUserResult = passwordService.CreateNewUser(user);
Assert.AreEqual(AddUserResult.Successful, createUserResult);
Assert.AreEqual(1, ((InMemoryDatabase)db).LocalUserDbAccess.Count);
}
// Use TestCleanup to run code after each test has run
// [TestCleanup()]
// public void MyTestCleanup() { }
//
#endregion
[TestMethod]
public void GetCurrentUserTest()
{
loginResult = passwordService.Login("testAccount", "testPassword1@aaaaaaaaa");
Assert.AreEqual(AuthenticateResult.Successful, loginResult);
User user = passwordService.GetCurrentUser();
Assert.AreEqual("testAccount", user.Username);
Assert.AreEqual("testFirstName", user.FirstName);
Assert.AreEqual("testLastName", user.LastName);
Assert.AreEqual("222-111-1111", user.PhoneNumber);
Assert.AreEqual("test@test.com", user.Email);
Assert.AreEqual(true, user.ValidUser);
logoutResult = passwordService.Logout();
Assert.AreEqual(LogOutResult.Success, logoutResult);
user = passwordService.GetCurrentUser();
Assert.AreEqual(false, user.ValidUser);
}
[TestMethod]
public void GetCurrentUserNameTest()
{
loginResult = passwordService.Login("testAccount", "testPassword1@aaaaaaaaa");
Assert.AreEqual(AuthenticateResult.Successful, loginResult);
string username = passwordService.GetCurrentUsername();
Assert.AreEqual("testAccount", username);
logoutResult = passwordService.Logout();
Assert.AreEqual(LogOutResult.Success, logoutResult);
username = passwordService.GetCurrentUsername();
Assert.AreEqual("", username);
}
[TestMethod]
public void VerifyCurrentUserPasswordTest()
{
loginResult = passwordService.Login("testAccount", "testPassword1@aaaaaaaaa");
Assert.AreEqual(AuthenticateResult.Successful, loginResult);
bool verifyResult;
verifyResult = passwordService.VerifyCurrentUserPassword("testPassword1@aaaaaaaaa");
Assert.AreEqual(true, verifyResult);
verifyResult = passwordService.VerifyCurrentUserPassword("testPassword1");
Assert.AreEqual(false, verifyResult);
verifyResult = passwordService.VerifyCurrentUserPassword("");
Assert.AreEqual(false, verifyResult);
verifyResult = passwordService.VerifyCurrentUserPassword(null);
Assert.AreEqual(false, verifyResult);
logoutResult = passwordService.Logout();
Assert.AreEqual(LogOutResult.Success, logoutResult);
verifyResult = passwordService.VerifyCurrentUserPassword("testPassword1");
Assert.AreEqual(false, verifyResult);
}
[TestMethod]
public void GeneratePasswordKeyTest()
{
string passphrase = passwordService.GeneratePassword();
Assert.AreEqual(20, passphrase.Length);
}
[TestMethod]
public void GetMinimumPasswordTest()
{
var num = passwordService.GetMinimumPasswordLength();
Assert.AreEqual(15, num);
}
}
}
| 34.870968 | 136 | 0.631637 | [
"Apache-2.0"
] | willem445/PasswordVault | PasswordVault.ServicesTests/PasswordServiceTests.cs | 5,407 | C# |
// 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 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.StreamAnalytics
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Serialization;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
/// <summary>
/// Composite Swagger for Stream Analytics Client
/// </summary>
public partial class StreamAnalyticsManagementClient : ServiceClient<StreamAnalyticsManagementClient>, IStreamAnalyticsManagementClient, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Credentials needed for the client to connect to Azure.
/// </summary>
public ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// GUID which uniquely identify Microsoft Azure subscription. The subscription
/// ID forms part of the URI for every service call.
/// </summary>
public string SubscriptionId { get; set; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running Operations.
/// Default value is 30.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// When set to true a unique x-ms-client-request-id value is generated and
/// included in each request. Default is true.
/// </summary>
public bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Gets the IOperations.
/// </summary>
public virtual IOperations Operations { get; private set; }
/// <summary>
/// Gets the IStreamingJobsOperations.
/// </summary>
public virtual IStreamingJobsOperations StreamingJobs { get; private set; }
/// <summary>
/// Gets the IInputsOperations.
/// </summary>
public virtual IInputsOperations Inputs { get; private set; }
/// <summary>
/// Gets the IOutputsOperations.
/// </summary>
public virtual IOutputsOperations Outputs { get; private set; }
/// <summary>
/// Gets the ITransformationsOperations.
/// </summary>
public virtual ITransformationsOperations Transformations { get; private set; }
/// <summary>
/// Gets the IFunctionsOperations.
/// </summary>
public virtual IFunctionsOperations Functions { get; private set; }
/// <summary>
/// Gets the ISubscriptionsOperations.
/// </summary>
public virtual ISubscriptionsOperations Subscriptions { get; private set; }
/// <summary>
/// Initializes a new instance of the StreamAnalyticsManagementClient class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected StreamAnalyticsManagementClient(params DelegatingHandler[] handlers) : base(handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the StreamAnalyticsManagementClient class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected StreamAnalyticsManagementClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the StreamAnalyticsManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected StreamAnalyticsManagementClient(System.Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the StreamAnalyticsManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected StreamAnalyticsManagementClient(System.Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the StreamAnalyticsManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public StreamAnalyticsManagementClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the StreamAnalyticsManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public StreamAnalyticsManagementClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the StreamAnalyticsManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public StreamAnalyticsManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the StreamAnalyticsManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public StreamAnalyticsManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// An optional partial-method to perform custom initialization.
/// </summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
Operations = new Operations(this);
StreamingJobs = new StreamingJobsOperations(this);
Inputs = new InputsOperations(this);
Outputs = new OutputsOperations(this);
Transformations = new TransformationsOperations(this);
Functions = new FunctionsOperations(this);
Subscriptions = new SubscriptionsOperations(this);
BaseUri = new System.Uri("https://management.azure.com");
AcceptLanguage = "en-US";
LongRunningOperationRetryTimeout = 30;
GenerateClientRequestId = true;
SerializationSettings = new JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
SerializationSettings.Converters.Add(new TransformationJsonConverter());
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<Serialization>("type"));
DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<Serialization>("type"));
SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<InputProperties>("type"));
DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<InputProperties>("type"));
SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<OutputDataSource>("type"));
DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<OutputDataSource>("type"));
SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<FunctionProperties>("type"));
DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<FunctionProperties>("type"));
SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<StreamInputDataSource>("type"));
DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<StreamInputDataSource>("type"));
SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<ReferenceInputDataSource>("type"));
DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<ReferenceInputDataSource>("type"));
SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<FunctionBinding>("type"));
DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<FunctionBinding>("type"));
SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<FunctionRetrieveDefaultDefinitionParameters>("bindingType"));
DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<FunctionRetrieveDefaultDefinitionParameters>("bindingType"));
CustomInitialize();
DeserializationSettings.Converters.Add(new TransformationJsonConverter());
DeserializationSettings.Converters.Add(new CloudErrorJsonConverter());
}
}
}
| 43.643052 | 202 | 0.618218 | [
"MIT"
] | azure-keyvault/azure-sdk-for-net | src/SDKs/StreamAnalytics/Management.StreamAnalytics/Generated/StreamAnalyticsManagementClient.cs | 16,017 | C# |
using Dynamo.UI.Commands;
using System.Collections.ObjectModel;
using System.Windows.Controls;
using Dynamo.Updates;
using Microsoft.Practices.Prism.ViewModel;
namespace Dynamo.UI.Controls
{
/// <summary>
/// Interaction logic for ShortcutToolbar.xaml
/// </summary>
public partial class ShortcutToolbar : UserControl
{
private ObservableCollection<ShortcutBarItem> shortcutBarItems;
public ObservableCollection<ShortcutBarItem> ShortcutBarItems
{
get { return shortcutBarItems; }
}
private ObservableCollection<ShortcutBarItem> shortcutBarRightSideItems;
public ObservableCollection<ShortcutBarItem> ShortcutBarRightSideItems
{
get { return shortcutBarRightSideItems; }
}
public ShortcutToolbar(IUpdateManager updateManager)
{
shortcutBarItems = new ObservableCollection<ShortcutBarItem>();
shortcutBarRightSideItems = new ObservableCollection<ShortcutBarItem>();
InitializeComponent();
this.UpdateControl.DataContext = updateManager;
}
}
public partial class ShortcutBarItem : NotificationObject
{
private string shortcutToolTip;
private string imgNormalSource;
private string imgHoverSource;
private string imgDisabledSource;
private DelegateCommand shortcutCommand;
private string shortcutCommandParameter;
public string ShortcutCommandParameter
{
get { return shortcutCommandParameter; }
set { shortcutCommandParameter = value; }
}
public DelegateCommand ShortcutCommand
{
get { return shortcutCommand; }
set { shortcutCommand = value; }
}
public string ImgDisabledSource
{
get { return imgDisabledSource; }
set { imgDisabledSource = value; }
}
public string ImgHoverSource
{
get { return imgHoverSource; }
set { imgHoverSource = value; }
}
public string ImgNormalSource
{
get { return imgNormalSource; }
set { imgNormalSource = value; }
}
public string ShortcutToolTip
{
get { return shortcutToolTip; }
set { shortcutToolTip = value; }
}
}
}
| 28.879518 | 88 | 0.629537 | [
"Apache-2.0",
"MIT"
] | frankfralick/Dynamo | src/DynamoCoreWpf/Controls/ShortcutToolbar.xaml.cs | 2,399 | 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.Media.Inputs
{
/// <summary>
/// Select video tracks from the input by specifying a track identifier.
/// </summary>
public sealed class SelectVideoTrackByIdArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The discriminator for derived types.
/// Expected value is '#Microsoft.Media.SelectVideoTrackById'.
/// </summary>
[Input("odataType", required: true)]
public Input<string> OdataType { get; set; } = null!;
/// <summary>
/// Track identifier to select
/// </summary>
[Input("trackId", required: true)]
public Input<double> TrackId { get; set; } = null!;
public SelectVideoTrackByIdArgs()
{
}
}
}
| 29.611111 | 81 | 0.631332 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/Media/Inputs/SelectVideoTrackByIdArgs.cs | 1,066 | C# |
//<unit_header>
//----------------------------------------------------------------
//
// Martin Korneffel: IT Beratung/Softwareentwicklung
// Stuttgart, den 6.4.2017
//
// Projekt.......: mko.RPN.Arithmetik
// Name..........: IFunctionNames.cs
// Aufgabe/Fkt...: Definiert die Funktionsnamen. Die Bennenung kann so von
// dem Gebrauch in Algorithmen getrennt werden
//
//
//
//
//<unit_environment>
//------------------------------------------------------------------
// Zielmaschine..: PC
// Betriebssystem: Windows 7 mit .NET 4.5
// Werkzeuge.....: Visual Studio 2013
// Autor.........: Martin Korneffel (mko)
// Version 1.0...:
//
// </unit_environment>
//
//<unit_history>
//------------------------------------------------------------------
//
// Version.......: 1.1
// Autor.........: Martin Korneffel (mko)
// Datum.........:
// Änderungen....:
//
//</unit_history>
//</unit_header>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace mko.RPN.Arithmetik
{
public interface IFunctionNames
{
string ADD { get; }
string SUB { get; }
string MUL { get; }
string DIV { get; }
/// <summary>
/// Akkumulation/Aufsummation einer Reihe
/// </summary>
string SUMAT { get; }
}
}
| 23.62069 | 75 | 0.5 | [
"MIT"
] | mk-prg-net/mk-prg-net.lib | mko.RPN.Arithmetik/IFunctionNames.cs | 1,373 | 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/dwrite_1.h in the Windows SDK for Windows 10.0.19041.0
// Original source is Copyright © Microsoft. All rights reserved.
namespace TerraFX.Interop
{
public enum DWRITE_PANOSE_ARM_STYLE
{
DWRITE_PANOSE_ARM_STYLE_ANY = 0,
DWRITE_PANOSE_ARM_STYLE_NO_FIT = 1,
DWRITE_PANOSE_ARM_STYLE_STRAIGHT_ARMS_HORIZONTAL = 2,
DWRITE_PANOSE_ARM_STYLE_STRAIGHT_ARMS_WEDGE = 3,
DWRITE_PANOSE_ARM_STYLE_STRAIGHT_ARMS_VERTICAL = 4,
DWRITE_PANOSE_ARM_STYLE_STRAIGHT_ARMS_SINGLE_SERIF = 5,
DWRITE_PANOSE_ARM_STYLE_STRAIGHT_ARMS_DOUBLE_SERIF = 6,
DWRITE_PANOSE_ARM_STYLE_NONSTRAIGHT_ARMS_HORIZONTAL = 7,
DWRITE_PANOSE_ARM_STYLE_NONSTRAIGHT_ARMS_WEDGE = 8,
DWRITE_PANOSE_ARM_STYLE_NONSTRAIGHT_ARMS_VERTICAL = 9,
DWRITE_PANOSE_ARM_STYLE_NONSTRAIGHT_ARMS_SINGLE_SERIF = 10,
DWRITE_PANOSE_ARM_STYLE_NONSTRAIGHT_ARMS_DOUBLE_SERIF = 11,
DWRITE_PANOSE_ARM_STYLE_STRAIGHT_ARMS_HORZ = DWRITE_PANOSE_ARM_STYLE_STRAIGHT_ARMS_HORIZONTAL,
DWRITE_PANOSE_ARM_STYLE_STRAIGHT_ARMS_VERT = DWRITE_PANOSE_ARM_STYLE_STRAIGHT_ARMS_VERTICAL,
DWRITE_PANOSE_ARM_STYLE_BENT_ARMS_HORZ = DWRITE_PANOSE_ARM_STYLE_NONSTRAIGHT_ARMS_HORIZONTAL,
DWRITE_PANOSE_ARM_STYLE_BENT_ARMS_WEDGE = DWRITE_PANOSE_ARM_STYLE_NONSTRAIGHT_ARMS_WEDGE,
DWRITE_PANOSE_ARM_STYLE_BENT_ARMS_VERT = DWRITE_PANOSE_ARM_STYLE_NONSTRAIGHT_ARMS_VERTICAL,
DWRITE_PANOSE_ARM_STYLE_BENT_ARMS_SINGLE_SERIF = DWRITE_PANOSE_ARM_STYLE_NONSTRAIGHT_ARMS_SINGLE_SERIF,
DWRITE_PANOSE_ARM_STYLE_BENT_ARMS_DOUBLE_SERIF = DWRITE_PANOSE_ARM_STYLE_NONSTRAIGHT_ARMS_DOUBLE_SERIF,
}
}
| 58.483871 | 145 | 0.813017 | [
"MIT"
] | Ethereal77/terrafx.interop.windows | sources/Interop/Windows/um/dwrite_1/DWRITE_PANOSE_ARM_STYLE.cs | 1,815 | C# |
using System;
using UnityEngine;
using UnityEngine.Events;
namespace Signals.Common
{
[Serializable]
public class Vector2IntEvent : UnityEvent<Vector2Int> { }
}
| 17 | 61 | 0.758824 | [
"MIT"
] | jheiling/unity-signals | Common/Scripts/Vector2IntEvent.cs | 170 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace NuGet.Server.Core.Infrastructure
{
public interface ISettingsProvider
{
bool GetBoolSetting(string key, bool defaultValue);
string GetStringSetting(string key, string defaultValue);
int GetIntSetting(string key, int defaultValue);
}
}
| 37.5 | 112 | 0.733333 | [
"ECL-2.0",
"Apache-2.0"
] | 563256676/test2 | src/NuGet.Server.Core/Infrastructure/ISettingsProvider.cs | 452 | C# |
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Ocuda.Ops.Data.ServiceFacade;
using Ocuda.Ops.Models.Entities;
using Ocuda.Ops.Service.Interfaces.Ops.Repositories;
namespace Ocuda.Ops.Data.Ops
{
public class EmailTemplateTextRepository
: GenericRepository<OpsContext, EmailTemplateText>, IEmailTemplateTextRepository
{
public EmailTemplateTextRepository(Repository<OpsContext> repositoryFacade,
ILogger<EmailTemplateTextRepository> logger) : base(repositoryFacade, logger)
{
}
public async Task<EmailTemplateText> GetByIdLanguageAsync(int emailTemplateId,
string languageName)
{
return await DbSet
.Where(_ => _.EmailTemplateId == emailTemplateId
&& _.PromenadeLanguageName == languageName)
.Select(_ => new EmailTemplateText
{
EmailTemplateId = _.EmailTemplateId,
TemplateHtml = _.TemplateHtml,
TemplateText = _.TemplateText
})
.AsNoTracking()
.SingleOrDefaultAsync();
}
}
}
| 34.416667 | 89 | 0.637611 | [
"MIT"
] | MCLD/ocuda | src/Ops.Data/Ops/EmailTemplateTextRepository.cs | 1,241 | C# |
using System;
using System.Diagnostics;
using NBitcoin.BouncyCastle.Math.Raw;
using NBitcoin.BouncyCastle.Utilities;
namespace NBitcoin.BouncyCastle.Math.EC
{
internal abstract class ECFieldElement
{
public abstract BigInteger ToBigInteger();
public abstract string FieldName
{
get;
}
public abstract int FieldSize
{
get;
}
public abstract ECFieldElement Add(ECFieldElement b);
public abstract ECFieldElement AddOne();
public abstract ECFieldElement Subtract(ECFieldElement b);
public abstract ECFieldElement Multiply(ECFieldElement b);
public abstract ECFieldElement Divide(ECFieldElement b);
public abstract ECFieldElement Negate();
public abstract ECFieldElement Square();
public abstract ECFieldElement Invert();
public abstract ECFieldElement Sqrt();
public virtual int BitLength
{
get
{
return ToBigInteger().BitLength;
}
}
public virtual bool IsOne
{
get
{
return this.BitLength == 1;
}
}
public virtual bool IsZero
{
get
{
return 0 == ToBigInteger().SignValue;
}
}
public virtual ECFieldElement MultiplyMinusProduct(ECFieldElement b, ECFieldElement x, ECFieldElement y)
{
return Multiply(b).Subtract(x.Multiply(y));
}
public virtual ECFieldElement MultiplyPlusProduct(ECFieldElement b, ECFieldElement x, ECFieldElement y)
{
return Multiply(b).Add(x.Multiply(y));
}
public virtual ECFieldElement SquareMinusProduct(ECFieldElement x, ECFieldElement y)
{
return Square().Subtract(x.Multiply(y));
}
public virtual ECFieldElement SquarePlusProduct(ECFieldElement x, ECFieldElement y)
{
return Square().Add(x.Multiply(y));
}
public virtual ECFieldElement SquarePow(int pow)
{
ECFieldElement r = this;
for(int i = 0; i < pow; ++i)
{
r = r.Square();
}
return r;
}
public virtual bool TestBitZero()
{
return ToBigInteger().TestBit(0);
}
public override bool Equals(object obj)
{
return Equals(obj as ECFieldElement);
}
public virtual bool Equals(ECFieldElement other)
{
if(this == other)
return true;
if(null == other)
return false;
return ToBigInteger().Equals(other.ToBigInteger());
}
public override int GetHashCode()
{
return ToBigInteger().GetHashCode();
}
public override string ToString()
{
return ToBigInteger().ToString(16);
}
public virtual byte[] GetEncoded()
{
return BigIntegers.AsUnsignedByteArray((this.FieldSize + 7) / 8, ToBigInteger());
}
}
internal class FpFieldElement
: ECFieldElement
{
private readonly BigInteger q, r, x;
internal static BigInteger CalculateResidue(BigInteger p)
{
int bitLength = p.BitLength;
if(bitLength >= 96)
{
BigInteger firstWord = p.ShiftRight(bitLength - 64);
if(firstWord.LongValue == -1L)
{
return BigInteger.One.ShiftLeft(bitLength).Subtract(p);
}
if((bitLength & 7) == 0)
{
return BigInteger.One.ShiftLeft(bitLength << 1).Divide(p).Negate();
}
}
return null;
}
[Obsolete("Use ECCurve.FromBigInteger to construct field elements")]
public FpFieldElement(BigInteger q, BigInteger x)
: this(q, CalculateResidue(q), x)
{
}
internal FpFieldElement(BigInteger q, BigInteger r, BigInteger x)
{
if(x == null || x.SignValue < 0 || x.CompareTo(q) >= 0)
throw new ArgumentException("value invalid in Fp field element", "x");
this.q = q;
this.r = r;
this.x = x;
}
public override BigInteger ToBigInteger()
{
return this.x;
}
/**
* return the field name for this field.
*
* @return the string "Fp".
*/
public override string FieldName
{
get
{
return "Fp";
}
}
public override int FieldSize
{
get
{
return this.q.BitLength;
}
}
public BigInteger Q
{
get
{
return this.q;
}
}
public override ECFieldElement Add(
ECFieldElement b)
{
return new FpFieldElement(this.q, this.r, ModAdd(this.x, b.ToBigInteger()));
}
public override ECFieldElement AddOne()
{
BigInteger x2 = this.x.Add(BigInteger.One);
if(x2.CompareTo(this.q) == 0)
{
x2 = BigInteger.Zero;
}
return new FpFieldElement(this.q, this.r, x2);
}
public override ECFieldElement Subtract(
ECFieldElement b)
{
return new FpFieldElement(this.q, this.r, ModSubtract(this.x, b.ToBigInteger()));
}
public override ECFieldElement Multiply(
ECFieldElement b)
{
return new FpFieldElement(this.q, this.r, ModMult(this.x, b.ToBigInteger()));
}
public override ECFieldElement MultiplyMinusProduct(ECFieldElement b, ECFieldElement x, ECFieldElement y)
{
BigInteger ax = this.x, bx = b.ToBigInteger(), xx = x.ToBigInteger(), yx = y.ToBigInteger();
BigInteger ab = ax.Multiply(bx);
BigInteger xy = xx.Multiply(yx);
return new FpFieldElement(this.q, this.r, ModReduce(ab.Subtract(xy)));
}
public override ECFieldElement MultiplyPlusProduct(ECFieldElement b, ECFieldElement x, ECFieldElement y)
{
BigInteger ax = this.x, bx = b.ToBigInteger(), xx = x.ToBigInteger(), yx = y.ToBigInteger();
BigInteger ab = ax.Multiply(bx);
BigInteger xy = xx.Multiply(yx);
BigInteger sum = ab.Add(xy);
if(this.r != null && this.r.SignValue < 0 && sum.BitLength > (this.q.BitLength << 1))
{
sum = sum.Subtract(this.q.ShiftLeft(this.q.BitLength));
}
return new FpFieldElement(this.q, this.r, ModReduce(sum));
}
public override ECFieldElement Divide(
ECFieldElement b)
{
return new FpFieldElement(this.q, this.r, ModMult(this.x, ModInverse(b.ToBigInteger())));
}
public override ECFieldElement Negate()
{
return this.x.SignValue == 0 ? this : new FpFieldElement(this.q, this.r, this.q.Subtract(this.x));
}
public override ECFieldElement Square()
{
return new FpFieldElement(this.q, this.r, ModMult(this.x, this.x));
}
public override ECFieldElement SquareMinusProduct(ECFieldElement x, ECFieldElement y)
{
BigInteger ax = this.x, xx = x.ToBigInteger(), yx = y.ToBigInteger();
BigInteger aa = ax.Multiply(ax);
BigInteger xy = xx.Multiply(yx);
return new FpFieldElement(this.q, this.r, ModReduce(aa.Subtract(xy)));
}
public override ECFieldElement SquarePlusProduct(ECFieldElement x, ECFieldElement y)
{
BigInteger ax = this.x, xx = x.ToBigInteger(), yx = y.ToBigInteger();
BigInteger aa = ax.Multiply(ax);
BigInteger xy = xx.Multiply(yx);
BigInteger sum = aa.Add(xy);
if(this.r != null && this.r.SignValue < 0 && sum.BitLength > (this.q.BitLength << 1))
{
sum = sum.Subtract(this.q.ShiftLeft(this.q.BitLength));
}
return new FpFieldElement(this.q, this.r, ModReduce(sum));
}
public override ECFieldElement Invert()
{
// TODO Modular inversion can be faster for a (Generalized) Mersenne Prime.
return new FpFieldElement(this.q, this.r, ModInverse(this.x));
}
/**
* return a sqrt root - the routine verifies that the calculation
* returns the right value - if none exists it returns null.
*/
public override ECFieldElement Sqrt()
{
if(this.IsZero || this.IsOne)
return this;
if(!this.q.TestBit(0))
throw Platform.CreateNotImplementedException("even value of q");
if(this.q.TestBit(1)) // q == 4m + 3
{
BigInteger e = this.q.ShiftRight(2).Add(BigInteger.One);
return CheckSqrt(new FpFieldElement(this.q, this.r, this.x.ModPow(e, this.q)));
}
if(this.q.TestBit(2)) // q == 8m + 5
{
BigInteger t1 = this.x.ModPow(this.q.ShiftRight(3), this.q);
BigInteger t2 = ModMult(t1, this.x);
BigInteger t3 = ModMult(t2, t1);
if(t3.Equals(BigInteger.One))
{
return CheckSqrt(new FpFieldElement(this.q, this.r, t2));
}
// TODO This is constant and could be precomputed
BigInteger t4 = BigInteger.Two.ModPow(this.q.ShiftRight(2), this.q);
BigInteger y = ModMult(t2, t4);
return CheckSqrt(new FpFieldElement(this.q, this.r, y));
}
// q == 8m + 1
BigInteger legendreExponent = this.q.ShiftRight(1);
if(!(this.x.ModPow(legendreExponent, this.q).Equals(BigInteger.One)))
return null;
BigInteger X = this.x;
BigInteger fourX = ModDouble(ModDouble(X));
;
BigInteger k = legendreExponent.Add(BigInteger.One), qMinusOne = this.q.Subtract(BigInteger.One);
BigInteger U, V;
do
{
BigInteger P;
do
{
P = BigInteger.Arbitrary(this.q.BitLength);
}
while(P.CompareTo(this.q) >= 0
|| !ModReduce(P.Multiply(P).Subtract(fourX)).ModPow(legendreExponent, this.q).Equals(qMinusOne));
BigInteger[] result = LucasSequence(P, X, k);
U = result[0];
V = result[1];
if(ModMult(V, V).Equals(fourX))
{
return new FpFieldElement(this.q, this.r, ModHalfAbs(V));
}
}
while(U.Equals(BigInteger.One) || U.Equals(qMinusOne));
return null;
}
private ECFieldElement CheckSqrt(ECFieldElement z)
{
return z.Square().Equals(this) ? z : null;
}
private BigInteger[] LucasSequence(
BigInteger P,
BigInteger Q,
BigInteger k)
{
// TODO Research and apply "common-multiplicand multiplication here"
int n = k.BitLength;
int s = k.GetLowestSetBit();
Debug.Assert(k.TestBit(s));
BigInteger Uh = BigInteger.One;
BigInteger Vl = BigInteger.Two;
BigInteger Vh = P;
BigInteger Ql = BigInteger.One;
BigInteger Qh = BigInteger.One;
for(int j = n - 1; j >= s + 1; --j)
{
Ql = ModMult(Ql, Qh);
if(k.TestBit(j))
{
Qh = ModMult(Ql, Q);
Uh = ModMult(Uh, Vh);
Vl = ModReduce(Vh.Multiply(Vl).Subtract(P.Multiply(Ql)));
Vh = ModReduce(Vh.Multiply(Vh).Subtract(Qh.ShiftLeft(1)));
}
else
{
Qh = Ql;
Uh = ModReduce(Uh.Multiply(Vl).Subtract(Ql));
Vh = ModReduce(Vh.Multiply(Vl).Subtract(P.Multiply(Ql)));
Vl = ModReduce(Vl.Multiply(Vl).Subtract(Ql.ShiftLeft(1)));
}
}
Ql = ModMult(Ql, Qh);
Qh = ModMult(Ql, Q);
Uh = ModReduce(Uh.Multiply(Vl).Subtract(Ql));
Vl = ModReduce(Vh.Multiply(Vl).Subtract(P.Multiply(Ql)));
Ql = ModMult(Ql, Qh);
for(int j = 1; j <= s; ++j)
{
Uh = ModMult(Uh, Vl);
Vl = ModReduce(Vl.Multiply(Vl).Subtract(Ql.ShiftLeft(1)));
Ql = ModMult(Ql, Ql);
}
return new BigInteger[] { Uh, Vl };
}
protected virtual BigInteger ModAdd(BigInteger x1, BigInteger x2)
{
BigInteger x3 = x1.Add(x2);
if(x3.CompareTo(this.q) >= 0)
{
x3 = x3.Subtract(this.q);
}
return x3;
}
protected virtual BigInteger ModDouble(BigInteger x)
{
BigInteger _2x = x.ShiftLeft(1);
if(_2x.CompareTo(this.q) >= 0)
{
_2x = _2x.Subtract(this.q);
}
return _2x;
}
protected virtual BigInteger ModHalf(BigInteger x)
{
if(x.TestBit(0))
{
x = this.q.Add(x);
}
return x.ShiftRight(1);
}
protected virtual BigInteger ModHalfAbs(BigInteger x)
{
if(x.TestBit(0))
{
x = this.q.Subtract(x);
}
return x.ShiftRight(1);
}
protected virtual BigInteger ModInverse(BigInteger x)
{
int bits = this.FieldSize;
int len = (bits + 31) >> 5;
uint[] p = Nat.FromBigInteger(bits, this.q);
uint[] n = Nat.FromBigInteger(bits, x);
uint[] z = Nat.Create(len);
Mod.Invert(p, n, z);
return Nat.ToBigInteger(len, z);
}
protected virtual BigInteger ModMult(BigInteger x1, BigInteger x2)
{
return ModReduce(x1.Multiply(x2));
}
protected virtual BigInteger ModReduce(BigInteger x)
{
if(this.r == null)
{
x = x.Mod(this.q);
}
else
{
bool negative = x.SignValue < 0;
if(negative)
{
x = x.Abs();
}
int qLen = this.q.BitLength;
if(this.r.SignValue > 0)
{
BigInteger qMod = BigInteger.One.ShiftLeft(qLen);
bool rIsOne = this.r.Equals(BigInteger.One);
while(x.BitLength > (qLen + 1))
{
BigInteger u = x.ShiftRight(qLen);
BigInteger v = x.Remainder(qMod);
if(!rIsOne)
{
u = u.Multiply(this.r);
}
x = u.Add(v);
}
}
else
{
int d = ((qLen - 1) & 31) + 1;
BigInteger mu = this.r.Negate();
BigInteger u = mu.Multiply(x.ShiftRight(qLen - d));
BigInteger quot = u.ShiftRight(qLen + d);
BigInteger v = quot.Multiply(this.q);
BigInteger bk1 = BigInteger.One.ShiftLeft(qLen + d);
v = v.Remainder(bk1);
x = x.Remainder(bk1);
x = x.Subtract(v);
if(x.SignValue < 0)
{
x = x.Add(bk1);
}
}
while(x.CompareTo(this.q) >= 0)
{
x = x.Subtract(this.q);
}
if(negative && x.SignValue != 0)
{
x = this.q.Subtract(x);
}
}
return x;
}
protected virtual BigInteger ModSubtract(BigInteger x1, BigInteger x2)
{
BigInteger x3 = x1.Subtract(x2);
if(x3.SignValue < 0)
{
x3 = x3.Add(this.q);
}
return x3;
}
public override bool Equals(
object obj)
{
if(obj == this)
return true;
var other = obj as FpFieldElement;
if(other == null)
return false;
return Equals(other);
}
public virtual bool Equals(
FpFieldElement other)
{
return this.q.Equals(other.q) && base.Equals(other);
}
public override int GetHashCode()
{
return this.q.GetHashCode() ^ base.GetHashCode();
}
}
/**
* Class representing the Elements of the finite field
* <code>F<sub>2<sup>m</sup></sub></code> in polynomial basis (PB)
* representation. Both trinomial (Tpb) and pentanomial (Ppb) polynomial
* basis representations are supported. Gaussian normal basis (GNB)
* representation is not supported.
*/
internal class F2mFieldElement
: ECFieldElement
{
/**
* Indicates gaussian normal basis representation (GNB). Number chosen
* according to X9.62. GNB is not implemented at present.
*/
public const int Gnb = 1;
/**
* Indicates trinomial basis representation (Tpb). Number chosen
* according to X9.62.
*/
public const int Tpb = 2;
/**
* Indicates pentanomial basis representation (Ppb). Number chosen
* according to X9.62.
*/
public const int Ppb = 3;
/**
* Tpb or Ppb.
*/
private int representation;
/**
* The exponent <code>m</code> of <code>F<sub>2<sup>m</sup></sub></code>.
*/
private int m;
private int[] ks;
/**
* The <code>LongArray</code> holding the bits.
*/
private LongArray x;
/**
* Constructor for Ppb.
* @param m The exponent <code>m</code> of
* <code>F<sub>2<sup>m</sup></sub></code>.
* @param k1 The integer <code>k1</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.
* @param k2 The integer <code>k2</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.
* @param k3 The integer <code>k3</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.
* @param x The BigInteger representing the value of the field element.
*/
public F2mFieldElement(
int m,
int k1,
int k2,
int k3,
BigInteger x)
{
if(x == null || x.SignValue < 0 || x.BitLength > m)
throw new ArgumentException("value invalid in F2m field element", "x");
if((k2 == 0) && (k3 == 0))
{
this.representation = Tpb;
this.ks = new int[] { k1 };
}
else
{
if(k2 >= k3)
throw new ArgumentException("k2 must be smaller than k3");
if(k2 <= 0)
throw new ArgumentException("k2 must be larger than 0");
this.representation = Ppb;
this.ks = new int[] { k1, k2, k3 };
}
this.m = m;
this.x = new LongArray(x);
}
/**
* Constructor for Tpb.
* @param m The exponent <code>m</code> of
* <code>F<sub>2<sup>m</sup></sub></code>.
* @param k The integer <code>k</code> where <code>x<sup>m</sup> +
* x<sup>k</sup> + 1</code> represents the reduction
* polynomial <code>f(z)</code>.
* @param x The BigInteger representing the value of the field element.
*/
public F2mFieldElement(
int m,
int k,
BigInteger x)
: this(m, k, 0, 0, x)
{
// Set k1 to k, and set k2 and k3 to 0
}
private F2mFieldElement(int m, int[] ks, LongArray x)
{
this.m = m;
this.representation = (ks.Length == 1) ? Tpb : Ppb;
this.ks = ks;
this.x = x;
}
public override int BitLength
{
get
{
return this.x.Degree();
}
}
public override bool IsOne
{
get
{
return this.x.IsOne();
}
}
public override bool IsZero
{
get
{
return this.x.IsZero();
}
}
public override bool TestBitZero()
{
return this.x.TestBitZero();
}
public override BigInteger ToBigInteger()
{
return this.x.ToBigInteger();
}
public override string FieldName
{
get
{
return "F2m";
}
}
public override int FieldSize
{
get
{
return this.m;
}
}
/**
* Checks, if the ECFieldElements <code>a</code> and <code>b</code>
* are elements of the same field <code>F<sub>2<sup>m</sup></sub></code>
* (having the same representation).
* @param a field element.
* @param b field element to be compared.
* @throws ArgumentException if <code>a</code> and <code>b</code>
* are not elements of the same field
* <code>F<sub>2<sup>m</sup></sub></code> (having the same
* representation).
*/
public static void CheckFieldElements(
ECFieldElement a,
ECFieldElement b)
{
if(!(a is F2mFieldElement) || !(b is F2mFieldElement))
{
throw new ArgumentException("Field elements are not "
+ "both instances of F2mFieldElement");
}
var aF2m = (F2mFieldElement)a;
var bF2m = (F2mFieldElement)b;
if(aF2m.representation != bF2m.representation)
{
// Should never occur
throw new ArgumentException("One of the F2m field elements has incorrect representation");
}
if((aF2m.m != bF2m.m) || !Arrays.AreEqual(aF2m.ks, bF2m.ks))
{
throw new ArgumentException("Field elements are not elements of the same field F2m");
}
}
public override ECFieldElement Add(
ECFieldElement b)
{
// No check performed here for performance reasons. Instead the
// elements involved are checked in ECPoint.F2m
// checkFieldElements(this, b);
LongArray iarrClone = this.x.Copy();
var bF2m = (F2mFieldElement)b;
iarrClone.AddShiftedByWords(bF2m.x, 0);
return new F2mFieldElement(this.m, this.ks, iarrClone);
}
public override ECFieldElement AddOne()
{
return new F2mFieldElement(this.m, this.ks, this.x.AddOne());
}
public override ECFieldElement Subtract(
ECFieldElement b)
{
// Addition and subtraction are the same in F2m
return Add(b);
}
public override ECFieldElement Multiply(
ECFieldElement b)
{
// Right-to-left comb multiplication in the LongArray
// Input: Binary polynomials a(z) and b(z) of degree at most m-1
// Output: c(z) = a(z) * b(z) mod f(z)
// No check performed here for performance reasons. Instead the
// elements involved are checked in ECPoint.F2m
// checkFieldElements(this, b);
return new F2mFieldElement(this.m, this.ks, this.x.ModMultiply(((F2mFieldElement)b).x, this.m, this.ks));
}
public override ECFieldElement MultiplyMinusProduct(ECFieldElement b, ECFieldElement x, ECFieldElement y)
{
return MultiplyPlusProduct(b, x, y);
}
public override ECFieldElement MultiplyPlusProduct(ECFieldElement b, ECFieldElement x, ECFieldElement y)
{
LongArray ax = this.x, bx = ((F2mFieldElement)b).x, xx = ((F2mFieldElement)x).x, yx = ((F2mFieldElement)y).x;
LongArray ab = ax.Multiply(bx, this.m, this.ks);
LongArray xy = xx.Multiply(yx, this.m, this.ks);
if(ab == ax || ab == bx)
{
ab = (LongArray)ab.Copy();
}
ab.AddShiftedByWords(xy, 0);
ab.Reduce(this.m, this.ks);
return new F2mFieldElement(this.m, this.ks, ab);
}
public override ECFieldElement Divide(
ECFieldElement b)
{
// There may be more efficient implementations
ECFieldElement bInv = b.Invert();
return Multiply(bInv);
}
public override ECFieldElement Negate()
{
// -x == x holds for all x in F2m
return this;
}
public override ECFieldElement Square()
{
return new F2mFieldElement(this.m, this.ks, this.x.ModSquare(this.m, this.ks));
}
public override ECFieldElement SquareMinusProduct(ECFieldElement x, ECFieldElement y)
{
return SquarePlusProduct(x, y);
}
public override ECFieldElement SquarePlusProduct(ECFieldElement x, ECFieldElement y)
{
LongArray ax = this.x, xx = ((F2mFieldElement)x).x, yx = ((F2mFieldElement)y).x;
LongArray aa = ax.Square(this.m, this.ks);
LongArray xy = xx.Multiply(yx, this.m, this.ks);
if(aa == ax)
{
aa = (LongArray)aa.Copy();
}
aa.AddShiftedByWords(xy, 0);
aa.Reduce(this.m, this.ks);
return new F2mFieldElement(this.m, this.ks, aa);
}
public override ECFieldElement SquarePow(int pow)
{
return pow < 1 ? this : new F2mFieldElement(this.m, this.ks, this.x.ModSquareN(pow, this.m, this.ks));
}
public override ECFieldElement Invert()
{
return new F2mFieldElement(this.m, this.ks, this.x.ModInverse(this.m, this.ks));
}
public override ECFieldElement Sqrt()
{
return (this.x.IsZero() || this.x.IsOne()) ? this : SquarePow(this.m - 1);
}
/**
* @return the representation of the field
* <code>F<sub>2<sup>m</sup></sub></code>, either of
* {@link F2mFieldElement.Tpb} (trinomial
* basis representation) or
* {@link F2mFieldElement.Ppb} (pentanomial
* basis representation).
*/
public int Representation
{
get
{
return this.representation;
}
}
/**
* @return the degree <code>m</code> of the reduction polynomial
* <code>f(z)</code>.
*/
public int M
{
get
{
return this.m;
}
}
/**
* @return Tpb: The integer <code>k</code> where <code>x<sup>m</sup> +
* x<sup>k</sup> + 1</code> represents the reduction polynomial
* <code>f(z)</code>.<br/>
* Ppb: The integer <code>k1</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.<br/>
*/
public int K1
{
get
{
return this.ks[0];
}
}
/**
* @return Tpb: Always returns <code>0</code><br/>
* Ppb: The integer <code>k2</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.<br/>
*/
public int K2
{
get
{
return this.ks.Length >= 2 ? this.ks[1] : 0;
}
}
/**
* @return Tpb: Always set to <code>0</code><br/>
* Ppb: The integer <code>k3</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.<br/>
*/
public int K3
{
get
{
return this.ks.Length >= 3 ? this.ks[2] : 0;
}
}
public override bool Equals(
object obj)
{
if(obj == this)
return true;
var other = obj as F2mFieldElement;
if(other == null)
return false;
return Equals(other);
}
public virtual bool Equals(
F2mFieldElement other)
{
return ((this.m == other.m)
&& (this.representation == other.representation)
&& Arrays.AreEqual(this.ks, other.ks)
&& (this.x.Equals(other.x)));
}
public override int GetHashCode()
{
return this.x.GetHashCode() ^ this.m ^ Arrays.GetHashCode(this.ks);
}
}
}
| 31.175992 | 121 | 0.488416 | [
"MIT"
] | 0tim0/StratisFullNode | src/NBitcoin/BouncyCastle/math/ec/ECFieldElement.cs | 30,646 | C# |
using Gum.Collections;
using Pretune;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using M = Gum.CompileTime;
namespace Gum.IR0Translator
{
[ImplementIEquatable]
partial class InternalModuleClassInfo : IModuleClassInfo
{
M.Name name;
ImmutableArray<string> typeParams;
M.Type? baseType;
ImmutableArray<M.Type> interfaceTypes;
ImmutableArray<IModuleTypeInfo> types;
ImmutableArray<IModuleFuncInfo> funcs;
ImmutableArray<IModuleConstructorInfo> constructors;
IModuleConstructorInfo? autoConstructor;
ImmutableArray<IModuleMemberVarInfo> memberVars;
ModuleTypeDict typeDict;
ModuleFuncDict funcDict;
public InternalModuleClassInfo(
M.Name name, ImmutableArray<string> typeParams,
M.Type? baseType,
ImmutableArray<M.Type> interfaceTypes,
IEnumerable<IModuleTypeInfo> types,
IEnumerable<IModuleFuncInfo> funcs,
ImmutableArray<IModuleConstructorInfo> constructors,
IModuleConstructorInfo? autoConstructor,
ImmutableArray<IModuleMemberVarInfo> memberVars)
{
this.name = name;
this.typeParams = typeParams;
this.baseType = baseType;
this.types = types.ToImmutableArray();
this.funcs = funcs.ToImmutableArray();
this.constructors = constructors;
this.autoConstructor = autoConstructor;
this.memberVars = memberVars;
this.typeDict = new ModuleTypeDict(types);
this.funcDict = new ModuleFuncDict(funcs);
}
IModuleConstructorInfo? IModuleClassInfo.GetAutoConstructor()
{
return autoConstructor;
}
M.Type? IModuleClassInfo.GetBaseType()
{
return baseType;
}
ImmutableArray<IModuleConstructorInfo> IModuleClassInfo.GetConstructors()
{
return constructors;
}
IModuleFuncInfo? IModuleFuncContainer.GetFunc(M.Name name, int typeParamCount, M.ParamTypes paramTypes)
{
return funcDict.Get(name, typeParamCount, paramTypes);
}
ImmutableArray<IModuleFuncInfo> IModuleFuncContainer.GetFuncs(M.Name name, int minTypeParamCount)
{
return funcDict.Get(name, minTypeParamCount);
}
ImmutableArray<IModuleFuncInfo> IModuleClassInfo.GetMemberFuncs()
{
return funcs;
}
ImmutableArray<IModuleTypeInfo> IModuleClassInfo.GetMemberTypes()
{
return types;
}
ImmutableArray<IModuleMemberVarInfo> IModuleClassInfo.GetMemberVars()
{
return memberVars;
}
M.Name IModuleItemInfo.GetName()
{
return name;
}
IModuleTypeInfo? IModuleTypeContainer.GetType(M.Name name, int typeParamCount)
{
return typeDict.Get(name, typeParamCount);
}
ImmutableArray<string> IModuleItemInfo.GetTypeParams()
{
return typeParams;
}
}
}
| 30.648148 | 112 | 0.613595 | [
"MIT"
] | ioklo/gum | Src/Gum.IR0Translator/IR0Translator/InternalModuleClassInfo.cs | 3,312 | C# |
namespace Infrastructure
{
using Domain.Repository;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
public static class DependencyInjection
{
private const string Datasource = "database.db";
public static IServiceCollection AddInfrastructureServices(this IServiceCollection services)
{
services.AddTransient<ISensorRepository, SensorRepository>();
services.AddDbContext<SqliteContext>(optionsBuilder =>
{
optionsBuilder
.UseSqlite($"Data Source={Datasource}")
.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
});
return services;
}
}
}
| 31.333333 | 100 | 0.652926 | [
"MIT"
] | Letsafko/TemperatureCaptor | src/Infrastructure/DependencyInjection.cs | 754 | C# |
using Surging.Core.CPlatform.Address;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Surging.Core.CPlatform.Mqtt
{
public class MqttServiceRoute
{
/// <summary>
/// Mqtt服务可用地址。
/// </summary>
public IEnumerable<AddressModel> MqttEndpoint { get; set; }
/// <summary>
/// Mqtt服务描述符。
/// </summary>
public MqttDescriptor MqttDescriptor { get; set; }
#region Equality members
/// <summary>Determines whether the specified object is equal to the current object.</summary>
/// <returns>true if the specified object is equal to the current object; otherwise, false.</returns>
/// <param name="obj">The object to compare with the current object. </param>
public override bool Equals(object obj)
{
var model = obj as MqttServiceRoute;
if (model == null)
return false;
if (obj.GetType() != GetType())
return false;
if (model.MqttDescriptor != MqttDescriptor)
return false;
return model.MqttEndpoint.Count() == MqttEndpoint.Count() && model.MqttEndpoint.All(addressModel => MqttEndpoint.Contains(addressModel));
}
/// <summary>Serves as the default hash function. </summary>
/// <returns>A hash code for the current object.</returns>
public override int GetHashCode()
{
return ToString().GetHashCode();
}
public static bool operator ==(MqttServiceRoute model1, MqttServiceRoute model2)
{
return Equals(model1, model2);
}
public static bool operator != (MqttServiceRoute model1, MqttServiceRoute model2)
{
return !Equals(model1, model2);
}
#endregion Equality members
}
}
| 31.55 | 149 | 0.60169 | [
"MIT"
] | 857593381/surging | src/Surging.Core/Surging.Core.CPlatform/Mqtt/MqttServiceRoute.cs | 1,921 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
namespace Microsoft.Azure.SignalR.Management
{
//used to reduce test time
internal class HealthCheckOption
{
public TimeSpan? CheckInterval { get; set; }
public TimeSpan? RetryInterval { get; set; }
public bool EnabledForSingleEndpoint { get; set; } = false;
}
} | 31.333333 | 101 | 0.7 | [
"MIT"
] | Arash-Sabet/azure-signalr | src/Microsoft.Azure.SignalR.Management/HubInstanceFactories/HealthCheckOptions.cs | 472 | C# |
using System;
using System.Collections.Generic;
using Learning.Models;
using Learning.Repositories;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using RouteAttribute = Microsoft.AspNetCore.Mvc.RouteAttribute;
namespace Learning.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class GameController : ControllerBase
{
private readonly GameRepository _repository = new GameRepository();
//Get api/games
[HttpGet]
public ActionResult<IEnumerable<GameState>> LoadGame()
{
return Ok(_repository.Games);
}
//Get api/games/42
[HttpGet("{id}")]
public ActionResult<GameState> LoadGame(int id)
{
var game = _repository.GetGame(id);
if (game != null)
{
return Ok(game);
}
return new NotFoundResult();
}
// POST api/games
[HttpPost]
public CreatedResult NewGame()
{
var game = _repository.CreateNewGame();
return new CreatedResult($"/api/games/{game.Id}", game);
}
//Delete api/games/42
[HttpDelete("{id}")]
public ActionResult<GameState> Delete(int id)
{
bool deleted = _repository.DeleteGame(id);
if (deleted)
{
return new StatusCodeResult(StatusCodes.Status204NoContent);
}
return new NotFoundResult();
}
}
}
| 24.453125 | 76 | 0.580192 | [
"MIT"
] | PiotrZak/C---learning-set | 10/Learning/Controllers/GameController.cs | 1,567 | C# |
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Newtonsoft.Json;
namespace MangaRipper.Core.Models
{
/// <summary>
/// Configuration for plugins
/// </summary>
public class Configuration : IConfiguration
{
private string ConfigFile
{
get;
}
public Configuration(string path)
{
if (!File.Exists(path))
{
throw new FileNotFoundException("Cannot find config file.", path);
}
ConfigFile = path;
}
public IEnumerable<KeyValuePair<string, object>> FindConfigByPrefix(string prefix)
{
var json = File.ReadAllText(ConfigFile);
var dict = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
return dict.Where(i => i.Key.StartsWith(prefix));
}
}
}
| 25.457143 | 90 | 0.582492 | [
"MIT"
] | 00destroyer/jeff | MangaRipper.Core/Models/Configuration.cs | 893 | C# |
using System.Diagnostics.CodeAnalysis;
using HotChocolate.Language;
using HotChocolate.Language.Visitors;
namespace HotChocolate.Data.Sorting
{
public interface ISortOperationHandler<in TContext>
: ISortOperationHandler
where TContext : ISortVisitorContext
{
bool TryHandleEnter(
TContext context,
ISortField field,
ISortEnumValue? enumValue,
EnumValueNode valueNode,
[NotNullWhen(true)] out ISyntaxVisitorAction? action);
}
}
| 27.578947 | 66 | 0.687023 | [
"MIT"
] | Asshiah/hotchocolate | src/HotChocolate/Data/src/Data/Sorting/Visitor/ISortOperationHandler~1.cs | 524 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.ResourceManager;
namespace Azure.ResourceManager.AppService
{
/// <summary>
/// A Class representing a SiteHybridConnection along with the instance operations that can be performed on it.
/// If you have a <see cref="ResourceIdentifier" /> you can construct a <see cref="SiteHybridConnectionResource" />
/// from an instance of <see cref="ArmClient" /> using the GetSiteHybridConnectionResource method.
/// Otherwise you can get one from its parent resource <see cref="WebSiteResource" /> using the GetSiteHybridConnection method.
/// </summary>
public partial class SiteHybridConnectionResource : ArmResource
{
/// <summary> Generate the resource identifier of a <see cref="SiteHybridConnectionResource"/> instance. </summary>
public static ResourceIdentifier CreateResourceIdentifier(string subscriptionId, string resourceGroupName, string name, string entityName)
{
var resourceId = $"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/hybridconnection/{entityName}";
return new ResourceIdentifier(resourceId);
}
private readonly ClientDiagnostics _siteHybridConnectionWebAppsClientDiagnostics;
private readonly WebAppsRestOperations _siteHybridConnectionWebAppsRestClient;
private readonly RelayServiceConnectionEntityData _data;
/// <summary> Initializes a new instance of the <see cref="SiteHybridConnectionResource"/> class for mocking. </summary>
protected SiteHybridConnectionResource()
{
}
/// <summary> Initializes a new instance of the <see cref = "SiteHybridConnectionResource"/> class. </summary>
/// <param name="client"> The client parameters to use in these operations. </param>
/// <param name="data"> The resource that is the target of operations. </param>
internal SiteHybridConnectionResource(ArmClient client, RelayServiceConnectionEntityData data) : this(client, data.Id)
{
HasData = true;
_data = data;
}
/// <summary> Initializes a new instance of the <see cref="SiteHybridConnectionResource"/> class. </summary>
/// <param name="client"> The client parameters to use in these operations. </param>
/// <param name="id"> The identifier of the resource that is the target of operations. </param>
internal SiteHybridConnectionResource(ArmClient client, ResourceIdentifier id) : base(client, id)
{
_siteHybridConnectionWebAppsClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.AppService", ResourceType.Namespace, Diagnostics);
TryGetApiVersion(ResourceType, out string siteHybridConnectionWebAppsApiVersion);
_siteHybridConnectionWebAppsRestClient = new WebAppsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, siteHybridConnectionWebAppsApiVersion);
#if DEBUG
ValidateResourceId(Id);
#endif
}
/// <summary> Gets the resource type for the operations. </summary>
public static readonly ResourceType ResourceType = "Microsoft.Web/sites/hybridconnection";
/// <summary> Gets whether or not the current instance has data. </summary>
public virtual bool HasData { get; }
/// <summary> Gets the data representing this Feature. </summary>
/// <exception cref="InvalidOperationException"> Throws if there is no data loaded in the current instance. </exception>
public virtual RelayServiceConnectionEntityData Data
{
get
{
if (!HasData)
throw new InvalidOperationException("The current instance does not have data, you must call Get first.");
return _data;
}
}
internal static void ValidateResourceId(ResourceIdentifier id)
{
if (id.ResourceType != ResourceType)
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceType), nameof(id));
}
/// <summary>
/// Description for Gets a hybrid connection configuration by its name.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/hybridconnection/{entityName}
/// Operation Id: WebApps_GetRelayServiceConnection
/// </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual async Task<Response<SiteHybridConnectionResource>> GetAsync(CancellationToken cancellationToken = default)
{
using var scope = _siteHybridConnectionWebAppsClientDiagnostics.CreateScope("SiteHybridConnectionResource.Get");
scope.Start();
try
{
var response = await _siteHybridConnectionWebAppsRestClient.GetRelayServiceConnectionAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken).ConfigureAwait(false);
if (response.Value == null)
throw new RequestFailedException(response.GetRawResponse());
return Response.FromValue(new SiteHybridConnectionResource(Client, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Description for Gets a hybrid connection configuration by its name.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/hybridconnection/{entityName}
/// Operation Id: WebApps_GetRelayServiceConnection
/// </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual Response<SiteHybridConnectionResource> Get(CancellationToken cancellationToken = default)
{
using var scope = _siteHybridConnectionWebAppsClientDiagnostics.CreateScope("SiteHybridConnectionResource.Get");
scope.Start();
try
{
var response = _siteHybridConnectionWebAppsRestClient.GetRelayServiceConnection(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken);
if (response.Value == null)
throw new RequestFailedException(response.GetRawResponse());
return Response.FromValue(new SiteHybridConnectionResource(Client, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Description for Deletes a relay service connection by its name.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/hybridconnection/{entityName}
/// Operation Id: WebApps_DeleteRelayServiceConnection
/// </summary>
/// <param name="waitUntil"> "F:Azure.WaitUntil.Completed" if the method should wait to return until the long-running operation has completed on the service; "F:Azure.WaitUntil.Started" if it should return after starting the operation. For more information on long-running operations, please see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/LongRunningOperations.md"> Azure.Core Long-Running Operation samples</see>. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual async Task<ArmOperation> DeleteAsync(WaitUntil waitUntil, CancellationToken cancellationToken = default)
{
using var scope = _siteHybridConnectionWebAppsClientDiagnostics.CreateScope("SiteHybridConnectionResource.Delete");
scope.Start();
try
{
var response = await _siteHybridConnectionWebAppsRestClient.DeleteRelayServiceConnectionAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken).ConfigureAwait(false);
var operation = new AppServiceArmOperation(response);
if (waitUntil == WaitUntil.Completed)
await operation.WaitForCompletionResponseAsync(cancellationToken).ConfigureAwait(false);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Description for Deletes a relay service connection by its name.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/hybridconnection/{entityName}
/// Operation Id: WebApps_DeleteRelayServiceConnection
/// </summary>
/// <param name="waitUntil"> "F:Azure.WaitUntil.Completed" if the method should wait to return until the long-running operation has completed on the service; "F:Azure.WaitUntil.Started" if it should return after starting the operation. For more information on long-running operations, please see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/LongRunningOperations.md"> Azure.Core Long-Running Operation samples</see>. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual ArmOperation Delete(WaitUntil waitUntil, CancellationToken cancellationToken = default)
{
using var scope = _siteHybridConnectionWebAppsClientDiagnostics.CreateScope("SiteHybridConnectionResource.Delete");
scope.Start();
try
{
var response = _siteHybridConnectionWebAppsRestClient.DeleteRelayServiceConnection(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken);
var operation = new AppServiceArmOperation(response);
if (waitUntil == WaitUntil.Completed)
operation.WaitForCompletionResponse(cancellationToken);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Description for Creates a new hybrid connection configuration (PUT), or updates an existing one (PATCH).
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/hybridconnection/{entityName}
/// Operation Id: WebApps_UpdateRelayServiceConnection
/// </summary>
/// <param name="data"> Details of the hybrid connection configuration. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="data"/> is null. </exception>
public virtual async Task<Response<SiteHybridConnectionResource>> UpdateAsync(RelayServiceConnectionEntityData data, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(data, nameof(data));
using var scope = _siteHybridConnectionWebAppsClientDiagnostics.CreateScope("SiteHybridConnectionResource.Update");
scope.Start();
try
{
var response = await _siteHybridConnectionWebAppsRestClient.UpdateRelayServiceConnectionAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, data, cancellationToken).ConfigureAwait(false);
return Response.FromValue(new SiteHybridConnectionResource(Client, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Description for Creates a new hybrid connection configuration (PUT), or updates an existing one (PATCH).
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/hybridconnection/{entityName}
/// Operation Id: WebApps_UpdateRelayServiceConnection
/// </summary>
/// <param name="data"> Details of the hybrid connection configuration. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="data"/> is null. </exception>
public virtual Response<SiteHybridConnectionResource> Update(RelayServiceConnectionEntityData data, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(data, nameof(data));
using var scope = _siteHybridConnectionWebAppsClientDiagnostics.CreateScope("SiteHybridConnectionResource.Update");
scope.Start();
try
{
var response = _siteHybridConnectionWebAppsRestClient.UpdateRelayServiceConnection(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, data, cancellationToken);
return Response.FromValue(new SiteHybridConnectionResource(Client, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
}
}
| 57.260331 | 480 | 0.677347 | [
"MIT"
] | AikoBB/azure-sdk-for-net | sdk/websites/Azure.ResourceManager.AppService/src/Generated/SiteHybridConnectionResource.cs | 13,857 | C# |
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Seventh.DGuard.Domain.Entities;
namespace Seventh.DGuard.Infra.Data.Sql.EntityConfigurations
{
public class RecyclerConfiguration : IEntityTypeConfiguration<Recycler>
{
public void Configure(EntityTypeBuilder<Recycler> builder)
{
builder
.HasKey(x => x.Id);
builder
.Property(x => x.CreatedDate)
.IsRequired();
builder
.Property(x => x.UpdatedDate)
.IsRequired(false);
builder
.OwnsOne(x => x.Status, n =>
{
n.Property(s => s.Id);
n.Property(s => s.Description);
});
}
}
}
| 26.709677 | 75 | 0.530193 | [
"MIT"
] | MateusC/Seventh | Seventh.DGuard/Seventh.DGuard.Infra.Data.Sql/EntityConfigurations/RecyclerConfiguration.cs | 830 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Android.App;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("XFNextEntrySample.Android")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("XFNextEntrySample.Android")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
// Add some common permissions, these can be removed if not needed
[assembly: UsesPermission(Android.Manifest.Permission.Internet)]
[assembly: UsesPermission(Android.Manifest.Permission.WriteExternalStorage)]
| 37.057143 | 84 | 0.759445 | [
"MIT"
] | tsjdev-apps/xf-nextentry-sample | XFNextEntrySample/XFNextEntrySample/XFNextEntrySample.Android/Properties/AssemblyInfo.cs | 1,300 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void MultiplyAdd_Vector64_UInt32()
{
var test = new SimpleTernaryOpTest__MultiplyAdd_Vector64_UInt32();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleTernaryOpTest__MultiplyAdd_Vector64_UInt32
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] inArray3;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle inHandle3;
private GCHandle outHandle;
private ulong alignment;
public DataTable(UInt32[] inArray1, UInt32[] inArray2, UInt32[] inArray3, UInt32[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt32>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt32>();
int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<UInt32>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt32>();
if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.inArray3 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt32, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt32, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<UInt32, byte>(ref inArray3[0]), (uint)sizeOfinArray3);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
inHandle3.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector64<UInt32> _fld1;
public Vector64<UInt32> _fld2;
public Vector64<UInt32> _fld3;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt32>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt32>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<UInt32>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt32>, byte>(ref testStruct._fld3), ref Unsafe.As<UInt32, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector64<UInt32>>());
return testStruct;
}
public void RunStructFldScenario(SimpleTernaryOpTest__MultiplyAdd_Vector64_UInt32 testClass)
{
var result = AdvSimd.MultiplyAdd(_fld1, _fld2, _fld3);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleTernaryOpTest__MultiplyAdd_Vector64_UInt32 testClass)
{
fixed (Vector64<UInt32>* pFld1 = &_fld1)
fixed (Vector64<UInt32>* pFld2 = &_fld2)
fixed (Vector64<UInt32>* pFld3 = &_fld3)
{
var result = AdvSimd.MultiplyAdd(
AdvSimd.LoadVector64((UInt32*)(pFld1)),
AdvSimd.LoadVector64((UInt32*)(pFld2)),
AdvSimd.LoadVector64((UInt32*)(pFld3))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 8;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<UInt32>>() / sizeof(UInt32);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<UInt32>>() / sizeof(UInt32);
private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector64<UInt32>>() / sizeof(UInt32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<UInt32>>() / sizeof(UInt32);
private static UInt32[] _data1 = new UInt32[Op1ElementCount];
private static UInt32[] _data2 = new UInt32[Op2ElementCount];
private static UInt32[] _data3 = new UInt32[Op3ElementCount];
private static Vector64<UInt32> _clsVar1;
private static Vector64<UInt32> _clsVar2;
private static Vector64<UInt32> _clsVar3;
private Vector64<UInt32> _fld1;
private Vector64<UInt32> _fld2;
private Vector64<UInt32> _fld3;
private DataTable _dataTable;
static SimpleTernaryOpTest__MultiplyAdd_Vector64_UInt32()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt32>, byte>(ref _clsVar1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt32>, byte>(ref _clsVar2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<UInt32>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt32>, byte>(ref _clsVar3), ref Unsafe.As<UInt32, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector64<UInt32>>());
}
public SimpleTernaryOpTest__MultiplyAdd_Vector64_UInt32()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt32>, byte>(ref _fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt32>, byte>(ref _fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<UInt32>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt32>, byte>(ref _fld3), ref Unsafe.As<UInt32, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector64<UInt32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetUInt32(); }
_dataTable = new DataTable(_data1, _data2, _data3, new UInt32[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.MultiplyAdd(
Unsafe.Read<Vector64<UInt32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<UInt32>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector64<UInt32>>(_dataTable.inArray3Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.MultiplyAdd(
AdvSimd.LoadVector64((UInt32*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector64((UInt32*)(_dataTable.inArray2Ptr)),
AdvSimd.LoadVector64((UInt32*)(_dataTable.inArray3Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.MultiplyAdd), new Type[] { typeof(Vector64<UInt32>), typeof(Vector64<UInt32>), typeof(Vector64<UInt32>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector64<UInt32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<UInt32>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector64<UInt32>>(_dataTable.inArray3Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.MultiplyAdd), new Type[] { typeof(Vector64<UInt32>), typeof(Vector64<UInt32>), typeof(Vector64<UInt32>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector64((UInt32*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector64((UInt32*)(_dataTable.inArray2Ptr)),
AdvSimd.LoadVector64((UInt32*)(_dataTable.inArray3Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.MultiplyAdd(
_clsVar1,
_clsVar2,
_clsVar3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector64<UInt32>* pClsVar1 = &_clsVar1)
fixed (Vector64<UInt32>* pClsVar2 = &_clsVar2)
fixed (Vector64<UInt32>* pClsVar3 = &_clsVar3)
{
var result = AdvSimd.MultiplyAdd(
AdvSimd.LoadVector64((UInt32*)(pClsVar1)),
AdvSimd.LoadVector64((UInt32*)(pClsVar2)),
AdvSimd.LoadVector64((UInt32*)(pClsVar3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector64<UInt32>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector64<UInt32>>(_dataTable.inArray2Ptr);
var op3 = Unsafe.Read<Vector64<UInt32>>(_dataTable.inArray3Ptr);
var result = AdvSimd.MultiplyAdd(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector64((UInt32*)(_dataTable.inArray1Ptr));
var op2 = AdvSimd.LoadVector64((UInt32*)(_dataTable.inArray2Ptr));
var op3 = AdvSimd.LoadVector64((UInt32*)(_dataTable.inArray3Ptr));
var result = AdvSimd.MultiplyAdd(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleTernaryOpTest__MultiplyAdd_Vector64_UInt32();
var result = AdvSimd.MultiplyAdd(test._fld1, test._fld2, test._fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleTernaryOpTest__MultiplyAdd_Vector64_UInt32();
fixed (Vector64<UInt32>* pFld1 = &test._fld1)
fixed (Vector64<UInt32>* pFld2 = &test._fld2)
fixed (Vector64<UInt32>* pFld3 = &test._fld3)
{
var result = AdvSimd.MultiplyAdd(
AdvSimd.LoadVector64((UInt32*)(pFld1)),
AdvSimd.LoadVector64((UInt32*)(pFld2)),
AdvSimd.LoadVector64((UInt32*)(pFld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.MultiplyAdd(_fld1, _fld2, _fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector64<UInt32>* pFld1 = &_fld1)
fixed (Vector64<UInt32>* pFld2 = &_fld2)
fixed (Vector64<UInt32>* pFld3 = &_fld3)
{
var result = AdvSimd.MultiplyAdd(
AdvSimd.LoadVector64((UInt32*)(pFld1)),
AdvSimd.LoadVector64((UInt32*)(pFld2)),
AdvSimd.LoadVector64((UInt32*)(pFld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.MultiplyAdd(test._fld1, test._fld2, test._fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.MultiplyAdd(
AdvSimd.LoadVector64((UInt32*)(&test._fld1)),
AdvSimd.LoadVector64((UInt32*)(&test._fld2)),
AdvSimd.LoadVector64((UInt32*)(&test._fld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector64<UInt32> op1, Vector64<UInt32> op2, Vector64<UInt32> op3, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray1 = new UInt32[Op1ElementCount];
UInt32[] inArray2 = new UInt32[Op2ElementCount];
UInt32[] inArray3 = new UInt32[Op3ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), op2);
Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray3[0]), op3);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt32>>());
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray1 = new UInt32[Op1ElementCount];
UInt32[] inArray2 = new UInt32[Op2ElementCount];
UInt32[] inArray3 = new UInt32[Op3ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<UInt32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<UInt32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector64<UInt32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt32>>());
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(UInt32[] firstOp, UInt32[] secondOp, UInt32[] thirdOp, UInt32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if (Helpers.MultiplyAdd(firstOp[i], secondOp[i], thirdOp[i]) != result[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.MultiplyAdd)}<UInt32>(Vector64<UInt32>, Vector64<UInt32>, Vector64<UInt32>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})");
TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| 45.93345 | 200 | 0.593259 | [
"MIT"
] | 2m0nd/runtime | src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/MultiplyAdd.Vector64.UInt32.cs | 26,228 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.