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
//------------------------------------------------------------------------------ // <auto-generated /> // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ #region License // Copyright (c) 2007 James Newton-King // // 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. #endregion using System; using System.Collections.Generic; #if !HAVE_LINQ using Datadog.Trace.Vendors.Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; #endif using Datadog.Trace.Vendors.Newtonsoft.Json.Utilities; using System.Collections; namespace Datadog.Trace.Vendors.Newtonsoft.Json.Linq { /// <summary> /// Represents a collection of <see cref="JToken"/> objects. /// </summary> /// <typeparam name="T">The type of token.</typeparam> internal readonly struct JEnumerable<T> : IJEnumerable<T>, IEquatable<JEnumerable<T>> where T : JToken { /// <summary> /// An empty collection of <see cref="JToken"/> objects. /// </summary> public static readonly JEnumerable<T> Empty = new JEnumerable<T>(Enumerable.Empty<T>()); private readonly IEnumerable<T> _enumerable; /// <summary> /// Initializes a new instance of the <see cref="JEnumerable{T}"/> struct. /// </summary> /// <param name="enumerable">The enumerable.</param> public JEnumerable(IEnumerable<T> enumerable) { ValidationUtils.ArgumentNotNull(enumerable, nameof(enumerable)); _enumerable = enumerable; } /// <summary> /// Returns an enumerator that can be used to iterate through the collection. /// </summary> /// <returns> /// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection. /// </returns> public IEnumerator<T> GetEnumerator() { return (_enumerable ?? Empty).GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } /// <summary> /// Gets the <see cref="IJEnumerable{T}"/> of <see cref="JToken"/> with the specified key. /// </summary> /// <value></value> public IJEnumerable<JToken> this[object key] { get { if (_enumerable == null) { return JEnumerable<JToken>.Empty; } return new JEnumerable<JToken>(_enumerable.Values<T, JToken>(key)); } } /// <summary> /// Determines whether the specified <see cref="JEnumerable{T}"/> is equal to this instance. /// </summary> /// <param name="other">The <see cref="JEnumerable{T}"/> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="JEnumerable{T}"/> is equal to this instance; otherwise, <c>false</c>. /// </returns> public bool Equals(JEnumerable<T> other) { return Equals(_enumerable, other._enumerable); } /// <summary> /// Determines whether the specified <see cref="Object"/> is equal to this instance. /// </summary> /// <param name="obj">The <see cref="Object"/> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="Object"/> is equal to this instance; otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) { if (obj is JEnumerable<T> enumerable) { return Equals(enumerable); } return false; } /// <summary> /// Returns a hash code for this instance. /// </summary> /// <returns> /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. /// </returns> public override int GetHashCode() { if (_enumerable == null) { return 0; } return _enumerable.GetHashCode(); } } }
36.472222
122
0.588728
[ "Apache-2.0" ]
ConnectionMaster/dd-trace-dotnet
src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JEnumerable.cs
5,252
C#
using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using FluentValidation; using FluentValidation.Results; using Snorlax.Repository; using Snorlax.Validator; using Snorlax.Web.Api.Models.Request; namespace Snorlax.Web.Api.Validators { public class CategoryPostModelValidator : AbstractValidator<Models.Request.CategoryPostModel>, Validator.IValidator { private readonly ICategoryRepository _categoryRepository; public CategoryPostModelValidator( ICategoryRepository categoryRepository,RequestType requestType) { this._categoryRepository=categoryRepository; RuleFor(m=>m.Name) .NotEmpty() .WithMessage("kategori adı girmelisiniz."); if(requestType==RequestType.POST){ RuleFor(m=>m.Name) .MustAsync(CategoryNameValidAsync) .WithMessage("bu isimde bir kategori zaten ekli"); } } private async Task<bool> CategoryNameValidAsync(string categoryName, CancellationToken cancellationToken) { return !(await _categoryRepository.ExistsByNameAsync(categoryName)); } public ValidatorResult Valid(object obj) { ValidationResult validationResult=base.Validate((Models.Request.CategoryPostModel)obj); return new ValidatorResult(){ IsValid=validationResult.IsValid, Errors=validationResult.Errors.Select(x=>new ErrorModel(){ Code=x.ErrorCode, UserMessage=x.ErrorMessage }).ToList() }; } } }
34.653061
113
0.642521
[ "MIT" ]
furkaandogan/Snorlax
src/Snorlax.Web.Api/Validators/CategoryPostModelValidator.cs
1,699
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; /// <summary> /// Interface for items splitting. /// </summary> public class SplitInterface : MonoBehaviour { [Tooltip("Stack amount of left item")] public InputField leftAmount; // Stack amount of left item [Tooltip("Stack amount of right item")] public InputField rightAmount; // Stack amount of right item [Tooltip("Price game object of left item")] public GameObject leftPrice; // Price GO of left item [Tooltip("Price game object of right item")] public GameObject rightPrice; // Price GO of right item private Text leftPriceText; // Text field of left item's price private Text rightPriceText; // Text field of right item's price private StackItem stackItem; // Current stack item private PriceItem priceItem; // Current price item /// <summary> /// Show/Hide the prices GO. /// </summary> /// <param name="condition">If set to <c>true</c> condition.</param> private void ShowPrices(bool condition) { leftPrice.SetActive(condition); rightPrice.SetActive(condition); } /// <summary> /// Updates the prices using modifier. /// </summary> private void UpdatePrices() { if (priceItem != null) { leftPriceText.text = (GetLeftAmount() * priceItem.GetPrice()).ToString(); rightPriceText.text = (GetRightAmount() * priceItem.GetPrice()).ToString(); } } /// <summary> /// Sets the left stack amount. /// </summary> /// <param name="amount">Amount.</param> private void SetLeftAmount(int amount) { int maxAmount = stackItem.GetStack(); if (amount > maxAmount) { amount = maxAmount; } leftAmount.text = amount.ToString(); // Update right stack amount rightAmount.text = (maxAmount - amount).ToString(); UpdatePrices(); } /// <summary> /// Sets the right stack amount. /// </summary> /// <param name="amount">Amount.</param> private void SetRightAmount(int amount) { int maxAmount = stackItem.GetStack(); if (amount > maxAmount) { amount = maxAmount; } rightAmount.text = amount.ToString(); // Update left stack amount leftAmount.text = (maxAmount - amount).ToString(); UpdatePrices(); } /// <summary> /// Gets the left stack amount. /// </summary> /// <returns>The left amount.</returns> public int GetLeftAmount() { int amount; int.TryParse(leftAmount.text, out amount); return amount; } /// <summary> /// Gets the right stack amount. /// </summary> /// <returns>The right amount.</returns> public int GetRightAmount() { int amount; int.TryParse(rightAmount.text, out amount); return amount; } /// <summary> /// Increases right stack amount. /// </summary> /// <param name="amount">Amount.</param> public void IncreaseAmount(int amount) { int currentAmount = GetRightAmount(); int maxAmount = stackItem.GetStack(); currentAmount += amount; if (currentAmount > maxAmount) { currentAmount = maxAmount; } SetRightAmount(currentAmount); } /// <summary> /// Decreases right stack amount. /// </summary> /// <param name="amount">Amount.</param> public void DecreaseAmount(int amount) { int currentAmount = GetRightAmount(); currentAmount -= amount; if (currentAmount < 0) { currentAmount = 0; } SetRightAmount(currentAmount); } /// <summary> /// Sets max right stack amount. /// </summary> public void SetMaxAmount() { SetRightAmount(stackItem.GetStack()); } /// <summary> /// Sets min right stack amount. /// </summary> public void SetMinAmount() { SetRightAmount(0); } /// <summary> /// Raises the left amount update event. /// </summary> public void OnLeftAmountUpdate() { SetLeftAmount(GetLeftAmount()); } /// <summary> /// Raises the right amount update event. /// </summary> public void OnRightAmountUpdate() { SetRightAmount(GetRightAmount()); } /// <summary> /// Shows split interface. /// </summary> /// <param name="item">Item.</param> /// <param name="price">Price.</param> public void ShowSplitter(StackItem item, PriceItem price) { if (item != null) { // Set interface active gameObject.SetActive(true); Debug.Assert(leftAmount && rightAmount && leftPrice && rightPrice, "Wrong settings"); // Get prices textfield leftPriceText = leftPrice.GetComponentInChildren<Text>(true); rightPriceText = rightPrice.GetComponentInChildren<Text>(true); Debug.Assert(leftPriceText && rightPriceText, "Wrong settings"); stackItem = item; priceItem = price; // Hide prices if no different price groups ShowPrices(priceItem != null); // By default set min stack amount to split SetMinAmount(); } } /// <summary> /// Splits the complete. /// </summary> public void SplitComplete() { gameObject.SetActive(false); } }
24.41206
88
0.668588
[ "MIT" ]
sunaliner/LandRushProject
LandRushUnity/Assets/DaD Inventory/Scripts/Inventory/SplitInterface.cs
4,860
C#
using System; using OpenTK; using OpenTK.Graphics; using osum.Audio; using osum.Graphics; using osum.Graphics.Sprites; using osum.Helpers; namespace osum.GameModes.Play.Components { internal class CountdownDisplay : GameComponent { private pSprite background; private pSprite text; private const float distance_from_bottom = 0; internal event VoidDelegate OnPulse; public override void Initialize() { background = new pSprite(TextureManager.Load(OsuTexture.countdown_background), FieldTypes.StandardSnapCentre, OriginTypes.Centre, ClockTypes.Audio, new Vector2(0, distance_from_bottom), 0.99f, true, Color4.White); spriteManager.Add(background); text = new pSprite(null, FieldTypes.StandardSnapCentre, OriginTypes.Centre, ClockTypes.Audio, new Vector2(0, distance_from_bottom), 1, true, Color4.White); spriteManager.Add(text); spriteManager.Alpha = 0; base.Initialize(); } public override void Dispose() { OnPulse = null; base.Dispose(); } internal int StartTime = -1; private double BeatLength; internal void SetStartTime(int start, double beatLength) { StartTime = start; BeatLength = beatLength; spriteManager.Alpha = 0; HasFinished = false; } internal void Hide() { HasFinished = true; StartTime = -1; spriteManager.Alpha = 0; } internal void SetDisplay(int countdown) { bool didChangeTexture = true; switch (countdown) { case 0: text.Texture = TextureManager.Load(OsuTexture.countdown_go); spriteManager.FadeOut(400); AudioEngine.PlaySample(OsuSamples.countgo); HasFinished = true; break; case 1: text.Texture = TextureManager.Load(OsuTexture.countdown_1); AudioEngine.PlaySample(OsuSamples.count1); break; case 2: text.Texture = TextureManager.Load(OsuTexture.countdown_2); AudioEngine.PlaySample(OsuSamples.count2); break; case 3: text.Texture = TextureManager.Load(OsuTexture.countdown_3); AudioEngine.PlaySample(OsuSamples.count3); break; case 4: case 5: case 6: case 7: text.Texture = TextureManager.Load(OsuTexture.countdown_ready); if (spriteManager.Alpha == 0) spriteManager.FadeIn(200); didChangeTexture = countdown == 7; break; default: return; } if (countdown < 4) { text.Transformations.RemoveAll(t => t is TransformationBounce); background.Transformations.RemoveAll(t => t is TransformationBounce); text.Transform(new TransformationBounce(Clock.AudioTime, Clock.AudioTime + 300, Math.Max(1, text.ScaleScalar), 0.2f, 3)); background.Transform(new TransformationBounce(Clock.AudioTime, Clock.AudioTime + 300, Math.Max(1, background.ScaleScalar), 0.2f, 3)); OnPulse?.Invoke(); } if (didChangeTexture) { pDrawable flash = text.AdditiveFlash(300, 0.5f); flash.Transform(new TransformationF(TransformationType.Scale, 1, 1.2f, Clock.AudioTime, Clock.AudioTime + 400)); flash.Transform(new TransformationF(TransformationType.Rotation, 0, 0.1f, Clock.AudioTime, Clock.AudioTime + 400)); } } private int lastCountdownUpdate = -1; public bool HasFinished = true; public override void Update() { if (StartTime < 0 || (Clock.AudioTime > StartTime && lastCountdownUpdate < 0)) return; if (!HasFinished) { int countdown = (int)Math.Max(0, (StartTime - Clock.AudioTime) / BeatLength); if (countdown != lastCountdownUpdate) { lastCountdownUpdate = countdown; SetDisplay(countdown); } } base.Update(); } } }
35.074627
226
0.534255
[ "MIT" ]
Aikoyori/osu-stream
osu!stream/GameModes/Play/Components/Countdown.cs
4,702
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.AspNetCore.Mvc.ModelBinding.Validation; using Microsoft.AspNetCore.Testing; using Microsoft.Extensions.Localization; using Moq; using Xunit; namespace Microsoft.AspNetCore.Mvc.DataAnnotations { public class RequiredAttributeAdapterTest { [Fact] [ReplaceCulture] public void AddValidation_AddsValidation_Localize() { // Arrange var provider = TestModelMetadataProvider.CreateDefaultProvider(); var metadata = provider.GetMetadataForProperty(typeof(string), "Length"); var attribute = new RequiredAttribute(); var expectedProperties = new object[] { "Length" }; var message = "This parameter is required."; var expectedMessage = "FR This parameter is required."; attribute.ErrorMessage = message; var stringLocalizer = new Mock<IStringLocalizer>(); stringLocalizer.Setup(s => s[attribute.ErrorMessage, expectedProperties]) .Returns(new LocalizedString(attribute.ErrorMessage, expectedMessage)); var adapter = new RequiredAttributeAdapter(attribute, stringLocalizer: stringLocalizer.Object); var actionContext = new ActionContext(); var context = new ClientModelValidationContext(actionContext, metadata, provider, new Dictionary<string, string>()); // Act adapter.AddValidation(context); // Assert Assert.Collection( context.Attributes, kvp => { Assert.Equal("data-val", kvp.Key); Assert.Equal("true", kvp.Value); }, kvp => { Assert.Equal("data-val-required", kvp.Key); Assert.Equal(expectedMessage, kvp.Value); }); } [Fact] [ReplaceCulture] public void AddValidation_AddsValidation() { // Arrange var expectedMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Length"); var provider = TestModelMetadataProvider.CreateDefaultProvider(); var metadata = provider.GetMetadataForProperty(typeof(string), "Length"); var attribute = new RequiredAttribute(); var adapter = new RequiredAttributeAdapter(attribute, stringLocalizer: null); var actionContext = new ActionContext(); var context = new ClientModelValidationContext(actionContext, metadata, provider, new Dictionary<string, string>()); // Act adapter.AddValidation(context); // Assert Assert.Collection( context.Attributes, kvp => { Assert.Equal("data-val", kvp.Key); Assert.Equal("true", kvp.Value); }, kvp => { Assert.Equal("data-val-required", kvp.Key); Assert.Equal(expectedMessage, kvp.Value); }); } [Fact] [ReplaceCulture] public void AddValidation_DoesNotTrounceExistingAttributes() { // Arrange var expectedMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Length"); var provider = TestModelMetadataProvider.CreateDefaultProvider(); var metadata = provider.GetMetadataForProperty(typeof(string), "Length"); var attribute = new RequiredAttribute(); var adapter = new RequiredAttributeAdapter(attribute, stringLocalizer: null); var actionContext = new ActionContext(); var context = new ClientModelValidationContext(actionContext, metadata, provider, new Dictionary<string, string>()); context.Attributes.Add("data-val", "original"); context.Attributes.Add("data-val-required", "original"); // Act adapter.AddValidation(context); // Assert Assert.Collection( context.Attributes, kvp => { Assert.Equal("data-val", kvp.Key); Assert.Equal("original", kvp.Value); }, kvp => { Assert.Equal("data-val-required", kvp.Key); Assert.Equal("original", kvp.Value); }); } } }
41.342857
128
0.637411
[ "MIT" ]
48355746/AspNetCore
src/Mvc/Mvc.DataAnnotations/test/RequiredAttributeAdapterTest.cs
4,341
C#
using System; using System.Collections.Generic; using System.Text; namespace NeedForSpeed { public class Motorcycle : Vehicle { public Motorcycle(int horsePower, double fuel) : base(horsePower, fuel) { } public override void Drive(double kilometers) { base.Drive(kilometers); } } }
18.5
55
0.591892
[ "MIT" ]
martinsivanov/CSharp-Advanced-September-2020
C # OOP/Homeworks/02 - Inheritance - Exercise/04. Need for Speed/Motorcycle.cs
372
C#
// Copyright 2014 Toni Petrina // // 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.Globalization; using System.Windows.Data; using FastSharpIDE.ViewModel; namespace FastSharpIDE.Converters { public class StatusTypeToBackgroundConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (!(value is StatusType)) return "White"; switch ((StatusType)value) { case StatusType.Info: return "#007ACC"; case StatusType.Error: return "DarkRed"; } return "White"; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }
30.382979
103
0.647059
[ "Apache-2.0" ]
tpetrina/FastSharp
FastSharp/FastSharpIDE/Converters/StatusTypeToBackgroundConverter.cs
1,430
C#
using System.Collections.Generic; using System; using System.Linq; using UnityEngine.Rendering.Universal.LibTessDotNet; namespace UnityEngine.Rendering.Universal { internal class ShadowUtility { internal struct Edge : IComparable<Edge> { public int vertexIndex0; public int vertexIndex1; public Vector4 tangent; private bool compareReversed; // This is done so that edge AB can equal edge BA public void AssignVertexIndices(int vi0, int vi1) { vertexIndex0 = vi0; vertexIndex1 = vi1; compareReversed = vi0 > vi1; } public int Compare(Edge a, Edge b) { int adjustedVertexIndex0A = a.compareReversed ? a.vertexIndex1 : a.vertexIndex0; int adjustedVertexIndex1A = a.compareReversed ? a.vertexIndex0 : a.vertexIndex1; int adjustedVertexIndex0B = b.compareReversed ? b.vertexIndex1 : b.vertexIndex0; int adjustedVertexIndex1B = b.compareReversed ? b.vertexIndex0 : b.vertexIndex1; // Sort first by VI0 then by VI1 int deltaVI0 = adjustedVertexIndex0A - adjustedVertexIndex0B; int deltaVI1 = adjustedVertexIndex1A - adjustedVertexIndex1B; if (deltaVI0 == 0) return deltaVI1; else return deltaVI0; } public int CompareTo(Edge edgeToCompare) { return Compare(this, edgeToCompare); } } static Edge CreateEdge(int triangleIndexA, int triangleIndexB, List<Vector3> vertices, List<int> triangles) { Edge retEdge = new Edge(); retEdge.AssignVertexIndices(triangles[triangleIndexA], triangles[triangleIndexB]); Vector3 vertex0 = vertices[retEdge.vertexIndex0]; vertex0.z = 0; Vector3 vertex1 = vertices[retEdge.vertexIndex1]; vertex1.z = 0; Vector3 edgeDir = Vector3.Normalize(vertex1 - vertex0); retEdge.tangent = Vector3.Cross(-Vector3.forward, edgeDir); return retEdge; } static void PopulateEdgeArray(List<Vector3> vertices, List<int> triangles, List<Edge> edges) { for (int triangleIndex = 0; triangleIndex < triangles.Count; triangleIndex += 3) { edges.Add(CreateEdge(triangleIndex, triangleIndex + 1, vertices, triangles)); edges.Add(CreateEdge(triangleIndex + 1, triangleIndex + 2, vertices, triangles)); edges.Add(CreateEdge(triangleIndex + 2, triangleIndex, vertices, triangles)); } } static bool IsOutsideEdge(int edgeIndex, List<Edge> edgesToProcess) { int previousIndex = edgeIndex - 1; int nextIndex = edgeIndex + 1; int numberOfEdges = edgesToProcess.Count; Edge currentEdge = edgesToProcess[edgeIndex]; return (previousIndex < 0 || (currentEdge.CompareTo(edgesToProcess[edgeIndex - 1]) != 0)) && (nextIndex >= numberOfEdges || (currentEdge.CompareTo(edgesToProcess[edgeIndex + 1]) != 0)); } static void SortEdges(List<Edge> edgesToProcess) { edgesToProcess.Sort(); } static void CreateShadowTriangles(List<Vector3> vertices, List<Color> colors, List<int> triangles, List<Vector4> tangents, List<Edge> edges) { for (int edgeIndex = 0; edgeIndex < edges.Count; edgeIndex++) { if (IsOutsideEdge(edgeIndex, edges)) { Edge edge = edges[edgeIndex]; tangents[edge.vertexIndex1] = -edge.tangent; int newVertexIndex = vertices.Count; vertices.Add(vertices[edge.vertexIndex0]); colors.Add(colors[edge.vertexIndex0]); tangents.Add(-edge.tangent); triangles.Add(edge.vertexIndex0); triangles.Add(newVertexIndex); triangles.Add(edge.vertexIndex1); } } } static object InterpCustomVertexData(Vec3 position, object[] data, float[] weights) { return data[0]; } static void InitializeTangents(int tangentsToAdd, List<Vector4> tangents) { for (int i = 0; i < tangentsToAdd; i++) tangents.Add(Vector4.zero); } static internal void ComputeBoundingSphere(Vector3[] shapePath, out BoundingSphere boundingSphere) { float minX = float.MaxValue; float maxX = float.MinValue; float minY = float.MaxValue; float maxY = float.MinValue; // Add outline vertices int pathLength = shapePath.Length; for (int i = 0; i < pathLength; i++) { Vector3 vertex = shapePath[i]; if (minX > vertex.x) minX = vertex.x; if (maxX < vertex.x) maxX = vertex.x; if (minY > vertex.y) minY = vertex.y; if (maxY < vertex.y) maxY = vertex.y; } // Calculate bounding sphere (circle) Vector3 origin = new Vector2(0.5f * (minX + maxX), 0.5f * (minY + maxY)); float deltaX = maxX - minX; float deltaY = maxY - minY; float radius = 0.5f * Mathf.Sqrt(deltaX * deltaX + deltaY * deltaY); boundingSphere.position = origin; boundingSphere.radius = radius; } public static BoundingSphere GenerateShadowMesh(Mesh mesh, Vector3[] shapePath) { List<Vector3> vertices = new List<Vector3>(); List<int> triangles = new List<int>(); List<Vector4> tangents = new List<Vector4>(); List<Color> extrusion = new List<Color>(); // Create interior geometry int pointCount = shapePath.Length; var inputs = new ContourVertex[2 * pointCount]; for (int i = 0; i < pointCount; i++) { Color extrusionData = new Color(shapePath[i].x, shapePath[i].y, shapePath[i].x, shapePath[i].y); int nextPoint = (i + 1) % pointCount; inputs[2 * i] = new ContourVertex() { Position = new Vec3() { X = shapePath[i].x, Y = shapePath[i].y, Z = 0 }, Data = extrusionData }; extrusionData = new Color(shapePath[i].x, shapePath[i].y, shapePath[nextPoint].x, shapePath[nextPoint].y); Vector2 midPoint = 0.5f * (shapePath[i] + shapePath[nextPoint]); inputs[2 * i + 1] = new ContourVertex() { Position = new Vec3() { X = midPoint.x, Y = midPoint.y, Z = 0 }, Data = extrusionData }; } Tess tessI = new Tess(); tessI.AddContour(inputs, ContourOrientation.Original); tessI.Tessellate(WindingRule.EvenOdd, ElementType.Polygons, 3, InterpCustomVertexData); var indicesI = tessI.Elements.Select(i => i).ToArray(); var verticesI = tessI.Vertices.Select(v => new Vector3(v.Position.X, v.Position.Y, 0)).ToArray(); var extrusionI = tessI.Vertices.Select(v => new Color(((Color)v.Data).r, ((Color)v.Data).g, ((Color)v.Data).b, ((Color)v.Data).a)).ToArray(); vertices.AddRange(verticesI); triangles.AddRange(indicesI); extrusion.AddRange(extrusionI); InitializeTangents(vertices.Count, tangents); List<Edge> edges = new List<Edge>(); PopulateEdgeArray(vertices, triangles, edges); SortEdges(edges); CreateShadowTriangles(vertices, extrusion, triangles, tangents, edges); Color[] finalExtrusion = extrusion.ToArray(); Vector3[] finalVertices = vertices.ToArray(); int[] finalTriangles = triangles.ToArray(); Vector4[] finalTangents = tangents.ToArray(); mesh.Clear(); mesh.vertices = finalVertices; mesh.triangles = finalTriangles; mesh.tangents = finalTangents; mesh.colors = finalExtrusion; BoundingSphere retSphere; ComputeBoundingSphere(shapePath, out retSphere); return retSphere; } } }
39.623256
197
0.565442
[ "MIT" ]
Liaoer/ToonShader
Packages/com.unity.render-pipelines.universal@12.1.3/Runtime/2D/Shadows/ShadowUtility.cs
8,519
C#
// ---------------------------------------------------------------------------- // <copyright file="PhotonEditorUtils.cs" company="Exit Games GmbH"> // PhotonNetwork Framework for Unity - Copyright (C) 2011 Exit Games GmbH // </copyright> // <summary> // Unity Editor Utils // </summary> // <author>developer@exitgames.com</author> // ---------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using System.IO; using UnityEditor; namespace ExitGames.Client.Photon { [InitializeOnLoad] public class PhotonEditorUtils { /// <summary>True if the ChatClient of the Photon Chat API is available. If so, the editor may (e.g.) show additional options in settings.</summary> public static bool HasChat; /// <summary>True if the VoiceClient of the Photon Voice API is available. If so, the editor may (e.g.) show additional options in settings.</summary> public static bool HasVoice; /// <summary>True if the PhotonEditorUtils checked the available products / APIs. If so, the editor may (e.g.) show additional options in settings.</summary> public static bool HasCheckedProducts; static PhotonEditorUtils() { HasVoice = Type.GetType("ExitGames.Client.Photon.Voice.VoiceClient, Assembly-CSharp") != null || Type.GetType("ExitGames.Client.Photon.Voice.VoiceClient, Assembly-CSharp-firstpass") != null; HasChat = Type.GetType("ExitGames.Client.Photon.Chat.ChatClient, Assembly-CSharp") != null || Type.GetType("ExitGames.Client.Photon.Chat.ChatClient, Assembly-CSharp-firstpass") != null; PhotonEditorUtils.HasCheckedProducts = true; } public static void MountScriptingDefineSymbolToAllTargets(string defineSymbol) { foreach (BuildTargetGroup _group in Enum.GetValues(typeof(BuildTargetGroup))) { if (_group == BuildTargetGroup.Unknown) continue; List<string> _defineSymbols = PlayerSettings.GetScriptingDefineSymbolsForGroup(_group).Split(';').Select(d => d.Trim()).ToList(); if (!_defineSymbols.Contains(defineSymbol)) { _defineSymbols.Add(defineSymbol); PlayerSettings.SetScriptingDefineSymbolsForGroup(_group, string.Join(";", _defineSymbols.ToArray())); } } } public static void UnMountScriptingDefineSymbolToAllTargets(string defineSymbol) { foreach (BuildTargetGroup _group in Enum.GetValues(typeof(BuildTargetGroup))) { if (_group == BuildTargetGroup.Unknown) continue; List<string> _defineSymbols = PlayerSettings.GetScriptingDefineSymbolsForGroup(_group).Split(';').Select(d => d.Trim()).ToList(); if (_defineSymbols.Contains(defineSymbol)) { _defineSymbols.Remove(defineSymbol); PlayerSettings.SetScriptingDefineSymbolsForGroup(_group, string.Join(";", _defineSymbols.ToArray())); } } } /// <summary> /// Gets the parent directory of a path. Recursive Function, will return null if parentName not found /// </summary> /// <returns>The parent directory</returns> /// <param name="path">Path.</param> /// <param name="parentName">Parent name.</param> public static string GetParent(string path, string parentName) { var dir = new DirectoryInfo(path); if (dir.Parent == null) { return null; } if (string.IsNullOrEmpty(parentName)) { return dir.Parent.FullName; } if (dir.Parent.Name == parentName) { return dir.Parent.FullName; } return GetParent(dir.Parent.FullName, parentName); } } }
35.81
202
0.671879
[ "Apache-2.0" ]
Asues/Elementia
Assets/Photon Unity Networking/Editor/PhotonNetwork/PhotonEditorUtils.cs
3,583
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Xunit; namespace System.Linq.Expressions.Tests { public static class LambdaSubtractNullableTests { #region Test methods [Theory, ClassData(typeof(CompilationTypes))] public static void LambdaSubtractNullableDecimalTest(bool useInterpreter) { decimal?[] values = new decimal?[] { null, decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifySubtractNullableDecimal(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void LambdaSubtractNullableDoubleTest(bool useInterpreter) { double?[] values = new double?[] { null, 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifySubtractNullableDouble(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void LambdaSubtractNullableFloatTest(bool useInterpreter) { float?[] values = new float?[] { null, 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifySubtractNullableFloat(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void LambdaSubtractNullableIntTest(bool useInterpreter) { int?[] values = new int?[] { null, 0, 1, -1, int.MinValue, int.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifySubtractNullableInt(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void LambdaSubtractNullableLongTest(bool useInterpreter) { long?[] values = new long?[] { null, 0, 1, -1, long.MinValue, long.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifySubtractNullableLong(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void LambdaSubtractNullableShortTest(bool useInterpreter) { short?[] values = new short?[] { null, 0, 1, -1, short.MinValue, short.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifySubtractNullableShort(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void LambdaSubtractNullableUIntTest(bool useInterpreter) { uint?[] values = new uint?[] { null, 0, 1, uint.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifySubtractNullableUInt(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void LambdaSubtractNullableULongTest(bool useInterpreter) { ulong?[] values = new ulong?[] { null, 0, 1, ulong.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifySubtractNullableULong(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void LambdaSubtractNullableUShortTest(bool useInterpreter) { ushort?[] values = new ushort?[] { null, 0, 1, ushort.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifySubtractNullableUShort(values[i], values[j], useInterpreter); } } } #endregion #region Test verifiers #region Verify decimal? private static void VerifySubtractNullableDecimal(decimal? a, decimal? b, bool useInterpreter) { decimal? expected = null; bool overflowed = false; try { expected = a - b; } catch (OverflowException) { overflowed = true; } ParameterExpression p0 = Expression.Parameter(typeof(decimal?), "p0"); ParameterExpression p1 = Expression.Parameter(typeof(decimal?), "p1"); // verify with parameters supplied Expression<Func<decimal?>> e1 = Expression.Lambda<Func<decimal?>>( Expression.Invoke( Expression.Lambda<Func<decimal?, decimal?, decimal?>>( Expression.Subtract(p0, p1), new ParameterExpression[] { p0, p1 }), new Expression[] { Expression.Constant(a, typeof(decimal?)), Expression.Constant(b, typeof(decimal?)) }), Enumerable.Empty<ParameterExpression>()); Func<decimal?> f1 = e1.Compile(useInterpreter); if (overflowed) { Assert.Throws<OverflowException>(() => f1()); } else { Assert.Equal(expected, f1()); } // verify with values passed to make parameters Expression<Func<decimal?, decimal?, Func<decimal?>>> e2 = Expression.Lambda<Func<decimal?, decimal?, Func<decimal?>>>( Expression.Lambda<Func<decimal?>>( Expression.Subtract(p0, p1), Enumerable.Empty<ParameterExpression>()), new ParameterExpression[] { p0, p1 }); Func<decimal?, decimal?, Func<decimal?>> f2 = e2.Compile(useInterpreter); if (overflowed) { Assert.Throws<OverflowException>(() => f2(a, b)()); } else { Assert.Equal(expected, f2(a, b)()); } // verify with values directly passed Expression<Func<Func<decimal?, decimal?, decimal?>>> e3 = Expression.Lambda<Func<Func<decimal?, decimal?, decimal?>>>( Expression.Invoke( Expression.Lambda<Func<Func<decimal?, decimal?, decimal?>>>( Expression.Lambda<Func<decimal?, decimal?, decimal?>>( Expression.Subtract(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()), Enumerable.Empty<Expression>()), Enumerable.Empty<ParameterExpression>()); Func<decimal?, decimal?, decimal?> f3 = e3.Compile(useInterpreter)(); if (overflowed) { Assert.Throws<OverflowException>(() => f3(a, b)); } else { Assert.Equal(expected, f3(a, b)); } // verify as a function generator Expression<Func<Func<decimal?, decimal?, decimal?>>> e4 = Expression.Lambda<Func<Func<decimal?, decimal?, decimal?>>>( Expression.Lambda<Func<decimal?, decimal?, decimal?>>( Expression.Subtract(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()); Func<Func<decimal?, decimal?, decimal?>> f4 = e4.Compile(useInterpreter); if (overflowed) { Assert.Throws<OverflowException>(() => f4()(a, b)); } else { Assert.Equal(expected, f4()(a, b)); } // verify with currying Expression<Func<decimal?, Func<decimal?, decimal?>>> e5 = Expression.Lambda<Func<decimal?, Func<decimal?, decimal?>>>( Expression.Lambda<Func<decimal?, decimal?>>( Expression.Subtract(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }); Func<decimal?, Func<decimal?, decimal?>> f5 = e5.Compile(useInterpreter); if (overflowed) { Assert.Throws<OverflowException>(() => f5(a)(b)); } else { Assert.Equal(expected, f5(a)(b)); } // verify with one parameter Expression<Func<Func<decimal?, decimal?>>> e6 = Expression.Lambda<Func<Func<decimal?, decimal?>>>( Expression.Invoke( Expression.Lambda<Func<decimal?, Func<decimal?, decimal?>>>( Expression.Lambda<Func<decimal?, decimal?>>( Expression.Subtract(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }), new Expression[] { Expression.Constant(a, typeof(decimal?)) }), Enumerable.Empty<ParameterExpression>()); Func<decimal?, decimal?> f6 = e6.Compile(useInterpreter)(); if (overflowed) { Assert.Throws<OverflowException>(() => f6(b)); } else { Assert.Equal(expected, f6(b)); } } #endregion #region Verify double? private static void VerifySubtractNullableDouble(double? a, double? b, bool useInterpreter) { double? expected = a - b; ParameterExpression p0 = Expression.Parameter(typeof(double?), "p0"); ParameterExpression p1 = Expression.Parameter(typeof(double?), "p1"); // verify with parameters supplied Expression<Func<double?>> e1 = Expression.Lambda<Func<double?>>( Expression.Invoke( Expression.Lambda<Func<double?, double?, double?>>( Expression.Subtract(p0, p1), new ParameterExpression[] { p0, p1 }), new Expression[] { Expression.Constant(a, typeof(double?)), Expression.Constant(b, typeof(double?)) }), Enumerable.Empty<ParameterExpression>()); Func<double?> f1 = e1.Compile(useInterpreter); Assert.Equal(expected, f1()); // verify with values passed to make parameters Expression<Func<double?, double?, Func<double?>>> e2 = Expression.Lambda<Func<double?, double?, Func<double?>>>( Expression.Lambda<Func<double?>>( Expression.Subtract(p0, p1), Enumerable.Empty<ParameterExpression>()), new ParameterExpression[] { p0, p1 }); Func<double?, double?, Func<double?>> f2 = e2.Compile(useInterpreter); Assert.Equal(expected, f2(a, b)()); // verify with values directly passed Expression<Func<Func<double?, double?, double?>>> e3 = Expression.Lambda<Func<Func<double?, double?, double?>>>( Expression.Invoke( Expression.Lambda<Func<Func<double?, double?, double?>>>( Expression.Lambda<Func<double?, double?, double?>>( Expression.Subtract(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()), Enumerable.Empty<Expression>()), Enumerable.Empty<ParameterExpression>()); Func<double?, double?, double?> f3 = e3.Compile(useInterpreter)(); Assert.Equal(expected, f3(a, b)); // verify as a function generator Expression<Func<Func<double?, double?, double?>>> e4 = Expression.Lambda<Func<Func<double?, double?, double?>>>( Expression.Lambda<Func<double?, double?, double?>>( Expression.Subtract(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()); Func<Func<double?, double?, double?>> f4 = e4.Compile(useInterpreter); Assert.Equal(expected, f4()(a, b)); // verify with currying Expression<Func<double?, Func<double?, double?>>> e5 = Expression.Lambda<Func<double?, Func<double?, double?>>>( Expression.Lambda<Func<double?, double?>>( Expression.Subtract(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }); Func<double?, Func<double?, double?>> f5 = e5.Compile(useInterpreter); Assert.Equal(expected, f5(a)(b)); // verify with one parameter Expression<Func<Func<double?, double?>>> e6 = Expression.Lambda<Func<Func<double?, double?>>>( Expression.Invoke( Expression.Lambda<Func<double?, Func<double?, double?>>>( Expression.Lambda<Func<double?, double?>>( Expression.Subtract(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }), new Expression[] { Expression.Constant(a, typeof(double?)) }), Enumerable.Empty<ParameterExpression>()); Func<double?, double?> f6 = e6.Compile(useInterpreter)(); Assert.Equal(expected, f6(b)); } #endregion #region Verify float? private static void VerifySubtractNullableFloat(float? a, float? b, bool useInterpreter) { float? expected = a - b; ParameterExpression p0 = Expression.Parameter(typeof(float?), "p0"); ParameterExpression p1 = Expression.Parameter(typeof(float?), "p1"); // verify with parameters supplied Expression<Func<float?>> e1 = Expression.Lambda<Func<float?>>( Expression.Invoke( Expression.Lambda<Func<float?, float?, float?>>( Expression.Subtract(p0, p1), new ParameterExpression[] { p0, p1 }), new Expression[] { Expression.Constant(a, typeof(float?)), Expression.Constant(b, typeof(float?)) }), Enumerable.Empty<ParameterExpression>()); Func<float?> f1 = e1.Compile(useInterpreter); Assert.Equal(expected, f1()); // verify with values passed to make parameters Expression<Func<float?, float?, Func<float?>>> e2 = Expression.Lambda<Func<float?, float?, Func<float?>>>( Expression.Lambda<Func<float?>>( Expression.Subtract(p0, p1), Enumerable.Empty<ParameterExpression>()), new ParameterExpression[] { p0, p1 }); Func<float?, float?, Func<float?>> f2 = e2.Compile(useInterpreter); Assert.Equal(expected, f2(a, b)()); // verify with values directly passed Expression<Func<Func<float?, float?, float?>>> e3 = Expression.Lambda<Func<Func<float?, float?, float?>>>( Expression.Invoke( Expression.Lambda<Func<Func<float?, float?, float?>>>( Expression.Lambda<Func<float?, float?, float?>>( Expression.Subtract(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()), Enumerable.Empty<Expression>()), Enumerable.Empty<ParameterExpression>()); Func<float?, float?, float?> f3 = e3.Compile(useInterpreter)(); Assert.Equal(expected, f3(a, b)); // verify as a function generator Expression<Func<Func<float?, float?, float?>>> e4 = Expression.Lambda<Func<Func<float?, float?, float?>>>( Expression.Lambda<Func<float?, float?, float?>>( Expression.Subtract(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()); Func<Func<float?, float?, float?>> f4 = e4.Compile(useInterpreter); Assert.Equal(expected, f4()(a, b)); // verify with currying Expression<Func<float?, Func<float?, float?>>> e5 = Expression.Lambda<Func<float?, Func<float?, float?>>>( Expression.Lambda<Func<float?, float?>>( Expression.Subtract(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }); Func<float?, Func<float?, float?>> f5 = e5.Compile(useInterpreter); Assert.Equal(expected, f5(a)(b)); // verify with one parameter Expression<Func<Func<float?, float?>>> e6 = Expression.Lambda<Func<Func<float?, float?>>>( Expression.Invoke( Expression.Lambda<Func<float?, Func<float?, float?>>>( Expression.Lambda<Func<float?, float?>>( Expression.Subtract(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }), new Expression[] { Expression.Constant(a, typeof(float?)) }), Enumerable.Empty<ParameterExpression>()); Func<float?, float?> f6 = e6.Compile(useInterpreter)(); Assert.Equal(expected, f6(b)); } #endregion #region Verify int? private static void VerifySubtractNullableInt(int? a, int? b, bool useInterpreter) { int? expected = a - b; ParameterExpression p0 = Expression.Parameter(typeof(int?), "p0"); ParameterExpression p1 = Expression.Parameter(typeof(int?), "p1"); // verify with parameters supplied Expression<Func<int?>> e1 = Expression.Lambda<Func<int?>>( Expression.Invoke( Expression.Lambda<Func<int?, int?, int?>>( Expression.Subtract(p0, p1), new ParameterExpression[] { p0, p1 }), new Expression[] { Expression.Constant(a, typeof(int?)), Expression.Constant(b, typeof(int?)) }), Enumerable.Empty<ParameterExpression>()); Func<int?> f1 = e1.Compile(useInterpreter); Assert.Equal(expected, f1()); // verify with values passed to make parameters Expression<Func<int?, int?, Func<int?>>> e2 = Expression.Lambda<Func<int?, int?, Func<int?>>>( Expression.Lambda<Func<int?>>( Expression.Subtract(p0, p1), Enumerable.Empty<ParameterExpression>()), new ParameterExpression[] { p0, p1 }); Func<int?, int?, Func<int?>> f2 = e2.Compile(useInterpreter); Assert.Equal(expected, f2(a, b)()); // verify with values directly passed Expression<Func<Func<int?, int?, int?>>> e3 = Expression.Lambda<Func<Func<int?, int?, int?>>>( Expression.Invoke( Expression.Lambda<Func<Func<int?, int?, int?>>>( Expression.Lambda<Func<int?, int?, int?>>( Expression.Subtract(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()), Enumerable.Empty<Expression>()), Enumerable.Empty<ParameterExpression>()); Func<int?, int?, int?> f3 = e3.Compile(useInterpreter)(); Assert.Equal(expected, f3(a, b)); // verify as a function generator Expression<Func<Func<int?, int?, int?>>> e4 = Expression.Lambda<Func<Func<int?, int?, int?>>>( Expression.Lambda<Func<int?, int?, int?>>( Expression.Subtract(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()); Func<Func<int?, int?, int?>> f4 = e4.Compile(useInterpreter); Assert.Equal(expected, f4()(a, b)); // verify with currying Expression<Func<int?, Func<int?, int?>>> e5 = Expression.Lambda<Func<int?, Func<int?, int?>>>( Expression.Lambda<Func<int?, int?>>( Expression.Subtract(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }); Func<int?, Func<int?, int?>> f5 = e5.Compile(useInterpreter); Assert.Equal(expected, f5(a)(b)); // verify with one parameter Expression<Func<Func<int?, int?>>> e6 = Expression.Lambda<Func<Func<int?, int?>>>( Expression.Invoke( Expression.Lambda<Func<int?, Func<int?, int?>>>( Expression.Lambda<Func<int?, int?>>( Expression.Subtract(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }), new Expression[] { Expression.Constant(a, typeof(int?)) }), Enumerable.Empty<ParameterExpression>()); Func<int?, int?> f6 = e6.Compile(useInterpreter)(); Assert.Equal(expected, f6(b)); } #endregion #region Verify long? private static void VerifySubtractNullableLong(long? a, long? b, bool useInterpreter) { long? expected = a - b; ParameterExpression p0 = Expression.Parameter(typeof(long?), "p0"); ParameterExpression p1 = Expression.Parameter(typeof(long?), "p1"); // verify with parameters supplied Expression<Func<long?>> e1 = Expression.Lambda<Func<long?>>( Expression.Invoke( Expression.Lambda<Func<long?, long?, long?>>( Expression.Subtract(p0, p1), new ParameterExpression[] { p0, p1 }), new Expression[] { Expression.Constant(a, typeof(long?)), Expression.Constant(b, typeof(long?)) }), Enumerable.Empty<ParameterExpression>()); Func<long?> f1 = e1.Compile(useInterpreter); Assert.Equal(expected, f1()); // verify with values passed to make parameters Expression<Func<long?, long?, Func<long?>>> e2 = Expression.Lambda<Func<long?, long?, Func<long?>>>( Expression.Lambda<Func<long?>>( Expression.Subtract(p0, p1), Enumerable.Empty<ParameterExpression>()), new ParameterExpression[] { p0, p1 }); Func<long?, long?, Func<long?>> f2 = e2.Compile(useInterpreter); Assert.Equal(expected, f2(a, b)()); // verify with values directly passed Expression<Func<Func<long?, long?, long?>>> e3 = Expression.Lambda<Func<Func<long?, long?, long?>>>( Expression.Invoke( Expression.Lambda<Func<Func<long?, long?, long?>>>( Expression.Lambda<Func<long?, long?, long?>>( Expression.Subtract(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()), Enumerable.Empty<Expression>()), Enumerable.Empty<ParameterExpression>()); Func<long?, long?, long?> f3 = e3.Compile(useInterpreter)(); Assert.Equal(expected, f3(a, b)); // verify as a function generator Expression<Func<Func<long?, long?, long?>>> e4 = Expression.Lambda<Func<Func<long?, long?, long?>>>( Expression.Lambda<Func<long?, long?, long?>>( Expression.Subtract(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()); Func<Func<long?, long?, long?>> f4 = e4.Compile(useInterpreter); Assert.Equal(expected, f4()(a, b)); // verify with currying Expression<Func<long?, Func<long?, long?>>> e5 = Expression.Lambda<Func<long?, Func<long?, long?>>>( Expression.Lambda<Func<long?, long?>>( Expression.Subtract(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }); Func<long?, Func<long?, long?>> f5 = e5.Compile(useInterpreter); Assert.Equal(expected, f5(a)(b)); // verify with one parameter Expression<Func<Func<long?, long?>>> e6 = Expression.Lambda<Func<Func<long?, long?>>>( Expression.Invoke( Expression.Lambda<Func<long?, Func<long?, long?>>>( Expression.Lambda<Func<long?, long?>>( Expression.Subtract(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }), new Expression[] { Expression.Constant(a, typeof(long?)) }), Enumerable.Empty<ParameterExpression>()); Func<long?, long?> f6 = e6.Compile(useInterpreter)(); Assert.Equal(expected, f6(b)); } #endregion #region Verify short? private static void VerifySubtractNullableShort(short? a, short? b, bool useInterpreter) { short? expected = (short?)(a - b); ParameterExpression p0 = Expression.Parameter(typeof(short?), "p0"); ParameterExpression p1 = Expression.Parameter(typeof(short?), "p1"); // verify with parameters supplied Expression<Func<short?>> e1 = Expression.Lambda<Func<short?>>( Expression.Invoke( Expression.Lambda<Func<short?, short?, short?>>( Expression.Subtract(p0, p1), new ParameterExpression[] { p0, p1 }), new Expression[] { Expression.Constant(a, typeof(short?)), Expression.Constant(b, typeof(short?)) }), Enumerable.Empty<ParameterExpression>()); Func<short?> f1 = e1.Compile(useInterpreter); Assert.Equal(expected, f1()); // verify with values passed to make parameters Expression<Func<short?, short?, Func<short?>>> e2 = Expression.Lambda<Func<short?, short?, Func<short?>>>( Expression.Lambda<Func<short?>>( Expression.Subtract(p0, p1), Enumerable.Empty<ParameterExpression>()), new ParameterExpression[] { p0, p1 }); Func<short?, short?, Func<short?>> f2 = e2.Compile(useInterpreter); Assert.Equal(expected, f2(a, b)()); // verify with values directly passed Expression<Func<Func<short?, short?, short?>>> e3 = Expression.Lambda<Func<Func<short?, short?, short?>>>( Expression.Invoke( Expression.Lambda<Func<Func<short?, short?, short?>>>( Expression.Lambda<Func<short?, short?, short?>>( Expression.Subtract(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()), Enumerable.Empty<Expression>()), Enumerable.Empty<ParameterExpression>()); Func<short?, short?, short?> f3 = e3.Compile(useInterpreter)(); Assert.Equal(expected, f3(a, b)); // verify as a function generator Expression<Func<Func<short?, short?, short?>>> e4 = Expression.Lambda<Func<Func<short?, short?, short?>>>( Expression.Lambda<Func<short?, short?, short?>>( Expression.Subtract(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()); Func<Func<short?, short?, short?>> f4 = e4.Compile(useInterpreter); Assert.Equal(expected, f4()(a, b)); // verify with currying Expression<Func<short?, Func<short?, short?>>> e5 = Expression.Lambda<Func<short?, Func<short?, short?>>>( Expression.Lambda<Func<short?, short?>>( Expression.Subtract(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }); Func<short?, Func<short?, short?>> f5 = e5.Compile(useInterpreter); Assert.Equal(expected, f5(a)(b)); // verify with one parameter Expression<Func<Func<short?, short?>>> e6 = Expression.Lambda<Func<Func<short?, short?>>>( Expression.Invoke( Expression.Lambda<Func<short?, Func<short?, short?>>>( Expression.Lambda<Func<short?, short?>>( Expression.Subtract(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }), new Expression[] { Expression.Constant(a, typeof(short?)) }), Enumerable.Empty<ParameterExpression>()); Func<short?, short?> f6 = e6.Compile(useInterpreter)(); Assert.Equal(expected, f6(b)); } #endregion #region Verify uint? private static void VerifySubtractNullableUInt(uint? a, uint? b, bool useInterpreter) { uint? expected = a - b; ParameterExpression p0 = Expression.Parameter(typeof(uint?), "p0"); ParameterExpression p1 = Expression.Parameter(typeof(uint?), "p1"); // verify with parameters supplied Expression<Func<uint?>> e1 = Expression.Lambda<Func<uint?>>( Expression.Invoke( Expression.Lambda<Func<uint?, uint?, uint?>>( Expression.Subtract(p0, p1), new ParameterExpression[] { p0, p1 }), new Expression[] { Expression.Constant(a, typeof(uint?)), Expression.Constant(b, typeof(uint?)) }), Enumerable.Empty<ParameterExpression>()); Func<uint?> f1 = e1.Compile(useInterpreter); Assert.Equal(expected, f1()); // verify with values passed to make parameters Expression<Func<uint?, uint?, Func<uint?>>> e2 = Expression.Lambda<Func<uint?, uint?, Func<uint?>>>( Expression.Lambda<Func<uint?>>( Expression.Subtract(p0, p1), Enumerable.Empty<ParameterExpression>()), new ParameterExpression[] { p0, p1 }); Func<uint?, uint?, Func<uint?>> f2 = e2.Compile(useInterpreter); Assert.Equal(expected, f2(a, b)()); // verify with values directly passed Expression<Func<Func<uint?, uint?, uint?>>> e3 = Expression.Lambda<Func<Func<uint?, uint?, uint?>>>( Expression.Invoke( Expression.Lambda<Func<Func<uint?, uint?, uint?>>>( Expression.Lambda<Func<uint?, uint?, uint?>>( Expression.Subtract(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()), Enumerable.Empty<Expression>()), Enumerable.Empty<ParameterExpression>()); Func<uint?, uint?, uint?> f3 = e3.Compile(useInterpreter)(); Assert.Equal(expected, f3(a, b)); // verify as a function generator Expression<Func<Func<uint?, uint?, uint?>>> e4 = Expression.Lambda<Func<Func<uint?, uint?, uint?>>>( Expression.Lambda<Func<uint?, uint?, uint?>>( Expression.Subtract(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()); Func<Func<uint?, uint?, uint?>> f4 = e4.Compile(useInterpreter); Assert.Equal(expected, f4()(a, b)); // verify with currying Expression<Func<uint?, Func<uint?, uint?>>> e5 = Expression.Lambda<Func<uint?, Func<uint?, uint?>>>( Expression.Lambda<Func<uint?, uint?>>( Expression.Subtract(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }); Func<uint?, Func<uint?, uint?>> f5 = e5.Compile(useInterpreter); Assert.Equal(expected, f5(a)(b)); // verify with one parameter Expression<Func<Func<uint?, uint?>>> e6 = Expression.Lambda<Func<Func<uint?, uint?>>>( Expression.Invoke( Expression.Lambda<Func<uint?, Func<uint?, uint?>>>( Expression.Lambda<Func<uint?, uint?>>( Expression.Subtract(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }), new Expression[] { Expression.Constant(a, typeof(uint?)) }), Enumerable.Empty<ParameterExpression>()); Func<uint?, uint?> f6 = e6.Compile(useInterpreter)(); Assert.Equal(expected, f6(b)); } #endregion #region Verify ulong? private static void VerifySubtractNullableULong(ulong? a, ulong? b, bool useInterpreter) { ulong? expected = a - b; ParameterExpression p0 = Expression.Parameter(typeof(ulong?), "p0"); ParameterExpression p1 = Expression.Parameter(typeof(ulong?), "p1"); // verify with parameters supplied Expression<Func<ulong?>> e1 = Expression.Lambda<Func<ulong?>>( Expression.Invoke( Expression.Lambda<Func<ulong?, ulong?, ulong?>>( Expression.Subtract(p0, p1), new ParameterExpression[] { p0, p1 }), new Expression[] { Expression.Constant(a, typeof(ulong?)), Expression.Constant(b, typeof(ulong?)) }), Enumerable.Empty<ParameterExpression>()); Func<ulong?> f1 = e1.Compile(useInterpreter); Assert.Equal(expected, f1()); // verify with values passed to make parameters Expression<Func<ulong?, ulong?, Func<ulong?>>> e2 = Expression.Lambda<Func<ulong?, ulong?, Func<ulong?>>>( Expression.Lambda<Func<ulong?>>( Expression.Subtract(p0, p1), Enumerable.Empty<ParameterExpression>()), new ParameterExpression[] { p0, p1 }); Func<ulong?, ulong?, Func<ulong?>> f2 = e2.Compile(useInterpreter); Assert.Equal(expected, f2(a, b)()); // verify with values directly passed Expression<Func<Func<ulong?, ulong?, ulong?>>> e3 = Expression.Lambda<Func<Func<ulong?, ulong?, ulong?>>>( Expression.Invoke( Expression.Lambda<Func<Func<ulong?, ulong?, ulong?>>>( Expression.Lambda<Func<ulong?, ulong?, ulong?>>( Expression.Subtract(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()), Enumerable.Empty<Expression>()), Enumerable.Empty<ParameterExpression>()); Func<ulong?, ulong?, ulong?> f3 = e3.Compile(useInterpreter)(); Assert.Equal(expected, f3(a, b)); // verify as a function generator Expression<Func<Func<ulong?, ulong?, ulong?>>> e4 = Expression.Lambda<Func<Func<ulong?, ulong?, ulong?>>>( Expression.Lambda<Func<ulong?, ulong?, ulong?>>( Expression.Subtract(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()); Func<Func<ulong?, ulong?, ulong?>> f4 = e4.Compile(useInterpreter); Assert.Equal(expected, f4()(a, b)); // verify with currying Expression<Func<ulong?, Func<ulong?, ulong?>>> e5 = Expression.Lambda<Func<ulong?, Func<ulong?, ulong?>>>( Expression.Lambda<Func<ulong?, ulong?>>( Expression.Subtract(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }); Func<ulong?, Func<ulong?, ulong?>> f5 = e5.Compile(useInterpreter); Assert.Equal(expected, f5(a)(b)); // verify with one parameter Expression<Func<Func<ulong?, ulong?>>> e6 = Expression.Lambda<Func<Func<ulong?, ulong?>>>( Expression.Invoke( Expression.Lambda<Func<ulong?, Func<ulong?, ulong?>>>( Expression.Lambda<Func<ulong?, ulong?>>( Expression.Subtract(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }), new Expression[] { Expression.Constant(a, typeof(ulong?)) }), Enumerable.Empty<ParameterExpression>()); Func<ulong?, ulong?> f6 = e6.Compile(useInterpreter)(); Assert.Equal(expected, f6(b)); } #endregion #region Verify ushort? private static void VerifySubtractNullableUShort(ushort? a, ushort? b, bool useInterpreter) { ushort? expected = (ushort?)(a - b); ParameterExpression p0 = Expression.Parameter(typeof(ushort?), "p0"); ParameterExpression p1 = Expression.Parameter(typeof(ushort?), "p1"); // verify with parameters supplied Expression<Func<ushort?>> e1 = Expression.Lambda<Func<ushort?>>( Expression.Invoke( Expression.Lambda<Func<ushort?, ushort?, ushort?>>( Expression.Subtract(p0, p1), new ParameterExpression[] { p0, p1 }), new Expression[] { Expression.Constant(a, typeof(ushort?)), Expression.Constant(b, typeof(ushort?)) }), Enumerable.Empty<ParameterExpression>()); Func<ushort?> f1 = e1.Compile(useInterpreter); Assert.Equal(expected, f1()); // verify with values passed to make parameters Expression<Func<ushort?, ushort?, Func<ushort?>>> e2 = Expression.Lambda<Func<ushort?, ushort?, Func<ushort?>>>( Expression.Lambda<Func<ushort?>>( Expression.Subtract(p0, p1), Enumerable.Empty<ParameterExpression>()), new ParameterExpression[] { p0, p1 }); Func<ushort?, ushort?, Func<ushort?>> f2 = e2.Compile(useInterpreter); Assert.Equal(expected, f2(a, b)()); // verify with values directly passed Expression<Func<Func<ushort?, ushort?, ushort?>>> e3 = Expression.Lambda<Func<Func<ushort?, ushort?, ushort?>>>( Expression.Invoke( Expression.Lambda<Func<Func<ushort?, ushort?, ushort?>>>( Expression.Lambda<Func<ushort?, ushort?, ushort?>>( Expression.Subtract(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()), Enumerable.Empty<Expression>()), Enumerable.Empty<ParameterExpression>()); Func<ushort?, ushort?, ushort?> f3 = e3.Compile(useInterpreter)(); Assert.Equal(expected, f3(a, b)); // verify as a function generator Expression<Func<Func<ushort?, ushort?, ushort?>>> e4 = Expression.Lambda<Func<Func<ushort?, ushort?, ushort?>>>( Expression.Lambda<Func<ushort?, ushort?, ushort?>>( Expression.Subtract(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()); Func<Func<ushort?, ushort?, ushort?>> f4 = e4.Compile(useInterpreter); Assert.Equal(expected, f4()(a, b)); // verify with currying Expression<Func<ushort?, Func<ushort?, ushort?>>> e5 = Expression.Lambda<Func<ushort?, Func<ushort?, ushort?>>>( Expression.Lambda<Func<ushort?, ushort?>>( Expression.Subtract(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }); Func<ushort?, Func<ushort?, ushort?>> f5 = e5.Compile(useInterpreter); Assert.Equal(expected, f5(a)(b)); // verify with one parameter Expression<Func<Func<ushort?, ushort?>>> e6 = Expression.Lambda<Func<Func<ushort?, ushort?>>>( Expression.Invoke( Expression.Lambda<Func<ushort?, Func<ushort?, ushort?>>>( Expression.Lambda<Func<ushort?, ushort?>>( Expression.Subtract(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }), new Expression[] { Expression.Constant(a, typeof(ushort?)) }), Enumerable.Empty<ParameterExpression>()); Func<ushort?, ushort?> f6 = e6.Compile(useInterpreter)(); Assert.Equal(expected, f6(b)); } #endregion #endregion } }
44.587719
176
0.49577
[ "MIT" ]
OceanYan/corefx
src/System.Linq.Expressions/tests/Lambda/LambdaSubtractNullableTests.cs
45,747
C#
using System.Linq; using System.Runtime.Serialization; using PrtgAPI.Attributes; using PrtgAPI.Exceptions.Internal; using PrtgAPI.Reflection; using PrtgAPI.Utilities; namespace PrtgAPI.Parameters { class SystemInfoParameters<T> : BaseActionParameters, IJsonParameters where T : IDeviceInfo { JsonFunction IJsonParameters.Function => JsonFunction.TableData; public SysInfoProperty[] Columns { get { return (SysInfoProperty[])this[Parameter.Columns]; } set { this[Parameter.Columns] = value; } } public SystemInfoParameters(int deviceId) : base(deviceId) { this[Parameter.Content] = Content.SysInfo; Columns = GetProperties(); var category = typeof(T).GetTypeCache().GetAttribute<CategoryAttribute>(); if (category == null) throw new MissingAttributeException(GetType(), typeof(CategoryAttribute)); this[Parameter.Category] = category.Name.GetDescription().ToLower(); } private SysInfoProperty[] GetProperties() { var properties = typeof(T).GetTypeCache().Properties .Where(p => p.GetAttribute<UndocumentedAttribute>() == null) .Select(e => e.GetAttribute<DataMemberAttribute>()) .Where(p => p != null) .Select(e => e.Name.ToEnum<SysInfoProperty>()) .Distinct() .ToArray(); return properties; } } }
32.297872
95
0.611989
[ "MIT" ]
ericsp59/PrtgAPI
src/PrtgAPI/Parameters/ObjectData/SystemInfoParameters.cs
1,520
C#
using Autofac; using Microsoft.FeatureFlighting.Common.Group; using Microsoft.FeatureFlighting.Common.Caching; using Microsoft.FeatureFlighting.Common.Storage; using Microsoft.FeatureFlighting.Common.Webhook; using Microsoft.FeatureFlighting.Common.AppConfig; using Microsoft.FeatureFlighting.Infrastructure.Cache; using Microsoft.FeatureFlighting.Infrastructure.Graph; using Microsoft.FeatureFlighting.Common.Authorization; using Microsoft.FeatureFlighting.Common.Authentication; using Microsoft.FeatureFlighting.Infrastructure.Storage; using Microsoft.FeatureFlighting.Infrastructure.Webhook; using Microsoft.FeatureFlighting.Infrastructure.AppConfig; using Microsoft.FeatureFlighting.Infrastructure.Authorization; using Microsoft.FeatureFlighting.Infrastructure.Authentication; using Microsoft.FeatureFlighting.Common.Cache; using Autofac.Core; using System.Collections.Generic; namespace Microsoft.FeatureFlighting.Infrastructure { /// <summary> /// <see cref="Module"/> for registering infrastructure dependencies /// </summary> public class InfrastructureModule : Module { protected override void Load(ContainerBuilder builder) { base.Load(builder); RegisterAppConfig(builder); RegisterAuthentication(builder); RegisterAuthorization(builder); RegisterCache(builder); RegisterGraph(builder); RegisterStorage(builder); RegisterWebhook(builder); } private void RegisterAppConfig(ContainerBuilder builder) { builder.RegisterType<AzureConfigurationClientProvider>() .As<IAzureConfigurationClientProvider>() .SingleInstance(); builder.RegisterType<AzureFeatureManager>() .As<IAzureFeatureManager>() .SingleInstance(); } private void RegisterAuthentication(ContainerBuilder builder) { builder.RegisterType<IdentityContext>() .As<IIdentityContext>() .SingleInstance(); builder.RegisterType<AadTokenGenerator>() .As<ITokenGenerator>() .SingleInstance(); } private void RegisterAuthorization(ContainerBuilder builder) { builder.RegisterType<AuthorizationService>() .As<IAuthorizationService>() .SingleInstance(); } private void RegisterCache(ContainerBuilder builder) { builder.RegisterType<FlightingCacheFactory>() .As<ICacheFactory>() .SingleInstance(); builder.RegisterType<BackgroundCacheManager>() .As<IBackgroundCacheManager>() .WithParameter(new ResolvedParameter( (pi, ctx) => pi.ParameterType == typeof(IEnumerable<IBackgroundCacheable>), (pi, ctx) => ctx.Resolve<IEnumerable<IBackgroundCacheable>>() )); } private void RegisterGraph(ContainerBuilder builder) { builder.RegisterType<GraphGroupVerificationService>() .As<IGroupVerificationService>() .As<IBackgroundCacheable>() .SingleInstance(); } private void RegisterStorage(ContainerBuilder builder) { builder.RegisterType<BlobProviderFactory>() .As<IBlobProviderFactory>() .SingleInstance(); builder.RegisterType<FlightsDbRepositoryFactory>() .As<IFlightsDbRepositoryFactory>() .SingleInstance(); } private void RegisterWebhook(ContainerBuilder builder) { builder.RegisterType<WebhookTriggerManager>() .As<IWebhookTriggerManager>() .SingleInstance(); } } }
35.472727
95
0.645566
[ "MIT" ]
microsoft/FeatureFlightingManagement
src/service/Infrastructure/InfrastructureModule.cs
3,904
C#
// Copyright 2022 dSPACE GmbH, Mark Lechtermann, Matthias Nissen and Contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace dSPACE.Runtime.InteropServices.Tests; internal class DynamicMethodBuilder : DynamicBuilder<DynamicMethodBuilder> { internal record struct DefaultValue( object? Value ); internal record struct ParameterItem( Type Type, ParameterAttributes? ParameterAttributes, DefaultValue? DefaultValue = null ); public DynamicMethodBuilder(DynamicTypeBuilder dynamicTypeBuilder, string name) : base(name) { DynamicTypeBuilder = dynamicTypeBuilder; } public DynamicTypeBuilder DynamicTypeBuilder { get; } public Type? ReturnType { get; set; } = typeof(void); private Tuple<Type, object>? ReturnTypeAttribute { get; set; } public List<ParameterItem> ParamterItems { get; } = new(); public Tuple<Type, object?>[]? ParamAttributes { get; set; } public Dictionary<int, Tuple<FieldInfo[], object?[]>> ParamAttributesFieldValues { get; set; } = new(); protected override AttributeTargets AttributeTarget => AttributeTargets.Method; public DynamicMethodBuilder WithReturnType(Type type) { ReturnType = type; return this; } public DynamicMethodBuilder WithReturnType<T>() { ReturnType = typeof(T); return this; } public DynamicMethodBuilder WithParameter<T>() { return WithParameter(typeof(T)); } public DynamicMethodBuilder WithParameter(Type parameterType) { ParamterItems.Add(new ParameterItem(parameterType, null)); return this; } public DynamicMethodBuilder WithParameter(ParameterItem parameterItem) { ParamterItems.Add(parameterItem); return this; } public DynamicMethodBuilder WithReturnTypeCustomAttribute<T>(object value) { ReturnTypeAttribute = new Tuple<Type, object>(typeof(T), value); return this; } public DynamicMethodBuilder WithParameterCustomAttribute<T>(int parameterIndex) { var attributes = ParamAttributes ?? new Tuple<Type, object?>[ParamterItems == null ? 0 : ParamterItems.Count]; attributes[parameterIndex] = new(typeof(T), null); ParamAttributes = attributes; return this; } public DynamicMethodBuilder WithParameterCustomAttribute<T>(int parameterIndex, object value) { var attributes = ParamAttributes ?? new Tuple<Type, object?>[ParamterItems == null ? 0 : ParamterItems.Count]; attributes[parameterIndex] = new(typeof(T), value); ParamAttributes = attributes; return this; } public DynamicMethodBuilder WithParameterCustomAttribute<T>(int parameterIndex, object value, FieldInfo[] namedFields, object?[] fieldValues) { var attributes = ParamAttributes ?? new Tuple<Type, object?>[ParamterItems == null ? 0 : ParamterItems.Count]; attributes[parameterIndex] = new(typeof(T), value); ParamAttributes = attributes; ParamAttributesFieldValues[parameterIndex] = new(namedFields, fieldValues); return this; } public DynamicTypeBuilder CreateMethod() { var methodBuilder = DynamicTypeBuilder.TypeBuilder!.DefineMethod(Name, MethodAttributes.Abstract | MethodAttributes.Public | MethodAttributes.Virtual, CallingConventions.HasThis, ReturnType, ParamterItems.Select(p => p.Type).ToArray()); var returnParamBuilder = methodBuilder.DefineParameter(0, ParameterAttributes.Retval, null); if (ReturnTypeAttribute != null) { var attributeParam = ReturnTypeAttribute.Item2; var typeAttributeParam = ReturnTypeAttribute.Item2.GetType(); var typeAttribute = ReturnTypeAttribute.Item1; var attributeConstructor = typeAttribute.GetConstructor(new Type[] { typeAttributeParam }); var attributeBuilder = new CustomAttributeBuilder(attributeConstructor!, new object[] { attributeParam }); returnParamBuilder.SetCustomAttribute(attributeBuilder); } var index = 1; foreach (var item in ParamterItems) { var hasDefaultValue = item.DefaultValue != null; var parameterAttribute = item.ParameterAttributes; if (parameterAttribute == null) { parameterAttribute = hasDefaultValue ? ParameterAttributes.HasDefault : ParameterAttributes.None; } var paramBuilder = methodBuilder.DefineParameter(index, parameterAttribute.Value, $"Param{index}"); if (ParamAttributes != null) { //use parameter attributes if ((ParamAttributes.Length > index - 1) && ParamAttributes.GetValue(index - 1) != null) { var attributeParam = ParamAttributes[index - 1].Item2; var typeAttributeParam = ParamAttributes[index - 1].Item2 == null ? typeof(object) : ParamAttributes[index - 1].Item2?.GetType(); var typeAttribute = ParamAttributes[index - 1].Item1; var attributeConstructor = attributeParam != null && typeAttributeParam != null ? typeAttribute.GetConstructor(new Type[] { typeAttributeParam }) : typeAttribute.GetConstructor(Array.Empty<Type>()); ParamAttributesFieldValues.TryGetValue(index - 1, out var fields); var attributeBuilder = attributeParam == null ? new CustomAttributeBuilder(attributeConstructor!, Array.Empty<object>()) : fields != null ? new CustomAttributeBuilder(attributeConstructor!, new object[] { attributeParam }, fields.Item1, fields.Item2) : new CustomAttributeBuilder(attributeConstructor!, new object[] { attributeParam }); paramBuilder.SetCustomAttribute(attributeBuilder); } } if (hasDefaultValue) { paramBuilder.SetConstant(item.DefaultValue!.Value.Value); } index++; } foreach (var customAttributeBuilder in CustomAttributeBuilder) { methodBuilder.SetCustomAttribute(customAttributeBuilder); } return DynamicTypeBuilder; } public DynamicTypeBuilder Build() { return DynamicTypeBuilder; } }
39.022222
218
0.659453
[ "Apache-2.0" ]
carstencodes/dscom
src/dscom.test/builder/DynamicMethodBuilder.cs
7,024
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using MaterialUI; namespace StackMaps { /// <summary> /// This manages the display of libraries and floors on the sidebar. It loads /// the libraries and floors. When the user wants to edit a library, /// information should be copied from this class to the EditAreaController. /// </summary> public class LibraryExplorer : MonoBehaviour { public ExpandButton expandButton; public SidebarElement container; public SidebarElement defaultCell; public GameObject loadingPanel; public GameObject loadFailedPanel; public GameObject emptyPanel; public LibraryCell libraryCellPrefab; public LibraryViewController libraryViewController; [SerializeField] public List<Library> libraries; public enum DisplayMode { Loading, LoadFailed, Loaded } void Start() { UpdateLibraries(); } public void UpdateLibraries() { // We want to reset all the libraries. Does not change the current editing // floor. libraries = null; defaultCell.Show(true, true); SetMode(DisplayMode.Loading); ServiceController.shared.GetLibraryList((success, list) => { if (success) { libraries = list; SetMode(DisplayMode.Loaded); defaultCell.Show(libraries.Count == 0, true); ConfigureCells(); } else { // Failed to load the library. SetMode(DisplayMode.LoadFailed); } }); } public void SetMode(DisplayMode mode) { loadingPanel.SetActive(mode == DisplayMode.Loading); loadFailedPanel.SetActive(mode == DisplayMode.LoadFailed); emptyPanel.SetActive(mode == DisplayMode.Loaded && libraries != null && libraries.Count == 0); } public void OnExpandButtonPress() { // We want to show or hide everything in the panel. container.Show(expandButton.isExpanded, true); } public void ConfigureCells() { // Remove for (int i = 1; i < container.transform.childCount; i++) { Destroy(container.transform.GetChild(i).gameObject); } // Add for (int i = 0; i < libraries.Count; i++) { int capture = i; LibraryCell cell = Instantiate(libraryCellPrefab, container.transform); cell.SetLibrary(libraries[i]); cell.selectButton.buttonObject.onClick.AddListener(() => OnLibraryCellPress(capture)); } } void OnLibraryCellPress(int index) { // Configure library view controller. if (libraries[index].floors == null) { // We need to load this library from server first! That means a loading // dialog. DialogComplexProgress d = (DialogComplexProgress)DialogManager.CreateComplexProgressLinear(); d.Initialize("Getting library floor plans...", "Loading", MaterialIconHelper.GetIcon(MaterialIconEnum.HOURGLASS_EMPTY)); d.InitializeCancelButton("Cancel", () => { ServiceController.shared.CancelGetLibrary(); d.Hide(); }); d.Show(); ServiceController.shared.GetLibrary(libraries[index].libraryId, (success, lib) => { d.Hide(); if (success) { // Load the library. libraries[index] = lib; libraryViewController.Show(libraries[index]); } else { // Display error. DialogManager.ShowAlert("Unable to connect to server!", "Connection Error", MaterialIconHelper.GetIcon(MaterialIconEnum.ERROR)); } }); } else { libraryViewController.Show(libraries[index]); } } } }
32.324561
128
0.640434
[ "MIT" ]
stack-maps/map-editor
Assets/Scripts/MapEditor/Views/LibraryExplorer.cs
3,687
C#
using System.Reflection; using NodeCanvas.Framework; using NodeCanvas.Framework.Internal; using ParadoxNotion; using ParadoxNotion.Design; using ParadoxNotion.Serialization; using UnityEngine; using System.Linq; namespace NodeCanvas.Tasks.Conditions { [Name("Check Property (mp)")] [Category("✫ Script Control/Multiplatform")] [Description("Check a property on a script and return if it's equal or not to the check value")] public class CheckProperty_Multiplatform : ConditionTask { [SerializeField] protected SerializedMethodInfo method; [SerializeField] protected BBObjectParameter checkValue; [SerializeField] protected CompareMethod comparison; private MethodInfo targetMethod { get { return method != null ? method.Get() : null; } } public override System.Type agentType { get { if ( targetMethod == null ) { return typeof(Transform); } return targetMethod.IsStatic ? null : targetMethod.RTReflectedOrDeclaredType(); } } protected override string info { get { if ( method == null ) { return "No Property Selected"; } if ( targetMethod == null ) { return string.Format("<color=#ff6457>* {0} *</color>", method.GetMethodString()); } var mInfo = targetMethod.IsStatic ? targetMethod.RTReflectedOrDeclaredType().FriendlyName() : agentInfo; return string.Format("{0}.{1}{2}", mInfo, targetMethod.Name, OperationTools.GetCompareString(comparison) + checkValue.ToString()); } } public override void OnValidate(ITaskSystem ownerSystem) { if ( method != null && method.HasChanged() ) { SetMethod(method.Get()); } if ( method != null && method.Get() == null ) { Error(string.Format("Missing Property '{0}'", method.GetMethodString())); } } //store the method info on agent set for performance protected override string OnInit() { if ( targetMethod == null ) { return "CheckProperty Error"; } return null; } //do it by invoking method protected override bool OnCheck() { var instance = targetMethod.IsStatic ? null : agent; if ( checkValue.varType == typeof(float) ) { return OperationTools.Compare((float)targetMethod.Invoke(instance, null), (float)checkValue.value, comparison, 0.05f); } if ( checkValue.varType == typeof(int) ) { return OperationTools.Compare((int)targetMethod.Invoke(instance, null), (int)checkValue.value, comparison); } return ObjectUtils.TrueEquals(targetMethod.Invoke(instance, null), checkValue.value); } void SetMethod(MethodInfo method) { if ( method != null ) { this.method = new SerializedMethodInfo(method); this.checkValue.SetType(method.ReturnType); comparison = CompareMethod.EqualTo; } } ///---------------------------------------------------------------------------------------------- ///---------------------------------------UNITY EDITOR------------------------------------------- #if UNITY_EDITOR protected override void OnTaskInspectorGUI() { if ( !Application.isPlaying && GUILayout.Button("Select Property") ) { var menu = new UnityEditor.GenericMenu(); if ( agent != null ) { foreach ( var comp in agent.GetComponents(typeof(Component)).Where(c => c.hideFlags == 0) ) { menu = EditorUtils.GetInstanceMethodSelectionMenu(comp.GetType(), typeof(object), typeof(object), SetMethod, 0, true, true, menu); } menu.AddSeparator("/"); } foreach ( var t in TypePrefs.GetPreferedTypesList(typeof(object)) ) { menu = EditorUtils.GetStaticMethodSelectionMenu(t, typeof(object), typeof(object), SetMethod, 0, true, true, menu); if ( typeof(UnityEngine.Component).IsAssignableFrom(t) ) { menu = EditorUtils.GetInstanceMethodSelectionMenu(t, typeof(object), typeof(object), SetMethod, 0, true, true, menu); } } menu.ShowAsBrowser("Select Property", this.GetType()); Event.current.Use(); } if ( targetMethod != null ) { GUILayout.BeginVertical("box"); UnityEditor.EditorGUILayout.LabelField("Type", targetMethod.RTReflectedOrDeclaredType().FriendlyName()); UnityEditor.EditorGUILayout.LabelField("Property", targetMethod.Name); GUILayout.EndVertical(); GUI.enabled = checkValue.varType == typeof(float) || checkValue.varType == typeof(int); comparison = (CompareMethod)UnityEditor.EditorGUILayout.EnumPopup("Comparison", comparison); GUI.enabled = true; NodeCanvas.Editor.BBParameterEditor.ParameterField("Value", checkValue); } } #endif } }
41.761538
154
0.557745
[ "MIT" ]
Marcgs96/Guild-Master
Guild Master/Assets/ParadoxNotion/NodeCanvas/Tasks/Conditions/ScriptControl/Multiplatform/CheckProperty_Multiplatform.cs
5,433
C#
using System.Collections.Generic; using UnityEngine; namespace XFramework.UI { /// <summary> /// 形状绘制基类 /// </summary> public abstract class ShapeGraphicBase { public abstract void GetVertexs(ref List<UIVertex> vertexs); public abstract void GetTriangles(ref List<int> triangles, int offset); } }
24.142857
79
0.677515
[ "Apache-2.0" ]
xdedzl/XFramework
XFramework/Assets/XFramework/Core/Runtime/Modules/UI/Core/Component/ShapeGraphic/ShapeGraphicBase.cs
352
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.Network.V20200401 { /// <summary> /// Service End point policy resource. /// </summary> public partial class ServiceEndpointPolicy : Pulumi.CustomResource { /// <summary> /// A unique read-only string that changes whenever the resource is updated. /// </summary> [Output("etag")] public Output<string> Etag { get; private set; } = null!; /// <summary> /// Resource location. /// </summary> [Output("location")] public Output<string?> Location { get; private set; } = null!; /// <summary> /// Resource name. /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; /// <summary> /// The provisioning state of the service endpoint policy resource. /// </summary> [Output("provisioningState")] public Output<string> ProvisioningState { get; private set; } = null!; /// <summary> /// The resource GUID property of the service endpoint policy resource. /// </summary> [Output("resourceGuid")] public Output<string> ResourceGuid { get; private set; } = null!; /// <summary> /// A collection of service endpoint policy definitions of the service endpoint policy. /// </summary> [Output("serviceEndpointPolicyDefinitions")] public Output<ImmutableArray<Outputs.ServiceEndpointPolicyDefinitionResponse>> ServiceEndpointPolicyDefinitions { get; private set; } = null!; /// <summary> /// A collection of references to subnets. /// </summary> [Output("subnets")] public Output<ImmutableArray<Outputs.SubnetResponse>> Subnets { get; private set; } = null!; /// <summary> /// Resource tags. /// </summary> [Output("tags")] public Output<ImmutableDictionary<string, string>?> Tags { get; private set; } = null!; /// <summary> /// Resource type. /// </summary> [Output("type")] public Output<string> Type { get; private set; } = null!; /// <summary> /// Create a ServiceEndpointPolicy resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public ServiceEndpointPolicy(string name, ServiceEndpointPolicyArgs args, CustomResourceOptions? options = null) : base("azure-nextgen:network/v20200401:ServiceEndpointPolicy", name, args ?? new ServiceEndpointPolicyArgs(), MakeResourceOptions(options, "")) { } private ServiceEndpointPolicy(string name, Input<string> id, CustomResourceOptions? options = null) : base("azure-nextgen:network/v20200401:ServiceEndpointPolicy", name, null, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, Aliases = { new Pulumi.Alias { Type = "azure-nextgen:network/latest:ServiceEndpointPolicy"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20180701:ServiceEndpointPolicy"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20180801:ServiceEndpointPolicy"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20181001:ServiceEndpointPolicy"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20181101:ServiceEndpointPolicy"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20181201:ServiceEndpointPolicy"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190201:ServiceEndpointPolicy"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190401:ServiceEndpointPolicy"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190601:ServiceEndpointPolicy"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190701:ServiceEndpointPolicy"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190801:ServiceEndpointPolicy"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190901:ServiceEndpointPolicy"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20191101:ServiceEndpointPolicy"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20191201:ServiceEndpointPolicy"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200301:ServiceEndpointPolicy"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200501:ServiceEndpointPolicy"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200601:ServiceEndpointPolicy"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200701:ServiceEndpointPolicy"}, }, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing ServiceEndpointPolicy resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static ServiceEndpointPolicy Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new ServiceEndpointPolicy(name, id, options); } } public sealed class ServiceEndpointPolicyArgs : Pulumi.ResourceArgs { /// <summary> /// Resource ID. /// </summary> [Input("id")] public Input<string>? Id { get; set; } /// <summary> /// Resource location. /// </summary> [Input("location")] public Input<string>? Location { get; set; } /// <summary> /// The name of the resource group. /// </summary> [Input("resourceGroupName", required: true)] public Input<string> ResourceGroupName { get; set; } = null!; [Input("serviceEndpointPolicyDefinitions")] private InputList<Inputs.ServiceEndpointPolicyDefinitionArgs>? _serviceEndpointPolicyDefinitions; /// <summary> /// A collection of service endpoint policy definitions of the service endpoint policy. /// </summary> public InputList<Inputs.ServiceEndpointPolicyDefinitionArgs> ServiceEndpointPolicyDefinitions { get => _serviceEndpointPolicyDefinitions ?? (_serviceEndpointPolicyDefinitions = new InputList<Inputs.ServiceEndpointPolicyDefinitionArgs>()); set => _serviceEndpointPolicyDefinitions = value; } /// <summary> /// The name of the service endpoint policy. /// </summary> [Input("serviceEndpointPolicyName", required: true)] public Input<string> ServiceEndpointPolicyName { get; set; } = null!; [Input("tags")] private InputMap<string>? _tags; /// <summary> /// Resource tags. /// </summary> public InputMap<string> Tags { get => _tags ?? (_tags = new InputMap<string>()); set => _tags = value; } public ServiceEndpointPolicyArgs() { } } }
44.289474
156
0.613428
[ "Apache-2.0" ]
test-wiz-sec/pulumi-azure-nextgen
sdk/dotnet/Network/V20200401/ServiceEndpointPolicy.cs
8,415
C#
using MessageBox.Messages; using System.Buffers; namespace MessageBox { public interface IMessageSink { Task OnReceivedMessage(IMessage message, CancellationToken cancellationToken = default); } }
19.909091
96
0.748858
[ "MIT" ]
adospace/message-box
src/MessageBox.Core/IMessageSink.cs
221
C#
#region License // Copyright (c) 2007 James Newton-King // // 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. #endregion using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Globalization; #if NET20 using Medivh.Json.Utilities.LinqBridge; #else using System.Linq; #endif namespace Medivh.Json.Utilities { internal interface IWrappedCollection : IList { object UnderlyingCollection { get; } } internal class CollectionWrapper<T> : ICollection<T>, IWrappedCollection { private readonly IList _list; private readonly ICollection<T> _genericCollection; private object _syncRoot; public CollectionWrapper(IList list) { ValidationUtils.ArgumentNotNull(list, nameof(list)); if (list is ICollection<T>) { _genericCollection = (ICollection<T>)list; } else { _list = list; } } public CollectionWrapper(ICollection<T> list) { ValidationUtils.ArgumentNotNull(list, nameof(list)); _genericCollection = list; } public virtual void Add(T item) { if (_genericCollection != null) { _genericCollection.Add(item); } else { _list.Add(item); } } public virtual void Clear() { if (_genericCollection != null) { _genericCollection.Clear(); } else { _list.Clear(); } } public virtual bool Contains(T item) { if (_genericCollection != null) { return _genericCollection.Contains(item); } else { return _list.Contains(item); } } public virtual void CopyTo(T[] array, int arrayIndex) { if (_genericCollection != null) { _genericCollection.CopyTo(array, arrayIndex); } else { _list.CopyTo(array, arrayIndex); } } public virtual int Count { get { if (_genericCollection != null) { return _genericCollection.Count; } else { return _list.Count; } } } public virtual bool IsReadOnly { get { if (_genericCollection != null) { return _genericCollection.IsReadOnly; } else { return _list.IsReadOnly; } } } public virtual bool Remove(T item) { if (_genericCollection != null) { return _genericCollection.Remove(item); } else { bool contains = _list.Contains(item); if (contains) { _list.Remove(item); } return contains; } } public virtual IEnumerator<T> GetEnumerator() { if (_genericCollection != null) { return _genericCollection.GetEnumerator(); } return _list.Cast<T>().GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { if (_genericCollection != null) { return _genericCollection.GetEnumerator(); } else { return _list.GetEnumerator(); } } int IList.Add(object value) { VerifyValueType(value); Add((T)value); return (Count - 1); } bool IList.Contains(object value) { if (IsCompatibleObject(value)) { return Contains((T)value); } return false; } int IList.IndexOf(object value) { if (_genericCollection != null) { throw new InvalidOperationException("Wrapped ICollection<T> does not support IndexOf."); } if (IsCompatibleObject(value)) { return _list.IndexOf((T)value); } return -1; } void IList.RemoveAt(int index) { if (_genericCollection != null) { throw new InvalidOperationException("Wrapped ICollection<T> does not support RemoveAt."); } _list.RemoveAt(index); } void IList.Insert(int index, object value) { if (_genericCollection != null) { throw new InvalidOperationException("Wrapped ICollection<T> does not support Insert."); } VerifyValueType(value); _list.Insert(index, (T)value); } bool IList.IsFixedSize { get { if (_genericCollection != null) { // ICollection<T> only has IsReadOnly return _genericCollection.IsReadOnly; } else { return _list.IsFixedSize; } } } void IList.Remove(object value) { if (IsCompatibleObject(value)) { Remove((T)value); } } object IList.this[int index] { get { if (_genericCollection != null) { throw new InvalidOperationException("Wrapped ICollection<T> does not support indexer."); } return _list[index]; } set { if (_genericCollection != null) { throw new InvalidOperationException("Wrapped ICollection<T> does not support indexer."); } VerifyValueType(value); _list[index] = (T)value; } } void ICollection.CopyTo(Array array, int arrayIndex) { CopyTo((T[])array, arrayIndex); } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { if (_syncRoot == null) { Interlocked.CompareExchange(ref _syncRoot, new object(), null); } return _syncRoot; } } private static void VerifyValueType(object value) { if (!IsCompatibleObject(value)) { throw new ArgumentException("The value '{0}' is not of type '{1}' and cannot be used in this generic collection.".FormatWith(CultureInfo.InvariantCulture, value, typeof(T)), nameof(value)); } } private static bool IsCompatibleObject(object value) { if (!(value is T) && (value != null || (typeof(T).IsValueType() && !ReflectionUtils.IsNullableType(typeof(T))))) { return false; } return true; } public object UnderlyingCollection { get { if (_genericCollection != null) { return _genericCollection; } else { return _list; } } } } }
26.028736
205
0.482667
[ "Apache-2.0" ]
larrymshi/medivh.client-csharp
src/Medivh/Json/Utilities/CollectionWrapper.cs
9,060
C#
using RPG.Data.Context; using RPG.Domain.Models; using RPG.Domain.Response; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RPG.Data.Repository.AuthRepository { public class AuthRepository : IAuthRepository { private readonly DataContext _dataContext; public AuthRepository(DataContext dataContext) { _dataContext = dataContext; } public async Task<ServiceResponse<string>> Login(string userName, string password) { throw new NotImplementedException(); } public async Task<ServiceResponse<int>> Regester(User user, string password) { await _dataContext.User.AddAsync(user); } public async Task<bool> UserExists(string userName) { throw new NotImplementedException(); } public async Task<bool> SaveChanges() { return _dataContext.SaveChanges > 0; } } }
24.52381
90
0.649515
[ "MIT" ]
HusseinShukri/DotNET-RPG
RPG/RPG.DB/Repository/AuthRepository/.vshistory/AuthRepository.cs/2021-08-09_22_16_57_495.cs
1,032
C#
using System; using Aras.IOM; namespace External_Input_Example { public partial class Login : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Submit_Click(object sender, EventArgs e) { string myTitle = PRTitle.Text; string myDescription = PRDesc.Text; string mySteps2Rep = PRStepsRepeat.Text; if (myTitle == "" || myDescription == "") Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "MyAlert", "<script>alert('Please fill in required fields of PR Title and PR Description!!!')</script>"); else { String url = url_text.Text; String db = db_text.Text; String user = user_text.Text; String password = password_text.Text; HttpServerConnection conn = IomFactory.CreateHttpServerConnection(url, db, user, password); Item login_result = conn.Login(); if (login_result.isError()) { throw new Exception("Login failed:" + login_result.getErrorDetail()); } Innovator inn = IomFactory.CreateInnovator(conn); Item myPR = inn.newItem("PR", "add"); myPR.setProperty("title", myTitle); myPR.setProperty("description", myDescription); myPR.setProperty("events", mySteps2Rep); myPR.apply(); conn.Logout(); Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "MyAlert", "<script>alert('Your PR was created successfully!!!')</script>"); } } } }
38.8
181
0.56071
[ "MIT" ]
ArasLabs/External-Input-Example
Visual Studio Solution/External_Input_Example/Default.aspx.cs
1,746
C#
 /*=================================================================================== * * Copyright (c) Userware/OpenSilver.net * * This file is part of the OpenSilver Runtime (https://opensilver.net), which is * licensed under the MIT license: https://opensource.org/licenses/MIT * * As stated in the MIT license, "the above copyright notice and this permission * notice shall be included in all copies or substantial portions of the Software." * \*====================================================================================*/ #if MIGRATION using System.Windows.Data; #else using Windows.UI.Xaml.Data; #endif #if MIGRATION namespace System.Windows.Controls #else namespace Windows.UI.Xaml.Controls #endif { /// <summary> /// Serves as the base class for columns that can bind to a property in the data /// source of a <see cref="DataGrid"/>. /// </summary> public partial class DataGridBoundColumn { private Binding _clipboardContentBinding; protected DataGridBoundColumn() { } [OpenSilver.NotImplemented] public Style EditingElementStyle { get; set; } [OpenSilver.NotImplemented] public Style ElementStyle { get; set; } [OpenSilver.NotImplemented] internal override FrameworkElement GenerateEditingElement(object childData) { //return GenerateElement(childData, true); return null; } /// <summary> /// When overridden in a derived class, gets an editing element that is bound to the column's <see cref="P:System.Windows.Controls.DataGridBoundColumn.Binding" /> property value. /// </summary> /// <param name="cell"> /// The cell that will contain the generated element. /// </param> /// <param name="dataItem"> /// The data item represented by the row that contains the intended cell. /// </param> /// <returns> /// A new editing element that is bound to the column's <see cref="P:System.Windows.Controls.DataGridBoundColumn.Binding" /> property value. /// </returns> protected abstract FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem); [OpenSilver.NotImplemented] protected abstract object PrepareCellForEdit(FrameworkElement editingElement, RoutedEventArgs editingEventArgs); /// <summary> /// The binding that will be used to get or set cell content for the clipboard. /// </summary> public virtual Binding ClipboardContentBinding { get { return this._clipboardContentBinding; } set { this._clipboardContentBinding = value; } } } }
31.21978
186
0.594157
[ "MIT" ]
Barjonp/OpenSilver
src/Runtime/Runtime/System.Windows.Controls/WORKINPROGRESS/DataGridBoundColumn.cs
2,843
C#
using System; using System.Collections.Generic; using System.Linq; using UnityEditor; using UnityEngine; using UnityObject = UnityEngine.Object; namespace Unity.InteractiveTutorials { class InstantiatePrefabCriterion : Criterion { [SerializeField] GameObject m_PrefabParent; [SerializeField] FuturePrefabInstanceCollection m_FuturePrefabInstances = new FuturePrefabInstanceCollection(); // InstanceID's of existing GameObject prefab instance roots we want to ignore HashSet<int> m_ExistingPrefabInstances = new HashSet<int>(); // InstanceID of GameObject prefab instance root that initially completed this criterion int m_PrefabInstance; public GameObject prefabParent { get { return m_PrefabParent; } set { m_PrefabParent = value; OnValidate(); } } public void SetFuturePrefabInstances(IList<UnityObject> prefabParents) { var futurePrefabInstances = prefabParents.Select(prefabParent => new FuturePrefabInstance(prefabParent)); m_FuturePrefabInstances.SetItems(futurePrefabInstances.ToList()); OnValidate(); } protected override void OnValidate() { base.OnValidate(); if (m_PrefabParent == null) return; // Ensure prefab parent is infact a prefab parent if (PrefabUtility.GetPrefabAssetType(m_PrefabParent) != PrefabAssetType.NotAPrefab) { // Ensure prefab parent is the prefab root var prefabRoot = m_PrefabParent.transform.root.gameObject; if (m_PrefabParent != prefabRoot) m_PrefabParent = prefabRoot; } else { Debug.LogWarning("Prefab parent must either be a prefab parent or a prefab instance."); m_PrefabParent = null; } // Prevent aliasing of future reference whenever the last item is copied var count = m_FuturePrefabInstances.count; if (count >= 2) { var last = m_FuturePrefabInstances[count - 1]; var secondLast = m_FuturePrefabInstances[count - 2]; if (last.futureReference == secondLast.futureReference) last.futureReference = null; } var updateFutureReferenceNames = false; var futurePrefabInstanceIndex = -1; foreach (var futurePrefabInstance in m_FuturePrefabInstances) { futurePrefabInstanceIndex++; // Destroy future reference if prefab parent is null or it changed var prefabParent = futurePrefabInstance.prefabParent; var previousPrefabParent = futurePrefabInstance.previousPrefabParent; futurePrefabInstance.previousPrefabParent = prefabParent; if (prefabParent == null || (previousPrefabParent != null && prefabParent != previousPrefabParent)) { if (futurePrefabInstance.futureReference != null) { DestroyImmediate(futurePrefabInstance.futureReference, true); futurePrefabInstance.futureReference = null; } } if (prefabParent == null) continue; // Ensure future prefab parent is infact a prefab parent if (PrefabUtility.GetPrefabAssetType(prefabParent) != PrefabAssetType.NotAPrefab) { // Find root game object of future prefab parent GameObject futurePrefabParentRoot = null; if (prefabParent is GameObject) { var gameObject = (GameObject)prefabParent; futurePrefabParentRoot = gameObject.transform.root.gameObject; } else if (prefabParent is Component) { var component = (Component)prefabParent; futurePrefabParentRoot = component.transform.root.gameObject; } // Ensure prefab parent and future prefab parent belong to the same prefab if (futurePrefabParentRoot == m_PrefabParent) { // Create new future reference if it doesn't exist yet if (futurePrefabInstance.futureReference == null) { var referenceName = string.Format("{0}: {1} ({2})", futurePrefabInstanceIndex + 1, prefabParent.name, prefabParent.GetType().Name); futurePrefabInstance.futureReference = CreateFutureObjectReference(referenceName); updateFutureReferenceNames = true; } } else { Debug.LogWarning("Prefab parent and future prefab parent have different prefab objects."); futurePrefabInstance.prefabParent = null; } } else { Debug.LogWarning("Future prefab parent must be either a prefab parent or a prefab instance."); futurePrefabInstance.prefabParent = null; } } if (updateFutureReferenceNames) UpdateFutureObjectReferenceNames(); } public override void StartTesting() { // Record existing prefab instances m_ExistingPrefabInstances.Clear(); foreach (var gameObject in UnityObject.FindObjectsOfType<GameObject>()) { if (PrefabUtilityShim.GetCorrespondingObjectFromSource(gameObject) != null) { var prefabInstanceRoot = PrefabUtility.GetOutermostPrefabInstanceRoot(gameObject); m_ExistingPrefabInstances.Add(prefabInstanceRoot.GetInstanceID()); } } Selection.selectionChanged += OnSelectionChanged; if (completed) EditorApplication.update += OnUpdateWhenCompleted; UpdateCompletion(); } public override void StopTesting() { m_ExistingPrefabInstances.Clear(); Selection.selectionChanged -= OnSelectionChanged; EditorApplication.update -= OnUpdateWhenCompleted; } void OnSelectionChanged() { if (completed) return; foreach (var gameObject in Selection.gameObjects) { if (PrefabUtilityShim.GetCorrespondingObjectFromSource(gameObject) != null) { var prefabInstanceRoot = PrefabUtility.GetOutermostPrefabInstanceRoot(gameObject); if (prefabInstanceRoot == gameObject && m_ExistingPrefabInstances.Add(prefabInstanceRoot.GetInstanceID())) OnPrefabInstantiated(prefabInstanceRoot); } } } void OnPrefabInstantiated(GameObject prefabInstanceRoot) { if (m_PrefabParent == null) return; if (PrefabUtilityShim.GetCorrespondingObjectFromSource(prefabInstanceRoot) == m_PrefabParent) { foreach (var component in prefabInstanceRoot.GetComponentsInChildren<Component>()) { UpdateFutureReferences(component); if (component is Transform) UpdateFutureReferences(component.gameObject); } m_PrefabInstance = prefabInstanceRoot.GetInstanceID(); UpdateCompletion(); } } void OnUpdateWhenCompleted() { if (!completed) { EditorApplication.update -= OnUpdateWhenCompleted; return; } UpdateCompletion(); } bool EvaluateCompletionInternal() { if (m_PrefabInstance == 0) return false; var prefabObject = EditorUtility.InstanceIDToObject(m_PrefabInstance); if (prefabObject == null) { m_ExistingPrefabInstances.Remove(m_PrefabInstance); m_PrefabInstance = 0; return false; } return true; } protected override bool EvaluateCompletion() { var willBeCompleted = EvaluateCompletionInternal(); if (!completed && willBeCompleted) EditorApplication.update += OnUpdateWhenCompleted; return willBeCompleted; } void UpdateFutureReferences(UnityObject prefabInstance) { UnityObject prefabParent = PrefabUtilityShim.GetCorrespondingObjectFromSource(prefabInstance); foreach (var futurePrefabInstance in m_FuturePrefabInstances) { if (futurePrefabInstance.prefabParent == prefabParent) futurePrefabInstance.futureReference.sceneObjectReference.Update(prefabInstance); } } protected override IEnumerable<FutureObjectReference> GetFutureObjectReferences() { return m_FuturePrefabInstances .Select(futurePrefabInstance => futurePrefabInstance.futureReference) .Where(futurePrefabInstance => futurePrefabInstance != null); } public override bool AutoComplete() { if (m_PrefabParent == null) return false; Selection.activeObject = PrefabUtility.InstantiatePrefab(m_PrefabParent); return true; } [Serializable] public class FuturePrefabInstance { [SerializeField] UnityObject m_PrefabParent; UnityObject m_PreviousPrefabParent; [SerializeField, HideInInspector] FutureObjectReference m_FutureReference; public UnityObject prefabParent { get { return m_PrefabParent; } set { m_PrefabParent = value; } } public UnityObject previousPrefabParent { get { return m_PreviousPrefabParent; } set { m_PreviousPrefabParent = value; } } public FutureObjectReference futureReference { get { return m_FutureReference; } set { m_FutureReference = value; } } public FuturePrefabInstance(UnityObject prefabParent) { m_PrefabParent = prefabParent; } } [Serializable] class FuturePrefabInstanceCollection : CollectionWrapper<FuturePrefabInstance> { } } }
37.220779
127
0.54911
[ "Apache-2.0" ]
HomamAl/Homzino-GoKarting-Game
Library/PackageCache/com.unity.learn.iet-framework@0.3.0-preview.5/Framework/Interactive Tutorials/Editor/Criteria/InstantiatePrefabCriterion.cs
11,464
C#
using System; namespace Umbraco.Core { /// <summary> /// Abstract implementation of managed IDisposable. /// </summary> /// <remarks> /// This is for objects that do NOT have unmanaged resources. Use <see cref="DisposableObject"/> /// for objects that DO have unmanaged resources and need to deal with them when disposing. /// /// Can also be used as a pattern for when inheriting is not possible. /// /// See also: https://msdn.microsoft.com/en-us/library/b1yfkh5e%28v=vs.110%29.aspx /// See also: https://lostechies.com/chrispatterson/2012/11/29/idisposable-done-right/ /// /// Note: if an object's ctor throws, it will never be disposed, and so if that ctor /// has allocated disposable objects, it should take care of disposing them. /// </remarks> public abstract class DisposableObjectSlim : IDisposable { private readonly object _locko = new object(); // gets a value indicating whether this instance is disposed. // for internal tests only (not thread safe) public bool Disposed { get; private set; } // implements IDisposable public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private void Dispose(bool disposing) { // can happen if the object construction failed if (_locko == null) return; lock (_locko) { if (Disposed) return; Disposed = true; } if (disposing) DisposeResources(); } protected virtual void DisposeResources() { } } }
31.444444
100
0.592462
[ "MIT" ]
0Neji/Umbraco-CMS
src/Umbraco.Core/DisposableObjectSlim.cs
1,700
C#
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) // This code is distributed under the GNU LGPL (for details please see \doc\license.txt) using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ICSharpCode.Data.EDMDesigner.Core.ObjectModelConverters { public enum ObjectModelConverterExceptionEnum { CSDL, EDM, SSDL } public class ObjectModelConverterException : Exception { public ObjectModelConverterException(string message, string detail, ObjectModelConverterExceptionEnum type) : base(message) { Detail = detail; ExceptionType = type; } public string FullMessage { get { return Message + "\n\nDetailed error message:\n" + Detail; } } public string Detail { get; protected set; } public ObjectModelConverterExceptionEnum ExceptionType { get; protected set; } public override string ToString() { return String.Format("{0}\n{1}", FullMessage, base.ToString()); } } }
27.432432
109
0.747783
[ "MIT" ]
Plankankul/SharpDevelop-w-Framework
src/AddIns/DisplayBindings/Data/ICSharpCode.Data.EDMDesigner.Core/ObjectModelConverters/ObjectModelConverterException.cs
1,017
C#
// ------------------------------------------------------------------------- // Copyright © 2019 Province of British Columbia // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ------------------------------------------------------------------------- namespace HealthGateway.CommonTests.Utils { using System.IO; using System.Security.Claims; using System.Text; using HealthGateway.Common.Utils; using Newtonsoft.Json; using Xunit; /// <summary> /// JsonClaimsPrincipalConverterTest. /// </summary> public class JsonClaimsPrincipalConverterTest { /// <summary> /// ShouldCanConvertClaimsPrincipal. /// </summary> [Fact] public void ShouldCanConvertClaimsPrincipal() { JsonClaimsPrincipalConverter jsonClaimsPrincipalConverter = new JsonClaimsPrincipalConverter(); var actualResult = jsonClaimsPrincipalConverter.CanConvert(typeof(ClaimsPrincipal)); Assert.True(actualResult); } /// <summary> /// ShouldCanConvertNotClaimsPrincipal. /// </summary> [Fact] public void ShouldCanConvertNotClaimsPrincipal() { JsonClaimsPrincipalConverter jsonClaimsPrincipalConverter = new JsonClaimsPrincipalConverter(); var actualResult = jsonClaimsPrincipalConverter.CanConvert(typeof(string)); Assert.False(actualResult); } /// <summary> /// ShouldWriteJson. /// </summary> [Fact] public void ShouldWriteJson() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter writer = new JsonTextWriter(sw)) { ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(); JsonSerializer jsonSerializer = new JsonSerializer(); JsonClaimsPrincipalConverter jsonClaimsPrincipalConverter = new JsonClaimsPrincipalConverter(); jsonClaimsPrincipalConverter.WriteJson(writer, claimsPrincipal, jsonSerializer); } Assert.NotEmpty(sb.ToString()); } /// <summary> /// ShouldReadJson. /// </summary> [Fact] public void ShouldReadJson() { string json = @"{ 'Type': 'mockType', 'Value': 'mockValue', 'ValueType':'mockValueType', 'Issuer':'mockIssuer', 'OriginalIssuer':'mockOriginalIssuer', }"; StringReader textReader = new StringReader(json); using (JsonTextReader reader = new JsonTextReader(textReader)) { JsonSerializer jsonSerializer = new JsonSerializer(); JsonClaimConverter jsonClaimConverter = new JsonClaimConverter(); object actualResult = jsonClaimConverter.ReadJson(reader, typeof(Claim), "existingValue", jsonSerializer); Assert.IsType<Claim>(actualResult); Claim claim = (Claim)actualResult; Assert.Equal("mockType", claim.Type); Assert.Equal("mockValue", claim.Value); Assert.Equal("mockValueType", claim.ValueType); Assert.Equal("mockIssuer", claim.Issuer); Assert.Equal("mockOriginalIssuer", claim.OriginalIssuer); } } } }
38.359223
122
0.594533
[ "Apache-2.0" ]
WadeBarnes/healthgateway
Apps/Common/test/unit/Utils/JsonClaimsPrincipalConverterTest.cs
3,952
C#
/** * @file * @brief stringの拡張メソッド */ using System; using System.Text; namespace ThunderEgg.Extentions { /// <summary>stringの拡張メソッド</summary> public static class StringExtension { #region static methods /// <summary>コピーを返す</summary> /// <seealso cref="string.Copy(string)"/> public static string Copy(this string @this) { return string.Copy(@this); } /// <summary>書式から文字列を生成する</summary> /// <seealso cref="string.Format(string, object[])"/> public static string format(this string @this, params object[] args) { return string.Format(@this, args); } /// <summary>書式から文字列を生成する</summary> /// <seealso cref="string.Format(string, object)"/> public static string format(this string @this, object arg0) { return string.Format(@this, arg0); } /// <summary>書式から文字列を生成する</summary> /// <seealso cref="string.Format(string, object, object)"/> public static string format(this string @this, object arg0, object arg1) { return string.Format(@this, arg0, arg1); } /// <summary>書式から文字列を生成する</summary> /// <seealso cref="string.Format(string, object, object, object)"/> public static string format(this string @this, object arg0, object arg1, object arg2) { return string.Format(@this, arg0, arg1, arg2); } /// <summary>インターンプールしその文字列を返します</summary> /// <seealso cref="string.Intern(string)"/> public static string Intern(this string @this) { return string.Intern(@this); } /// <summary>インターンプールされているか返します</summary> /// <returns>プールされているなら文字列,プールされてなければnull</returns> /// <seealso cref="string.IsInterned(string)"/> public static string IsInterned(this string @this) { return string.IsInterned(@this); } /// <summary>ヌルもしくは空文字列であるか返します</summary> /// <seealso cref="string.IsNullOrEmpty(string)"/> public static bool IsNullOrEmpty(this string @this) { return string.IsNullOrEmpty(@this); } /// <summary>文字列を連結します</summary> public static string join(this string @this, params string[] values) { return string.Join(@this, values); } /// <summary>文字列を連結します</summary> public static string join(this string @this, string[] values, int start, int count) { return string.Join(@this, values, start, count); } #endregion // // // #region option /// <summary>文字数を返します</summary> public static int RealLength(this string @this) { var count = 0; var hi = '\0'; for (var i = 0; i < @this.Length; ++i) { var lo = @this[i]; if (!char.IsSurrogatePair(hi, lo)) { hi = lo; ++count; } } return count; } #endregion } }
30.176471
95
0.554581
[ "MIT" ]
m5knt/ThunderEgg.Extensions
src/StdTypes/StringExtension.cs
3,424
C#
using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; namespace Standard { [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses")] [StructLayout(LayoutKind.Sequential)] internal class RefPOINT { public int x; public int y; } }
21.875
92
0.694286
[ "MIT" ]
Yerongn/HandyControl
src/Shared/Microsoft.Windows.Shell/Standard/RefPOINT.cs
352
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Security.Cryptography.Tests; using Test.Cryptography; using Xunit; namespace System.Security.Cryptography.EcDiffieHellman.Tests { #if NETCOREAPP public partial class ECDiffieHellmanTests { // On CentOS, secp224r1 (also called nistP224) appears to be disabled. To prevent test failures on that platform, // probe for this capability before depending on it. internal static bool ECDsa224Available => ECDiffieHellmanFactory.IsCurveValid(new Oid(ECDSA_P224_OID_VALUE)); internal static bool CanDeriveNewPublicKey { get; } = EcDiffieHellman.Tests.ECDiffieHellmanFactory.CanDeriveNewPublicKey; [Theory, MemberData(nameof(TestCurvesFull))] public static void TestNamedCurves(CurveDef curveDef) { if (!curveDef.Curve.IsNamed) return; using (ECDiffieHellman ec1 = ECDiffieHellmanFactory.Create(curveDef.Curve)) { ECParameters param1 = ec1.ExportParameters(curveDef.IncludePrivate); VerifyNamedCurve(param1, ec1, curveDef.KeySize, curveDef.IncludePrivate); using (ECDiffieHellman ec2 = ECDiffieHellmanFactory.Create()) { ec2.ImportParameters(param1); ECParameters param2 = ec2.ExportParameters(curveDef.IncludePrivate); VerifyNamedCurve(param2, ec2, curveDef.KeySize, curveDef.IncludePrivate); AssertEqual(param1, param2); } } } [Theory, MemberData(nameof(TestInvalidCurves))] public static void TestNamedCurvesNegative(CurveDef curveDef) { if (!curveDef.Curve.IsNamed) return; // An exception may be thrown during Create() if the Oid is bad, or later during native calls Assert.Throws<PlatformNotSupportedException>( () => ECDiffieHellmanFactory.Create(curveDef.Curve).ExportParameters(false)); } [Theory, MemberData(nameof(TestCurvesFull))] public static void TestExplicitCurves(CurveDef curveDef) { if (!ECDiffieHellmanFactory.ExplicitCurvesSupported) { return; } using (ECDiffieHellman ec1 = ECDiffieHellmanFactory.Create(curveDef.Curve)) { ECParameters param1 = ec1.ExportExplicitParameters(curveDef.IncludePrivate); VerifyExplicitCurve(param1, ec1, curveDef); using (ECDiffieHellman ec2 = ECDiffieHellmanFactory.Create()) { ec2.ImportParameters(param1); ECParameters param2 = ec2.ExportExplicitParameters(curveDef.IncludePrivate); VerifyExplicitCurve(param1, ec1, curveDef); AssertEqual(param1, param2); } } } [Theory, MemberData(nameof(TestCurves))] public static void TestExplicitCurvesKeyAgree(CurveDef curveDef) { if (!ECDiffieHellmanFactory.ExplicitCurvesSupported) { return; } using (ECDiffieHellman ecdh1Named = ECDiffieHellmanFactory.Create(curveDef.Curve)) { ECParameters ecdh1ExplicitParameters = ecdh1Named.ExportExplicitParameters(true); using (ECDiffieHellman ecdh1Explicit = ECDiffieHellmanFactory.Create()) using (ECDiffieHellman ecdh2 = ECDiffieHellmanFactory.Create(ecdh1ExplicitParameters.Curve)) { ecdh1Explicit.ImportParameters(ecdh1ExplicitParameters); using (ECDiffieHellmanPublicKey ecdh1NamedPub = ecdh1Named.PublicKey) using (ECDiffieHellmanPublicKey ecdh1ExplicitPub = ecdh1Explicit.PublicKey) using (ECDiffieHellmanPublicKey ecdh2Pub = ecdh2.PublicKey) { HashAlgorithmName hash = HashAlgorithmName.SHA256; byte[] ech1Named_ecdh1Named = ecdh1Named.DeriveKeyFromHash(ecdh1NamedPub, hash); byte[] ech1Named_ecdh1Named2 = ecdh1Named.DeriveKeyFromHash(ecdh1NamedPub, hash); byte[] ech1Named_ecdh1Explicit = ecdh1Named.DeriveKeyFromHash(ecdh1ExplicitPub, hash); byte[] ech1Named_ecdh2Explicit = ecdh1Named.DeriveKeyFromHash(ecdh2Pub, hash); byte[] ecdh1Explicit_ecdh1Named = ecdh1Explicit.DeriveKeyFromHash(ecdh1NamedPub, hash); byte[] ecdh1Explicit_ecdh1Explicit = ecdh1Explicit.DeriveKeyFromHash(ecdh1ExplicitPub, hash); byte[] ecdh1Explicit_ecdh1Explicit2 = ecdh1Explicit.DeriveKeyFromHash(ecdh1ExplicitPub, hash); byte[] ecdh1Explicit_ecdh2Explicit = ecdh1Explicit.DeriveKeyFromHash(ecdh2Pub, hash); byte[] ecdh2_ecdh1Named = ecdh2.DeriveKeyFromHash(ecdh1NamedPub, hash); byte[] ecdh2_ecdh1Explicit = ecdh2.DeriveKeyFromHash(ecdh1ExplicitPub, hash); byte[] ecdh2_ecdh2Explicit = ecdh2.DeriveKeyFromHash(ecdh2Pub, hash); byte[] ecdh2_ecdh2Explicit2 = ecdh2.DeriveKeyFromHash(ecdh2Pub, hash); Assert.Equal(ech1Named_ecdh1Named, ech1Named_ecdh1Named2); Assert.Equal(ech1Named_ecdh1Explicit, ecdh1Explicit_ecdh1Named); Assert.Equal(ech1Named_ecdh2Explicit, ecdh2_ecdh1Named); Assert.Equal(ecdh1Explicit_ecdh1Explicit, ecdh1Explicit_ecdh1Explicit2); Assert.Equal(ecdh1Explicit_ecdh2Explicit, ecdh2_ecdh1Explicit); Assert.Equal(ecdh2_ecdh2Explicit, ecdh2_ecdh2Explicit2); } } } } [Fact] public static void TestNamedCurveNegative() { Assert.Throws<PlatformNotSupportedException>( () => ECDiffieHellmanFactory.Create(ECCurve.CreateFromFriendlyName("Invalid")).ExportExplicitParameters(false)); Assert.Throws<PlatformNotSupportedException>( () => ECDiffieHellmanFactory.Create(ECCurve.CreateFromValue("Invalid")).ExportExplicitParameters(false)); } [Fact] public static void TestKeySizeCreateKey() { using (ECDiffieHellman ec = ECDiffieHellmanFactory.Create(ECCurve.NamedCurves.nistP256)) { // Ensure the handle is created Assert.Equal(256, ec.KeySize); ec.Exercise(); ec.KeySize = 521; //nistP521 Assert.Equal(521, ec.KeySize); ec.Exercise(); Assert.ThrowsAny<CryptographicException>(() => ec.KeySize = 9999); } } [Fact] [PlatformSpecific(~TestPlatforms.Android)] // Android does not validate curve parameters public static void TestExplicitImportValidationNegative() { if (!ECDiffieHellmanFactory.ExplicitCurvesSupported) { return; } unchecked { using (ECDiffieHellman ec = ECDiffieHellmanFactory.Create()) { ECParameters p = EccTestData.GetNistP256ExplicitTestData(); Assert.True(p.Curve.IsPrime); ec.ImportParameters(p); ECParameters temp = p; temp.Q.X = null; Assert.ThrowsAny<CryptographicException>(() => ec.ImportParameters(temp)); temp.Q.X = new byte[] { }; Assert.ThrowsAny<CryptographicException>(() => ec.ImportParameters(temp)); temp.Q.X = new byte[1] { 0x10 }; Assert.ThrowsAny<CryptographicException>(() => ec.ImportParameters(temp)); temp.Q.X = (byte[])p.Q.X.Clone(); --temp.Q.X[0]; Assert.ThrowsAny<CryptographicException>(() => ec.ImportParameters(temp)); temp = p; temp.Q.Y = null; Assert.ThrowsAny<CryptographicException>(() => ec.ImportParameters(temp)); temp.Q.Y = new byte[] { }; Assert.ThrowsAny<CryptographicException>(() => ec.ImportParameters(temp)); temp.Q.Y = new byte[1] { 0x10 }; Assert.ThrowsAny<CryptographicException>(() => ec.ImportParameters(temp)); temp.Q.Y = (byte[])p.Q.Y.Clone(); --temp.Q.Y[0]; Assert.ThrowsAny<CryptographicException>(() => ec.ImportParameters(temp)); temp = p; temp.Curve.A = null; Assert.ThrowsAny<CryptographicException>(() => ec.ImportParameters(temp)); temp.Curve.A = new byte[] { }; Assert.ThrowsAny<CryptographicException>(() => ec.ImportParameters(temp)); temp.Curve.A = new byte[1] { 0x10 }; Assert.ThrowsAny<CryptographicException>(() => ec.ImportParameters(temp)); temp.Curve.A = (byte[])p.Curve.A.Clone(); --temp.Curve.A[0]; Assert.ThrowsAny<CryptographicException>(() => ec.ImportParameters(temp)); temp = p; temp.Curve.B = null; Assert.ThrowsAny<CryptographicException>(() => ec.ImportParameters(temp)); temp.Curve.B = new byte[] { }; Assert.ThrowsAny<CryptographicException>(() => ec.ImportParameters(temp)); temp.Curve.B = new byte[1] { 0x10 }; Assert.ThrowsAny<CryptographicException>(() => ec.ImportParameters(temp)); temp.Curve.B = (byte[])p.Curve.B.Clone(); --temp.Curve.B[0]; Assert.ThrowsAny<CryptographicException>(() => ec.ImportParameters(temp)); temp = p; temp.Curve.Order = null; Assert.ThrowsAny<CryptographicException>(() => ec.ImportParameters(temp)); temp.Curve.Order = new byte[] { }; Assert.ThrowsAny<CryptographicException>(() => ec.ImportParameters(temp)); temp = p; temp.Curve.Prime = null; Assert.ThrowsAny<CryptographicException>(() => ec.ImportParameters(temp)); temp.Curve.Prime = new byte[] { }; Assert.ThrowsAny<CryptographicException>(() => ec.ImportParameters(temp)); temp.Curve.Prime = new byte[1] { 0x10 }; Assert.ThrowsAny<CryptographicException>(() => ec.ImportParameters(temp)); temp.Curve.Prime = (byte[])p.Curve.Prime.Clone(); --temp.Curve.Prime[0]; Assert.ThrowsAny<CryptographicException>(() => ec.ImportParameters(temp)); } } } [Fact] public static void ImportExplicitWithSeedButNoHash() { if (!ECDiffieHellmanFactory.ExplicitCurvesSupported) { return; } using (ECDiffieHellman ec = ECDiffieHellmanFactory.Create()) { ECCurve curve = EccTestData.GetNistP256ExplicitCurve(); Assert.NotNull(curve.Hash); ec.GenerateKey(curve); ECParameters parameters = ec.ExportExplicitParameters(true); Assert.NotNull(parameters.Curve.Seed); parameters.Curve.Hash = null; ec.ImportParameters(parameters); ec.Exercise(); } } [Fact] [PlatformSpecific(TestPlatforms.Windows/* "parameters.Curve.Hash doesn't round trip on Unix." */)] public static void ImportExplicitWithHashButNoSeed() { if (!ECDiffieHellmanFactory.ExplicitCurvesSupported) { return; } using (ECDiffieHellman ec = ECDiffieHellmanFactory.Create()) { ECCurve curve = EccTestData.GetNistP256ExplicitCurve(); Assert.NotNull(curve.Hash); ec.GenerateKey(curve); ECParameters parameters = ec.ExportExplicitParameters(true); Assert.NotNull(parameters.Curve.Hash); parameters.Curve.Seed = null; ec.ImportParameters(parameters); ec.Exercise(); } } [ConditionalFact(nameof(ECDsa224Available))] public static void TestNamedImportValidationNegative() { if (!ECDiffieHellmanFactory.ExplicitCurvesSupported) { return; } unchecked { using (ECDiffieHellman ec = ECDiffieHellmanFactory.Create()) { ECParameters p = EccTestData.GetNistP224KeyTestData(); Assert.True(p.Curve.IsNamed); var q = p.Q; var c = p.Curve; ec.ImportParameters(p); ECParameters temp = p; temp.Q.X = null; Assert.ThrowsAny<CryptographicException>(() => ec.ImportParameters(temp)); temp.Q.X = new byte[] { }; Assert.ThrowsAny<CryptographicException>(() => ec.ImportParameters(temp)); temp.Q.X = new byte[1] { 0x10 }; Assert.ThrowsAny<CryptographicException>(() => ec.ImportParameters(temp)); temp.Q.X = (byte[])p.Q.X.Clone(); temp.Q.X[0]--; Assert.ThrowsAny<CryptographicException>(() => ec.ImportParameters(temp)); temp = p; temp.Q.Y = null; Assert.ThrowsAny<CryptographicException>(() => ec.ImportParameters(temp)); temp.Q.Y = new byte[] { }; Assert.ThrowsAny<CryptographicException>(() => ec.ImportParameters(temp)); temp.Q.Y = new byte[1] { 0x10 }; Assert.ThrowsAny<CryptographicException>(() => ec.ImportParameters(temp)); temp.Q.Y = (byte[])p.Q.Y.Clone(); temp.Q.Y[0]--; Assert.ThrowsAny<CryptographicException>(() => ec.ImportParameters(temp)); temp = p; temp.Curve = ECCurve.CreateFromOid(new Oid("Invalid", "Invalid")); Assert.ThrowsAny<PlatformNotSupportedException>(() => ec.ImportParameters(temp)); } } } [Fact] public static void TestGeneralExportWithExplicitParameters() { if (!ECDiffieHellmanFactory.ExplicitCurvesSupported) { return; } using (ECDiffieHellman ecdsa = ECDiffieHellmanFactory.Create()) { ECParameters param = EccTestData.GetNistP256ExplicitTestData(); param.Validate(); ecdsa.ImportParameters(param); Assert.True(param.Curve.IsExplicit); param = ecdsa.ExportParameters(false); param.Validate(); // We should have explicit values, not named, as this curve has no name. Assert.True(param.Curve.IsExplicit); } } [Fact] public static void TestExplicitCurveImportOnUnsupportedPlatform() { if (ECDiffieHellmanFactory.ExplicitCurvesSupported) { return; } using (ECDiffieHellman ecdh = ECDiffieHellmanFactory.Create()) { ECParameters param = EccTestData.GetNistP256ExplicitTestData(); Assert.Throws<PlatformNotSupportedException>( () => { try { ecdh.ImportParameters(param); } catch (CryptographicException e) { throw new PlatformNotSupportedException("Converting exception", e); } }); } } [ConditionalFact(nameof(ECDsa224Available))] public static void TestNamedCurveWithExplicitKey() { if (!ECDiffieHellmanFactory.ExplicitCurvesSupported) { return; } using (ECDiffieHellman ec = ECDiffieHellmanFactory.Create()) { ECParameters parameters = EccTestData.GetNistP224KeyTestData(); ec.ImportParameters(parameters); VerifyNamedCurve(parameters, ec, 224, true); } } [Fact] public static void ExportIncludingPrivateOnPublicOnlyKey() { ECParameters iutParameters = new ECParameters { Curve = ECCurve.NamedCurves.nistP521, Q = { X = "00d45615ed5d37fde699610a62cd43ba76bedd8f85ed31005fe00d6450fbbd101291abd96d4945a8b57bc73b3fe9f4671105309ec9b6879d0551d930dac8ba45d255".HexToByteArray(), Y = "01425332844e592b440c0027972ad1526431c06732df19cd46a242172d4dd67c2c8c99dfc22e49949a56cf90c6473635ce82f25b33682fb19bc33bd910ed8ce3a7fa".HexToByteArray(), }, D = "00816f19c1fb10ef94d4a1d81c156ec3d1de08b66761f03f06ee4bb9dcebbbfe1eaa1ed49a6a990838d8ed318c14d74cc872f95d05d07ad50f621ceb620cd905cfb8".HexToByteArray(), }; using (ECDiffieHellman iut = ECDiffieHellmanFactory.Create()) using (ECDiffieHellman cavs = ECDiffieHellmanFactory.Create()) { iut.ImportParameters(iutParameters); cavs.ImportParameters(iut.ExportParameters(false)); Assert.ThrowsAny<CryptographicException>(() => cavs.ExportParameters(true)); if (ECDiffieHellmanFactory.ExplicitCurvesSupported) { Assert.ThrowsAny<CryptographicException>(() => cavs.ExportExplicitParameters(true)); } using (ECDiffieHellmanPublicKey iutPublic = iut.PublicKey) { Assert.ThrowsAny<CryptographicException>(() => cavs.DeriveKeyFromHash(iutPublic, HashAlgorithmName.SHA256)); } } } [ConditionalFact(nameof(CanDeriveNewPublicKey))] public static void ImportFromPrivateOnlyKey() { byte[] expectedX = "00d45615ed5d37fde699610a62cd43ba76bedd8f85ed31005fe00d6450fbbd101291abd96d4945a8b57bc73b3fe9f4671105309ec9b6879d0551d930dac8ba45d255".HexToByteArray(); byte[] expectedY = "01425332844e592b440c0027972ad1526431c06732df19cd46a242172d4dd67c2c8c99dfc22e49949a56cf90c6473635ce82f25b33682fb19bc33bd910ed8ce3a7fa".HexToByteArray(); ECParameters limitedPrivateParameters = new ECParameters { Curve = ECCurve.NamedCurves.nistP521, Q = default, D = "00816f19c1fb10ef94d4a1d81c156ec3d1de08b66761f03f06ee4bb9dcebbbfe1eaa1ed49a6a990838d8ed318c14d74cc872f95d05d07ad50f621ceb620cd905cfb8".HexToByteArray(), }; using (ECDiffieHellman ecdh = ECDiffieHellmanFactory.Create()) { ecdh.ImportParameters(limitedPrivateParameters); ECParameters exportedParameters = ecdh.ExportParameters(true); Assert.Equal(expectedX, exportedParameters.Q.X); Assert.Equal(expectedY, exportedParameters.Q.Y); Assert.Equal(limitedPrivateParameters.D, exportedParameters.D); } } private static void VerifyNamedCurve(ECParameters parameters, ECDiffieHellman ec, int keySize, bool includePrivate) { parameters.Validate(); Assert.True(parameters.Curve.IsNamed); Assert.Equal(keySize, ec.KeySize); Assert.True( includePrivate && parameters.D.Length > 0 || !includePrivate && parameters.D == null); if (includePrivate) ec.Exercise(); // Ensure the key doesn't get regenerated after export ECParameters paramSecondExport = ec.ExportParameters(includePrivate); paramSecondExport.Validate(); AssertEqual(parameters, paramSecondExport); } private static void VerifyExplicitCurve(ECParameters parameters, ECDiffieHellman ec, CurveDef curveDef) { Assert.True(parameters.Curve.IsExplicit); ECCurve curve = parameters.Curve; Assert.True(curveDef.IsCurveTypeEqual(curve.CurveType)); Assert.True( curveDef.IncludePrivate && parameters.D.Length > 0 || !curveDef.IncludePrivate && parameters.D == null); Assert.Equal(curveDef.KeySize, ec.KeySize); Assert.Equal(curve.A.Length, parameters.Q.X.Length); Assert.Equal(curve.A.Length, parameters.Q.Y.Length); Assert.Equal(curve.A.Length, curve.B.Length); Assert.Equal(curve.A.Length, curve.G.X.Length); Assert.Equal(curve.A.Length, curve.G.Y.Length); Assert.True(curve.Seed == null || curve.Seed.Length > 0); Assert.True(curve.Order == null || curve.Order.Length > 0); if (curve.IsPrime) { Assert.Equal(curve.A.Length, curve.Prime.Length); } if (curveDef.IncludePrivate) ec.Exercise(); // Ensure the key doesn't get regenerated after export ECParameters paramSecondExport = ec.ExportExplicitParameters(curveDef.IncludePrivate); AssertEqual(parameters, paramSecondExport); } } #endif }
46.179487
183
0.591153
[ "MIT" ]
C-xC-c/runtime
src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/ECDiffieHellman/ECDiffieHellmanTests.ImportExport.cs
21,612
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. // ReSharper disable InconsistentNaming using System.Threading.Tasks; using Xunit; namespace Microsoft.EntityFrameworkCore.Query { public abstract class TPTInheritanceQueryTestBase<TFixture> : InheritanceQueryTestBase<TFixture> where TFixture : TPTInheritanceQueryFixture, new() { public TPTInheritanceQueryTestBase(TFixture fixture) : base(fixture) { } // Keyless entities does not have TPT public override Task Can_query_all_animal_views(bool async) => Task.CompletedTask; // TPT does not have discriminator public override Task Discriminator_used_when_projection_over_derived_type(bool async) => Task.CompletedTask; // TPT does not have discriminator public override Task Discriminator_used_when_projection_over_derived_type2(bool async) => Task.CompletedTask; // TPT does not have discriminator public override Task Discriminator_used_when_projection_over_of_type(bool async) => Task.CompletedTask; // TPT does not have discriminator public override Task Discriminator_with_cast_in_shadow_property(bool async) => Task.CompletedTask; } }
38.657143
117
0.741316
[ "Apache-2.0" ]
ChristopherHaws/efcore
test/EFCore.Relational.Specification.Tests/Query/TPTInheritanceQueryTestBase.cs
1,355
C#
namespace Fortnite.Model.Responses.WorldInfo { public class MissionWeightOverride { public double weight { get; set; } public string missionGenerator { get; set; } } }
24.5
52
0.663265
[ "MIT" ]
msx752/FTN-Power
src/Fortnite/Fortnite.Model/Responses/WorldInfo/MissionWeightOverride.cs
198
C#
using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using WebStore.Model.Interfaces; using WebStore.ViewModels; using WebStore.Infrastructure.Mappings; namespace WebStore.Components { public class SectionsViewComponent : ViewComponent { private readonly IProductDataProvider _ProductData; public SectionsViewComponent(IProductDataProvider productData) { _ProductData = productData; } public IViewComponentResult Invoke() => View(GetSections()); private IEnumerable<SectionViewModel> GetSections() { var sections = _ProductData.GetSections(); var parentSections = sections.Where(s => s.ParentId == null); IEnumerable<SectionViewModel> childSectionsView; var parentSectionsView = parentSections .Select(s=>new SectionViewModel { Id=s.Id, Name=s.Name, Order=s.Order }) .OrderBy(s=>s.Order).ToArray(); foreach (var parentSectionView in parentSectionsView) { childSectionsView = sections .Where(s => s.ParentId == parentSectionView.Id) .Select((ch) => new SectionViewModel { Id = ch.Id, Name = ch.Name, Order = ch.Order, ParentSection = parentSectionView }).OrderBy(ch=>ch.Order); parentSectionView.ChildSections = childSectionsView.ToList(); } return parentSectionsView; } } }
37.698113
79
0.499499
[ "MIT" ]
SDWT/WebStoreASP
WebStoreASP/Components/SectionsViewComponent.cs
2,000
C#
// Copyright 2018 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // package issue23092 -- go2cs converted at 2020 October 09 06:02:42 UTC // import "go/internal/srcimporter/testdata/issue23092" ==> using issue23092 = go.go.@internal.srcimporter.testdata.issue23092_package // Original source: C:\Go\src\go\internal\srcimporter\testdata\issue23092\issue23092.go }
46.3
134
0.764579
[ "MIT" ]
GridProtectionAlliance/go2cs
src/go-src-converted/go/internal/srcimporter/testdata/issue23092/issue23092.cs
463
C#
using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Threading.Tasks; using Tellma.Api; using Tellma.Api.Base; using Tellma.Api.Dto; using Tellma.Model.Application; using Tellma.Services.Utilities; namespace Tellma.Controllers { [Route("api/document-definitions")] [ApplicationController] [ApiVersion("1.0")] public class DocumentDefinitionsController : CrudControllerBase<DocumentDefinitionForSave, DocumentDefinition, int> { private readonly DocumentDefinitionsService _service; public DocumentDefinitionsController(DocumentDefinitionsService service) { _service = service; } [HttpPut("update-state")] public async Task<ActionResult<EntitiesResponse<Document>>> UpdateState([FromBody] List<int> ids, [FromQuery] UpdateStateArguments args) { var serverTime = DateTimeOffset.UtcNow; var result = await _service.UpdateState(ids, args); var response = TransformToEntitiesResponse(result, serverTime, cancellation: default); Response.Headers.Set("x-definitions-version", Constants.Stale); if (args.ReturnEntities ?? false) { return Ok(response); } else { return Ok(); } } protected override CrudServiceBase<DocumentDefinitionForSave, DocumentDefinition, int> GetCrudService() { return _service; } protected override Task OnSuccessfulSave(EntitiesResult<DocumentDefinition> result) { Response.Headers.Set("x-definitions-version", Constants.Stale); return base.OnSuccessfulSave(result); } protected override Task OnSuccessfulDelete(List<int> ids) { Response.Headers.Set("x-definitions-version", Constants.Stale); return base.OnSuccessfulDelete(ids); } } }
32.508197
144
0.652547
[ "Apache-2.0" ]
lulzzz/tellma
Tellma.Api.Web/Controllers/DocumentDefinitionsController.cs
1,985
C#
namespace Reportr.Registration.Entity.Repositories { using Reportr.Registration.Globalization; using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; /// <summary> /// Represents an Entity Framework registered language repository /// </summary> public sealed class EfRegisteredLanguageRepository : IRegisteredLanguageRepository { private readonly ReportrDbContext _context; /// <summary> /// Constructs the repository with a database context /// </summary> /// <param name="context">The database context</param> public EfRegisteredLanguageRepository ( ReportrDbContext context ) { Validate.IsNotNull(context); _context = context; } /// <summary> /// Adds a single registered language to the repository /// </summary> /// <param name="language">The registered language</param> public void AddLanguage ( RegisteredLanguage language ) { Validate.IsNotNull(language); _context.Set<RegisteredLanguage>().Add ( language ); } /// <summary> /// Gets a registered language from the repository /// </summary> /// <param name="id">The language ID</param> /// <returns>The matching registered language</returns> public RegisteredLanguage GetLanguage ( Guid id ) { var set = _context.Set<RegisteredLanguage>(); var language = set.FirstOrDefault(l => l.Id == id); if (language == null) { throw new KeyNotFoundException ( "The registered language was not found." ); } return language; } /// <summary> /// Finds a registered language in the repository /// </summary> /// <param name="iso">The language ISO</param> /// <returns>The registered language, if found; otherwise null</returns> public RegisteredLanguage FindLanguage ( string iso ) { Validate.IsNotEmpty(iso); var set = _context.Set<RegisteredLanguage>(); return set.FirstOrDefault ( l => l.Iso.Equals(iso, StringComparison.OrdinalIgnoreCase) ); } /// <summary> /// Determines if a language has been registered /// </summary> /// <param name="iso">The language ISO</param> /// <returns>True, if a match was found; otherwise false</returns> public bool HasBeenRegistered ( string iso ) { Validate.IsNotEmpty(iso); var set = _context.Set<RegisteredLanguage>(); return set.Any ( l => l.Iso.Equals(iso, StringComparison.OrdinalIgnoreCase) ); } /// <summary> /// Gets the default registered language from the repository /// </summary> /// <returns>The registered language</returns> public RegisteredLanguage GetDefaultLanguage() { var set = _context.Set<RegisteredLanguage>(); var language = set.FirstOrDefault(l => l.Default); if (language == null) { language = set.FirstOrDefault(); if (language == null) { throw new KeyNotFoundException ( "No languages have been registered." ); } } return language; } /// <summary> /// Gets all registered languages in the repository /// </summary> /// <returns>A collection of registered languages</returns> public IEnumerable<RegisteredLanguage> GetAllLanguages() { var languages = _context.Set<RegisteredLanguage>(); return languages.OrderBy ( a => a.Name ); } /// <summary> /// Updates a single registered language in the repository /// </summary> /// <param name="language">The registered language to update</param> public void UpdateLanguage ( RegisteredLanguage language ) { Validate.IsNotNull(language); var entry = _context.Entry<RegisteredLanguage> ( language ); entry.State = EntityState.Modified; } /// <summary> /// Removes a single registered language from the repository /// </summary> /// <param name="name">The name of the language</param> public void RemoveLanguage ( Guid id ) { var language = GetLanguage(id); var entry = _context.Entry<RegisteredLanguage> ( language ); // Ensure the entity has been attached to the object state manager if (entry.State == EntityState.Detached) { _context.Set<RegisteredLanguage>().Attach ( language ); } _context.Set<RegisteredLanguage>().Remove ( language ); } } }
28.348259
86
0.501404
[ "MIT" ]
JTOne123/Reportr
src/Reportr.Registration.EF6/Repositories/EfRegisteredLanguageRepository.cs
5,700
C#
using System; using System.Collections.Generic; using System.Linq; using EventStore.Projections.Core.Messages; using EventStore.Projections.Core.Services.Processing; using NUnit.Framework; namespace EventStore.Projections.Core.Tests.Services.event_reader.all_streams_with_links_event_reader { namespace when_including_links { [TestFixture] public class when_reading : TestFixtureWithEventReaderService { protected Guid _subscriptionId; private QuerySourcesDefinition _sourceDefinition; protected IReaderStrategy _readerStrategy; protected ReaderSubscriptionOptions _readerSubscriptionOptions; protected override bool GivenHeadingReaderRunning() { return false; } protected override void Given() { base.Given(); AllWritesSucceed(); ExistingEvent("test-stream", "$>", "{}", "{Data: 1}"); ExistingEvent("test-stream", "$>", "{}", "{Data: 2}"); ExistingEvent("test-stream", "$>", "{}", "{Data: 3}"); ExistingEvent("test-stream", "eventType", "{}", "{Data: 4}"); ExistingEvent("test-stream", "eventType", "{}", "{Data: 5}"); ExistingEvent("test-stream", "eventType", "{}", "{Data: 6}"); ExistingEvent("test-stream", "eventType", "{}", "{Data: 7}"); _subscriptionId = Guid.NewGuid(); _sourceDefinition = new QuerySourcesDefinition { ByStreams = true, AllStreams = true, AllEvents = true, Options = new QuerySourcesDefinitionOptions { IncludeLinks = true } }; _readerStrategy = ReaderStrategy.Create( "test", 0, _sourceDefinition, _timeProvider, stopOnEof: true, runAs: null); _readerSubscriptionOptions = new ReaderSubscriptionOptions( checkpointUnhandledBytesThreshold: 10000, checkpointProcessedEventsThreshold: 100, checkpointAfterMs: 10000, stopOnEof: true, stopAfterNEvents: null, enableContentTypeValidation: true); } protected override IEnumerable<WhenStep> When() { var fromZeroPosition = CheckpointTag.FromPosition(0, 0, 0); yield return new ReaderSubscriptionManagement.Subscribe( _subscriptionId, fromZeroPosition, _readerStrategy, _readerSubscriptionOptions); } [Test] public void returns_linked_events() { var receivedEvents = _consumer.HandledMessages.OfType<EventReaderSubscriptionMessage.CommittedEventReceived>().ToArray(); Assert.AreEqual(7, receivedEvents.Length); } } } }
33.082192
105
0.711801
[ "Apache-2.0", "CC0-1.0" ]
ahjohannessen/EventStore
src/EventStore.Projections.Core.Tests/Services/event_reader/all_streams_with_links_event_reader/when_including_links.cs
2,417
C#
namespace EventTraceKit.VsExtension { public interface IDiagLog { void WriteLine(string format, params object[] args); } public class NullDiagLog : IDiagLog { public void WriteLine(string format, params object[] args) { } } }
18.866667
66
0.614841
[ "MIT" ]
gix/event-trace-kit
src/EventTraceKit.VsExtension/IDiagLog.cs
283
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.VisualStudio.IntegrationTest.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities.Input; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpInteractiveCommands : AbstractInteractiveWindowTest { public CSharpInteractiveCommands(VisualStudioInstanceFactory instanceFactory, ITestOutputHelper testOutputHelper) : base(instanceFactory, testOutputHelper) { } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/18779")] public void VerifyPreviousAndNextHistory() { VisualStudio.InteractiveWindow.SubmitText("1 + 2"); VisualStudio.InteractiveWindow.SubmitText("1.ToString()"); VisualStudio.InteractiveWindow.WaitForLastReplOutput("\"1\""); VisualStudio.SendKeys.Send(Alt(VirtualKey.Up)); VisualStudio.InteractiveWindow.Verify.LastReplInput("1.ToString()"); VisualStudio.SendKeys.Send(VirtualKey.Enter); VisualStudio.InteractiveWindow.WaitForLastReplOutput("\"1\""); VisualStudio.SendKeys.Send(Alt(VirtualKey.Up)); VisualStudio.InteractiveWindow.Verify.LastReplInput("1.ToString()"); VisualStudio.SendKeys.Send(Alt(VirtualKey.Up)); VisualStudio.InteractiveWindow.Verify.LastReplInput("1 + 2"); VisualStudio.SendKeys.Send(VirtualKey.Enter); VisualStudio.InteractiveWindow.WaitForLastReplOutput("3"); VisualStudio.SendKeys.Send(Alt(VirtualKey.Down)); VisualStudio.InteractiveWindow.Verify.LastReplInput("1.ToString()"); VisualStudio.SendKeys.Send(VirtualKey.Enter); VisualStudio.InteractiveWindow.WaitForLastReplOutput("\"1\""); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40160")] public void VerifyMaybeExecuteInput() { VisualStudio.InteractiveWindow.InsertCode("2 + 3"); VisualStudio.SendKeys.Send(VirtualKey.Enter); VisualStudio.InteractiveWindow.WaitForLastReplOutput("5"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40160")] public void VerifyNewLineAndIndent() { VisualStudio.InteractiveWindow.InsertCode("3 + "); VisualStudio.SendKeys.Send(VirtualKey.Enter); VisualStudio.InteractiveWindow.InsertCode("4"); VisualStudio.SendKeys.Send(VirtualKey.Enter); VisualStudio.InteractiveWindow.WaitForLastReplOutput("7"); } [WpfFact] public void VerifyExecuteInput() { VisualStudio.InteractiveWindow.SubmitText("1 + "); VisualStudio.InteractiveWindow.WaitForLastReplOutputContains("CS1733"); } [WpfFact] public void VerifyForceNewLineAndIndent() { VisualStudio.InteractiveWindow.InsertCode("1 + 2"); VisualStudio.SendKeys.Send(VirtualKey.Enter); VisualStudio.InteractiveWindow.SubmitText("+ 3"); VisualStudio.InteractiveWindow.WaitForLastReplOutputContains("3"); VisualStudio.InteractiveWindow.Verify.ReplPromptConsistency("<![CDATA[1 + 2 + 3]]>", "6"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40160")] public void VerifyCancelInput() { VisualStudio.InteractiveWindow.InsertCode("1 + 4"); VisualStudio.SendKeys.Send(Shift(VirtualKey.Enter)); VisualStudio.SendKeys.Send(VirtualKey.Escape); VisualStudio.InteractiveWindow.Verify.LastReplInput(string.Empty); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40160")] public void VerifyUndoAndRedo() { VisualStudio.InteractiveWindow.ClearReplText(); VisualStudio.InteractiveWindow.InsertCode(" 2 + 4 "); VisualStudio.SendKeys.Send(Ctrl(VirtualKey.Z)); VisualStudio.InteractiveWindow.Verify.ReplPromptConsistency("< ![CDATA[]] >", string.Empty); VisualStudio.SendKeys.Send(Ctrl(VirtualKey.Y)); VisualStudio.InteractiveWindow.Verify.LastReplInput(" 2 + 4 "); VisualStudio.SendKeys.Send(VirtualKey.Enter); VisualStudio.InteractiveWindow.WaitForLastReplOutput("6"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40160")] public void CutDeletePasteSelectAll() { ClearInteractiveWindow(); VisualStudio.InteractiveWindow.InsertCode("Text"); VisualStudio.ExecuteCommand(WellKnownCommandNames.Edit_LineStart); VisualStudio.ExecuteCommand(WellKnownCommandNames.Edit_LineEnd); VisualStudio.ExecuteCommand(WellKnownCommandNames.Edit_LineStartExtend); VisualStudio.ExecuteCommand(WellKnownCommandNames.Edit_SelectionCancel); VisualStudio.ExecuteCommand(WellKnownCommandNames.Edit_LineEndExtend); VisualStudio.ExecuteCommand(WellKnownCommandNames.Edit_SelectAll); VisualStudio.ExecuteCommand(WellKnownCommandNames.Edit_SelectAll); VisualStudio.ExecuteCommand(WellKnownCommandNames.Edit_Copy); VisualStudio.ExecuteCommand(WellKnownCommandNames.Edit_Cut); VisualStudio.ExecuteCommand(WellKnownCommandNames.Edit_Paste); VisualStudio.InteractiveWindow.WaitForLastReplInputContains("Text"); VisualStudio.InteractiveWindow.Verify.LastReplInput("Text"); VisualStudio.ExecuteCommand(WellKnownCommandNames.Edit_Delete); VisualStudio.ExecuteCommand(WellKnownCommandNames.Edit_LineUp); VisualStudio.ExecuteCommand(WellKnownCommandNames.Edit_LineDown); VisualStudio.ExecuteCommand(WellKnownCommandNames.Edit_Paste); VisualStudio.InteractiveWindow.WaitForLastReplInputContains("TextText"); VisualStudio.InteractiveWindow.Verify.LastReplInput("TextText"); VisualStudio.ExecuteCommand(WellKnownCommandNames.Edit_Paste); VisualStudio.InteractiveWindow.WaitForLastReplInputContains("TextTextText"); VisualStudio.InteractiveWindow.Verify.LastReplInput("TextTextText"); VisualStudio.SendKeys.Send(VirtualKey.Escape); } //<!-- Regression test for bug 13731. // Unfortunately we don't have good unit-test infrastructure to test InteractiveWindow.cs. // For now, since we don't have coverage of InteractiveWindow.IndentCurrentLine at all, // I'd rather have a quick integration test scenario rather than no coverage at all. // At some point when we start investing in Interactive work again, we'll go through some // of these tests and convert them to unit-tests. // --> //<!-- TODO(https://github.com/dotnet/roslyn/issues/4235) [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40160")] public void VerifyReturnIndentCurrentLine() { VisualStudio.InteractiveWindow.ClearScreen(); VisualStudio.SendKeys.Send(" ("); VisualStudio.SendKeys.Send(")"); VisualStudio.SendKeys.Send(VirtualKey.Left); VisualStudio.SendKeys.Send(VirtualKey.Enter); VisualStudio.InteractiveWindow.Verify.CaretPosition(12); } } }
51.597315
121
0.683923
[ "MIT" ]
BertanAygun/roslyn
src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpInteractiveCommands.cs
7,690
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using VolumeControl.ViewModel.Types.Loggers; namespace VolumeControl.Types { public class ViewLogger : ILogger { public void Log(String msg) { var w = MainWindow.WindowSingleton; if (w._Messages != null) { w.Dispatcher.Invoke(() => w._Messages.Text = $"{msg}{Environment.NewLine}{w._Messages.Text}"); } } } }
25.863636
111
0.59754
[ "Unlicense" ]
schlechtums/VolumeControl
src/VolumeControl/VolumeControl/Types/ViewLogger.cs
571
C#
using GTA.Core; namespace GTA.Plugins.Common { partial class OriginalIntman { private sealed class TICKET : External { public override void START( LabelJump label ) { AppendLine( @"2@ = 0 if 2@ == 1 jf @TICKET_60 0@ = Actor.Create(CivFemale, #NULL, 0.0, 0.0, 0.0) :TICKET_60 04ED: load_animation ""CASINO"" :TICKET_70 if 84EE: not animation ""CASINO"" loaded jf @TICKET_102 wait 0 jump @TICKET_70 :TICKET_102 3@ = 1 4@ = 0 :TICKET_116 wait 0 if not Actor.Dead(0@) jf @TICKET_180 if 09C5: unknown_actor 0@ jf @TICKET_166 gosub @TICKET_194 jump @TICKET_173 :TICKET_166 gosub @TICKET_875 :TICKET_173 jump @TICKET_187 :TICKET_180 gosub @TICKET_875 :TICKET_187 jump @TICKET_116 :TICKET_194 0871: init_jump_table 3@ total_jumps 1 default_jump 0 @TICKET_271 jumps 1 @TICKET_257 -1 @TICKET_271 -1 @TICKET_271 -1 @TICKET_271 -1 @TICKET_271 -1 @TICKET_271 -1 @TICKET_271 :TICKET_257 gosub @TICKET_273 jump @TICKET_271 :TICKET_271 return :TICKET_273 0871: init_jump_table 4@ total_jumps 7 default_jump 0 @TICKET_873 jumps 0 @TICKET_336 1 @TICKET_387 2 @TICKET_472 3 @TICKET_566 4 @TICKET_650 5 @TICKET_736 6 @TICKET_830 :TICKET_336 0605: actor 0@ perform_animation ""SLOT_IN"" IFP ""CASINO"" framedelta 4.0 loop 0 lockX 0 lockY 0 lockF 0 time -1 4@ += 1 jump @TICKET_873 :TICKET_387 062E: get_actor 0@ task 1541 status_store_to 2@ if 04A4: 2@ == 7 jf @TICKET_465 0605: actor 0@ perform_animation ""SLOT_BET_01"" IFP ""CASINO"" framedelta 4.0 loop 0 lockX 0 lockY 0 lockF 0 time 2@ 4@ += 1 :TICKET_465 jump @TICKET_873 :TICKET_472 062E: get_actor 0@ task 1541 status_store_to 2@ if 04A4: 2@ == 7 jf @TICKET_559 0209: 2@ = random_int_in_ranges 5000 10000 0605: actor 0@ perform_animation ""SLOT_WAIT"" IFP ""CASINO"" framedelta 4.0 loop 1 lockX 0 lockY 0 lockF 1 time 2@ 4@ += 1 :TICKET_559 jump @TICKET_873 :TICKET_566 062E: get_actor 0@ task 1541 status_store_to 2@ if 04A4: 2@ == 7 jf @TICKET_643 0605: actor 0@ perform_animation ""SLOT_BET_02"" IFP ""CASINO"" framedelta 4.0 loop 0 lockX 0 lockY 0 lockF 0 time -1 4@ += 1 :TICKET_643 jump @TICKET_873 :TICKET_650 062E: get_actor 0@ task 1541 status_store_to 2@ if 04A4: 2@ == 7 jf @TICKET_729 0605: actor 0@ perform_animation ""SLOT_LOSE_OUT"" IFP ""CASINO"" framedelta 4.0 loop 0 lockX 0 lockY 0 lockF 0 time -1 4@ += 1 :TICKET_729 jump @TICKET_873 :TICKET_736 062E: get_actor 0@ task 1541 status_store_to 2@ if 04A4: 2@ == 7 jf @TICKET_823 0209: 2@ = random_int_in_ranges 4000 8000 0605: actor 0@ perform_animation ""SLOT_WAIT"" IFP ""CASINO"" framedelta 4.0 loop 1 lockX 0 lockY 0 lockF 1 time 2@ 4@ += 1 :TICKET_823 jump @TICKET_873 :TICKET_830 062E: get_actor 0@ task 1541 status_store_to 2@ if 04A4: 2@ == 7 jf @TICKET_866 gosub @TICKET_875 :TICKET_866 jump @TICKET_873 :TICKET_873 return :TICKET_875 04EF: release_animation ""CASINO"" end_thread return 0663: printint ""PEDSTATE"" 3@ 0663: printint ""SUBSTATESTATUS"" 4@ 0663: printint ""LOOP_TIMER"" TIMERB 0663: printint ""SCRIPT_TIMER"" TIMERA return end_thread" ); } } } }
21.235669
177
0.669766
[ "Apache-2.0" ]
wmysterio/gta-script-generator
GTA.SA/Plugins/Common/Originals/INTMAN/IntmanTICKET.cs
3,336
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp1.classes { class Dog : IPrintable, IMovable, IRenderable { public string _dogBreed; public Dog(string dogBreed) { _dogBreed = dogBreed; } public bool Moves { get; set; } public bool IsRenderable { get; set; } public void Print() { Console.WriteLine(_dogBreed); } public void Renderable() { Console.WriteLine(_dogBreed + " can be renederable"); } } }
19.333333
65
0.579937
[ "MIT" ]
marciusg/cSharpCoursePractice
Inheritance/ConsoleApp1/classes/Dog.cs
640
C#
using System.Collections.Generic; using System.Linq; using Baseline; using Npgsql; namespace Weasel.Postgresql.SqlGeneration { public static class SqlFragmentExtensions { /// <summary> /// Combine an "and" compound filter with the two filters /// </summary> /// <param name="filter"></param> /// <param name="fragments"></param> /// <returns></returns> public static ISqlFragment CombineAnd(this ISqlFragment filter, ISqlFragment other) { if (filter is CompoundWhereFragment c && c.Separator.EqualsIgnoreCase("and")) { c.Add(other); return c; } return CompoundWhereFragment.And(filter, other); } /// <summary> /// If extras has any items, return an "and" compound fragment. Otherwise return the original filter /// </summary> /// <param name="filter"></param> /// <param name="fragments"></param> /// <returns></returns> public static ISqlFragment CombineAnd(this ISqlFragment filter, IReadOnlyList<ISqlFragment> extras) { if (extras.Any()) { if (filter is CompoundWhereFragment c && c.Separator.EqualsIgnoreCase("and")) { c.Add(extras); return c; } var compound = CompoundWhereFragment.And(extras); compound.Add(filter); return compound; } return filter; } public static ISqlFragment[] Flatten(this ISqlFragment fragment) { if (fragment == null) { return new ISqlFragment[0]; } if (fragment is CompoundWhereFragment c) { return c.Children.ToArray(); } return new[] {fragment}; } public static string ToSql(this ISqlFragment fragment) { if (fragment == null) { return null; } var cmd = new NpgsqlCommand(); var builder = new CommandBuilder(cmd); fragment.Apply(builder); return builder.ToString().Trim(); } } }
28.52439
108
0.508764
[ "MIT" ]
Hawxy/weasel
src/Weasel.Postgresql/SqlGeneration/SqlFragmentExtensions.cs
2,339
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace WindowsFormLogin.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.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; } } } }
35.666667
151
0.584112
[ "MIT" ]
AnweshDahal/windows-form-login
WindowsFormLogin/Properties/Settings.Designer.cs
1,072
C#
// Enum generated by TankLibHelper.EnumBuilder // ReSharper disable All namespace TankLib.STU.Types.Enums { [STUEnumAttribute(0x3BED1D03)] public enum Enum_3BED1D03 : uint { [STUFieldAttribute(0x522E8850)] x522E8850 = 0x0, [STUFieldAttribute(0xBF026E89)] xBF026E89 = 0x1, [STUFieldAttribute(0x8144602D)] x8144602D = 0x2, [STUFieldAttribute(0x52D87F3B)] x52D87F3B = 0x3, } }
26.529412
46
0.656319
[ "MIT" ]
Mike111177/OWLib
TankLib/STU/Types/Enums/Enum_3BED1D03.cs
451
C#
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace Microsoft.Azure.Cosmos.Routing { using System; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.Azure.Cosmos.Collections; using Microsoft.Azure.Cosmos.Query; using Newtonsoft.Json; using Microsoft.Azure.Cosmos.Internal; using Microsoft.Azure.Documents.Routing; using Microsoft.Azure.Documents; using Microsoft.Azure.Documents.Collections; /// <summary> /// Tests for <see cref="PartitionRoutingHelper"/> class. /// </summary> [TestClass] public class PartitionRoutingHelperTest { PartitionRoutingHelper partitionRoutingHelper; public PartitionRoutingHelperTest() { this.partitionRoutingHelper = new PartitionRoutingHelper(); } /// <summary> /// Tests for <see cref="PartitionRoutingHelper.ExtractPartitionKeyRangeFromContinuationToken"/> method. /// </summary> [TestMethod] [TestCategory(TestTypeCategory.Quarantine)] [Ignore] /* TODO: There is a TODO in PartitionRoutingHelper.ExtractPartitionKeyRangeFromContinuationToken that it's refering to some pending deployment */ public void TestExtractPartitionKeyRangeFromHeaders() { Func<string, INameValueCollection> getHeadersWithContinuation = (string continuationToken) => { INameValueCollection headers = new DictionaryNameValueCollection(); headers[HttpConstants.HttpHeaders.Continuation] = continuationToken; return headers; }; using (Stream stream = new MemoryStream(Properties.Resources.BaselineTest_PartitionRoutingHelper_ExtractPartitionKeyRangeFromHeaders)) { using (StreamReader reader = new StreamReader(stream)) { TestSet<ExtractPartitionKeyRangeFromHeadersTestData> testSet = JsonConvert.DeserializeObject<TestSet<ExtractPartitionKeyRangeFromHeadersTestData>>(reader.ReadToEnd()); foreach (ExtractPartitionKeyRangeFromHeadersTestData testData in testSet.Postive) { INameValueCollection headers = getHeadersWithContinuation(testData.CompositeContinuationToken); List<CompositeContinuationToken> suppliedTokens; Range<string> range = this.partitionRoutingHelper.ExtractPartitionKeyRangeFromContinuationToken(headers, out suppliedTokens); if (suppliedTokens != null) { Assert.AreEqual(testData.ContinuationToken, headers[HttpConstants.HttpHeaders.Continuation]); Assert.AreEqual(JsonConvert.SerializeObject(testData.PartitionKeyRange), JsonConvert.SerializeObject(range)); } else { Assert.IsTrue(testData.ContinuationToken == headers[HttpConstants.HttpHeaders.Continuation] || testData.ContinuationToken == null); } } foreach (ExtractPartitionKeyRangeFromHeadersTestData testData in testSet.Negative) { INameValueCollection headers = getHeadersWithContinuation(testData.CompositeContinuationToken); try { List<CompositeContinuationToken> suppliedTokens; Range<string> rangeOrId = this.partitionRoutingHelper.ExtractPartitionKeyRangeFromContinuationToken(headers, out suppliedTokens); Assert.Fail("Expect BadRequestException"); } catch (BadRequestException) { } } } } } /// <summary> /// Tests for <see cref="PartitionRoutingHelper.ExtractPartitionKeyRangeFromContinuationToken"/> method. /// </summary> [TestMethod] [TestCategory(TestTypeCategory.Quarantine)] [Ignore] /* Buffer cannot be null */ public async Task TestAddFormattedContinuationToHeader() { using (Stream stream = new MemoryStream(Properties.Resources.BaselineTest_PartitionRoutingHelper_AddFormattedContinuationToHeader)) { using (StreamReader reader = new StreamReader(stream)) { AddFormattedContinuationToHeaderTestData testData = JsonConvert.DeserializeObject<AddFormattedContinuationToHeaderTestData>(reader.ReadToEnd()); CollectionRoutingMap routingMap = CollectionRoutingMap.TryCreateCompleteRoutingMap( testData.RoutingMap.Select(range => Tuple.Create(range, (ServiceIdentity)null)), string.Empty); RoutingMapProvider routingMapProvider = new RoutingMapProvider(routingMap); foreach (AddFormattedContinuationToHeaderTestUnit positiveTestData in testData.TestSet.Postive) { INameValueCollection headers; List<CompositeContinuationToken> resolvedContinuationTokens; List<PartitionKeyRange> resolvedRanges; this.AddFormattedContinuationHeaderHelper(positiveTestData, out headers, out resolvedRanges, out resolvedContinuationTokens); bool answer = await this.partitionRoutingHelper.TryAddPartitionKeyRangeToContinuationTokenAsync(headers, positiveTestData.ProvidedRanges, routingMapProvider, null, new PartitionRoutingHelper.ResolvedRangeInfo(resolvedRanges[0], (resolvedContinuationTokens.Count > 0) ? resolvedContinuationTokens : null)); Assert.AreEqual(positiveTestData.OutputCompositeContinuationToken, headers[HttpConstants.HttpHeaders.Continuation]); } foreach (AddFormattedContinuationToHeaderTestUnit negativeTestData in testData.TestSet.Negative) { try { INameValueCollection headers; List<CompositeContinuationToken> resolvedContinuationTokens; List<PartitionKeyRange> resolvedRanges; this.AddFormattedContinuationHeaderHelper(negativeTestData, out headers, out resolvedRanges, out resolvedContinuationTokens); bool answer = await this.partitionRoutingHelper.TryAddPartitionKeyRangeToContinuationTokenAsync(headers, negativeTestData.ProvidedRanges, routingMapProvider, null, new PartitionRoutingHelper.ResolvedRangeInfo(resolvedRanges[0], (resolvedContinuationTokens.Count > 0) ? resolvedContinuationTokens : null)); Assert.Fail("Expect BadRequestException"); } catch (BadRequestException) { } catch (InternalServerErrorException) { } } } } } private void AddFormattedContinuationHeaderHelper(AddFormattedContinuationToHeaderTestUnit positiveTestData, out INameValueCollection headers, out List<PartitionKeyRange> resolvedRanges, out List<CompositeContinuationToken> resolvedContinuationTokens) { Func<string, INameValueCollection> getHeadersWithContinuation = (string continuationToken) => { INameValueCollection localHeaders = new DictionaryNameValueCollection(); if (continuationToken != null) { localHeaders[HttpConstants.HttpHeaders.Continuation] = continuationToken; } return localHeaders; }; resolvedRanges = positiveTestData.ResolvedRanges.Select(x => new PartitionKeyRange() { MinInclusive = x.Min, MaxExclusive = x.Max }).ToList(); resolvedContinuationTokens = new List<CompositeContinuationToken>(); CompositeContinuationToken[] initialContinuationTokens = null; if (!string.IsNullOrEmpty(positiveTestData.InputCompositeContinuationToken)) { if (positiveTestData.InputCompositeContinuationToken.Trim().StartsWith("[", StringComparison.Ordinal)) { initialContinuationTokens = JsonConvert.DeserializeObject<CompositeContinuationToken[]>(positiveTestData.InputCompositeContinuationToken); } else { initialContinuationTokens = new CompositeContinuationToken[] { JsonConvert.DeserializeObject<CompositeContinuationToken>(positiveTestData.InputCompositeContinuationToken) }; } } if (resolvedRanges.Count > 1) { CompositeContinuationToken continuationToBeCopied; if (initialContinuationTokens != null && initialContinuationTokens.Length > 0) { continuationToBeCopied = (CompositeContinuationToken) initialContinuationTokens[0].ShallowCopy(); } else { continuationToBeCopied = new CompositeContinuationToken(); continuationToBeCopied.Token = string.Empty; } headers = getHeadersWithContinuation(continuationToBeCopied.Token); foreach (PartitionKeyRange pkrange in resolvedRanges) { CompositeContinuationToken token = (CompositeContinuationToken) continuationToBeCopied.ShallowCopy(); token.Range = pkrange.ToRange(); resolvedContinuationTokens.Add(token); } if (initialContinuationTokens != null) { resolvedContinuationTokens.AddRange(initialContinuationTokens.Skip(1)); } } else { headers = getHeadersWithContinuation(null); } } /// <summary> /// Tests for <see cref="PartitionRoutingHelper.TryGetTargetRangeFromContinuationTokenRangeAsync"/> method. /// </summary> [TestMethod] public async Task TestGetPartitionRoutingInfo() { using (Stream stream = new MemoryStream(Properties.Resources.BaselineTest_PartitionRoutingHelper_GetPartitionRoutingInfo)) { using (StreamReader reader = new StreamReader(stream)) { GetPartitionRoutingInfoTestData testData = JsonConvert.DeserializeObject<GetPartitionRoutingInfoTestData>(reader.ReadToEnd()); CollectionRoutingMap routingMap = CollectionRoutingMap.TryCreateCompleteRoutingMap( testData.RoutingMap.Select(range => Tuple.Create(range, (ServiceIdentity)null)), string.Empty); foreach (GetPartitionRoutingInfoTestCase testCase in testData.TestCases) { List<string> actualPartitionKeyRangeIds = new List<string>(); Range<string> startRange = Range<string>.GetEmptyRange(PartitionKeyInternal.MinimumInclusiveEffectivePartitionKey); for (Range<string> currentRange = startRange; currentRange != null;) { RoutingMapProvider routingMapProvider = new RoutingMapProvider(routingMap); PartitionRoutingHelper.ResolvedRangeInfo resolvedRangeInfo = await this.partitionRoutingHelper.TryGetTargetRangeFromContinuationTokenRangeAsync(testCase.ProvidedRanges, routingMapProvider, string.Empty, currentRange, null); actualPartitionKeyRangeIds.Add(resolvedRangeInfo.ResolvedRange.Id); INameValueCollection headers = new DictionaryNameValueCollection(); await this.partitionRoutingHelper.TryAddPartitionKeyRangeToContinuationTokenAsync(headers, testCase.ProvidedRanges, routingMapProvider, string.Empty, resolvedRangeInfo); List<CompositeContinuationToken> suppliedTokens; Range<string> nextRange = this.partitionRoutingHelper.ExtractPartitionKeyRangeFromContinuationToken(headers, out suppliedTokens); currentRange = nextRange.IsEmpty ? null : nextRange; } Assert.AreEqual(string.Join(", ", testCase.RoutingRangeIds), string.Join(", ", actualPartitionKeyRangeIds)); } } } } private class RoutingMapProvider : IRoutingMapProvider { private readonly CollectionRoutingMap collectionRoutingMap; public RoutingMapProvider(CollectionRoutingMap collectionRoutingMap) { this.collectionRoutingMap = collectionRoutingMap; } public Task<IReadOnlyList<PartitionKeyRange>> TryGetOverlappingRangesAsync(string collectionResourceId, Range<string> range, bool forceRefresh = false) { return Task.FromResult(this.collectionRoutingMap.GetOverlappingRanges(range)); } public Task<PartitionKeyRange> TryGetPartitionKeyRangeByIdAsync(string collectionResourceId, string partitionKeyRangeId, bool forceRefresh = false) { return Task.FromResult(this.collectionRoutingMap.TryGetRangeByPartitionKeyRangeId(partitionKeyRangeId)); } public Task<PartitionKeyRange> TryGetRangeByEffectivePartitionKey(string collectionResourceId, string effectivePartitionKey) { return Task.FromResult(this.collectionRoutingMap.GetOverlappingRanges(Range<string>.GetPointRange(effectivePartitionKey)).Single()); } } private class TestSet<T> { [JsonProperty(PropertyName = "positive")] public T[] Postive { get; set; } [JsonProperty(PropertyName = "negative")] public T[] Negative { get; set; } } private class ExtractPartitionKeyRangeFromHeadersTestData { [JsonProperty(PropertyName = "compositeContinuationToken")] public string CompositeContinuationToken { get; set; } [JsonProperty(PropertyName = "continuationToken")] public string ContinuationToken { get; set; } [JsonProperty(PropertyName = "partitionKeyRange")] public Range<string> PartitionKeyRange { get; set; } } private class AddFormattedContinuationToHeaderTestUnit { [JsonProperty(PropertyName = "inputCompositeContinuationToken")] public string InputCompositeContinuationToken { get; set; } [JsonProperty(PropertyName = "outputCompositeContinuationToken")] public string OutputCompositeContinuationToken { get; set; } [JsonProperty(PropertyName = "resolvedRanges")] public List<Range<string>> ResolvedRanges { get; set; } [JsonProperty(PropertyName = "providedRanges")] public List<Range<string>> ProvidedRanges { get; set; } } private class AddFormattedContinuationToHeaderTestData { [JsonProperty(PropertyName = "testSet")] public TestSet<AddFormattedContinuationToHeaderTestUnit> TestSet { get; set; } [JsonProperty(PropertyName = "routingMap")] public PartitionKeyRange[] RoutingMap { get; set; } } private class GetPartitionRoutingInfoTestCase { [JsonProperty(PropertyName = "providedRanges")] public List<Range<string>> ProvidedRanges { get; set; } [JsonProperty(PropertyName = "routingRangeIds")] public List<string> RoutingRangeIds { get; set; } } private class GetPartitionRoutingInfoTestData { [JsonProperty(PropertyName = "testCases")] public GetPartitionRoutingInfoTestCase[] TestCases { get; set; } [JsonProperty(PropertyName = "routingMap")] public PartitionKeyRange[] RoutingMap { get; set; } } } }
49.645161
333
0.621714
[ "MIT" ]
CasP0/azure-cosmos-dotnet-v3
Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.Tests/Routing/PartitionRoutingHelperTest.cs
16,931
C#
namespace Tests.Resolvers { using System; using System.ComponentModel; using Castle.Facilities.ServiceFabricIntegration.Resolvers; using Castle.MicroKernel; using Castle.Windsor; using Microsoft.ServiceFabric.Actors; using Microsoft.ServiceFabric.Actors.Runtime; using Moq; using ServiceFabric.Mocks; using Xunit; using Component=Castle.MicroKernel.Registration.Component; public class ActorResolverTests { [Fact] public void ConstructorTest() { var kernelMock = new Mock<IKernel>(); new ActorResolver(kernelMock.Object, typeof(Actor)); new ActorResolver(kernelMock.Object, typeof(TestActor)); Assert.Throws<ArgumentException>(() => new ActorResolver(kernelMock.Object, typeof(object))); } [Fact] public void ResolveTest() { using (var container = new WindsorContainer()) { var resolver = new ActorResolver(container.Kernel, typeof(TestActor)); var actorService = MockActorServiceFactory.CreateActorServiceForActor<TestActor>(); Assert.Throws<ComponentNotFoundException>(() => resolver.Resolve(actorService, new ActorId(1))); container.Register( Component.For<TestActor>().LifestyleTransient()); var actor = resolver.Resolve(actorService, new ActorId(1)); Assert.NotNull(actor); var testActor = Assert.IsType<TestActor>(actor); Assert.Equal(new ActorId(1), testActor.ActorId); } } } }
32.92
112
0.625759
[ "MIT" ]
Daedeross/Castle.Facilities.ServiceFabricIntegration
Tests/Resolvers/ActorResolverTests.cs
1,648
C#
//------------------------------------------------------------------------------ // <auto-generated /> // // This file was automatically generated by SWIG (http://www.swig.org). // Version 3.0.10 // // Do not make changes to this file unless you know what you are doing--modify // the SWIG interface file instead. //------------------------------------------------------------------------------ using System; using System.Runtime.InteropServices; namespace Noesis { public class StreamGeometry : Geometry { internal new static StreamGeometry CreateProxy(IntPtr cPtr, bool cMemoryOwn) { return new StreamGeometry(cPtr, cMemoryOwn); } internal StreamGeometry(IntPtr cPtr, bool cMemoryOwn) : base(cPtr, cMemoryOwn) { } internal static HandleRef getCPtr(StreamGeometry obj) { return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr; } public override string ToString() { return ToStringHelper(); } public StreamGeometry(string data) : this(NoesisGUI_PINVOKE.new_StreamGeometry__SWIG_0(data != null ? data : string.Empty), true) { } public StreamGeometry() { } protected override IntPtr CreateCPtr(Type type, out bool registerExtend) { registerExtend = false; return NoesisGUI_PINVOKE.new_StreamGeometry__SWIG_1(); } public void SetData(string data) { NoesisGUI_PINVOKE.StreamGeometry_SetData(swigCPtr, data != null ? data : string.Empty); } public StreamGeometryContext Open() { StreamGeometryContext ret = new StreamGeometryContext(NoesisGUI_PINVOKE.StreamGeometry_Open(swigCPtr), true); return ret; } public override bool IsEmpty() { bool ret = NoesisGUI_PINVOKE.StreamGeometry_IsEmpty(swigCPtr); return ret; } public static DependencyProperty FillRuleProperty { get { IntPtr cPtr = NoesisGUI_PINVOKE.StreamGeometry_FillRuleProperty_get(); return (DependencyProperty)Noesis.Extend.GetProxy(cPtr, false); } } public FillRule FillRule { set { NoesisGUI_PINVOKE.StreamGeometry_FillRule_set(swigCPtr, (int)value); } get { FillRule ret = (FillRule)NoesisGUI_PINVOKE.StreamGeometry_FillRule_get(swigCPtr); return ret; } } private string ToStringHelper() { IntPtr strPtr = NoesisGUI_PINVOKE.StreamGeometry_ToStringHelper(swigCPtr); string str = Noesis.Extend.StringFromNativeUtf8(strPtr); NoesisGUI_PINVOKE.FreeString(strPtr); return str; } } }
28.965517
134
0.65754
[ "MIT" ]
CodingJinxx/gameoff2020
Gameoff2020/Assets/NoesisGUI/Plugins/API/Proxies/StreamGeometry.cs
2,520
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.DesktopVirtualization.V20201110Preview { /// <summary> /// Represents a Workspace definition. /// </summary> [AzureNextGenResourceType("azure-nextgen:desktopvirtualization/v20201110preview:Workspace")] public partial class Workspace : Pulumi.CustomResource { /// <summary> /// List of applicationGroup resource Ids. /// </summary> [Output("applicationGroupReferences")] public Output<ImmutableArray<string>> ApplicationGroupReferences { get; private set; } = null!; /// <summary> /// Description of Workspace. /// </summary> [Output("description")] public Output<string?> Description { get; private set; } = null!; /// <summary> /// Friendly name of Workspace. /// </summary> [Output("friendlyName")] public Output<string?> FriendlyName { get; private set; } = null!; /// <summary> /// The geo-location where the resource lives /// </summary> [Output("location")] public Output<string> Location { get; private set; } = null!; /// <summary> /// The name of the resource /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; /// <summary> /// Resource tags. /// </summary> [Output("tags")] public Output<ImmutableDictionary<string, string>?> Tags { get; private set; } = null!; /// <summary> /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" /// </summary> [Output("type")] public Output<string> Type { get; private set; } = null!; /// <summary> /// Create a Workspace resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public Workspace(string name, WorkspaceArgs args, CustomResourceOptions? options = null) : base("azure-nextgen:desktopvirtualization/v20201110preview:Workspace", name, args ?? new WorkspaceArgs(), MakeResourceOptions(options, "")) { } private Workspace(string name, Input<string> id, CustomResourceOptions? options = null) : base("azure-nextgen:desktopvirtualization/v20201110preview:Workspace", name, null, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, Aliases = { new Pulumi.Alias { Type = "azure-nextgen:desktopvirtualization:Workspace"}, new Pulumi.Alias { Type = "azure-nextgen:desktopvirtualization/v20190123preview:Workspace"}, new Pulumi.Alias { Type = "azure-nextgen:desktopvirtualization/v20190924preview:Workspace"}, new Pulumi.Alias { Type = "azure-nextgen:desktopvirtualization/v20191210preview:Workspace"}, new Pulumi.Alias { Type = "azure-nextgen:desktopvirtualization/v20200921preview:Workspace"}, new Pulumi.Alias { Type = "azure-nextgen:desktopvirtualization/v20201019preview:Workspace"}, new Pulumi.Alias { Type = "azure-nextgen:desktopvirtualization/v20201102preview:Workspace"}, new Pulumi.Alias { Type = "azure-nextgen:desktopvirtualization/v20210114preview:Workspace"}, new Pulumi.Alias { Type = "azure-nextgen:desktopvirtualization/v20210201preview:Workspace"}, }, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing Workspace resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static Workspace Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new Workspace(name, id, options); } } public sealed class WorkspaceArgs : Pulumi.ResourceArgs { [Input("applicationGroupReferences")] private InputList<string>? _applicationGroupReferences; /// <summary> /// List of applicationGroup resource Ids. /// </summary> public InputList<string> ApplicationGroupReferences { get => _applicationGroupReferences ?? (_applicationGroupReferences = new InputList<string>()); set => _applicationGroupReferences = value; } /// <summary> /// Description of Workspace. /// </summary> [Input("description")] public Input<string>? Description { get; set; } /// <summary> /// Friendly name of Workspace. /// </summary> [Input("friendlyName")] public Input<string>? FriendlyName { get; set; } /// <summary> /// The geo-location where the resource lives /// </summary> [Input("location")] public Input<string>? Location { get; set; } /// <summary> /// The name of the resource group. The name is case insensitive. /// </summary> [Input("resourceGroupName", required: true)] public Input<string> ResourceGroupName { get; set; } = null!; [Input("tags")] private InputMap<string>? _tags; /// <summary> /// Resource tags. /// </summary> public InputMap<string> Tags { get => _tags ?? (_tags = new InputMap<string>()); set => _tags = value; } /// <summary> /// The name of the workspace /// </summary> [Input("workspaceName")] public Input<string>? WorkspaceName { get; set; } public WorkspaceArgs() { } } }
40.034091
153
0.600057
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/DesktopVirtualization/V20201110Preview/Workspace.cs
7,046
C#
using System; using System.Xml.Serialization; #region dynamo using Autodesk.DesignScript.Runtime; #endregion namespace FemDesign.Reinforcement { [IsVisibleInDynamoLibrary(false)] public partial class HiddenBar: EntityBase { } }
15.9375
46
0.737255
[ "MIT" ]
AmalieRask131/femdesign-api
FemDesign.Dynamo/Dynamo/Reinforcement/HiddenBar.cs
255
C#
using AudioSwitchWrapper.Exception; using AudioSwitchWrapper.Model; using System.Collections.Generic; namespace AudioSwitchWrapper { public class AudioDevicesRepository { private List<AudioDevice> audioDevices = new List<AudioDevice>(); public void Add(AudioDevice audioDevice) { if (Exists(audioDevice)) throw new AudioSwitchWrapperException("The device already exists in the repository"); audioDevices.Add(audioDevice); } public bool Exists(AudioDevice audioDevice) { if (audioDevice == null) return false; return (audioDevices.Find(dev => dev.Equals(audioDevice)) != null); } public AudioDevice GetById(string id) { return id == null ? null : audioDevices.FindLast(dev => dev.ID.Equals(id)); } public AudioDevice GetByName(string name) { return name == null ? null : audioDevices.FindLast(dev => dev.Name.Equals(name)); } public List<AudioDevice> GetAll() { return audioDevices; } public void Flush() { audioDevices = new List<AudioDevice>(); } } }
29.690476
102
0.590217
[ "MIT" ]
fx89/audio-switch
code/AudioSwitch/AudioSwitchWrapper/AudioDevicesRepository.cs
1,249
C#
/************************************************/ /* */ /* Copyright (c) 2018 - 2021 monitor1394 */ /* https://github.com/monitor1394 */ /* */ /************************************************/ using System; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; using XUGL; namespace XCharts { public partial class CoordinateChart { protected Action<PointerEventData, int> m_OnPointerClickBar; protected void DrawYBarSerie(VertexHelper vh, Serie serie, int colorIndex) { if (!IsActive(serie.name)) return; if (serie.animation.HasFadeOut()) return; var xAxis = m_XAxes[serie.xAxisIndex]; var yAxis = m_YAxes[serie.yAxisIndex]; var grid = GetSerieGridOrDefault(serie); var dataZoom = DataZoomHelper.GetAxisRelatedDataZoom(yAxis, dataZooms); var showData = serie.GetDataList(dataZoom); float categoryWidth = AxisHelper.GetDataWidth(yAxis, grid.runtimeHeight, showData.Count, dataZoom); float barGap = Internal_GetBarGap(SerieType.Bar); float totalBarWidth = Internal_GetBarTotalWidth(categoryWidth, barGap, SerieType.Bar); float barWidth = serie.GetBarWidth(categoryWidth); float offset = (categoryWidth - totalBarWidth) / 2; float barGapWidth = barWidth + barWidth * barGap; float space = serie.barGap == -1 ? offset : offset + Internal_GetBarIndex(serie, SerieType.Bar) * barGapWidth; var isStack = SeriesHelper.IsStack(m_Series, serie.stack, SerieType.Bar); m_StackSerieData.Clear(); if (isStack) SeriesHelper.UpdateStackDataList(m_Series, serie, dataZoom, m_StackSerieData); int maxCount = serie.maxShow > 0 ? (serie.maxShow > showData.Count ? showData.Count : serie.maxShow) : showData.Count; var isPercentStack = SeriesHelper.IsPercentStack(m_Series, serie.stack, SerieType.Bar); bool dataChanging = false; float dataChangeDuration = serie.animation.GetUpdateAnimationDuration(); double xMinValue = xAxis.GetCurrMinValue(dataChangeDuration); double xMaxValue = xAxis.GetCurrMaxValue(dataChangeDuration); var isAllBarEnd = true; for (int i = serie.minShow; i < maxCount; i++) { var serieData = showData[i]; if (!serieData.show || serie.IsIgnoreValue(serieData)) { serie.dataPoints.Add(Vector3.zero); continue; } var highlight = (tooltip.show && tooltip.IsSelected(i)) || serie.data[i].highlighted || serie.highlighted; var itemStyle = SerieHelper.GetItemStyle(serie, serieData, highlight); serieData.canShowLabel = true; double value = showData[i].GetCurrData(1, dataChangeDuration, xAxis.inverse, xMinValue, xMaxValue); float borderWidth = value == 0 ? 0 : itemStyle.runtimeBorderWidth; if (showData[i].IsDataChanged()) dataChanging = true; float axisLineWidth = value == 0 ? 0 : ((value < 0 ? -1 : 1) * yAxis.axisLine.GetWidth(m_Theme.axis.lineWidth)); float pY = grid.runtimeY + i * categoryWidth; if (!yAxis.boundaryGap) pY -= categoryWidth / 2; float pX = grid.runtimeX + xAxis.runtimeZeroXOffset + axisLineWidth; if (isStack) { for (int n = 0; n < m_StackSerieData.Count - 1; n++) { pX += m_StackSerieData[n][i].runtimeStackHig; } } var barHig = 0f; double valueTotal = 0f; if (isPercentStack) { valueTotal = Internal_GetBarSameStackTotalValue(serie.stack, i, SerieType.Bar); barHig = valueTotal != 0 ? (float)((value / valueTotal * grid.runtimeWidth)) : 0; } else { if (yAxis.IsLog()) { int minIndex = xAxis.runtimeMinLogIndex; float nowIndex = xAxis.GetLogValue(value); barHig = (nowIndex - minIndex) / xAxis.splitNumber * grid.runtimeWidth; } else { valueTotal = xMaxValue - xMinValue; if (valueTotal != 0) barHig = (float)((xMinValue > 0 ? value - xMinValue : value) / valueTotal * grid.runtimeWidth); } } serieData.runtimeStackHig = barHig; var isBarEnd = false; float currHig = Internal_CheckBarAnimation(serie, i, barHig, out isBarEnd); if (!isBarEnd) isAllBarEnd = false; Vector3 plt, prt, prb, plb, top; if (value < 0) { plt = new Vector3(pX - borderWidth, pY + space + barWidth - borderWidth); prt = new Vector3(pX + currHig + borderWidth, pY + space + barWidth - borderWidth); prb = new Vector3(pX + currHig + borderWidth, pY + space + borderWidth); plb = new Vector3(pX - borderWidth, pY + space + borderWidth); } else { plt = new Vector3(pX + borderWidth, pY + space + barWidth - borderWidth); prt = new Vector3(pX + currHig - borderWidth, pY + space + barWidth - borderWidth); prb = new Vector3(pX + currHig - borderWidth, pY + space + borderWidth); plb = new Vector3(pX + borderWidth, pY + space + borderWidth); } top = new Vector3(pX + currHig - borderWidth, pY + space + barWidth / 2); if (serie.clip) { plt = ClampInGrid(grid, plt); prt = ClampInGrid(grid, prt); prb = ClampInGrid(grid, prb); plb = ClampInGrid(grid, plb); top = ClampInGrid(grid, top); } serie.dataPoints.Add(top); if (serie.show) { switch (serie.barType) { case BarType.Normal: DrawNormalBar(vh, serie, serieData, itemStyle, colorIndex, highlight, space, barWidth, pX, pY, plb, plt, prt, prb, true, grid); break; case BarType.Zebra: DrawZebraBar(vh, serie, serieData, itemStyle, colorIndex, highlight, space, barWidth, pX, pY, plb, plt, prt, prb, true, grid); break; case BarType.Capsule: DrawCapsuleBar(vh, serie, serieData, itemStyle, colorIndex, highlight, space, barWidth, pX, pY, plb, plt, prt, prb, true, grid); break; } } } if (isAllBarEnd) serie.animation.AllBarEnd(); if (dataChanging) { RefreshPainter(serie); } } public float Internal_CheckBarAnimation(Serie serie, int dataIndex, float barHig, out bool isBarEnd) { float currHig = serie.animation.CheckBarProgress(dataIndex, barHig, serie.dataCount, out isBarEnd); if (!serie.animation.IsFinish()) { RefreshPainter(serie); m_IsPlayingAnimation = true; } return currHig; } protected void DrawXBarSerie(VertexHelper vh, Serie serie, int colorIndex) { if (!IsActive(serie.index)) return; if (serie.animation.HasFadeOut()) return; var yAxis = m_YAxes[serie.yAxisIndex]; var xAxis = m_XAxes[serie.xAxisIndex]; var grid = GetSerieGridOrDefault(serie); var dataZoom = DataZoomHelper.GetAxisRelatedDataZoom(xAxis, dataZooms); var showData = serie.GetDataList(dataZoom); var isStack = SeriesHelper.IsStack(m_Series, serie.stack, SerieType.Bar); m_StackSerieData.Clear(); if (isStack) SeriesHelper.UpdateStackDataList(m_Series, serie, dataZoom, m_StackSerieData); float categoryWidth = AxisHelper.GetDataWidth(xAxis, grid.runtimeWidth, showData.Count, dataZoom); float barGap = Internal_GetBarGap(SerieType.Bar); float totalBarWidth = Internal_GetBarTotalWidth(categoryWidth, barGap, SerieType.Bar); float barWidth = serie.GetBarWidth(categoryWidth); float offset = (categoryWidth - totalBarWidth) / 2; float barGapWidth = barWidth + barWidth * barGap; float space = serie.barGap == -1 ? offset : offset + Internal_GetBarIndex(serie, SerieType.Bar) * barGapWidth; int maxCount = serie.maxShow > 0 ? (serie.maxShow > showData.Count ? showData.Count : serie.maxShow) : showData.Count; var isPercentStack = SeriesHelper.IsPercentStack(m_Series, serie.stack, SerieType.Bar); bool dataChanging = false; float dataChangeDuration = serie.animation.GetUpdateAnimationDuration(); double yMinValue = yAxis.GetCurrMinValue(dataChangeDuration); double yMaxValue = yAxis.GetCurrMaxValue(dataChangeDuration); var isAllBarEnd = true; for (int i = serie.minShow; i < maxCount; i++) { var serieData = showData[i]; if (!serieData.show || serie.IsIgnoreValue(serieData)) { serie.dataPoints.Add(Vector3.zero); continue; } var highlight = (tooltip.show && tooltip.IsSelected(i)) || serie.data[i].highlighted || serie.highlighted; var itemStyle = SerieHelper.GetItemStyle(serie, serieData, highlight); double value = serieData.GetCurrData(1, dataChangeDuration, yAxis.inverse, yMinValue, yMaxValue); float borderWidth = value == 0 ? 0 : itemStyle.runtimeBorderWidth; if (serieData.IsDataChanged()) dataChanging = true; float pX = grid.runtimeX + i * categoryWidth; float zeroY = grid.runtimeY + yAxis.runtimeZeroYOffset; if (!xAxis.boundaryGap) pX -= categoryWidth / 2; float axisLineWidth = value == 0 ? 0 : ((value < 0 ? -1 : 1) * xAxis.axisLine.GetWidth(m_Theme.axis.lineWidth)); float pY = zeroY + axisLineWidth; if (isStack) { for (int n = 0; n < m_StackSerieData.Count - 1; n++) { pY += m_StackSerieData[n][i].runtimeStackHig; } } var barHig = 0f; double valueTotal = 0f; if (isPercentStack) { valueTotal = Internal_GetBarSameStackTotalValue(serie.stack, i, SerieType.Bar); barHig = valueTotal != 0 ? (float)(value / valueTotal * grid.runtimeHeight) : 0; } else { valueTotal = (double)(yMaxValue - yMinValue); if (valueTotal != 0) { if (yAxis.IsLog()) { int minIndex = yAxis.runtimeMinLogIndex; var nowIndex = yAxis.GetLogValue(value); barHig = (nowIndex - minIndex) / yAxis.splitNumber * grid.runtimeHeight; } else { barHig = (float)((yMinValue > 0 ? value - yMinValue : value) / valueTotal * grid.runtimeHeight); } } } serieData.runtimeStackHig = barHig; var isBarEnd = false; float currHig = Internal_CheckBarAnimation(serie, i, barHig, out isBarEnd); if (!isBarEnd) isAllBarEnd = false; Vector3 plb, plt, prt, prb, top; if (value < 0) { plb = new Vector3(pX + space + borderWidth, pY - borderWidth); plt = new Vector3(pX + space + borderWidth, pY + currHig + borderWidth); prt = new Vector3(pX + space + barWidth - borderWidth, pY + currHig + borderWidth); prb = new Vector3(pX + space + barWidth - borderWidth, pY - borderWidth); } else { plb = new Vector3(pX + space + borderWidth, pY + borderWidth); plt = new Vector3(pX + space + borderWidth, pY + currHig - borderWidth); prt = new Vector3(pX + space + barWidth - borderWidth, pY + currHig - borderWidth); prb = new Vector3(pX + space + barWidth - borderWidth, pY + borderWidth); } top = new Vector3(pX + space + barWidth / 2, pY + currHig - borderWidth); if (serie.clip) { plb = ClampInGrid(grid, plb); plt = ClampInGrid(grid, plt); prt = ClampInGrid(grid, prt); prb = ClampInGrid(grid, prb); top = ClampInGrid(grid, top); } serie.dataPoints.Add(top); if (serie.show && currHig != 0) { switch (serie.barType) { case BarType.Normal: DrawNormalBar(vh, serie, serieData, itemStyle, colorIndex, highlight, space, barWidth, pX, pY, plb, plt, prt, prb, false, grid); break; case BarType.Zebra: DrawZebraBar(vh, serie, serieData, itemStyle, colorIndex, highlight, space, barWidth, pX, pY, plb, plt, prt, prb, false, grid); break; case BarType.Capsule: DrawCapsuleBar(vh, serie, serieData, itemStyle, colorIndex, highlight, space, barWidth, pX, pY, plb, plt, prt, prb, false, grid); break; } } } if (isAllBarEnd) { serie.animation.AllBarEnd(); } if (dataChanging) { RefreshPainter(serie); } } private void DrawNormalBar(VertexHelper vh, Serie serie, SerieData serieData, ItemStyle itemStyle, int colorIndex, bool highlight, float space, float barWidth, float pX, float pY, Vector3 plb, Vector3 plt, Vector3 prt, Vector3 prb, bool isYAxis, Grid grid) { var areaColor = SerieHelper.GetItemColor(serie, serieData, m_Theme, colorIndex, highlight); var areaToColor = SerieHelper.GetItemToColor(serie, serieData, m_Theme, colorIndex, highlight); DrawBarBackground(vh, serie, serieData, itemStyle, colorIndex, highlight, pX, pY, space, barWidth, isYAxis, grid); var borderWidth = itemStyle.runtimeBorderWidth; if (isYAxis) { if (serie.clip) { prb = ClampInGrid(grid, prb); plb = ClampInGrid(grid, plb); plt = ClampInGrid(grid, plt); prt = ClampInGrid(grid, prt); } var itemWidth = Mathf.Abs(prb.x - plt.x); var itemHeight = Mathf.Abs(prt.y - plb.y); var center = new Vector3((plt.x + prb.x) / 2, (prt.y + plb.y) / 2); if (itemWidth > 0 && itemHeight > 0) { if (ItemStyleHelper.IsNeedCorner(itemStyle)) { UGL.DrawRoundRectangle(vh, center, itemWidth, itemHeight, areaColor, areaToColor, 0, itemStyle.cornerRadius, isYAxis); } else { Internal_CheckClipAndDrawPolygon(vh, plb, plt, prt, prb, areaColor, areaToColor, serie.clip, grid); } UGL.DrawBorder(vh, center, itemWidth, itemHeight, borderWidth, itemStyle.borderColor, itemStyle.borderToColor, 0, itemStyle.cornerRadius, isYAxis); } } else { if (serie.clip) { prb = ClampInGrid(grid, prb); plb = ClampInGrid(grid, plb); plt = ClampInGrid(grid, plt); prt = ClampInGrid(grid, prt); } var itemWidth = Mathf.Abs(prt.x - plb.x); var itemHeight = Mathf.Abs(plt.y - prb.y); var center = new Vector3((plb.x + prt.x) / 2, (plt.y + prb.y) / 2); if (itemWidth > 0 && itemHeight > 0) { if (ItemStyleHelper.IsNeedCorner(itemStyle)) { UGL.DrawRoundRectangle(vh, center, itemWidth, itemHeight, areaColor, areaToColor, 0, itemStyle.cornerRadius, isYAxis); } else { Internal_CheckClipAndDrawPolygon(vh, ref prb, ref plb, ref plt, ref prt, areaColor, areaToColor, serie.clip, grid); } UGL.DrawBorder(vh, center, itemWidth, itemHeight, borderWidth, itemStyle.borderColor, itemStyle.borderToColor, 0, itemStyle.cornerRadius, isYAxis); } } } private void DrawZebraBar(VertexHelper vh, Serie serie, SerieData serieData, ItemStyle itemStyle, int colorIndex, bool highlight, float space, float barWidth, float pX, float pY, Vector3 plb, Vector3 plt, Vector3 prt, Vector3 prb, bool isYAxis, Grid grid) { var barColor = SerieHelper.GetItemColor(serie, serieData, m_Theme, colorIndex, highlight); var barToColor = SerieHelper.GetItemToColor(serie, serieData, m_Theme, colorIndex, highlight); DrawBarBackground(vh, serie, serieData, itemStyle, colorIndex, highlight, pX, pY, space, barWidth, isYAxis, grid); if (isYAxis) { plt = (plb + plt) / 2; prt = (prt + prb) / 2; Internal_CheckClipAndDrawZebraLine(vh, plt, prt, barWidth / 2, serie.barZebraWidth, serie.barZebraGap, barColor, barToColor, serie.clip, grid); } else { plb = (prb + plb) / 2; plt = (plt + prt) / 2; Internal_CheckClipAndDrawZebraLine(vh, plb, plt, barWidth / 2, serie.barZebraWidth, serie.barZebraGap, barColor, barToColor, serie.clip, grid); } } private void DrawCapsuleBar(VertexHelper vh, Serie serie, SerieData serieData, ItemStyle itemStyle, int colorIndex, bool highlight, float space, float barWidth, float pX, float pY, Vector3 plb, Vector3 plt, Vector3 prt, Vector3 prb, bool isYAxis, Grid grid) { var areaColor = SerieHelper.GetItemColor(serie, serieData, m_Theme, colorIndex, highlight); var areaToColor = SerieHelper.GetItemToColor(serie, serieData, m_Theme, colorIndex, highlight); DrawBarBackground(vh, serie, serieData, itemStyle, colorIndex, highlight, pX, pY, space, barWidth, isYAxis, grid); var borderWidth = itemStyle.runtimeBorderWidth; var radius = barWidth / 2 - borderWidth; var isGradient = !ChartHelper.IsValueEqualsColor(areaColor, areaToColor); if (isYAxis) { var diff = Vector3.right * radius; if (plt.x < prt.x) { var pcl = (plt + plb) / 2 + diff; var pcr = (prt + prb) / 2 - diff; if (pcr.x > pcl.x) { if (isGradient) { var barLen = prt.x - plt.x; var rectStartColor = Color32.Lerp(areaColor, areaToColor, radius / barLen); var rectEndColor = Color32.Lerp(areaColor, areaToColor, (barLen - radius) / barLen); Internal_CheckClipAndDrawPolygon(vh, plb + diff, plt + diff, prt - diff, prb - diff, rectStartColor, rectEndColor, serie.clip, grid); UGL.DrawSector(vh, pcl, radius, areaColor, rectStartColor, 180, 360, 1, isYAxis); UGL.DrawSector(vh, pcr, radius, rectEndColor, areaToColor, 0, 180, 1, isYAxis); } else { Internal_CheckClipAndDrawPolygon(vh, plb + diff, plt + diff, prt - diff, prb - diff, areaColor, areaToColor, serie.clip, grid); UGL.DrawSector(vh, pcl, radius, areaColor, 180, 360); UGL.DrawSector(vh, pcr, radius, areaToColor, 0, 180); } } } else if (plt.x > prt.x) { var pcl = (plt + plb) / 2 - diff; var pcr = (prt + prb) / 2 + diff; if (pcr.x < pcl.x) { if (isGradient) { var barLen = plt.x - prt.x; var rectStartColor = Color32.Lerp(areaColor, areaToColor, radius / barLen); var rectEndColor = Color32.Lerp(areaColor, areaToColor, (barLen - radius) / barLen); Internal_CheckClipAndDrawPolygon(vh, plb - diff, plt - diff, prt + diff, prb + diff, rectStartColor, rectEndColor, serie.clip, grid); UGL.DrawSector(vh, pcl, radius, rectStartColor, areaColor, 0, 180, 1, isYAxis); UGL.DrawSector(vh, pcr, radius, areaToColor, rectEndColor, 180, 360, 1, isYAxis); } else { Internal_CheckClipAndDrawPolygon(vh, plb - diff, plt - diff, prt + diff, prb + diff, areaColor, areaToColor, serie.clip, grid); UGL.DrawSector(vh, pcl, radius, areaColor, 0, 180); UGL.DrawSector(vh, pcr, radius, areaToColor, 180, 360); } } } } else { var diff = Vector3.up * radius; if (plt.y > plb.y) { var pct = (plt + prt) / 2 - diff; var pcb = (plb + prb) / 2 + diff; if (pct.y > pcb.y) { if (isGradient) { var barLen = plt.y - plb.y; var rectStartColor = Color32.Lerp(areaColor, areaToColor, radius / barLen); var rectEndColor = Color32.Lerp(areaColor, areaToColor, (barLen - radius) / barLen); Internal_CheckClipAndDrawPolygon(vh, prb + diff, plb + diff, plt - diff, prt - diff, rectStartColor, rectEndColor, serie.clip, grid); UGL.DrawSector(vh, pct, radius, rectEndColor, areaToColor, 270, 450, 1, isYAxis); UGL.DrawSector(vh, pcb, radius, rectStartColor, areaColor, 90, 270, 1, isYAxis); } else { Internal_CheckClipAndDrawPolygon(vh, prb + diff, plb + diff, plt - diff, prt - diff, areaColor, areaToColor, serie.clip, grid); UGL.DrawSector(vh, pct, radius, areaToColor, 270, 450); UGL.DrawSector(vh, pcb, radius, areaColor, 90, 270); } } } else if (plt.y < plb.y) { var pct = (plt + prt) / 2 + diff; var pcb = (plb + prb) / 2 - diff; if (pct.y < pcb.y) { if (isGradient) { var barLen = plb.y - plt.y; var rectStartColor = Color32.Lerp(areaColor, areaToColor, radius / barLen); var rectEndColor = Color32.Lerp(areaColor, areaToColor, (barLen - radius) / barLen); Internal_CheckClipAndDrawPolygon(vh, prb - diff, plb - diff, plt + diff, prt + diff, rectStartColor, rectEndColor, serie.clip, grid); UGL.DrawSector(vh, pct, radius, rectEndColor, areaToColor, 90, 270, 1, isYAxis); UGL.DrawSector(vh, pcb, radius, rectStartColor, areaColor, 270, 450, 1, isYAxis); } else { Internal_CheckClipAndDrawPolygon(vh, prb - diff, plb - diff, plt + diff, prt + diff, areaColor, areaToColor, serie.clip, grid); UGL.DrawSector(vh, pct, radius, areaToColor, 90, 270); UGL.DrawSector(vh, pcb, radius, areaColor, 270, 450); } } } } } private void DrawBarBackground(VertexHelper vh, Serie serie, SerieData serieData, ItemStyle itemStyle, int colorIndex, bool highlight, float pX, float pY, float space, float barWidth, bool isYAxis, Grid grid) { var color = SerieHelper.GetItemBackgroundColor(serie, serieData, m_Theme, colorIndex, highlight, false); if (ChartHelper.IsClearColor(color)) return; if (isYAxis) { var axis = m_YAxes[serie.yAxisIndex]; var axisWidth = axis.axisLine.GetWidth(m_Theme.axis.lineWidth); Vector3 plt = new Vector3(grid.runtimeX + axisWidth, pY + space + barWidth); Vector3 prt = new Vector3(grid.runtimeX + axisWidth + grid.runtimeWidth, pY + space + barWidth); Vector3 prb = new Vector3(grid.runtimeX + axisWidth + grid.runtimeWidth, pY + space); Vector3 plb = new Vector3(grid.runtimeX + axisWidth, pY + space); if (serie.barType == BarType.Capsule) { var radius = barWidth / 2; var diff = Vector3.right * radius; var pcl = (plt + plb) / 2 + diff; var pcr = (prt + prb) / 2 - diff; Internal_CheckClipAndDrawPolygon(vh, plb + diff, plt + diff, prt - diff, prb - diff, color, color, serie.clip, grid); UGL.DrawSector(vh, pcl, radius, color, 180, 360); UGL.DrawSector(vh, pcr, radius, color, 0, 180); if (itemStyle.NeedShowBorder()) { var borderWidth = itemStyle.borderWidth; var borderColor = itemStyle.borderColor; var smoothness = settings.cicleSmoothness; var inRadius = radius - borderWidth; var outRadius = radius; var p1 = plb + diff + Vector3.up * borderWidth / 2; var p2 = prb - diff + Vector3.up * borderWidth / 2; var p3 = plt + diff - Vector3.up * borderWidth / 2; var p4 = prt - diff - Vector3.up * borderWidth / 2; UGL.DrawLine(vh, p1, p2, borderWidth / 2, borderColor); UGL.DrawLine(vh, p3, p4, borderWidth / 2, borderColor); UGL.DrawDoughnut(vh, pcl, inRadius, outRadius, borderColor, ChartConst.clearColor32, 180, 360, smoothness); UGL.DrawDoughnut(vh, pcr, inRadius, outRadius, borderColor, ChartConst.clearColor32, 0, 180, smoothness); } } else { Internal_CheckClipAndDrawPolygon(vh, ref plb, ref plt, ref prt, ref prb, color, color, serie.clip, grid); } } else { var axis = m_XAxes[serie.xAxisIndex]; var axisWidth = axis.axisLine.GetWidth(m_Theme.axis.lineWidth); Vector3 plb = new Vector3(pX + space, grid.runtimeY + axisWidth); Vector3 plt = new Vector3(pX + space, grid.runtimeY + grid.runtimeHeight + axisWidth); Vector3 prt = new Vector3(pX + space + barWidth, grid.runtimeY + grid.runtimeHeight + axisWidth); Vector3 prb = new Vector3(pX + space + barWidth, grid.runtimeY + axisWidth); if (serie.barType == BarType.Capsule) { var radius = barWidth / 2; var diff = Vector3.up * radius; var pct = (plt + prt) / 2 - diff; var pcb = (plb + prb) / 2 + diff; Internal_CheckClipAndDrawPolygon(vh, prb + diff, plb + diff, plt - diff, prt - diff, color, color, serie.clip, grid); UGL.DrawSector(vh, pct, radius, color, 270, 450); UGL.DrawSector(vh, pcb, radius, color, 90, 270); if (itemStyle.NeedShowBorder()) { var borderWidth = itemStyle.borderWidth; var borderColor = itemStyle.borderColor; var smoothness = settings.cicleSmoothness; var inRadius = radius - borderWidth; var outRadius = radius; var p1 = plb + diff + Vector3.right * borderWidth / 2; var p2 = plt - diff + Vector3.right * borderWidth / 2; var p3 = prb + diff - Vector3.right * borderWidth / 2; var p4 = prt - diff - Vector3.right * borderWidth / 2; UGL.DrawLine(vh, p1, p2, borderWidth / 2, borderColor); UGL.DrawLine(vh, p3, p4, borderWidth / 2, borderColor); UGL.DrawDoughnut(vh, pct, inRadius, outRadius, borderColor, ChartConst.clearColor32, 270, 450, smoothness); UGL.DrawDoughnut(vh, pcb, inRadius, outRadius, borderColor, ChartConst.clearColor32, 90, 270, smoothness); } } else { Internal_CheckClipAndDrawPolygon(vh, ref prb, ref plb, ref plt, ref prt, color, color, serie.clip, grid); } } } public float Internal_GetBarGap(SerieType type) { float gap = 0f; for (int i = 0; i < m_Series.Count; i++) { var serie = m_Series.list[i]; if (serie.type == type) { if (serie.barGap != 0) { gap = serie.barGap; } } } return gap; } public double Internal_GetBarSameStackTotalValue(string stack, int dataIndex, SerieType type) { if (string.IsNullOrEmpty(stack)) return 0; double total = 0; foreach (var serie in m_Series.list) { if (serie.type == type) { if (stack.Equals(serie.stack)) { total += serie.data[dataIndex].data[1]; } } } return total; } private HashSet<string> barStackSet = new HashSet<string>(); public float Internal_GetBarTotalWidth(float categoryWidth, float gap, SerieType type) { float total = 0; float lastGap = 0; barStackSet.Clear(); for (int i = 0; i < m_Series.Count; i++) { var serie = m_Series.list[i]; if (!serie.show) continue; if (serie.type == type) { if (!string.IsNullOrEmpty(serie.stack)) { if (barStackSet.Contains(serie.stack)) continue; barStackSet.Add(serie.stack); } var width = GetStackBarWidth(categoryWidth, serie, type); if (gap == -1) { if (width > total) total = width; } else { lastGap = width * gap; total += width; total += lastGap; } } } if (total > 0 && gap != -1) total -= lastGap; return total; } private float GetStackBarWidth(float categoryWidth, Serie now, SerieType type) { if (string.IsNullOrEmpty(now.stack)) return now.GetBarWidth(categoryWidth); float barWidth = 0; for (int i = 0; i < m_Series.Count; i++) { var serie = m_Series.list[i]; if ((serie.type == type) && serie.show && now.stack.Equals(serie.stack)) { if (serie.barWidth > barWidth) barWidth = serie.barWidth; } } if (barWidth > 1) return barWidth; else return barWidth * categoryWidth; } private List<string> tempList = new List<string>(); public int Internal_GetBarIndex(Serie currSerie, SerieType type) { tempList.Clear(); int index = 0; for (int i = 0; i < m_Series.Count; i++) { var serie = m_Series.GetSerie(i); if (serie.type != type) continue; if (string.IsNullOrEmpty(serie.stack)) { if (serie.index == currSerie.index) return index; tempList.Add(string.Empty); index++; } else { if (!tempList.Contains(serie.stack)) { if (serie.index == currSerie.index) return index; tempList.Add(serie.stack); index++; } else { if (serie.index == currSerie.index) return tempList.IndexOf(serie.stack); } } } return 0; } } }
50.263085
137
0.48042
[ "MIT" ]
dkjfdkjf/unity-ugui-XCharts
Assets/XCharts/Runtime/Internal/CoordinateChart_DrawBar.cs
36,491
C#
namespace WindowsFirewallHelper { /// <summary> /// Firewall rule actions /// </summary> public enum FirewallAction { /// <summary> /// Block rule /// </summary> Block, /// <summary> /// Allow rule /// </summary> Allow } }
18
33
0.441358
[ "MIT" ]
TechnikEmpire/WindowsFirewallHelper
WindowsFirewallHelper/FirewallAction.cs
326
C#
//------------------------------------------------------------------------------ // // System.IO.FileOptions.cs // // Author: Zoltan Varga (vargaz@gmail.com) // //------------------------------------------------------------------------------ // // Copyright (C) 2004 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System.Runtime.InteropServices; namespace System.IO { [Flags] [Serializable] [ComVisible(true)] public enum FileOptions { None = 0, Encrypted = 0x4000, DeleteOnClose = 0x4000000, SequentialScan = 0x8000000, RandomAccess = 0x10000000, Asynchronous = 0x40000000, WriteThrough = -2147483648 // // FileIsTemporary = 1 // The above is an internal value used by Path.GetTempFile to // get a file with 600 permissions, regardless of the umask // settings. If a value "1" must be introduced here, update // both metadata/file-io.c and Path.GetTempFile // } }
34.551724
80
0.668663
[ "Apache-2.0" ]
121468615/mono
mcs/class/corlib/System.IO/FileOptions.cs
2,004
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("RestoreManagePermissionsToProjectAdminGroups")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("")] [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("e449c3c1-8272-4781-a658-dda4a3682a44")] // 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.540541
84
0.750351
[ "MIT" ]
willsmythe/vsts-integration-samples
dotnet/service-hooks/ServiceHooksSecurityUtils/Properties/AssemblyInfo.cs
1,429
C#
//------------------------------------------------------------------------------ // <auto-generated> // 이 코드는 도구를 사용하여 생성되었습니다. // 런타임 버전:4.0.30319.42000 // // 파일 내용을 변경하면 잘못된 동작이 발생할 수 있으며, 코드를 다시 생성하면 // 이러한 변경 내용이 손실됩니다. // </auto-generated> //------------------------------------------------------------------------------ namespace Machine.Properties { using System; /// <summary> /// 지역화된 문자열 등을 찾기 위한 강력한 형식의 리소스 클래스입니다. /// </summary> // 이 클래스는 ResGen 또는 Visual Studio와 같은 도구를 통해 StronglyTypedResourceBuilder // 클래스에서 자동으로 생성되었습니다. // 멤버를 추가하거나 제거하려면 .ResX 파일을 편집한 다음 /str 옵션을 사용하여 ResGen을 // 다시 실행하거나 VS 프로젝트를 다시 빌드하십시오. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// 이 클래스에서 사용하는 캐시된 ResourceManager 인스턴스를 반환합니다. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Machine.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// 이 강력한 형식의 리소스 클래스를 사용하여 모든 리소스 조회에 대해 현재 스레드의 CurrentUICulture 속성을 /// 재정의합니다. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// (아이콘)과(와) 유사한 System.Drawing.Icon 형식의 지역화된 리소스를 찾습니다. /// </summary> internal static System.Drawing.Icon TrayIcon { get { object obj = ResourceManager.GetObject("TrayIcon", resourceCulture); return ((System.Drawing.Icon)(obj)); } } } }
39.540541
173
0.578264
[ "MIT" ]
ExNaGNe/MLearning
Machine/Properties/Resources.Designer.cs
3,456
C#
using System.Threading; using System.Threading.Tasks; namespace OliveHelpsLDK.Clipboard { /// <summary> /// Provides access to the contents of the Clipboard. /// </summary> public interface IClipboardService { /// <summary> /// Reads the clipboard's contents. /// </summary> /// <param name="cancellationToken"></param> /// <returns>A Task resolving with the string contents of the clipboard.</returns> Task<string> Read(CancellationToken cancellationToken = default); /// <summary> /// Writes the provided text to the clipboard. /// </summary> /// <param name="contents">The text to write to the clipboard.</param> /// <param name="cancellationToken"></param> /// <returns>A Task resolving when the request is completed.</returns> Task Write(string contents, CancellationToken cancellationToken = default); /// <summary> /// Creates a stream receiving updates when the clipboard's contents change. /// </summary> /// <param name="cancellationToken"></param> /// <returns></returns> IStreamingCall<string> Stream(CancellationToken cancellationToken = default); } }
37.666667
90
0.632341
[ "MIT" ]
bbrewer-oliveai/loop-development-k
ldk/csharp/OliveHelpsLDK/OliveHelpsLDK/Clipboard/IClipboardService.cs
1,243
C#
using System; using UniDi.Internal; namespace UniDi { [NoReflectionBaking] public class FactorySubContainerBinderBase<TContract> { public FactorySubContainerBinderBase( DiContainer bindContainer, BindInfo bindInfo, FactoryBindInfo factoryBindInfo, object subIdentifier) { FactoryBindInfo = factoryBindInfo; SubIdentifier = subIdentifier; BindInfo = bindInfo; BindContainer = bindContainer; // Reset so we get errors if we end here factoryBindInfo.ProviderFunc = null; } protected DiContainer BindContainer { get; private set; } protected FactoryBindInfo FactoryBindInfo { get; private set; } protected Func<DiContainer, IProvider> ProviderFunc { get { return FactoryBindInfo.ProviderFunc; } set { FactoryBindInfo.ProviderFunc = value; } } protected BindInfo BindInfo { get; private set; } protected object SubIdentifier { get; private set; } protected Type ContractType { get { return typeof(TContract); } } public ScopeConcreteIdArgConditionCopyNonLazyBinder ByInstaller<TInstaller>() where TInstaller : InstallerBase { return ByInstaller(typeof(TInstaller)); } public ScopeConcreteIdArgConditionCopyNonLazyBinder ByInstaller(Type installerType) { Assert.That(installerType.DerivesFrom<InstallerBase>(), "Invalid installer type given during bind command. Expected type '{0}' to derive from 'Installer<>'", installerType); var subcontainerBindInfo = new SubContainerCreatorBindInfo(); ProviderFunc = (container) => new SubContainerDependencyProvider( ContractType, SubIdentifier, new SubContainerCreatorByInstaller( container, subcontainerBindInfo, installerType, BindInfo.Arguments), false); return new ScopeConcreteIdArgConditionCopyNonLazyBinder(BindInfo); } #if !NOT_UNITY3D public NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder ByNewGameObjectInstaller<TInstaller>() where TInstaller : InstallerBase { return ByNewGameObjectInstaller(typeof(TInstaller)); } public NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder ByNewGameObjectInstaller(Type installerType) { Assert.That(installerType.DerivesFrom<InstallerBase>(), "Invalid installer type given during bind command. Expected type '{0}' to derive from 'Installer<>'", installerType); var gameObjectInfo = new GameObjectCreationParameters(); ProviderFunc = (container) => new SubContainerDependencyProvider( ContractType, SubIdentifier, new SubContainerCreatorByNewGameObjectInstaller( container, gameObjectInfo, installerType, BindInfo.Arguments), false); return new NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder(BindInfo, gameObjectInfo); } public NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder ByNewPrefabInstaller<TInstaller>( Func<InjectContext, UnityEngine.Object> prefabGetter) where TInstaller : InstallerBase { return ByNewPrefabInstaller(prefabGetter, typeof(TInstaller)); } public NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder ByNewPrefabInstaller( Func<InjectContext, UnityEngine.Object> prefabGetter, Type installerType) { Assert.That(installerType.DerivesFrom<InstallerBase>(), "Invalid installer type given during bind command. Expected type '{0}' to derive from 'Installer<>'", installerType); var gameObjectInfo = new GameObjectCreationParameters(); ProviderFunc = (container) => new SubContainerDependencyProvider( ContractType, SubIdentifier, new SubContainerCreatorByNewPrefabInstaller( container, new PrefabProviderCustom(prefabGetter), gameObjectInfo, installerType, BindInfo.Arguments), false); return new NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder(BindInfo, gameObjectInfo); } public NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder ByNewPrefabInstaller<TInstaller>( UnityEngine.Object prefab) where TInstaller : InstallerBase { return ByNewPrefabInstaller(prefab, typeof(TInstaller)); } public NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder ByNewPrefabInstaller( UnityEngine.Object prefab, Type installerType) { Assert.That(installerType.DerivesFrom<InstallerBase>(), "Invalid installer type given during bind command. Expected type '{0}' to derive from 'Installer<>'", installerType); var gameObjectInfo = new GameObjectCreationParameters(); ProviderFunc = (container) => new SubContainerDependencyProvider( ContractType, SubIdentifier, new SubContainerCreatorByNewPrefabInstaller( container, new PrefabProvider(prefab), gameObjectInfo, installerType, BindInfo.Arguments), false); return new NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder(BindInfo, gameObjectInfo); } public NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder ByNewPrefabResourceInstaller<TInstaller>( string resourcePath) where TInstaller : InstallerBase { return ByNewPrefabResourceInstaller(resourcePath, typeof(TInstaller)); } public NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder ByNewPrefabResourceInstaller( string resourcePath, Type installerType) { BindingUtil.AssertIsValidResourcePath(resourcePath); Assert.That(installerType.DerivesFrom<InstallerBase>(), "Invalid installer type given during bind command. Expected type '{0}' to derive from 'Installer<>'", installerType); var gameObjectInfo = new GameObjectCreationParameters(); ProviderFunc = (container) => new SubContainerDependencyProvider( ContractType, SubIdentifier, new SubContainerCreatorByNewPrefabInstaller( container, new PrefabProviderResource(resourcePath), gameObjectInfo, installerType, BindInfo.Arguments), false); return new NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder(BindInfo, gameObjectInfo); } #endif } }
39.95
134
0.643999
[ "Apache-2.0" ]
UniDi/UniDi
Source/Binding/Binders/Factory/FactoryFromBinder/SubContainerBinder/FactorySubContainerBinderBase.cs
7,191
C#
/* * Location Intelligence APIs * * Incorporate our extensive geodata into everyday applications, business processes and workflows. * * OpenAPI spec version: 8.5.0 * * Generated by: https://github.com/swagger-api/swagger-codegen.git * * 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.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace pb.locationIntelligence.Model { /// <summary> /// Intersection /// </summary> [DataContract] public partial class Intersection : IEquatable<Intersection> { /// <summary> /// Initializes a new instance of the <see cref="Intersection" /> class. /// </summary> /// <param name="Distance">Distance.</param> /// <param name="DriveTime">DriveTime.</param> /// <param name="DriveDistance">DriveDistance.</param> /// <param name="Geometry">Geometry.</param> /// <param name="Roads">Roads.</param> public Intersection(Unit Distance = null, Unit DriveTime = null, Unit DriveDistance = null, CommonGeometry Geometry = null, List<Road> Roads = null) { this.Distance = Distance; this.DriveTime = DriveTime; this.DriveDistance = DriveDistance; this.Geometry = Geometry; this.Roads = Roads; } /// <summary> /// Gets or Sets Distance /// </summary> [DataMember(Name="distance", EmitDefaultValue=false)] public Unit Distance { get; set; } /// <summary> /// Gets or Sets DriveTime /// </summary> [DataMember(Name="driveTime", EmitDefaultValue=false)] public Unit DriveTime { get; set; } /// <summary> /// Gets or Sets DriveDistance /// </summary> [DataMember(Name="driveDistance", EmitDefaultValue=false)] public Unit DriveDistance { get; set; } /// <summary> /// Gets or Sets Geometry /// </summary> [DataMember(Name="geometry", EmitDefaultValue=false)] public CommonGeometry Geometry { get; set; } /// <summary> /// Gets or Sets Roads /// </summary> [DataMember(Name="roads", EmitDefaultValue=false)] public List<Road> Roads { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class Intersection {\n"); sb.Append(" Distance: ").Append(Distance).Append("\n"); sb.Append(" DriveTime: ").Append(DriveTime).Append("\n"); sb.Append(" DriveDistance: ").Append(DriveDistance).Append("\n"); sb.Append(" Geometry: ").Append(Geometry).Append("\n"); sb.Append(" Roads: ").Append(Roads).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as Intersection); } /// <summary> /// Returns true if Intersection instances are equal /// </summary> /// <param name="other">Instance of Intersection to be compared</param> /// <returns>Boolean</returns> public bool Equals(Intersection other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.Distance == other.Distance || this.Distance != null && this.Distance.Equals(other.Distance) ) && ( this.DriveTime == other.DriveTime || this.DriveTime != null && this.DriveTime.Equals(other.DriveTime) ) && ( this.DriveDistance == other.DriveDistance || this.DriveDistance != null && this.DriveDistance.Equals(other.DriveDistance) ) && ( this.Geometry == other.Geometry || this.Geometry != null && this.Geometry.Equals(other.Geometry) ) && ( this.Roads == other.Roads || this.Roads != null && this.Roads.SequenceEqual(other.Roads) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.Distance != null) hash = hash * 59 + this.Distance.GetHashCode(); if (this.DriveTime != null) hash = hash * 59 + this.DriveTime.GetHashCode(); if (this.DriveDistance != null) hash = hash * 59 + this.DriveDistance.GetHashCode(); if (this.Geometry != null) hash = hash * 59 + this.Geometry.GetHashCode(); if (this.Roads != null) hash = hash * 59 + this.Roads.GetHashCode(); return hash; } } } }
36.705882
156
0.545309
[ "Apache-2.0" ]
PitneyBowes/LocationIntelligenceSDK-CSharp
src/pb.locationIntelligence/Model/Intersection.cs
6,864
C#
using System; using Agrirouter.Api.Exception; using Agrirouter.Impl.Service.Common; using Xunit; namespace Agrirouter.Api.Test.Service.Common { /// <summary> /// Functional tests. /// </summary> public class DecodeMessageServiceTest { [Fact] public void GivenInvalidDataAsMessageWhenDecodingTheMessageThenThereShouldBeAnException() { Assert.Throws<CouldNotDecodeMessageException>(() => DecodeMessageService.Decode("INVALID MESSAGE")); } [Fact] public void GivenValidCapabilitiesMessageResponseWhenDecodingTheMessageThenTheResponseEnvelopeAndResponsePayloadWrapperShouldBeFilled() { const string responseMessage = "XgjJARACGiQ5MDAxMjg3Yi03NjA5LTQ0MjYtYjU3My0xNTE5MmQwYzEyNDIiJGMyZGViM2VlLTIyMDItNDA1Mi1hZDJhLTUxMjVkND" + "g3YjdmNioLCMHy1/AFEICvvnGEAQqBAQowdHlwZXMuYWdyaXJvdXRlci5jb20vYWdyaXJvdXRlci5jb21tb25zLk1lc3NhZ2VzEk0K" + "Swo9U2tpcHBpbmcgY2FwYWJpbGl0aWVzIHVwZGF0ZSBiZWNhdXNlIHRoZXJlIGFyZSBubyBkaWZmZXJlbmNlcxIKVkFMXzAwMDAyMg=="; var decodedMessage = DecodeMessageService.Decode(responseMessage); Assert.NotNull(decodedMessage.ResponseEnvelope); Assert.NotNull(decodedMessage.ResponsePayloadWrapper); Assert.Equal(201, decodedMessage.ResponseEnvelope.ResponseCode); } [Fact] public void GivenValidMessageWhenDecodingTheMessageThenTheMessageShouldBeParsedCorrectly() { const string responseMessage = "EwiQAxADKgwIpITc8AUQgP/1sQNvCm0KMHR5cGVzLmFncmlyb3V0ZXIuY29tL2Fncmlyb3V0ZXIuY29tbW9ucy5NZXNzYWdlcxI5" + "CjcKKUVycm9yIG9jY3VyZWQgd2hpbGUgZGVjb2RpbmcgdGhlIG1lc3NhZ2UuEgpWQUxfMDAwMzAw"; var decodedMessage = DecodeMessageService.Decode(responseMessage); Assert.NotNull(decodedMessage.ResponseEnvelope); Assert.NotNull(decodedMessage.ResponsePayloadWrapper); Assert.Equal(400, decodedMessage.ResponseEnvelope.ResponseCode); var messages = DecodeMessageService.Decode(decodedMessage.ResponsePayloadWrapper.Details); Assert.NotNull(messages); Assert.NotEmpty(messages.Messages_); Assert.Single(messages.Messages_); Assert.Equal("VAL_000300", messages.Messages_[0].MessageCode); Assert.Equal("Error occured while decoding the message.", messages.Messages_[0].Message_); } [Fact] public void GivenWhitespacesAsMessageWhenDecodingTheMessageThenThereShouldBeAnException() { Assert.Throws<ArgumentException>(() => DecodeMessageService.Decode(" ")); } [Fact] public void GivenErrorMessageWhenDecodingTheMessageThenTheMessageShouldBeParsedCorrectly() { const string responseMessage = "XgiQAxADGiQ0MDkyNzU3Yi1iNjIxLTRjMzktODMyMi03ODIzOGY3Mjc3NDciJDhiODA3M2Y0LThhOGItNDU5NC1iMTYwLWZmYWRmMDJm" + "NTFiNioLCMHNs/oFEMDDkweYAQqVAQowdHlwZXMuYWdyaXJvdXRlci5jb20vYWdyaXJvdXRlci5jb21tb25zLk1lc3NhZ2VzEmEKXwpR" + "Tm8gcmVjaXBpZW50cyBoYXZlIGJlZW4gaWRlbnRpZmllZCBmb3IgaXNvOjExNzgzOi0xMDpkZXZpY2VfZGVzY3JpcHRpb246cHJvdG9" + "idWYuEgpWQUxfMDAwMDA0"; var decodedMessage = DecodeMessageService.Decode(responseMessage); Assert.NotNull(decodedMessage.ResponseEnvelope); Assert.NotNull(decodedMessage.ResponsePayloadWrapper); Assert.Equal(400, decodedMessage.ResponseEnvelope.ResponseCode); var messages = DecodeMessageService.Decode(decodedMessage.ResponsePayloadWrapper.Details); Assert.NotNull(messages); Assert.NotEmpty(messages.Messages_); Assert.Single(messages.Messages_); Assert.Equal("VAL_000004", messages.Messages_[0].MessageCode); Assert.Equal("No recipients have been identified for iso:11783:-10:device_description:protobuf.", messages.Messages_[0].Message_); } } }
49.012048
142
0.717797
[ "Apache-2.0" ]
kuhn-it/agrirouter-api-dotnet-standard
agrirouter-api-dotnet-standard-test/Service/Common/DecodeMessageServiceTest.cs
4,068
C#
// Copyright (c) Dapplo and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading; using System.Threading.Tasks; using Dapplo.HttpExtensions; using Dapplo.Jira.Domains; using Dapplo.Jira.Entities; using Dapplo.Jira.Internal; namespace Dapplo.Jira { /// <summary> /// This holds all the issue related extensions methods /// </summary> public static class AgileExtensions { /// <summary> /// Add comment to the specified issue /// See: https://docs.atlassian.com/jira/REST/latest/#d2e1139 /// </summary> /// <param name="jiraClient">IAgileDomain to bind the extension method to</param> /// <param name="issueKey">key for the issue</param> /// <param name="cancellationToken">CancellationToken</param> /// <returns>AgileIssue</returns> public static async Task<AgileIssue> GetIssueAsync(this IAgileDomain jiraClient, string issueKey, CancellationToken cancellationToken = default) { if (issueKey == null) { throw new ArgumentNullException(nameof(issueKey)); } jiraClient.Behaviour.MakeCurrent(); var agileIssueUri = jiraClient.JiraAgileRestUri.AppendSegments("issue", issueKey); if (JiraConfig.ExpandGetIssue?.Length > 0) { agileIssueUri = agileIssueUri.ExtendQuery("expand", string.Join(",", JiraConfig.ExpandGetIssue.Concat(new[] {"customfield_10007"}))); } var response = await agileIssueUri.GetAsAsync<HttpResponse<AgileIssue, Error>>(cancellationToken).ConfigureAwait(false); return response.HandleErrors(); } /// <summary> /// Get all sprints /// See: https://docs.atlassian.com/jira/REST/latest/#d2e1139 /// </summary> /// <param name="jiraClient">IAgileDomain to bind the extension method to</param> /// <param name="boardId">Id of the board to get the sprints for</param> /// <param name="stateFilter"> /// Filters results to sprints in specified states. Valid values: future, active, closed. You can /// define multiple states separated by commas, e.g. state=active,closed /// </param> /// <param name="page">optional Page</param> /// <param name="cancellationToken">CancellationToken</param> /// <returns>Results with Sprint objects</returns> public static async Task<SearchResult<Sprint, Tuple<long, string>>> GetSprintsAsync(this IAgileDomain jiraClient, long boardId, string stateFilter = null, Page page = null, CancellationToken cancellationToken = default) { jiraClient.Behaviour.MakeCurrent(); var sprintsUri = jiraClient.JiraAgileRestUri.AppendSegments("board", boardId, "sprint"); if (page != null) { sprintsUri = sprintsUri.ExtendQuery(new Dictionary<string, object> { { "startAt", page.StartAt }, { "maxResults", page.MaxResults } }); } if (stateFilter != null) { sprintsUri = sprintsUri.ExtendQuery("state", stateFilter); } var response = await sprintsUri.GetAsAsync<HttpResponse<SearchResult<Sprint, Tuple<long, string>>, Error>>(cancellationToken).ConfigureAwait(false); var result = response.HandleErrors(); // Store the original search parameter(s), so we can get the next page result.SearchParameter = new Tuple<long, string>(boardId, stateFilter); return result; } /// <summary> /// Get backlog of a board /// See /// <a href="https://docs.atlassian.com/jira-software/REST/cloud/#agile/1.0/board-getIssuesForBacklog"> /// get issues for /// backlog /// </a> /// </summary> /// <param name="jiraClient">IAgileDomain to bind the extension method to</param> /// <param name="boardId">Id of the board to get the backlog for</param> /// <param name="page">optional Page</param> /// <param name="cancellationToken">CancellationToken</param> /// <returns>Results with Sprint objects</returns> public static async Task<SearchIssuesResult<AgileIssue, long>> GetBacklogAsync(this IAgileDomain jiraClient, long boardId, Page page = null, CancellationToken cancellationToken = default) { jiraClient.Behaviour.MakeCurrent(); var backlogIssuesUri = jiraClient.JiraAgileRestUri.AppendSegments("board", boardId, "backlog"); if (page != null) { backlogIssuesUri = backlogIssuesUri.ExtendQuery(new Dictionary<string, object> { { "startAt", page.StartAt }, { "maxResults", page.MaxResults } }); } var response = await backlogIssuesUri.GetAsAsync<HttpResponse<SearchIssuesResult<AgileIssue, long>, Error>>(cancellationToken).ConfigureAwait(false); var result = response.HandleErrors(); // Store the original search parameter(s), so we can get the next page result.SearchParameter = boardId; return result; } /// <summary> /// Get all issues on a board /// See /// <a href="https://docs.atlassian.com/jira-software/REST/cloud/#agile/1.0/board-getIssuesForBoard"> /// get issues for /// board /// </a> /// </summary> /// <param name="jiraClient">IAgileDomain to bind the extension method to</param> /// <param name="boardId">Id of the board to get the issues for</param> /// <param name="page">optional Page</param> /// <param name="cancellationToken">CancellationToken</param> /// <returns>SearchResult with AgileIssue objects</returns> public static async Task<SearchIssuesResult<AgileIssue, long>> GetIssuesOnBoardAsync(this IAgileDomain jiraClient, long boardId, Page page = null, CancellationToken cancellationToken = default) { jiraClient.Behaviour.MakeCurrent(); var boardIssuesUri = jiraClient.JiraAgileRestUri.AppendSegments("board", boardId, "issue"); if (page != null) { boardIssuesUri = boardIssuesUri.ExtendQuery(new Dictionary<string, object> { { "startAt", page.StartAt }, { "maxResults", page.MaxResults } }); } var response = await boardIssuesUri.GetAsAsync<HttpResponse<SearchIssuesResult<AgileIssue, long>, Error>>(cancellationToken).ConfigureAwait(false); var result = response.HandleErrors(); // Store the original search parameter(s), so we can get the next page result.SearchParameter = boardId; return result; } /// <summary> /// Get all issues for a spring /// See /// <a href="https://docs.atlassian.com/jira-software/REST/cloud/#agile/1.0/board/{boardId}/sprint-getIssuesForSprint"> /// get /// issues for spring /// </a> /// </summary> /// <param name="jiraClient">IAgileDomain to bind the extension method to</param> /// <param name="boardId">Id of the board to get the issues for</param> /// <param name="sprintId">Id of the sprint to get the issues for</param> /// <param name="page">optional Page</param> /// <param name="cancellationToken">CancellationToken</param> /// <returns>SearchResult with AgileIssue objects</returns> public static async Task<SearchIssuesResult<AgileIssue, Tuple<long, long>>> GetIssuesInSprintAsync(this IAgileDomain jiraClient, long boardId, long sprintId, Page page = null, CancellationToken cancellationToken = default) { jiraClient.Behaviour.MakeCurrent(); var sprintIssuesUri = jiraClient.JiraAgileRestUri.AppendSegments("board", boardId, "sprint", sprintId, "issue"); if (page != null) { sprintIssuesUri = sprintIssuesUri.ExtendQuery(new Dictionary<string, object> { { "startAt", page.StartAt }, { "maxResults", page.MaxResults } }); } var response = await sprintIssuesUri.GetAsAsync<HttpResponse<SearchIssuesResult<AgileIssue, Tuple<long, long>>, Error>>(cancellationToken).ConfigureAwait(false); var result = response.HandleErrors(); // Store the original search parameter(s), so we can get the next page result.SearchParameter = new Tuple<long,long>(boardId, sprintId); return result; } /// <summary> /// Get board configuration /// See /// <a href="https://docs.atlassian.com/jira-software/REST/cloud/#agile/1.0/board-getConfiguration"> /// get board /// configuration /// </a> /// </summary> /// <param name="jiraClient">IAgileDomain to bind the extension method to</param> /// <param name="boardId">Id of the board to get the sprints for</param> /// <param name="cancellationToken">CancellationToken</param> /// <returns>BoardConfiguration</returns> public static async Task<BoardConfiguration> GetBoardConfigurationAsync(this IAgileDomain jiraClient, long boardId, CancellationToken cancellationToken = default) { jiraClient.Behaviour.MakeCurrent(); var boardConfigurationUri = jiraClient.JiraAgileRestUri.AppendSegments("board", boardId, "configuration"); var response = await boardConfigurationUri.GetAsAsync<HttpResponse<BoardConfiguration, Error>>(cancellationToken).ConfigureAwait(false); return response.HandleErrors(); } /// <summary> /// Returns the board for the given board Id. This board will only be returned if the user has permission to view it. /// See <a href="https://docs.atlassian.com/jira-software/REST/cloud/#agile/1.0/board-getBoard">get board</a> /// </summary> /// <param name="jiraClient">IAgileDomain to bind the extension method to</param> /// <param name="boardId">Id of the board to return</param> /// <param name="cancellationToken">CancellationToken</param> /// <returns>Board</returns> public static async Task<Board> GetBoardAsync(this IAgileDomain jiraClient, long boardId, CancellationToken cancellationToken = default) { jiraClient.Behaviour.MakeCurrent(); var boardUri = jiraClient.JiraAgileRestUri.AppendSegments("board", boardId); var response = await boardUri.GetAsAsync<HttpResponse<Board, Error>>(cancellationToken).ConfigureAwait(false); return response.HandleErrors(); } /// <summary> /// Creates a new board. Board name, type and filter Id is required. /// See <a href="https://docs.atlassian.com/jira-software/REST/cloud/#agile/1.0/board-createBoard">create board</a> /// </summary> /// <param name="jiraClient">IAgileDomain to bind the extension method to</param> /// <param name="board">Board to create</param> /// <param name="cancellationToken">CancellationToken</param> public static async Task<Board> CreateBoardAsync(this IAgileDomain jiraClient, Board board, CancellationToken cancellationToken = default) { if (board == null) { throw new ArgumentNullException(nameof(board)); } if (board.FilterId == 0) { throw new ArgumentNullException(nameof(board.FilterId)); } jiraClient.Behaviour.MakeCurrent(); var boardUri = jiraClient.JiraAgileRestUri.AppendSegments("board"); var response = await boardUri.PostAsync<HttpResponse<Board>>(board, cancellationToken).ConfigureAwait(false); return response.HandleErrors(HttpStatusCode.Created); } /// <summary> /// Deletes the board. /// See <a href="https://docs.atlassian.com/jira-software/REST/cloud/#agile/1.0/board-deleteBoard">delete board</a> /// </summary> /// <param name="jiraClient">IAgileDomain to bind the extension method to</param> /// <param name="boardId">Id of the board to return</param> /// <param name="cancellationToken">CancellationToken</param> public static async Task DeleteBoardAsync(this IAgileDomain jiraClient, long boardId, CancellationToken cancellationToken = default) { jiraClient.Behaviour.MakeCurrent(); var boardUri = jiraClient.JiraAgileRestUri.AppendSegments("board", boardId); var response = await boardUri.DeleteAsync<HttpResponse>(cancellationToken).ConfigureAwait(false); response.HandleStatusCode(HttpStatusCode.NoContent); } /// <summary> /// Get all boards /// See <a href="https://docs.atlassian.com/jira-software/REST/cloud/#agile/1.0/board-getAllBoards">get all boards</a> /// </summary> /// <param name="jiraClient">IAgileDomain to bind the extension method to</param> /// <param name="type">Filters results to boards of the specified type. Valid values: scrum, kanban.</param> /// <param name="name">Filters results to boards that match or partially match the specified name.</param> /// <param name="projectKeyOrId"> /// Filters results to boards that are relevant to a project. Relevance means that the jql /// filter defined in board contains a reference to a project. /// </param> /// <param name="page">optional Page</param> /// <param name="cancellationToken">CancellationToken</param> /// <returns>Results with Board objects</returns> public static async Task<SearchResult<Board, Tuple<string, string, string>>> GetBoardsAsync(this IAgileDomain jiraClient, string type = null, string name = null, string projectKeyOrId = null, Page page = null, CancellationToken cancellationToken = default) { jiraClient.Behaviour.MakeCurrent(); var boardsUri = jiraClient.JiraAgileRestUri.AppendSegments("board"); if (page != null) { boardsUri = boardsUri.ExtendQuery(new Dictionary<string, object> { { "startAt", page.StartAt }, { "maxResults", page.MaxResults } }); } if (type != null) { boardsUri = boardsUri.ExtendQuery("type", type); } if (name != null) { boardsUri = boardsUri.ExtendQuery("name", name); } if (projectKeyOrId != null) { boardsUri = boardsUri.ExtendQuery("projectKeyOrId", projectKeyOrId); } var response = await boardsUri.GetAsAsync<HttpResponse<SearchResult<Board, Tuple<string, string, string>>, Error>>(cancellationToken).ConfigureAwait(false); // Store the original search parameter(s), so we can get the next page var result = response.HandleErrors(); // Store the original search parameter(s), so we can get the next page result.SearchParameter = new Tuple<string, string, string>(type, name, projectKeyOrId); return result; } /// <summary> /// Get all epics for a board /// See <a href="https://docs.atlassian.com/jira-software/REST/cloud/#agile/1.0/board/{boardId}/epic">get epics on board</a> /// </summary> /// <param name="jiraClient">IAgileDomain to bind the extension method to</param> /// <param name="boardId">Id of the board to get the epics for</param> /// <param name="page">optional Page</param> /// <param name="cancellationToken">CancellationToken</param> /// <returns>Results with Epic objects</returns> public static async Task<SearchResult<Epic, long>> GetEpicsAsync(this IAgileDomain jiraClient, long boardId, Page page = null, CancellationToken cancellationToken = default) { jiraClient.Behaviour.MakeCurrent(); var epicsUri = jiraClient.JiraAgileRestUri.AppendSegments("board", boardId, "epic"); if (page != null) { epicsUri = epicsUri.ExtendQuery(new Dictionary<string, object> { { "startAt", page.StartAt }, { "maxResults", page.MaxResults } }); } var response = await epicsUri.GetAsAsync<HttpResponse<SearchResult<Epic, long>, Error>>(cancellationToken).ConfigureAwait(false); // Store the original search parameter(s), so we can get the next page var result = response.HandleErrors(); // Store the original search parameter(s), so we can get the next page result.SearchParameter = boardId; return result; } /// <summary> /// Get all issues for an Epic /// See <a href="https://docs.atlassian.com/jira-software/REST/cloud/#agile/1.0/board/{boardId}/epic-getIssuesForEpic">get issues for epic</a> /// </summary> /// <param name="jiraClient">IAgileDomain to bind the extension method to</param> /// <param name="boardId">Id of the board to get the issues for</param> /// <param name="epicId">Id of the epic to get the issues for</param> /// <param name="page">optional Page</param> /// <param name="cancellationToken">CancellationToken</param> /// <returns>SearchResult with AgileIssue objects</returns> public static async Task<SearchIssuesResult<AgileIssue, Tuple<long, long>>> GetIssuesForEpicAsync(this IAgileDomain jiraClient, long boardId, long epicId, Page page = null, CancellationToken cancellationToken = default) { jiraClient.Behaviour.MakeCurrent(); var epicIssuesUri = jiraClient.JiraAgileRestUri.AppendSegments("board", boardId, "epic", epicId, "issue"); if (page != null) { epicIssuesUri = epicIssuesUri.ExtendQuery(new Dictionary<string, object> { { "startAt", page.StartAt }, { "maxResults", page.MaxResults } }); } var response = await epicIssuesUri.GetAsAsync<HttpResponse<SearchIssuesResult<AgileIssue, Tuple<long, long>>, Error>>(cancellationToken).ConfigureAwait(false); var result = response.HandleErrors(); // Store the original search parameter(s), so we can get the next page result.SearchParameter = new Tuple<long, long>(boardId, epicId); return result; } /// <summary> /// Returns all issues that belong to the epic, for the given epic Id. /// This only includes issues that the user has permission to view. /// Issues returned from this resource include Agile fields, like sprint, closedSprints, flagged, and epic. By default, the returned issues are ordered by rank. /// See <a href="https://docs.atlassian.com/jira-software/REST/cloud/#agile/1.0/epic-getIssuesForEpic">get issues for epic</a> /// </summary> /// <param name="jiraClient">IAgileDomain to bind the extension method to</param> /// <param name="epicId">Id of the epic to get the issues for</param> /// <param name="page">optional Page</param> /// <param name="cancellationToken">CancellationToken</param> /// <returns>SearchResult with AgileIssue objects</returns> public static async Task<SearchIssuesResult<AgileIssue, long>> GetIssuesForEpicAsync(this IAgileDomain jiraClient, long epicId, Page page = null, CancellationToken cancellationToken = default) { jiraClient.Behaviour.MakeCurrent(); var epicIssuesUri = jiraClient.JiraAgileRestUri.AppendSegments("epic", epicId, "issue"); if (page != null) { epicIssuesUri = epicIssuesUri.ExtendQuery(new Dictionary<string, object> { { "startAt", page.StartAt }, { "maxResults", page.MaxResults } }); } var response = await epicIssuesUri.GetAsAsync<HttpResponse<SearchIssuesResult<AgileIssue, long>, Error>>(cancellationToken).ConfigureAwait(false); var result = response.HandleErrors(); // Store the original search parameter(s), so we can get the next page result.SearchParameter = epicId; return result; } /// <summary> /// Get an Epic /// See <a href="https://docs.atlassian.com/jira-software/REST/cloud/#agile/1.0/epic-getEpic">Get epic</a> /// </summary> /// <param name="jiraClient">IAgileDomain to bind the extension method to</param> /// <param name="epicId">Id of the epic to get</param> /// <param name="cancellationToken">CancellationToken</param> /// <returns>Epic</returns> public static async Task<Epic> GetEpicAsync(this IAgileDomain jiraClient, long epicId, CancellationToken cancellationToken = default) { jiraClient.Behaviour.MakeCurrent(); var epicUri = jiraClient.JiraAgileRestUri.AppendSegments("epic", epicId); var response = await epicUri.GetAsAsync<HttpResponse<Epic, Error>>(cancellationToken).ConfigureAwait(false); return response.HandleErrors(); } /// <summary> /// Update an Epic /// See <a href="https://docs.atlassian.com/jira-software/REST/cloud/#agile/1.0/epic-partiallyUpdateEpic">Partially update epic</a> /// </summary> /// <param name="jiraClient">IAgileDomain to bind the extension method to</param> /// <param name="epic">Epic to update</param> /// <param name="cancellationToken">CancellationToken</param> /// <returns>Epic</returns> public static async Task<Epic> UpdateEpicAsync(this IAgileDomain jiraClient, Epic epic, CancellationToken cancellationToken = default) { jiraClient.Behaviour.MakeCurrent(); var epicUri = jiraClient.JiraAgileRestUri.AppendSegments("epic", epic.Id); var response = await epicUri.PostAsync<HttpResponse<Epic, Error>>(epic, cancellationToken).ConfigureAwait(false); return response.HandleErrors(); } /// <summary> /// Get all issues without an Epic /// See <a href="https://docs.atlassian.com/jira-software/REST/cloud/#agile/1.0/board/{boardId}/epic-getIssuesWithoutEpic">get issues without epic</a> /// </summary> /// <param name="jiraClient">IAgileDomain to bind the extension method to</param> /// <param name="boardId">Id of the board to get the issues for</param> /// <param name="page">optional Page</param> /// <param name="cancellationToken">CancellationToken</param> /// <returns>SearchResult with AgileIssue objects</returns> public static async Task<SearchIssuesResult<AgileIssue, long>> GetIssuesWithoutEpicAsync(this IAgileDomain jiraClient, long boardId, Page page = null, CancellationToken cancellationToken = default) { jiraClient.Behaviour.MakeCurrent(); var epicLessIssuesUri = jiraClient.JiraAgileRestUri.AppendSegments("board", boardId, "epic", "none", "issue"); if (page != null) { epicLessIssuesUri = epicLessIssuesUri.ExtendQuery(new Dictionary<string, object> { { "startAt", page.StartAt }, { "maxResults", page.MaxResults } }); } var response = await epicLessIssuesUri.GetAsAsync<HttpResponse<SearchIssuesResult<AgileIssue, long>, Error>>(cancellationToken).ConfigureAwait(false); var result = response.HandleErrors(); // Store the original search parameter(s), so we can get the next page result.SearchParameter = boardId; return result; } } }
52.296146
199
0.596075
[ "MIT" ]
oldmansauls/Dapplo.Jira
src/Dapplo.Jira/AgileExtensions.cs
25,784
C#
 // IOpenCommand.cs // Copyright (c) 2014+ by Michael Penner. All rights reserved. namespace EamonRT.Framework.Commands { /// <summary></summary> public interface IOpenCommand : ICommand { } }
15.357143
64
0.660465
[ "MIT" ]
TheRealEamonCS/Eamon-CS
System/EamonRT/Framework/Commands/Player/Manipulation/IOpenCommand.cs
217
C#
using System; using System.Collections.Generic; using Elasticsearch.Net; namespace Nest { [JsonFormatter(typeof(LikeFormatter))] public class Like : Union<string, ILikeDocument> { public Like(string item) : base(item) { } public Like(ILikeDocument item) : base(item) { } public static implicit operator Like(string likeText) => new Like(likeText); public static implicit operator Like(LikeDocumentBase like) => new Like(like); internal static bool IsConditionless(Like like) => like.Item1.IsNullOrEmpty() && (like.Item2 == null || like.Item2.Id == null && like.Item2.Document == null); } public class LikeDescriptor<T> : DescriptorPromiseBase<LikeDescriptor<T>, List<Like>> where T : class { public LikeDescriptor() : base(new List<Like>()) { } public LikeDescriptor<T> Text(string likeText) => Assign(likeText, (a, v) => a.Add(v)); public LikeDescriptor<T> Document(Func<LikeDocumentDescriptor<T>, ILikeDocument> selector) { var l = selector?.Invoke(new LikeDocumentDescriptor<T>()); return l == null ? this : Assign(l, (a, v) => a.Add(new Like(v))); } } internal class LikeFormatter : IJsonFormatter<Like> { private static readonly UnionFormatter<string, ILikeDocument> UnionFormatter = new UnionFormatter<string, ILikeDocument>(); public Like Deserialize(ref JsonReader reader, IJsonFormatterResolver formatterResolver) { var union = UnionFormatter.Deserialize(ref reader, formatterResolver); if (union == null) return null; switch (union._tag) { case 0: return new Like(union.Item1); case 1: return new Like(union.Item2); default: return null; } } public void Serialize(ref JsonWriter writer, Like value, IJsonFormatterResolver formatterResolver) => UnionFormatter.Serialize(ref writer, value, formatterResolver); } }
29.612903
125
0.714597
[ "Apache-2.0" ]
591094733/elasticsearch-net
src/Nest/QueryDsl/Specialized/MoreLikeThis/Like/Like.cs
1,838
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Krypton.Toolkit.Resources { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class SparkleOrangeRadioButtonResources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal SparkleOrangeRadioButtonResources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Krypton.Toolkit.Resources.SparkleOrangeRadioButtonResources", typeof(SparkleOrangeRadioButtonResources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap RadioButtonSparkleOrangeNC { get { object obj = ResourceManager.GetObject("RadioButtonSparkleOrangeNC", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap RadioButtonSparkleOrangeP { get { object obj = ResourceManager.GetObject("RadioButtonSparkleOrangeP", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap RadioButtonSparkleOrangePC { get { object obj = ResourceManager.GetObject("RadioButtonSparkleOrangePC", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap RadioButtonSparkleOrangeT { get { object obj = ResourceManager.GetObject("RadioButtonSparkleOrangeT", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap RadioButtonSparkleOrangeTC { get { object obj = ResourceManager.GetObject("RadioButtonSparkleOrangeTC", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } } }
43.017544
228
0.60053
[ "BSD-3-Clause" ]
Krypton-Suite/Standard-Toolk
Source/Krypton Components/Krypton.Toolkit/Resources/SparkleOrangeRadioButtonResources.Designer.cs
4,906
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.Certmanager.V1Alpha2 { /// <summary> /// A node selector requirement is a selector that contains values, a key, and an operator that relates the key and values. /// </summary> public class ClusterIssuerSpecAcmeSolversHttp01IngressPodTemplateSpecAffinityNodeAffinityRequiredDuringSchedulingIgnoredDuringExecutionNodeSelectorTermsMatchExpressionsArgs : Pulumi.ResourceArgs { /// <summary> /// The label key that the selector applies to. /// </summary> [Input("key", required: true)] public Input<string> Key { get; set; } = null!; /// <summary> /// Represents a key's relationship to a set of values. Valid operators are In, NotIn, Exists, DoesNotExist. Gt, and Lt. /// </summary> [Input("operator", required: true)] public Input<string> Operator { get; set; } = null!; [Input("values")] private InputList<string>? _values; /// <summary> /// An array of string values. If the operator is In or NotIn, the values array must be non-empty. If the operator is Exists or DoesNotExist, the values array must be empty. If the operator is Gt or Lt, the values array must have a single element, which will be interpreted as an integer. This array is replaced during a strategic merge patch. /// </summary> public InputList<string> Values { get => _values ?? (_values = new InputList<string>()); set => _values = value; } public ClusterIssuerSpecAcmeSolversHttp01IngressPodTemplateSpecAffinityNodeAffinityRequiredDuringSchedulingIgnoredDuringExecutionNodeSelectorTermsMatchExpressionsArgs() { } } }
43.276596
351
0.685349
[ "MIT" ]
WhereIsMyTransport/Pulumi.Crds.CertManager
crd/dotnet/Certmanager/V1Alpha2/Inputs/ClusterIssuerSpecAcmeSolversHttp01IngressPodTemplateSpecAffinityNodeAffinityRequiredDuringSchedulingIgnoredDuringExecutionNodeSelectorTermsMatchExpressionsArgs.cs
2,034
C#
using System; using System.IO; using System.Threading.Tasks; using Adriva.Common.Core; namespace Adriva.Storage.Abstractions { public interface IBlobClient : IStorageClient { ValueTask<bool> ExistsAsync(string name); Task<BlobItemProperties> GetPropertiesAsync(string name); Task<string> UpsertAsync(string name, Stream stream, int cacheDuration = 0); Task<string> UpsertAsync(string name, ReadOnlyMemory<byte> data, int cacheDuration = 0); Task UpdateAsync(string name, Stream stream, string etag); Task UpdateAsync(string name, ReadOnlyMemory<byte> data, string etag); Task<Stream> OpenReadStreamAsync(string name); Task<ReadOnlyMemory<byte>> ReadAllBytesAsync(string name); ValueTask DeleteAsync(string name); Task<SegmentedResult<string>> ListAllAsync(string continuationToken, string prefix = null, int count = 500); } }
30.9
116
0.719525
[ "MIT" ]
adriva/coreframework
Storage/src/Adriva.Storage.Abstractions/IBlobClient.cs
927
C#
using System; using System.Collections.Generic; class BinarySearch { static void Main() { Console.WriteLine("Enter your int array, separated by coma (,):"); List<int> arr = new List<int> { 1, 3, 7, 12, 13, 23, 45 }; /*Console.ReadLine() .Split(new char[] { ' ', ',', '\t' }, StringSplitOptions.RemoveEmptyEntries) .Select(x => int.Parse(x)) .ToArray();*/ Console.Write("Enter value of K:"); int K = int.Parse(Console.ReadLine()); int index = Math.Abs(arr.BinarySearch(K)); if (arr.BinarySearch(K) > 0) { Console.WriteLine(arr[index]); } else { Console.WriteLine(arr[index - 1]); } } }
28.730769
88
0.524766
[ "MIT" ]
TemplarRei/TelerikAcademy
CSharpTwo/0202.MultidimensionalArrays/04.BinarySearch/BinarySearch.cs
749
C#
using System.Linq; public class House { private static string[] nouns = { "", "house", "malt", "rat", "cat","dog", "cow with the crumpled horn", "maiden all forlorn", "man all tattered and torn", "priest all shaven and shorn", "rooster that crowed in the morn", "farmer sowing his corn", "horse and the hound and the horn", }; private static string[] verbs = { "", "lay in", "ate", "killed", "worried", "tossed", "milked", "kissed", "married", "woke", "kept", "belonged to", }; public static string Recite(int verseNum) { var parade = from i in Enumerable.Range(1, verseNum - 1) let v = verseNum - i select $"that {verbs[v]} the {nouns[v]} "; return $"This is the {nouns[verseNum]} {string.Join("", parade)}that Jack built."; } public static string Recite(int startVerse, int endVerse) => string.Join( "\n", Enumerable.Range(startVerse, endVerse - startVerse + 1) .Select(i => Recite(i)) ); }
27.23913
91
0.480447
[ "MIT" ]
cmccandless/ExercismSolutions-csharp
house/House.cs
1,255
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. namespace WordAddInWeb.Services { using System.Threading.Tasks; using WordAddInWeb.Models; public interface IAssignedUserService { Task<Activation> Activate(string url, string accesstoken); } }
21.428571
66
0.72
[ "MIT" ]
BobGerman/office-add-in-saas-monetization-sample
MonetizationCodeSample/WordAddinWeb/Services/Interfaces/IAssignedUserService.cs
302
C#
// Copyright (c) 2021 Salim Mayaleh. All Rights Reserved // Licensed under the BSD-3-Clause License // Generated at 08.11.2021 21:25:55 by RaynetApiDocToDotnet.ApiDocParser, created by Salim Mayaleh. using System; using System.Collections.Generic; using Newtonsoft.Json; namespace Maya.Raynet.Crm.Response.Get { public class BusinessCase { [JsonProperty("id", DefaultValueHandling = DefaultValueHandling.Ignore)] public int Id { get; set; } [JsonProperty("code", DefaultValueHandling = DefaultValueHandling.Ignore)] public string Code { get; set; } [JsonProperty("name", DefaultValueHandling = DefaultValueHandling.Ignore)] public string Name { get; set; } [JsonProperty("company", DefaultValueHandling = DefaultValueHandling.Ignore)] public Company Company { get; set; } [JsonProperty("person", DefaultValueHandling = DefaultValueHandling.Ignore)] public Person Person { get; set; } [JsonProperty("owner", DefaultValueHandling = DefaultValueHandling.Ignore)] public Person Owner { get; set; } [JsonProperty("currency", DefaultValueHandling = DefaultValueHandling.Ignore)] public IdValue Currency { get; set; } [JsonProperty("validFrom", DefaultValueHandling = DefaultValueHandling.Ignore)] public string ValidFrom { get; set; } [JsonProperty("validTill", DefaultValueHandling = DefaultValueHandling.Ignore)] public DateTimeOffset? ValidTill { get; set; } [JsonProperty("scheduledEnd", DefaultValueHandling = DefaultValueHandling.Ignore)] public DateTimeOffset? ScheduledEnd { get; set; } [JsonProperty("totalAmount", DefaultValueHandling = DefaultValueHandling.Ignore)] public int TotalAmount { get; set; } [JsonProperty("totalAmountWithTax", DefaultValueHandling = DefaultValueHandling.Ignore)] public int TotalAmountWithTax { get; set; } [JsonProperty("estimatedValue", DefaultValueHandling = DefaultValueHandling.Ignore)] public int EstimatedValue { get; set; } [JsonProperty("tradingProfit", DefaultValueHandling = DefaultValueHandling.Ignore)] public int TradingProfit { get; set; } [JsonProperty("status", DefaultValueHandling = DefaultValueHandling.Ignore)] public string Status { get; set; } [JsonProperty("probability", DefaultValueHandling = DefaultValueHandling.Ignore)] public int Probability { get; set; } [JsonProperty("exchangeRate", DefaultValueHandling = DefaultValueHandling.Ignore)] public int ExchangeRate { get; set; } [JsonProperty("businessCasePhase", DefaultValueHandling = DefaultValueHandling.Ignore)] public IdValue BusinessCasePhase { get; set; } [JsonProperty("businessCaseType", DefaultValueHandling = DefaultValueHandling.Ignore)] public BusinessCaseType BusinessCaseType { get; set; } [JsonProperty("category", DefaultValueHandling = DefaultValueHandling.Ignore)] public BusinessCaseCategory Category { get; set; } [JsonProperty("project", DefaultValueHandling = DefaultValueHandling.Ignore)] public Project Project { get; set; } /* "source": null */ [JsonProperty("source", DefaultValueHandling = DefaultValueHandling.Ignore)] public object Source { get; set; } [JsonProperty("businessCaseClassification1", DefaultValueHandling = DefaultValueHandling.Ignore)] public IdValue BusinessCaseClassification1 { get; set; } /* "businessCaseClassification2": null */ [JsonProperty("businessCaseClassification2", DefaultValueHandling = DefaultValueHandling.Ignore)] public IdValue BusinessCaseClassification2 { get; set; } /* "businessCaseClassification3": null */ [JsonProperty("businessCaseClassification3", DefaultValueHandling = DefaultValueHandling.Ignore)] public IdValue BusinessCaseClassification3 { get; set; } /* "losingReason": null */ [JsonProperty("losingReason", DefaultValueHandling = DefaultValueHandling.Ignore)] public object LosingReason { get; set; } /* "losingCategory": null */ [JsonProperty("losingCategory", DefaultValueHandling = DefaultValueHandling.Ignore)] public object LosingCategory { get; set; } [JsonProperty("rowInfo.createdAt", DefaultValueHandling = DefaultValueHandling.Ignore)] public string RowInfo_createdAt { get; set; } [JsonProperty("rowInfo.createdBy", DefaultValueHandling = DefaultValueHandling.Ignore)] public string RowInfo_createdBy { get; set; } [JsonProperty("rowInfo.updatedAt", DefaultValueHandling = DefaultValueHandling.Ignore)] public string RowInfo_updatedAt { get; set; } [JsonProperty("rowInfo.updatedBy", DefaultValueHandling = DefaultValueHandling.Ignore)] public string RowInfo_updatedBy { get; set; } /* "rowInfo.rowAccess": null */ [JsonProperty("rowInfo.rowAccess", DefaultValueHandling = DefaultValueHandling.Ignore)] public string RowInfo_rowAccess { get; set; } /* "rowInfo.rowState": null */ [JsonProperty("rowInfo.rowState", DefaultValueHandling = DefaultValueHandling.Ignore)] public string RowInfo_rowState { get; set; } [JsonProperty("securityLevel", DefaultValueHandling = DefaultValueHandling.Ignore)] public SecurityLevel SecurityLevel { get; set; } [JsonProperty("description", DefaultValueHandling = DefaultValueHandling.Ignore)] public string Description { get; set; } [JsonProperty("tags", DefaultValueHandling = DefaultValueHandling.Ignore)] public List<string> Tags { get; set; } [JsonProperty("attachments", DefaultValueHandling = DefaultValueHandling.Ignore)] public List<Attachment> Attachments { get; set; } [JsonProperty("customFields", DefaultValueHandling = DefaultValueHandling.Ignore)] public Dictionary<string, object> CustomFields { get; set; } [JsonProperty("items", DefaultValueHandling = DefaultValueHandling.Ignore)] public List<BusinessCaseItem> Items { get; set; } } }
44.798561
105
0.704513
[ "BSD-3-Clause" ]
mayaleh/Maya.Raynet.Crm
src/Maya.Raynet.Crm/Response/Get/BusinessCase.cs
6,227
C#
namespace Emeraude.Application.Admin.EmPages.Shared; /// <summary> /// EmPages constants used in the workflow. /// </summary> public static class EmPagesConstants { /// <summary> /// Query param key used for identification of the parent. /// </summary> public const string ParentQueryParam = "em_parent_id"; }
27.25
62
0.703364
[ "Apache-2.0" ]
emeraudeframework/emeraude
src/Emeraude.Application.Admin.EmPages/Shared/EmPagesConstants.cs
329
C#
using System; using System.Globalization; using System.Linq; using System.Windows.Forms; using Unity; using WebMoney.Services.Contracts; using WMBusinessTools.Extensions.BusinessObjects; using WMBusinessTools.Extensions.Contracts; using WMBusinessTools.Extensions.Contracts.Contexts; using WMBusinessTools.Extensions.DisplayHelpers; using WMBusinessTools.Extensions.StronglyTypedWrappers; using Xml2WinForms; namespace WMBusinessTools.Extensions { public sealed class ContractDetailsFormProvider : IContractFormProvider { public bool CheckCompatibility(ContractContext context) { if (null == context) throw new ArgumentNullException(nameof(context)); return true; } public Form GetForm(ContractContext context) { if (null == context) throw new ArgumentNullException(nameof(context)); var signatures = context.Contract.Signatures.Select(s => { var formattingService = context.UnityContainer.Resolve<IFormattingService>(); var identifierValue = formattingService.FormatIdentifier(s.AcceptorIdentifier); var acceptTimeValue = null == s.AcceptTime ? string.Empty : formattingService.FormatDateTime(s.AcceptTime.Value); return new ListItemContent(new ResultRecord(identifierValue, acceptTimeValue)) { ImageKey = "Ant" }; }) .ToList(); var valuesWrapper = new ContractDetailsFormValuesWrapper { Control1Name = context.Contract.Name, Control2Text = context.Contract.Text, Control3HasLimitedAccess = !context.Contract.IsPublic, Control4Details = signatures }; var form = SubmitFormDisplayHelper.LoadSubmitFormByExtensionId(context.ExtensionManager, ExtensionCatalog.ContractDetails, valuesWrapper.CollectIncomeValues()); form.ServiceCommand += (sender, args) => { if (!"Copy".Equals(args.Command)) return; var resultRecord = args.Argument as ResultRecord; if (null != resultRecord) { string text = string.Format(CultureInfo.InvariantCulture, "{0} {1}", resultRecord.Name, resultRecord.Value); Clipboard.SetText(text, TextDataFormat.UnicodeText); } }; return form; } } }
35.447368
107
0.595768
[ "MIT" ]
MarketKernel/webmoney-business-tools
Src/WMBusinessTools.Extensions/ContractExtensions/ContractDetailsFormProvider.cs
2,696
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Kinetic_Saaand { class DistanceParticlePairsSelector : IParticlePairsSelector { private int dim; private double maxDistance; public DistanceParticlePairsSelector(int dim, double maxDistance) { this.dim = dim; this.maxDistance = maxDistance; } // public IEnumerable<Tuple<Particle, Particle>> selectPairs(IEnumerable<Particle> particles) { List<Particle> particlesList = particles.ToList(); //for multiple iterations Tuple<double[], double[]> bounds = getCoordinateBounds(particlesList); double[] minBounds = bounds.Item1; double[] maxBounds = bounds.Item2; //create a grid with boxes of side length maxDistance, and divide the points to bins representing //the grid boxes. That guarentees that points in non-touching bins are of distance of atleast maxDistance. //By only generating non-empty bins, the number of bins is bounded by the number of points. The time complexity //of selecting all pairs of points from same/neighboring grids is O(M^2 * d * 2k), when M is the maximum number //of points in a grid, d is the number of non-empty grids, and k is the dimension. This is bounded by O(n^2). //If the points are somewhat evenly distributed, this makes for a big reduction in running time. //prepare bins Dictionary<double[], List<Particle>> gridsByPosition = new Dictionary<double[], List<Particle>>(); foreach(Particle particle in particles) { double[] binLowerCorner = new double[dim]; //given a particle's position, the corresponding bin needs to be identified. double[] particlePosition = particle.getPosition(); for(int i=0; i<dim; i++) { double boxIndex = Math.Floor((particlePosition[i] - minBounds[i]) / maxDistance); binLowerCorner[i] = minBounds[i] + maxDistance * boxIndex; } if (!gridsByPosition.ContainsKey(binLowerCorner)) gridsByPosition.Add(binLowerCorner, new List<Particle>()); gridsByPosition[binLowerCorner].Add(particle); } //select pairs from bins HashSet<Tuple<Particle, Particle>> pairs = new HashSet<Tuple<Particle,Particle>>(); HashSet<double[]> alreadyVisited = new HashSet<double[]>(); foreach (double[] position in gridsByPosition.Keys) { double[][] adjacentCoordinates = new double[dim][]; for(int coordinate =0 ; coordinate < dim; coordinate ++) adjacentCoordinates[coordinate] = new double[]{ position[coordinate] - maxDistance, position[coordinate], position[coordinate] + maxDistance}; foreach(double[] neighborPosition in Misc.CartesianProduct(adjacentCoordinates)) { if(alreadyVisited.Contains(neighborPosition)) continue; if(neighborPosition == position) { //pairs in the same bin foreach(Particle particle1 in gridsByPosition[position]) foreach(Particle particle2 in gridsByPosition[neighborPosition]) if(particle2 < particle1) //don't repeat pairs (x,y == y,x) pairs.Add(new Tuple<Particle, Particle>(particle1, particle2)); } else //pairs in adjacent bins foreach(Particle particle1 in gridsByPosition[position]) foreach(Particle particle2 in gridsByPosition[neighborPosition]) pairs.Add(new Tuple<Particle, Particle>(particle1, particle2)); } alreadyVisited.Add(position); } return pairs; } private Tuple<double[], double[]> getCoordinateBounds(List<Particle> particles) { double[] minBounds = new double[dim]; double[] maxBounds = new double[dim]; minBounds = maxBounds = particles[0].getPosition(); foreach(Particle particle in particles) { double[] position = particle.getPosition(); for(int i=0; i<dim; i++) { if (position[i] < minBounds[i]) minBounds[i] = position[i]; if (position[i] > maxBounds[i]) maxBounds[i] = position[i]; } } return new Tuple<double[], double[]>(minBounds, maxBounds); } } }
47.216981
135
0.565634
[ "MIT" ]
arielbro/Kinetic-Saaand
Kinetic_Saaand/DistanceParticlePairsSelector.cs
5,007
C#
// This file is part of Silk.NET. // // You may modify and distribute Silk.NET under the terms // of the MIT license. See the LICENSE file for details. using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Text; using Silk.NET.Core; using Silk.NET.Core.Native; using Silk.NET.Core.Attributes; using Silk.NET.Core.Contexts; using Silk.NET.Core.Loader; #pragma warning disable 1591 namespace Silk.NET.SDL { public unsafe readonly struct PfnSDLCurrentBeginThread : IDisposable { private readonly void* _handle; public delegate* unmanaged[Cdecl]<void*, uint, PfnVvUi, void*, uint, uint*, uint> Handle => (delegate* unmanaged[Cdecl]<void*, uint, PfnVvUi, void*, uint, uint*, uint>) _handle; public PfnSDLCurrentBeginThread ( delegate* unmanaged[Cdecl]<void*, uint, PfnVvUi, void*, uint, uint*, uint> ptr ) => _handle = ptr; public PfnSDLCurrentBeginThread ( SDLCurrentBeginThread proc ) => _handle = (void*) SilkMarshal.DelegateToPtr(proc); public static PfnSDLCurrentBeginThread From(SDLCurrentBeginThread proc) => new PfnSDLCurrentBeginThread(proc); public void Dispose() => SilkMarshal.Free((nint) _handle); public static implicit operator nint(PfnSDLCurrentBeginThread pfn) => (nint) pfn.Handle; public static explicit operator PfnSDLCurrentBeginThread(nint pfn) => new PfnSDLCurrentBeginThread((delegate* unmanaged[Cdecl]<void*, uint, PfnVvUi, void*, uint, uint*, uint>) pfn); public static implicit operator PfnSDLCurrentBeginThread(SDLCurrentBeginThread proc) => new PfnSDLCurrentBeginThread(proc); public static explicit operator SDLCurrentBeginThread(PfnSDLCurrentBeginThread pfn) => SilkMarshal.PtrToDelegate<SDLCurrentBeginThread>(pfn); public static implicit operator delegate* unmanaged[Cdecl]<void*, uint, PfnVvUi, void*, uint, uint*, uint>(PfnSDLCurrentBeginThread pfn) => pfn.Handle; public static implicit operator PfnSDLCurrentBeginThread(delegate* unmanaged[Cdecl]<void*, uint, PfnVvUi, void*, uint, uint*, uint> ptr) => new PfnSDLCurrentBeginThread(ptr); } public unsafe delegate uint SDLCurrentBeginThread(void* arg0, uint arg1, PfnVvUi arg2, void* arg3, uint arg4, uint* arg5); }
43
185
0.716279
[ "MIT" ]
ThomasMiz/Silk.NET
src/Windowing/Silk.NET.SDL/Structs/PfnSDLCurrentBeginThread.gen.cs
2,365
C#
// This file is part of the DisCatSharp project, based off DSharpPlus. // // Copyright (c) 2021-2022 AITSYS // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System; using System.Collections.Generic; using System.Linq; using DisCatSharp.Enums; using Newtonsoft.Json; namespace DisCatSharp.Entities { /// <summary> /// A select menu with multiple options to choose from. /// </summary> public sealed class DiscordSelectComponent : DiscordComponent { /// <summary> /// The options to pick from on this component. /// </summary> [JsonProperty("options", NullValueHandling = NullValueHandling.Ignore)] public IReadOnlyList<DiscordSelectComponentOption> Options { get; internal set; } = Array.Empty<DiscordSelectComponentOption>(); /// <summary> /// The text to show when no option is selected. /// </summary> [JsonProperty("placeholder", NullValueHandling = NullValueHandling.Ignore)] public string Placeholder { get; internal set; } /// <summary> /// The minimum amount of options that can be selected. Must be less than or equal to <see cref="MaximumSelectedValues"/>. Defaults to one. /// </summary> [JsonProperty("min_values", NullValueHandling = NullValueHandling.Ignore)] public int? MinimumSelectedValues { get; internal set; } = 1; /// <summary> /// The maximum amount of options that can be selected. Must be greater than or equal to zero or <see cref="MinimumSelectedValues"/>. Defaults to one. /// </summary> [JsonProperty("max_values", NullValueHandling = NullValueHandling.Ignore)] public int? MaximumSelectedValues { get; internal set; } = 1; /// <summary> /// Whether this select can be used. /// </summary> [JsonProperty("disabled", NullValueHandling = NullValueHandling.Ignore)] public bool Disabled { get; internal set; } /// <summary> /// Enables this component if it was disabled before. /// </summary> /// <returns>The current component.</returns> public DiscordSelectComponent Enable() { this.Disabled = false; return this; } /// <summary> /// Disables this component. /// </summary> /// <returns>The current component.</returns> public DiscordSelectComponent Disable() { this.Disabled = true; return this; } /// <summary> /// Constructs a new <see cref="DiscordSelectComponent"/>. /// </summary> /// <param name="customId">The Id to assign to the button. This is sent back when a user presses it.</param> /// <param name="options">Array of options</param> /// <param name="placeholder">Text to show if no option is slected.</param> /// <param name="minOptions">Minmum count of selectable options.</param> /// <param name="maxOptions">Maximum count of selectable options.</param> /// <param name="disabled">Whether this button should be initialized as being disabled. User sees a greyed out button that cannot be interacted with.</param> public DiscordSelectComponent(string customId, string placeholder, IEnumerable<DiscordSelectComponentOption> options, int minOptions = 1, int maxOptions = 1, bool disabled = false) : this() { this.CustomId = customId; this.Disabled = disabled; this.Options = options.ToArray(); this.Placeholder = placeholder; this.MinimumSelectedValues = minOptions; this.MaximumSelectedValues = maxOptions; } /// <summary> /// Initializes a new instance of the <see cref="DiscordSelectComponent"/> class. /// </summary> public DiscordSelectComponent() { this.Type = ComponentType.Select; } } }
39.060345
191
0.72324
[ "Apache-2.0" ]
Aiko-IT-Systems/DSharpPlusNextGen
DisCatSharp/Entities/Interaction/Components/Select/DiscordSelectComponent.cs
4,531
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using DSC.Core; using DSC.Actor; using DSC.Event; namespace DSC.Template.Actor.Default { public class ActorData { public Transform m_hActor; public BaseActorController<ActorData, DSC_ActorBehaviour> m_hController; public BaseActorStatus<ActorStatus> m_hStatus; public ActorStateFlag m_eStateFlag; public InputData m_hInputData; public ActorData(Transform hActor) { if (hActor == null) return; m_hActor = hActor; m_hController = hActor.GetComponent<BaseActorController<ActorData, DSC_ActorBehaviour>>(); InitData(); } public ActorData(Transform hActor, BaseActorController<ActorData, DSC_ActorBehaviour> hController) { m_hActor = hActor; m_hController = hController; InitData(); } protected virtual void InitData() { if (m_hActor == null) return; m_hStatus = m_hActor.GetComponent<BaseActorStatus<ActorStatus>>(); m_hInputData = new InputData { m_hInputCallback = new EventCallback<(InputEventType, GetInputType), ActorData, List<IActorBehaviourData>>() }; } } }
26.307692
124
0.615497
[ "MIT" ]
DeStiCap/Dim-Mind
Global Game Jam 2020/Library/PackageCache/com.dsc.actor@900269120db5276794759bcad0dec52537e6f458/Samples~/ActorTemplate/Scripts/Data/ActorData.cs
1,370
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Devices.V20160203.Inputs { /// <summary> /// The properties of an IoT hub shared access policy. /// </summary> public sealed class SharedAccessSignatureAuthorizationRuleArgs : Pulumi.ResourceArgs { /// <summary> /// The name of the shared access policy. /// </summary> [Input("keyName", required: true)] public Input<string> KeyName { get; set; } = null!; /// <summary> /// The primary key. /// </summary> [Input("primaryKey")] public Input<string>? PrimaryKey { get; set; } /// <summary> /// The permissions assigned to the shared access policy. /// </summary> [Input("rights", required: true)] public Input<Pulumi.AzureNative.Devices.V20160203.AccessRights> Rights { get; set; } = null!; /// <summary> /// The secondary key. /// </summary> [Input("secondaryKey")] public Input<string>? SecondaryKey { get; set; } public SharedAccessSignatureAuthorizationRuleArgs() { } } }
30.12766
101
0.610876
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/Devices/V20160203/Inputs/SharedAccessSignatureAuthorizationRuleArgs.cs
1,416
C#
using System.Collections.Generic; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace ConsoleApplication1 { class UsingCollector:CSharpSyntaxWalker { public readonly List<SyntaxNode> Statements = new List<SyntaxNode>(); public List<SyntaxKind> find = new List<SyntaxKind>() {SyntaxKind.IfStatement,SyntaxKind.ElseClause,SyntaxKind.ForEachStatement,SyntaxKind.WhileStatement,SyntaxKind.ForStatement,SyntaxKind.DoStatement,SyntaxKind.SwitchStatement,SyntaxKind.TryStatement}; public override void VisitIfStatement(IfStatementSyntax node) { this.Statements.Add(node); } public override void VisitSwitchStatement(SwitchStatementSyntax node) { this.Statements.Add(node); } public override void VisitElseClause(ElseClauseSyntax node) { this.Statements.Add(node); } public override void VisitWhileStatement(WhileStatementSyntax node) { this.Statements.Add(node); } public override void VisitForEachStatement(ForEachStatementSyntax node) { this.Statements.Add(node); } public override void VisitForStatement(ForStatementSyntax node) { this.Statements.Add(node); } public override void VisitDoStatement(DoStatementSyntax node) { this.Statements.Add(node); } public override void VisitTryStatement(TryStatementSyntax node) { this.Statements.Add(node); } } }
34.87234
263
0.671751
[ "MIT" ]
SilviaDGregorio/TestCreator
TestCreator/UsingCollector.cs
1,641
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.GoogleNative.Notebooks.V1.Outputs { /// <summary> /// A set of Shielded Instance options. Check [Images using supported Shielded VM features] Not all combinations are valid. /// </summary> [OutputType] public sealed class ShieldedInstanceConfigResponse { /// <summary> /// Defines whether the instance has integrity monitoring enabled. Enables monitoring and attestation of the boot integrity of the instance. The attestation is performed against the integrity policy baseline. This baseline is initially derived from the implicitly trusted boot image when the instance is created. Enabled by default. /// </summary> public readonly bool EnableIntegrityMonitoring; /// <summary> /// Defines whether the instance has Secure Boot enabled. Secure Boot helps ensure that the system only runs authentic software by verifying the digital signature of all boot components, and halting the boot process if signature verification fails. Disabled by default. /// </summary> public readonly bool EnableSecureBoot; /// <summary> /// Defines whether the instance has the vTPM enabled. Enabled by default. /// </summary> public readonly bool EnableVtpm; [OutputConstructor] private ShieldedInstanceConfigResponse( bool enableIntegrityMonitoring, bool enableSecureBoot, bool enableVtpm) { EnableIntegrityMonitoring = enableIntegrityMonitoring; EnableSecureBoot = enableSecureBoot; EnableVtpm = enableVtpm; } } }
42.282609
340
0.700257
[ "Apache-2.0" ]
AaronFriel/pulumi-google-native
sdk/dotnet/Notebooks/V1/Outputs/ShieldedInstanceConfigResponse.cs
1,945
C#
using AutoMapper; using Infrastructure.API; using Microsoft.Extensions.DependencyInjection; namespace Infrastructure.Mappings { public static class DataMappings { public static void AddDataMappings(this IServiceCollection services) { // add automapper services.AddAutoMapper(typeof(DataMappingProfile), typeof(APIModelsMappingProfile)); } } }
25.3125
96
0.711111
[ "MIT" ]
sailingchannels/data
Infrastructure/Mappings/AddDataMappings.cs
407
C#
// Copyright (c) Six Labors and contributors. // Licensed under the Apache License, Version 2.0. using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Reflection; using SixLabors.ImageSharp.Formats; using SixLabors.ImageSharp.PixelFormats; using Xunit.Abstractions; namespace SixLabors.ImageSharp.Tests { public abstract partial class TestImageProvider<TPixel> where TPixel : struct, IPixel<TPixel> { private class FileProvider : TestImageProvider<TPixel>, IXunitSerializable { // Need PixelTypes in the dictionary key, because result images of TestImageProvider<TPixel>.FileProvider // are shared between PixelTypes.Color & PixelTypes.Rgba32 private class Key : IEquatable<Key> { private Tuple<PixelTypes, string, Type> commonValues; private Dictionary<string, object> decoderParameters; public Key(PixelTypes pixelType, string filePath, IImageDecoder customDecoder) { Type customType = customDecoder?.GetType(); this.commonValues = new Tuple<PixelTypes, string, Type>(pixelType, filePath, customType); this.decoderParameters = GetDecoderParameters(customDecoder); } private static Dictionary<string, object> GetDecoderParameters(IImageDecoder customDecoder) { Type type = customDecoder.GetType(); var data = new Dictionary<string, object>(); while (type != null && type != typeof(object)) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo p in properties) { string key = $"{type.FullName}.{p.Name}"; object value = p.GetValue(customDecoder); data[key] = value; } type = type.GetTypeInfo().BaseType; } return data; } public bool Equals(Key other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; if (!this.commonValues.Equals(other.commonValues)) return false; if (this.decoderParameters.Count != other.decoderParameters.Count) { return false; } foreach (KeyValuePair<string, object> kv in this.decoderParameters) { object otherVal; if (!other.decoderParameters.TryGetValue(kv.Key, out otherVal)) { return false; } if (!object.Equals(kv.Value, otherVal)) { return false; } } return true; } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != this.GetType()) return false; return this.Equals((Key)obj); } public override int GetHashCode() { return this.commonValues.GetHashCode(); } public static bool operator ==(Key left, Key right) { return Equals(left, right); } public static bool operator !=(Key left, Key right) { return !Equals(left, right); } } private static readonly ConcurrentDictionary<Key, Image<TPixel>> cache = new ConcurrentDictionary<Key, Image<TPixel>>(); // Needed for deserialization! // ReSharper disable once UnusedMember.Local public FileProvider() { } public FileProvider(string filePath) { this.FilePath = filePath; } /// <summary> /// Gets the file path relative to the "~/tests/images" folder /// </summary> public string FilePath { get; private set; } public override string SourceFileOrDescription => this.FilePath; public override Image<TPixel> GetImage() { IImageDecoder decoder = TestEnvironment.GetReferenceDecoder(this.FilePath); return this.GetImage(decoder); } public override Image<TPixel> GetImage(IImageDecoder decoder) { Guard.NotNull(decoder, nameof(decoder)); Key key = new Key(this.PixelType, this.FilePath, decoder); Image<TPixel> cachedImage = cache.GetOrAdd( key, fn => { var testFile = TestFile.Create(this.FilePath); return Image.Load<TPixel>(this.Configuration, testFile.Bytes, decoder); }); return cachedImage.Clone(); } public override void Deserialize(IXunitSerializationInfo info) { this.FilePath = info.GetValue<string>("path"); base.Deserialize(info); // must be called last } public override void Serialize(IXunitSerializationInfo info) { base.Serialize(info); info.AddValue("path", this.FilePath); } } public static string GetFilePathOrNull(ITestImageProvider provider) { var fileProvider = provider as FileProvider; return fileProvider?.FilePath; } } }
36.91716
132
0.507453
[ "Apache-2.0" ]
4thOffice/ImageSharp
tests/ImageSharp.Tests/TestUtilities/ImageProviders/FileProvider.cs
6,241
C#
using System; using System.Windows.Forms; namespace ReciPro { public partial class FormResolution : Form { public FormResolution() => InitializeComponent(); private bool SkipEvent = false; private void numericUpDownWidth_ValueChanged(object sender, EventArgs e) { if (SkipEvent) return; SkipEvent = true; if (checkBoxKeepAspect.Checked) numericUpDownHeight.Value = numericUpDownWidth.Value; SkipEvent = false; } private void numericUpDownHeight_ValueChanged(object sender, EventArgs e) { if (SkipEvent) return; SkipEvent = true; if (checkBoxKeepAspect.Checked) numericUpDownWidth.Value = numericUpDownHeight.Value; SkipEvent = false; } } }
28.233333
81
0.608028
[ "MIT" ]
seto77/ReciPro
ReciPro/StructureViewer/FormResolution.cs
847
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. #if REGISTRY_ASSEMBLY using Microsoft.Win32.SafeHandles; #else using Internal.Win32.SafeHandles; #endif using System; using System.Runtime.InteropServices; using System.Text; internal partial class Interop { internal partial class Advapi32 { [DllImport(Libraries.Advapi32, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegEnumKeyExW")] internal static extern unsafe int RegEnumKeyEx( SafeRegistryHandle hKey, int dwIndex, char[] lpName, ref int lpcbName, int[] lpReserved, [Out]StringBuilder lpClass, int[] lpcbClass, long[] lpftLastWriteTime); } }
29.9
120
0.682274
[ "MIT" ]
Adam25T/corefx
src/Common/src/CoreLib/Interop/Windows/Advapi32/Interop.RegEnumKeyEx.cs
897
C#
using System; 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("Samotorcan.HtmlUi.Core")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Samotorcan.HtmlUi.Core")] [assembly: AssemblyCopyright("Copyright © 2015")] [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)] [assembly: CLSCompliant(true)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("5eb47dd2-24bf-46e3-b471-fd20a2425f39")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: InternalsVisibleTo("Samotorcan.HtmlUi.WindowsForms, PublicKey=00240000048000009400000006020000002400005253413100040000010001003b32dbc9bef3fe21acfb27f9f8165bb08b4c001dd41d23b77a87d2f9b04bc5f6d6036e44fb301cbd47ead7bccc71de9993e25da9f11c9833102554e5990cc3da0602fb90717466c88c4b6135364373fd06e566d29505386bb41c2472de6838107dc58d9e93b7ef8715bcfd999fe898499075c1bfbfe2855c097df13574c0cf9b")] [assembly: InternalsVisibleTo("Samotorcan.HtmlUi.Windows, PublicKey=00240000048000009400000006020000002400005253413100040000010001003b32dbc9bef3fe21acfb27f9f8165bb08b4c001dd41d23b77a87d2f9b04bc5f6d6036e44fb301cbd47ead7bccc71de9993e25da9f11c9833102554e5990cc3da0602fb90717466c88c4b6135364373fd06e566d29505386bb41c2472de6838107dc58d9e93b7ef8715bcfd999fe898499075c1bfbfe2855c097df13574c0cf9b")] [assembly: InternalsVisibleTo("Samotorcan.HtmlUi.Linux, PublicKey=00240000048000009400000006020000002400005253413100040000010001003b32dbc9bef3fe21acfb27f9f8165bb08b4c001dd41d23b77a87d2f9b04bc5f6d6036e44fb301cbd47ead7bccc71de9993e25da9f11c9833102554e5990cc3da0602fb90717466c88c4b6135364373fd06e566d29505386bb41c2472de6838107dc58d9e93b7ef8715bcfd999fe898499075c1bfbfe2855c097df13574c0cf9b")]
62.880952
396
0.843998
[ "MIT" ]
Samotorcan/Html.Ui
src/Samotorcan.HtmlUi.Core/Properties/AssemblyInfo.cs
2,644
C#
using CoinBot.Clients.Binance; using CoinBot.Clients.Bittrex; using CoinBot.Clients.FunFair; using CoinBot.Clients.GateIo; using CoinBot.Clients.Gdax; using CoinBot.Clients.Kraken; using CoinBot.Clients.Poloniex; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace CoinBot.Clients.Extensions; /// <summary> /// <see cref="IServiceCollection" /> extension methods. /// </summary> public static class ServiceCollectionExtensions { /// <summary> /// Adds coin sources to the <paramref name="services" />. /// </summary> /// <param name="services">The <see cref="IServiceCollection" />.</param> /// <param name="configurationRoot">Configuration</param> /// <returns></returns> public static IServiceCollection AddClients(this IServiceCollection services, IConfigurationRoot configurationRoot) { #if NOT_DEPRECATED // currently returning errors CoinMarketCapClient.Register(services); #endif BinanceClient.Register(services); BittrexClient.Register(services); GdaxClient.Register(services); GateIoClient.Register(services); KrakenClient.Register(services); PoloniexClient.Register(services); FunFairClientBase.Register(services: services, configurationRoot.GetSection(key: "Sources:FunFair") .Get<FunFairClientConfiguration>()); return services; } }
35.255814
119
0.682718
[ "MIT" ]
funfair-tech/CoinBot
src/CoinBot.Clients/Extensions/ServiceCollectionExtensions.cs
1,518
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Model.DTOs { public class RegisterDto { [Required] public string Username { get; set; } [Required] [StringLength(8, MinimumLength = 4)] public string Password { get; set; } } }
21.157895
44
0.671642
[ "MIT" ]
dbaker731/SwipeRight
Backend/Model/DTOs/RegisterDto.cs
404
C#
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("AWSSDK.SagemakerEdgeManager")] [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - Amazon Sagemaker Edge Manager. Amazon SageMaker Edge Manager makes it easy to optimize, secure, monitor, and maintain machine learning (ML) models across fleets of edge devices such as smart cameras, smart speakers, and robots.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Amazon Web Services SDK for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [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)] // 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("3.3")] [assembly: AssemblyFileVersion("3.7.0.17")]
49.4375
308
0.754109
[ "Apache-2.0" ]
KenHundley/aws-sdk-net
sdk/code-analysis/ServiceAnalysis/SagemakerEdgeManager/Properties/AssemblyInfo.cs
1,582
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 rds-2014-10-31.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.RDS.Model { /// <summary> /// <code>BacktrackIdentifier</code> doesn't refer to an existing backtrack. /// </summary> #if !NETSTANDARD [Serializable] #endif public partial class DBClusterBacktrackNotFoundException : AmazonRDSException { /// <summary> /// Constructs a new DBClusterBacktrackNotFoundException with the specified error /// message. /// </summary> /// <param name="message"> /// Describes the error encountered. /// </param> public DBClusterBacktrackNotFoundException(string message) : base(message) {} /// <summary> /// Construct instance of DBClusterBacktrackNotFoundException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> public DBClusterBacktrackNotFoundException(string message, Exception innerException) : base(message, innerException) {} /// <summary> /// Construct instance of DBClusterBacktrackNotFoundException /// </summary> /// <param name="innerException"></param> public DBClusterBacktrackNotFoundException(Exception innerException) : base(innerException) {} /// <summary> /// Construct instance of DBClusterBacktrackNotFoundException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public DBClusterBacktrackNotFoundException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, innerException, errorType, errorCode, requestId, statusCode) {} /// <summary> /// Construct instance of DBClusterBacktrackNotFoundException /// </summary> /// <param name="message"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public DBClusterBacktrackNotFoundException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, errorType, errorCode, requestId, statusCode) {} #if !NETSTANDARD /// <summary> /// Constructs a new instance of the DBClusterBacktrackNotFoundException class with serialized data. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception> /// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception> protected DBClusterBacktrackNotFoundException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } /// <summary> /// Sets the <see cref="T:System.Runtime.Serialization.SerializationInfo" /> with information about the exception. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is a null reference (Nothing in Visual Basic). </exception> #if BCL35 [System.Security.Permissions.SecurityPermission( System.Security.Permissions.SecurityAction.LinkDemand, Flags = System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)] #endif [System.Security.SecurityCritical] // These FxCop rules are giving false-positives for this method [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2134:MethodsMustOverrideWithConsistentTransparencyFxCopRule")] public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { base.GetObjectData(info, context); } #endif } }
48.201613
178
0.686967
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/RDS/Generated/Model/DBClusterBacktrackNotFoundException.cs
5,977
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class GameLevel { [HideInInspector] public GameObject enemyObj; [HideInInspector] public GameObject playerObj; [HideInInspector] public GameObject playerHealthBar; [HideInInspector] public GameObject enemyHealthBar; [HideInInspector] public Text comboCount; Slider enemyHealthSlider; Slider playerHealthSlider; Player player; Enemy enemy; EnemyInfo levelInfo; SpriteRenderer backGround; public bool levelLoaded = false; public int LevelNum = 0; private Vector2 playerPos = new Vector2(-0.5f, -3.5f); private Vector2 enemyPos = new Vector2(1.5f, 0.5f); int combo = 0; public GameLevel(EnemyInfo enemyInfo) { levelInfo = enemyInfo; } public void initLevel() { levelLoaded = true; backGround = GameObject.FindGameObjectWithTag("Background").GetComponent<SpriteRenderer>(); enemyObj = GameObject.FindGameObjectWithTag("Enemy"); playerObj = GameObject.FindGameObjectWithTag("Player"); playerHealthBar = GameObject.FindGameObjectWithTag("PlayerHealth"); enemyHealthBar = GameObject.FindGameObjectWithTag("EnemyHealth"); comboCount = GameObject.FindGameObjectWithTag("Combo").GetComponent<Text>(); playerHealthSlider = playerHealthBar.GetComponentInChildren<Slider>(); enemyHealthSlider = enemyHealthBar.GetComponentInChildren<Slider>(); enemy = enemyObj.GetComponent<Enemy>(); enemy.enemyInfo = levelInfo; backGround.sprite = levelInfo.BackgroundSprite; player = playerObj.GetComponent<Player>(); playerHealthSlider.value = player.health; enemyHealthSlider.value = enemy.health; playerHealthSlider.maxValue = player.maxHealth; enemyHealthSlider.maxValue = levelInfo.Health; player.InitPlayer(); enemy.InitEnemy(); } public void Update() { playerHealthSlider.value = player.health; enemyHealthSlider.value = enemy.health; combo = player.GetCombo(); comboCount.text = "X" + combo; } }
29.932432
99
0.689842
[ "MIT" ]
ashpemb/KnightOut
Assets/Scripts/GameLevel.cs
2,217
C#
namespace WizMail.Services.Models.Email { using System; using System.Collections.Generic; using WizMail.Common.AutoMapping; using WizMail.Models; public class MailBoxItemServiceModel : IMapWith<Email> { public int Id { get; set; } public string Title { get; set; } public string Message { get; set; } public string Attachment { get; set; } public DateTime SendDate { get; set; } public string SenderEmailAddress { get; set; } public Flag Flag { get; set; } //public ICollection<UserEmail> Recipients { get; set; } } }
24.111111
64
0.596006
[ "MIT" ]
msotiroff/Softuni-learning
C# Web Module/CSharp-Web-Development-Basics/ExamPreparations/Exam_09.05.2017_WizMail/WizMail/WizMail.Services/Models/Email/MailBoxItemServiceModel.cs
653
C#
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Design; using Microsoft.Extensions.Configuration; using Simple.Todo.Configuration; using Simple.Todo.Web; namespace Simple.Todo.EntityFrameworkCore { /* This class is needed to run "dotnet ef ..." commands from command line on development. Not used anywhere else */ public class TodoDbContextFactory : IDesignTimeDbContextFactory<TodoDbContext> { public TodoDbContext CreateDbContext(string[] args) { var builder = new DbContextOptionsBuilder<TodoDbContext>(); var configuration = AppConfigurations.Get(WebContentDirectoryFinder.CalculateContentRootFolder()); TodoDbContextConfigurer.Configure(builder, configuration.GetConnectionString(TodoConsts.ConnectionStringName)); return new TodoDbContext(builder.Options); } } }
38.521739
123
0.751693
[ "MIT" ]
Conlog-hub/Simple.Todo
aspnet-core/src/Simple.Todo.EntityFrameworkCore/EntityFrameworkCore/TodoDbContextFactory.cs
888
C#
using System; using Xunit; namespace Harmony.Tests.Common { public class UnitTest1 { [Fact] public void Test1() { } } }
12
31
0.483333
[ "MIT" ]
cshunk/TimeSeriesAccumulatorWithStats
Harmony.Tests.Common/UnitTest1.cs
180
C#
using System; using System.Security.Cryptography.X509Certificates; using ceenq.com.AzureManagement.Models; using ceenq.com.Core.Accounts; using ceenq.com.Core.Infrastructure.Database; using Microsoft.Azure; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.Management.Sql; using Orchard; using Orchard.ContentManagement; using Orchard.Environment.Extensions; using Orchard.UI.Notify; namespace ceenq.com.AzureManagement.Services { [OrchardSuppressDependency("ceenq.com.Core.Infrastructure.Database.DefaultDatabaseManagement")] public class SqlServerManagement :Component, IDatabaseManagement { private readonly INotifier _notifier; public SqlServerManagement(INotifier notifier) { _notifier = notifier; } public DatabaseInfo Create(DatabaseCreateParameters parameters) { var account = parameters.Account; var azureSettings = account.As<AzureSettingsPart>(); var cloudCredentials = new CertificateCloudCredentials(azureSettings.SubscriptionId, new X509Certificate2(Convert.FromBase64String(azureSettings.Base64EncodedCertificate))); var sqlManagementClient = new SqlManagementClient(cloudCredentials); try { sqlManagementClient.Databases.Create(azureSettings.SqlServerDatabaseName, new Microsoft.WindowsAzure.Management.Sql.Models.DatabaseCreateParameters() { CollationName = azureSettings.SqlServerDatabaseCollation, Edition = azureSettings.SqlServerDatabaseEdition, MaximumDatabaseSizeInGB = azureSettings.SqlServerDatabaseMaximumSizeInGb, Name = account.Name }); } catch (Exception ex) { _notifier.Error(T("Sql Server Database could not be created. {0}",ex.Message)); throw new OrchardFatalException(T("Sql Server Database could not be created. {0}", ex.Message),ex); } var connectionString = string.Format( "Server=tcp:{0}.{2},{3};Database={1};User ID={4}@{0};Password={5};Trusted_Connection=False;Encrypt=True;Connection Timeout={6};" , azureSettings.SqlServerDatabaseName //server name , account.Name , azureSettings.SqlServerDomain , azureSettings.SqlServerPort , azureSettings.SqlServerDatabaseUsername , azureSettings.SqlServerDatabasePassword , azureSettings.SqlServerDatabaseConnectionTimeout); return new DatabaseInfo {ConnectionString = connectionString}; } } }
42.439394
185
0.651196
[ "BSD-3-Clause" ]
bill-cooper/catc-cms
src/Orchard.Web/Modules/ceenq.com.AzureManagement/Services/SqlServerManagement.cs
2,803
C#
using ManahostManager.Domain.DAL; using ManahostManager.Domain.Entity; namespace ManahostManager.Domain.Repository { public interface IFieldGroupRepository : IAbstractRepository<FieldGroup> { FieldGroup GetFieldGroupById(int id, int clientId); } public class FieldGroupRepository : AbstractRepository<FieldGroup>, IFieldGroupRepository { public FieldGroupRepository(ManahostManagerDAL ctx) : base(ctx) { } public FieldGroup GetFieldGroupById(int id, int clientId) { return GetUniq(p => p.Id == id && p.Home.ClientId == clientId); } } }
28.863636
93
0.680315
[ "MIT" ]
charla-n/ManahostManager
ManahostManager.Domain/Repository/FieldGroupRepository.cs
637
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.VR.WSA; using HoloToolkit.Unity.SpatialMapping; namespace HoloToolkit.Unity { /// <summary> /// Handles the custom meshes generated by the understanding dll. The meshes /// are generated during the scanning phase and once more on scan finalization. /// The meshes can be used to visualize the scanning progress. /// </summary> public class SpatialUnderstandingCustomMesh : SpatialMappingSource { // Config [Tooltip("Indicate the time in seconds between mesh imports, during the scanning phase. A value of zero will disable pulling meshes from the dll")] public float ImportMeshPeriod = 1.0f; [Tooltip("Material used to render the custom mesh generated by the dll")] public Material MeshMaterial; /// <summary> /// Used to keep our processing from exceeding our frame budget. /// </summary> [Tooltip("Max time per frame in milliseconds to spend processing the mesh")] public float MaxFrameTime = 5.0f; private float MaxFrameTimeInSeconds { get { return (MaxFrameTime / 1000); } } /// <summary> /// Whether to create mesh colliders. If unchecked, mesh colliders will be empty and disabled. /// </summary> public bool CreateMeshColliders = true; private bool drawProcessedMesh = true; // Properties /// <summary> /// Controls rendering of the mesh. This can be set by the user to hide or show the mesh. /// </summary> public bool DrawProcessedMesh { get { return drawProcessedMesh; } set { drawProcessedMesh = value; for (int i = 0; i < SurfaceObjects.Count; ++i) { SurfaceObjects[i].Renderer.enabled = drawProcessedMesh; } } } /// <summary> /// Indicates if the previous import is still being processed. /// </summary> public bool IsImportActive { get; private set; } /// <summary> /// The material to use if rendering. /// </summary> protected override Material RenderMaterial { get { return MeshMaterial; } } /// <summary> /// To prevent us from importing too often, we keep track of the last import. /// </summary> private float timeLastImportedMesh = 0; /// <summary> /// For a cached SpatialUnderstanding.Instance. /// </summary> private SpatialUnderstanding spatialUnderstanding; /// <summary> /// The spatial understanding mesh will be split into pieces so that we don't have to /// render the whole mesh, rather just the parts that are visible to the user. /// </summary> private Dictionary<Vector3, MeshData> meshSectors = new Dictionary<Vector3, MeshData>(); /// <summary> /// A data structure to manage collecting triangles as we /// subdivide the spatial understanding mesh into smaller sub meshes. /// </summary> private class MeshData { /// <summary> /// Lists of verts/triangles that describe the mesh geometry. /// </summary> private readonly List<Vector3> verts = new List<Vector3>(); private readonly List<int> tris = new List<int>(); /// <summary> /// The mesh object based on the triangles passed in. /// </summary> public readonly Mesh MeshObject = new Mesh(); /// <summary> /// The MeshCollider with which this mesh is associated. Must be set even if /// no collision mesh will be created. /// </summary> public MeshCollider SpatialCollider = null; /// <summary> /// Whether to create collision mesh. If false, the MeshCollider attached to this /// object will also be disabled when Commit() is called. /// </summary> public bool CreateMeshCollider = false; /// <summary> /// Clears the geometry, but does not clear the mesh. /// </summary> public void Reset() { verts.Clear(); tris.Clear(); } /// <summary> /// Commits the new geometry to the mesh. /// </summary> public void Commit() { MeshObject.Clear(); if (verts.Count > 2) { MeshObject.SetVertices(verts); MeshObject.SetTriangles(tris, 0); MeshObject.RecalculateNormals(); MeshObject.RecalculateBounds(); // The null assignment is required by Unity in order to pick up the new mesh SpatialCollider.sharedMesh = null; if (CreateMeshCollider) { SpatialCollider.sharedMesh = MeshObject; SpatialCollider.enabled = true; } else { SpatialCollider.enabled = false; } } } /// <summary> /// Adds a triangle composed of the specified three points to our mesh. /// </summary> /// <param name="point1">First point on the triangle.</param> /// <param name="point2">Second point on the triangle.</param> /// <param name="point3">Third point on the triangle.</param> public void AddTriangle(Vector3 point1, Vector3 point2, Vector3 point3) { // Currently spatial understanding in the native layer voxellizes the space // into ~2000 voxels per cubic meter. Even in a degerate case we // will use far fewer than 65000 vertices, this check should not fail // unless the spatial understanding native layer is updated to have more // voxels per cubic meter. if (verts.Count < 65000) { tris.Add(verts.Count); verts.Add(point1); tris.Add(verts.Count); verts.Add(point2); tris.Add(verts.Count); verts.Add(point3); } else { Debug.LogError("Mesh would have more vertices than Unity supports"); } } } private void Start() { spatialUnderstanding = SpatialUnderstanding.Instance; if (gameObject.GetComponent<WorldAnchor>() == null) { gameObject.AddComponent<WorldAnchor>(); } } private void Update() { Update_MeshImport(); } /// <summary> /// Adds a triangle with the specified points to the specified sector. /// </summary> /// <param name="sector">The sector to add the triangle to.</param> /// <param name="point1">First point of the triangle.</param> /// <param name="point2">Second point of the triangle.</param> /// <param name="point3">Third point of the triangle.</param> private void AddTriangleToSector(Vector3 sector, Vector3 point1, Vector3 point2, Vector3 point3) { // Grab the mesh container we are using for this sector. MeshData nextSectorData; if (!meshSectors.TryGetValue(sector, out nextSectorData)) { nextSectorData = new MeshData(); nextSectorData.CreateMeshCollider = CreateMeshColliders; int surfaceObjectIndex = SurfaceObjects.Count; SurfaceObject surfaceObject = CreateSurfaceObject( mesh: nextSectorData.MeshObject, objectName: string.Format("SurfaceUnderstanding Mesh-{0}", surfaceObjectIndex), parentObject: transform, meshID: surfaceObjectIndex, drawVisualMeshesOverride: DrawProcessedMesh); nextSectorData.SpatialCollider = surfaceObject.Collider; AddSurfaceObject(surfaceObject); // Or make it if this is a new sector. meshSectors.Add(sector, nextSectorData); } // Add the vertices to the sector's mesh container. nextSectorData.AddTriangle(point1, point2, point3); } /// <summary> /// Imports the custom mesh from the dll. This a a coroutine which will take multiple frames to complete. /// </summary> /// <returns></returns> public IEnumerator Import_UnderstandingMesh() { var stopwatch = System.Diagnostics.Stopwatch.StartNew(); int startFrameCount = Time.frameCount; if (!spatialUnderstanding.AllowSpatialUnderstanding || IsImportActive) { yield break; } IsImportActive = true; SpatialUnderstandingDll dll = spatialUnderstanding.UnderstandingDLL; Vector3[] meshVertices = null; Vector3[] meshNormals = null; Int32[] meshIndices = null; // Pull the mesh - first get the size, then allocate and pull the data int vertCount; int idxCount; if ((SpatialUnderstandingDll.Imports.GeneratePlayspace_ExtractMesh_Setup(out vertCount, out idxCount) > 0) && (vertCount > 0) && (idxCount > 0)) { meshVertices = new Vector3[vertCount]; IntPtr vertPos = dll.PinObject(meshVertices); meshNormals = new Vector3[vertCount]; IntPtr vertNorm = dll.PinObject(meshNormals); meshIndices = new Int32[idxCount]; IntPtr indices = dll.PinObject(meshIndices); SpatialUnderstandingDll.Imports.GeneratePlayspace_ExtractMesh_Extract(vertCount, vertPos, vertNorm, idxCount, indices); } // Wait a frame stopwatch.Stop(); yield return null; stopwatch.Start(); // Create output meshes if ((meshVertices != null) && (meshVertices.Length > 0) && (meshIndices != null) && (meshIndices.Length > 0)) { // first get all our mesh data containers ready for meshes. foreach (MeshData meshdata in meshSectors.Values) { meshdata.Reset(); } float startTime = Time.realtimeSinceStartup; // first we need to split the playspace up into segments so we don't always // draw everything. We can break things up in to cubic meters. for (int index = 0; index < meshIndices.Length; index += 3) { Vector3 firstVertex = meshVertices[meshIndices[index]]; Vector3 secondVertex = meshVertices[meshIndices[index + 1]]; Vector3 thirdVertex = meshVertices[meshIndices[index + 2]]; // The triangle may belong to multiple sectors. We will copy the whole triangle // to all of the sectors it belongs to. This will fill in seams on sector edges // although it could cause some amount of visible z-fighting if rendering a wireframe. Vector3 firstSector = VectorToSector(firstVertex); AddTriangleToSector(firstSector, firstVertex, secondVertex, thirdVertex); // If the second sector doesn't match the first, copy the triangle to the second sector. Vector3 secondSector = VectorToSector(secondVertex); if (secondSector != firstSector) { AddTriangleToSector(secondSector, firstVertex, secondVertex, thirdVertex); } // If the third sector matches neither the first nor second sector, copy the triangle to the // third sector. Vector3 thirdSector = VectorToSector(thirdVertex); if (thirdSector != firstSector && thirdSector != secondSector) { AddTriangleToSector(thirdSector, firstVertex, secondVertex, thirdVertex); } // Limit our run time so that we don't cause too many frame drops. // Only checking every few iterations or so to prevent losing too much time to checking the clock. if ((index % 30 == 0) && ((Time.realtimeSinceStartup - startTime) > MaxFrameTimeInSeconds)) { // Debug.LogFormat("{0} of {1} processed", index, meshIndices.Length); stopwatch.Stop(); yield return null; stopwatch.Start(); startTime = Time.realtimeSinceStartup; } } startTime = Time.realtimeSinceStartup; // Now we have all of our triangles assigned to the correct mesh, we can make all of the meshes. // Each sector will have its own mesh. foreach (MeshData meshData in meshSectors.Values) { // Construct the mesh. meshData.Commit(); // Make sure we don't build too many meshes in a single frame. if ((Time.realtimeSinceStartup - startTime) > MaxFrameTimeInSeconds) { stopwatch.Stop(); yield return null; stopwatch.Start(); startTime = Time.realtimeSinceStartup; } } } // Wait a frame stopwatch.Stop(); yield return null; stopwatch.Start(); // All done - can free up marshal pinned memory dll.UnpinAllObjects(); // Done IsImportActive = false; // Mark the timestamp timeLastImportedMesh = Time.time; stopwatch.Stop(); int deltaFrameCount = (Time.frameCount - startFrameCount + 1); if (stopwatch.Elapsed.TotalSeconds > 0.75) { Debug.LogWarningFormat("Import_UnderstandingMesh took {0:N0} frames ({1:N3} ms)", deltaFrameCount, stopwatch.Elapsed.TotalMilliseconds ); } } /// <summary> /// Basically floors the Vector so we can use it to subdivide our spatial understanding mesh into parts based /// on their position in the world. /// </summary> /// <param name="vector">The vector to floor.</param> /// <returns>A floored vector</returns> private Vector3 VectorToSector(Vector3 vector) { return new Vector3(Mathf.FloorToInt(vector.x), Mathf.FloorToInt(vector.y), Mathf.FloorToInt(vector.z)); } /// <summary> /// Updates the mesh import process. This function will kick off the import /// coroutine at the requested internal. /// </summary> private void Update_MeshImport() { // Only update every so often if (IsImportActive || (ImportMeshPeriod <= 0.0f) || ((Time.time - timeLastImportedMesh) < ImportMeshPeriod) || (spatialUnderstanding.ScanState != SpatialUnderstanding.ScanStates.Scanning)) { return; } StartCoroutine(Import_UnderstandingMesh()); } private void OnDestroy() { Cleanup(); } } }
39.869565
155
0.543075
[ "MIT" ]
AmrARaouf/WDM-hololens
WoundManagementUnity/WoundManagement/Assets/HoloToolkit/SpatialUnderstanding/Scripts/SpatialUnderstandingCustomMesh.cs
16,508
C#
// This software is part of the IoC.Configuration library // Copyright © 2018 IoC.Configuration Contributors // http://oroptimizer.com // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. namespace IoC.Configuration { public static class HelpersIoC { // TODO: Add an element Version to configuration file and use to convert to latest version. // Will do in next version of IoC.Configuration that will introduce changes to configuration file. public const string ConfigurationFileVersion = "7579ADB2-0FBD-4210-A8CA-EE4B4646DB3F"; public const string IoCConfigurationSchemaName = "IoC.Configuration.Schema." + ConfigurationFileVersion + ".xsd"; public const string OnDiContainerReadyMethodName = "OnDiContainerReady"; } }
50.138889
121
0.755125
[ "MIT" ]
artakhak/IoC.Configuration
IoC.Configuration/HelpersIoC.cs
1,808
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Lab_8.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.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; } } } }
34.193548
151
0.579245
[ "MIT" ]
GoonerMAK/SWE_4202_OOC-I
Lab_8/Properties/Settings.Designer.cs
1,062
C#
// <auto-generated> This file has been auto generated by EF Core Power Tools. </auto-generated> using System; using System.Collections.Generic; #nullable disable namespace T0002.Models { public partial class MoDepartment { public string Id { get; set; } public string DepartmentName { get; set; } public string DepartmentDescription { get; set; } public string Status { get; set; } public string CreateOwner { get; set; } public DateTime? CreateTime { get; set; } } }
30.388889
97
0.641682
[ "MIT" ]
twoutlook/BlazorServerDbContextExample
BlazorServerEFCoreSample/T0002/Models/MoDepartment.cs
549
C#
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using Simple.OData.Client.Extensions; namespace Simple.OData.Client { /// <summary> /// Provides access to OData operations in a fluent style. /// </summary> /// <typeparam name="T">The entity type.</typeparam> public abstract partial class FluentClientBase<T, FT> : IFluentClient<T, FT> where T : class where FT : class { #pragma warning disable 1591 protected readonly ODataClient _client; internal readonly Session _session; protected readonly FluentCommand _parentCommand; protected FluentCommand _command; protected readonly bool _dynamicResults; internal FluentClientBase(ODataClient client, Session session, FluentCommand parentCommand = null, FluentCommand command = null, bool dynamicResults = false) { _client = client; _session = session; _parentCommand = parentCommand; _command = command; _dynamicResults = dynamicResults; } internal FluentCommand Command { get { if (_command != null) return _command; lock (this) { return _command ?? (_command = CreateCommand()); } } } protected FluentCommand CreateCommand() { return new FluentCommand(this.Session, _parentCommand, _client.BatchEntries); } internal Session Session { get { return _session; } } public FT WithProperties(Expression<Func<T, IDictionary<string, object>>> expression) { this.Command.WithProperties(ColumnExpression.ExtractColumnName(expression)); return this as FT; } public FT WithMedia(IEnumerable<string> properties) { this.Command.WithMedia(properties); return this as FT; } public FT WithMedia(params string[] properties) { this.Command.WithMedia(properties); return this as FT; } public FT WithMedia(params ODataExpression[] properties) { this.Command.WithMedia(properties); return this as FT; } public FT WithMedia(Expression<Func<T, object>> expression) { this.Command.WithMedia(ColumnExpression.ExtractColumnNames(expression)); return this as FT; } public FT Key(params object[] entryKey) { this.Command.Key(entryKey); return this as FT; } public FT Key(IEnumerable<object> entryKey) { this.Command.Key(entryKey); return this as FT; } public FT Key(IDictionary<string, object> entryKey) { this.Command.Key(entryKey); return this as FT; } public FT Key(T entryKey) { this.Command.Key(entryKey.ToDictionary()); return this as FT; } public FT Filter(string filter) { this.Command.Filter(filter); return this as FT; } public FT Filter(ODataExpression expression) { this.Command.Filter(expression); return this as FT; } public FT Filter(Expression<Func<T, bool>> expression) { this.Command.Filter(ODataExpression.FromLinqExpression(expression.Body)); return this as FT; } public FT Search(string search) { this.Command.Search(search); return this as FT; } public FT Function(string functionName) { this.Command.Function(functionName); return this as FT; } public FT Action(string actionName) { this.Command.Action(actionName); return this as FT; } public FT Skip(long count) { this.Command.Skip(count); return this as FT; } public FT Top(long count) { this.Command.Top(count); return this as FT; } public FT Expand(ODataExpandOptions expandOptions) { this.Command.Expand(expandOptions); return this as FT; } public FT Expand(IEnumerable<string> associations) { this.Command.Expand(associations); return this as FT; } public FT Expand(ODataExpandOptions expandOptions, IEnumerable<string> associations) { this.Command.Expand(expandOptions, associations); return this as FT; } public FT Expand(params string[] associations) { this.Command.Expand(associations); return this as FT; } public FT Expand(ODataExpandOptions expandOptions, params string[] associations) { this.Command.Expand(expandOptions, associations); return this as FT; } public FT Expand(params ODataExpression[] associations) { this.Command.Expand(associations); return this as FT; } public FT Expand(ODataExpandOptions expandOptions, params ODataExpression[] associations) { this.Command.Expand(expandOptions, associations); return this as FT; } public FT Expand(Expression<Func<T, object>> expression) { this.Command.Expand(ColumnExpression.ExtractColumnNames(expression)); return this as FT; } public FT Expand(ODataExpandOptions expandOptions, Expression<Func<T, object>> expression) { this.Command.Expand(expandOptions, ColumnExpression.ExtractColumnNames(expression)); return this as FT; } public FT Select(IEnumerable<string> columns) { this.Command.Select(columns); return this as FT; } public FT Select(params string[] columns) { this.Command.Select(columns); return this as FT; } public FT Select(params ODataExpression[] columns) { this.Command.Select(columns); return this as FT; } public FT Select(Expression<Func<T, object>> expression) { this.Command.Select(ColumnExpression.ExtractColumnNames(expression)); return this as FT; } public FT OrderBy(IEnumerable<KeyValuePair<string, bool>> columns) { this.Command.OrderBy(columns); return this as FT; } public FT OrderBy(params string[] columns) { this.Command.OrderBy(columns); return this as FT; } public FT OrderBy(params ODataExpression[] columns) { this.Command.OrderBy(columns); return this as FT; } public FT OrderBy(Expression<Func<T, object>> expression) { this.Command.OrderBy(ColumnExpression.ExtractColumnNames(expression).Select(x => new KeyValuePair<string, bool>(x, false))); return this as FT; } public FT ThenBy(params ODataExpression[] columns) { this.Command.ThenBy(columns); return this as FT; } public FT ThenBy(Expression<Func<T, object>> expression) { this.Command.ThenBy(ColumnExpression.ExtractColumnNames(expression).ToArray()); return this as FT; } public FT OrderByDescending(params string[] columns) { this.Command.OrderByDescending(columns); return this as FT; } public FT OrderByDescending(params ODataExpression[] columns) { this.Command.OrderByDescending(columns); return this as FT; } public FT OrderByDescending(Expression<Func<T, object>> expression) { this.Command.OrderBy(ColumnExpression.ExtractColumnNames(expression).Select(x => new KeyValuePair<string, bool>(x, true))); return this as FT; } public FT ThenByDescending(params ODataExpression[] columns) { this.Command.ThenByDescending(columns); return this as FT; } public FT ThenByDescending(Expression<Func<T, object>> expression) { this.Command.ThenByDescending(ColumnExpression.ExtractColumnNames(expression).ToArray()); return this as FT; } public FT QueryOptions(string queryOptions) { this.Command.QueryOptions(queryOptions); return this as FT; } public FT QueryOptions(IDictionary<string, object> queryOptions) { this.Command.QueryOptions(queryOptions); return this as FT; } public FT QueryOptions(ODataExpression expression) { this.Command.QueryOptions(expression); return this as FT; } public FT QueryOptions<U>(Expression<Func<U, bool>> expression) { this.Command.QueryOptions(ODataExpression.FromLinqExpression(expression.Body)); return this as FT; } public IMediaClient Media() { this.Command.Media(); return new MediaClient(_client, _session, this.Command, _dynamicResults); } public IMediaClient Media(string streamName) { this.Command.Media(streamName); return new MediaClient(_client, _session, this.Command, _dynamicResults); } public IMediaClient Media(ODataExpression expression) { this.Command.Media(expression); return new MediaClient(_client, _session, this.Command, _dynamicResults); } public IMediaClient Media(Expression<Func<T, object>> expression) { this.Command.Media(ColumnExpression.ExtractColumnName(expression)); return new MediaClient(_client, _session, this.Command, _dynamicResults); } public FT Count() { this.Command.Count(); return this as FT; } protected BoundClient<U> Link<U>(FluentCommand command, string linkName = null) where U : class { linkName = linkName ?? typeof(U).Name; var links = linkName.Split('/'); var linkCommand = command; BoundClient<U> linkedClient = null; foreach (var link in links) { linkedClient = new BoundClient<U>(_client, _session, linkCommand, null, _dynamicResults); linkedClient.Command.Link(link); linkCommand = linkedClient.Command; } return linkedClient; } protected BoundClient<U> Link<U>(FluentCommand command, ODataExpression expression) where U : class { return Link<U>(command, expression.Reference); } #pragma warning restore 1591 /// <summary> /// Navigates to the linked entity. /// </summary> /// <typeparam name="U">The type of the linked entity.</typeparam> /// <param name="linkName">Name of the link.</param> /// <returns>Self.</returns> public IBoundClient<U> NavigateTo<U>(string linkName = null) where U : class { return this.Link<U>(this.Command, linkName); } /// <summary> /// Navigates to the linked entity. /// </summary> /// <typeparam name="U">The type of the linked entity.</typeparam> /// <param name="expression">The expression for the link.</param> /// <returns>Self.</returns> public IBoundClient<U> NavigateTo<U>(Expression<Func<T, U>> expression) where U : class { return this.Link<U>(this.Command, ColumnExpression.ExtractColumnName(expression)); } /// <summary> /// Navigates to the linked entity. /// </summary> /// <typeparam name="U">The type of the linked entity.</typeparam> /// <param name="expression">The expression for the link.</param> /// <returns>Self.</returns> public IBoundClient<U> NavigateTo<U>(Expression<Func<T, IEnumerable<U>>> expression) where U : class { return this.Link<U>(this.Command, ColumnExpression.ExtractColumnName(expression)); } /// <summary> /// Navigates to the linked entity. /// </summary> /// <typeparam name="U">The type of the linked entity.</typeparam> /// <param name="expression">The expression for the link.</param> /// <returns>Self.</returns> public IBoundClient<U> NavigateTo<U>(Expression<Func<T, IList<U>>> expression) where U : class { return this.Link<U>(this.Command, ColumnExpression.ExtractColumnName(expression)); } /// <summary> /// Navigates to the linked entity. /// </summary> /// <typeparam name="U">The type of the linked entity.</typeparam> /// <param name="expression">The expression for the link.</param> /// <returns>Self.</returns> public IBoundClient<U> NavigateTo<U>(Expression<Func<T, ISet<U>>> expression) where U : class { return this.Link<U>(this.Command, ColumnExpression.ExtractColumnName(expression)); } /// <summary> /// Navigates to the linked entity. /// </summary> /// <typeparam name="U">The type of the linked entity.</typeparam> /// <param name="expression">The expression for the link.</param> /// <returns>Self.</returns> public IBoundClient<U> NavigateTo<U>(Expression<Func<T, HashSet<U>>> expression) where U : class { return this.Link<U>(this.Command, ColumnExpression.ExtractColumnName(expression)); } /// <summary> /// Navigates to the linked entity. /// </summary> /// <typeparam name="U">The type of the linked entity.</typeparam> /// <param name="expression">The expression for the link.</param> /// <returns>Self.</returns> public IBoundClient<U> NavigateTo<U>(Expression<Func<T, U[]>> expression) where U : class { return this.Link<U>(this.Command, ColumnExpression.ExtractColumnName(expression)); } /// <summary> /// Navigates to the linked entity. /// </summary> /// <param name="linkName">Name of the link.</param> /// <returns>Self.</returns> public IBoundClient<IDictionary<string, object>> NavigateTo(string linkName) { return this.Link<IDictionary<string, object>>(this.Command, linkName); } /// <summary> /// Navigates to the linked entity. /// </summary> /// <param name="expression">The expression for the link.</param> /// <returns>Self.</returns> public IBoundClient<T> NavigateTo(ODataExpression expression) { return this.Link<T>(this.Command, expression); } /// <summary> /// Executes the OData function or action. /// </summary> /// <returns>Execution result task.</returns> public Task ExecuteAsync() { return _client.ExecuteAsync(_command, CancellationToken.None); } /// <summary> /// Executes the OData function or action. /// </summary> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>Execution result task.</returns> public Task ExecuteAsync(CancellationToken cancellationToken) { return _client.ExecuteAsync(_command, cancellationToken); } /// <summary> /// Executes the OData function or action and returns a single item. /// </summary> /// <returns>Execution result.</returns> public Task<T> ExecuteAsSingleAsync() { return RectifyColumnSelectionAsync( _client.ExecuteAsSingleAsync(_command, CancellationToken.None), _command.SelectedColumns, _command.DynamicPropertiesContainerName); } /// <summary> /// Executes the OData function or action and returns a single item. /// </summary> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>Execution result.</returns> public Task<T> ExecuteAsSingleAsync(CancellationToken cancellationToken) { return RectifyColumnSelectionAsync( _client.ExecuteAsSingleAsync(_command, cancellationToken), _command.SelectedColumns, _command.DynamicPropertiesContainerName); } /// <summary> /// Executes the OData function or action and returns enumerable result. /// </summary> /// <returns>Execution result.</returns> public Task<IEnumerable<T>> ExecuteAsEnumerableAsync() { return RectifyColumnSelectionAsync( _client.ExecuteAsEnumerableAsync(_command, CancellationToken.None), _command.SelectedColumns, _command.DynamicPropertiesContainerName); } /// <summary> /// Executes the OData function or action and returns enumerable result. /// </summary> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>Execution result.</returns> public Task<IEnumerable<T>> ExecuteAsEnumerableAsync(CancellationToken cancellationToken) { return RectifyColumnSelectionAsync( _client.ExecuteAsEnumerableAsync(_command, cancellationToken), _command.SelectedColumns, _command.DynamicPropertiesContainerName); } /// <summary> /// Executes the OData function or action and returns scalar result. /// </summary> /// <returns>Execution result.</returns> public Task<U> ExecuteAsScalarAsync<U>() { return _client.ExecuteAsScalarAsync<U>(_command, CancellationToken.None); } /// <summary> /// Executes the OData function or action and returns scalar result. /// </summary> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>Execution result.</returns> public Task<U> ExecuteAsScalarAsync<U>(CancellationToken cancellationToken) { return _client.ExecuteAsScalarAsync<U>(_command, cancellationToken); } /// <summary> /// Executes the OData function and returns an array. /// </summary> /// <returns>Execution result.</returns> public Task<U[]> ExecuteAsArrayAsync<U>() { return ExecuteAsArrayAsync<U>(CancellationToken.None); } /// <summary> /// Executes the OData function and returns an array. /// </summary> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>Execution result.</returns> public Task<U[]> ExecuteAsArrayAsync<U>(CancellationToken cancellationToken) { return _client.ExecuteAsArrayAsync<U>(_command, cancellationToken); } /// <summary> /// Gets the OData command text. /// </summary> /// <returns>The command text.</returns> public Task<string> GetCommandTextAsync() { return GetCommandTextAsync(CancellationToken.None); } /// <summary> /// Gets the OData command text. /// </summary> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The command text.</returns> public Task<string> GetCommandTextAsync(CancellationToken cancellationToken) { return this.Command.GetCommandTextAsync(cancellationToken); } #pragma warning disable 1591 protected async Task<IEnumerable<T>> RectifyColumnSelectionAsync( Task<IEnumerable<IDictionary<string, object>>> entries, IList<string> selectedColumns, string dynamicPropertiesContainerName) { var result = RectifyColumnSelection(await entries.ConfigureAwait(false), selectedColumns); return result == null ? null : result.Select(z => ConvertResult(z, dynamicPropertiesContainerName)); } protected async Task<T> RectifyColumnSelectionAsync( Task<IDictionary<string, object>> entry, IList<string> selectedColumns, string dynamicPropertiesContainerName) { return ConvertResult(RectifyColumnSelection(await entry.ConfigureAwait(false), selectedColumns), dynamicPropertiesContainerName); } protected async Task<Tuple<IEnumerable<T>, int>> RectifyColumnSelectionAsync( Task<Tuple<IEnumerable<IDictionary<string, object>>, int>> entries, IList<string> selectedColumns, string dynamicPropertiesContainerName) { var result = await entries.ConfigureAwait(false); return new Tuple<IEnumerable<T>, int>( RectifyColumnSelection(result.Item1, selectedColumns).Select(y => ConvertResult(y, dynamicPropertiesContainerName)), result.Item2); } protected static IEnumerable<IDictionary<string, object>> RectifyColumnSelection(IEnumerable<IDictionary<string, object>> entries, IList<string> selectedColumns) { return entries == null ? null : entries.Select(x => RectifyColumnSelection(x, selectedColumns)); } protected static IDictionary<string, object> RectifyColumnSelection(IDictionary<string, object> entry, IList<string> selectedColumns) { if (entry == null || selectedColumns == null || !selectedColumns.Any()) { return entry; } else { return entry.Where(x => selectedColumns.Any(y => IsSelectedColumn(x, y))).ToIDictionary(); } } private T ConvertResult(IDictionary<string, object> result, string dynamicPropertiesContainerName) { if (result != null && result.Keys.Count == 1 && result.ContainsKey(FluentCommand.ResultLiteral) && typeof(T).IsValue() || typeof(T) == typeof(string) || typeof(T) == typeof(object)) return (T)Utils.Convert(result.Values.First(), typeof(T)); else return result.ToObject<T>(dynamicPropertiesContainerName, _dynamicResults); } private static bool IsSelectedColumn(KeyValuePair<string, object> kv, string columnName) { var items = columnName.Split('/'); if (items.Count() == 1) { return kv.Key.Homogenize() == columnName.Homogenize(); } else { var item = items.First(); return kv.Key.Homogenize() == item.Homogenize() && (kv.Value is IDictionary<string, object> && (kv.Value as IDictionary<string, object>) .Any(x => IsSelectedColumn(x, string.Join("/", items.Skip(1)))) || kv.Value is IEnumerable<object> && (kv.Value as IEnumerable<object>) .Any(x => x is IDictionary<string, object> && (x as IDictionary<string, object>) .Any(y => IsSelectedColumn(y, string.Join("/", items.Skip(1)))))); } } #pragma warning restore 1591 } }
36.069173
169
0.588343
[ "MIT" ]
richardalmonte/Simple.OData.Client
Simple.OData.Client.Core/Fluent/FluentClientBase.cs
23,988
C#
using System; using System.Collections.Generic; using System.Text; public class Hacker { public string username = "securityGod82"; private string password = "mySuperSecretPassw0rd"; public string Password { get => this.password; set => this.password = value; } private int Id { get; set; } public double BankAccountBalance { get; private set; } public void DownloadAllBankAccountsInTheWorld() { } }
17.185185
58
0.659483
[ "MIT" ]
TodorNikolov89/SoftwareUniversity
CSharp_OOP_Advanced/ReflectionAndAttributes_Lab/Stealer/Hacker.cs
466
C#
using System; using System.Collections.Generic; using System.Text; namespace RiskyMod.VoidLocus { public class VoidLocusCore { public static bool enabled = true; public VoidLocusCore() { if (!enabled) return; new RemoveFog(); new ModifyHoldout(); new PillarsDropItems(); } } }
19.526316
42
0.574124
[ "MIT" ]
Moffein/RiskyMod
RiskyMod/VoidLocus/VoidLocusCore.cs
373
C#