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
sequence
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的常规信息通过下列特性集 // 控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("HttpInterface")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("HttpInterface")] [assembly: AssemblyCopyright("版权所有(C) Microsoft 2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 将 ComVisible 设置为 false 会使此程序集中的类型 // 对 COM 组件不可见。如果需要从 COM 访问此程序集中的某个类型, // 请针对该类型将 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("be386164-3402-48a4-9147-19e8fc44a0bb")] // 程序集的版本信息由下列四个值组成: // // 主版本 // 次版本 // 内部版本号 // 修订号 // // 可以指定所有这些值,也可以使用“修订号”和“内部版本号”的默认值, // 方法是按如下所示使用“*”: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
25.861111
56
0.727175
[ "MIT" ]
lfpei/PersonalWeb
PersonalWeb/HttpInterface/Properties/AssemblyInfo.cs
1,311
C#
using Flunt.Notifications; using Flunt.Validations; namespace BaltaStore.Domain.StoreContext.ValueObjects { public class Email : Notifiable { public Email(string address) { Address = address; AddNotifications(new Contract() .Requires() .IsEmail(Address, nameof(Email), "O E-mail é inválido") ); } public string Address { get; private set; } public override string ToString() { return Address; } } }
22.04
71
0.553539
[ "MIT" ]
renebentes/BaltaStore
BaltaStore.Domain/StoreContext/ValueObjects/Email.cs
555
C#
using System.Threading.Tasks; using OrchardCore.ContentManagement.Metadata.Models; using OrchardCore.ContentTypes.Editors; using OrchardCore.DisplayManagement.Views; using OrchardCore.Spatial.Fields; using OrchardCore.Spatial.Settings; namespace OrchardCore.Spatial.Drivers { public class GeoPointFieldSettingsDriver : ContentPartFieldDefinitionDisplayDriver<GeoPointField> { public override IDisplayResult Edit(ContentPartFieldDefinition partFieldDefinition) { return Initialize<GeoPointFieldSettings>("GeoPointFieldSettings_Edit", model => partFieldDefinition.PopulateSettings(model)) .Location("Content"); } public override async Task<IDisplayResult> UpdateAsync(ContentPartFieldDefinition partFieldDefinition, UpdatePartFieldEditorContext context) { var model = new GeoPointFieldSettings(); await context.Updater.TryUpdateModelAsync(model, Prefix); context.Builder.WithSettings(model); return Edit(partFieldDefinition); } } }
35.7
148
0.745098
[ "BSD-3-Clause" ]
CityofSantaMonica/OrchardCore
src/OrchardCore.Modules/OrchardCore.Spatial/Drivers/GeoPointFieldSettingsDriver.cs
1,071
C#
// ChooseKeyProviderForm.cs // Copyright (C) 2018 Kinsey Roberts (@kinzdesign), Weatherhead School of Management (@wsomweb) // MIT License // 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.Windows.Forms; namespace edu.cwru.weatherhead.WebConfigEncrypt { public partial class ChooseKeyProviderForm : Form { public ChooseKeyProviderForm(string prompt, IEnumerable<string> providers) { InitializeComponent(); this.Icon = System.Drawing.Icon.ExtractAssociatedIcon(Application.ExecutablePath); // config label text lblPrompt.Text = prompt; // load drop-down foreach (string provider in providers) cbProviders.Items.Add(provider); } public static string GetKeyProvider(IWin32Window window, string configFilePath, string section, IEnumerable<string> providers) { string prompt = String.Format("Multiple key providers were found in {0}.\r\nPlease choose which provider to use when encrypting {1}.", configFilePath, section); return GetKeyProvider(window, prompt, providers); } public static string GetKeyProvider(IWin32Window window, string prompt, IEnumerable<string> providers) { // build window var form = new ChooseKeyProviderForm(prompt, providers); // show window if (form.ShowDialog(window) == DialogResult.OK) return form.cbProviders.SelectedItem.ToString(); return null; } private void cbProviders_SelectedIndexChanged(object sender, EventArgs e) { // only allow OK button when a provider is selected btnOk.Enabled = !String.IsNullOrEmpty(cbProviders.SelectedItem.ToString()); } private void btnOk_Click(object sender, EventArgs e) { DialogResult = DialogResult.OK; Close(); } private void btnCancel_Click(object sender, EventArgs e) { DialogResult = DialogResult.Cancel; Close(); } } }
39.45679
172
0.682728
[ "MIT" ]
wsomweb/WebConfigEncrypt
WebConfigEncrypt/ChooseKeyProviderForm.cs
3,198
C#
using System; using UnityEngine; namespace WizardsCode.Controller { /// <summary> /// Camera Controller interface used to ensure that camera controllers are interchangeable across /// proejects. Pull all common method descriptors up into this interface to make them available /// across all camera controllers (which should always inmplement this interface). /// </summary> [Serializable] public abstract class AbstractCameraController : MonoBehaviour { GameObject desiredCameraPosition; protected virtual void Awake() { desiredCameraPosition = new GameObject("Set Camera Position"); desiredCameraPosition.SetActive(false); } /// <summary> /// Position the camera so that it is looking at a given game object. /// The camera will attempt to position itself so that it has a good angle /// on the target. For more precise positioning of th camers see /// SetPosition(transform). /// </summary> /// <param name="target">The transform to look at.</param> public virtual void LookAt(Transform target) { desiredCameraPosition.SetActive(true); Vector3 offset = new Vector3(0, 15, 10); desiredCameraPosition.transform.position = target.position + offset; desiredCameraPosition.transform.LookAt(target.transform); SetPosition(desiredCameraPosition.transform); desiredCameraPosition.SetActive(false); } /// <summary> /// Sets the position and rotation of the camera to match that of a supplied transform. /// </summary> /// <param name="transform">The position and rotation the camera is to take.</param> public abstract void SetPosition(Transform transform); } }
41.954545
102
0.657638
[ "Apache-2.0" ]
3dtbd/Common
Assets/OpenSourceCommon/Scripts/Controller/AbstractCameraController.cs
1,848
C#
using System; using System.Net; namespace KcpSharp.ThroughputBanchmarks { internal abstract class UdpSocketDispatcherOptions<T> where T : class, IUdpService { public virtual TimeSpan KeepAliveInterval => TimeSpan.FromMinutes(1); public virtual TimeSpan ScanInterval => TimeSpan.FromMinutes(2); public abstract T Activate(IUdpServiceDispatcher dispatcher, EndPoint endpoint); public abstract void Close(T service); } }
31
88
0.739785
[ "MIT" ]
yigolden/KcpSharp
tests/KcpSharp.ThroughputBanchmarks/UdpServerDispatcherOptions.cs
467
C#
using OrchardCore.Modules.Manifest; [assembly: Module( Name = "Tubumu.Modules.Admin", Author = "Alby", Website = "https://blog.tubumu.com", Version = "1.0.0", Description = "Tubumu admin module." )]
22.1
40
0.633484
[ "MIT" ]
albyho/Tubumu
src/Tubumu.Modules.Admin/Manifest.cs
223
C#
using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; using NetOffice; using NetOffice.Attributes; using NetOffice.Exceptions; namespace NetOffice.VisioApi.Behind.EventContracts { /// <summary> /// Default implementation of <see cref="NetOffice.VisioApi.EventContracts.ERow"/> /// </summary> [InternalEntity(InternalEntityKind.SinkHelper)] [ComVisible(true), ClassInterface(ClassInterfaceType.None), TypeLibType(TypeLibTypeFlags.FHidden)] public class ERow_SinkHelper : SinkHelper, NetOffice.VisioApi.EventContracts.ERow { #region Static /// <summary> /// Interface Id from ERow /// </summary> public static readonly string Id = "000D0B0F-0000-0000-C000-000000000046"; #endregion #region Ctor /// <summary> /// Creates an instance of the class /// </summary> /// <param name="eventClass"></param> /// <param name="connectPoint"></param> /// <exception cref="NetOfficeCOMException">Unexpected error</exception> public ERow_SinkHelper(ICOMObject eventClass, IConnectionPoint connectPoint) : base(eventClass) { SetupEventBinding(connectPoint); } #endregion #region ERow /// <summary> /// /// </summary> /// <param name="cell"></param> public void CellChanged([In, MarshalAs(UnmanagedType.IDispatch)] object cell) { if (!Validate("CellChanged")) { Invoker.ReleaseParamsArray(cell); return; } NetOffice.VisioApi.IVCell newCell = Factory.CreateEventArgumentObjectFromComProxy(EventClass, cell) as NetOffice.VisioApi.IVCell; object[] paramsArray = new object[1]; paramsArray[0] = newCell; EventBinding.RaiseCustomEvent("CellChanged", ref paramsArray); } /// <summary> /// /// </summary> /// <param name="cell"></param> public void FormulaChanged([In, MarshalAs(UnmanagedType.IDispatch)] object cell) { if (!Validate("FormulaChanged")) { Invoker.ReleaseParamsArray(cell); return; } NetOffice.VisioApi.IVCell newCell = Factory.CreateEventArgumentObjectFromComProxy(EventClass, cell) as NetOffice.VisioApi.IVCell; object[] paramsArray = new object[1]; paramsArray[0] = newCell; EventBinding.RaiseCustomEvent("FormulaChanged", ref paramsArray); } #endregion } }
30.011765
141
0.647981
[ "MIT" ]
igoreksiz/NetOffice
Source/Visio/Behind/Events/ERow.cs
2,553
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. #nullable disable using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class LambdaParameterParsingTests : ParsingTests { public LambdaParameterParsingTests(ITestOutputHelper output) : base(output) { } protected override SyntaxTree ParseTree(string text, CSharpParseOptions options) { return SyntaxFactory.ParseSyntaxTree(text, options: options); } protected override CSharpSyntaxNode ParseNode(string text, CSharpParseOptions options) { return SyntaxFactory.ParseExpression(text, options: options); } [Fact] public void EndOfFileAfterOut() { UsingTree(@" class C { void Goo() { System.Func<int, int> f = (out "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.DotToken); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.CommaToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.GreaterThanToken); } } } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.ParenthesizedLambdaExpression); { N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.OutKeyword); M(SyntaxKind.IdentifierName); // parameter type { M(SyntaxKind.IdentifierToken); } M(SyntaxKind.IdentifierToken); // parameter name } M(SyntaxKind.CloseParenToken); } M(SyntaxKind.EqualsGreaterThanToken); M(SyntaxKind.IdentifierName); // lambda body { M(SyntaxKind.IdentifierToken); } } } } } M(SyntaxKind.SemicolonToken); } M(SyntaxKind.CloseBraceToken); } } M(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } } [Fact] public void EndOfFileAfterOutType() { UsingTree(@" class C { void Goo() { System.Func<int, int> f = (out C "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.DotToken); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.CommaToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.GreaterThanToken); } } } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.ParenthesizedLambdaExpression); { N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.OutKeyword); N(SyntaxKind.IdentifierName); // parameter type { N(SyntaxKind.IdentifierToken); } M(SyntaxKind.IdentifierToken); // parameter name } M(SyntaxKind.CloseParenToken); } M(SyntaxKind.EqualsGreaterThanToken); M(SyntaxKind.IdentifierName); // lambda body { M(SyntaxKind.IdentifierToken); } } } } } M(SyntaxKind.SemicolonToken); } M(SyntaxKind.CloseBraceToken); } } M(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } } [Fact] public void EndOfFileAfterOutTypeIdentifier() { UsingTree(@" class C { void Goo() { System.Func<int, int> f = (out C c "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.DotToken); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.CommaToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.GreaterThanToken); } } } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.ParenthesizedLambdaExpression); { N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.OutKeyword); N(SyntaxKind.IdentifierName); // parameter type { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.IdentifierToken); // parameter name } M(SyntaxKind.CloseParenToken); } M(SyntaxKind.EqualsGreaterThanToken); M(SyntaxKind.IdentifierName); // lambda body { M(SyntaxKind.IdentifierToken); } } } } } M(SyntaxKind.SemicolonToken); } M(SyntaxKind.CloseBraceToken); } } M(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } } [Fact] public void EndOfFileAfterOutTypeIdentifierParen() { UsingTree(@" class C { void Goo() { System.Func<int, int> f = (out C c "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.DotToken); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.CommaToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.GreaterThanToken); } } } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.ParenthesizedLambdaExpression); { N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.OutKeyword); N(SyntaxKind.IdentifierName); // parameter type { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.IdentifierToken); // parameter name } M(SyntaxKind.CloseParenToken); } M(SyntaxKind.EqualsGreaterThanToken); M(SyntaxKind.IdentifierName); // lambda body { M(SyntaxKind.IdentifierToken); } } } } } M(SyntaxKind.SemicolonToken); } M(SyntaxKind.CloseBraceToken); } } M(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } } [Fact] public void EndOfFileAfterOutTypeIdentifierComma() { UsingTree(@" class C { void Goo() { System.Func<int, int> f = (out C c, "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.DotToken); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.CommaToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.GreaterThanToken); } } } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.ParenthesizedLambdaExpression); { N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.OutKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CommaToken); M(SyntaxKind.Parameter); { M(SyntaxKind.IdentifierToken); } M(SyntaxKind.CloseParenToken); } M(SyntaxKind.EqualsGreaterThanToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } } } M(SyntaxKind.SemicolonToken); } M(SyntaxKind.CloseBraceToken); } } M(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } } [Fact, WorkItem(14167, "https://github.com/dotnet/roslyn/issues/14167")] public void HangingLambdaParsing_Bug14167() { var tree = UsingNode(@"(int a, int b Main();"); tree.GetDiagnostics().Verify( // (1,1): error CS1073: Unexpected token 'b' // (int a, int b Main(); Diagnostic(ErrorCode.ERR_UnexpectedToken, "(int a, int ").WithArguments("b").WithLocation(1, 1), // (1,9): error CS1525: Invalid expression term 'int' // (int a, int b Main(); Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(1, 9), // (1,13): error CS1026: ) expected // (int a, int b Main(); Diagnostic(ErrorCode.ERR_CloseParenExpected, "b").WithLocation(1, 13) ); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "a"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } M(SyntaxKind.CloseParenToken); } EOF(); } } }
49.697793
112
0.287305
[ "MIT" ]
Acidburn0zzz/roslyn
src/Compilers/CSharp/Test/Syntax/Parsing/LambdaParameterParsingTests.cs
29,274
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("ArrayManipulation")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("HP Inc.")] [assembly: AssemblyProduct("ArrayManipulation")] [assembly: AssemblyCopyright("Copyright © HP Inc. 2018")] [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("c6f4af9e-59b5-4ebf-b961-ee9bc2c0f4d9")] // 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.27027
84
0.749294
[ "MIT" ]
IvanVillani/Coding
C#/coding/ListsExercises/ArrayManipulation/Properties/AssemblyInfo.cs
1,419
C#
using System; using System.Management.Automation; using Microsoft.SharePoint.Client; using OfficeDevPnP.PowerShell.CmdletHelpAttributes; using OfficeDevPnP.PowerShell.Commands.Base.PipeBinds; namespace OfficeDevPnP.PowerShell.Commands { [Cmdlet(VerbsCommon.Add, "SPOFieldToContentType")] [CmdletHelp("Adds an existing site column to a content type", Category = "Content Types")] [CmdletExample( Code = @"PS:> Add-SPOFieldToContentType -Field ""Project_Name"" -ContentType ""Project Document""", Remarks = @"This will add an existing site column with an internal name of ""Project_Name"" to a content type called ""Project Document""", SortOrder = 1)] public class AddFieldToContentType : SPOWebCmdlet { [Parameter(Mandatory = true)] public FieldPipeBind Field; [Parameter(Mandatory = true)] public ContentTypePipeBind ContentType; [Parameter(Mandatory = false)] public SwitchParameter Required; [Parameter(Mandatory = false)] public SwitchParameter Hidden; protected override void ExecuteCmdlet() { Field field = Field.Field; if (field == null) { if (Field.Id != Guid.Empty) { field = SelectedWeb.Fields.GetById(Field.Id); } else if (!string.IsNullOrEmpty(Field.Name)) { field = SelectedWeb.Fields.GetByInternalNameOrTitle(Field.Name); } ClientContext.Load(field); ClientContext.ExecuteQueryRetry(); } if (field != null) { if (ContentType.ContentType != null) { SelectedWeb.AddFieldToContentType(ContentType.ContentType, field, Required, Hidden); } else { ContentType ct; if (!string.IsNullOrEmpty(ContentType.Id)) { ct = SelectedWeb.GetContentTypeById(ContentType.Id); } else { ct = SelectedWeb.GetContentTypeByName(ContentType.Name); } if (ct != null) { SelectedWeb.AddFieldToContentType(ct, field, Required, false); } } } else { throw new Exception("Field not found"); } } } }
33.666667
160
0.525133
[ "Apache-2.0" ]
iratherscribble/OfficeDevPnP
Solutions/PowerShell.Commands/Commands/ContentTypes/AddFieldToContentType.cs
2,628
C#
using System; namespace ConsoleApp { class Program { static void Main(string[] args) { Console.WriteLine("Gra za Duzo za Malo"); //1. Komputer losuje #region losowanie var los = new Random(); // Tworze obiekt tupu random int wylosowana = los.Next(1, 101); #if DEBUG Console.WriteLine(wylosowana); // Howa kod po przeniesieniu sie na tryb relise #endif Console.WriteLine("Wylosowałem liczbę od 1 - 100. \nOdgadnij ją!"); #endregion bool odgadniete = false; // Dopuki nie odgadniete while(!odgadniete) { //2. człowiek proponuje Console.Write("Podaj swoją propozycje"); //int propozycja = int.Parse(Console.ReadLine()); int propozycja = int.Parse(Console.ReadLine()); //3. komp ocenia if (propozycja < wylosowana) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Za mało!"); Console.ResetColor(); } else if (propozycja > wylosowana) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Za duzo!"); Console.ResetColor(); } else { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Trafiono!"); Console.ResetColor(); odgadniete = true; } // Console.Write("Podaj swoją propozycje jeszcze raz"); // propozycja = int.Parse(Console.ReadLine()); // } // Console.ForegroundColor = ConsoleColor.Green; //Console.WriteLine("Trafiono!"); //Console.ResetColor(); } Console.WriteLine("Koniec Gry. Wygrałes!"); } } }
26.095238
91
0.453467
[ "MIT" ]
Damiancie24/zgadywanka
Zgadywanka/ConsoleApp/Program.cs
2,202
C#
using Amazon.JSII.Runtime.Deputy; #pragma warning disable CS0672,CS0809,CS1591 namespace AlibabaCloud.SDK.ROS.CDK.Slb { #pragma warning disable CS8618 /// <summary>Properties for defining a `ALIYUN::SLB::DomainExtension`.</summary> [JsiiByValue(fqn: "@alicloud/ros-cdk-slb.DomainExtensionProps")] public class DomainExtensionProps : AlibabaCloud.SDK.ROS.CDK.Slb.IDomainExtensionProps { /// <summary>Property domain: The domain name.</summary> [JsiiProperty(name: "domain", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOverride: true)] public object Domain { get; set; } /// <summary>Property listenerPort: The front-end HTTPS listener port of the Server Load Balancer instance.</summary> /// <remarks> /// Valid value: /// 1-65535 /// </remarks> [JsiiProperty(name: "listenerPort", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"number\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOverride: true)] public object ListenerPort { get; set; } /// <summary>Property loadBalancerId: The ID of Server Load Balancer instance.</summary> [JsiiProperty(name: "loadBalancerId", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOverride: true)] public object LoadBalancerId { get; set; } /// <summary>Property serverCertificateId: The ID of the certificate corresponding to the domain name.</summary> [JsiiProperty(name: "serverCertificateId", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOverride: true)] public object ServerCertificateId { get; set; } } }
39.86
184
0.596588
[ "Apache-2.0" ]
aliyun/Resource-Orchestration-Service-Cloud-Development-K
multiple-languages/dotnet/AlibabaCloud.SDK.ROS.CDK.Slb/AlibabaCloud/SDK/ROS/CDK/Slb/DomainExtensionProps.cs
1,993
C#
namespace ClassLib005 { public class Class010 { public static string Property => "ClassLib005"; } }
15
55
0.633333
[ "MIT" ]
333fred/performance
src/scenarios/weblarge2.0/src/ClassLib005/Class010.cs
120
C#
using advent.Enums._2020; using advent.Extensions; using System.Collections.Generic; using System.Linq; namespace advent.Models._2020 { public class TicketReader { public TrainRuleset Ruleset { get; } public IList<TrainTicket> Tickets { get; } public TrainTicket MyTicket { get; } private bool areTicketsChecked = false; public TicketReader(string input) { Ruleset = new TrainRuleset(); Tickets = new List<TrainTicket>(); var lines = input.Lines(); var phase = TicketPhase.Rules; foreach (var line in lines) { switch (line) { case "your ticket:": phase = TicketPhase.YourTicket; continue; case "nearby tickets:": phase = TicketPhase.NearbyTickets; continue; } switch (phase) { case TicketPhase.Rules: Ruleset.Add(line); break; case TicketPhase.YourTicket: MyTicket = new TrainTicket(line); break; case TicketPhase.NearbyTickets: Tickets.Add(new TrainTicket(line)); break; } } } public int CheckTickets() { var values = new List<int>(); foreach (var ticket in Tickets) { var check = Ruleset.CheckTicket(ticket); if (check > 0) { values.Add(check); } } areTicketsChecked = true; return values.Sum(); } public IDictionary<int, string> CheckValidTickets() { if (!areTicketsChecked) CheckTickets(); var validTickets = Tickets.Where(x => x.IsValid).ToList(); var result = new Dictionary<int, string>(); var toProcess = validTickets[0].Valids.Keys.ToList(); do { var nextToProcess = new List<int>(); foreach (var i in toProcess) { var fields = validTickets.Select(x => x.Valids[i]); var intersection = fields.Intersect() .Where(x => !result.ContainsValue(x)) .ToList(); if (intersection.Count == 1) { result.Add(i, intersection[0]); } else { nextToProcess.Add(i); } } toProcess = nextToProcess; } while (toProcess.Count > 0); return result; } } }
27.154545
71
0.429528
[ "MIT" ]
aethercowboy/advent
advent/Models/2020/TicketReader.cs
2,989
C#
using System; using System.Numerics; using CoreEngine.Collections; namespace CoreEngine.Rendering.Components { public partial struct CameraComponent : IComponentData { public Vector3 EyePosition { get; set; } public Vector3 LookAtPosition { get; set; } public ItemIdentifier Camera { get; set; } public void SetDefaultValues() { } } }
20.947368
58
0.660804
[ "MIT" ]
tdecroyere/CoreEngine
src/CoreEngine/Rendering/Components/CameraComponent.cs
398
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using Newtonsoft.Json; using Parquet.Data; using Parquet.Data.Rows; using Xunit; namespace Parquet.Test.Rows { public class RowsModelTest : TestBase { #region [ Flat Tables ] [Fact] public void Flat_add_valid_row_succeeds() { var table = new Table(new Schema(new DataField<int>("id"))); table.Add(new Row(1)); } [Fact] public void Flat_add_invalid_type_fails() { var table = new Table(new Schema(new DataField<int>("id"))); Assert.Throws<ArgumentException>(() => table.Add(new Row("1"))); } [Fact] public void Flat_write_read() { var table = new Table(new Schema(new DataField<int>("id"), new DataField<string>("city"))); var ms = new MemoryStream(); //generate fake data for (int i = 0; i < 1000; i++) { table.Add(new Row(i, "record#" + i)); } //write to stream using (var writer = new ParquetWriter(table.Schema, ms)) { writer.Write(table); } //read back into table ms.Position = 0; Table table2; using (var reader = new ParquetReader(ms)) { table2 = reader.ReadAsTable(); } //validate data Assert.True(table.Equals(table2, true)); } #endregion #region [ Array Tables ] [Fact] public void Array_validate_succeeds() { var table = new Table(new Schema(new DataField<IEnumerable<int>>("ids"))); table.Add(new Row(new[] { 1, 2, 3 })); table.Add(new Row(new[] { 4, 5, 6 })); } [Fact] public void Array_validate_fails() { var table = new Table(new Schema(new DataField<IEnumerable<int>>("ids"))); Assert.Throws<ArgumentException>(() => table.Add(new Row(1))); } [Fact] public void Array_write_read() { var table = new Table( new Schema( new DataField<int>("id"), new DataField<string[]>("categories") //array field ) ); var ms = new MemoryStream(); table.Add(1, new[] { "1", "2", "3" }); table.Add(3, new[] { "3", "3", "3" }); //write to stream using (var writer = new ParquetWriter(table.Schema, ms)) { writer.Write(table); } //System.IO.File.WriteAllBytes("c:\\tmp\\1.parquet", ms.ToArray()); //read back into table ms.Position = 0; Table table2; using (var reader = new ParquetReader(ms)) { table2 = reader.ReadAsTable(); } //validate data Assert.Equal(table.ToString(), table2.ToString(), ignoreLineEndingDifferences: true); } #endregion #region [ Maps ] [Fact] public void Map_validate_succeeds() { var table = new Table(new Schema( new MapField("map", new DataField<string>("key"), new DataField<string>("value")) )); table.Add(Row.SingleCell( new List<Row> { new Row("one", "v1"), new Row("two", "v2") })); } [Fact] public void Map_validate_fails() { var table = new Table(new Schema( new MapField("map", new DataField<string>("key"), new DataField<string>("value")) )); Assert.Throws<ArgumentException>(() => table.Add(new Row(1))); } [Fact] public void Map_read_from_Apache_Spark() { Table t; using (Stream stream = OpenTestFile("map_simple.parquet")) { using (var reader = new ParquetReader(stream)) { t = reader.ReadAsTable(); } } Assert.Equal("{'id': 1, 'numbers': [{'key': 1, 'value': 'one'}, {'key': 2, 'value': 'two'}, {'key': 3, 'value': 'three'}]}", t[0].ToString(), ignoreLineEndingDifferences: true); } [Fact] public void Map_write_read() { var table = new Table( new Schema( new DataField<string>("city"), new MapField("population", new DataField<int>("areaId"), new DataField<long>("count")))); var ms = new MemoryStream(); table.Add("London", new List<Row> { new Row(234, 100L), new Row(235, 110L) }); Table table2 = WriteRead(table); Assert.Equal(table.ToString(), table2.ToString(), ignoreLineEndingDifferences: true); } #endregion #region [ Struct ] [Fact] public void Struct_read_plain_structs_from_Apache_Spark() { Table t = ReadTestFileAsTable("struct_plain.parquet"); Assert.Equal(@"{'isbn': '12345-6', 'author': {'firstName': 'Ivan', 'lastName': 'Gavryliuk'}} {'isbn': '12345-7', 'author': {'firstName': 'Richard', 'lastName': 'Conway'}}", t.ToString(), ignoreLineEndingDifferences: true); } [Fact] public void Struct_write_read() { var table = new Table( new Schema( new DataField<string>("isbn"), new StructField("author", new DataField<string>("firstName"), new DataField<string>("lastName")))); var ms = new MemoryStream(); table.Add("12345-6", new Row("Ivan", "Gavryliuk")); table.Add("12345-7", new Row("Richard", "Conway")); Table table2 = WriteRead(table); Assert.Equal(table.ToString(), table2.ToString(), ignoreLineEndingDifferences: true); } [Fact] public void Struct_with_repeated_field_writes_reads() { var t = new Table(new Schema( new DataField<string>("name"), new StructField("address", new DataField<string>("name"), new DataField<IEnumerable<string>>("lines")))); t.Add("Ivan", new Row("Primary", new[] { "line1", "line2" })); Table t2 = WriteRead(t); Assert.Equal("{'name': 'Ivan', 'address': {'name': 'Primary', 'lines': ['line1', 'line2']}}", t2.ToString(), ignoreLineEndingDifferences: true); } #endregion #region [ List ] [Fact] public void List_table_equality() { var schema = new Schema(new ListField("ints", new DataField<int>("int"))); var tbl1 = new Table(schema); tbl1.Add(Row.SingleCell(new[] { 1, 1, 1 })); var tbl2 = new Table(schema); tbl2.Add(Row.SingleCell(new[] { 1, 1, 1 })); Assert.True(tbl1.Equals(tbl2, true)); } [Fact] public void List_read_simple_element_from_Apache_Spark() { Table t; using (Stream stream = OpenTestFile("list_simple.parquet")) { using (var reader = new ParquetReader(stream)) { t = reader.ReadAsTable(); } } Assert.Equal("{'cities': ['London', 'Derby', 'Paris', 'New York'], 'id': 1}", t[0].ToString(), ignoreLineEndingDifferences: true); } [Fact] public void List_simple_element_write_read() { var table = new Table( new Schema( new DataField<int>("id"), new ListField("cities", new DataField<string>("name")))); var ms = new MemoryStream(); table.Add(1, new[] { "London", "Derby" }); table.Add(2, new[] { "Paris", "New York" }); //write as table using (var writer = new ParquetWriter(table.Schema, ms)) { writer.Write(table); } //read back into table ms.Position = 0; Table table2; using (var reader = new ParquetReader(ms)) { table2 = reader.ReadAsTable(); } //validate data Assert.Equal(table.ToString(), table2.ToString(), ignoreLineEndingDifferences: true); } [Fact] public void List_read_structures_from_Apache_Spark() { Table t; using (Stream stream = OpenTestFile("list_structs.parquet")) { using (var reader = new ParquetReader(stream)) { t = reader.ReadAsTable(); } } Assert.Single(t); Assert.Equal("{'cities': [{'country': 'UK', 'name': 'London'}, {'country': 'US', 'name': 'New York'}], 'id': 1}", t[0].ToString(), ignoreLineEndingDifferences: true); } [Fact] public void List_read_write_structures() { Table t = new Table( new DataField<int>("id"), new ListField("structs", new StructField("mystruct", new DataField<int>("id"), new DataField<string>("name")))); t.Add(1, new[] { new Row(1, "Joe"), new Row(2, "Bloggs") }); t.Add(2, new[] { new Row(3, "Star"), new Row(4, "Wars") }); Table t2 = WriteRead(t); Assert.Equal(t.ToString(), t2.ToString(), ignoreLineEndingDifferences: true); } [Fact] public void List_of_elements_is_empty_read_from_Apache_Spark() { Table t = ReadTestFileAsTable("list_empty.parquet"); Assert.Equal("{'id': 2, 'repeats1': []}", t[0].ToString(), ignoreLineEndingDifferences: true); } [Fact] public void List_of_elements_empty_alternates_read_from_Apache_Spark() { /* list data: - 1: [1, 2, 3] - 2: [] - 3: [1, 2, 3] - 4: [] */ Table t = ReadTestFileAsTable("list_empty_alt.parquet"); Assert.Equal(@"{'id': 1, 'repeats2': ['1', '2', '3']} {'id': 2, 'repeats2': []} {'id': 3, 'repeats2': ['1', '2', '3']} {'id': 4, 'repeats2': []}", t.ToString(), ignoreLineEndingDifferences: true); } [Fact] public void List_of_elements_is_empty_writes_reads() { var t = new Table( new DataField<int>("id"), new ListField("strings", new DataField<string>("item") )); t.Add(1, new string[0]); Assert.Equal("{'id': 1, 'strings': []}", WriteRead(t).ToString(), ignoreLineEndingDifferences: true); } [Fact] public void List_of_elements_with_some_items_empty_writes_reads() { var t = new Table( new DataField<int>("id"), new ListField("strings", new DataField<string>("item") )); t.Add(1, new string[] { "1", "2", "3" }); t.Add(2, new string[] { }); t.Add(3, new string[] { "1", "2", "3" }); t.Add(4, new string[] { }); Table t1 = WriteRead(t); Assert.Equal(4, t1.Count); Assert.Equal(@"{'id': 1, 'strings': ['1', '2', '3']} {'id': 2, 'strings': []} {'id': 3, 'strings': ['1', '2', '3']} {'id': 4, 'strings': []}", t.ToString(), ignoreLineEndingDifferences: true); } [Fact] public void List_of_lists_read_write_structures() { var t = new Table( new DataField<int>("id"), new ListField( "items", new StructField( "item", new DataField<int>("id"), new ListField( "values", new DataField<string>("value"))))); t.Add(0, new[] { new Row(0, new[] { "0,0,0", "0,0,1", "0,0,2" }), new Row(1, new[] { "0,1,0", "0,1,1", "0,1,2" }), new Row(2, new[] { "0,2,0", "0,2,1", "0,2,2" }), }); Table t1 = WriteRead(t); Assert.Equal(3, ((object[])t1[0][1]).Length); Assert.Equal(t.ToString(), t1.ToString(), ignoreLineEndingDifferences: true); } [Fact] public void List_of_structures_is_empty_read_write_structures() { Table t = new Table( new DataField<int>("id"), new ListField("structs", new StructField("mystruct", new DataField<int>("id"), new DataField<string>("name")))); t.Add(1, new Row[0]); t.Add(2, new Row[0]); Table t2 = WriteRead(t); Assert.Equal(t.ToString(), t2.ToString(), ignoreLineEndingDifferences: true); } [Fact] public void List_of_structures_is_empty_as_first_field_read_write_structures() { Table t = new Table( new ListField("structs", new StructField("mystruct", new DataField<int>("id"), new DataField<string>("name"))), new DataField<int>("id")); t.Add(new Row[0], 1); t.Add(new Row[0], 2); Table t2 = WriteRead(t); Assert.Equal(t.ToString(), t2.ToString(), ignoreLineEndingDifferences: true); } #endregion #region [ Mixed ] #endregion #region [ Special Cases ] [Fact] public void Special_read_all_nulls_no_booleans() { ReadTestFileAsTable("special/all_nulls_no_booleans.parquet"); } [Fact] public void Special_all_nulls_file() { Table t = ReadTestFileAsTable("special/all_nulls.parquet"); Assert.Equal(1, t.Schema.Fields.Count); Assert.Equal("lognumber", t.Schema[0].Name); Assert.Single(t); Assert.Null(t[0][0]); } [Fact] public void Special_read_all_nulls_decimal_column() { ReadTestFileAsTable("special/decimalnulls.parquet"); } [Fact] public void Special_read_all_legacy_decimals() { Table ds = ReadTestFileAsTable("special/decimallegacy.parquet"); Row row = ds[0]; Assert.Equal(1, (int)row[0]); Assert.Equal(1.2m, (decimal)row[1], 2); Assert.Null(row[2]); Assert.Equal(-1m, (decimal)row[3], 2); } [Fact] public void Special_read_file_with_multiple_row_groups() { var ms = new MemoryStream(); //create multirowgroup file //first row group var t = new Table(new DataField<int>("id")); t.Add(1); t.Add(2); using (var writer = new ParquetWriter(t.Schema, ms)) { writer.Write(t); } //second row group t.Clear(); t.Add(3); t.Add(4); using (var writer = new ParquetWriter(t.Schema, ms, null, true)) { writer.Write(t); } //read back as table t = ParquetReader.ReadTableFromStream(ms); Assert.Equal(4, t.Count); } #endregion #region [ And the Big Ultimate Fat Test!!! ] /// <summary> /// This essentially proves that we can READ complicated data structures, but not write (see other tests) /// </summary> [Fact] public void BigFatOne_variations_from_Apache_Spark() { Table t; using (Stream stream = OpenTestFile("all_var1.parquet")) { using (var reader = new ParquetReader(stream)) { t = reader.ReadAsTable(); } } Assert.Equal(2, t.Count); Assert.Equal("{'addresses': [{'line1': 'Dante Road', 'name': 'Head Office', 'openingHours': [9, 10, 11, 12, 13, 14, 15, 16, 17, 18], 'postcode': 'SE11'}, {'line1': 'Somewhere Else', 'name': 'Small Office', 'openingHours': [6, 7, 19, 20, 21, 22, 23], 'postcode': 'TN19'}], 'cities': ['London', 'Derby'], 'comment': 'this file contains all the permunations for nested structures and arrays to test Parquet parser', 'id': 1, 'location': {'latitude': 51.2, 'longitude': 66.3}, 'price': {'lunch': {'max': 2, 'min': 1}}}", t[0].ToString()); Assert.Equal("{'addresses': [{'line1': 'Dante Road', 'name': 'Head Office', 'openingHours': [9, 10, 11, 12, 13, 14, 15, 16, 17, 18], 'postcode': 'SE11'}, {'line1': 'Somewhere Else', 'name': 'Small Office', 'openingHours': [6, 7, 19, 20, 21, 22, 23], 'postcode': 'TN19'}], 'cities': ['London', 'Derby'], 'comment': 'this file contains all the permunations for nested structures and arrays to test Parquet parser', 'id': 1, 'location': {'latitude': 51.2, 'longitude': 66.3}, 'price': {'lunch': {'max': 2, 'min': 1}}}", t[1].ToString()); } #endregion #region [ JSON Conversions ] [Fact] public void JSON_struct_plain_reads_by_newtonsoft() { Table t = ReadTestFileAsTable("struct_plain.parquet"); Assert.Equal("{'isbn': '12345-6', 'author': {'firstName': 'Ivan', 'lastName': 'Gavryliuk'}}", t[0].ToString("jsq")); Assert.Equal("{'isbn': '12345-7', 'author': {'firstName': 'Richard', 'lastName': 'Conway'}}", t[1].ToString("jsq")); string[] jsons = t.ToString("j").Split(new[] { Environment.NewLine }, StringSplitOptions.None); jsons.Select(j => JsonConvert.DeserializeObject(j)).ToList(); } [Fact] public void JSON_convert_with_null_arrays() { var t = new Table(new Schema( new DataField<string>("name"), new ListField("observations", new StructField("observation", new DataField<DateTimeOffset>("date"), new DataField<bool>("bool"), new DataField<IEnumerable<int?>>("values"))))); DateTimeOffset defaultDate = new DateTimeOffset(2018, 1, 1, 1, 1, 1, TimeSpan.Zero); t.Add("London", new[] { new Row(defaultDate, true, new int?[] { 1, 2, 3, 4, 5 }) }); t.Add("Oslo", new[] { new Row(defaultDate, false, new int?[] { null, null, null, null, null, null, null }) }); string[] jsons = t.ToString("jsq").Split(new[] {Environment.NewLine}, StringSplitOptions.None); Assert.Equal($"{{'name': 'London', 'observations': [{{'date': '{defaultDate}', 'bool': true, 'values': [1, 2, 3, 4, 5]}}]}}", jsons[0]); Assert.Equal($"{{'name': 'Oslo', 'observations': [{{'date': '{defaultDate}', 'bool': false, 'values': [null, null, null, null, null, null, null]}}]}}", jsons[1]); } #endregion } }
30.93311
543
0.520705
[ "MIT" ]
AiimiLtd/parquet-dotnet
src/Parquet.Test/Rows/RowsModelTest.cs
18,500
C#
using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using System.Transactions; using Abp.Auditing; using Abp.Authorization.Roles; using Abp.Authorization.Users; using Abp.Configuration; using Abp.Configuration.Startup; using Abp.Dependency; using Abp.Domain.Repositories; using Abp.Domain.Uow; using Abp.Extensions; using Abp.IdentityFramework; using Abp.MultiTenancy; using Abp.Timing; using Abp.Zero.Configuration; using Microsoft.AspNetCore.Identity; namespace Abp.Authorization { public class AbpLogInManager<TTenant, TRole, TUser> : ITransientDependency where TTenant : AbpTenant<TUser> where TRole : AbpRole<TUser>, new() where TUser : AbpUser<TUser> { public IClientInfoProvider ClientInfoProvider { get; set; } protected IMultiTenancyConfig MultiTenancyConfig { get; } protected IRepository<TTenant> TenantRepository { get; } protected IUnitOfWorkManager UnitOfWorkManager { get; } protected AbpUserManager<TRole, TUser> UserManager { get; } protected ISettingManager SettingManager { get; } protected IRepository<UserLoginAttempt, long> UserLoginAttemptRepository { get; } protected IUserManagementConfig UserManagementConfig { get; } protected IIocResolver IocResolver { get; } protected AbpRoleManager<TRole, TUser> RoleManager { get; } private readonly IPasswordHasher<TUser> _passwordHasher; private readonly AbpUserClaimsPrincipalFactory<TUser, TRole> _claimsPrincipalFactory; public AbpLogInManager( AbpUserManager<TRole, TUser> userManager, IMultiTenancyConfig multiTenancyConfig, IRepository<TTenant> tenantRepository, IUnitOfWorkManager unitOfWorkManager, ISettingManager settingManager, IRepository<UserLoginAttempt, long> userLoginAttemptRepository, IUserManagementConfig userManagementConfig, IIocResolver iocResolver, IPasswordHasher<TUser> passwordHasher, AbpRoleManager<TRole, TUser> roleManager, AbpUserClaimsPrincipalFactory<TUser, TRole> claimsPrincipalFactory) { _passwordHasher = passwordHasher; _claimsPrincipalFactory = claimsPrincipalFactory; MultiTenancyConfig = multiTenancyConfig; TenantRepository = tenantRepository; UnitOfWorkManager = unitOfWorkManager; SettingManager = settingManager; UserLoginAttemptRepository = userLoginAttemptRepository; UserManagementConfig = userManagementConfig; IocResolver = iocResolver; RoleManager = roleManager; UserManager = userManager; ClientInfoProvider = NullClientInfoProvider.Instance; } [UnitOfWork] public virtual async Task<AbpLoginResult<TTenant, TUser>> LoginAsync(UserLoginInfo login, string tenancyName = null) { var result = await LoginAsyncInternal(login, tenancyName); await SaveLoginAttempt(result, tenancyName, login.ProviderKey + "@" + login.LoginProvider); return result; } protected virtual async Task<AbpLoginResult<TTenant, TUser>> LoginAsyncInternal(UserLoginInfo login, string tenancyName) { if (login == null || login.LoginProvider.IsNullOrEmpty() || login.ProviderKey.IsNullOrEmpty()) { throw new ArgumentException("login"); } //Get and check tenant TTenant tenant = null; if (!MultiTenancyConfig.IsEnabled) { tenant = await GetDefaultTenantAsync(); } else if (!string.IsNullOrWhiteSpace(tenancyName)) { tenant = await TenantRepository.FirstOrDefaultAsync(t => t.TenancyName == tenancyName); if (tenant == null) { return new AbpLoginResult<TTenant, TUser>(AbpLoginResultType.InvalidTenancyName); } if (!tenant.IsActive) { return new AbpLoginResult<TTenant, TUser>(AbpLoginResultType.TenantIsNotActive, tenant); } } int? tenantId = tenant == null ? (int?)null : tenant.Id; using (UnitOfWorkManager.Current.SetTenantId(tenantId)) { var user = await UserManager.FindAsync(tenantId, login); if (user == null) { return new AbpLoginResult<TTenant, TUser>(AbpLoginResultType.UnknownExternalLogin, tenant); } return await CreateLoginResultAsync(user, tenant); } } [UnitOfWork] public virtual async Task<AbpLoginResult<TTenant, TUser>> LoginAsync(string userNameOrEmailAddress, string plainPassword, string tenancyName = null, bool shouldLockout = true) { var result = await LoginAsyncInternal(userNameOrEmailAddress, plainPassword, tenancyName, shouldLockout); await SaveLoginAttempt(result, tenancyName, userNameOrEmailAddress); return result; } protected virtual async Task<AbpLoginResult<TTenant, TUser>> LoginAsyncInternal(string userNameOrEmailAddress, string plainPassword, string tenancyName, bool shouldLockout) { if (userNameOrEmailAddress.IsNullOrEmpty()) { throw new ArgumentNullException(nameof(userNameOrEmailAddress)); } if (plainPassword.IsNullOrEmpty()) { throw new ArgumentNullException(nameof(plainPassword)); } //Get and check tenant TTenant tenant = null; using (UnitOfWorkManager.Current.SetTenantId(null)) { if (!MultiTenancyConfig.IsEnabled) { tenant = await GetDefaultTenantAsync(); } else if (!string.IsNullOrWhiteSpace(tenancyName)) { tenant = await TenantRepository.FirstOrDefaultAsync(t => t.TenancyName == tenancyName); if (tenant == null) { return new AbpLoginResult<TTenant, TUser>(AbpLoginResultType.InvalidTenancyName); } if (!tenant.IsActive) { return new AbpLoginResult<TTenant, TUser>(AbpLoginResultType.TenantIsNotActive, tenant); } } } var tenantId = tenant == null ? (int?)null : tenant.Id; using (UnitOfWorkManager.Current.SetTenantId(tenantId)) { await UserManager.InitializeOptionsAsync(tenantId); //TryLoginFromExternalAuthenticationSources method may create the user, that's why we are calling it before AbpUserStore.FindByNameOrEmailAsync var loggedInFromExternalSource = await TryLoginFromExternalAuthenticationSources(userNameOrEmailAddress, plainPassword, tenant); var user = await UserManager.FindByNameOrEmailAsync(tenantId, userNameOrEmailAddress); if (user == null) { return new AbpLoginResult<TTenant, TUser>(AbpLoginResultType.InvalidUserNameOrEmailAddress, tenant); } if (await UserManager.IsLockedOutAsync(user)) { return new AbpLoginResult<TTenant, TUser>(AbpLoginResultType.LockedOut, tenant, user); } if (!loggedInFromExternalSource) { if (!await UserManager.CheckPasswordAsync(user, plainPassword)) { if (shouldLockout) { if (await TryLockOutAsync(tenantId, user.Id)) { return new AbpLoginResult<TTenant, TUser>(AbpLoginResultType.LockedOut, tenant, user); } } return new AbpLoginResult<TTenant, TUser>(AbpLoginResultType.InvalidPassword, tenant, user); } await UserManager.ResetAccessFailedCountAsync(user); } return await CreateLoginResultAsync(user, tenant); } } protected virtual async Task<AbpLoginResult<TTenant, TUser>> CreateLoginResultAsync(TUser user, TTenant tenant = null) { if (!user.IsActive) { return new AbpLoginResult<TTenant, TUser>(AbpLoginResultType.UserIsNotActive); } if (await IsEmailConfirmationRequiredForLoginAsync(user.TenantId) && !user.IsEmailConfirmed) { return new AbpLoginResult<TTenant, TUser>(AbpLoginResultType.UserEmailIsNotConfirmed); } if (await IsPhoneConfirmationRequiredForLoginAsync(user.TenantId) && !user.IsPhoneNumberConfirmed) { return new AbpLoginResult<TTenant, TUser>(AbpLoginResultType.UserPhoneNumberIsNotConfirmed); } var principal = await _claimsPrincipalFactory.CreateAsync(user); return new AbpLoginResult<TTenant, TUser>( tenant, user, principal.Identity as ClaimsIdentity ); } protected virtual async Task SaveLoginAttempt(AbpLoginResult<TTenant, TUser> loginResult, string tenancyName, string userNameOrEmailAddress) { using (var uow = UnitOfWorkManager.Begin(TransactionScopeOption.Suppress)) { var tenantId = loginResult.Tenant != null ? loginResult.Tenant.Id : (int?)null; using (UnitOfWorkManager.Current.SetTenantId(tenantId)) { var loginAttempt = new UserLoginAttempt { TenantId = tenantId, TenancyName = tenancyName, UserId = loginResult.User != null ? loginResult.User.Id : (long?)null, UserNameOrEmailAddress = userNameOrEmailAddress, Result = loginResult.Result, BrowserInfo = ClientInfoProvider.BrowserInfo, ClientIpAddress = ClientInfoProvider.ClientIpAddress, ClientName = ClientInfoProvider.ComputerName, }; await UserLoginAttemptRepository.InsertAsync(loginAttempt); await UnitOfWorkManager.Current.SaveChangesAsync(); await uow.CompleteAsync(); } } } protected virtual async Task<bool> TryLockOutAsync(int? tenantId, long userId) { using (var uow = UnitOfWorkManager.Begin(TransactionScopeOption.Suppress)) { using (UnitOfWorkManager.Current.SetTenantId(tenantId)) { var user = await UserManager.FindByIdAsync(userId.ToString()); (await UserManager.AccessFailedAsync(user)).CheckErrors(); var isLockOut = await UserManager.IsLockedOutAsync(user); await UnitOfWorkManager.Current.SaveChangesAsync(); await uow.CompleteAsync(); return isLockOut; } } } protected virtual async Task<bool> TryLoginFromExternalAuthenticationSources(string userNameOrEmailAddress, string plainPassword, TTenant tenant) { if (!UserManagementConfig.ExternalAuthenticationSources.Any()) { return false; } foreach (var sourceType in UserManagementConfig.ExternalAuthenticationSources) { using (var source = IocResolver.ResolveAsDisposable<IExternalAuthenticationSource<TTenant, TUser>>(sourceType)) { if (await source.Object.TryAuthenticateAsync(userNameOrEmailAddress, plainPassword, tenant)) { var tenantId = tenant == null ? (int?)null : tenant.Id; using (UnitOfWorkManager.Current.SetTenantId(tenantId)) { var user = await UserManager.FindByNameOrEmailAsync(tenantId, userNameOrEmailAddress); if (user == null) { user = await source.Object.CreateUserAsync(userNameOrEmailAddress, tenant); user.TenantId = tenantId; user.AuthenticationSource = source.Object.Name; user.Password = _passwordHasher.HashPassword(user, Guid.NewGuid().ToString("N").Left(16)); //Setting a random password since it will not be used user.SetNormalizedNames(); if (user.Roles == null) { user.Roles = new List<UserRole>(); foreach (var defaultRole in RoleManager.Roles.Where(r => r.TenantId == tenantId && r.IsDefault).ToList()) { user.Roles.Add(new UserRole(tenantId, user.Id, defaultRole.Id)); } } await UserManager.CreateAsync(user); } else { await source.Object.UpdateUserAsync(user, tenant); user.AuthenticationSource = source.Object.Name; await UserManager.UpdateAsync(user); } await UnitOfWorkManager.Current.SaveChangesAsync(); return true; } } } } return false; } protected virtual async Task<TTenant> GetDefaultTenantAsync() { var tenant = await TenantRepository.FirstOrDefaultAsync(t => t.TenancyName == AbpTenant<TUser>.DefaultTenantName); if (tenant == null) { throw new AbpException("There should be a 'Default' tenant if multi-tenancy is disabled!"); } return tenant; } protected virtual async Task<bool> IsEmailConfirmationRequiredForLoginAsync(int? tenantId) { if (tenantId.HasValue) { return await SettingManager.GetSettingValueForTenantAsync<bool>(AbpZeroSettingNames.UserManagement.IsEmailConfirmationRequiredForLogin, tenantId.Value); } return await SettingManager.GetSettingValueForApplicationAsync<bool>(AbpZeroSettingNames.UserManagement.IsEmailConfirmationRequiredForLogin); } protected virtual Task<bool> IsPhoneConfirmationRequiredForLoginAsync(int? tenantId) { return Task.FromResult(false); } } }
42.306011
183
0.578985
[ "MIT" ]
12321/aspnetboilerplate
src/Abp.ZeroCore/Authorization/AbpLoginManager.cs
15,486
C#
using CloudinaryDotNet.Actions; using NUnit.Framework; using System.Threading.Tasks; namespace CloudinaryDotNet.IntegrationTest.UploadApi { public class DestroyMethodsTest : IntegrationTestBase { [Test] public void TestDestroyRaw() { var uploadResult = UploadTestRawResource(type: ApiShared.GetCloudinaryParam(ResourceType.Raw)); var deletionParams = GetDeletionParams(uploadResult.PublicId); var destroyResult = m_cloudinary.Destroy(deletionParams); AssertDestroyed(destroyResult); } [Test] public async Task TestDestroyRawAsync() { var uploadResult = await UploadTestRawResourceAsync(type: ApiShared.GetCloudinaryParam(ResourceType.Raw)); var deletionParams = GetDeletionParams(uploadResult.PublicId); var destroyResult = await m_cloudinary.DestroyAsync(deletionParams); AssertDestroyed(destroyResult); } private DeletionParams GetDeletionParams(string publicId) { return new DeletionParams(publicId) { ResourceType = ResourceType.Raw }; } private void AssertDestroyed(DeletionResult result) { Assert.AreEqual("ok", result.Result); } } }
29.622222
118
0.648912
[ "MIT" ]
jordansjones/CloudinaryDotNet
Shared.IntegrationTests/UploadApi/DestroyMethodsTest.cs
1,335
C#
using System; using System.Collections; using System.Collections.Generic; using Xunit; using System.Linq; using System.Linq.Expressions; using Marten.Services; using Marten.Linq; using Marten.Schema; namespace Marten.Testing.Linq { public class SimpleNotEqualsParserTests : DocumentSessionFixture<NulloIdentityMap> { class QueryTarget { public int IntProp { get; set; } public long LongProp { get; set; } public decimal DecimalProp { get; set; } public bool BoolProp { get; set; } public Guid Id { get; set; } public DateTime DateTimeProp { get; set; } public DateTimeOffset DateTimeOffsetProp { get; set; } } [Fact] public void CanTranslateNotEqualsToQueries() { var queryTarget = new QueryTarget { IntProp = 1, LongProp = 2, DecimalProp = 1.1m, BoolProp = true, Id = Guid.NewGuid(), DateTimeProp = DateTime.UtcNow, DateTimeOffsetProp = DateTimeOffset.UtcNow }; theSession.Store(queryTarget); theSession.SaveChanges(); var itemFromDb = theSession.Query<QueryTarget>() .Where(x => !x.IntProp.Equals(queryTarget.IntProp)) .Where(x => !x.LongProp.Equals(queryTarget.LongProp)) .Where(x => !x.DecimalProp.Equals(queryTarget.DecimalProp)) .Where(x => !x.BoolProp.Equals(queryTarget.BoolProp)) .Where(x => !x.Id.Equals(queryTarget.Id)) .Where(x => !x.DateTimeProp.Equals(queryTarget.DateTimeProp)) .Where(x => !x.DateTimeOffsetProp.Equals(queryTarget.DateTimeOffsetProp)) .FirstOrDefault(); Assert.Null(itemFromDb); } [Fact] public void ThrowsWhenValueNotConvertibleToComparandType() { var queryTarget = new QueryTarget { Id = System.Guid.NewGuid() }; theSession.Store(queryTarget); theSession.SaveChanges(); object notInt = "not int"; Assert.Throws<BadLinqExpressionException>(() => { theSession.Query<QueryTarget>() .Where(x => !x.IntProp.Equals(notInt)) .FirstOrDefault(); }); } public class TestData : IEnumerable<object[]> { private readonly List<object[]> _data = new List<object[]> { new object[] { Guid.NewGuid() }, new object[] { 0 }, new object[] { null }, new object[] { false }, new object[] { 32m }, new object[] { 0L }, new object[] { DateTime.UtcNow }, new object[] { DateTimeOffset.UtcNow }, }; public IEnumerator<object[]> GetEnumerator() { return _data.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } [Theory] [InlineData(PropertySearching.ContainmentOperator)] [InlineData(PropertySearching.JSON_Locator_Only)] public void NotEqualsGeneratesSameSqlAsNotEqualityOperatorWhenRegardlessOfPropertySearching(PropertySearching search) { StoreOptions(options => { options.Schema.For<QueryTarget>().PropertySearching(search); }); var queryTarget = new QueryTarget { IntProp = 1, LongProp = 2, DecimalProp = 1.1m, BoolProp = true, Id = Guid.NewGuid(), DateTimeProp = DateTime.UtcNow }; var queryEquals = theSession.Query<QueryTarget>() .Where(x => !x.IntProp.Equals(queryTarget.IntProp)) .Where(x => !x.LongProp.Equals(queryTarget.LongProp)) .Where(x => !x.DecimalProp.Equals(queryTarget.DecimalProp)) .Where(x => !x.BoolProp.Equals(queryTarget.BoolProp)) .Where(x => !x.Id.Equals(queryTarget.Id)) .Where(x => !x.DateTimeProp.Equals(queryTarget.DateTimeProp)) .Where(x => !x.DateTimeOffsetProp.Equals(queryTarget.DateTimeOffsetProp)) .ToCommand().CommandText; var queryEqualOperator = theSession.Query<QueryTarget>() .Where(x => x.IntProp != queryTarget.IntProp) .Where(x => x.LongProp != queryTarget.LongProp) .Where(x => x.DecimalProp != queryTarget.DecimalProp) .Where(x => x.BoolProp != queryTarget.BoolProp) .Where(x => x.Id != queryTarget.Id) .Where(x => x.DateTimeProp != queryTarget.DateTimeProp) .Where(x => x.DateTimeOffsetProp != queryTarget.DateTimeOffsetProp) .ToCommand().CommandText; Assert.Equal(queryEqualOperator, queryEquals); } [Theory] [ClassData(typeof(TestData))] public void NotEqualsGeneratesSameSqlAsNotEqualityOperator(object value) { string queryEquals = null, queryEqualOperator = null; switch (value) { case int intValue: queryEquals = theSession.Query<QueryTarget>() .Where(x => !x.IntProp.Equals(intValue)).ToCommand().CommandText; queryEqualOperator = theSession.Query<QueryTarget>() .Where(x => x.IntProp != intValue).ToCommand().CommandText; break; case Guid guidValue: queryEquals = theSession.Query<QueryTarget>() .Where(x => !x.Id.Equals(guidValue)).ToCommand().CommandText; queryEqualOperator = theSession.Query<QueryTarget>() .Where(x => x.Id != guidValue).ToCommand().CommandText; break; case decimal decimalValue: queryEquals = theSession.Query<QueryTarget>() .Where(x => !x.DecimalProp.Equals(decimalValue)).ToCommand().CommandText; queryEqualOperator = theSession.Query<QueryTarget>() .Where(x => x.DecimalProp != decimalValue).ToCommand().CommandText; break; case long longValue: queryEquals = theSession.Query<QueryTarget>() .Where(x => !x.LongProp.Equals(longValue)).ToCommand().CommandText; queryEqualOperator = theSession.Query<QueryTarget>() .Where(x => x.LongProp != longValue).ToCommand().CommandText; break; case DateTime dateTimeValue: queryEquals = theSession.Query<QueryTarget>() .Where(x => !x.DateTimeProp.Equals(dateTimeValue)).ToCommand().CommandText; queryEqualOperator = theSession.Query<QueryTarget>() .Where(x => x.DateTimeProp != dateTimeValue).ToCommand().CommandText; break; case DateTimeOffset dateTimeOffsetValue: queryEquals = theSession.Query<QueryTarget>() .Where(x => !x.DateTimeOffsetProp.Equals(dateTimeOffsetValue)).ToCommand().CommandText; queryEqualOperator = theSession.Query<QueryTarget>() .Where(x => x.DateTimeOffsetProp != dateTimeOffsetValue).ToCommand().CommandText; break; // Null default: queryEquals = theSession.Query<QueryTarget>() .Where(x => !x.BoolProp.Equals(null)).ToCommand().CommandText; queryEqualOperator = theSession.Query<QueryTarget>() #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' .Where(x => x.BoolProp != null).ToCommand().CommandText; #pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' break; } Assert.Equal(queryEqualOperator, queryEquals); } } }
33.1133
133
0.690717
[ "MIT" ]
Crown0815/marten
src/Marten.Testing/Linq/SimpleNotEqualsParserTests.cs
6,724
C#
using System; using Microsoft.AspNet.Identity; using Microsoft.Owin; using Microsoft.Owin.Security.Cookies; using Microsoft.Owin.Security.OAuth; using Owin; using FreeBird.Infrastructure.Core; using FreeBird.Infrastructure.OAuth; using SimpleSSO.Code.OAuth; using static SimpleSSO.Setting; namespace SimpleSSO { public partial class Startup { public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; } public static string PublicClientId { get; private set; } // 有关配置身份验证的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkId=301864 public void ConfigureAuth(IAppBuilder app) { // 将数据库上下文和用户管理器配置为对每个请求使用单个实例 // 使应用程序可以使用 Cookie 来存储已登录用户的信息 // 并使用 Cookie 来临时存储有关使用第三方登录提供程序登录的用户的信息 app.UseCookieAuthentication(new CookieAuthenticationOptions() { CookieName = "SimpleSSOLoginData", AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/OAuth/Login") }); // 针对基于 OAuth 的流配置应用程序 OAuthOptions = EngineContext.Current.Resolve<OAuthAuthorizationServerOptions>(); // 使应用程序可以使用不记名令牌来验证用户身份 app.UseOAuthBearerTokens(OAuthOptions); } } }
31.452381
92
0.678274
[ "Apache-2.0" ]
stonysong/SimpleSSO
src/SimpleSSO/App_Start/Startup.Auth.cs
1,575
C#
using esencialAdmin.Data.Models; using System; using System.Linq; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Identity; using esencialAdmin.Data; using esencialAdmin.Models.EmployeeViewModels; using System.Collections.Generic; namespace esencialAdmin.Services { public class EmployeeService : IEmployeeService { protected readonly esencialAdminContext _context; private readonly UserManager<ApplicationUser> _userManager; public EmployeeService( esencialAdminContext context, UserManager<ApplicationUser> userManager) { _context = context; _userManager = userManager; } public async System.Threading.Tasks.Task<bool> deleteEmployee(string username) { try { await _userManager.UpdateSecurityStampAsync(await _userManager.FindByNameAsync(username)); await _userManager.DeleteAsync(await _userManager.FindByNameAsync(username)); return true; } catch (Exception ex) { return false; } } public async System.Threading.Tasks.Task<bool> unlockEmployee(string username) { try { await _userManager.SetLockoutEndDateAsync(await _userManager.FindByNameAsync(username), DateTimeOffset.MinValue); await _userManager.ResetAccessFailedCountAsync(await _userManager.FindByNameAsync(username)); return true; } catch (Exception ex) { return false; } } public JsonResult loadEmployeeDataTable(HttpRequest Request) { try { var draw = Request.Form["draw"].FirstOrDefault(); // Skiping number of Rows count var start = Request.Form["start"].FirstOrDefault(); // Paging Length 10,20 var length = Request.Form["length"].FirstOrDefault(); // Sort Column Name var columnIndex = Request.Form["order[0][column]"].ToString(); // var sortColumn = Request.Form["columns[" + Request.Form["order[0][column]"].FirstOrDefault() + "][name]"].FirstOrDefault(); string sortColumn = Request.Form[$"columns[{columnIndex}][data]"].ToString(); var sortDirection = Request.Form["order[0][dir]"].ToString(); // Sort Column Direction ( asc ,desc) var sortColumnDirection = Request.Form["order[0][dir]"].FirstOrDefault(); // Search Value from (Search box) var searchValue = Request.Form["search[value]"].FirstOrDefault(); //Paging Size (10,20,50,100) int pageSize = length != null ? Convert.ToInt32(length) : 0; int skip = start != null ? Convert.ToInt32(start) : 0; int recordsTotal = 0; // Getting all Customer data var employeeData = (from tempemployee in _context.AspNetUsers select new { firstName = tempemployee.FirstName, lastName= tempemployee.LastName, username = tempemployee.UserName, role = tempemployee.AspNetUserRoles.FirstOrDefault().Role.Name }); //Sorting if (!(string.IsNullOrEmpty(sortColumn) && string.IsNullOrEmpty(sortColumnDirection))) { employeeData = employeeData.OrderBy(sortColumn + ' ' + sortColumnDirection); } //Search if (!string.IsNullOrEmpty(searchValue)) { employeeData = employeeData.Where(m => m.firstName.StartsWith(searchValue) || m.lastName.StartsWith(searchValue) || m.username.StartsWith(searchValue) || m.role.StartsWith(searchValue)); } //total number of rows count recordsTotal = employeeData.Count(); //Paging var data = employeeData.Skip(skip).Take(pageSize).ToList(); //Returning Json Data return new JsonResult(new { draw = draw, recordsFiltered = recordsTotal, recordsTotal = recordsTotal, data = data }); } catch (Exception ex) { return null; } } public EmployeeEditViewModel loadEmployeeEditModel(string username) { try { var applicationUser = _context.AspNetUsers.Where(x => x.UserName == username).FirstOrDefault(); if (applicationUser == null) { return null; } EmployeeEditViewModel employeeEditViewModel = new EmployeeEditViewModel { FirstName = applicationUser.FirstName, LastName = applicationUser.LastName, Email = applicationUser.Email, currentEmail = applicationUser.UserName, }; if(applicationUser.LockoutEnd > DateTime.Now) { employeeEditViewModel.isLocked = true; } employeeEditViewModel.EmployeeRoles = getAvailableRoles(); string role = _context.AspNetUserRoles.Where(x => x.UserId == applicationUser.Id).Select(y => y.Role.Name).FirstOrDefault(); if (role != null) { employeeEditViewModel.Role = role; } return employeeEditViewModel; } catch(Exception ex) { return null; } } public async System.Threading.Tasks.Task<bool> updateEmployee(EmployeeEditViewModel employeeToUpdate) { try { var user = await _userManager.FindByNameAsync(employeeToUpdate.currentEmail); if (user == null) { return false; } var email = user.Email; if (employeeToUpdate.Email != employeeToUpdate.currentEmail) { var setEmailResult = await _userManager.SetEmailAsync(user, employeeToUpdate.Email); if (!setEmailResult.Succeeded) { throw new ApplicationException($"Unexpected error occurred setting email for user with ID '{user.Id}'."); } var setUserNameResult = await _userManager.SetUserNameAsync(user, employeeToUpdate.Email); if (!setEmailResult.Succeeded) { await _userManager.SetEmailAsync(user, user.UserName); throw new ApplicationException($"Unexpected error occurred setting email for user with ID '{user.Id}'."); } } var employeeToEdit = this._context.AspNetUsers .Where(c => c.UserName == employeeToUpdate.Email) .FirstOrDefault(); if (employeeToEdit == null) { return false; } employeeToEdit.FirstName = employeeToUpdate.FirstName; employeeToEdit.LastName = employeeToUpdate.LastName; this._context.SaveChanges(); string role = _context.AspNetUserRoles.Where(x => x.UserId == user.Id).Select(y => y.Role.Name).FirstOrDefault(); if (role != employeeToUpdate.Role) { await _userManager.RemoveFromRoleAsync(user,role); await _userManager.AddToRoleAsync(user, employeeToUpdate.Role); } return true; } catch (Exception ex) { return false; } } public List<EmployeeRolesViewModel> getAvailableRoles() { List<EmployeeRolesViewModel> roleList = new List<EmployeeRolesViewModel>(); foreach (AspNetRoles role in _context.AspNetRoles) { roleList.Add(new EmployeeRolesViewModel { Id = role.Name, Role = role.Name }); } return roleList; } public bool isUsernameUnique(string username) { return !_context.AspNetUsers.Any(x => x.UserName == username); } } }
38.612069
206
0.524671
[ "Apache-2.0" ]
Che4ter/PAWI
src/esencialAdmin/Services/EmployeeService.cs
8,960
C#
using Microsoft.AspNetCore.Mvc.Formatters; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using System; using System.Threading.Tasks; using Timeline.Models; namespace Timeline.Formatters { /// <summary> /// Formatter that reads body as byte data. /// </summary> public class ByteDataInputFormatter : InputFormatter { /// <summary> /// /// </summary> public ByteDataInputFormatter() { SupportedMediaTypes.Add(MimeTypes.ImagePng); SupportedMediaTypes.Add(MimeTypes.ImageJpeg); SupportedMediaTypes.Add(MimeTypes.ImageGif); SupportedMediaTypes.Add(MimeTypes.ImageWebp); SupportedMediaTypes.Add(MimeTypes.TextPlain); SupportedMediaTypes.Add(MimeTypes.TextMarkdown); } /// <inheritdoc/> public override bool CanRead(InputFormatterContext context) { if (context == null) throw new ArgumentNullException(nameof(context)); if (context.ModelType == typeof(ByteData)) return true; return false; } /// <inheritdoc/> public override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context) { var request = context.HttpContext.Request; var contentLength = request.ContentLength; var logger = context.HttpContext.RequestServices.GetRequiredService<ILogger<ByteDataInputFormatter>>(); if (request.ContentType is null) { logger.LogInformation("Failed to read body as bytes. Content-Type is not set."); return await InputFormatterResult.FailureAsync(); } if (contentLength == null) { logger.LogInformation("Failed to read body as bytes. Content-Length is not set."); return await InputFormatterResult.FailureAsync(); } if (contentLength == 0) { logger.LogInformation("Failed to read body as bytes. Content-Length is 0."); return await InputFormatterResult.FailureAsync(); } var bodyStream = request.Body; var data = new byte[contentLength.Value]; var bytesRead = await bodyStream.ReadAsync(data); if (bytesRead != contentLength) { logger.LogInformation("Failed to read body as bytes. Actual length of body is smaller than Content-Length."); return await InputFormatterResult.FailureAsync(); } var extraByte = new byte[1]; if (await bodyStream.ReadAsync(extraByte) != 0) { logger.LogInformation("Failed to read body as bytes. Actual length of body is greater than Content-Length."); return await InputFormatterResult.FailureAsync(); } return await InputFormatterResult.SuccessAsync(new ByteData(data, request.ContentType)); } } }
36.482759
126
0.594833
[ "MIT" ]
crupest/Timeline
BackEnd/Timeline/Formatters/ByteDataInputFormatter.cs
3,176
C#
using AnnoSavegameViewer.Serialization.Core; using System.Collections.Generic; namespace AnnoSavegameViewer.Structures.Savegame.Generated { public class LogisticNodeTransporters { [BinaryContent(Name = "None", NodeType = BinaryContentTypes.Attribute)] public List<object> None { get; set; } [BinaryContent(Name = "None", NodeType = BinaryContentTypes.Node)] public List<LogisticNodeTransportersList> LogisticNodeTransportersList { get; set; } } }
31.4
88
0.770701
[ "MIT" ]
brumiros/AnnoSavegameViewer
AnnoSavegameViewer/Structures/Savegame/Generated/Content/LogisticNodeTransporters.cs
471
C#
using System; using System.Xml.Serialization; using System.Collections.Generic; // ======================================================= /// <author> /// Simon-Pierre Plante ([email protected]) /// </author> // ======================================================= namespace PNP.Deployer.ExtensibilityProviders.SSOM { #region SiteFieldsConfigurationData [Serializable()] [XmlRoot(ElementName = "ProviderConfiguration", Namespace = "http://PNP.Deployer/ProviderConfiguration")] public class SiteFieldsConfigurationData { [XmlArray("Fields")] [XmlArrayItem("Field", typeof(Field))] public List<Field> Fields { get; set; } } #endregion #region Field [Serializable()] public class Field { [XmlAttribute("Name")] public string Name { get; set; } [XmlArray("TitleResources")] [XmlArrayItem("TitleResource", typeof(TitleResource))] public List<TitleResource> TitleResources { get; set; } } #endregion #region TitleResource [Serializable()] public class TitleResource { [XmlAttribute("LCID")] public int LCID { get; set; } [XmlAttribute("Value")] public string Value { get; set; } } #endregion }
22.473684
109
0.575332
[ "MIT" ]
AnouckF/PnP
Samples/Provisioning.PnPDeployer.Console/PNP.Deployer.ExtensibilityProviders.SSOM/Classes/Serialization/SiteFieldsConfigurationData.cs
1,283
C#
// Copyright (c) rubicon IT GmbH, www.rubicon.eu // // See the NOTICE file distributed with this work for additional information // regarding copyright ownership. rubicon licenses this file to you under // the Apache License, Version 2.0 (the "License"); you may not use this // file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations // under the License. // using System; using System.Linq.Expressions; using JetBrains.Annotations; namespace Remotion.Linq.Clauses { /// <summary> /// Common interface for from clauses (<see cref="AdditionalFromClause"/> and <see cref="MainFromClause"/>). From clauses define query sources that /// provide data items to the query which are filtered, ordered, projected, or otherwise processed by the following clauses. /// </summary> public interface IFromClause : IClause, IQuerySource { /// <summary> /// The expression generating the data items for this from clause. /// </summary> Expression FromExpression { get; } /// <summary> /// Copies the <paramref name="source"/>'s attributes, i.e. the <see cref="IQuerySource.ItemName"/>, <see cref="IQuerySource.ItemType"/>, and /// <see cref="FromExpression"/>. /// </summary> /// <param name="source"></param> void CopyFromSource ([NotNull] IFromClause source); } }
40.5
149
0.712522
[ "ECL-2.0", "Apache-2.0" ]
biohazard999/Relinq
Core/Clauses/IFromClause.cs
1,701
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace IOT_Sensors { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new OpenCon()); } } }
22.26087
65
0.613281
[ "MIT" ]
yashen97/IOT
IOT_Sensors/IOT_Sensors/Program.cs
514
C#
// This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. // // To add a suppression to this file, right-click the message in the // Error List, point to "Suppress Message(s)", and click // "In Project Suppression File". // You do not need to add suppressions to this file manually. [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue", Scope = "type", Target = "CommandLine.ArgumentType")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1014:MarkAssembliesWithClsCompliant")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Scope = "member", Target = "CommandLine.Parser.#GetConsoleWindowWidth()")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Scope = "member", Target = "CommandLine.Parser+Argument.#ParseValue(System.Type,System.String,System.Object&)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Scope = "member", Target = "CommandLine.Parser.#LexFileArguments(System.String,System.String[]&)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1053:StaticHolderTypesShouldNotHaveConstructors", Scope = "type", Target = "ConsensusUtil.Program")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass", Scope = "member", Target = "CommandLine.Parser.#GetConsoleScreenBufferInfo(System.Int32,CommandLine.Parser+CONSOLE_SCREEN_BUFFER_INFO&)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass", Scope = "member", Target = "CommandLine.Parser.#GetStdHandle(System.Int32)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Scope = "member", Target = "CommandLine.Parser.#IndexOf(System.Text.StringBuilder,System.Char,System.Int32)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Scope = "member", Target = "CommandLine.Parser.#LastIndexOf(System.Text.StringBuilder,System.Char,System.Int32)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "1", Scope = "member", Target = "CommandLine.Parser.#ParseArguments(System.String[],System.Object,CommandLine.ErrorReporter)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "1", Scope = "member", Target = "CommandLine.Parser.#ParseArgumentsWithUsage(System.String[],System.Object)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Scope = "member", Target = "CommandLine.Parser.#.ctor(System.Type,CommandLine.ErrorReporter)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "System.Console.WriteLine(System.String,System.Object)", Scope = "member", Target = "ConsensusUtil.ConsensusArguments.#GenerateConsensus()")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "CommandLine.ErrorReporter.Invoke(System.String)", Scope = "member", Target = "CommandLine.Parser+Argument.#ReportBadArgumentValue(System.String)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "CommandLine.ErrorReporter.Invoke(System.String)", Scope = "member", Target = "CommandLine.Parser+Argument.#ReportDuplicateArgumentValue(System.String)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "CommandLine.ErrorReporter.Invoke(System.String)", Scope = "member", Target = "CommandLine.Parser+Argument.#ReportMissingRequiredArgument()")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "CommandLine.ErrorReporter.Invoke(System.String)", Scope = "member", Target = "CommandLine.Parser+Argument.#SetValue(System.String,System.Object)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "CommandLine.ErrorReporter.Invoke(System.String)", Scope = "member", Target = "CommandLine.Parser.#LexFileArguments(System.String,System.String[]&)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "CommandLine.ErrorReporter.Invoke(System.String)", Scope = "member", Target = "CommandLine.Parser.#ReportUnrecognizedArgument(System.String)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Double.Parse(System.String)", Scope = "member", Target = "CommandLine.Parser+Argument.#ParseValue(System.Type,System.String,System.Object&)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.Parse(System.String)", Scope = "member", Target = "CommandLine.Parser+Argument.#ParseValue(System.Type,System.String,System.Object&)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.String.Format(System.String,System.Object)", Scope = "member", Target = "ConsensusUtil.IO.DeltaAlignmentParser.#Parse()")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.String.Format(System.String,System.Object)", Scope = "member", Target = "CommandLine.Parser+Argument.#ReportMissingRequiredArgument()")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.String.Format(System.String,System.Object)", Scope = "member", Target = "CommandLine.Parser+Argument.#SetValue(System.String,System.Object)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.String.Format(System.String,System.Object)", Scope = "member", Target = "CommandLine.Parser.#LexFileArguments(System.String,System.String[]&)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.String.Format(System.String,System.Object)", Scope = "member", Target = "CommandLine.Parser.#ReportUnrecognizedArgument(System.String)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.String.Format(System.String,System.Object,System.Object)", Scope = "member", Target = "CommandLine.Parser+Argument.#ReportBadArgumentValue(System.String)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.String.Format(System.String,System.Object,System.Object)", Scope = "member", Target = "CommandLine.Parser+Argument.#ReportDuplicateArgumentValue(System.String)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.String.Format(System.String,System.Object,System.Object)", Scope = "member", Target = "CommandLine.Parser.#LexFileArguments(System.String,System.String[]&)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1500:VariableNamesShouldNotMatchFieldNames", MessageId = "arguments", Scope = "member", Target = "CommandLine.Parser.#LexFileArguments(System.String,System.String[]&)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1500:VariableNamesShouldNotMatchFieldNames", MessageId = "field", Scope = "member", Target = "CommandLine.Parser+Argument.#SyntaxHelp")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods", Scope = "member", Target = "CommandLine.ArgumentAttribute.#Type")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "field", Scope = "member", Target = "CommandLine.Parser.#DefaultValue(CommandLine.ArgumentAttribute,System.Reflection.FieldInfo)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "field", Scope = "member", Target = "CommandLine.Parser.#HelpText(CommandLine.ArgumentAttribute,System.Reflection.FieldInfo)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "rc", Scope = "member", Target = "CommandLine.Parser.#GetConsoleWindowWidth()")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "ConsensusUtil.Program.#RemoveCommandLine(System.String[])")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1813:AvoidUnsealedAttributes", Scope = "type", Target = "CommandLine.ArgumentAttribute")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1813:AvoidUnsealedAttributes", Scope = "type", Target = "CommandLine.DefaultArgumentAttribute")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1820:TestForEmptyStringsUsingStringLength", Scope = "member", Target = "CommandLine.ArgumentAttribute.#LongName")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1820:TestForEmptyStringsUsingStringLength", Scope = "member", Target = "CommandLine.Parser+Argument.#.ctor(CommandLine.ArgumentAttribute,System.Reflection.FieldInfo,CommandLine.ErrorReporter)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields", Scope = "member", Target = "ConsensusUtil.ConsensusArguments.#Help")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1824:MarkAssembliesWithNeutralResourcesLanguage")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", MessageId = "0", Scope = "member", Target = "CommandLine.Parser.#GetConsoleScreenBufferInfo(System.Int32,CommandLine.Parser+CONSOLE_SCREEN_BUFFER_INFO&)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", MessageId = "return", Scope = "member", Target = "CommandLine.Parser.#GetStdHandle(System.Int32)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Scope = "member", Target = "ConsensusUtil.ConsensusArguments.#GenerateConsensus()")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA2210:AssembliesShouldHaveValidStrongNames")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", MessageId = "CommandLine.Parser.GetConsoleScreenBufferInfo(System.Int32,CommandLine.Parser+CONSOLE_SCREEN_BUFFER_INFO@)", Scope = "member", Target = "CommandLine.Parser.#GetConsoleWindowWidth()")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "CommandLine.Parser.#IsValidElementType(System.Type)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Scope = "member", Target = "ConsensusUtil.ConsensusArguments.#Parse(System.String)")]
207.04918
309
0.808076
[ "Apache-2.0" ]
jdm7dv/Microsoft-Biology-Foundation
archive/Changesets/mbf/Source/Tools/ConsensusUtil/GlobalSuppressions.cs
12,632
C#
// lookup.cs // // Copyright 2010 Microsoft Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using NUglify.Helpers; using NUglify.JavaScript.Visitors; namespace NUglify.JavaScript.Syntax { public enum ReferenceType { Variable, Function, Constructor } public sealed class LookupExpression : Expression, INameReference, IRenameable { public JSVariableField VariableField { get; set; } public bool IsGenerated { get; set; } public ReferenceType RefType { get; set; } public string Name { get; set; } public bool IsAssignment { get { var isAssign = false; // see if our parent is a binary operator. var binaryOp = Parent as BinaryExpression; if (binaryOp != null) { // if we are, we are an assignment lookup if the binary operator parent is an assignment // and we are the left-hand side. isAssign = binaryOp.IsAssign && binaryOp.Operand1 == this; } else { // not a binary op -- but we might still be an "assignment" if we are an increment or decrement operator. var unaryOp = Parent as UnaryExpression; isAssign = unaryOp != null && (unaryOp.OperatorToken == JSToken.Increment || unaryOp.OperatorToken == JSToken.Decrement); if (!isAssign) { // AND if we are the variable of a for-in statement, we are an "assignment". // (if the forIn variable is a var, then it wouldn't be a lookup, so we don't have to worry about // going up past a var-decl intermediate node) var forIn = Parent as ForInStatement; isAssign = forIn != null && this == forIn.Variable; } } return isAssign; } } public AstNode AssignmentValue { get { AstNode value = null; // see if our parent is a binary operator. var binaryOp = Parent as BinaryExpression; if (binaryOp != null) { // the parent is a binary operator. If it is an assignment operator // (not including any of the op-assign which depend on an initial value) // then the value we are assigning is the right-hand side of the = operator. value = binaryOp.OperatorToken == JSToken.Assign && binaryOp.Operand1 == this ? binaryOp.Operand2 : null; } return value; } } /// <summary> /// Gets the original name of the identifier, before any renaming /// </summary> public string OriginalName { get { return Name; } } /// <summary> /// Gets whether or not the item was renamed /// </summary> public bool WasRenamed { get { return VariableField.IfNotNull(f => !f.CrunchedName.IsNullOrWhiteSpace()); } } public LookupExpression(SourceContext context) : base(context) { RefType = ReferenceType.Variable; } public override void Accept(IVisitor visitor) { visitor?.Visit(this); } public override bool IsEquivalentTo(AstNode otherNode) { // this one is tricky. If we have a field assigned, then we are equivalent if the // field is the same as the other one. If there is no field, then just check the name var otherLookup = otherNode as LookupExpression; if (otherLookup != null) { if (VariableField != null) { // the variable fields should be the same return VariableField.IsSameField(otherLookup.VariableField); } else { // otherwise the names should be identical return string.CompareOrdinal(Name, otherLookup.Name) == 0; } } // if we get here, we're not equivalent return false; } internal override string GetFunctionGuess(AstNode target) { // return the source name return Name; } //code in parser relies on this.name being returned from here public override String ToString() { return Name; } #region INameReference Members public ActivationObject VariableScope { get { // get the enclosing scope from the node, but that might be // a block scope -- we only want variable scopes: functions or global. // so walk up until we find one. var enclosingScope = this.EnclosingScope; while (enclosingScope is BlockScope) { enclosingScope = enclosingScope.Parent; } return enclosingScope; } } #endregion } }
33.198895
125
0.530205
[ "Apache-2.0" ]
DogBitesMe/NUglify
src/NUglify/JavaScript/Syntax/LookupExpression.cs
6,009
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("Task04")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Task04")] [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("191d19cb-d07e-4d0f-9186-2c682c7aea1f")] // 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")]
37.432432
84
0.74296
[ "MIT" ]
SHAMMY1/Telerik-Academy-2016
CSharp-Advanced/Exam/Exam/Task04/Properties/AssemblyInfo.cs
1,388
C#
using System; namespace PM.BO.Exceptions { public class TKSFILE_INVALID_RECORD_ERR : Exception { private const string _message = "An invalid S Record type was found."; private const short Code = -10305; public TKSFILE_INVALID_RECORD_ERR() : base(_message) { } public TKSFILE_INVALID_RECORD_ERR(string message) : base (_message + "\nAdditional Information: " + message) { } } }
26.133333
114
0.739796
[ "BSD-2-Clause" ]
addixon/ErgCompetePM
PM.BO/Exceptions/TKSFILE_INVALID_RECORD_ERR.cs
394
C#
// This is an open source non-commercial project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com /* EmbeddedField.cs -- работа со встроенными полями * Ars Magna project, http://arsmagna.ru * ------------------------------------------------------- * Status: poor */ #region Using directives using System; using System.Collections.Generic; using AM.Collections; using AM.Logging; using CodeJam; using JetBrains.Annotations; using MoonSharp.Interpreter; #endregion namespace ManagedIrbis { /// <summary> /// Работа со встроенными полями. /// </summary> [PublicAPI] [MoonSharpUserData] public static class EmbeddedField { #region Constants /// <summary> /// Код по умолчанию, используемый для встраивания полей. /// </summary> public const char DefaultCode = '1'; #endregion #region Public methods /// <summary> /// Получение встроенных полей. /// </summary> [NotNull] [ItemNotNull] public static RecordField[] GetEmbeddedFields ( [NotNull] this RecordField field ) { Code.NotNull(field, "field"); return GetEmbeddedFields ( field.SubFields, DefaultCode ); } /// <summary> /// Get embedded fields. /// </summary> [NotNull] [ItemNotNull] public static RecordField[] GetEmbeddedFields ( [NotNull] IEnumerable<SubField> subfields, char sign ) { Code.NotNull(subfields, "subfields"); LocalList<RecordField> result = new LocalList<RecordField>(); RecordField found = null; foreach (SubField subField in subfields) { if (subField.Code == sign) { if (!ReferenceEquals(found, null)) { result.Add(found); } string value = subField.Value; if (string.IsNullOrEmpty(value)) { Log.Error ( "EmbeddedField::GetEmbeddedFields: " + "bad format" ); throw new FormatException(); } string tag = value.Substring(0, 3); found = new RecordField(tag); if (tag.StartsWith("00") && value.Length > 3 ) { found.Value = value.Substring(3); } } else { if (!ReferenceEquals(found, null)) { found.AddSubField(subField.Code, subField.Value); } } } if (!ReferenceEquals(found, null)) { result.Add(found); } return result.ToArray(); } /// <summary> /// Получение встроенных полей с указанным тегом. /// </summary> [NotNull] [ItemNotNull] public static RecordField[] GetEmbeddedField ( [NotNull] this RecordField field, int tag ) { Code.NotNull(field, "field"); RecordField[] result = GetEmbeddedFields ( field.SubFields, DefaultCode ) .GetField(tag); return result; } #endregion } }
25.756579
84
0.440358
[ "MIT" ]
amironov73/ManagedClient.45
Source/Classic/Libs/ManagedIrbis/Source/EmbeddedField.cs
4,075
C#
using Laser.Orchard.NwazetIntegration.Models; using Laser.Orchard.Policy.Models; using Nwazet.Commerce.Models; using Nwazet.Commerce.Services; using Orchard.ContentManagement; using Orchard.Localization; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Web; using System.Xml.Linq; namespace Laser.Orchard.NwazetIntegration.Services { public class CheckoutPoliciesOrderAdditionalInformationProvider : BaseOrderAdditionalInformationProvider { private readonly ICheckoutPoliciesService _checkoutPoliciesService; private readonly IContentManager _contentManager; public CheckoutPoliciesOrderAdditionalInformationProvider( ICheckoutPoliciesService checkoutPoliciesService, IContentManager contentManager) { _checkoutPoliciesService = checkoutPoliciesService; _contentManager = contentManager; T = NullLocalizer.Instance; } public Localizer T { get; set; } public override IEnumerable<XElement> PrepareAdditionalInformation(OrderContext context) { // add information on the policies the user had accepted var workContext = context.WorkContextAccessor.GetContext(); var user = workContext.CurrentUser; var culture = workContext.CurrentCulture; var policies = _checkoutPoliciesService.CheckoutPoliciesForUser(user, culture); foreach (var policy in policies) { var policyPart = policy.PolicyText != null ? policy.PolicyText : _contentManager.Get<PolicyTextInfoPart>(policy.PolicyTextId); var policyXElement = new XElement(CheckoutPolicySettingsPart.OrderXElementName) .With(policy) .ToAttr(p => p.AnswerId) .ToAttr(p => p.PolicyTextId) .ToAttr(p => p.AnswerDate) .ToAttr(p => p.OldAccepted) .ToAttr(p => p.Accepted) .ToAttr(p => p.UserId); // we save the "state" of the PolicyTextInfoPart policyXElement.Element .AddEl(new XElement("PolicyTextInfoPart") .With(policyPart) .ToAttr(p => p.UserHaveToAccept) .ToAttr(p => p.Priority) .ToAttr(p => p.PolicyType) .ToAttr(p => p.AddPolicyToRegistration)); // we should also save the version number of the contentitem for the policy policyXElement.Element.SetAttributeValue("VersionNumber", policyPart.ContentItem.Version); yield return policyXElement; } } } }
41.411765
106
0.628551
[ "Apache-2.0" ]
INVA-Spa/Laser.Orchard.Platform
src/Modules/Laser.Orchard.NwazetIntegration/Services/CheckoutPoliciesOrderAdditionalInformationProvider.cs
2,818
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; namespace AoC.Advent2018.Test { [TestCategory("2018")] [TestClass] public class Day02Test { string input = Util.GetInput<Day02>(); [TestCategory("Test")] [DataRow("abcdef,bababc,abbcde,abcccd,aabcdd,abcdee,ababab", 12)] [DataTestMethod] public void Inventory01Test(string input, int expected) { Assert.AreEqual(expected, Advent2018.Day02.Part1(input)); } [TestCategory("Test")] [DataRow("abcde,fghij,klmno,pqrst,fguij,axcye,wvxyz", "fgij")] [DataTestMethod] public void Inventory02Test(string input, string expected) { Assert.AreEqual(expected, Advent2018.Day02.Part2(input)); } [TestCategory("Regression")] [DataTestMethod] public void Inventory_Part1_Regression() { Assert.AreEqual(9139, Day02.Part1(input)); } [TestCategory("Regression")] [DataTestMethod] public void Inventory_Part2_Regression() { Assert.AreEqual("uqcidadzwtnhsljvxyobmkfyr", Day02.Part2(input)); } } }
27.534884
77
0.611486
[ "MIT" ]
benjymous/AdventOfCode
test/Advent2018/Day02Test.cs
1,184
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.V20180801 { public static class GetExpressRouteCrossConnectionPeering { /// <summary> /// Peering in an ExpressRoute Cross Connection resource. /// </summary> public static Task<GetExpressRouteCrossConnectionPeeringResult> InvokeAsync(GetExpressRouteCrossConnectionPeeringArgs args, InvokeOptions? options = null) => Pulumi.Deployment.Instance.InvokeAsync<GetExpressRouteCrossConnectionPeeringResult>("azure-nextgen:network/v20180801:getExpressRouteCrossConnectionPeering", args ?? new GetExpressRouteCrossConnectionPeeringArgs(), options.WithVersion()); } public sealed class GetExpressRouteCrossConnectionPeeringArgs : Pulumi.InvokeArgs { /// <summary> /// The name of the ExpressRouteCrossConnection. /// </summary> [Input("crossConnectionName", required: true)] public string CrossConnectionName { get; set; } = null!; /// <summary> /// The name of the peering. /// </summary> [Input("peeringName", required: true)] public string PeeringName { get; set; } = null!; /// <summary> /// The name of the resource group. /// </summary> [Input("resourceGroupName", required: true)] public string ResourceGroupName { get; set; } = null!; public GetExpressRouteCrossConnectionPeeringArgs() { } } [OutputType] public sealed class GetExpressRouteCrossConnectionPeeringResult { /// <summary> /// The Azure ASN. /// </summary> public readonly int AzureASN; /// <summary> /// A unique read-only string that changes whenever the resource is updated. /// </summary> public readonly string Etag; /// <summary> /// The GatewayManager Etag. /// </summary> public readonly string? GatewayManagerEtag; /// <summary> /// Resource ID. /// </summary> public readonly string? Id; /// <summary> /// The IPv6 peering configuration. /// </summary> public readonly Outputs.Ipv6ExpressRouteCircuitPeeringConfigResponse? Ipv6PeeringConfig; /// <summary> /// Gets whether the provider or the customer last modified the peering. /// </summary> public readonly string? LastModifiedBy; /// <summary> /// The Microsoft peering configuration. /// </summary> public readonly Outputs.ExpressRouteCircuitPeeringConfigResponse? MicrosoftPeeringConfig; /// <summary> /// Gets name of the resource that is unique within a resource group. This name can be used to access the resource. /// </summary> public readonly string? Name; /// <summary> /// The peer ASN. /// </summary> public readonly double? PeerASN; /// <summary> /// The peering type. /// </summary> public readonly string? PeeringType; /// <summary> /// The primary port. /// </summary> public readonly string PrimaryAzurePort; /// <summary> /// The primary address prefix. /// </summary> public readonly string? PrimaryPeerAddressPrefix; /// <summary> /// Gets the provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. /// </summary> public readonly string ProvisioningState; /// <summary> /// The secondary port. /// </summary> public readonly string SecondaryAzurePort; /// <summary> /// The secondary address prefix. /// </summary> public readonly string? SecondaryPeerAddressPrefix; /// <summary> /// The shared key. /// </summary> public readonly string? SharedKey; /// <summary> /// The peering state. /// </summary> public readonly string? State; /// <summary> /// The VLAN ID. /// </summary> public readonly int? VlanId; [OutputConstructor] private GetExpressRouteCrossConnectionPeeringResult( int azureASN, string etag, string? gatewayManagerEtag, string? id, Outputs.Ipv6ExpressRouteCircuitPeeringConfigResponse? ipv6PeeringConfig, string? lastModifiedBy, Outputs.ExpressRouteCircuitPeeringConfigResponse? microsoftPeeringConfig, string? name, double? peerASN, string? peeringType, string primaryAzurePort, string? primaryPeerAddressPrefix, string provisioningState, string secondaryAzurePort, string? secondaryPeerAddressPrefix, string? sharedKey, string? state, int? vlanId) { AzureASN = azureASN; Etag = etag; GatewayManagerEtag = gatewayManagerEtag; Id = id; Ipv6PeeringConfig = ipv6PeeringConfig; LastModifiedBy = lastModifiedBy; MicrosoftPeeringConfig = microsoftPeeringConfig; Name = name; PeerASN = peerASN; PeeringType = peeringType; PrimaryAzurePort = primaryAzurePort; PrimaryPeerAddressPrefix = primaryPeerAddressPrefix; ProvisioningState = provisioningState; SecondaryAzurePort = secondaryAzurePort; SecondaryPeerAddressPrefix = secondaryPeerAddressPrefix; SharedKey = sharedKey; State = state; VlanId = vlanId; } } }
33.032787
252
0.603474
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/Network/V20180801/GetExpressRouteCrossConnectionPeering.cs
6,045
C#
using RestEase.SampleWebApi.Contracts; using System.Net.Http; using System.Net.Http.Headers; namespace RestEase.SampleWebApi.Infrastructure { public class FileContentRequestBodySerializer : JsonRequestBodySerializer { public override HttpContent SerializeBody<T>(T body, RequestBodySerializerInfo info) { if (body is FileContent fileContent) { var content = new ByteArrayContent(fileContent.Content); content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-header") { FileName = $"\"{fileContent.FileName}\"" }; content.Headers.ContentType = new MediaTypeHeaderValue(fileContent.MimeType); return content; } return base.SerializeBody(body, info); } } }
32.545455
135
0.768156
[ "MIT" ]
BelyaevEvgeny/RestEase.Controllers.SourceGenerator
tests/RestEase.SampleWebApi/Infrastructure/FileContentRequestBodySerializer.cs
718
C#
/* Copyright 2015-2016 MongoDB Inc. * * 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.Threading; using System.Threading.Tasks; using FluentAssertions; using MongoDB.Bson.Serialization.Serializers; using MongoDB.Bson.TestHelpers.XunitExtensions; using MongoDB.Driver.Core; using MongoDB.Driver.Core.Bindings; using MongoDB.Driver.Core.TestHelpers.XunitExtensions; using MongoDB.Driver.Core.WireProtocol.Messages.Encoders; using MongoDB.Driver.Operations; using Xunit; namespace MongoDB.Driver.Tests.Operations { public class CurrentOpUsingCommandOperationTests { // private fields private DatabaseNamespace _adminDatabaseNamespace; private MessageEncoderSettings _messageEncoderSettings; // public methods public CurrentOpUsingCommandOperationTests() { _adminDatabaseNamespace = new DatabaseNamespace("admin"); _messageEncoderSettings = CoreTestConfiguration.MessageEncoderSettings; } [Fact] public void constructor_should_initialize_instance() { var result = new CurrentOpUsingCommandOperation(_adminDatabaseNamespace, _messageEncoderSettings); result.DatabaseNamespace.Should().Be(_adminDatabaseNamespace); result.MessageEncoderSettings.Should().BeEquivalentTo(_messageEncoderSettings); } [Fact] public void constructor_should_throw_when_databaseNamespace_is_null() { Action action = () => new CurrentOpUsingCommandOperation(null, _messageEncoderSettings); action.ShouldThrow<ArgumentNullException>().And.ParamName.Should().Be("databaseNamespace"); } [Fact] public void CreateOperation_should_return_expected_result() { var subject = new CurrentOpUsingCommandOperation(_adminDatabaseNamespace, _messageEncoderSettings); var result = subject.CreateOperation(); result.Command.Should().Be("{ currentOp : 1 }"); result.DatabaseNamespace.Should().BeSameAs(_adminDatabaseNamespace); result.MessageEncoderSettings.Should().BeSameAs(_messageEncoderSettings); result.ResultSerializer.Should().BeSameAs(BsonDocumentSerializer.Instance); } [SkippableFact] public void Execute_should_return_expected_result() { RequireServer.Where(minimumVersion: "3.1.2"); var subject = new CurrentOpUsingCommandOperation(_adminDatabaseNamespace, _messageEncoderSettings); using (var binding = new ReadPreferenceBinding(CoreTestConfiguration.Cluster, ReadPreference.PrimaryPreferred)) { var result = subject.Execute(binding, CancellationToken.None); result.Contains("inprog"); } } } }
37.931818
123
0.715099
[ "Apache-2.0" ]
joeenzminger/mongo-csharp-driver
tests/MongoDB.Driver.Legacy.Tests/Operations/CurrentOpUsingCommandOperation.cs
3,340
C#
//------------------------------------------------------------------------------ // <copyright file="OleDbStruct.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> // <owner current="true" primary="false">[....]</owner> //------------------------------------------------------------------------------ namespace System.Data.OleDb { using System; using System.Runtime.InteropServices; #if DEBUG using System.Diagnostics; using System.Globalization; using System.Text; #endif internal enum DBBindStatus { OK = 0, BADORDINAL = 1, UNSUPPORTEDCONVERSION = 2, BADBINDINFO = 3, BADSTORAGEFLAGS = 4, NOINTERFACE = 5, MULTIPLESTORAGE = 6 } #if false typedef struct tagDBPARAMBINDINFO { LPOLESTR pwszDataSourceType; LPOLESTR pwszName; DBLENGTH ulParamSize; DBPARAMFLAGS dwFlags; BYTE bPrecision; BYTE bScale; } #endif #if (WIN32 && !ARCH_arm) [StructLayoutAttribute(LayoutKind.Sequential, Pack = 2)] #else [StructLayoutAttribute(LayoutKind.Sequential, Pack = 8)] #endif internal struct tagDBPARAMBINDINFO { internal IntPtr pwszDataSourceType; internal IntPtr pwszName; internal IntPtr ulParamSize; internal Int32 dwFlags; internal Byte bPrecision; internal Byte bScale; #if DEBUG public override string ToString() { StringBuilder builder = new StringBuilder(); builder.Append("tagDBPARAMBINDINFO").Append(Environment.NewLine); if (IntPtr.Zero != pwszDataSourceType) { builder.Append("pwszDataSourceType =").Append(Marshal.PtrToStringUni(pwszDataSourceType)).Append(Environment.NewLine); } builder.Append("\tulParamSize =" + ulParamSize.ToInt64().ToString(CultureInfo.InvariantCulture)).Append(Environment.NewLine); builder.Append("\tdwFlags =0x" + dwFlags.ToString("X4", CultureInfo.InvariantCulture)).Append(Environment.NewLine); builder.Append("\tPrecision =" + bPrecision.ToString(CultureInfo.InvariantCulture)).Append(Environment.NewLine); builder.Append("\tScale =" + bScale.ToString(CultureInfo.InvariantCulture)).Append(Environment.NewLine); return builder.ToString(); } #endif } #if false typedef struct tagDBBINDING { DBORDINAL iOrdinal; DBBYTEOFFSET obValue; DBBYTEOFFSET obLength; DBBYTEOFFSET obStatus; ITypeInfo *pTypeInfo; DBOBJECT *pObject; DBBINDEXT *pBindExt; DBPART dwPart; DBMEMOWNER dwMemOwner; DBPARAMIO eParamIO; DBLENGTH cbMaxLen; DWORD dwFlags; DBTYPE wType; BYTE bPrecision; BYTE bScale; } #endif #if (WIN32 && !ARCH_arm) [StructLayoutAttribute(LayoutKind.Sequential, Pack = 2)] #else [StructLayoutAttribute(LayoutKind.Sequential, Pack = 8)] #endif internal sealed class tagDBBINDING { internal IntPtr iOrdinal; internal IntPtr obValue; internal IntPtr obLength; internal IntPtr obStatus; internal IntPtr pTypeInfo; internal IntPtr pObject; internal IntPtr pBindExt; internal Int32 dwPart; internal Int32 dwMemOwner; internal Int32 eParamIO; internal IntPtr cbMaxLen; internal Int32 dwFlags; internal Int16 wType; internal byte bPrecision; internal byte bScale; internal tagDBBINDING() { } #if DEBUG public override string ToString() { StringBuilder builder = new StringBuilder(); builder.Append("tagDBBINDING").Append(Environment.NewLine); builder.Append("\tOrdinal =" + iOrdinal.ToInt64().ToString(CultureInfo.InvariantCulture)).Append(Environment.NewLine); builder.Append("\tValueOffset =" + obValue.ToInt64().ToString(CultureInfo.InvariantCulture)).Append(Environment.NewLine); builder.Append("\tLengthOffset=" + obLength.ToInt64().ToString(CultureInfo.InvariantCulture)).Append(Environment.NewLine); builder.Append("\tStatusOffset=" + obStatus.ToInt64().ToString(CultureInfo.InvariantCulture)).Append(Environment.NewLine); builder.Append("\tMaxLength =" + cbMaxLen.ToInt64().ToString(CultureInfo.InvariantCulture)).Append(Environment.NewLine); builder.Append("\tDB_Type =" + ODB.WLookup(wType)).Append(Environment.NewLine); builder.Append("\tPrecision =" + bPrecision.ToString(CultureInfo.InvariantCulture)).Append(Environment.NewLine); builder.Append("\tScale =" + bScale.ToString(CultureInfo.InvariantCulture)).Append(Environment.NewLine); return builder.ToString(); } #endif } #if false typedef struct tagDBCOLUMNACCESS { void *pData; DBID columnid; DBLENGTH cbDataLen; DBSTATUS dwStatus; DBLENGTH cbMaxLen; DB_DWRESERVE dwReserved; DBTYPE wType; BYTE bPrecision; BYTE bScale; } #endif #if (WIN32 && !ARCH_arm) [StructLayoutAttribute(LayoutKind.Sequential, Pack = 2)] #else [StructLayoutAttribute(LayoutKind.Sequential, Pack = 8)] #endif internal struct tagDBCOLUMNACCESS { internal IntPtr pData; internal tagDBIDX columnid; internal IntPtr cbDataLen; internal Int32 dwStatus; internal IntPtr cbMaxLen; internal IntPtr dwReserved; internal Int16 wType; internal Byte bPrecision; internal Byte bScale; } #if false typedef struct tagDBID { /* [switch_is][switch_type] */ union { /* [case()] */ GUID guid; /* [case()] */ GUID *pguid; /* [default] */ /* Empty union arm */ } uGuid; DBKIND eKind; /* [switch_is][switch_type] */ union { /* [case()] */ LPOLESTR pwszName; /* [case()] */ ULONG ulPropid; /* [default] */ /* Empty union arm */ } uName; } #endif #if (WIN32 && !ARCH_arm) [StructLayoutAttribute(LayoutKind.Sequential, Pack = 2)] #else [StructLayoutAttribute(LayoutKind.Sequential, Pack = 8)] #endif internal struct tagDBIDX { internal Guid uGuid; internal Int32 eKind; internal IntPtr ulPropid; } #if (WIN32 && !ARCH_arm) [StructLayoutAttribute(LayoutKind.Sequential, Pack = 2)] #else [StructLayoutAttribute(LayoutKind.Sequential, Pack = 8)] #endif internal sealed class tagDBID { internal Guid uGuid; internal Int32 eKind; internal IntPtr ulPropid; } #if false typedef struct tagDBLITERALINFO { LPOLESTR pwszLiteralValue; LPOLESTR pwszInvalidChars; LPOLESTR pwszInvalidStartingChars; DBLITERAL lt; BOOL fSupported; ULONG cchMaxLen; } #endif #if (WIN32 && !ARCH_arm) [StructLayoutAttribute(LayoutKind.Sequential, Pack = 2)] #else [StructLayoutAttribute(LayoutKind.Sequential, Pack = 8)] #endif sealed internal class tagDBLITERALINFO { [MarshalAs(UnmanagedType.LPWStr)] internal String pwszLiteralValue = null; [MarshalAs(UnmanagedType.LPWStr)] internal String pwszInvalidChars = null; [MarshalAs(UnmanagedType.LPWStr)] internal String pwszInvalidStartingChars = null; internal Int32 it; internal Int32 fSupported; internal Int32 cchMaxLen; internal tagDBLITERALINFO() { } } #if false typedef struct tagDBPROPSET { /* [size_is] */ DBPROP *rgProperties; ULONG cProperties; GUID guidPropertySet; } #endif #if (WIN32 && !ARCH_arm) [StructLayoutAttribute(LayoutKind.Sequential, Pack = 2)] #else [StructLayoutAttribute(LayoutKind.Sequential, Pack = 8)] #endif sealed internal class tagDBPROPSET { internal IntPtr rgProperties; internal Int32 cProperties; internal Guid guidPropertySet; internal tagDBPROPSET() { } internal tagDBPROPSET(int propertyCount, Guid propertySet) { cProperties = propertyCount; guidPropertySet = propertySet; } } #if false typedef struct tagDBPROP { DBPROPID dwPropertyID; DBPROPOPTIONS dwOptions; DBPROPSTATUS dwStatus; DBID colid; VARIANT vValue; } #endif #if (WIN32 && !ARCH_arm) [StructLayoutAttribute(LayoutKind.Sequential, Pack = 2)] #else [StructLayoutAttribute(LayoutKind.Sequential, Pack = 8)] #endif sealed internal class tagDBPROP { internal Int32 dwPropertyID; internal Int32 dwOptions; internal OleDbPropertyStatus dwStatus; internal tagDBIDX columnid; // Variant [MarshalAs(UnmanagedType.Struct)] internal object vValue; internal tagDBPROP() { } internal tagDBPROP(int propertyID, bool required, object value) { dwPropertyID = propertyID; dwOptions = ((required) ? ODB.DBPROPOPTIONS_REQUIRED : ODB.DBPROPOPTIONS_OPTIONAL); vValue = value; } } #if false typedef struct tagDBPARAMS { void *pData; DB_UPARAMS cParamSets; HACCESSOR hAccessor; } #endif #if (WIN32 && !ARCH_arm) [StructLayoutAttribute(LayoutKind.Sequential, Pack = 2)] #else [StructLayoutAttribute(LayoutKind.Sequential, Pack = 8)] #endif sealed internal class tagDBPARAMS { internal IntPtr pData; internal Int32 cParamSets; internal IntPtr hAccessor; internal tagDBPARAMS() { } } #if false typedef struct tagDBCOLUMNINFO { LPOLESTR pwszName; ITypeInfo *pTypeInfo; DBORDINAL iOrdinal; DBCOLUMNFLAGS dwFlags; DBLENGTH ulColumnSize; DBTYPE wType; BYTE bPrecision; BYTE bScale; DBID columnid; } #endif #if (WIN32 && !ARCH_arm) [StructLayoutAttribute(LayoutKind.Sequential, Pack = 2)] #else [StructLayoutAttribute(LayoutKind.Sequential, Pack = 8)] #endif sealed internal class tagDBCOLUMNINFO { [MarshalAs(UnmanagedType.LPWStr)] internal String pwszName = null; //[MarshalAs(UnmanagedType.Interface)] internal IntPtr pTypeInfo = (IntPtr) 0; internal IntPtr iOrdinal = (IntPtr) 0; internal Int32 dwFlags = 0; internal IntPtr ulColumnSize = (IntPtr) 0; internal Int16 wType = 0; internal Byte bPrecision = 0; internal Byte bScale = 0; internal tagDBIDX columnid; internal tagDBCOLUMNINFO() { } #if DEBUG public override string ToString() { StringBuilder builder = new StringBuilder(); builder.Append("tagDBCOLUMNINFO: " + Convert.ToString(pwszName, CultureInfo.InvariantCulture)).Append(Environment.NewLine); builder.Append("\t" + iOrdinal.ToInt64().ToString(CultureInfo.InvariantCulture)).Append(Environment.NewLine); builder.Append("\t" + "0x" + dwFlags.ToString("X8", CultureInfo.InvariantCulture)).Append(Environment.NewLine); builder.Append("\t" + ulColumnSize.ToInt64().ToString(CultureInfo.InvariantCulture)).Append(Environment.NewLine); builder.Append("\t" + "0x" + wType.ToString("X2", CultureInfo.InvariantCulture)).Append(Environment.NewLine); builder.Append("\t" + bPrecision.ToString(CultureInfo.InvariantCulture)).Append(Environment.NewLine); builder.Append("\t" + bScale.ToString(CultureInfo.InvariantCulture)).Append(Environment.NewLine); builder.Append("\t" + columnid.eKind.ToString(CultureInfo.InvariantCulture)).Append(Environment.NewLine); return builder.ToString(); } #endif } #if false typedef struct tagDBPROPINFOSET { /* [size_is] */ PDBPROPINFO rgPropertyInfos; ULONG cPropertyInfos; GUID guidPropertySet; } #endif #if (WIN32 && !ARCH_arm) [StructLayoutAttribute(LayoutKind.Sequential, Pack = 2)] #else [StructLayoutAttribute(LayoutKind.Sequential, Pack = 8)] #endif sealed internal class tagDBPROPINFOSET { internal IntPtr rgPropertyInfos; internal Int32 cPropertyInfos; internal Guid guidPropertySet; internal tagDBPROPINFOSET() { } } #if false typedef struct tagDBPROPINFO { LPOLESTR pwszDescription; DBPROPID dwPropertyID; DBPROPFLAGS dwFlags; VARTYPE vtType; VARIANT vValues; } #endif #if (WIN32 && !ARCH_arm) [StructLayoutAttribute(LayoutKind.Sequential, Pack = 2)] #else [StructLayoutAttribute(LayoutKind.Sequential, Pack = 8)] #endif sealed internal class tagDBPROPINFO { [MarshalAs(UnmanagedType.LPWStr)] internal string pwszDescription; internal Int32 dwPropertyID; internal Int32 dwFlags; internal Int16 vtType; [MarshalAs(UnmanagedType.Struct)] internal object vValue; internal tagDBPROPINFO() { } } #if false typedef struct tagDBPROPIDSET { /* [size_is] */ DBPROPID *rgPropertyIDs; ULONG cPropertyIDs; GUID guidPropertySet; } #endif #if (WIN32 && !ARCH_arm) [StructLayoutAttribute(LayoutKind.Sequential, Pack = 2)] #else [StructLayoutAttribute(LayoutKind.Sequential, Pack = 8)] #endif internal struct tagDBPROPIDSET { internal IntPtr rgPropertyIDs; internal Int32 cPropertyIDs; internal Guid guidPropertySet; } }
30.294248
138
0.640108
[ "Apache-2.0" ]
295007712/295007712.github.io
sourceCode/dotNet4.6/ndp/fx/src/data/System/Data/OleDb/OleDbStruct.cs
13,693
C#
#region License // MIT License // // Copyright (c) 2022 Joerg Frank // // // 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 namespace ISO22900.II.OdxLikeComParamSets.TransportOrDataLinkLayer { public partial class ISO_14230_2 { public interface IIso142302UniqueComParams { uint CP_EcuRespSourceAddress { get; set; } uint CP_FuncRespFormatPriorityType { get; set; } uint CP_FuncRespTargetAddr { get; set; } uint CP_PhysRespFormatPriorityType { get; set; } } } }
38.707317
81
0.727788
[ "MIT" ]
DiagProf/ISO22900.II
WrapISO22900.II.OdxLikeComParamSets/TransportOrDataLinkLayer/ISO_14230_2.IUniqueComParams.cs
1,589
C#
using System.Collections.Generic; using System.IO; using System.Linq; using Ultima5Redux.Data; namespace Ultima5Redux.Maps { public class Signs { /// <summary> /// Total number of expected signs in file /// </summary> private const short TOTAL_SIGNS = 0x21; /// <summary> /// List of all assembled signs /// </summary> private readonly List<Sign> _signList = new List<Sign>(TOTAL_SIGNS); /// <summary> /// Loads the "Look" descriptions /// </summary> /// <param name="u5directory">directory of data files</param> public Signs(string u5directory) { List<byte> signsByteArray = Utils.GetFileAsByteList(Path.Combine(u5directory, FileConstants.SIGNS_DAT)); int nIndex = TOTAL_SIGNS * 2; // we are ignoring the "offsets" which are likely used to help optimize the lookup // on older hardware, instead we will just be lazy and search for them by cycling // through the whole list do { string rawSignTxt = Utils.BytesToStringNullTerm(signsByteArray, nIndex + 4, 0xFF); int nRawSignTxtLength = rawSignTxt.Length; // there are often two "warning signs" in the main virtue townes. Only one of the signs text is actually // populated - so if we see a "\n" as the only string, then we look ahead to the next signs text and use // it instead if (rawSignTxt.Trim() == string.Empty) { int nNextSignAdjust = rawSignTxt.Length + 1 + 4; rawSignTxt = Utils.BytesToStringNullTerm(signsByteArray, nIndex + 4 + nNextSignAdjust, 0xFF); } _signList.Add(new Sign((SmallMapReferences.SingleMapReference.Location)signsByteArray[nIndex], signsByteArray[nIndex + 1], signsByteArray[nIndex + 2], signsByteArray[nIndex + 3], rawSignTxt, nIndex)); nIndex += nRawSignTxtLength + 1 + 4; // we hop over the string plus it's null byte plus the four bytes for definition // while we don't encounter four zero bytes in a row, which is essentially the end of the file } while (!(signsByteArray[nIndex] == 0 && signsByteArray[nIndex + 1] == 0 && signsByteArray[nIndex + 2] == 0 && signsByteArray[nIndex + 3] == 0)); // there are some signs that are not included in the signs.dat file, so we manually pont to them and add them to our sign list List<byte> dataOvlSignsByteArray = Utils.GetFileAsByteList(Path.Combine(u5directory, FileConstants.DATA_OVL)); List<byte> shSign = DataChunk.CreateDataChunk(DataChunk.DataFormatType.ByteList, "SH Sign of Eight Laws", dataOvlSignsByteArray, 0x743a, 0x66).GetAsByteList(); _signList.Add(new Sign(SmallMapReferences.SingleMapReference.Location.Serpents_Hold, 0, 15, 19, shSign.ToArray(), 0x743a)); } public Sign GetSign(int nSign) { return _signList[nSign]; } public Sign GetSign(SmallMapReferences.SingleMapReference.Location location, int x, int y) { return _signList.FirstOrDefault(sign => sign.X == x && sign.Y == y && sign.Location == location); } } }
46.328947
138
0.591309
[ "MIT" ]
bradhannah/Ultima5Redux
Ultima5Redux/Maps/Signs.cs
3,523
C#
// Copyright (c) MarinAtanasov. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the project root for license information. // using System; namespace AppBrix.Events.Impl { internal abstract class EventWrapper { public abstract object Handler { get; } public abstract void Execute(IEvent args); } internal sealed class EventWrapper<T> : EventWrapper where T : IEvent { public EventWrapper(Action<T> handler) { this.handler = handler; } public override object Handler => this.handler; public override void Execute(IEvent args) => this.handler((T)args); private readonly Action<T> handler; } }
25.172414
101
0.654795
[ "MIT" ]
MarinAtanasov/AppBrix.NetCore
Modules/AppBrix.Events/Impl/EventWrapper.cs
732
C#
using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; namespace Ryujinx.Graphics.GAL { [StructLayout(LayoutKind.Sequential, Size = 8)] public struct BufferHandle : IEquatable<BufferHandle> { private readonly ulong _value; public static BufferHandle Null => new BufferHandle(0); private BufferHandle(ulong value) => _value = value; public override bool Equals(object obj) => obj is BufferHandle handle && Equals(handle); public bool Equals([AllowNull] BufferHandle other) => other._value == _value; public override int GetHashCode() => _value.GetHashCode(); public static bool operator ==(BufferHandle left, BufferHandle right) => left.Equals(right); public static bool operator !=(BufferHandle left, BufferHandle right) => !(left == right); } }
37.695652
100
0.701269
[ "MIT" ]
0MrDarn0/Ryujinx
Ryujinx.Graphics.GAL/BufferHandle.cs
869
C#
using System; using System.IO; namespace O3DConverter { class D3DXVECTOR3 { public float x,y,z; public D3DXVECTOR3(BinaryReader binaryReader) { this.x = binaryReader.ReadSingle(); this.y = binaryReader.ReadSingle(); this.z = binaryReader.ReadSingle(); } public static D3DXVECTOR3[] ReadBulk (BinaryReader binaryReader,int count) { var bulk = new D3DXVECTOR3[count]; for (int i = 0; i < count; i++) bulk[i] = new D3DXVECTOR3(binaryReader); return bulk; } } class D3DXMATRIX { public float _11, _12, _13, _14; public float _21, _22, _23, _24; public float _31, _32, _33, _34; public float _41, _42, _43, _44; /// <summary> /// Returns Column X of Row Y from Matrix /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <returns></returns> public float this[int x, int y] { get { if (x >= 0 && y >= 0 && x < 5 && y < 5) return (int)GetType().GetField("_" + x + y).GetValue(this); else return 0; } set { if (x > 0 && y > 0 && x < 5 && y < 5) { var prop = GetType().GetField("_" + x + y); prop.SetValue(this, value); } } } /// <summary> /// Parse Matrix from Binary Reader /// </summary> /// <param name="binaryReader"></param> public D3DXMATRIX(BinaryReader binaryReader) { for (int y = 1; y < 5; y++) for (int x = 1; x < 5; x++) this[x, y] = binaryReader.ReadSingle(); } public static D3DXMATRIX[] ReadBulk(BinaryReader binaryReader,int count) { var matrices = new D3DXMATRIX[count]; for (int i = 0; i < count; i++) matrices[i] = new D3DXMATRIX(binaryReader); return matrices; } }; class D3DXQUATERNION { float x; float y; float z; float w; public D3DXQUATERNION(BinaryReader binaryReader) { x = binaryReader.ReadSingle(); y = binaryReader.ReadSingle(); z = binaryReader.ReadSingle(); w = binaryReader.ReadSingle(); } } class D3DCOLORVALUE { public float r; public float g; public float b; public float a; public D3DCOLORVALUE(BinaryReader binaryReader) { r = binaryReader.ReadSingle(); g = binaryReader.ReadSingle(); b = binaryReader.ReadSingle(); a = binaryReader.ReadSingle(); } } class D3DMATERIAL9 { public D3DCOLORVALUE Diffuse; public D3DCOLORVALUE Ambient; public D3DCOLORVALUE Specular; public D3DCOLORVALUE Emissive; public float Power; public D3DMATERIAL9(BinaryReader binaryReader) { Diffuse = new D3DCOLORVALUE(binaryReader); Ambient = new D3DCOLORVALUE(binaryReader); Specular = new D3DCOLORVALUE(binaryReader); Emissive = new D3DCOLORVALUE(binaryReader); Power = binaryReader.ReadSingle(); } } class MATERIAL_BLOCK { const int MAX_VS_BONE = 28; int m_nStartVertex; int m_nPrimitiveCount; int m_nTextureID; // int m_n2Side; // 2 side render block // int m_nReflect; // int m_nOpacity; uint m_dwEffect; int m_nAmount; // ������ int m_nMaxUseBone; int[] m_UseBone; public MATERIAL_BLOCK(BinaryReader binaryReader) { m_nStartVertex = binaryReader.ReadInt32(); m_nPrimitiveCount = binaryReader.ReadInt32(); m_nTextureID = binaryReader.ReadInt32(); m_dwEffect = binaryReader.ReadUInt32(); m_nAmount = binaryReader.ReadInt32(); m_nMaxUseBone = binaryReader.ReadInt32(); m_UseBone = new int[MAX_VS_BONE]; for(int i = 0;i < MAX_VS_BONE; i++) m_UseBone[i] = binaryReader.ReadInt32(); } public static MATERIAL_BLOCK[] ReadBulk(BinaryReader binaryReader,int count) { var material_blocks = new MATERIAL_BLOCK[count]; for (int i = 0; i < count; i++) material_blocks[i] = new MATERIAL_BLOCK(binaryReader); return material_blocks; } }; class SKINVERTEX : NORMALVERTEX { public float w1, w2; // vertex weight public uint matIdx; public SKINVERTEX(BinaryReader binaryReader) { position = new D3DXVECTOR3(binaryReader); w1 = binaryReader.ReadSingle(); w2 = binaryReader.ReadSingle(); matIdx = binaryReader.ReadUInt32(); normal = new D3DXVECTOR3(binaryReader); tu = binaryReader.ReadSingle(); tv = binaryReader.ReadSingle(); } public static new SKINVERTEX[] ReadBulk(BinaryReader binaryReader, int count) { var vertices = new SKINVERTEX[count]; for (int i = 0; i < count; i++) vertices[i] = new SKINVERTEX(binaryReader); return vertices; } }; class NORMALVERTEX { public D3DXVECTOR3 position; // The 3D position for the vertex public D3DXVECTOR3 normal; // The surface normal for the vertex public float tu, tv; // The texture coordinates public NORMALVERTEX() { } public NORMALVERTEX(BinaryReader binaryReader) { position = new D3DXVECTOR3(binaryReader); normal = new D3DXVECTOR3(binaryReader); tu = binaryReader.ReadSingle(); tv = binaryReader.ReadSingle(); } public static NORMALVERTEX[] ReadBulk(BinaryReader binaryReader, int count) { var vertices = new NORMALVERTEX[count]; for (int i = 0; i < count; i++) vertices[i] = new NORMALVERTEX(binaryReader); return vertices; } }; }
32.15
85
0.52535
[ "Apache-2.0" ]
electriZer/O3D-Converter
O3DConverter/RawD3D.cs
6,444
C#
using System; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization; using System.Text; namespace S22.Imap.Provider.Auth.Sasl.Mechanisms.Ntlm { /// <summary> /// Represents an NTLM Type 2 Message. /// </summary> internal class Type2Message { /// <summary> /// The NTLM message signature which is always "NTLMSSP". /// </summary> static readonly string signature = "NTLMSSP"; /// <summary> /// The NTML message type which is always 2 for an NTLM Type 2 message. /// </summary> static readonly MessageType type = MessageType.Type2; /// <summary> /// The challenge is an 8-byte block of random data. /// </summary> public byte[] Challenge { get; private set; } /// <summary> /// The target name of the authentication target. /// </summary> public string TargetName { get; private set; } /// <summary> /// The NTLM flags set on this message. /// </summary> public Flags Flags { get; private set; } /// <summary> /// The SSPI context handle when a local call is being made, /// otherwise null. /// </summary> public Int64 Context { get; private set; } /// <summary> /// Contains the data present in the OS version structure. /// </summary> public OSVersion OSVersion { get; private set; } /// <summary> /// The version of this Type 2 message instance. /// </summary> public Type2Version Version { get; private set; } /// <summary> /// Contains the data present in the target information block. /// </summary> public Type2TargetInformation TargetInformation { get; private set; } /// <summary> /// Contains the raw data present in the target information block. /// </summary> public byte[] RawTargetInformation { get; private set; } /// <summary> /// Private constructor. /// </summary> private Type2Message() { TargetInformation = new Type2TargetInformation(); OSVersion = new OSVersion(); } /// <summary> /// Deserializes a Type 2 message instance from the specified buffer /// of bytes. /// </summary> /// <param name="buffer">The buffer containing a sequence of bytes /// representing an NTLM Type 2 message.</param> /// <returns>An initialized instance of the Type2 class.</returns> /// <exception cref="SerializationException">Thrown if an error occurs /// during deserialization of the Type 2 message.</exception> static internal Type2Message Deserialize(byte[] buffer) { try { Type2Message t2 = new Type2Message(); using (var ms = new MemoryStream(buffer)) { using (var r = new BinaryReader(ms)) { if (r.ReadASCIIString(8) != signature) throw new InvalidDataException("Invalid signature."); if (r.ReadInt32() != (int) type) throw new InvalidDataException("Unexpected message type."); int targetLength = r.ReadInt16(), targetSpace = r.ReadInt16(), targetOffset = r.ReadInt32(); t2.Flags = (Flags) r.ReadInt32(); t2.Challenge = r.ReadBytes(8); // Figure out, which of the several versions of Type 2 we're // dealing with. t2.Version = GetType2Version(targetOffset); if (t2.Version > Type2Version.Version1) { t2.Context = r.ReadInt64(); // Read the target information security buffer int informationLength = r.ReadInt16(), informationSpace = r.ReadInt16(), informationOffset = r.ReadInt32(); t2.RawTargetInformation = new byte[informationLength]; Array.Copy(buffer, informationOffset, t2.RawTargetInformation, 0, informationLength); // Version 3 has an additional OS version structure. if (t2.Version > Type2Version.Version2) t2.OSVersion = ReadOSVersion(r); } t2.TargetName = GetTargetName(r.ReadBytes(targetLength), (t2.Flags & Flags.NegotiateUnicode) == Flags.NegotiateUnicode); if (t2.Version > Type2Version.Version1) { t2.TargetInformation = ReadTargetInformation(r); } } } return t2; } catch (Exception e) { throw new SerializationException("NTLM Type 2 message could not be " + "deserialized.", e); } } /// <summary> /// Determines the version of an NTLM type 2 message. /// </summary> /// <param name="targetOffset">The target offset field of the NTLM /// type 2 message.</param> /// <returns>A value from the Type2Version enumeration.</returns> static Type2Version GetType2Version(int targetOffset) { var dict = new Dictionary<int, Type2Version>() { { 32, Type2Version.Version1 }, { 48, Type2Version.Version2 }, { 56, Type2Version.Version3 } }; return dict.ContainsKey(targetOffset) ? dict[targetOffset] : Type2Version.Unknown; } /// <summary> /// Reads the OS information data present in version 3 of an NTLM /// type 2 message from the specified BinaryReader. /// </summary> /// <param name="r">The BinaryReader instance to read from.</param> /// <returns>An initialized instance of the OSVersion class.</returns> static OSVersion ReadOSVersion(BinaryReader r) { OSVersion version = new OSVersion(); version.MajorVersion = r.ReadByte(); version.MinorVersion = r.ReadByte(); version.BuildNumber = r.ReadInt16(); // Swallow the reserved 32-bit word. r.ReadInt32(); return version; } /// <summary> /// Reads the target information data present in version 2 and 3 of /// an NTLM type 2 message from the specified BinaryReader. /// </summary> /// <param name="r">The BinaryReader instance to read from.</param> /// <returns>An initialized instance of the Type2TargetInformation /// class.</returns> static Type2TargetInformation ReadTargetInformation(BinaryReader r) { Type2TargetInformation info = new Type2TargetInformation(); while (true) { var _type = (Type2InformationType) r.ReadInt16(); if (_type == Type2InformationType.TerminatorBlock) break; short length = r.ReadInt16(); string content = Encoding.Unicode.GetString(r.ReadBytes(length)); switch (_type) { case Type2InformationType.ServerName: info.ServerName = content; break; case Type2InformationType.DomainName: info.DomainName = content; break; case Type2InformationType.DnsHostname: info.DnsHostname = content; break; case Type2InformationType.DnsDomainName: info.DnsDomainName = content; break; } } return info; } /// <summary> /// Retrieves the target name from the specified byte array. /// </summary> /// <param name="data">A byte array containing the target name.</param> /// <param name="isUnicode">If true the target name will be decoded /// using UTF-16 unicode encoding.</param> /// <returns></returns> static string GetTargetName(byte[] data, bool isUnicode) { Encoding enc = isUnicode ? Encoding.Unicode : Encoding.ASCII; return enc.GetString(data); } } }
31.685841
75
0.645999
[ "MIT" ]
AccentureRapid/OrchardCollaboration
src/Orchard.Web/Modules/S22.IMAP/Provider/Auth/Sasl/Mechanisms/Ntlm/Type2Message.cs
7,163
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Storage; using Microsoft.Xna.Framework.GamerServices; namespace MonsterSwap { public class MenuState: IState { Game1 game; GameTime gameTime; public void SetGame(Game1 _game) { game = _game; } public void SetTime(GameTime _time) { gameTime = _time; } public void Update() { Input(); } public void Draw() { game.gameObject.Texture = game.backgroundMenu; game.gameObject.Draw(game.spriteBatch); game.fontVector2 = new Vector2(game.GraphicsDevice.Viewport.Width / 2 - 130, game.GraphicsDevice.Viewport.Height - 90); game.spriteBatch.DrawString(game.font, "Press Enter to Begin", game.fontVector2, Color.Brown); game.fontVector2 = new Vector2(game.GraphicsDevice.Viewport.Width / 2 - 130, game.GraphicsDevice.Viewport.Height - 40); game.spriteBatch.DrawString(game.font, "Made by: Sean, Wyatt, Jeremy, James.", game.fontVector2, Color.Crimson); } public void Input() { if (game.redo == true) { game.lives = 16; game.HiScore = 0; } else { game.lives = 15; game.HiScore = 0; } game.kStateCurrent = Keyboard.GetState(); game.mState = Mouse.GetState(); if (game.kStateCurrent.IsKeyDown(Keys.Enter)) { game.state = game.gameState; game.state.SetGame(game); } } } }
27.913043
132
0.563863
[ "MIT" ]
maegico/Monster-Swap
MonsterSwap/MenuState.cs
1,928
C#
using System.Collections; using System.Collections.Generic; using UniRx.Triggers; using UnityEngine; using UniRx; using PsycthoMothers.Battle.Inputs; using PsycthoMothers.Battle.Manager; using Zenject; namespace PsycthoMothers.Battle.Players { /// <summary> /// PlayerAnimator /// アニメーション管理 /// </summary> [RequireComponent(typeof(Animator), typeof(Rigidbody2D))] public class PlayerAnimator : MonoBehaviour { /// <summary> /// Rigidbody2D /// </summary> [SerializeField] private Rigidbody2D _rigidbody2D; /// <summary> /// Animator /// </summary> [SerializeField] private Animator _anim; [Inject] private GameStateManager _gameStateManager; private Vector3 _moveVelocity; /// <summary> /// Start /// </summary> protected void Start() { var inputEvent = GetComponent<IInputEventProvider>(); //移動 inputEvent.MoveDirection.Subscribe(x => _moveVelocity = x); this.UpdateAsObservable() .Where(_ => _gameStateManager.CurrentState.Value == GameState.Battle) .Subscribe(_ => { if (_moveVelocity == Vector3.zero) return; _anim.SetFloat("x", _moveVelocity.x); _anim.SetFloat("y", _moveVelocity.y); }); } } }
26.648148
85
0.577484
[ "MIT" ]
TORISOUP/PsychoMothers
Assets/PsycthoMothers/Scripts/Battle/Players/PlayerAnimator.cs
1,463
C#
using System; using System.Collections.Generic; using System.ComponentModel.Composition.Hosting; using System.ComponentModel.Composition.Primitives; using System.IO; using System.Reflection; namespace Panteon.Host.Infrastructure { public sealed class CatalogConfigurator { private readonly object _lockObject = new object(); private readonly AggregateCatalog _currentAggregateCatalog = new AggregateCatalog(); private CompositionContainer _container; public CatalogConfigurator AddCatalogs(params ComposablePartCatalog[] catalogs) { foreach (var catalog in catalogs) { _currentAggregateCatalog.Catalogs.Add(catalog); } return this; } public CatalogConfigurator AddCatalogs(IEnumerable<ComposablePartCatalog> catalogs) { if (catalogs != null) { foreach (var catalog in catalogs) { _currentAggregateCatalog.Catalogs.Add(catalog); } } return this; } public CatalogConfigurator AddAssembly(Assembly assembly) { return AddCatalogs(new AssemblyCatalog(assembly)); } public CatalogConfigurator AddAssembly(string codeBase) { return AddCatalogs(new AssemblyCatalog(codeBase)); } public CatalogConfigurator AddDirectory(string path) { return AddCatalogs(new DirectoryCatalog(path)); } public CatalogConfigurator AddNestedDirectory(string path) { string[] directories = Directory.GetDirectories(path); foreach (var directoryPath in directories) { AddCatalogs(new DirectoryCatalog(directoryPath)); } return this; } public CatalogConfigurator AddDirectory(string path, string searchPattern) { return AddCatalogs(new DirectoryCatalog(path, searchPattern)); } public CatalogConfigurator AddTypes(params Type[] types) { return AddCatalogs(new TypeCatalog(types)); } public CatalogConfigurator AddTypes(IEnumerable<Type> types) { return AddCatalogs(new TypeCatalog(types)); } public CompositionContainer BuildContainer() { return BuildContainer(false); } public CompositionContainer BuildContainer(bool rebuildContainer) { lock (_lockObject) { if (rebuildContainer || (_container == null)) { _container = new CompositionContainer(_currentAggregateCatalog); } } return _container; } } }
30.505376
92
0.59993
[ "MIT" ]
PanteonProject/Panteon.Host
Panteon.Host/Infrastructure/CatalogConfigurator.cs
2,839
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using Microsoft.Win32.SafeHandles; namespace Meziantou.Framework { public static partial class ProcessExtensions { public static void Kill(this Process process, bool entireProcessTree = false) { if (process == null) throw new ArgumentNullException(nameof(process)); #if NETCOREAPP3_1 process.Kill(entireProcessTree); #elif NETSTANDARD2_0 || NET461 if (!entireProcessTree) { process.Kill(); return; } if (!IsWindows()) throw new PlatformNotSupportedException("Only supported on Windows"); var childProcesses = GetDescendantProcesses(process); if (!process.HasExited) { process.Kill(); } foreach (var childProcess in childProcesses) { if (!childProcess.HasExited) { if (!childProcess.HasExited) { childProcess.Kill(); } } } #else #error Platform not supported #endif } public static IReadOnlyList<Process> GetDescendantProcesses(this Process process) { if (process == null) throw new ArgumentNullException(nameof(process)); if (!IsWindows()) throw new PlatformNotSupportedException("Only supported on Windows"); var children = new List<Process>(); GetChildProcesses(process, children, int.MaxValue, 0); return children; } public static IReadOnlyList<Process> GetChildProcesses(this Process process) { if (process == null) throw new ArgumentNullException(nameof(process)); if (!IsWindows()) throw new PlatformNotSupportedException("Only supported on Windows"); var children = new List<Process>(); GetChildProcesses(process, children, 1, 0); return children; } public static IEnumerable<int> GetAncestorProcessIds(this Process process) { if (process == null) throw new ArgumentNullException(nameof(process)); if (!IsWindows()) throw new PlatformNotSupportedException("Only supported on Windows"); return GetAncestorProcessIdsIterator(); IEnumerable<int> GetAncestorProcessIdsIterator() { var processId = process.Id; var processes = GetProcesses().ToList(); var found = true; while (found) { found = false; foreach (var entry in processes) { if (entry.ProcessId == processId) { yield return entry.ParentProcessId; processId = entry.ParentProcessId; found = true; } } if (!found) yield break; } } } public static int? GetParentProcessId(this Process process) { if (process == null) throw new ArgumentNullException(nameof(process)); if (!IsWindows()) throw new PlatformNotSupportedException("Only supported on Windows"); var processId = process.Id; foreach (var entry in GetProcesses()) { if (entry.ProcessId == processId) { return entry.ParentProcessId; } } return null; } public static Process? GetParentProcess(this Process process) { var parentProcessId = GetParentProcessId(process); if (parentProcessId == null) return null; return Process.GetProcessById(parentProcessId.Value); } public static IEnumerable<ProcessEntry> GetProcesses() { using var snapShotHandle = CreateToolhelp32Snapshot(SnapshotFlags.TH32CS_SNAPPROCESS, 0); var entry = new ProcessEntry32 { dwSize = (uint)Marshal.SizeOf(typeof(ProcessEntry32)), }; var result = Process32First(snapShotHandle, ref entry); while (result != 0) { yield return new ProcessEntry(entry.th32ProcessID, entry.th32ParentProcessID); result = Process32Next(snapShotHandle, ref entry); } } private static void GetChildProcesses(Process process, List<Process> children, int maxDepth, int currentDepth) { var entries = new List<ProcessEntry>(100); foreach (var entry in GetProcesses()) { entries.Add(entry); } GetChildProcesses(entries, process, children, maxDepth, currentDepth); } private static void GetChildProcesses(List<ProcessEntry> entries, Process process, List<Process> children, int maxDepth, int currentDepth) { var processId = process.Id; foreach (var entry in entries) { if (entry.ParentProcessId == processId) { try { var child = entry.ToProcess(); children.Add(child); if (currentDepth < maxDepth) { GetChildProcesses(entries, child, children, maxDepth, currentDepth + 1); } } catch (ArgumentException) { // process might have exited since the snapshot, ignore it } } } } private static bool IsWindows() { #if NETSTANDARD2_0 || NETCOREAPP3_1 return RuntimeInformation.IsOSPlatform(OSPlatform.Windows); #elif NET461 return true; #else #error Platform not supported #endif } [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool CloseHandle(IntPtr hObject); [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)] private static extern int Process32First(SnapshotSafeHandle handle, ref ProcessEntry32 entry); [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)] private static extern int Process32Next(SnapshotSafeHandle handle, ref ProcessEntry32 entry); // https://msdn.microsoft.com/en-us/library/windows/desktop/ms682489.aspx [DllImport("kernel32.dll", SetLastError = true)] private static extern SnapshotSafeHandle CreateToolhelp32Snapshot(SnapshotFlags dwFlags, uint th32ProcessID); private const int MAX_PATH = 260; // https://msdn.microsoft.com/en-us/library/windows/desktop/ms684839.aspx [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] internal struct ProcessEntry32 { #pragma warning disable IDE1006 // Naming Styles public uint dwSize; public uint cntUsage; public int th32ProcessID; public IntPtr th32DefaultHeapID; public uint th32ModuleID; public uint cntThreads; public int th32ParentProcessID; public int pcPriClassBase; public uint dwFlags; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = MAX_PATH)] public string szExeFile; #pragma warning restore IDE1006 // Naming Styles } // https://msdn.microsoft.com/en-us/library/windows/desktop/ms682489.aspx private enum SnapshotFlags : uint { TH32CS_SNAPHEAPLIST = 0x00000001, TH32CS_SNAPPROCESS = 0x00000002, TH32CS_SNAPTHREAD = 0x00000004, TH32CS_SNAPMODULE = 0x00000008, TH32CS_SNAPMODULE32 = 0x00000010, TH32CS_INHERIT = 0x80000000, } private sealed class SnapshotSafeHandle : SafeHandleZeroOrMinusOneIsInvalid { public SnapshotSafeHandle() : base(ownsHandle: true) { } protected override bool ReleaseHandle() { return CloseHandle(handle); } } } }
33.429658
146
0.549704
[ "MIT" ]
LePtitDev/Meziantou.Framework
src/Meziantou.Framework/ProcessExtensions.cs
8,794
C#
using VRTK; using UnityEngine; using System; namespace com.EvolveVR.BonejanglesVR { public class SkeletonHanger : InteractableSlide { [Range(0, 1)] public float rotationSmoothFactor = 0.2f; float lastHandRotationY = 0; protected override void OnInitialTriggerInteraction(Collider other) { lastHandRotationY = hand.transform.eulerAngles.y; } protected override void OnInteraction(Collider other) { Vector3 controllerPos = InteractingHandPosition; Vector3 newPosition = new Vector3(controllerPos.x, transform.position.y, controllerPos.z); transform.position = Vector3.Lerp(transform.position, newPosition, smoothingFactor); float dR = hand.transform.eulerAngles.y - lastHandRotationY; Quaternion newRotation = Quaternion.Euler(0, transform.eulerAngles.y + dR, 0); transform.rotation = Quaternion.Lerp(transform.rotation, newRotation, rotationSmoothFactor); lastHandRotationY = hand.transform.eulerAngles.y; currentHapticTime += Time.deltaTime; if (currentHapticTime > timeBetweenPulses) { VRTK_ControllerHaptics.TriggerHapticPulse(handRef, 0.3f); currentHapticTime = Time.deltaTime; } } } }
38.114286
104
0.667166
[ "MIT" ]
RJ45toCerebrum/BoneJanglesVR
BonejanglesVR/Assets/Scripts/SkeletonHanger.cs
1,336
C#
using System.Threading.Tasks; using kinema.Messaging; namespace kinema.Actors { public delegate Task<IActorResult> MessageHandler(IMessage message); }
22.285714
72
0.801282
[ "MIT" ]
iiwaasnet/kinema
src/kinema/Actors/MessageHandler.cs
158
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using Microsoft.Azure.RemoteRendering; using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using UnityEngine; public class ProgressStatus { private float _currentProgress = 0.0f; private float _maxProgress = 0.0f; /// <summary> /// Get the total loading progress /// </summary> public float Progress { get { if (_maxProgress == 0.0f) { return 1.0f; } float progress = (float)(_currentProgress / _maxProgress); if (Mathf.Approximately(progress, 1.0f) || progress > 1.0f) { return 1.0f; } return progress; } } /// <summary> /// Add or remote progress change handlers. /// </summary> public event EventHandler<ProgressTaskChangeArgs> ProgressChanged; /// <summary> /// Fired when progress reaches 100% /// </summary> public event EventHandler<ProgressTaskChangeArgs> Completed; /// <summary> /// Update the max value of the inner progress value. /// </summary> protected void UpdateMax(float max) { float oldTotalProgress = Progress; _maxProgress = max; float newTotalProgress = Progress; if (oldTotalProgress != newTotalProgress) { ProgressChanged?.Invoke(this, new ProgressTaskChangeArgs(oldTotalProgress, newTotalProgress)); } CheckCompleted(); } /// <summary> /// Update the inner progress value; /// </summary> protected void UpdateProgress(float progress) { float oldTotalProgress = Progress; _currentProgress = progress; float newTotalProgress = Progress; if (oldTotalProgress != newTotalProgress) { ProgressChanged?.Invoke(this, new ProgressTaskChangeArgs(oldTotalProgress, newTotalProgress)); } CheckCompleted(); } /// <summary> /// Check if prgress has completed, and if so fire compelted evnt. /// </summary> private void CheckCompleted() { if (Mathf.Approximately(_currentProgress, _maxProgress) || _currentProgress >= _maxProgress) { float oldTotalProgress = Progress; _currentProgress = _maxProgress; Completed?.Invoke(this, new ProgressTaskChangeArgs(oldTotalProgress, Progress)); _currentProgress = 0.0f; _maxProgress = 0.0f; } } } /// <summary> /// A class that exposes IAsync operation progress along side an awaitable task. /// </summary> public class ModelProgressStatus : ProgressStatus { private LoadModelAsync _waitable = null; private TaskCompletionSource<LoadModelResult> _taskSource = new TaskCompletionSource<LoadModelResult>(); public ModelProgressStatus() { UpdateMax(1.0f); } /// <summary> /// Get the related task /// </summary> /// <remarks> /// Start() can be called after something requests this task, hence the use of a TaskCompletionSource /// </remarks> public Task<LoadModelResult> Result => _taskSource.Task; /// <summary> /// Start the progress using the given IAsync operation /// </summary> /// <param name="asyncOperation"></param> public void Start(LoadModelAsync asyncOperation) { _waitable = asyncOperation; if (_waitable == null) { return; } _waitable.ProgressUpdated += (float value) => { UpdateProgress(value); }; _waitable.Completed += WaitableCompleted; } /// <summary> /// Handle the waitable completion event. /// </summary> private void WaitableCompleted(LoadModelAsync async) { if (_waitable == null || _taskSource.Task.IsCompleted) { return; } _waitable.Completed -= WaitableCompleted; if (_waitable.IsRanToCompletion) { _taskSource.TrySetResult(_waitable.Result); } else { _taskSource.TrySetException(new Exception($"Load model failed with status '{_waitable.Status}'")); } // Force progress to complete on success or failure UpdateProgress(1.0f); } } /// <summary> /// A helper class used to track the progress of many progress tasks /// </summary> public class ProgressCollection : ProgressStatus { private readonly List<ProgressStatus> _inners = new List<ProgressStatus>(); private Timer _updateTimer = null; private static readonly TimeSpan _timerDueTime = TimeSpan.FromSeconds(1.0 / 30.0); private static readonly TimeSpan _timerPeriosDueTime = TimeSpan.FromSeconds(1.0 / 30.0); public ProgressCollection() { } public void Add(ProgressStatus item) { RegisterInner(item); UpdateMax(_inners.Count); StartUpdates(); } public void Clear() { foreach (var item in _inners) { UnregisterInner(item); } _inners.Clear(); UpdateMax(0.0f); UpdateProgress(0.0f); StopUpdates(); } private void StartUpdates() { if (_updateTimer == null) { _updateTimer = new Timer(new TimerCallback(UpdateTick), SynchronizationContext.Current, _timerDueTime, _timerPeriosDueTime); } } private void UpdateTick(object state) { SynchronizationContext context = state as SynchronizationContext; if (context != null) { context.Send(contextState => UpdateProgress(), null); } else { UpdateProgress(); } } private void StopUpdates() { if (_updateTimer != null) { Debug.Assert(UnityEngine.WSA.Application.RunningOnAppThread(), "Not running on app thread."); _updateTimer.Dispose(); _updateTimer = null; } } /// <summary> /// Register an additional task to monitor /// </summary> private void RegisterInner(ProgressStatus inner) { if (_inners.Contains(inner)) { return; } _inners.Add(inner); inner.ProgressChanged += InnerProgress; inner.Completed += InnerCompleted; } /// <summary> /// Unregister an additional task to monitor /// </summary> private void UnregisterInner(ProgressStatus inner) { inner.Completed -= InnerCompleted; inner.ProgressChanged -= InnerProgress; } /// <summary> /// Update the total progress /// </summary> private void UpdateProgress() { float total = 0; foreach (var item in _inners) { total += item.Progress; } UpdateProgress(total); // If progress reaches 100%, clear inners if (total >= _inners.Count) { Clear(); } } /// <summary> /// Update a task's progress /// </summary> private void InnerProgress(object sender, ProgressTaskChangeArgs args) { StartUpdates(); } /// <summary> /// Clean up a inner task registration. /// </summary> private void InnerCompleted(object sender, ProgressTaskChangeArgs args) { UnregisterInner((ProgressStatus)sender); StartUpdates(); } } public struct ProgressTaskChangeArgs { public ProgressTaskChangeArgs(float oldValue, float newValue) { OldValue = oldValue; NewValue = newValue; } public float OldValue { get; } public float NewValue { get; } }
27.228956
137
0.58254
[ "MIT" ]
ForrestTrepte/azure-remote-rendering
Unity/AzureRemoteRenderingShowcase/arr-showcase-app/Assets/App/Utilities/ProgressStatus.cs
8,089
C#
// Copyright (c) Argo Zhang ([email protected]). All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Website: https://www.blazor.zone or https://argozhang.github.io/ using Microsoft.AspNetCore.Components; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading.Tasks; namespace BootstrapBlazor.Components { /// <summary> /// 时间线组件基类 /// </summary> public abstract class TimelineBase : BootstrapComponentBase { /// <summary> /// 获得 Timeline 样式 /// </summary> protected string? ClassString => CssBuilder.Default("timeline") .AddClass("is-alternate", IsAlternate && !IsLeft) .AddClass("is-left", IsLeft) .AddClassFromAttributes(AdditionalAttributes) .Build(); /// <summary> /// 获得/设置 绑定数据集 /// </summary> [Parameter] [NotNull] public IEnumerable<TimelineItem>? Items { get; set; } /// <summary> /// 获得/设置 是否反转 /// </summary> [Parameter] public bool IsReverse { get; set; } /// <summary> /// 获得/设置 是否左右交替出现 默认 false /// </summary> [Parameter] public bool IsAlternate { get; set; } /// <summary> /// 获得/设置 内容是否出现在时间线左侧 默认为 false /// </summary> [Parameter] public bool IsLeft { get; set; } /// <summary> /// OnInitializedAsync 方法 /// </summary> /// <returns></returns> protected override async Task OnInitializedAsync() { await base.OnInitializedAsync(); if (Items == null) { Items = Enumerable.Empty<TimelineItem>(); } } /// <summary> /// OnParametersSet 方法 /// </summary> protected override void OnParametersSet() { base.OnParametersSet(); if (IsReverse) { var arr = Items.Reverse(); Items = arr; } } } }
26.950617
111
0.539166
[ "Apache-2.0" ]
5118234/BootstrapBlazor
src/BootstrapBlazor/Components/Timeline/TimelineBase.cs
2,315
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> //------------------------------------------------------------------------------ /// <summary> /// Enum GlobalNamespaceTest_Enum_NonShared /// </summary> public enum GlobalNamespaceTest_Enum_NonShared { /// <summary> /// DefaultValue /// </summary> DefaultValue = 0, /// <summary> /// NonDefaultValue /// </summary> NonDefaultValue = 1, } namespace GlobalNamespaceTest { /// <summary> /// The DomainContext corresponding to the 'GlobalNamespaceTest_DomainService' DomainService. /// </summary> [global::GlobalNamespaceTest_Attribute(EnumProperty=global::GlobalNamespaceTest_Enum.NonDefaultValue)] public sealed partial class GlobalNamespaceTest_DomainContext : global::OpenRiaServices.Client.DomainContext { #region Extensibility Method Definitions /// <summary> /// This method is invoked from the constructor once initialization is complete and /// can be used for further object setup. /// </summary> partial void OnCreated(); #endregion /// <summary> /// Initializes a new instance of the <see cref="GlobalNamespaceTest_DomainContext"/> class. /// </summary> public GlobalNamespaceTest_DomainContext() : this(new global::System.Uri("GlobalNamespaceTest-GlobalNamespaceTest_DomainService.svc", global::System.UriKind.Relative)) { } /// <summary> /// Initializes a new instance of the <see cref="GlobalNamespaceTest_DomainContext"/> class with the specified service URI. /// </summary> /// <param name="serviceUri">The GlobalNamespaceTest_DomainService service URI.</param> public GlobalNamespaceTest_DomainContext(global::System.Uri serviceUri) : this(global::OpenRiaServices.Client.DomainContext.CreateDomainClient(typeof(global::GlobalNamespaceTest.GlobalNamespaceTest_DomainContext.IGlobalNamespaceTest_DomainServiceContract), serviceUri, false)) { } /// <summary> /// Initializes a new instance of the <see cref="GlobalNamespaceTest_DomainContext"/> class with the specified <paramref name="domainClient"/>. /// </summary> /// <param name="domainClient">The DomainClient instance to use for this DomainContext.</param> public GlobalNamespaceTest_DomainContext(global::OpenRiaServices.Client.DomainClient domainClient) : base(domainClient) { this.OnCreated(); } /// <summary> /// Gets the set of <see cref="GlobalNamespaceTest_Entity"/> entity instances that have been loaded into this <see cref="GlobalNamespaceTest_DomainContext"/> instance. /// </summary> public global::OpenRiaServices.Client.EntitySet<global::GlobalNamespaceTest.GlobalNamespaceTest_Entity> GlobalNamespaceTest_Entities { get { return base.EntityContainer.GetEntitySet<global::GlobalNamespaceTest.GlobalNamespaceTest_Entity>(); } } /// <summary> /// Gets an EntityQuery instance that can be used to load <see cref="GlobalNamespaceTest_Entity"/> entity instances using the 'GetEntities' query. /// </summary> /// <returns>An EntityQuery that can be loaded to retrieve <see cref="GlobalNamespaceTest_Entity"/> entity instances.</returns> [global::GlobalNamespaceTest_Attribute()] public global::OpenRiaServices.Client.EntityQuery<global::GlobalNamespaceTest.GlobalNamespaceTest_Entity> GetEntitiesQuery() { this.ValidateMethod("GetEntitiesQuery", null); return base.CreateQuery<global::GlobalNamespaceTest.GlobalNamespaceTest_Entity>("GetEntities", null, false, true); } /// <summary> /// Gets an EntityQuery instance that can be used to load <see cref="GlobalNamespaceTest_Entity"/> entity instances using the 'ReadEntities' query. /// </summary> /// <param name="enumParameter">The value for the 'enumParameter' parameter of the query.</param> /// <returns>An EntityQuery that can be loaded to retrieve <see cref="GlobalNamespaceTest_Entity"/> entity instances.</returns> [global::GlobalNamespaceTest_Attribute()] public global::OpenRiaServices.Client.EntityQuery<global::GlobalNamespaceTest.GlobalNamespaceTest_Entity> ReadEntitiesQuery([global::GlobalNamespaceTest_ValidationAttribute()] global::GlobalNamespaceTest_Enum enumParameter) { global::System.Collections.Generic.Dictionary<string, object> parameters = new global::System.Collections.Generic.Dictionary<string, object>(); parameters.Add("enumParameter", enumParameter); this.ValidateMethod("ReadEntitiesQuery", parameters); return base.CreateQuery<global::GlobalNamespaceTest.GlobalNamespaceTest_Entity>("ReadEntities", parameters, false, true); } /// <summary> /// Invokes the 'CustomUpdateEntity' method of the specified <see cref="GlobalNamespaceTest_Entity"/> entity. /// </summary> /// <param name="entity">The <see cref="GlobalNamespaceTest_Entity"/> entity instance.</param> /// <param name="enumParameter">The value for the 'enumParameter' parameter for this action.</param> public void CustomUpdateEntity(global::GlobalNamespaceTest.GlobalNamespaceTest_Entity entity, global::GlobalNamespaceTest_Enum enumParameter) { entity.CustomUpdateEntity(enumParameter); } /// <summary> /// Asynchronously invokes the 'InvokeReturn' method of the DomainService. /// </summary> /// <param name="enumParameter">The value for the 'enumParameter' parameter of this action.</param> /// <param name="callback">Callback to invoke when the operation completes.</param> /// <param name="userState">Value to pass to the callback. It can be <c>null</c>.</param> /// <returns>An operation instance that can be used to manage the asynchronous request.</returns> [global::GlobalNamespaceTest_Attribute()] public global::OpenRiaServices.Client.InvokeOperation<global::GlobalNamespaceTest_Enum> InvokeReturn([global::GlobalNamespaceTest_ValidationAttribute()] global::GlobalNamespaceTest_Enum enumParameter, global::System.Action<global::OpenRiaServices.Client.InvokeOperation<global::GlobalNamespaceTest_Enum>> callback, object userState) { global::System.Collections.Generic.Dictionary<string, object> parameters = new global::System.Collections.Generic.Dictionary<string, object>(); parameters.Add("enumParameter", enumParameter); this.ValidateMethod("InvokeReturn", parameters); return this.InvokeOperation<global::GlobalNamespaceTest_Enum>("InvokeReturn", typeof(global::GlobalNamespaceTest_Enum), parameters, true, callback, userState); } /// <summary> /// Asynchronously invokes the 'InvokeReturn' method of the DomainService. /// </summary> /// <param name="enumParameter">The value for the 'enumParameter' parameter of this action.</param> /// <returns>An operation instance that can be used to manage the asynchronous request.</returns> [global::GlobalNamespaceTest_Attribute()] public global::OpenRiaServices.Client.InvokeOperation<global::GlobalNamespaceTest_Enum> InvokeReturn([global::GlobalNamespaceTest_ValidationAttribute()] global::GlobalNamespaceTest_Enum enumParameter) { global::System.Collections.Generic.Dictionary<string, object> parameters = new global::System.Collections.Generic.Dictionary<string, object>(); parameters.Add("enumParameter", enumParameter); this.ValidateMethod("InvokeReturn", parameters); return this.InvokeOperation<global::GlobalNamespaceTest_Enum>("InvokeReturn", typeof(global::GlobalNamespaceTest_Enum), parameters, true, null, null); } /// <summary> /// Asynchronously invokes the 'InvokeReturn' method of the DomainService. /// </summary> /// <param name="enumParameter">The value for the 'enumParameter' parameter of this action.</param> /// <param name="cancellationToken">A cancellation token that can be used to cancel the work</param> /// <returns>An operation instance that can be used to manage the asynchronous request.</returns> [global::GlobalNamespaceTest_Attribute()] public global::System.Threading.Tasks.Task<global::OpenRiaServices.Client.InvokeResult<global::GlobalNamespaceTest_Enum>> InvokeReturnAsync([global::GlobalNamespaceTest_ValidationAttribute()] global::GlobalNamespaceTest_Enum enumParameter, global::System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { global::System.Collections.Generic.Dictionary<string, object> parameters = new global::System.Collections.Generic.Dictionary<string, object>(); parameters.Add("enumParameter", enumParameter); this.ValidateMethod("InvokeReturn", parameters); return this.InvokeOperationAsync<global::GlobalNamespaceTest_Enum>("InvokeReturn", parameters, true, cancellationToken); } /// <summary> /// Asynchronously invokes the 'InvokeVoid' method of the DomainService. /// </summary> /// <param name="enumParameter">The value for the 'enumParameter' parameter of this action.</param> /// <param name="callback">Callback to invoke when the operation completes.</param> /// <param name="userState">Value to pass to the callback. It can be <c>null</c>.</param> /// <returns>An operation instance that can be used to manage the asynchronous request.</returns> [global::GlobalNamespaceTest_Attribute()] public global::OpenRiaServices.Client.InvokeOperation InvokeVoid([global::GlobalNamespaceTest_ValidationAttribute()] global::GlobalNamespaceTest_Enum enumParameter, global::System.Action<global::OpenRiaServices.Client.InvokeOperation> callback, object userState) { global::System.Collections.Generic.Dictionary<string, object> parameters = new global::System.Collections.Generic.Dictionary<string, object>(); parameters.Add("enumParameter", enumParameter); this.ValidateMethod("InvokeVoid", parameters); return this.InvokeOperation("InvokeVoid", typeof(void), parameters, true, callback, userState); } /// <summary> /// Asynchronously invokes the 'InvokeVoid' method of the DomainService. /// </summary> /// <param name="enumParameter">The value for the 'enumParameter' parameter of this action.</param> /// <returns>An operation instance that can be used to manage the asynchronous request.</returns> [global::GlobalNamespaceTest_Attribute()] public global::OpenRiaServices.Client.InvokeOperation InvokeVoid([global::GlobalNamespaceTest_ValidationAttribute()] global::GlobalNamespaceTest_Enum enumParameter) { global::System.Collections.Generic.Dictionary<string, object> parameters = new global::System.Collections.Generic.Dictionary<string, object>(); parameters.Add("enumParameter", enumParameter); this.ValidateMethod("InvokeVoid", parameters); return this.InvokeOperation("InvokeVoid", typeof(void), parameters, true, null, null); } /// <summary> /// Asynchronously invokes the 'InvokeVoid' method of the DomainService. /// </summary> /// <param name="enumParameter">The value for the 'enumParameter' parameter of this action.</param> /// <param name="cancellationToken">A cancellation token that can be used to cancel the work</param> /// <returns>An operation instance that can be used to manage the asynchronous request.</returns> [global::GlobalNamespaceTest_Attribute()] public global::System.Threading.Tasks.Task<global::OpenRiaServices.Client.InvokeResult> InvokeVoidAsync([global::GlobalNamespaceTest_ValidationAttribute()] global::GlobalNamespaceTest_Enum enumParameter, global::System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { global::System.Collections.Generic.Dictionary<string, object> parameters = new global::System.Collections.Generic.Dictionary<string, object>(); parameters.Add("enumParameter", enumParameter); this.ValidateMethod("InvokeVoid", parameters); return this.InvokeOperationAsync("InvokeVoid", parameters, true, cancellationToken); } /// <summary> /// Creates a new EntityContainer for this DomainContext's EntitySets. /// </summary> /// <returns>A new container instance.</returns> protected override global::OpenRiaServices.Client.EntityContainer CreateEntityContainer() { return new global::GlobalNamespaceTest.GlobalNamespaceTest_DomainContext.GlobalNamespaceTest_DomainContextEntityContainer(); } /// <summary> /// Service contract for the 'GlobalNamespaceTest_DomainService' DomainService. /// </summary> [global::System.ServiceModel.ServiceContractAttribute()] [global::System.ServiceModel.ServiceKnownTypeAttribute(typeof(global::GlobalNamespaceTest_Enum))] public interface IGlobalNamespaceTest_DomainServiceContract { /// <summary> /// Asynchronously invokes the 'GetEntities' operation. /// </summary> /// <param name="callback">Callback to invoke on completion.</param> /// <param name="asyncState">Optional state object.</param> /// <returns>An IAsyncResult that can be used to monitor the request.</returns> [global::OpenRiaServices.Client.HasSideEffects(false)] [global::System.ServiceModel.OperationContractAttribute(AsyncPattern=true, Action="http://tempuri.org/GlobalNamespaceTest_DomainService/GetEntities", ReplyAction="http://tempuri.org/GlobalNamespaceTest_DomainService/GetEntitiesResponse")] global::System.IAsyncResult BeginGetEntities(global::System.AsyncCallback callback, object asyncState); /// <summary> /// Completes the asynchronous operation begun by 'BeginGetEntities'. /// </summary> /// <param name="result">The IAsyncResult returned from 'BeginGetEntities'.</param> /// <returns>The 'QueryResult' returned from the 'GetEntities' operation.</returns> global::OpenRiaServices.Client.QueryResult<global::GlobalNamespaceTest.GlobalNamespaceTest_Entity> EndGetEntities(global::System.IAsyncResult result); /// <summary> /// Asynchronously invokes the 'InvokeReturn' operation. /// </summary> /// <param name="enumParameter">The value for the 'enumParameter' parameter of this action.</param> /// <param name="callback">Callback to invoke on completion.</param> /// <param name="asyncState">Optional state object.</param> /// <returns>An IAsyncResult that can be used to monitor the request.</returns> [global::OpenRiaServices.Client.HasSideEffects(true)] [global::System.ServiceModel.OperationContractAttribute(AsyncPattern=true, Action="http://tempuri.org/GlobalNamespaceTest_DomainService/InvokeReturn", ReplyAction="http://tempuri.org/GlobalNamespaceTest_DomainService/InvokeReturnResponse")] global::System.IAsyncResult BeginInvokeReturn(global::GlobalNamespaceTest_Enum enumParameter, global::System.AsyncCallback callback, object asyncState); /// <summary> /// Completes the asynchronous operation begun by 'BeginInvokeReturn'. /// </summary> /// <param name="result">The IAsyncResult returned from 'BeginInvokeReturn'.</param> /// <returns>The 'GlobalNamespaceTest_Enum' returned from the 'InvokeReturn' operation.</returns> global::GlobalNamespaceTest_Enum EndInvokeReturn(global::System.IAsyncResult result); /// <summary> /// Asynchronously invokes the 'InvokeVoid' operation. /// </summary> /// <param name="enumParameter">The value for the 'enumParameter' parameter of this action.</param> /// <param name="callback">Callback to invoke on completion.</param> /// <param name="asyncState">Optional state object.</param> /// <returns>An IAsyncResult that can be used to monitor the request.</returns> [global::OpenRiaServices.Client.HasSideEffects(true)] [global::System.ServiceModel.OperationContractAttribute(AsyncPattern=true, Action="http://tempuri.org/GlobalNamespaceTest_DomainService/InvokeVoid", ReplyAction="http://tempuri.org/GlobalNamespaceTest_DomainService/InvokeVoidResponse")] global::System.IAsyncResult BeginInvokeVoid(global::GlobalNamespaceTest_Enum enumParameter, global::System.AsyncCallback callback, object asyncState); /// <summary> /// Completes the asynchronous operation begun by 'BeginInvokeVoid'. /// </summary> /// <param name="result">The IAsyncResult returned from 'BeginInvokeVoid'.</param> void EndInvokeVoid(global::System.IAsyncResult result); /// <summary> /// Asynchronously invokes the 'ReadEntities' operation. /// </summary> /// <param name="enumParameter">The value for the 'enumParameter' parameter of this action.</param> /// <param name="callback">Callback to invoke on completion.</param> /// <param name="asyncState">Optional state object.</param> /// <returns>An IAsyncResult that can be used to monitor the request.</returns> [global::OpenRiaServices.Client.HasSideEffects(false)] [global::System.ServiceModel.OperationContractAttribute(AsyncPattern=true, Action="http://tempuri.org/GlobalNamespaceTest_DomainService/ReadEntities", ReplyAction="http://tempuri.org/GlobalNamespaceTest_DomainService/ReadEntitiesResponse")] global::System.IAsyncResult BeginReadEntities(global::GlobalNamespaceTest_Enum enumParameter, global::System.AsyncCallback callback, object asyncState); /// <summary> /// Completes the asynchronous operation begun by 'BeginReadEntities'. /// </summary> /// <param name="result">The IAsyncResult returned from 'BeginReadEntities'.</param> /// <returns>The 'QueryResult' returned from the 'ReadEntities' operation.</returns> global::OpenRiaServices.Client.QueryResult<global::GlobalNamespaceTest.GlobalNamespaceTest_Entity> EndReadEntities(global::System.IAsyncResult result); /// <summary> /// Asynchronously invokes the 'SubmitChanges' operation. /// </summary> /// <param name="changeSet">The change-set to submit.</param> /// <param name="callback">Callback to invoke on completion.</param> /// <param name="asyncState">Optional state object.</param> /// <returns>An IAsyncResult that can be used to monitor the request.</returns> [global::System.ServiceModel.OperationContractAttribute(AsyncPattern=true, Action="http://tempuri.org/GlobalNamespaceTest_DomainService/SubmitChanges", ReplyAction="http://tempuri.org/GlobalNamespaceTest_DomainService/SubmitChangesResponse")] global::System.IAsyncResult BeginSubmitChanges(global::System.Collections.Generic.IEnumerable<global::OpenRiaServices.Client.ChangeSetEntry> changeSet, global::System.AsyncCallback callback, object asyncState); /// <summary> /// Completes the asynchronous operation begun by 'BeginSubmitChanges'. /// </summary> /// <param name="result">The IAsyncResult returned from 'BeginSubmitChanges'.</param> /// <returns>The collection of change-set entry elements returned from 'SubmitChanges'.</returns> global::System.Collections.Generic.IEnumerable<global::OpenRiaServices.Client.ChangeSetEntry> EndSubmitChanges(global::System.IAsyncResult result); } internal sealed class GlobalNamespaceTest_DomainContextEntityContainer : global::OpenRiaServices.Client.EntityContainer { public GlobalNamespaceTest_DomainContextEntityContainer() { this.CreateEntitySet<global::GlobalNamespaceTest.GlobalNamespaceTest_Entity>(global::OpenRiaServices.Client.EntitySetOperations.All); } } } /// <summary> /// The 'GlobalNamespaceTest_Entity' entity class. /// </summary> [global::GlobalNamespaceTest_Attribute()] [global::GlobalNamespaceTest_ValidationAttribute()] [global::System.Runtime.Serialization.DataContractAttribute(Namespace="http://schemas.datacontract.org/2004/07/GlobalNamespaceTest")] public sealed partial class GlobalNamespaceTest_Entity : global::OpenRiaServices.Client.Entity { private global::GlobalNamespaceTest_Enum _enumProperty; private global::GlobalNamespaceTest_Enum_NonShared _enumProperty_NonShared; private int _key; #region Extensibility Method Definitions /// <summary> /// This method is invoked from the constructor once initialization is complete and /// can be used for further object setup. /// </summary> partial void OnCreated(); partial void OnEnumPropertyChanging(global::GlobalNamespaceTest_Enum value); partial void OnEnumPropertyChanged(); partial void OnEnumProperty_NonSharedChanging(global::GlobalNamespaceTest_Enum_NonShared value); partial void OnEnumProperty_NonSharedChanged(); partial void OnKeyChanging(int value); partial void OnKeyChanged(); partial void OnCustomUpdateEntityInvoking(global::GlobalNamespaceTest_Enum enumParameter); partial void OnCustomUpdateEntityInvoked(); #endregion /// <summary> /// Initializes a new instance of the <see cref="GlobalNamespaceTest_Entity"/> class. /// </summary> public GlobalNamespaceTest_Entity() { this.OnCreated(); } /// <summary> /// Gets or sets the 'EnumProperty' value. /// </summary> [global::GlobalNamespaceTest_ValidationAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public global::GlobalNamespaceTest_Enum EnumProperty { get { return this._enumProperty; } set { if ((this._enumProperty != value)) { this.OnEnumPropertyChanging(value); this.RaiseDataMemberChanging("EnumProperty"); this.ValidateProperty("EnumProperty", value); this._enumProperty = value; this.RaiseDataMemberChanged("EnumProperty"); this.OnEnumPropertyChanged(); } } } /// <summary> /// Gets or sets the 'EnumProperty_NonShared' value. /// </summary> [global::GlobalNamespaceTest_ValidationAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public global::GlobalNamespaceTest_Enum_NonShared EnumProperty_NonShared { get { return this._enumProperty_NonShared; } set { if ((this._enumProperty_NonShared != value)) { this.OnEnumProperty_NonSharedChanging(value); this.RaiseDataMemberChanging("EnumProperty_NonShared"); this.ValidateProperty("EnumProperty_NonShared", value); this._enumProperty_NonShared = value; this.RaiseDataMemberChanged("EnumProperty_NonShared"); this.OnEnumProperty_NonSharedChanged(); } } } /// <summary> /// Gets or sets the 'Key' value. /// </summary> [global::GlobalNamespaceTest_ValidationAttribute()] [global::System.ComponentModel.DataAnnotations.CustomValidationAttribute(typeof(global::GlobalNamespaceTest_Validation), "Validate")] [global::System.ComponentModel.DataAnnotations.EditableAttribute(false, AllowInitialValue=true)] [global::System.ComponentModel.DataAnnotations.KeyAttribute()] [global::System.ComponentModel.DataAnnotations.RoundtripOriginalAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public int Key { get { return this._key; } set { if ((this._key != value)) { this.OnKeyChanging(value); this.ValidateProperty("Key", value); this._key = value; this.RaisePropertyChanged("Key"); this.OnKeyChanged(); } } } /// <summary> /// Gets a value indicating whether the 'CustomUpdateEntity' action has been invoked on this entity. /// </summary> [global::System.ComponentModel.DataAnnotations.DisplayAttribute(AutoGenerateField=false)] public bool IsCustomUpdateEntityInvoked { get { return base.IsActionInvoked("CustomUpdateEntity"); } } /// <summary> /// Gets a value indicating whether the 'CustomUpdateEntity' method can be invoked on this entity. /// </summary> [global::System.ComponentModel.DataAnnotations.DisplayAttribute(AutoGenerateField=false)] public bool CanCustomUpdateEntity { get { return base.CanInvokeAction("CustomUpdateEntity"); } } /// <summary> /// Computes a value from the key fields that uniquely identifies this entity instance. /// </summary> /// <returns>An object instance that uniquely identifies this entity instance.</returns> public override object GetIdentity() { return this._key; } /// <summary> /// Invokes the 'CustomUpdateEntity' action on this entity. /// </summary> /// <param name="enumParameter">The value to pass to the server method's 'enumParameter' parameter.</param> [global::GlobalNamespaceTest_Attribute()] [global::OpenRiaServices.Client.EntityAction("CustomUpdateEntity", AllowMultipleInvocations=false)] public void CustomUpdateEntity(global::GlobalNamespaceTest_Enum enumParameter) { this.OnCustomUpdateEntityInvoking(enumParameter); base.InvokeAction("CustomUpdateEntity", enumParameter); this.OnCustomUpdateEntityInvoked(); } } }
56.469758
355
0.660431
[ "Apache-2.0" ]
Daniel-Svensson/OpenRiaServices
src/Test/Desktop/OpenRiaServices.Common.DomainServices.Test/Baselines/FullTypeNames/Scenarios/GlobalNamespace.g.cs
28,009
C#
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using osuTK; namespace osu.Game.IO.Serialization.Converters { /// <summary> /// A type of <see cref="JsonConverter"/> that serializes only the X and Y coordinates of a <see cref="Vector2"/>. /// </summary> public class Vector2Converter : JsonConverter<Vector2> { public override Vector2 ReadJson(JsonReader reader, Type objectType, Vector2 existingValue, bool hasExistingValue, JsonSerializer serializer) { var obj = JObject.Load(reader); return new Vector2((float)obj["x"], (float)obj["y"]); } public override void WriteJson(JsonWriter writer, Vector2 value, JsonSerializer serializer) { writer.WriteStartObject(); writer.WritePropertyName("x"); writer.WriteValue(value.X); writer.WritePropertyName("y"); writer.WriteValue(value.Y); writer.WriteEndObject(); } } }
34.823529
150
0.633446
[ "MIT" ]
MATRIX-feather/osu
osu.Game/IO/Serialization/Converters/Vector2Converter.cs
1,151
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Configuration; using System.Data.SqlClient; using System.Data; public partial class FunctionAnouncement_Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (Session["login"] != "OK") { Response.Clear(); Response.Write(" <script language='javascript'+>top.location='/jssm/login.aspx';alert('对不起,您没有登陆!');</script>"); Response.Flush(); Response.End(); } bool 班级签到Bol = false, 班级签到管理Bol = false; string consql = "SELECT 班级签到,班级签到管理 FROM 权限表 WHERE 职务 = " + Session["职务"]; SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Main1ConnectionString"].ToString()); con.Open(); SqlCommand cons = new SqlCommand(consql, con); SqlDataReader conda = cons.ExecuteReader(); while (conda.Read()) { 班级签到Bol = conda.GetBoolean(0); 班级签到管理Bol = conda.GetBoolean(1); } con.Close(); if (班级签到Bol == false && 班级签到管理Bol == false) { Response.Clear(); Response.Write(" <script language='javascript'+>top.location='/jssm/index.aspx';alert('对不起,您没有此项操作权限!');</script>"); Response.Flush(); Response.End(); } 刷卡签到.Visible = false; 查看签到情况.Visible = false; if (班级签到Bol == true) { 标题.Text = "请刷卡签到:" + Session["班级名"]; 刷卡签到.Visible = true; Page.Form.DefaultButton = 确定.UniqueID; } if (班级签到管理Bol == true) { 标题.Text = "查看各班级签到情况"; 查看签到情况.Visible = true; } } protected void Button1_Click(object sender, EventArgs e) { string ConnectionString = ConfigurationManager.ConnectionStrings["SportConnectionString"].ToString(); SqlConnection con = new SqlConnection(ConnectionString); con.Open(); try { string ClearanceSql, IC = "", IC卡对应姓名 = "", IC卡对应班级 = ""; if (TextBox1.Text.ToString().Length == 10) { DateTime 上午到校时间 = DateTime.Now, 下午到校时间 = DateTime.Now; ClearanceSql = "SELECT IC卡编号,姓名,班级 FROM IC卡 WHERE ICID = '" + TextBox1.Text + "'"; SqlCommand cons = new SqlCommand(ClearanceSql, con); SqlDataReader conda = cons.ExecuteReader(); while (conda.Read()) { IC = conda.GetString(0); IC卡对应姓名 = conda.GetString(1); IC卡对应班级 = conda.GetString(2); } conda.Close(); string ClearanceSql2 = "SELECT 上午到校时间,下午到校时间 FROM 到校时间"; SqlCommand cons2 = new SqlCommand(ClearanceSql2, con); SqlDataReader conda2 = cons2.ExecuteReader(); while (conda2.Read()) { 上午到校时间 = conda2.GetDateTime(0); 下午到校时间 = conda2.GetDateTime(1); } conda2.Close(); if (IC != "") { string updata; bool 是否迟到 = false; DateTime Time = DateTime.Now; if ((Time.TimeOfDay > 上午到校时间.AddMinutes(-30).TimeOfDay) && (Time.TimeOfDay < 上午到校时间.AddMinutes(30).TimeOfDay)) //早上查迟到 { if (Time.TimeOfDay > 上午到校时间.TimeOfDay) { 是否迟到 = true; } updata = "INSERT INTO 班级签到 (IC卡编号,进入时间,姓名,班级,是否迟到) VALUES ('" + IC + "', '" + DateTime.Now + "','" + IC卡对应姓名 + "','" + IC卡对应班级 + "','" + 是否迟到 + "')"; SqlCommand Command1 = new SqlCommand(); Command1.Connection = con; Command1.CommandText = updata; Command1.CommandType = CommandType.Text; Command1.ExecuteNonQuery(); if (是否迟到 == false) { Label1.Text = "学生进入"; } else { Label1.Text = "对不起,您已迟到!"; } } else if ((Time.TimeOfDay > 下午到校时间.AddMinutes(-30).TimeOfDay) && (Time.TimeOfDay < 下午到校时间.AddMinutes(30).TimeOfDay)) //中午查迟到 { if (Time.TimeOfDay > 下午到校时间.TimeOfDay) { 是否迟到 = true; } updata = "INSERT INTO 班级签到 (IC卡编号,进入时间,姓名,班级,是否迟到) VALUES ('" + IC + "', '" + DateTime.Now + "','" + IC卡对应姓名 + "','" + IC卡对应班级 + "','" + 是否迟到 + "')"; SqlCommand Command1 = new SqlCommand(); Command1.Connection = con; Command1.CommandText = updata; Command1.CommandType = CommandType.Text; Command1.ExecuteNonQuery(); if (是否迟到 == false) { Label1.Text = "学生进入"; } else { Label1.Text = "对不起,您已迟到!"; } } else { Response.Clear(); Response.Write(" <script language='javascript'+>top.location='../index.aspx';alert('对不起,现在不是签到时间!');</script>"); Response.Flush(); Response.End(); } } else { Response.Clear(); Response.Write(" <script language='javascript'+>top.location='../icerror.aspx?num=" + TextBox1.Text + ";</script>"); Response.Flush(); Response.End(); } } else { Label1.Text = "请刷卡!"; } } finally { if (con != null && con.State != System.Data.ConnectionState.Closed) { con.Close(); } } TextBox1.Text = ""; Page.Form.DefaultFocus = TextBox1.UniqueID; } }
31.441315
173
0.440346
[ "MIT" ]
Ran-ying/JNFLS-IT-Dept
SAIMS/FunctionAttendanceManaging/class.aspx.cs
7,413
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: MethodRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; /// <summary> /// The type WorkbookFunctionsRoundRequest. /// </summary> public partial class WorkbookFunctionsRoundRequest : BaseRequest, IWorkbookFunctionsRoundRequest { /// <summary> /// Constructs a new WorkbookFunctionsRoundRequest. /// </summary> public WorkbookFunctionsRoundRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { this.ContentType = "application/json"; this.RequestBody = new WorkbookFunctionsRoundRequestBody(); } /// <summary> /// Gets the request body. /// </summary> public WorkbookFunctionsRoundRequestBody RequestBody { get; private set; } /// <summary> /// Issues the POST request. /// </summary> public System.Threading.Tasks.Task<WorkbookFunctionResult> PostAsync() { return this.PostAsync(CancellationToken.None); } /// <summary> /// Issues the POST request. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await for async call.</returns> public System.Threading.Tasks.Task<WorkbookFunctionResult> PostAsync( CancellationToken cancellationToken) { this.Method = "POST"; return this.SendAsync<WorkbookFunctionResult>(this.RequestBody, cancellationToken); } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IWorkbookFunctionsRoundRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IWorkbookFunctionsRoundRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } } }
34.712644
153
0.579139
[ "MIT" ]
DamienTehDemon/msgraph-sdk-dotnet
src/Microsoft.Graph/Generated/requests/WorkbookFunctionsRoundRequest.cs
3,020
C#
namespace YAMP { [Description("ArccosFunctionDescription")] [Kind(PopularKinds.Trigonometric)] [Link("ArccosFunctionLink")] sealed class ArccosFunction : StandardFunction { protected override ScalarValue GetValue(ScalarValue z) { return z.Arccos(); } } }
22.571429
62
0.639241
[ "BSD-3-Clause" ]
FlorianRappl/YAMP
YAMP.Core/Functions/Trigonometric/ArccosFunction.cs
318
C#
/* Yet Another Forum.NET * Copyright (C) 2003-2005 Bjørnar Henden * Copyright (C) 2006-2013 Jaben Cargman * Copyright (C) 2014 Ingo Herbote * http://www.yetanotherforum.net/ * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace YAF.Types.Exceptions { using System; using YAF.Types.Extensions; /// <summary> /// The No TopicRow Exception /// </summary> public class NoTopicRowException : Exception { /// <summary> /// Initializes a new instance of the <see cref="NoTopicRowException"/> class. /// </summary> /// <param name="topicRowID">The topic row identifier.</param> public NoTopicRowException(int? topicRowID) : base("No topic row found for topic row id [{0}]".FormatWith(topicRowID ?? 0)) { } } }
36.590909
92
0.67205
[ "Apache-2.0" ]
azarbara/YAFNET
yafsrc/YAF.Types/Exceptions/NoTopicRowException.cs
1,570
C#
using System; using System.Collections.Generic; using System.Linq; namespace zad_6 { class Program { static void Main() { var usNameIpCount = new SortedDictionary<string, Dictionary<string, int>>(); while (true) { string[] input = Console.ReadLine().Split(' ').ToArray(); if (input[0] == "end") { foreach (var kvp in usNameIpCount) { Console.WriteLine($"{kvp.Key}: "); string result = ""; foreach (var ipC in kvp.Value) { result+=$"{ipC.Key} => {ipC.Value}, "; } result = result.TrimEnd(' ', ',')+"."; Console.WriteLine(result); // Console.WriteLine(); } return; } input[0] = input[0].Remove(0, 3);//ip input[2] = input[2].Remove(0, 5);//name Dictionary<string, int> temp = new Dictionary<string, int>(); temp[input[0]] = 1; if (!usNameIpCount.ContainsKey(input[2]))//Ако в базата не се съдържа вредителя { usNameIpCount[input[2]] = temp; } else { if (usNameIpCount[input[2]].ContainsKey(input[0]))//Ако в базата с вредителя се съдържа ипто { usNameIpCount[input[2]][input[0]]++; } else//Ако в базата с вредителя НЕ се съдържа ипто { usNameIpCount[input[2]].Add(input[0], 1); } } } } } }
35.425926
112
0.384736
[ "MIT" ]
StackSmack007/Programing-Fundamentals-September-2018
Dictionaries, Lambda and LINQ-Excersises/zad_6/Program.cs
2,013
C#
using NHapi.Base.Parser; using NHapi.Base; using NHapi.Base.Log; using System; using System.Collections.Generic; using NHapi.Model.V25.Segment; using NHapi.Model.V25.Datatype; using NHapi.Base.Model; namespace NHapi.Model.V25.Group { ///<summary> ///Represents the NMQ_N01_CLOCK_AND_STATISTICS Group. A Group is an ordered collection of message /// segments that can repeat together or be optionally in/excluded together. /// This Group contains the following elements: ///<ol> ///<li>0: NCK (System Clock) optional </li> ///<li>1: NST (Application control level statistics) optional </li> ///<li>2: NSC (Application Status Change) optional </li> ///</ol> ///</summary> [Serializable] public class NMQ_N01_CLOCK_AND_STATISTICS : AbstractGroup { ///<summary> /// Creates a new NMQ_N01_CLOCK_AND_STATISTICS Group. ///</summary> public NMQ_N01_CLOCK_AND_STATISTICS(IGroup parent, IModelClassFactory factory) : base(parent, factory){ try { this.add(typeof(NCK), false, false); this.add(typeof(NST), false, false); this.add(typeof(NSC), false, false); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error creating NMQ_N01_CLOCK_AND_STATISTICS - this is probably a bug in the source code generator.", e); } } ///<summary> /// Returns NCK (System Clock) - creates it if necessary ///</summary> public NCK NCK { get{ NCK ret = null; try { ret = (NCK)this.GetStructure("NCK"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } } ///<summary> /// Returns NST (Application control level statistics) - creates it if necessary ///</summary> public NST NST { get{ NST ret = null; try { ret = (NST)this.GetStructure("NST"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } } ///<summary> /// Returns NSC (Application Status Change) - creates it if necessary ///</summary> public NSC NSC { get{ NSC ret = null; try { ret = (NSC)this.GetStructure("NSC"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } } } }
30.659091
166
0.683469
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
AMCN41R/nHapi
src/NHapi.Model.V25/Group/NMQ_N01_CLOCK_AND_STATISTICS.cs
2,698
C#
// Copyright (c) Josef Pihrt and Contributors. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Immutable; using System.Composition; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslynator.CodeFixes; using Roslynator.CSharp.Refactorings; namespace Roslynator.CSharp.CodeFixes { [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(VariableDeclarationCodeFixProvider))] [Shared] public sealed class VariableDeclarationCodeFixProvider : BaseCodeFixProvider { public override ImmutableArray<string> FixableDiagnosticIds { get { return ImmutableArray.Create(DiagnosticIdentifiers.SplitVariableDeclaration); } } public override async Task RegisterCodeFixesAsync(CodeFixContext context) { SyntaxNode root = await context.GetSyntaxRootAsync().ConfigureAwait(false); if (!TryFindFirstAncestorOrSelf(root, context.Span, out VariableDeclarationSyntax variableDeclaration)) return; CodeAction codeAction = CodeAction.Create( SplitVariableDeclarationRefactoring.GetTitle(variableDeclaration), ct => SplitVariableDeclarationRefactoring.RefactorAsync(context.Document, variableDeclaration, ct), GetEquivalenceKey(DiagnosticIdentifiers.SplitVariableDeclaration)); context.RegisterCodeFix(codeAction, context.Diagnostics); } } }
41.25
156
0.749697
[ "Apache-2.0" ]
ProphetLamb-Organistion/Roslynator
src/Analyzers.CodeFixes/CSharp/CodeFixes/VariableDeclarationCodeFixProvider.cs
1,652
C#
using Xamarin.Forms; using XLabs.Forms.Controls; [assembly: ExportRenderer(typeof(ExtendedEntry), typeof(ExtendedEntryRenderer))] namespace XLabs.Forms.Controls { using System.ComponentModel; using System.Linq; using System.Windows; using System.Windows.Controls; using Microsoft.Phone.Controls; using Xamarin.Forms; using Xamarin.Forms.Platform.WinPhone; using XLabs.Forms.Extensions; using TextAlignment = Xamarin.Forms.TextAlignment; /// <summary> /// Class ExtendedEntryRenderer. /// </summary> public class ExtendedEntryRenderer : EntryRenderer { /// <summary> /// The _this password box /// </summary> private PasswordBox _thisPasswordBox; /// <summary> /// The _this phone text box /// </summary> private PhoneTextBox _thisPhoneTextBox; /// <summary> /// Called when [element changed]. /// </summary> /// <param name="e">The e.</param> protected override void OnElementChanged(ElementChangedEventArgs<Entry> e) { base.OnElementChanged(e); var view = (ExtendedEntry)Element; //Because Xamarin EntryRenderer switches the type of control we need to find the right one if (view.IsPassword) { _thisPasswordBox = (PasswordBox) Control.Children.FirstOrDefault(c => c is PasswordBox); } else { _thisPhoneTextBox = (PhoneTextBox) Control.Children.FirstOrDefault(c => c is PhoneTextBox); } SetFont(view); SetTextAlignment(view); SetBorder(view); SetPlaceholderTextColor(view); SetMaxLength(view); } /// <summary> /// Handles the <see cref="E:ElementPropertyChanged" /> event. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="PropertyChangedEventArgs"/> instance containing the event data.</param> protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e) { base.OnElementPropertyChanged(sender, e); var view = (ExtendedEntry)Element; if(e.PropertyName == ExtendedEntry.FontProperty.PropertyName) SetFont(view); if (e.PropertyName == ExtendedEntry.XAlignProperty.PropertyName) SetTextAlignment(view); if (e.PropertyName == ExtendedEntry.HasBorderProperty.PropertyName) SetBorder(view); if (e.PropertyName == ExtendedEntry.PlaceholderTextColorProperty.PropertyName) SetPlaceholderTextColor(view); } /// <summary> /// Sets the border. /// </summary> /// <param name="view">The view.</param> private void SetBorder(ExtendedEntry view) { if (view.IsPassword && _thisPasswordBox != null) { _thisPasswordBox.BorderThickness = view.HasBorder ? new System.Windows.Thickness(2) : new System.Windows.Thickness(0); } else if (!view.IsPassword && _thisPhoneTextBox != null) { _thisPhoneTextBox.BorderThickness = view.HasBorder ? new System.Windows.Thickness(2) : new System.Windows.Thickness(0); } } /// <summary> /// Sets the text alignment. /// </summary> /// <param name="view">The view.</param> private void SetTextAlignment(ExtendedEntry view) { if (view.IsPassword && _thisPasswordBox != null) { switch (view.XAlign) { //NotCurrentlySupported: Text alaignement not available on Windows Phone for Password Entry } } else if (!view.IsPassword && _thisPhoneTextBox != null) { switch (view.XAlign) { case TextAlignment.Center: _thisPhoneTextBox.TextAlignment = System.Windows.TextAlignment.Center; break; case TextAlignment.End: _thisPhoneTextBox.TextAlignment = System.Windows.TextAlignment.Right; break; case TextAlignment.Start: _thisPhoneTextBox.TextAlignment = System.Windows.TextAlignment.Left; break; } } } /// <summary> /// Sets the font. /// </summary> /// <param name="view">The view.</param> private void SetFont(ExtendedEntry view) { if (view.Font != Font.Default) if (view.IsPassword) { if (_thisPasswordBox != null) { _thisPasswordBox.FontSize = view.Font.GetHeight(); } } else { if (_thisPhoneTextBox != null) { _thisPhoneTextBox.FontSize = view.Font.GetHeight(); } } } /// <summary> /// Sets the color of the placeholder text. /// </summary> /// <param name="view">The view.</param> private void SetPlaceholderTextColor(ExtendedEntry view) { //the EntryRenderer renders two child controls. A PhoneTextBox or PasswordBox // depending on the IsPassword property of the Xamarin form control if (view.IsPassword) { //NotCurrentlySupported: Placeholder text color is not supported on Windows Phone Password control } else { if (view.PlaceholderTextColor != Color.Default && _thisPhoneTextBox != null) { var hintStyle = new System.Windows.Style(typeof(System.Windows.Controls.ContentControl)); hintStyle.Setters.Add( new System.Windows.Setter( System.Windows.Controls.Control.ForegroundProperty, view.PlaceholderTextColor.ToBrush()) ); _thisPhoneTextBox.HintStyle = hintStyle; } } } /// <summary> /// Sets the MaxLength Characters. /// </summary> /// <param name="view">The view.</param> private void SetMaxLength(ExtendedEntry view) { if (_thisPhoneTextBox != null) _thisPhoneTextBox.MaxLength = view.MaxLength; } } }
35.546875
135
0.53641
[ "Apache-2.0" ]
alemarko/Xamarin-Forms-Labs
src/Forms/XLabs.Forms.WP8/Controls/ExtendedEntry/ExtendedEntryRenderer.cs
6,827
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Mime; using System.ServiceModel.Channels; using System.Text; using System.Text.RegularExpressions; using System.Xml.Linq; namespace WcfCoreMtomEncoder { public class MtomMessageEncoder : MessageEncoder { private readonly MessageEncoder _innerEncoder; public MtomMessageEncoder(MessageEncoder innerEncoder) { _innerEncoder = innerEncoder; } public override string ContentType => _innerEncoder.ContentType; public override string MediaType => _innerEncoder.MediaType; public override MessageVersion MessageVersion => _innerEncoder.MessageVersion; public override Message ReadMessage(ArraySegment<byte> buffer, BufferManager bufferManager, string contentType) { using (var stream = new MemoryStream(buffer.ToArray())) { var message = ReadMessage(stream, 1024, contentType); bufferManager.ReturnBuffer(buffer.Array); return message; } } public override Message ReadMessage(Stream stream, int maxSizeOfHeaders, string contentType) { if (_innerEncoder.IsContentTypeSupported(contentType)) { var memStream = new MemoryStream(); // We need an non disposed stream stream.CopyTo(memStream); memStream.Seek(0, SeekOrigin.Begin); return _innerEncoder.ReadMessage(memStream, maxSizeOfHeaders, contentType); } else { var parts = ( from p in GetMultipartContent(stream, contentType) select new MtomPart(p)).ToList(); var mainPart = ( from part in parts where part.ContentId == new ContentType(contentType).Parameters?["start"] select part).SingleOrDefault() ?? parts.First(); var mainContent = ResolveRefs(mainPart.GetStringContentForEncoder(_innerEncoder), parts); var mainContentStream = CreateStream(mainContent, mainPart.ContentType); return _innerEncoder.ReadMessage(mainContentStream, maxSizeOfHeaders, mainPart.ContentType.ToString()); } } public override ArraySegment<byte> WriteMessage(Message message, int maxMessageSize, BufferManager bufferManager, int messageOffset) { return _innerEncoder.WriteMessage(message, maxMessageSize, bufferManager, messageOffset); } public override void WriteMessage(Message message, Stream stream) { _innerEncoder.WriteMessage(message, stream); } public override bool IsContentTypeSupported(string contentType) { if (_innerEncoder.IsContentTypeSupported(contentType)) return true; var contentTypes = contentType.Split(';').Select(c => c.Trim()).ToList(); if (contentTypes.Contains("multipart/related", StringComparer.OrdinalIgnoreCase) && contentTypes.Contains("type=\"application/xop+xml\"", StringComparer.OrdinalIgnoreCase)) { return true; } return false; } public override T GetProperty<T>() { return _innerEncoder.GetProperty<T>(); } private static IEnumerable<HttpContent> GetMultipartContent(Stream stream, string contentType) { var content = new StreamContent(stream); content.Headers.Add("Content-Type", contentType); return content.ReadAsMultipartAsync().Result.Contents; } private static string ResolveRefs(string mainContent, IList<MtomPart> parts) { bool ReferenceMatch(XAttribute hrefAttr, MtomPart part) { var partId = Regex.Match(part.ContentId, "<(?<uri>.*)>"); var href = Regex.Match(hrefAttr.Value, "cid:(?<uri>.*)"); return href.Groups["uri"].Value == partId.Groups["uri"].Value; } var doc = XDocument.Parse(mainContent); var references = doc.Descendants(XName.Get("Include", "http://www.w3.org/2004/08/xop/include")).ToList(); foreach (var reference in references) { var referencedPart = ( from part in parts where ReferenceMatch(reference.Attribute("href"), part) select part).Single(); reference.ReplaceWith(Convert.ToBase64String(referencedPart.GetRawContent())); } return doc.ToString(SaveOptions.DisableFormatting); } private static Stream CreateStream(string content, MediaTypeHeaderValue contentType) { var encoding = !string.IsNullOrEmpty(contentType.CharSet) ? Encoding.GetEncoding(contentType.CharSet) : Encoding.Default; return new MemoryStream(encoding.GetBytes(content)); } } }
37.57554
140
0.613441
[ "MIT" ]
LokiMidgard/WcfCoreMtomEncoder
src/WcfCoreMtomEncoder/MtomMessageEncoder.cs
5,225
C#
// //AutoBlinkforSD.cs //SDユニティちゃん用オート目パチスクリプト //2014/12/10 N.Kobayashi // using UnityEngine; using System.Collections; namespace UnityChan { public class AutoBlinkforSD : MonoBehaviour { public bool isActive = true; //オート目パチ有効 public SkinnedMeshRenderer ref_face; //_faceへの参照 public float ratio_Close = 85.0f; //閉じ目ブレンドシェイプ比率 public float ratio_HalfClose = 20.0f; //半閉じ目ブレンドシェイプ比率 public int index_EYE_blk = 0; //目パチ用モーフのindex public int index_EYE_sml = 1; //目パチさせたくないモーフのindex public int index_EYE_dmg = 15; //目パチさせたくないモーフのindex [HideInInspector] public float ratio_Open = 0.0f; private bool timerStarted = false; //タイマースタート管理用 private bool isBlink = false; //目パチ管理用 public float timeBlink = 0.4f; //目パチの時間 private float timeRemining = 0.0f; //タイマー残り時間 public float threshold = 0.3f; // ランダム判定の閾値 public float interval = 3.0f; // ランダム判定のインターバル enum Status { Close, HalfClose, Open //目パチの状態 } private Status eyeStatus; //現在の目パチステータス void Awake () { //ref_SMR_EYE_DEF = GameObject.Find("EYE_DEF").GetComponent<SkinnedMeshRenderer>(); //ref_SMR_EL_DEF = GameObject.Find("EL_DEF").GetComponent<SkinnedMeshRenderer>(); } // Use this for initialization void Start () { ResetTimer (); // ランダム判定用関数をスタートする StartCoroutine ("RandomChange"); } //タイマーリセット void ResetTimer () { timeRemining = timeBlink; timerStarted = false; } // Update is called once per frame void Update () { if (!timerStarted) { eyeStatus = Status.Close; timerStarted = true; } if (timerStarted) { timeRemining -= Time.deltaTime; if (timeRemining <= 0.0f) { eyeStatus = Status.Open; ResetTimer (); } else if (timeRemining <= timeBlink * 0.3f) { eyeStatus = Status.HalfClose; } } } void LateUpdate () { if (isActive) { if (isBlink) { switch (eyeStatus) { case Status.Close: SetCloseEyes (); break; case Status.HalfClose: SetHalfCloseEyes (); break; case Status.Open: SetOpenEyes (); isBlink = false; break; } //Debug.Log(eyeStatus); } } } void SetCloseEyes () { ref_face.SetBlendShapeWeight (index_EYE_blk, ratio_Close); } void SetHalfCloseEyes () { ref_face.SetBlendShapeWeight (index_EYE_blk, ratio_HalfClose); } void SetOpenEyes () { ref_face.SetBlendShapeWeight (index_EYE_blk, ratio_Open); } // ランダム判定用関数 IEnumerator RandomChange () { // 無限ループ開始 while (true) { //ランダム判定用シード発生 float _seed = Random.Range (0.0f, 1.0f); if (!isBlink) { if (_seed > threshold) { //目パチさせたくないモーフの時だけ飛ばす. if(ref_face.GetBlendShapeWeight(index_EYE_sml)==0.0f && ref_face.GetBlendShapeWeight(index_EYE_dmg)==0.0f){ isBlink = true; } } } // 次の判定までインターバルを置く yield return new WaitForSeconds (interval); } } } }
21.479167
114
0.61623
[ "MIT" ]
flybirdQAQ/MyGenshinDemo
MyGenshin/Client/Assets/Import/UnityChan/Scripts/AutoBlinkforSD.cs
3,591
C#
#region BSD License /* * Use of this source code is governed by a BSD-style * license or other governing licenses that can be found in the LICENSE.md file or at * https://raw.githubusercontent.com/Krypton-Suite/Extended-Toolkit/master/LICENSE */ #endregion using Krypton.Toolkit.Suite.Extended.Utilities.SystemInternal.Speech; namespace Krypton.Toolkit.Suite.Extended.Utilities.System.SAPIInterop { internal static class SapiConstants { internal const string SPPROP_RESPONSE_SPEED = "ResponseSpeed"; internal const string SPPROP_COMPLEX_RESPONSE_SPEED = "ComplexResponseSpeed"; internal const string SPPROP_CFG_CONFIDENCE_REJECTION_THRESHOLD = "CFGConfidenceRejectionThreshold"; internal const uint SPDF_ALL = 255u; internal static SRID SapiErrorCode2SRID(SAPIErrorCodes code) { if (code >= SAPIErrorCodes.SPERR_FIRST && code <= SAPIErrorCodes.SPERR_LAST) { return (SRID)(258 + (code - -2147201023)); } switch (code) { case SAPIErrorCodes.SP_NO_RULE_ACTIVE: return SRID.SapiErrorNoRuleActive; case SAPIErrorCodes.SP_NO_RULES_TO_ACTIVATE: return SRID.SapiErrorNoRulesToActivate; case SAPIErrorCodes.SP_NO_PARSE_FOUND: return SRID.NoParseFound; case SAPIErrorCodes.S_FALSE: return SRID.UnexpectedError; default: return (SRID)(-1); } } } }
35.977273
108
0.640556
[ "BSD-3-Clause" ]
Krypton-Suite/Extended-Toolk
Source/Krypton Toolkit/Shared/Krypton.Toolkit.Suite.Extended.Utilities/Classes/System/SAPI/SAPI Interop/Classes/SapiConstants.cs
1,585
C#
namespace Apex.ConnectApi { using ApexSharp; using ApexSharp.ApexAttributes; using ApexSharp.Implementation; using global::Apex.System; /// <summary> /// /// </summary> public class SocialPostIntents { // infrastructure public SocialPostIntents(dynamic self) { Self = self; } dynamic Self { get; set; } static dynamic Implementation { get { return Implementor.GetImplementation(typeof(SocialPostIntents)); } } // API object approvalIntent { get { return Self.approvalIntent; } set { Self.approvalIntent = value; } } object deleteIntent { get { return Self.deleteIntent; } set { Self.deleteIntent = value; } } object followIntent { get { return Self.followIntent; } set { Self.followIntent = value; } } object hideIntent { get { return Self.hideIntent; } set { Self.hideIntent = value; } } object likeIntent { get { return Self.likeIntent; } set { Self.likeIntent = value; } } object replyIntent { get { return Self.replyIntent; } set { Self.replyIntent = value; } } public SocialPostIntents() { Self = Implementation.Constructor(); } public object clone() { return Self.clone(); } public bool equals(object obj) { return Self.equals(obj); } public double getBuildVersion() { return Self.getBuildVersion(); } public int hashCode() { return Self.hashCode(); } public string toString() { return Self.toString(); } } }
18.721805
80
0.38755
[ "MIT" ]
apexsharp/apexsharp
Apex/ConnectApi/SocialPostIntents.cs
2,490
C#
namespace SalesWebMvc.Models { public class ErrorViewModel { public string RequestId { get; set; } public string Message { get; set; } public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); } }
23.8
70
0.647059
[ "MIT" ]
RenatoSSouza/SalesWebMVC
SalesWebMvc/Models/ViewModels/ErrorViewModel.cs
238
C#
using System.Collections.Generic; using System.Threading.Tasks; namespace Elders.Cronus.Projections { public interface IProjectionStore { IEnumerable<ProjectionCommit> Load(ProjectionVersion version, IBlobId projectionId, int snapshotMarker); Task<IEnumerable<ProjectionCommit>> LoadAsync(ProjectionVersion version, IBlobId projectionId, int snapshotMarker); IEnumerable<ProjectionCommit> EnumerateProjection(ProjectionVersion version, IBlobId projectionId); void InitializeProjectionStore(ProjectionVersion projectionVersion); void Save(ProjectionCommit commit); } }
32.947368
123
0.782748
[ "Apache-2.0" ]
mynkow/Cronus
src/Elders.Cronus/Projections/IProjectionStore.cs
628
C#
using System; namespace Vehicles { class Sportscar : Car { } }
7.8
25
0.576923
[ "MIT" ]
rohithbodagala/Aptean_BootCamp
Assignments/30-03-2021 - 05-04-2021/6/Vehicles/Sportscar.cs
80
C#
#region License /* The MIT License Copyright (c) 2008 Sky Morey 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.Linq; using System.Collections; using System.Collections.Generic; namespace System.Web.Mvc { /// <summary> /// IndirectWebFormViewEngine /// </summary> public class IndirectWebFormViewEngine : WebFormViewEngine { public IndirectWebFormViewEngine() { } public IndirectWebFormViewEngine(params IndirectViewDirector[] viewDirectors) { ViewDirectors = viewDirectors; } public override ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache) { if (!EnumerableEx.IsNullOrEmpty(ViewDirectors)) foreach (var viewDirector in ViewDirectors.Where(x => x.CanIndirect(controllerContext))) { var result = base.FindView(controllerContext, (viewDirector.ViewNameBuilder != null ? viewDirector.ViewNameBuilder(controllerContext, viewName) : viewName), (viewDirector.MasterNameBuilder != null ? viewDirector.ViewNameBuilder(controllerContext, masterName) : masterName), useCache); if ((result != null) && (result.View != null)) return result; } return base.FindView(controllerContext, viewName, masterName, useCache); } public override ViewEngineResult FindPartialView(ControllerContext controllerContext, string partialViewName, bool useCache) { if (!EnumerableEx.IsNullOrEmpty(ViewDirectors)) foreach (var director in ViewDirectors.Where(x => x.CanIndirect(controllerContext))) { var result = base.FindPartialView(controllerContext, (director.PartialViewNameBuilder != null ? director.PartialViewNameBuilder(controllerContext, partialViewName) : partialViewName), useCache); if (result != null && result.View != null) return result; } return base.FindPartialView(controllerContext, partialViewName, useCache); } public IEnumerable<IndirectViewDirector> ViewDirectors { get; set; } } }
48.647059
305
0.692563
[ "MIT" ]
Grimace1975/bclcontrib-web
System.Web.MvcEx/Web/Mvc+IndirectView/IndirectWebFormViewEngine.cs
3,308
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using ConsumeAndMultiOutputPublisherWithRabbitMQ.Model; using Motor.Extensions.Hosting.Abstractions; namespace ConsumeAndMultiOutputPublisherWithRabbitMQ { public class MultiOutputService : IMultiOutputService<InputMessage, OutputMessage> { // Handle incoming messages public Task<IEnumerable<MotorCloudEvent<OutputMessage>>> ConvertMessageAsync( MotorCloudEvent<InputMessage> inputEvent, CancellationToken token = default) { // Get the input message from the cloud event var input = inputEvent.TypedData; // Do your magic here ..... var output = MagicFunc(input); // Create a new cloud event from your output message which is automatically published and return a new task. var outputEvent = output.Select(singleEvent => inputEvent.CreateNew(singleEvent)); return Task.FromResult(outputEvent); } private static IEnumerable<OutputMessage> MagicFunc(InputMessage input) { if (string.IsNullOrEmpty(input.FancyText)) { // Reject message in RabbitMQ queue (Any ArgumentException can be used to reject to messages.). throw new ArgumentNullException("FancyText is empty"); } return new List<OutputMessage> { new() { NotSoFancyText = input.FancyText.Reverse().ToString(), NotSoFancyNumber = input.FancyNumber * -1, }, new() { NotSoFancyText = input.FancyText, NotSoFancyNumber = input.FancyNumber * -2, }, }; } } }
35.641509
120
0.605082
[ "MIT" ]
rageagainsthepc/motornet
examples/ConsumeAndMultiOutputPublisherWithRabbitMQ/MultiOutputService.cs
1,889
C#
using System; namespace JenkinsTryOut.Net.MimeTypes { /* Copied from: * http://stackoverflow.com/questions/10362140/asp-mvc-are-there-any-constants-for-the-default-content-types */ /// <summary> /// Common mime types. /// </summary> public static class MimeTypeNames { ///<summary>Used to denote the encoding necessary for files containing JavaScript source code. The alternative MIME type for this file type is text/javascript.</summary> public const string ApplicationXJavascript = "application/x-javascript"; ///<summary>24bit Linear PCM audio at 8-48kHz, 1-N channels; Defined in RFC 3190</summary> public const string AudioL24 = "audio/L24"; ///<summary>Adobe Flash files for example with the extension .swf</summary> public const string ApplicationXShockwaveFlash = "application/x-shockwave-flash"; ///<summary>Arbitrary binary data.[5] Generally speaking this type identifies files that are not associated with a specific application. Contrary to past assumptions by software packages such as Apache this is not a type that should be applied to unknown files. In such a case, a server or application should not indicate a content type, as it may be incorrect, but rather, should omit the type in order to allow the recipient to guess the type.[6]</summary> public const string ApplicationOctetStream = "application/octet-stream"; ///<summary>Atom feeds</summary> public const string ApplicationAtomXml = "application/atom+xml"; ///<summary>Cascading Style Sheets; Defined in RFC 2318</summary> public const string TextCss = "text/css"; ///<summary>commands; subtype resident in Gecko browsers like Firefox 3.5</summary> public const string TextCmd = "text/cmd"; ///<summary>Comma-separated values; Defined in RFC 4180</summary> public const string TextCsv = "text/csv"; ///<summary>deb (file format), a software package format used by the Debian project</summary> public const string ApplicationXDeb = "application/x-deb"; ///<summary>Defined in RFC 1847</summary> public const string MultipartEncrypted = "multipart/encrypted"; ///<summary>Defined in RFC 1847</summary> public const string MultipartSigned = "multipart/signed"; ///<summary>Defined in RFC 2616</summary> public const string MessageHttp = "message/http"; ///<summary>Defined in RFC 4735</summary> public const string ModelExample = "model/example"; ///<summary>device-independent document in DVI format</summary> public const string ApplicationXDvi = "application/x-dvi"; ///<summary>DTD files; Defined by RFC 3023</summary> public const string ApplicationXmlDtd = "application/xml-dtd"; ///<summary>ECMAScript/JavaScript; Defined in RFC 4329 (equivalent to application/ecmascript but with looser processing rules) It is not accepted in IE 8 or earlier - text/javascript is accepted but it is defined as obsolete in RFC 4329. The "type" attribute of the <script> tag in HTML5 is optional and in practice omitting the media type of JavaScript programs is the most interoperable solution since all browsers have always assumed the correct default even before HTML5.</summary> public const string ApplicationJavascript = "application/javascript"; ///<summary>ECMAScript/JavaScript; Defined in RFC 4329 (equivalent to application/javascript but with stricter processing rules)</summary> public const string ApplicationEcmascript = "application/ecmascript"; ///<summary>EDI EDIFACT data; Defined in RFC 1767</summary> public const string ApplicationEdifact = "application/EDIFACT"; ///<summary>EDI X12 data; Defined in RFC 1767</summary> public const string ApplicationEdiX12 = "application/EDI-X12"; ///<summary>Email; Defined in RFC 2045 and RFC 2046</summary> public const string MessagePartial = "message/partial"; ///<summary>Email; EML files, MIME files, MHT files, MHTML files; Defined in RFC 2045 and RFC 2046</summary> public const string MessageRfc822 = "message/rfc822"; ///<summary>Extensible Markup Language; Defined in RFC 3023</summary> public const string TextXml = "text/xml"; ///<summary>Flash video (FLV files)</summary> public const string VideoXFlv = "video/x-flv"; ///<summary>GIF image; Defined in RFC 2045 and RFC 2046</summary> public const string ImageGif = "image/gif"; ///<summary>GoogleWebToolkit data</summary> public const string TextXGwtRpc = "text/x-gwt-rpc"; ///<summary>Gzip</summary> public const string ApplicationXGzip = "application/x-gzip"; ///<summary>HTML; Defined in RFC 2854</summary> public const string TextHtml = "text/html"; ///<summary>ICO image; Registered[9]</summary> public const string ImageVndMicrosoftIcon = "image/vnd.microsoft.icon"; ///<summary>IGS files, IGES files; Defined in RFC 2077</summary> public const string ModelIges = "model/iges"; ///<summary>IMDN Instant Message Disposition Notification; Defined in RFC 5438</summary> public const string MessageImdnXml = "message/imdn+xml"; ///<summary>JavaScript Object Notation JSON; Defined in RFC 4627</summary> public const string ApplicationJson = "application/json"; ///<summary>JavaScript Object Notation (JSON) Patch; Defined in RFC 6902</summary> public const string ApplicationJsonPatch = "application/json-patch+json"; ///<summary>JavaScript - Defined in and obsoleted by RFC 4329 in order to discourage its usage in favor of application/javascript. However,text/javascript is allowed in HTML 4 and 5 and, unlike application/javascript, has cross-browser support. The "type" attribute of the <script> tag in HTML5 is optional and there is no need to use it at all since all browsers have always assumed the correct default (even in HTML 4 where it was required by the specification).</summary> [Obsolete] public const string TextJavascript = "text/javascript"; ///<summary>JPEG JFIF image; Associated with Internet Explorer; Listed in ms775147(v=vs.85) - Progressive JPEG, initiated before global browser support for progressive JPEGs (Microsoft and Firefox).</summary> public const string ImagePjpeg = "image/pjpeg"; ///<summary>JPEG JFIF image; Defined in RFC 2045 and RFC 2046</summary> public const string ImageJpeg = "image/jpeg"; ///<summary>jQuery template data</summary> public const string TextXJqueryTmpl = "text/x-jquery-tmpl"; ///<summary>KML files (e.g. for Google Earth)</summary> public const string ApplicationVndGoogleEarthKmlXml = "application/vnd.google-earth.kml+xml"; ///<summary>LaTeX files</summary> public const string ApplicationXLatex = "application/x-latex"; ///<summary>Matroska open media format</summary> public const string VideoXMatroska = "video/x-matroska"; ///<summary>Microsoft Excel 2007 files</summary> public const string ApplicationVndOpenxmlformatsOfficedocumentSpreadsheetmlSheet = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; ///<summary>Microsoft Excel files</summary> public const string ApplicationVndMsExcel = "application/vnd.ms-excel"; ///<summary>Microsoft Powerpoint 2007 files</summary> public const string ApplicationVndOpenxmlformatsOfficedocumentPresentationmlPresentation = "application/vnd.openxmlformats-officedocument.presentationml.presentation"; ///<summary>Microsoft Powerpoint files</summary> public const string ApplicationVndMsPowerpoint = "application/vnd.ms-powerpoint"; ///<summary>Microsoft Word 2007 files</summary> public const string ApplicationVndOpenxmlformatsOfficedocumentWordprocessingmlDocument = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; ///<summary>Microsoft Word files[15]</summary> public const string ApplicationMsword = "application/msword"; ///<summary>MIME Email; Defined in RFC 2045 and RFC 2046</summary> public const string MultipartAlternative = "multipart/alternative"; ///<summary>MIME Email; Defined in RFC 2045 and RFC 2046</summary> public const string MultipartMixed = "multipart/mixed"; ///<summary>MIME Email; Defined in RFC 2387 and used by MHTML (HTML mail)</summary> public const string MultipartRelated = "multipart/related"; ///<summary>MIME Webform; Defined in RFC 2388</summary> public const string MultipartFormData = "multipart/form-data"; ///<summary>Mozilla XUL files</summary> public const string ApplicationVndMozillaXulXml = "application/vnd.mozilla.xul+xml"; ///<summary>MP3 or other MPEG audio; Defined in RFC 3003</summary> public const string AudioMpeg = "audio/mpeg"; ///<summary>MP4 audio</summary> public const string AudioMp4 = "audio/mp4"; ///<summary>MP4 video; Defined in RFC 4337</summary> public const string VideoMp4 = "video/mp4"; ///<summary>MPEG-1 video with multiplexed audio; Defined in RFC 2045 and RFC 2046</summary> public const string VideoMpeg = "video/mpeg"; ///<summary>MSH files, MESH files; Defined in RFC 2077, SILO files</summary> public const string ModelMesh = "model/mesh"; ///<summary>mulaw audio at 8 kHz, 1 channel; Defined in RFC 2046</summary> public const string AudioBasic = "audio/basic"; ///<summary>Ogg Theora or other video (with audio); Defined in RFC 5334</summary> public const string VideoOgg = "video/ogg"; ///<summary>Ogg Vorbis, Speex, Flac and other audio; Defined in RFC 5334</summary> public const string AudioOgg = "audio/ogg"; ///<summary>Ogg, a multimedia bitstream container format; Defined in RFC 5334</summary> public const string ApplicationOgg = "application/ogg"; ///<summary>OP</summary> public const string ApplicationXopXml = "application/xop+xml"; ///<summary>OpenDocument Graphics; Registered[14]</summary> public const string ApplicationVndOasisOpendocumentGraphics = "application/vnd.oasis.opendocument.graphics"; ///<summary>OpenDocument Presentation; Registered[13]</summary> public const string ApplicationVndOasisOpendocumentPresentation = "application/vnd.oasis.opendocument.presentation"; ///<summary>OpenDocument Spreadsheet; Registered[12]</summary> public const string ApplicationVndOasisOpendocumentSpreadsheet = "application/vnd.oasis.opendocument.spreadsheet"; ///<summary>OpenDocument Text; Registered[11]</summary> public const string ApplicationVndOasisOpendocumentText = "application/vnd.oasis.opendocument.text"; ///<summary>p12 files</summary> public const string ApplicationXPkcs12 = "application/x-pkcs12"; ///<summary>p7b and spc files</summary> public const string ApplicationXPkcs7Certificates = "application/x-pkcs7-certificates"; ///<summary>p7c files</summary> public const string ApplicationXPkcs7Mime = "application/x-pkcs7-mime"; ///<summary>p7r files</summary> public const string ApplicationXPkcs7Certreqresp = "application/x-pkcs7-certreqresp"; ///<summary>p7s files</summary> public const string ApplicationXPkcs7Signature = "application/x-pkcs7-signature"; ///<summary>Portable Document Format, PDF has been in use for document exchange on the Internet since 1993; Defined in RFC 3778</summary> public const string ApplicationPdf = "application/pdf"; ///<summary>Portable Network Graphics; Registered,[8] Defined in RFC 2083</summary> public const string ImagePng = "image/png"; ///<summary>PostScript; Defined in RFC 2046</summary> public const string ApplicationPostscript = "application/postscript"; ///<summary>QuickTime video; Registered[10]</summary> public const string VideoQuicktime = "video/quicktime"; ///<summary>RAR archive files</summary> public const string ApplicationXRarCompressed = "application/x-rar-compressed"; ///<summary>RealAudio; Documented in RealPlayer Customer Support Answer 2559</summary> public const string AudioVndRnRealaudio = "audio/vnd.rn-realaudio"; ///<summary>Resource Description Framework; Defined by RFC 3870</summary> public const string ApplicationRdfXml = "application/rdf+xml"; ///<summary>RSS feeds</summary> public const string ApplicationRssXml = "application/rss+xml"; ///<summary>SOAP; Defined by RFC 3902</summary> public const string ApplicationSoapXml = "application/soap+xml"; ///<summary>StuffIt archive files</summary> public const string ApplicationXStuffit = "application/x-stuffit"; ///<summary>SVG vector image; Defined in SVG Tiny 1.2 Specification Appendix M</summary> public const string ImageSvgXml = "image/svg+xml"; ///<summary>Tag Image File Format (only for Baseline TIFF); Defined in RFC 3302</summary> public const string ImageTiff = "image/tiff"; ///<summary>Tarball files</summary> public const string ApplicationXTar = "application/x-tar"; ///<summary>Textual data; Defined in RFC 2046 and RFC 3676</summary> public const string TextPlain = "text/plain"; ///<summary>TrueType Font No registered MIME type, but this is the most commonly used</summary> public const string ApplicationXFontTtf = "application/x-font-ttf"; ///<summary>vCard (contact information); Defined in RFC 6350</summary> public const string TextVcard = "text/vcard"; ///<summary>Vorbis encoded audio; Defined in RFC 5215</summary> public const string AudioVorbis = "audio/vorbis"; ///<summary>WAV audio; Defined in RFC 2361</summary> public const string AudioVndWave = "audio/vnd.wave"; ///<summary>Web Open Font Format; (candidate recommendation; use application/x-font-woff until standard is official)</summary> public const string ApplicationFontWoff = "application/font-woff"; ///<summary>WebM Matroska-based open media format</summary> public const string VideoWebm = "video/webm"; ///<summary>WebM open media format</summary> public const string AudioWebm = "audio/webm"; ///<summary>Windows Media Audio Redirector; Documented in Microsoft help page</summary> public const string AudioXMsWax = "audio/x-ms-wax"; ///<summary>Windows Media Audio; Documented in Microsoft KB 288102</summary> public const string AudioXMsWma = "audio/x-ms-wma"; ///<summary>Windows Media Video; Documented in Microsoft KB 288102</summary> public const string VideoXMsWmv = "video/x-ms-wmv"; ///<summary>WRL files, VRML files; Defined in RFC 2077</summary> public const string ModelVrml = "model/vrml"; ///<summary>X3D ISO standard for representing 3D computer graphics, X3D XML files</summary> public const string ModelX3DXml = "model/x3d+xml"; ///<summary>X3D ISO standard for representing 3D computer graphics, X3DB binary files</summary> public const string ModelX3DBinary = "model/x3d+binary"; ///<summary>X3D ISO standard for representing 3D computer graphics, X3DV VRML files</summary> public const string ModelX3DVrml = "model/x3d+vrml"; ///<summary>XHTML; Defined by RFC 3236</summary> public const string ApplicationXhtmlXml = "application/xhtml+xml"; ///<summary>ZIP archive files; Registered[7]</summary> public const string ApplicationZip = "application/zip"; } }
51.580128
493
0.698875
[ "MIT" ]
kgamab/jenkins-demo
aspnet-core/src/JenkinsTryOut.Application/Net/MimeTypes/MimeTypeNames.cs
16,095
C#
// Keep this file CodeMaid organised and cleaned using System; using System.Collections.Generic; using System.Data; using System.Globalization; using System.IO; namespace ClosedXML.Excel { public interface IXLWorkbook : IXLProtectable<IXLWorkbookProtection, XLWorkbookProtectionElements>, IDisposable { String Author { get; set; } /// <summary> /// Gets or sets the workbook's calculation mode. /// </summary> XLCalculateMode CalculateMode { get; set; } Boolean CalculationOnSave { get; set; } /// <summary> /// Gets or sets the default column width for the workbook. /// <para>All new worksheets will use this column width.</para> /// </summary> Double ColumnWidth { get; set; } IXLCustomProperties CustomProperties { get; } Boolean DefaultRightToLeft { get; } Boolean DefaultShowFormulas { get; } Boolean DefaultShowGridLines { get; } Boolean DefaultShowOutlineSymbols { get; } Boolean DefaultShowRowColHeaders { get; } Boolean DefaultShowRuler { get; } Boolean DefaultShowWhiteSpace { get; } Boolean DefaultShowZeros { get; } IXLFileSharing FileSharing { get; } Boolean ForceFullCalculation { get; set; } Boolean FullCalculationOnLoad { get; set; } Boolean FullPrecision { get; set; } //Boolean IsPasswordProtected { get; } //Boolean IsProtected { get; } Boolean LockStructure { get; set; } Boolean LockWindows { get; set; } /// <summary> /// Gets an object to manipulate this workbook's named ranges. /// </summary> IXLNamedRanges NamedRanges { get; } /// <summary> /// Gets or sets the default outline options for the workbook. /// <para>All new worksheets will use these outline options.</para> /// </summary> IXLOutline Outline { get; set; } /// <summary> /// Gets or sets the default page options for the workbook. /// <para>All new worksheets will use these page options.</para> /// </summary> IXLPageSetup PageOptions { get; set; } /// <summary> /// Gets or sets the workbook's properties. /// </summary> XLWorkbookProperties Properties { get; set; } /// <summary> /// Gets or sets the workbook's reference style. /// </summary> XLReferenceStyle ReferenceStyle { get; set; } Boolean RightToLeft { get; set; } /// <summary> /// Gets or sets the default row height for the workbook. /// <para>All new worksheets will use this row height.</para> /// </summary> Double RowHeight { get; set; } Boolean ShowFormulas { get; set; } Boolean ShowGridLines { get; set; } Boolean ShowOutlineSymbols { get; set; } Boolean ShowRowColHeaders { get; set; } Boolean ShowRuler { get; set; } Boolean ShowWhiteSpace { get; set; } Boolean ShowZeros { get; set; } /// <summary> /// Gets or sets the default style for the workbook. /// <para>All new worksheets will use this style.</para> /// </summary> IXLStyle Style { get; set; } /// <summary> /// Gets an object to manipulate this workbook's theme. /// </summary> IXLTheme Theme { get; } Boolean Use1904DateSystem { get; set; } /// <summary> /// Gets an object to manipulate the worksheets. /// </summary> IXLWorksheets Worksheets { get; } IXLWorksheet AddWorksheet(); IXLWorksheet AddWorksheet(Int32 position); IXLWorksheet AddWorksheet(String sheetName); IXLWorksheet AddWorksheet(String sheetName, Int32 position); IXLWorksheet AddWorksheet(DataTable dataTable); void AddWorksheet(DataSet dataSet); void AddWorksheet(IXLWorksheet worksheet); IXLWorksheet AddWorksheet(DataTable dataTable, String sheetName); IXLCell Cell(String namedCell); IXLCells Cells(String namedCells); IXLCustomProperty CustomProperty(String name); Object Evaluate(String expression); IXLCells FindCells(Func<IXLCell, Boolean> predicate); IXLColumns FindColumns(Func<IXLColumn, Boolean> predicate); IXLRows FindRows(Func<IXLRow, Boolean> predicate); IXLNamedRange NamedRange(String rangeName); [Obsolete("Use Protect(String password, Algorithm algorithm, TElement allowedElements)")] IXLWorkbookProtection Protect(Boolean lockStructure, Boolean lockWindows, String password); [Obsolete("Use Protect(String password, Algorithm algorithm, TElement allowedElements)")] IXLWorkbookProtection Protect(Boolean lockStructure); [Obsolete("Use Protect(String password, Algorithm algorithm, TElement allowedElements)")] IXLWorkbookProtection Protect(Boolean lockStructure, Boolean lockWindows); IXLRange Range(String range); IXLRange RangeFromFullAddress(String rangeAddress, out IXLWorksheet ws); IXLRanges Ranges(String ranges); /// <summary> /// Force recalculation of all cell formulas. /// </summary> void RecalculateAllFormulas(); /// <summary> /// Saves the current workbook. /// </summary> void Save(); /// <summary> /// Saves the current workbook and optionally performs validation /// </summary> void Save(Boolean validate, Boolean evaluateFormulae = false); void Save(SaveOptions options); /// <summary> /// Saves the current workbook to a file. /// </summary> void SaveAs(String file); /// <summary> /// Saves the current workbook to a file and optionally validates it. /// </summary> void SaveAs(String file, Boolean validate, Boolean evaluateFormulae = false); void SaveAs(String file, SaveOptions options); /// <summary> /// Saves the current workbook to a stream. /// </summary> void SaveAs(Stream stream); /// <summary> /// Saves the current workbook to a stream and optionally validates it. /// </summary> void SaveAs(Stream stream, Boolean validate, Boolean evaluateFormulae = false); void SaveAs(Stream stream, SaveOptions options); /// <summary> /// Searches the cells' contents for a given piece of text /// </summary> /// <param name="searchText">The search text.</param> /// <param name="compareOptions">The compare options.</param> /// <param name="searchFormulae">if set to <c>true</c> search formulae instead of cell values.</param> /// <returns></returns> IEnumerable<IXLCell> Search(String searchText, CompareOptions compareOptions = CompareOptions.Ordinal, Boolean searchFormulae = false); XLWorkbook SetLockStructure(Boolean value); XLWorkbook SetLockWindows(Boolean value); XLWorkbook SetUse1904DateSystem(); XLWorkbook SetUse1904DateSystem(Boolean value); /// <summary> /// Gets the Excel table of the given name /// </summary> /// <param name="tableName">Name of the table to return.</param> /// <param name="comparisonType">One of the enumeration values that specifies how the strings will be compared.</param> /// <returns>The table with given name</returns> /// <exception cref="ArgumentOutOfRangeException">If no tables with this name could be found in the workbook.</exception> IXLTable Table(String tableName, StringComparison comparisonType = StringComparison.OrdinalIgnoreCase); Boolean TryGetWorksheet(String name, out IXLWorksheet worksheet); IXLWorksheet Worksheet(String name); IXLWorksheet Worksheet(Int32 position); } }
33.361446
144
0.609245
[ "MIT" ]
0xced/ClosedXML
ClosedXML/Excel/IXLWorkbook.cs
8,307
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IAGrim.UI.Misc { class RequestCharacterDownloadUrlEventArg : EventArgs { public string Character { get; set; } public string Url { get; set; } } }
23
59
0.712375
[ "MIT" ]
211847750/iagd
IAGrim/UI/Misc/RequestCharacterDownloadUrlEventArgs.cs
301
C#
using System.Collections.Generic; using Steam.Models.SteamCommunity; namespace GameFinder { public class GameEqualityComparer : IEqualityComparer<OwnedGameModel> { public bool Equals(OwnedGameModel x, OwnedGameModel y) => x?.AppId == y?.AppId; public int GetHashCode(OwnedGameModel obj) => obj.AppId.GetHashCode() - 59128423; } }
30
89
0.727778
[ "MIT" ]
mrousavy/GameFinder
GameFinder/GameEqualityComparer.cs
362
C#
/******************************************************************************* * * * Author : Angus Johnson * * Version : 6.4.2 * * Date : 27 February 2017 * * Website : http://www.angusj.com * * Copyright : Angus Johnson 2010-2017 * * * * License: * * Use, modification & distribution is subject to Boost Software License Ver 1. * * http://www.boost.org/LICENSE_1_0.txt * * * * Attributions: * * The code in this library is an extension of Bala Vatti's clipping algorithm: * * "A generic solution to polygon clipping" * * Communications of the ACM, Vol 35, Issue 7 (July 1992) pp 56-63. * * http://portal.acm.org/citation.cfm?id=129906 * * * * Computer graphics and geometric modeling: implementation and algorithms * * By Max K. Agoston * * Springer; 1 edition (January 4, 2005) * * http://books.google.com/books?q=vatti+clipping+agoston * * * * See also: * * "Polygon Offsetting by Computing Winding Numbers" * * Paper no. DETC2005-85513 pp. 565-575 * * ASME 2005 International Design Engineering Technical Conferences * * and Computers and Information in Engineering Conference (IDETC/CIE2005) * * September 24-28, 2005 , Long Beach, California, USA * * http://www.me.berkeley.edu/~mcmains/pubs/DAC05OffsetPolygon.pdf * * * *******************************************************************************/ /******************************************************************************* * * * This is a translation of the Delphi Clipper library and the naming style * * used has retained a Delphi flavour. * * * *******************************************************************************/ //use_int32: When enabled 32bit ints are used instead of 64bit ints. This //improve performance but coordinate values are limited to the range +/- 46340 //#define use_int32 //use_xyz: adds a Z member to IntPoint. Adds a minor cost to performance. //#define use_xyz //use_lines: Enables open path clipping. Adds a very minor cost to performance. #define use_lines using System; using System.Collections.Generic; //using System.Text; //for Int128.AsString() & StringBuilder //using System.IO; //debugging with streamReader & StreamWriter //using System.Windows.Forms; //debugging to clipboard namespace ExtrasClipperLib { #if use_int32 using cInt = Int32; #else using cInt = Int64; #endif using Path = List<IntPoint>; using Paths = List<List<IntPoint>>; public struct DoublePoint { public double X; public double Y; public DoublePoint(double x = 0, double y = 0) { this.X = x; this.Y = y; } public DoublePoint(DoublePoint dp) { this.X = dp.X; this.Y = dp.Y; } public DoublePoint(IntPoint ip) { this.X = ip.X; this.Y = ip.Y; } }; //------------------------------------------------------------------------------ // PolyTree & PolyNode classes //------------------------------------------------------------------------------ public class PolyTree : PolyNode { internal List<PolyNode> m_AllPolys = new List<PolyNode>(); //The GC probably handles this cleanup more efficiently ... //~PolyTree(){Clear();} public void Clear() { for (int i = 0; i < m_AllPolys.Count; i++) m_AllPolys[i] = null; m_AllPolys.Clear(); m_Childs.Clear(); } public PolyNode GetFirst() { if (m_Childs.Count > 0) return m_Childs[0]; else return null; } public int Total { get { int result = m_AllPolys.Count; //with negative offsets, ignore the hidden outer polygon ... if (result > 0 && m_Childs[0] != m_AllPolys[0]) result--; return result; } } } public class PolyNode { internal PolyNode m_Parent; internal Path m_polygon = new Path(); internal int m_Index; internal JoinType m_jointype; internal EndType m_endtype; internal List<PolyNode> m_Childs = new List<PolyNode>(); private bool IsHoleNode() { bool result = true; PolyNode node = m_Parent; while (node != null) { result = !result; node = node.m_Parent; } return result; } public int ChildCount { get { return m_Childs.Count; } } public Path Contour { get { return m_polygon; } } internal void AddChild(PolyNode Child) { int cnt = m_Childs.Count; m_Childs.Add(Child); Child.m_Parent = this; Child.m_Index = cnt; } public PolyNode GetNext() { if (m_Childs.Count > 0) return m_Childs[0]; else return GetNextSiblingUp(); } internal PolyNode GetNextSiblingUp() { if (m_Parent == null) return null; else if (m_Index == m_Parent.m_Childs.Count - 1) return m_Parent.GetNextSiblingUp(); else return m_Parent.m_Childs[m_Index + 1]; } public List<PolyNode> Childs { get { return m_Childs; } } public PolyNode Parent { get { return m_Parent; } } public bool IsHole { get { return IsHoleNode(); } } public bool IsOpen { get; set; } } //------------------------------------------------------------------------------ // Int128 struct (enables safe math on signed 64bit integers) // eg Int128 val1((Int64)9223372036854775807); //ie 2^63 -1 // Int128 val2((Int64)9223372036854775807); // Int128 val3 = val1 * val2; // val3.ToString => "85070591730234615847396907784232501249" (8.5e+37) //------------------------------------------------------------------------------ internal struct Int128 { private Int64 hi; private UInt64 lo; public Int128(Int64 _lo) { lo = (UInt64)_lo; if (_lo < 0) hi = -1; else hi = 0; } public Int128(Int64 _hi, UInt64 _lo) { lo = _lo; hi = _hi; } public Int128(Int128 val) { hi = val.hi; lo = val.lo; } public bool IsNegative() { return hi < 0; } public static bool operator==(Int128 val1, Int128 val2) { if ((object)val1 == (object)val2) return true; else if ((object)val1 == null || (object)val2 == null) return false; return (val1.hi == val2.hi && val1.lo == val2.lo); } public static bool operator!=(Int128 val1, Int128 val2) { return !(val1 == val2); } public override bool Equals(System.Object obj) { if (obj == null || !(obj is Int128)) return false; Int128 i128 = (Int128)obj; return (i128.hi == hi && i128.lo == lo); } public override int GetHashCode() { return hi.GetHashCode() ^ lo.GetHashCode(); } public static bool operator>(Int128 val1, Int128 val2) { if (val1.hi != val2.hi) return val1.hi > val2.hi; else return val1.lo > val2.lo; } public static bool operator<(Int128 val1, Int128 val2) { if (val1.hi != val2.hi) return val1.hi < val2.hi; else return val1.lo < val2.lo; } public static Int128 operator+(Int128 lhs, Int128 rhs) { lhs.hi += rhs.hi; lhs.lo += rhs.lo; if (lhs.lo < rhs.lo) lhs.hi++; return lhs; } public static Int128 operator-(Int128 lhs, Int128 rhs) { return lhs + -rhs; } public static Int128 operator-(Int128 val) { if (val.lo == 0) return new Int128(-val.hi, 0); else return new Int128(~val.hi, ~val.lo + 1); } public static explicit operator double(Int128 val) { const double shift64 = 18446744073709551616.0; //2^64 if (val.hi < 0) { if (val.lo == 0) return (double)val.hi * shift64; else return -(double)(~val.lo + ~val.hi * shift64); } else return (double)(val.lo + val.hi * shift64); } //nb: Constructing two new Int128 objects every time we want to multiply longs //is slow. So, although calling the Int128Mul method doesn't look as clean, the //code runs significantly faster than if we'd used the * operator. public static Int128 Int128Mul(Int64 lhs, Int64 rhs) { bool negate = (lhs < 0) != (rhs < 0); if (lhs < 0) lhs = -lhs; if (rhs < 0) rhs = -rhs; UInt64 int1Hi = (UInt64)lhs >> 32; UInt64 int1Lo = (UInt64)lhs & 0xFFFFFFFF; UInt64 int2Hi = (UInt64)rhs >> 32; UInt64 int2Lo = (UInt64)rhs & 0xFFFFFFFF; //nb: see comments in clipper.pas UInt64 a = int1Hi * int2Hi; UInt64 b = int1Lo * int2Lo; UInt64 c = int1Hi * int2Lo + int1Lo * int2Hi; UInt64 lo; Int64 hi; hi = (Int64)(a + (c >> 32)); unchecked { lo = (c << 32) + b; } if (lo < b) hi++; Int128 result = new Int128(hi, lo); return negate ? -result : result; } }; //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ public struct IntPoint { public cInt X; public cInt Y; #if use_xyz public cInt Z; public IntPoint(cInt x, cInt y, cInt z = 0) { this.X = x; this.Y = y; this.Z = z; } public IntPoint(double x, double y, double z = 0) { this.X = (cInt)x; this.Y = (cInt)y; this.Z = (cInt)z; } public IntPoint(DoublePoint dp) { this.X = (cInt)dp.X; this.Y = (cInt)dp.Y; this.Z = 0; } public IntPoint(IntPoint pt) { this.X = pt.X; this.Y = pt.Y; this.Z = pt.Z; } #else public IntPoint(cInt X, cInt Y) { this.X = X; this.Y = Y; } public IntPoint(double x, double y) { this.X = (cInt)x; this.Y = (cInt)y; } public IntPoint(IntPoint pt) { this.X = pt.X; this.Y = pt.Y; } #endif public static bool operator==(IntPoint a, IntPoint b) { return a.X == b.X && a.Y == b.Y; } public static bool operator!=(IntPoint a, IntPoint b) { return a.X != b.X || a.Y != b.Y; } public override bool Equals(object obj) { if (obj == null) return false; if (obj is IntPoint) { IntPoint a = (IntPoint)obj; return (X == a.X) && (Y == a.Y); } else return false; } public override int GetHashCode() { //simply prevents a compiler warning return base.GetHashCode(); } }// end struct IntPoint public struct IntRect { public cInt left; public cInt top; public cInt right; public cInt bottom; public IntRect(cInt l, cInt t, cInt r, cInt b) { this.left = l; this.top = t; this.right = r; this.bottom = b; } public IntRect(IntRect ir) { this.left = ir.left; this.top = ir.top; this.right = ir.right; this.bottom = ir.bottom; } } public enum ClipType { ctIntersection, ctUnion, ctDifference, ctXor }; public enum PolyType { ptSubject, ptClip }; //By far the most widely used winding rules for polygon filling are //EvenOdd & NonZero (GDI, GDI+, XLib, OpenGL, Cairo, AGG, Quartz, SVG, Gr32) //Others rules include Positive, Negative and ABS_GTR_EQ_TWO (only in OpenGL) //see http://glprogramming.com/red/chapter11.html public enum PolyFillType { pftEvenOdd, pftNonZero, pftPositive, pftNegative }; public enum JoinType { jtSquare, jtRound, jtMiter }; public enum EndType { etClosedPolygon, etClosedLine, etOpenButt, etOpenSquare, etOpenRound }; internal enum EdgeSide { esLeft, esRight }; internal enum Direction { dRightToLeft, dLeftToRight }; internal class TEdge { internal IntPoint Bot; internal IntPoint Curr; //current (updated for every new scanbeam) internal IntPoint Top; internal IntPoint Delta; internal double Dx; internal PolyType PolyTyp; internal EdgeSide Side; //side only refers to current side of solution poly internal int WindDelta; //1 or -1 depending on winding direction internal int WindCnt; internal int WindCnt2; //winding count of the opposite polytype internal int OutIdx; internal TEdge Next; internal TEdge Prev; internal TEdge NextInLML; internal TEdge NextInAEL; internal TEdge PrevInAEL; internal TEdge NextInSEL; internal TEdge PrevInSEL; }; public class IntersectNode { internal TEdge Edge1; internal TEdge Edge2; internal IntPoint Pt; }; public class MyIntersectNodeSort : IComparer<IntersectNode> { public int Compare(IntersectNode node1, IntersectNode node2) { cInt i = node2.Pt.Y - node1.Pt.Y; if (i > 0) return 1; else if (i < 0) return -1; else return 0; } } internal class LocalMinima { internal cInt Y; internal TEdge LeftBound; internal TEdge RightBound; internal LocalMinima Next; }; internal class Scanbeam { internal cInt Y; internal Scanbeam Next; }; internal class Maxima { internal cInt X; internal Maxima Next; internal Maxima Prev; }; //OutRec: contains a path in the clipping solution. Edges in the AEL will //carry a pointer to an OutRec when they are part of the clipping solution. internal class OutRec { internal int Idx; internal bool IsHole; internal bool IsOpen; internal OutRec FirstLeft; //see comments in clipper.pas internal OutPt Pts; internal OutPt BottomPt; internal PolyNode PolyNode; }; internal class OutPt { internal int Idx; internal IntPoint Pt; internal OutPt Next; internal OutPt Prev; }; internal class Join { internal OutPt OutPt1; internal OutPt OutPt2; internal IntPoint OffPt; }; public class ClipperBase { internal const double horizontal = -3.4E+38; internal const int Skip = -2; internal const int Unassigned = -1; internal const double tolerance = 1.0E-20; internal static bool near_zero(double val) {return (val > -tolerance) && (val < tolerance); } #if use_int32 public const cInt loRange = 0x7FFF; public const cInt hiRange = 0x7FFF; #else public const cInt loRange = 0x3FFFFFFF; public const cInt hiRange = 0x3FFFFFFFFFFFFFFFL; #endif internal LocalMinima m_MinimaList; internal LocalMinima m_CurrentLM; internal List<List<TEdge>> m_edges = new List<List<TEdge>>(); internal Scanbeam m_Scanbeam; internal List<OutRec> m_PolyOuts; internal TEdge m_ActiveEdges; internal bool m_UseFullRange; internal bool m_HasOpenPaths; //------------------------------------------------------------------------------ public bool PreserveCollinear { get; set; } //------------------------------------------------------------------------------ public void Swap(ref cInt val1, ref cInt val2) { cInt tmp = val1; val1 = val2; val2 = tmp; } //------------------------------------------------------------------------------ internal static bool IsHorizontal(TEdge e) { return e.Delta.Y == 0; } //------------------------------------------------------------------------------ internal bool PointIsVertex(IntPoint pt, OutPt pp) { OutPt pp2 = pp; do { if (pp2.Pt == pt) return true; pp2 = pp2.Next; } while (pp2 != pp); return false; } //------------------------------------------------------------------------------ internal bool PointOnLineSegment(IntPoint pt, IntPoint linePt1, IntPoint linePt2, bool UseFullRange) { if (UseFullRange) return ((pt.X == linePt1.X) && (pt.Y == linePt1.Y)) || ((pt.X == linePt2.X) && (pt.Y == linePt2.Y)) || (((pt.X > linePt1.X) == (pt.X < linePt2.X)) && ((pt.Y > linePt1.Y) == (pt.Y < linePt2.Y)) && ((Int128.Int128Mul((pt.X - linePt1.X), (linePt2.Y - linePt1.Y)) == Int128.Int128Mul((linePt2.X - linePt1.X), (pt.Y - linePt1.Y))))); else return ((pt.X == linePt1.X) && (pt.Y == linePt1.Y)) || ((pt.X == linePt2.X) && (pt.Y == linePt2.Y)) || (((pt.X > linePt1.X) == (pt.X < linePt2.X)) && ((pt.Y > linePt1.Y) == (pt.Y < linePt2.Y)) && ((pt.X - linePt1.X) * (linePt2.Y - linePt1.Y) == (linePt2.X - linePt1.X) * (pt.Y - linePt1.Y))); } //------------------------------------------------------------------------------ internal bool PointOnPolygon(IntPoint pt, OutPt pp, bool UseFullRange) { OutPt pp2 = pp; while (true) { if (PointOnLineSegment(pt, pp2.Pt, pp2.Next.Pt, UseFullRange)) return true; pp2 = pp2.Next; if (pp2 == pp) break; } return false; } //------------------------------------------------------------------------------ internal static bool SlopesEqual(TEdge e1, TEdge e2, bool UseFullRange) { if (UseFullRange) return Int128.Int128Mul(e1.Delta.Y, e2.Delta.X) == Int128.Int128Mul(e1.Delta.X, e2.Delta.Y); else return (cInt)(e1.Delta.Y) * (e2.Delta.X) == (cInt)(e1.Delta.X) * (e2.Delta.Y); } //------------------------------------------------------------------------------ internal static bool SlopesEqual(IntPoint pt1, IntPoint pt2, IntPoint pt3, bool UseFullRange) { if (UseFullRange) return Int128.Int128Mul(pt1.Y - pt2.Y, pt2.X - pt3.X) == Int128.Int128Mul(pt1.X - pt2.X, pt2.Y - pt3.Y); else return (cInt)(pt1.Y - pt2.Y) * (pt2.X - pt3.X) - (cInt)(pt1.X - pt2.X) * (pt2.Y - pt3.Y) == 0; } //------------------------------------------------------------------------------ internal static bool SlopesEqual(IntPoint pt1, IntPoint pt2, IntPoint pt3, IntPoint pt4, bool UseFullRange) { if (UseFullRange) return Int128.Int128Mul(pt1.Y - pt2.Y, pt3.X - pt4.X) == Int128.Int128Mul(pt1.X - pt2.X, pt3.Y - pt4.Y); else return (cInt)(pt1.Y - pt2.Y) * (pt3.X - pt4.X) - (cInt)(pt1.X - pt2.X) * (pt3.Y - pt4.Y) == 0; } //------------------------------------------------------------------------------ internal ClipperBase() //constructor (nb: no external instantiation) { m_MinimaList = null; m_CurrentLM = null; m_UseFullRange = false; m_HasOpenPaths = false; } //------------------------------------------------------------------------------ public virtual void Clear() { DisposeLocalMinimaList(); for (int i = 0; i < m_edges.Count; ++i) { for (int j = 0; j < m_edges[i].Count; ++j) m_edges[i][j] = null; m_edges[i].Clear(); } m_edges.Clear(); m_UseFullRange = false; m_HasOpenPaths = false; } //------------------------------------------------------------------------------ private void DisposeLocalMinimaList() { while (m_MinimaList != null) { LocalMinima tmpLm = m_MinimaList.Next; m_MinimaList = null; m_MinimaList = tmpLm; } m_CurrentLM = null; } //------------------------------------------------------------------------------ void RangeTest(IntPoint Pt, ref bool useFullRange) { if (useFullRange) { if (Pt.X > hiRange || Pt.Y > hiRange || -Pt.X > hiRange || -Pt.Y > hiRange) throw new ClipperException("Coordinate outside allowed range"); } else if (Pt.X > loRange || Pt.Y > loRange || -Pt.X > loRange || -Pt.Y > loRange) { useFullRange = true; RangeTest(Pt, ref useFullRange); } } //------------------------------------------------------------------------------ private void InitEdge(TEdge e, TEdge eNext, TEdge ePrev, IntPoint pt) { e.Next = eNext; e.Prev = ePrev; e.Curr = pt; e.OutIdx = Unassigned; } //------------------------------------------------------------------------------ private void InitEdge2(TEdge e, PolyType polyType) { if (e.Curr.Y >= e.Next.Curr.Y) { e.Bot = e.Curr; e.Top = e.Next.Curr; } else { e.Top = e.Curr; e.Bot = e.Next.Curr; } SetDx(e); e.PolyTyp = polyType; } //------------------------------------------------------------------------------ private TEdge FindNextLocMin(TEdge E) { TEdge E2; for (;;) { while (E.Bot != E.Prev.Bot || E.Curr == E.Top) E = E.Next; if (E.Dx != horizontal && E.Prev.Dx != horizontal) break; while (E.Prev.Dx == horizontal) E = E.Prev; E2 = E; while (E.Dx == horizontal) E = E.Next; if (E.Top.Y == E.Prev.Bot.Y) continue; //ie just an intermediate horz. if (E2.Prev.Bot.X < E.Bot.X) E = E2; break; } return E; } //------------------------------------------------------------------------------ private TEdge ProcessBound(TEdge E, bool LeftBoundIsForward) { TEdge EStart, Result = E; TEdge Horz; if (Result.OutIdx == Skip) { //check if there are edges beyond the skip edge in the bound and if so //create another LocMin and calling ProcessBound once more ... E = Result; if (LeftBoundIsForward) { while (E.Top.Y == E.Next.Bot.Y) E = E.Next; while (E != Result && E.Dx == horizontal) E = E.Prev; } else { while (E.Top.Y == E.Prev.Bot.Y) E = E.Prev; while (E != Result && E.Dx == horizontal) E = E.Next; } if (E == Result) { if (LeftBoundIsForward) Result = E.Next; else Result = E.Prev; } else { //there are more edges in the bound beyond result starting with E if (LeftBoundIsForward) E = Result.Next; else E = Result.Prev; LocalMinima locMin = new LocalMinima(); locMin.Next = null; locMin.Y = E.Bot.Y; locMin.LeftBound = null; locMin.RightBound = E; E.WindDelta = 0; Result = ProcessBound(E, LeftBoundIsForward); InsertLocalMinima(locMin); } return Result; } if (E.Dx == horizontal) { //We need to be careful with open paths because this may not be a //true local minima (ie E may be following a skip edge). //Also, consecutive horz. edges may start heading left before going right. if (LeftBoundIsForward) EStart = E.Prev; else EStart = E.Next; if (EStart.Dx == horizontal) //ie an adjoining horizontal skip edge { if (EStart.Bot.X != E.Bot.X && EStart.Top.X != E.Bot.X) ReverseHorizontal(E); } else if (EStart.Bot.X != E.Bot.X) ReverseHorizontal(E); } EStart = E; if (LeftBoundIsForward) { while (Result.Top.Y == Result.Next.Bot.Y && Result.Next.OutIdx != Skip) Result = Result.Next; if (Result.Dx == horizontal && Result.Next.OutIdx != Skip) { //nb: at the top of a bound, horizontals are added to the bound //only when the preceding edge attaches to the horizontal's left vertex //unless a Skip edge is encountered when that becomes the top divide Horz = Result; while (Horz.Prev.Dx == horizontal) Horz = Horz.Prev; if (Horz.Prev.Top.X > Result.Next.Top.X) Result = Horz.Prev; } while (E != Result) { E.NextInLML = E.Next; if (E.Dx == horizontal && E != EStart && E.Bot.X != E.Prev.Top.X) ReverseHorizontal(E); E = E.Next; } if (E.Dx == horizontal && E != EStart && E.Bot.X != E.Prev.Top.X) ReverseHorizontal(E); Result = Result.Next; //move to the edge just beyond current bound } else { while (Result.Top.Y == Result.Prev.Bot.Y && Result.Prev.OutIdx != Skip) Result = Result.Prev; if (Result.Dx == horizontal && Result.Prev.OutIdx != Skip) { Horz = Result; while (Horz.Next.Dx == horizontal) Horz = Horz.Next; if (Horz.Next.Top.X == Result.Prev.Top.X || Horz.Next.Top.X > Result.Prev.Top.X) Result = Horz.Next; } while (E != Result) { E.NextInLML = E.Prev; if (E.Dx == horizontal && E != EStart && E.Bot.X != E.Next.Top.X) ReverseHorizontal(E); E = E.Prev; } if (E.Dx == horizontal && E != EStart && E.Bot.X != E.Next.Top.X) ReverseHorizontal(E); Result = Result.Prev; //move to the edge just beyond current bound } return Result; } //------------------------------------------------------------------------------ public bool AddPath(Path pg, PolyType polyType, bool Closed) { #if use_lines if (!Closed && polyType == PolyType.ptClip) throw new ClipperException("AddPath: Open paths must be subject."); #else if (!Closed) throw new ClipperException("AddPath: Open paths have been disabled."); #endif int highI = (int)pg.Count - 1; if (Closed) while (highI > 0 && (pg[highI] == pg[0])) --highI; while (highI > 0 && (pg[highI] == pg[highI - 1])) --highI; if ((Closed && highI < 2) || (!Closed && highI < 1)) return false; //create a new edge array ... List<TEdge> edges = new List<TEdge>(highI + 1); for (int i = 0; i <= highI; i++) edges.Add(new TEdge()); bool IsFlat = true; //1. Basic (first) edge initialization ... edges[1].Curr = pg[1]; RangeTest(pg[0], ref m_UseFullRange); RangeTest(pg[highI], ref m_UseFullRange); InitEdge(edges[0], edges[1], edges[highI], pg[0]); InitEdge(edges[highI], edges[0], edges[highI - 1], pg[highI]); for (int i = highI - 1; i >= 1; --i) { RangeTest(pg[i], ref m_UseFullRange); InitEdge(edges[i], edges[i + 1], edges[i - 1], pg[i]); } TEdge eStart = edges[0]; //2. Remove duplicate vertices, and (when closed) collinear edges ... TEdge E = eStart, eLoopStop = eStart; for (;;) { //nb: allows matching start and end points when not Closed ... if (E.Curr == E.Next.Curr && (Closed || E.Next != eStart)) { if (E == E.Next) break; if (E == eStart) eStart = E.Next; E = RemoveEdge(E); eLoopStop = E; continue; } if (E.Prev == E.Next) break; //only two vertices else if (Closed && SlopesEqual(E.Prev.Curr, E.Curr, E.Next.Curr, m_UseFullRange) && (!PreserveCollinear || !Pt2IsBetweenPt1AndPt3(E.Prev.Curr, E.Curr, E.Next.Curr))) { //Collinear edges are allowed for open paths but in closed paths //the default is to merge adjacent collinear edges into a single edge. //However, if the PreserveCollinear property is enabled, only overlapping //collinear edges (ie spikes) will be removed from closed paths. if (E == eStart) eStart = E.Next; E = RemoveEdge(E); E = E.Prev; eLoopStop = E; continue; } E = E.Next; if ((E == eLoopStop) || (!Closed && E.Next == eStart)) break; } if ((!Closed && (E == E.Next)) || (Closed && (E.Prev == E.Next))) return false; if (!Closed) { m_HasOpenPaths = true; eStart.Prev.OutIdx = Skip; } //3. Do second stage of edge initialization ... E = eStart; do { InitEdge2(E, polyType); E = E.Next; if (IsFlat && E.Curr.Y != eStart.Curr.Y) IsFlat = false; } while (E != eStart); //4. Finally, add edge bounds to LocalMinima list ... //Totally flat paths must be handled differently when adding them //to LocalMinima list to avoid endless loops etc ... if (IsFlat) { if (Closed) return false; E.Prev.OutIdx = Skip; LocalMinima locMin = new LocalMinima(); locMin.Next = null; locMin.Y = E.Bot.Y; locMin.LeftBound = null; locMin.RightBound = E; locMin.RightBound.Side = EdgeSide.esRight; locMin.RightBound.WindDelta = 0; for (;;) { if (E.Bot.X != E.Prev.Top.X) ReverseHorizontal(E); if (E.Next.OutIdx == Skip) break; E.NextInLML = E.Next; E = E.Next; } InsertLocalMinima(locMin); m_edges.Add(edges); return true; } m_edges.Add(edges); bool leftBoundIsForward; TEdge EMin = null; //workaround to avoid an endless loop in the while loop below when //open paths have matching start and end points ... if (E.Prev.Bot == E.Prev.Top) E = E.Next; for (;;) { E = FindNextLocMin(E); if (E == EMin) break; else if (EMin == null) EMin = E; //E and E.Prev now share a local minima (left aligned if horizontal). //Compare their slopes to find which starts which bound ... LocalMinima locMin = new LocalMinima(); locMin.Next = null; locMin.Y = E.Bot.Y; if (E.Dx < E.Prev.Dx) { locMin.LeftBound = E.Prev; locMin.RightBound = E; leftBoundIsForward = false; //Q.nextInLML = Q.prev } else { locMin.LeftBound = E; locMin.RightBound = E.Prev; leftBoundIsForward = true; //Q.nextInLML = Q.next } locMin.LeftBound.Side = EdgeSide.esLeft; locMin.RightBound.Side = EdgeSide.esRight; if (!Closed) locMin.LeftBound.WindDelta = 0; else if (locMin.LeftBound.Next == locMin.RightBound) locMin.LeftBound.WindDelta = -1; else locMin.LeftBound.WindDelta = 1; locMin.RightBound.WindDelta = -locMin.LeftBound.WindDelta; E = ProcessBound(locMin.LeftBound, leftBoundIsForward); if (E.OutIdx == Skip) E = ProcessBound(E, leftBoundIsForward); TEdge E2 = ProcessBound(locMin.RightBound, !leftBoundIsForward); if (E2.OutIdx == Skip) E2 = ProcessBound(E2, !leftBoundIsForward); if (locMin.LeftBound.OutIdx == Skip) locMin.LeftBound = null; else if (locMin.RightBound.OutIdx == Skip) locMin.RightBound = null; InsertLocalMinima(locMin); if (!leftBoundIsForward) E = E2; } return true; } //------------------------------------------------------------------------------ public bool AddPaths(Paths ppg, PolyType polyType, bool closed) { bool result = false; for (int i = 0; i < ppg.Count; ++i) if (AddPath(ppg[i], polyType, closed)) result = true; return result; } //------------------------------------------------------------------------------ internal bool Pt2IsBetweenPt1AndPt3(IntPoint pt1, IntPoint pt2, IntPoint pt3) { if ((pt1 == pt3) || (pt1 == pt2) || (pt3 == pt2)) return false; else if (pt1.X != pt3.X) return (pt2.X > pt1.X) == (pt2.X < pt3.X); else return (pt2.Y > pt1.Y) == (pt2.Y < pt3.Y); } //------------------------------------------------------------------------------ TEdge RemoveEdge(TEdge e) { //removes e from double_linked_list (but without removing from memory) e.Prev.Next = e.Next; e.Next.Prev = e.Prev; TEdge result = e.Next; e.Prev = null; //flag as removed (see ClipperBase.Clear) return result; } //------------------------------------------------------------------------------ private void SetDx(TEdge e) { e.Delta.X = (e.Top.X - e.Bot.X); e.Delta.Y = (e.Top.Y - e.Bot.Y); if (e.Delta.Y == 0) e.Dx = horizontal; else e.Dx = (double)(e.Delta.X) / (e.Delta.Y); } //--------------------------------------------------------------------------- private void InsertLocalMinima(LocalMinima newLm) { if (m_MinimaList == null) { m_MinimaList = newLm; } else if (newLm.Y >= m_MinimaList.Y) { newLm.Next = m_MinimaList; m_MinimaList = newLm; } else { LocalMinima tmpLm = m_MinimaList; while (tmpLm.Next != null && (newLm.Y < tmpLm.Next.Y)) tmpLm = tmpLm.Next; newLm.Next = tmpLm.Next; tmpLm.Next = newLm; } } //------------------------------------------------------------------------------ internal Boolean PopLocalMinima(cInt Y, out LocalMinima current) { current = m_CurrentLM; if (m_CurrentLM != null && m_CurrentLM.Y == Y) { m_CurrentLM = m_CurrentLM.Next; return true; } return false; } //------------------------------------------------------------------------------ private void ReverseHorizontal(TEdge e) { //swap horizontal edges' top and bottom x's so they follow the natural //progression of the bounds - ie so their xbots will align with the //adjoining lower edge. [Helpful in the ProcessHorizontal() method.] Swap(ref e.Top.X, ref e.Bot.X); #if use_xyz Swap(ref e.Top.Z, ref e.Bot.Z); #endif } //------------------------------------------------------------------------------ internal virtual void Reset() { m_CurrentLM = m_MinimaList; if (m_CurrentLM == null) return; //ie nothing to process //reset all edges ... m_Scanbeam = null; LocalMinima lm = m_MinimaList; while (lm != null) { InsertScanbeam(lm.Y); TEdge e = lm.LeftBound; if (e != null) { e.Curr = e.Bot; e.OutIdx = Unassigned; } e = lm.RightBound; if (e != null) { e.Curr = e.Bot; e.OutIdx = Unassigned; } lm = lm.Next; } m_ActiveEdges = null; } //------------------------------------------------------------------------------ public static IntRect GetBounds(Paths paths) { int i = 0, cnt = paths.Count; while (i < cnt && paths[i].Count == 0) i++; if (i == cnt) return new IntRect(0, 0, 0, 0); IntRect result = new IntRect(); result.left = paths[i][0].X; result.right = result.left; result.top = paths[i][0].Y; result.bottom = result.top; for (; i < cnt; i++) for (int j = 0; j < paths[i].Count; j++) { if (paths[i][j].X < result.left) result.left = paths[i][j].X; else if (paths[i][j].X > result.right) result.right = paths[i][j].X; if (paths[i][j].Y < result.top) result.top = paths[i][j].Y; else if (paths[i][j].Y > result.bottom) result.bottom = paths[i][j].Y; } return result; } //------------------------------------------------------------------------------ internal void InsertScanbeam(cInt Y) { //single-linked list: sorted descending, ignoring dups. if (m_Scanbeam == null) { m_Scanbeam = new Scanbeam(); m_Scanbeam.Next = null; m_Scanbeam.Y = Y; } else if (Y > m_Scanbeam.Y) { Scanbeam newSb = new Scanbeam(); newSb.Y = Y; newSb.Next = m_Scanbeam; m_Scanbeam = newSb; } else { Scanbeam sb2 = m_Scanbeam; while (sb2.Next != null && (Y <= sb2.Next.Y)) sb2 = sb2.Next; if (Y == sb2.Y) return; //ie ignores duplicates Scanbeam newSb = new Scanbeam(); newSb.Y = Y; newSb.Next = sb2.Next; sb2.Next = newSb; } } //------------------------------------------------------------------------------ internal Boolean PopScanbeam(out cInt Y) { if (m_Scanbeam == null) { Y = 0; return false; } Y = m_Scanbeam.Y; m_Scanbeam = m_Scanbeam.Next; return true; } //------------------------------------------------------------------------------ internal Boolean LocalMinimaPending() { return (m_CurrentLM != null); } //------------------------------------------------------------------------------ internal OutRec CreateOutRec() { OutRec result = new OutRec(); result.Idx = Unassigned; result.IsHole = false; result.IsOpen = false; result.FirstLeft = null; result.Pts = null; result.BottomPt = null; result.PolyNode = null; m_PolyOuts.Add(result); result.Idx = m_PolyOuts.Count - 1; return result; } //------------------------------------------------------------------------------ internal void DisposeOutRec(int index) { OutRec outRec = m_PolyOuts[index]; outRec.Pts = null; outRec = null; m_PolyOuts[index] = null; } //------------------------------------------------------------------------------ internal void UpdateEdgeIntoAEL(ref TEdge e) { if (e.NextInLML == null) throw new ClipperException("UpdateEdgeIntoAEL: invalid call"); TEdge AelPrev = e.PrevInAEL; TEdge AelNext = e.NextInAEL; e.NextInLML.OutIdx = e.OutIdx; if (AelPrev != null) AelPrev.NextInAEL = e.NextInLML; else m_ActiveEdges = e.NextInLML; if (AelNext != null) AelNext.PrevInAEL = e.NextInLML; e.NextInLML.Side = e.Side; e.NextInLML.WindDelta = e.WindDelta; e.NextInLML.WindCnt = e.WindCnt; e.NextInLML.WindCnt2 = e.WindCnt2; e = e.NextInLML; e.Curr = e.Bot; e.PrevInAEL = AelPrev; e.NextInAEL = AelNext; if (!IsHorizontal(e)) InsertScanbeam(e.Top.Y); } //------------------------------------------------------------------------------ internal void SwapPositionsInAEL(TEdge edge1, TEdge edge2) { //check that one or other edge hasn't already been removed from AEL ... if (edge1.NextInAEL == edge1.PrevInAEL || edge2.NextInAEL == edge2.PrevInAEL) return; if (edge1.NextInAEL == edge2) { TEdge next = edge2.NextInAEL; if (next != null) next.PrevInAEL = edge1; TEdge prev = edge1.PrevInAEL; if (prev != null) prev.NextInAEL = edge2; edge2.PrevInAEL = prev; edge2.NextInAEL = edge1; edge1.PrevInAEL = edge2; edge1.NextInAEL = next; } else if (edge2.NextInAEL == edge1) { TEdge next = edge1.NextInAEL; if (next != null) next.PrevInAEL = edge2; TEdge prev = edge2.PrevInAEL; if (prev != null) prev.NextInAEL = edge1; edge1.PrevInAEL = prev; edge1.NextInAEL = edge2; edge2.PrevInAEL = edge1; edge2.NextInAEL = next; } else { TEdge next = edge1.NextInAEL; TEdge prev = edge1.PrevInAEL; edge1.NextInAEL = edge2.NextInAEL; if (edge1.NextInAEL != null) edge1.NextInAEL.PrevInAEL = edge1; edge1.PrevInAEL = edge2.PrevInAEL; if (edge1.PrevInAEL != null) edge1.PrevInAEL.NextInAEL = edge1; edge2.NextInAEL = next; if (edge2.NextInAEL != null) edge2.NextInAEL.PrevInAEL = edge2; edge2.PrevInAEL = prev; if (edge2.PrevInAEL != null) edge2.PrevInAEL.NextInAEL = edge2; } if (edge1.PrevInAEL == null) m_ActiveEdges = edge1; else if (edge2.PrevInAEL == null) m_ActiveEdges = edge2; } //------------------------------------------------------------------------------ internal void DeleteFromAEL(TEdge e) { TEdge AelPrev = e.PrevInAEL; TEdge AelNext = e.NextInAEL; if (AelPrev == null && AelNext == null && (e != m_ActiveEdges)) return; //already deleted if (AelPrev != null) AelPrev.NextInAEL = AelNext; else m_ActiveEdges = AelNext; if (AelNext != null) AelNext.PrevInAEL = AelPrev; e.NextInAEL = null; e.PrevInAEL = null; } //------------------------------------------------------------------------------ } //end ClipperBase public class Clipper : ClipperBase { //InitOptions that can be passed to the constructor ... public const int ioReverseSolution = 1; public const int ioStrictlySimple = 2; public const int ioPreserveCollinear = 4; private ClipType m_ClipType; private Maxima m_Maxima; private TEdge m_SortedEdges; private List<IntersectNode> m_IntersectList; IComparer<IntersectNode> m_IntersectNodeComparer; private bool m_ExecuteLocked; private PolyFillType m_ClipFillType; private PolyFillType m_SubjFillType; private List<Join> m_Joins; private List<Join> m_GhostJoins; private bool m_UsingPolyTree; #if use_xyz public delegate void ZFillCallback(IntPoint bot1, IntPoint top1, IntPoint bot2, IntPoint top2, ref IntPoint pt); public ZFillCallback ZFillFunction { get; set; } #endif public Clipper(int InitOptions = 0) : base() //constructor { m_Scanbeam = null; m_Maxima = null; m_ActiveEdges = null; m_SortedEdges = null; m_IntersectList = new List<IntersectNode>(); m_IntersectNodeComparer = new MyIntersectNodeSort(); m_ExecuteLocked = false; m_UsingPolyTree = false; m_PolyOuts = new List<OutRec>(); m_Joins = new List<Join>(); m_GhostJoins = new List<Join>(); ReverseSolution = (ioReverseSolution & InitOptions) != 0; StrictlySimple = (ioStrictlySimple & InitOptions) != 0; PreserveCollinear = (ioPreserveCollinear & InitOptions) != 0; #if use_xyz ZFillFunction = null; #endif } //------------------------------------------------------------------------------ private void InsertMaxima(cInt X) { //double-linked list: sorted ascending, ignoring dups. Maxima newMax = new Maxima(); newMax.X = X; if (m_Maxima == null) { m_Maxima = newMax; m_Maxima.Next = null; m_Maxima.Prev = null; } else if (X < m_Maxima.X) { newMax.Next = m_Maxima; newMax.Prev = null; m_Maxima = newMax; } else { Maxima m = m_Maxima; while (m.Next != null && (X >= m.Next.X)) m = m.Next; if (X == m.X) return; //ie ignores duplicates (& CG to clean up newMax) //insert newMax between m and m.Next ... newMax.Next = m.Next; newMax.Prev = m; if (m.Next != null) m.Next.Prev = newMax; m.Next = newMax; } } //------------------------------------------------------------------------------ public bool ReverseSolution { get; set; } //------------------------------------------------------------------------------ public bool StrictlySimple { get; set; } //------------------------------------------------------------------------------ public bool Execute(ClipType clipType, Paths solution, PolyFillType FillType = PolyFillType.pftEvenOdd) { return Execute(clipType, solution, FillType, FillType); } //------------------------------------------------------------------------------ public bool Execute(ClipType clipType, PolyTree polytree, PolyFillType FillType = PolyFillType.pftEvenOdd) { return Execute(clipType, polytree, FillType, FillType); } //------------------------------------------------------------------------------ public bool Execute(ClipType clipType, Paths solution, PolyFillType subjFillType, PolyFillType clipFillType) { if (m_ExecuteLocked) return false; if (m_HasOpenPaths) throw new ClipperException("Error: PolyTree struct is needed for open path clipping."); m_ExecuteLocked = true; solution.Clear(); m_SubjFillType = subjFillType; m_ClipFillType = clipFillType; m_ClipType = clipType; m_UsingPolyTree = false; bool succeeded; try { succeeded = ExecuteInternal(); //build the return polygons ... if (succeeded) BuildResult(solution); } finally { DisposeAllPolyPts(); m_ExecuteLocked = false; } return succeeded; } //------------------------------------------------------------------------------ public bool Execute(ClipType clipType, PolyTree polytree, PolyFillType subjFillType, PolyFillType clipFillType) { if (m_ExecuteLocked) return false; m_ExecuteLocked = true; m_SubjFillType = subjFillType; m_ClipFillType = clipFillType; m_ClipType = clipType; m_UsingPolyTree = true; bool succeeded; try { succeeded = ExecuteInternal(); //build the return polygons ... if (succeeded) BuildResult2(polytree); } finally { DisposeAllPolyPts(); m_ExecuteLocked = false; } return succeeded; } //------------------------------------------------------------------------------ internal void FixHoleLinkage(OutRec outRec) { //skip if an outermost polygon or //already already points to the correct FirstLeft ... if (outRec.FirstLeft == null || (outRec.IsHole != outRec.FirstLeft.IsHole && outRec.FirstLeft.Pts != null)) return; OutRec orfl = outRec.FirstLeft; while (orfl != null && ((orfl.IsHole == outRec.IsHole) || orfl.Pts == null)) orfl = orfl.FirstLeft; outRec.FirstLeft = orfl; } //------------------------------------------------------------------------------ private bool ExecuteInternal() { try { Reset(); m_SortedEdges = null; m_Maxima = null; cInt botY, topY; if (!PopScanbeam(out botY)) return false; InsertLocalMinimaIntoAEL(botY); while (PopScanbeam(out topY) || LocalMinimaPending()) { ProcessHorizontals(); m_GhostJoins.Clear(); if (!ProcessIntersections(topY)) return false; ProcessEdgesAtTopOfScanbeam(topY); botY = topY; InsertLocalMinimaIntoAEL(botY); } //fix orientations ... foreach (OutRec outRec in m_PolyOuts) { if (outRec.Pts == null || outRec.IsOpen) continue; if ((outRec.IsHole ^ ReverseSolution) == (Area(outRec) > 0)) ReversePolyPtLinks(outRec.Pts); } JoinCommonEdges(); foreach (OutRec outRec in m_PolyOuts) { if (outRec.Pts == null) continue; else if (outRec.IsOpen) FixupOutPolyline(outRec); else FixupOutPolygon(outRec); } if (StrictlySimple) DoSimplePolygons(); return true; } //catch { return false; } finally { m_Joins.Clear(); m_GhostJoins.Clear(); } } //------------------------------------------------------------------------------ private void DisposeAllPolyPts() { for (int i = 0; i < m_PolyOuts.Count; ++i) DisposeOutRec(i); m_PolyOuts.Clear(); } //------------------------------------------------------------------------------ private void AddJoin(OutPt Op1, OutPt Op2, IntPoint OffPt) { Join j = new Join(); j.OutPt1 = Op1; j.OutPt2 = Op2; j.OffPt = OffPt; m_Joins.Add(j); } //------------------------------------------------------------------------------ private void AddGhostJoin(OutPt Op, IntPoint OffPt) { Join j = new Join(); j.OutPt1 = Op; j.OffPt = OffPt; m_GhostJoins.Add(j); } //------------------------------------------------------------------------------ #if use_xyz internal void SetZ(ref IntPoint pt, TEdge e1, TEdge e2) { if (pt.Z != 0 || ZFillFunction == null) return; else if (pt == e1.Bot) pt.Z = e1.Bot.Z; else if (pt == e1.Top) pt.Z = e1.Top.Z; else if (pt == e2.Bot) pt.Z = e2.Bot.Z; else if (pt == e2.Top) pt.Z = e2.Top.Z; else ZFillFunction(e1.Bot, e1.Top, e2.Bot, e2.Top, ref pt); } //------------------------------------------------------------------------------ #endif private void InsertLocalMinimaIntoAEL(cInt botY) { LocalMinima lm; while (PopLocalMinima(botY, out lm)) { TEdge lb = lm.LeftBound; TEdge rb = lm.RightBound; OutPt Op1 = null; if (lb == null) { InsertEdgeIntoAEL(rb, null); SetWindingCount(rb); if (IsContributing(rb)) Op1 = AddOutPt(rb, rb.Bot); } else if (rb == null) { InsertEdgeIntoAEL(lb, null); SetWindingCount(lb); if (IsContributing(lb)) Op1 = AddOutPt(lb, lb.Bot); InsertScanbeam(lb.Top.Y); } else { InsertEdgeIntoAEL(lb, null); InsertEdgeIntoAEL(rb, lb); SetWindingCount(lb); rb.WindCnt = lb.WindCnt; rb.WindCnt2 = lb.WindCnt2; if (IsContributing(lb)) Op1 = AddLocalMinPoly(lb, rb, lb.Bot); InsertScanbeam(lb.Top.Y); } if (rb != null) { if (IsHorizontal(rb)) { if (rb.NextInLML != null) InsertScanbeam(rb.NextInLML.Top.Y); AddEdgeToSEL(rb); } else InsertScanbeam(rb.Top.Y); } if (lb == null || rb == null) continue; //if output polygons share an Edge with a horizontal rb, they'll need joining later ... if (Op1 != null && IsHorizontal(rb) && m_GhostJoins.Count > 0 && rb.WindDelta != 0) { for (int i = 0; i < m_GhostJoins.Count; i++) { //if the horizontal Rb and a 'ghost' horizontal overlap, then convert //the 'ghost' join to a real join ready for later ... Join j = m_GhostJoins[i]; if (HorzSegmentsOverlap(j.OutPt1.Pt.X, j.OffPt.X, rb.Bot.X, rb.Top.X)) AddJoin(j.OutPt1, Op1, j.OffPt); } } if (lb.OutIdx >= 0 && lb.PrevInAEL != null && lb.PrevInAEL.Curr.X == lb.Bot.X && lb.PrevInAEL.OutIdx >= 0 && SlopesEqual(lb.PrevInAEL.Curr, lb.PrevInAEL.Top, lb.Curr, lb.Top, m_UseFullRange) && lb.WindDelta != 0 && lb.PrevInAEL.WindDelta != 0) { OutPt Op2 = AddOutPt(lb.PrevInAEL, lb.Bot); AddJoin(Op1, Op2, lb.Top); } if (lb.NextInAEL != rb) { if (rb.OutIdx >= 0 && rb.PrevInAEL.OutIdx >= 0 && SlopesEqual(rb.PrevInAEL.Curr, rb.PrevInAEL.Top, rb.Curr, rb.Top, m_UseFullRange) && rb.WindDelta != 0 && rb.PrevInAEL.WindDelta != 0) { OutPt Op2 = AddOutPt(rb.PrevInAEL, rb.Bot); AddJoin(Op1, Op2, rb.Top); } TEdge e = lb.NextInAEL; if (e != null) while (e != rb) { //nb: For calculating winding counts etc, IntersectEdges() assumes //that param1 will be to the right of param2 ABOVE the intersection ... IntersectEdges(rb, e, lb.Curr); //order important here e = e.NextInAEL; } } } } //------------------------------------------------------------------------------ private void InsertEdgeIntoAEL(TEdge edge, TEdge startEdge) { if (m_ActiveEdges == null) { edge.PrevInAEL = null; edge.NextInAEL = null; m_ActiveEdges = edge; } else if (startEdge == null && E2InsertsBeforeE1(m_ActiveEdges, edge)) { edge.PrevInAEL = null; edge.NextInAEL = m_ActiveEdges; m_ActiveEdges.PrevInAEL = edge; m_ActiveEdges = edge; } else { if (startEdge == null) startEdge = m_ActiveEdges; while (startEdge.NextInAEL != null && !E2InsertsBeforeE1(startEdge.NextInAEL, edge)) startEdge = startEdge.NextInAEL; edge.NextInAEL = startEdge.NextInAEL; if (startEdge.NextInAEL != null) startEdge.NextInAEL.PrevInAEL = edge; edge.PrevInAEL = startEdge; startEdge.NextInAEL = edge; } } //---------------------------------------------------------------------- private bool E2InsertsBeforeE1(TEdge e1, TEdge e2) { if (e2.Curr.X == e1.Curr.X) { if (e2.Top.Y > e1.Top.Y) return e2.Top.X < TopX(e1, e2.Top.Y); else return e1.Top.X > TopX(e2, e1.Top.Y); } else return e2.Curr.X < e1.Curr.X; } //------------------------------------------------------------------------------ private bool IsEvenOddFillType(TEdge edge) { if (edge.PolyTyp == PolyType.ptSubject) return m_SubjFillType == PolyFillType.pftEvenOdd; else return m_ClipFillType == PolyFillType.pftEvenOdd; } //------------------------------------------------------------------------------ private bool IsEvenOddAltFillType(TEdge edge) { if (edge.PolyTyp == PolyType.ptSubject) return m_ClipFillType == PolyFillType.pftEvenOdd; else return m_SubjFillType == PolyFillType.pftEvenOdd; } //------------------------------------------------------------------------------ private bool IsContributing(TEdge edge) { PolyFillType pft, pft2; if (edge.PolyTyp == PolyType.ptSubject) { pft = m_SubjFillType; pft2 = m_ClipFillType; } else { pft = m_ClipFillType; pft2 = m_SubjFillType; } switch (pft) { case PolyFillType.pftEvenOdd: //return false if a subj line has been flagged as inside a subj polygon if (edge.WindDelta == 0 && edge.WindCnt != 1) return false; break; case PolyFillType.pftNonZero: if (Math.Abs(edge.WindCnt) != 1) return false; break; case PolyFillType.pftPositive: if (edge.WindCnt != 1) return false; break; default: //PolyFillType.pftNegative if (edge.WindCnt != -1) return false; break; } switch (m_ClipType) { case ClipType.ctIntersection: switch (pft2) { case PolyFillType.pftEvenOdd: case PolyFillType.pftNonZero: return (edge.WindCnt2 != 0); case PolyFillType.pftPositive: return (edge.WindCnt2 > 0); default: return (edge.WindCnt2 < 0); } case ClipType.ctUnion: switch (pft2) { case PolyFillType.pftEvenOdd: case PolyFillType.pftNonZero: return (edge.WindCnt2 == 0); case PolyFillType.pftPositive: return (edge.WindCnt2 <= 0); default: return (edge.WindCnt2 >= 0); } case ClipType.ctDifference: if (edge.PolyTyp == PolyType.ptSubject) switch (pft2) { case PolyFillType.pftEvenOdd: case PolyFillType.pftNonZero: return (edge.WindCnt2 == 0); case PolyFillType.pftPositive: return (edge.WindCnt2 <= 0); default: return (edge.WindCnt2 >= 0); } else switch (pft2) { case PolyFillType.pftEvenOdd: case PolyFillType.pftNonZero: return (edge.WindCnt2 != 0); case PolyFillType.pftPositive: return (edge.WindCnt2 > 0); default: return (edge.WindCnt2 < 0); } case ClipType.ctXor: if (edge.WindDelta == 0) //XOr always contributing unless open switch (pft2) { case PolyFillType.pftEvenOdd: case PolyFillType.pftNonZero: return (edge.WindCnt2 == 0); case PolyFillType.pftPositive: return (edge.WindCnt2 <= 0); default: return (edge.WindCnt2 >= 0); } else return true; } return true; } //------------------------------------------------------------------------------ private void SetWindingCount(TEdge edge) { TEdge e = edge.PrevInAEL; //find the edge of the same polytype that immediately preceeds 'edge' in AEL while (e != null && ((e.PolyTyp != edge.PolyTyp) || (e.WindDelta == 0))) e = e.PrevInAEL; if (e == null) { PolyFillType pft; pft = (edge.PolyTyp == PolyType.ptSubject ? m_SubjFillType : m_ClipFillType); if (edge.WindDelta == 0) edge.WindCnt = (pft == PolyFillType.pftNegative ? -1 : 1); else edge.WindCnt = edge.WindDelta; edge.WindCnt2 = 0; e = m_ActiveEdges; //ie get ready to calc WindCnt2 } else if (edge.WindDelta == 0 && m_ClipType != ClipType.ctUnion) { edge.WindCnt = 1; edge.WindCnt2 = e.WindCnt2; e = e.NextInAEL; //ie get ready to calc WindCnt2 } else if (IsEvenOddFillType(edge)) { //EvenOdd filling ... if (edge.WindDelta == 0) { //are we inside a subj polygon ... bool Inside = true; TEdge e2 = e.PrevInAEL; while (e2 != null) { if (e2.PolyTyp == e.PolyTyp && e2.WindDelta != 0) Inside = !Inside; e2 = e2.PrevInAEL; } edge.WindCnt = (Inside ? 0 : 1); } else { edge.WindCnt = edge.WindDelta; } edge.WindCnt2 = e.WindCnt2; e = e.NextInAEL; //ie get ready to calc WindCnt2 } else { //nonZero, Positive or Negative filling ... if (e.WindCnt * e.WindDelta < 0) { //prev edge is 'decreasing' WindCount (WC) toward zero //so we're outside the previous polygon ... if (Math.Abs(e.WindCnt) > 1) { //outside prev poly but still inside another. //when reversing direction of prev poly use the same WC if (e.WindDelta * edge.WindDelta < 0) edge.WindCnt = e.WindCnt; //otherwise continue to 'decrease' WC ... else edge.WindCnt = e.WindCnt + edge.WindDelta; } else //now outside all polys of same polytype so set own WC ... edge.WindCnt = (edge.WindDelta == 0 ? 1 : edge.WindDelta); } else { //prev edge is 'increasing' WindCount (WC) away from zero //so we're inside the previous polygon ... if (edge.WindDelta == 0) edge.WindCnt = (e.WindCnt < 0 ? e.WindCnt - 1 : e.WindCnt + 1); //if wind direction is reversing prev then use same WC else if (e.WindDelta * edge.WindDelta < 0) edge.WindCnt = e.WindCnt; //otherwise add to WC ... else edge.WindCnt = e.WindCnt + edge.WindDelta; } edge.WindCnt2 = e.WindCnt2; e = e.NextInAEL; //ie get ready to calc WindCnt2 } //update WindCnt2 ... if (IsEvenOddAltFillType(edge)) { //EvenOdd filling ... while (e != edge) { if (e.WindDelta != 0) edge.WindCnt2 = (edge.WindCnt2 == 0 ? 1 : 0); e = e.NextInAEL; } } else { //nonZero, Positive or Negative filling ... while (e != edge) { edge.WindCnt2 += e.WindDelta; e = e.NextInAEL; } } } //------------------------------------------------------------------------------ private void AddEdgeToSEL(TEdge edge) { //SEL pointers in PEdge are use to build transient lists of horizontal edges. //However, since we don't need to worry about processing order, all additions //are made to the front of the list ... if (m_SortedEdges == null) { m_SortedEdges = edge; edge.PrevInSEL = null; edge.NextInSEL = null; } else { edge.NextInSEL = m_SortedEdges; edge.PrevInSEL = null; m_SortedEdges.PrevInSEL = edge; m_SortedEdges = edge; } } //------------------------------------------------------------------------------ internal Boolean PopEdgeFromSEL(out TEdge e) { //Pop edge from front of SEL (ie SEL is a FILO list) e = m_SortedEdges; if (e == null) return false; TEdge oldE = e; m_SortedEdges = e.NextInSEL; if (m_SortedEdges != null) m_SortedEdges.PrevInSEL = null; oldE.NextInSEL = null; oldE.PrevInSEL = null; return true; } //------------------------------------------------------------------------------ private void CopyAELToSEL() { TEdge e = m_ActiveEdges; m_SortedEdges = e; while (e != null) { e.PrevInSEL = e.PrevInAEL; e.NextInSEL = e.NextInAEL; e = e.NextInAEL; } } //------------------------------------------------------------------------------ private void SwapPositionsInSEL(TEdge edge1, TEdge edge2) { if (edge1.NextInSEL == null && edge1.PrevInSEL == null) return; if (edge2.NextInSEL == null && edge2.PrevInSEL == null) return; if (edge1.NextInSEL == edge2) { TEdge next = edge2.NextInSEL; if (next != null) next.PrevInSEL = edge1; TEdge prev = edge1.PrevInSEL; if (prev != null) prev.NextInSEL = edge2; edge2.PrevInSEL = prev; edge2.NextInSEL = edge1; edge1.PrevInSEL = edge2; edge1.NextInSEL = next; } else if (edge2.NextInSEL == edge1) { TEdge next = edge1.NextInSEL; if (next != null) next.PrevInSEL = edge2; TEdge prev = edge2.PrevInSEL; if (prev != null) prev.NextInSEL = edge1; edge1.PrevInSEL = prev; edge1.NextInSEL = edge2; edge2.PrevInSEL = edge1; edge2.NextInSEL = next; } else { TEdge next = edge1.NextInSEL; TEdge prev = edge1.PrevInSEL; edge1.NextInSEL = edge2.NextInSEL; if (edge1.NextInSEL != null) edge1.NextInSEL.PrevInSEL = edge1; edge1.PrevInSEL = edge2.PrevInSEL; if (edge1.PrevInSEL != null) edge1.PrevInSEL.NextInSEL = edge1; edge2.NextInSEL = next; if (edge2.NextInSEL != null) edge2.NextInSEL.PrevInSEL = edge2; edge2.PrevInSEL = prev; if (edge2.PrevInSEL != null) edge2.PrevInSEL.NextInSEL = edge2; } if (edge1.PrevInSEL == null) m_SortedEdges = edge1; else if (edge2.PrevInSEL == null) m_SortedEdges = edge2; } //------------------------------------------------------------------------------ private void AddLocalMaxPoly(TEdge e1, TEdge e2, IntPoint pt) { AddOutPt(e1, pt); if (e2.WindDelta == 0) AddOutPt(e2, pt); if (e1.OutIdx == e2.OutIdx) { e1.OutIdx = Unassigned; e2.OutIdx = Unassigned; } else if (e1.OutIdx < e2.OutIdx) AppendPolygon(e1, e2); else AppendPolygon(e2, e1); } //------------------------------------------------------------------------------ private OutPt AddLocalMinPoly(TEdge e1, TEdge e2, IntPoint pt) { OutPt result; TEdge e, prevE; if (IsHorizontal(e2) || (e1.Dx > e2.Dx)) { result = AddOutPt(e1, pt); e2.OutIdx = e1.OutIdx; e1.Side = EdgeSide.esLeft; e2.Side = EdgeSide.esRight; e = e1; if (e.PrevInAEL == e2) prevE = e2.PrevInAEL; else prevE = e.PrevInAEL; } else { result = AddOutPt(e2, pt); e1.OutIdx = e2.OutIdx; e1.Side = EdgeSide.esRight; e2.Side = EdgeSide.esLeft; e = e2; if (e.PrevInAEL == e1) prevE = e1.PrevInAEL; else prevE = e.PrevInAEL; } if (prevE != null && prevE.OutIdx >= 0 && prevE.Top.Y < pt.Y && e.Top.Y < pt.Y) { cInt xPrev = TopX(prevE, pt.Y); cInt xE = TopX(e, pt.Y); if ((xPrev == xE) && (e.WindDelta != 0) && (prevE.WindDelta != 0) && SlopesEqual(new IntPoint(xPrev, pt.Y), prevE.Top, new IntPoint(xE, pt.Y), e.Top, m_UseFullRange)) { OutPt outPt = AddOutPt(prevE, pt); AddJoin(result, outPt, e.Top); } } return result; } //------------------------------------------------------------------------------ private OutPt AddOutPt(TEdge e, IntPoint pt) { if (e.OutIdx < 0) { OutRec outRec = CreateOutRec(); outRec.IsOpen = (e.WindDelta == 0); OutPt newOp = new OutPt(); outRec.Pts = newOp; newOp.Idx = outRec.Idx; newOp.Pt = pt; newOp.Next = newOp; newOp.Prev = newOp; if (!outRec.IsOpen) SetHoleState(e, outRec); e.OutIdx = outRec.Idx; //nb: do this after SetZ ! return newOp; } else { OutRec outRec = m_PolyOuts[e.OutIdx]; //OutRec.Pts is the 'Left-most' point & OutRec.Pts.Prev is the 'Right-most' OutPt op = outRec.Pts; bool ToFront = (e.Side == EdgeSide.esLeft); if (ToFront && pt == op.Pt) return op; else if (!ToFront && pt == op.Prev.Pt) return op.Prev; OutPt newOp = new OutPt(); newOp.Idx = outRec.Idx; newOp.Pt = pt; newOp.Next = op; newOp.Prev = op.Prev; newOp.Prev.Next = newOp; op.Prev = newOp; if (ToFront) outRec.Pts = newOp; return newOp; } } //------------------------------------------------------------------------------ private OutPt GetLastOutPt(TEdge e) { OutRec outRec = m_PolyOuts[e.OutIdx]; if (e.Side == EdgeSide.esLeft) return outRec.Pts; else return outRec.Pts.Prev; } //------------------------------------------------------------------------------ internal void SwapPoints(ref IntPoint pt1, ref IntPoint pt2) { IntPoint tmp = new IntPoint(pt1); pt1 = pt2; pt2 = tmp; } //------------------------------------------------------------------------------ private bool HorzSegmentsOverlap(cInt seg1a, cInt seg1b, cInt seg2a, cInt seg2b) { if (seg1a > seg1b) Swap(ref seg1a, ref seg1b); if (seg2a > seg2b) Swap(ref seg2a, ref seg2b); return (seg1a < seg2b) && (seg2a < seg1b); } //------------------------------------------------------------------------------ private void SetHoleState(TEdge e, OutRec outRec) { TEdge e2 = e.PrevInAEL; TEdge eTmp = null; while (e2 != null) { if (e2.OutIdx >= 0 && e2.WindDelta != 0) { if (eTmp == null) eTmp = e2; else if (eTmp.OutIdx == e2.OutIdx) eTmp = null; //paired } e2 = e2.PrevInAEL; } if (eTmp == null) { outRec.FirstLeft = null; outRec.IsHole = false; } else { outRec.FirstLeft = m_PolyOuts[eTmp.OutIdx]; outRec.IsHole = !outRec.FirstLeft.IsHole; } } //------------------------------------------------------------------------------ private double GetDx(IntPoint pt1, IntPoint pt2) { if (pt1.Y == pt2.Y) return horizontal; else return (double)(pt2.X - pt1.X) / (pt2.Y - pt1.Y); } //--------------------------------------------------------------------------- private bool FirstIsBottomPt(OutPt btmPt1, OutPt btmPt2) { OutPt p = btmPt1.Prev; while ((p.Pt == btmPt1.Pt) && (p != btmPt1)) p = p.Prev; double dx1p = Math.Abs(GetDx(btmPt1.Pt, p.Pt)); p = btmPt1.Next; while ((p.Pt == btmPt1.Pt) && (p != btmPt1)) p = p.Next; double dx1n = Math.Abs(GetDx(btmPt1.Pt, p.Pt)); p = btmPt2.Prev; while ((p.Pt == btmPt2.Pt) && (p != btmPt2)) p = p.Prev; double dx2p = Math.Abs(GetDx(btmPt2.Pt, p.Pt)); p = btmPt2.Next; while ((p.Pt == btmPt2.Pt) && (p != btmPt2)) p = p.Next; double dx2n = Math.Abs(GetDx(btmPt2.Pt, p.Pt)); if (Math.Max(dx1p, dx1n) == Math.Max(dx2p, dx2n) && Math.Min(dx1p, dx1n) == Math.Min(dx2p, dx2n)) return Area(btmPt1) > 0; //if otherwise identical use orientation else return (dx1p >= dx2p && dx1p >= dx2n) || (dx1n >= dx2p && dx1n >= dx2n); } //------------------------------------------------------------------------------ private OutPt GetBottomPt(OutPt pp) { OutPt dups = null; OutPt p = pp.Next; while (p != pp) { if (p.Pt.Y > pp.Pt.Y) { pp = p; dups = null; } else if (p.Pt.Y == pp.Pt.Y && p.Pt.X <= pp.Pt.X) { if (p.Pt.X < pp.Pt.X) { dups = null; pp = p; } else { if (p.Next != pp && p.Prev != pp) dups = p; } } p = p.Next; } if (dups != null) { //there appears to be at least 2 vertices at bottomPt so ... while (dups != p) { if (!FirstIsBottomPt(p, dups)) pp = dups; dups = dups.Next; while (dups.Pt != pp.Pt) dups = dups.Next; } } return pp; } //------------------------------------------------------------------------------ private OutRec GetLowermostRec(OutRec outRec1, OutRec outRec2) { //work out which polygon fragment has the correct hole state ... if (outRec1.BottomPt == null) outRec1.BottomPt = GetBottomPt(outRec1.Pts); if (outRec2.BottomPt == null) outRec2.BottomPt = GetBottomPt(outRec2.Pts); OutPt bPt1 = outRec1.BottomPt; OutPt bPt2 = outRec2.BottomPt; if (bPt1.Pt.Y > bPt2.Pt.Y) return outRec1; else if (bPt1.Pt.Y < bPt2.Pt.Y) return outRec2; else if (bPt1.Pt.X < bPt2.Pt.X) return outRec1; else if (bPt1.Pt.X > bPt2.Pt.X) return outRec2; else if (bPt1.Next == bPt1) return outRec2; else if (bPt2.Next == bPt2) return outRec1; else if (FirstIsBottomPt(bPt1, bPt2)) return outRec1; else return outRec2; } //------------------------------------------------------------------------------ bool OutRec1RightOfOutRec2(OutRec outRec1, OutRec outRec2) { do { outRec1 = outRec1.FirstLeft; if (outRec1 == outRec2) return true; } while (outRec1 != null); return false; } //------------------------------------------------------------------------------ private OutRec GetOutRec(int idx) { OutRec outrec = m_PolyOuts[idx]; while (outrec != m_PolyOuts[outrec.Idx]) outrec = m_PolyOuts[outrec.Idx]; return outrec; } //------------------------------------------------------------------------------ private void AppendPolygon(TEdge e1, TEdge e2) { OutRec outRec1 = m_PolyOuts[e1.OutIdx]; OutRec outRec2 = m_PolyOuts[e2.OutIdx]; OutRec holeStateRec; if (OutRec1RightOfOutRec2(outRec1, outRec2)) holeStateRec = outRec2; else if (OutRec1RightOfOutRec2(outRec2, outRec1)) holeStateRec = outRec1; else holeStateRec = GetLowermostRec(outRec1, outRec2); //get the start and ends of both output polygons and //join E2 poly onto E1 poly and delete pointers to E2 ... OutPt p1_lft = outRec1.Pts; OutPt p1_rt = p1_lft.Prev; OutPt p2_lft = outRec2.Pts; OutPt p2_rt = p2_lft.Prev; //join e2 poly onto e1 poly and delete pointers to e2 ... if (e1.Side == EdgeSide.esLeft) { if (e2.Side == EdgeSide.esLeft) { //z y x a b c ReversePolyPtLinks(p2_lft); p2_lft.Next = p1_lft; p1_lft.Prev = p2_lft; p1_rt.Next = p2_rt; p2_rt.Prev = p1_rt; outRec1.Pts = p2_rt; } else { //x y z a b c p2_rt.Next = p1_lft; p1_lft.Prev = p2_rt; p2_lft.Prev = p1_rt; p1_rt.Next = p2_lft; outRec1.Pts = p2_lft; } } else { if (e2.Side == EdgeSide.esRight) { //a b c z y x ReversePolyPtLinks(p2_lft); p1_rt.Next = p2_rt; p2_rt.Prev = p1_rt; p2_lft.Next = p1_lft; p1_lft.Prev = p2_lft; } else { //a b c x y z p1_rt.Next = p2_lft; p2_lft.Prev = p1_rt; p1_lft.Prev = p2_rt; p2_rt.Next = p1_lft; } } outRec1.BottomPt = null; if (holeStateRec == outRec2) { if (outRec2.FirstLeft != outRec1) outRec1.FirstLeft = outRec2.FirstLeft; outRec1.IsHole = outRec2.IsHole; } outRec2.Pts = null; outRec2.BottomPt = null; outRec2.FirstLeft = outRec1; int OKIdx = e1.OutIdx; int ObsoleteIdx = e2.OutIdx; e1.OutIdx = Unassigned; //nb: safe because we only get here via AddLocalMaxPoly e2.OutIdx = Unassigned; TEdge e = m_ActiveEdges; while (e != null) { if (e.OutIdx == ObsoleteIdx) { e.OutIdx = OKIdx; e.Side = e1.Side; break; } e = e.NextInAEL; } outRec2.Idx = outRec1.Idx; } //------------------------------------------------------------------------------ private void ReversePolyPtLinks(OutPt pp) { if (pp == null) return; OutPt pp1; OutPt pp2; pp1 = pp; do { pp2 = pp1.Next; pp1.Next = pp1.Prev; pp1.Prev = pp2; pp1 = pp2; } while (pp1 != pp); } //------------------------------------------------------------------------------ private static void SwapSides(TEdge edge1, TEdge edge2) { EdgeSide side = edge1.Side; edge1.Side = edge2.Side; edge2.Side = side; } //------------------------------------------------------------------------------ private static void SwapPolyIndexes(TEdge edge1, TEdge edge2) { int outIdx = edge1.OutIdx; edge1.OutIdx = edge2.OutIdx; edge2.OutIdx = outIdx; } //------------------------------------------------------------------------------ private void IntersectEdges(TEdge e1, TEdge e2, IntPoint pt) { //e1 will be to the left of e2 BELOW the intersection. Therefore e1 is before //e2 in AEL except when e1 is being inserted at the intersection point ... bool e1Contributing = (e1.OutIdx >= 0); bool e2Contributing = (e2.OutIdx >= 0); #if use_xyz SetZ(ref pt, e1, e2); #endif #if use_lines //if either edge is on an OPEN path ... if (e1.WindDelta == 0 || e2.WindDelta == 0) { //ignore subject-subject open path intersections UNLESS they //are both open paths, AND they are both 'contributing maximas' ... if (e1.WindDelta == 0 && e2.WindDelta == 0) return; //if intersecting a subj line with a subj poly ... else if (e1.PolyTyp == e2.PolyTyp && e1.WindDelta != e2.WindDelta && m_ClipType == ClipType.ctUnion) { if (e1.WindDelta == 0) { if (e2Contributing) { AddOutPt(e1, pt); if (e1Contributing) e1.OutIdx = Unassigned; } } else { if (e1Contributing) { AddOutPt(e2, pt); if (e2Contributing) e2.OutIdx = Unassigned; } } } else if (e1.PolyTyp != e2.PolyTyp) { if ((e1.WindDelta == 0) && Math.Abs(e2.WindCnt) == 1 && (m_ClipType != ClipType.ctUnion || e2.WindCnt2 == 0)) { AddOutPt(e1, pt); if (e1Contributing) e1.OutIdx = Unassigned; } else if ((e2.WindDelta == 0) && (Math.Abs(e1.WindCnt) == 1) && (m_ClipType != ClipType.ctUnion || e1.WindCnt2 == 0)) { AddOutPt(e2, pt); if (e2Contributing) e2.OutIdx = Unassigned; } } return; } #endif //update winding counts... //assumes that e1 will be to the Right of e2 ABOVE the intersection if (e1.PolyTyp == e2.PolyTyp) { if (IsEvenOddFillType(e1)) { int oldE1WindCnt = e1.WindCnt; e1.WindCnt = e2.WindCnt; e2.WindCnt = oldE1WindCnt; } else { if (e1.WindCnt + e2.WindDelta == 0) e1.WindCnt = -e1.WindCnt; else e1.WindCnt += e2.WindDelta; if (e2.WindCnt - e1.WindDelta == 0) e2.WindCnt = -e2.WindCnt; else e2.WindCnt -= e1.WindDelta; } } else { if (!IsEvenOddFillType(e2)) e1.WindCnt2 += e2.WindDelta; else e1.WindCnt2 = (e1.WindCnt2 == 0) ? 1 : 0; if (!IsEvenOddFillType(e1)) e2.WindCnt2 -= e1.WindDelta; else e2.WindCnt2 = (e2.WindCnt2 == 0) ? 1 : 0; } PolyFillType e1FillType, e2FillType, e1FillType2, e2FillType2; if (e1.PolyTyp == PolyType.ptSubject) { e1FillType = m_SubjFillType; e1FillType2 = m_ClipFillType; } else { e1FillType = m_ClipFillType; e1FillType2 = m_SubjFillType; } if (e2.PolyTyp == PolyType.ptSubject) { e2FillType = m_SubjFillType; e2FillType2 = m_ClipFillType; } else { e2FillType = m_ClipFillType; e2FillType2 = m_SubjFillType; } int e1Wc, e2Wc; switch (e1FillType) { case PolyFillType.pftPositive: e1Wc = e1.WindCnt; break; case PolyFillType.pftNegative: e1Wc = -e1.WindCnt; break; default: e1Wc = Math.Abs(e1.WindCnt); break; } switch (e2FillType) { case PolyFillType.pftPositive: e2Wc = e2.WindCnt; break; case PolyFillType.pftNegative: e2Wc = -e2.WindCnt; break; default: e2Wc = Math.Abs(e2.WindCnt); break; } if (e1Contributing && e2Contributing) { if ((e1Wc != 0 && e1Wc != 1) || (e2Wc != 0 && e2Wc != 1) || (e1.PolyTyp != e2.PolyTyp && m_ClipType != ClipType.ctXor)) { AddLocalMaxPoly(e1, e2, pt); } else { AddOutPt(e1, pt); AddOutPt(e2, pt); SwapSides(e1, e2); SwapPolyIndexes(e1, e2); } } else if (e1Contributing) { if (e2Wc == 0 || e2Wc == 1) { AddOutPt(e1, pt); SwapSides(e1, e2); SwapPolyIndexes(e1, e2); } } else if (e2Contributing) { if (e1Wc == 0 || e1Wc == 1) { AddOutPt(e2, pt); SwapSides(e1, e2); SwapPolyIndexes(e1, e2); } } else if ((e1Wc == 0 || e1Wc == 1) && (e2Wc == 0 || e2Wc == 1)) { //neither edge is currently contributing ... cInt e1Wc2, e2Wc2; switch (e1FillType2) { case PolyFillType.pftPositive: e1Wc2 = e1.WindCnt2; break; case PolyFillType.pftNegative: e1Wc2 = -e1.WindCnt2; break; default: e1Wc2 = Math.Abs(e1.WindCnt2); break; } switch (e2FillType2) { case PolyFillType.pftPositive: e2Wc2 = e2.WindCnt2; break; case PolyFillType.pftNegative: e2Wc2 = -e2.WindCnt2; break; default: e2Wc2 = Math.Abs(e2.WindCnt2); break; } if (e1.PolyTyp != e2.PolyTyp) { AddLocalMinPoly(e1, e2, pt); } else if (e1Wc == 1 && e2Wc == 1) switch (m_ClipType) { case ClipType.ctIntersection: if (e1Wc2 > 0 && e2Wc2 > 0) AddLocalMinPoly(e1, e2, pt); break; case ClipType.ctUnion: if (e1Wc2 <= 0 && e2Wc2 <= 0) AddLocalMinPoly(e1, e2, pt); break; case ClipType.ctDifference: if (((e1.PolyTyp == PolyType.ptClip) && (e1Wc2 > 0) && (e2Wc2 > 0)) || ((e1.PolyTyp == PolyType.ptSubject) && (e1Wc2 <= 0) && (e2Wc2 <= 0))) AddLocalMinPoly(e1, e2, pt); break; case ClipType.ctXor: AddLocalMinPoly(e1, e2, pt); break; } else SwapSides(e1, e2); } } //------------------------------------------------------------------------------ private void DeleteFromSEL(TEdge e) { TEdge SelPrev = e.PrevInSEL; TEdge SelNext = e.NextInSEL; if (SelPrev == null && SelNext == null && (e != m_SortedEdges)) return; //already deleted if (SelPrev != null) SelPrev.NextInSEL = SelNext; else m_SortedEdges = SelNext; if (SelNext != null) SelNext.PrevInSEL = SelPrev; e.NextInSEL = null; e.PrevInSEL = null; } //------------------------------------------------------------------------------ private void ProcessHorizontals() { TEdge horzEdge; //m_SortedEdges; while (PopEdgeFromSEL(out horzEdge)) ProcessHorizontal(horzEdge); } //------------------------------------------------------------------------------ void GetHorzDirection(TEdge HorzEdge, out Direction Dir, out cInt Left, out cInt Right) { if (HorzEdge.Bot.X < HorzEdge.Top.X) { Left = HorzEdge.Bot.X; Right = HorzEdge.Top.X; Dir = Direction.dLeftToRight; } else { Left = HorzEdge.Top.X; Right = HorzEdge.Bot.X; Dir = Direction.dRightToLeft; } } //------------------------------------------------------------------------ private void ProcessHorizontal(TEdge horzEdge) { Direction dir; cInt horzLeft, horzRight; bool IsOpen = horzEdge.WindDelta == 0; GetHorzDirection(horzEdge, out dir, out horzLeft, out horzRight); TEdge eLastHorz = horzEdge, eMaxPair = null; while (eLastHorz.NextInLML != null && IsHorizontal(eLastHorz.NextInLML)) eLastHorz = eLastHorz.NextInLML; if (eLastHorz.NextInLML == null) eMaxPair = GetMaximaPair(eLastHorz); Maxima currMax = m_Maxima; if (currMax != null) { //get the first maxima in range (X) ... if (dir == Direction.dLeftToRight) { while (currMax != null && currMax.X <= horzEdge.Bot.X) currMax = currMax.Next; if (currMax != null && currMax.X >= eLastHorz.Top.X) currMax = null; } else { while (currMax.Next != null && currMax.Next.X < horzEdge.Bot.X) currMax = currMax.Next; if (currMax.X <= eLastHorz.Top.X) currMax = null; } } OutPt op1 = null; for (;;) //loop through consec. horizontal edges { bool IsLastHorz = (horzEdge == eLastHorz); TEdge e = GetNextInAEL(horzEdge, dir); while (e != null) { //this code block inserts extra coords into horizontal edges (in output //polygons) whereever maxima touch these horizontal edges. This helps //'simplifying' polygons (ie if the Simplify property is set). if (currMax != null) { if (dir == Direction.dLeftToRight) { while (currMax != null && currMax.X < e.Curr.X) { if (horzEdge.OutIdx >= 0 && !IsOpen) AddOutPt(horzEdge, new IntPoint(currMax.X, horzEdge.Bot.Y)); currMax = currMax.Next; } } else { while (currMax != null && currMax.X > e.Curr.X) { if (horzEdge.OutIdx >= 0 && !IsOpen) AddOutPt(horzEdge, new IntPoint(currMax.X, horzEdge.Bot.Y)); currMax = currMax.Prev; } } } if ((dir == Direction.dLeftToRight && e.Curr.X > horzRight) || (dir == Direction.dRightToLeft && e.Curr.X < horzLeft)) break; //Also break if we've got to the end of an intermediate horizontal edge ... //nb: Smaller Dx's are to the right of larger Dx's ABOVE the horizontal. if (e.Curr.X == horzEdge.Top.X && horzEdge.NextInLML != null && e.Dx < horzEdge.NextInLML.Dx) break; if (horzEdge.OutIdx >= 0 && !IsOpen) //note: may be done multiple times { #if use_xyz if (dir == Direction.dLeftToRight) SetZ(ref e.Curr, horzEdge, e); else SetZ(ref e.Curr, e, horzEdge); #endif op1 = AddOutPt(horzEdge, e.Curr); TEdge eNextHorz = m_SortedEdges; while (eNextHorz != null) { if (eNextHorz.OutIdx >= 0 && HorzSegmentsOverlap(horzEdge.Bot.X, horzEdge.Top.X, eNextHorz.Bot.X, eNextHorz.Top.X)) { OutPt op2 = GetLastOutPt(eNextHorz); AddJoin(op2, op1, eNextHorz.Top); } eNextHorz = eNextHorz.NextInSEL; } AddGhostJoin(op1, horzEdge.Bot); } //OK, so far we're still in range of the horizontal Edge but make sure //we're at the last of consec. horizontals when matching with eMaxPair if (e == eMaxPair && IsLastHorz) { if (horzEdge.OutIdx >= 0) AddLocalMaxPoly(horzEdge, eMaxPair, horzEdge.Top); DeleteFromAEL(horzEdge); DeleteFromAEL(eMaxPair); return; } if (dir == Direction.dLeftToRight) { IntPoint Pt = new IntPoint(e.Curr.X, horzEdge.Curr.Y); IntersectEdges(horzEdge, e, Pt); } else { IntPoint Pt = new IntPoint(e.Curr.X, horzEdge.Curr.Y); IntersectEdges(e, horzEdge, Pt); } TEdge eNext = GetNextInAEL(e, dir); SwapPositionsInAEL(horzEdge, e); e = eNext; } //end while(e != null) //Break out of loop if HorzEdge.NextInLML is not also horizontal ... if (horzEdge.NextInLML == null || !IsHorizontal(horzEdge.NextInLML)) break; UpdateEdgeIntoAEL(ref horzEdge); if (horzEdge.OutIdx >= 0) AddOutPt(horzEdge, horzEdge.Bot); GetHorzDirection(horzEdge, out dir, out horzLeft, out horzRight); } //end for (;;) if (horzEdge.OutIdx >= 0 && op1 == null) { op1 = GetLastOutPt(horzEdge); TEdge eNextHorz = m_SortedEdges; while (eNextHorz != null) { if (eNextHorz.OutIdx >= 0 && HorzSegmentsOverlap(horzEdge.Bot.X, horzEdge.Top.X, eNextHorz.Bot.X, eNextHorz.Top.X)) { OutPt op2 = GetLastOutPt(eNextHorz); AddJoin(op2, op1, eNextHorz.Top); } eNextHorz = eNextHorz.NextInSEL; } AddGhostJoin(op1, horzEdge.Top); } if (horzEdge.NextInLML != null) { if (horzEdge.OutIdx >= 0) { op1 = AddOutPt(horzEdge, horzEdge.Top); UpdateEdgeIntoAEL(ref horzEdge); if (horzEdge.WindDelta == 0) return; //nb: HorzEdge is no longer horizontal here TEdge ePrev = horzEdge.PrevInAEL; TEdge eNext = horzEdge.NextInAEL; if (ePrev != null && ePrev.Curr.X == horzEdge.Bot.X && ePrev.Curr.Y == horzEdge.Bot.Y && ePrev.WindDelta != 0 && (ePrev.OutIdx >= 0 && ePrev.Curr.Y > ePrev.Top.Y && SlopesEqual(horzEdge, ePrev, m_UseFullRange))) { OutPt op2 = AddOutPt(ePrev, horzEdge.Bot); AddJoin(op1, op2, horzEdge.Top); } else if (eNext != null && eNext.Curr.X == horzEdge.Bot.X && eNext.Curr.Y == horzEdge.Bot.Y && eNext.WindDelta != 0 && eNext.OutIdx >= 0 && eNext.Curr.Y > eNext.Top.Y && SlopesEqual(horzEdge, eNext, m_UseFullRange)) { OutPt op2 = AddOutPt(eNext, horzEdge.Bot); AddJoin(op1, op2, horzEdge.Top); } } else UpdateEdgeIntoAEL(ref horzEdge); } else { if (horzEdge.OutIdx >= 0) AddOutPt(horzEdge, horzEdge.Top); DeleteFromAEL(horzEdge); } } //------------------------------------------------------------------------------ private TEdge GetNextInAEL(TEdge e, Direction Direction) { return Direction == Direction.dLeftToRight ? e.NextInAEL : e.PrevInAEL; } //------------------------------------------------------------------------------ private bool IsMinima(TEdge e) { return e != null && (e.Prev.NextInLML != e) && (e.Next.NextInLML != e); } //------------------------------------------------------------------------------ private bool IsMaxima(TEdge e, double Y) { return (e != null && e.Top.Y == Y && e.NextInLML == null); } //------------------------------------------------------------------------------ private bool IsIntermediate(TEdge e, double Y) { return (e.Top.Y == Y && e.NextInLML != null); } //------------------------------------------------------------------------------ internal TEdge GetMaximaPair(TEdge e) { if ((e.Next.Top == e.Top) && e.Next.NextInLML == null) return e.Next; else if ((e.Prev.Top == e.Top) && e.Prev.NextInLML == null) return e.Prev; else return null; } //------------------------------------------------------------------------------ internal TEdge GetMaximaPairEx(TEdge e) { //as above but returns null if MaxPair isn't in AEL (unless it's horizontal) TEdge result = GetMaximaPair(e); if (result == null || result.OutIdx == Skip || ((result.NextInAEL == result.PrevInAEL) && !IsHorizontal(result))) return null; return result; } //------------------------------------------------------------------------------ private bool ProcessIntersections(cInt topY) { if (m_ActiveEdges == null) return true; try { BuildIntersectList(topY); if (m_IntersectList.Count == 0) return true; if (m_IntersectList.Count == 1 || FixupIntersectionOrder()) ProcessIntersectList(); else return false; } catch { m_SortedEdges = null; m_IntersectList.Clear(); throw new ClipperException("ProcessIntersections error"); } m_SortedEdges = null; return true; } //------------------------------------------------------------------------------ private void BuildIntersectList(cInt topY) { if (m_ActiveEdges == null) return; //prepare for sorting ... TEdge e = m_ActiveEdges; m_SortedEdges = e; while (e != null) { e.PrevInSEL = e.PrevInAEL; e.NextInSEL = e.NextInAEL; e.Curr.X = TopX(e, topY); e = e.NextInAEL; } //bubblesort ... bool isModified = true; while (isModified && m_SortedEdges != null) { isModified = false; e = m_SortedEdges; while (e.NextInSEL != null) { TEdge eNext = e.NextInSEL; IntPoint pt; if (e.Curr.X > eNext.Curr.X) { IntersectPoint(e, eNext, out pt); if (pt.Y < topY) pt = new IntPoint(TopX(e, topY), topY); IntersectNode newNode = new IntersectNode(); newNode.Edge1 = e; newNode.Edge2 = eNext; newNode.Pt = pt; m_IntersectList.Add(newNode); SwapPositionsInSEL(e, eNext); isModified = true; } else e = eNext; } if (e.PrevInSEL != null) e.PrevInSEL.NextInSEL = null; else break; } m_SortedEdges = null; } //------------------------------------------------------------------------------ private bool EdgesAdjacent(IntersectNode inode) { return (inode.Edge1.NextInSEL == inode.Edge2) || (inode.Edge1.PrevInSEL == inode.Edge2); } //------------------------------------------------------------------------------ private static int IntersectNodeSort(IntersectNode node1, IntersectNode node2) { //the following typecast is safe because the differences in Pt.Y will //be limited to the height of the scanbeam. return (int)(node2.Pt.Y - node1.Pt.Y); } //------------------------------------------------------------------------------ private bool FixupIntersectionOrder() { //pre-condition: intersections are sorted bottom-most first. //Now it's crucial that intersections are made only between adjacent edges, //so to ensure this the order of intersections may need adjusting ... m_IntersectList.Sort(m_IntersectNodeComparer); CopyAELToSEL(); int cnt = m_IntersectList.Count; for (int i = 0; i < cnt; i++) { if (!EdgesAdjacent(m_IntersectList[i])) { int j = i + 1; while (j < cnt && !EdgesAdjacent(m_IntersectList[j])) j++; if (j == cnt) return false; IntersectNode tmp = m_IntersectList[i]; m_IntersectList[i] = m_IntersectList[j]; m_IntersectList[j] = tmp; } SwapPositionsInSEL(m_IntersectList[i].Edge1, m_IntersectList[i].Edge2); } return true; } //------------------------------------------------------------------------------ private void ProcessIntersectList() { for (int i = 0; i < m_IntersectList.Count; i++) { IntersectNode iNode = m_IntersectList[i]; { IntersectEdges(iNode.Edge1, iNode.Edge2, iNode.Pt); SwapPositionsInAEL(iNode.Edge1, iNode.Edge2); } } m_IntersectList.Clear(); } //------------------------------------------------------------------------------ internal static cInt Round(double value) { return value < 0 ? (cInt)(value - 0.5) : (cInt)(value + 0.5); } //------------------------------------------------------------------------------ private static cInt TopX(TEdge edge, cInt currentY) { if (currentY == edge.Top.Y) return edge.Top.X; return edge.Bot.X + Round(edge.Dx * (currentY - edge.Bot.Y)); } //------------------------------------------------------------------------------ private void IntersectPoint(TEdge edge1, TEdge edge2, out IntPoint ip) { ip = new IntPoint(); double b1, b2; //nb: with very large coordinate values, it's possible for SlopesEqual() to //return false but for the edge.Dx value be equal due to double precision rounding. if (edge1.Dx == edge2.Dx) { ip.Y = edge1.Curr.Y; ip.X = TopX(edge1, ip.Y); return; } if (edge1.Delta.X == 0) { ip.X = edge1.Bot.X; if (IsHorizontal(edge2)) { ip.Y = edge2.Bot.Y; } else { b2 = edge2.Bot.Y - (edge2.Bot.X / edge2.Dx); ip.Y = Round(ip.X / edge2.Dx + b2); } } else if (edge2.Delta.X == 0) { ip.X = edge2.Bot.X; if (IsHorizontal(edge1)) { ip.Y = edge1.Bot.Y; } else { b1 = edge1.Bot.Y - (edge1.Bot.X / edge1.Dx); ip.Y = Round(ip.X / edge1.Dx + b1); } } else { b1 = edge1.Bot.X - edge1.Bot.Y * edge1.Dx; b2 = edge2.Bot.X - edge2.Bot.Y * edge2.Dx; double q = (b2 - b1) / (edge1.Dx - edge2.Dx); ip.Y = Round(q); if (Math.Abs(edge1.Dx) < Math.Abs(edge2.Dx)) ip.X = Round(edge1.Dx * q + b1); else ip.X = Round(edge2.Dx * q + b2); } if (ip.Y < edge1.Top.Y || ip.Y < edge2.Top.Y) { if (edge1.Top.Y > edge2.Top.Y) ip.Y = edge1.Top.Y; else ip.Y = edge2.Top.Y; if (Math.Abs(edge1.Dx) < Math.Abs(edge2.Dx)) ip.X = TopX(edge1, ip.Y); else ip.X = TopX(edge2, ip.Y); } //finally, don't allow 'ip' to be BELOW curr.Y (ie bottom of scanbeam) ... if (ip.Y > edge1.Curr.Y) { ip.Y = edge1.Curr.Y; //better to use the more vertical edge to derive X ... if (Math.Abs(edge1.Dx) > Math.Abs(edge2.Dx)) ip.X = TopX(edge2, ip.Y); else ip.X = TopX(edge1, ip.Y); } } //------------------------------------------------------------------------------ private void ProcessEdgesAtTopOfScanbeam(cInt topY) { TEdge e = m_ActiveEdges; while (e != null) { //1. process maxima, treating them as if they're 'bent' horizontal edges, // but exclude maxima with horizontal edges. nb: e can't be a horizontal. bool IsMaximaEdge = IsMaxima(e, topY); if (IsMaximaEdge) { TEdge eMaxPair = GetMaximaPairEx(e); IsMaximaEdge = (eMaxPair == null || !IsHorizontal(eMaxPair)); } if (IsMaximaEdge) { if (StrictlySimple) InsertMaxima(e.Top.X); TEdge ePrev = e.PrevInAEL; DoMaxima(e); if (ePrev == null) e = m_ActiveEdges; else e = ePrev.NextInAEL; } else { //2. promote horizontal edges, otherwise update Curr.X and Curr.Y ... if (IsIntermediate(e, topY) && IsHorizontal(e.NextInLML)) { UpdateEdgeIntoAEL(ref e); if (e.OutIdx >= 0) AddOutPt(e, e.Bot); AddEdgeToSEL(e); } else { e.Curr.X = TopX(e, topY); e.Curr.Y = topY; #if use_xyz if (e.Top.Y == topY) e.Curr.Z = e.Top.Z; else if (e.Bot.Y == topY) e.Curr.Z = e.Bot.Z; else e.Curr.Z = 0; #endif } //When StrictlySimple and 'e' is being touched by another edge, then //make sure both edges have a vertex here ... if (StrictlySimple) { TEdge ePrev = e.PrevInAEL; if ((e.OutIdx >= 0) && (e.WindDelta != 0) && ePrev != null && (ePrev.OutIdx >= 0) && (ePrev.Curr.X == e.Curr.X) && (ePrev.WindDelta != 0)) { IntPoint ip = new IntPoint(e.Curr); #if use_xyz SetZ(ref ip, ePrev, e); #endif OutPt op = AddOutPt(ePrev, ip); OutPt op2 = AddOutPt(e, ip); AddJoin(op, op2, ip); //StrictlySimple (type-3) join } } e = e.NextInAEL; } } //3. Process horizontals at the Top of the scanbeam ... ProcessHorizontals(); m_Maxima = null; //4. Promote intermediate vertices ... e = m_ActiveEdges; while (e != null) { if (IsIntermediate(e, topY)) { OutPt op = null; if (e.OutIdx >= 0) op = AddOutPt(e, e.Top); UpdateEdgeIntoAEL(ref e); //if output polygons share an edge, they'll need joining later ... TEdge ePrev = e.PrevInAEL; TEdge eNext = e.NextInAEL; if (ePrev != null && ePrev.Curr.X == e.Bot.X && ePrev.Curr.Y == e.Bot.Y && op != null && ePrev.OutIdx >= 0 && ePrev.Curr.Y > ePrev.Top.Y && SlopesEqual(e.Curr, e.Top, ePrev.Curr, ePrev.Top, m_UseFullRange) && (e.WindDelta != 0) && (ePrev.WindDelta != 0)) { OutPt op2 = AddOutPt(ePrev, e.Bot); AddJoin(op, op2, e.Top); } else if (eNext != null && eNext.Curr.X == e.Bot.X && eNext.Curr.Y == e.Bot.Y && op != null && eNext.OutIdx >= 0 && eNext.Curr.Y > eNext.Top.Y && SlopesEqual(e.Curr, e.Top, eNext.Curr, eNext.Top, m_UseFullRange) && (e.WindDelta != 0) && (eNext.WindDelta != 0)) { OutPt op2 = AddOutPt(eNext, e.Bot); AddJoin(op, op2, e.Top); } } e = e.NextInAEL; } } //------------------------------------------------------------------------------ private void DoMaxima(TEdge e) { TEdge eMaxPair = GetMaximaPairEx(e); if (eMaxPair == null) { if (e.OutIdx >= 0) AddOutPt(e, e.Top); DeleteFromAEL(e); return; } TEdge eNext = e.NextInAEL; while (eNext != null && eNext != eMaxPair) { IntersectEdges(e, eNext, e.Top); SwapPositionsInAEL(e, eNext); eNext = e.NextInAEL; } if (e.OutIdx == Unassigned && eMaxPair.OutIdx == Unassigned) { DeleteFromAEL(e); DeleteFromAEL(eMaxPair); } else if (e.OutIdx >= 0 && eMaxPair.OutIdx >= 0) { if (e.OutIdx >= 0) AddLocalMaxPoly(e, eMaxPair, e.Top); DeleteFromAEL(e); DeleteFromAEL(eMaxPair); } #if use_lines else if (e.WindDelta == 0) { if (e.OutIdx >= 0) { AddOutPt(e, e.Top); e.OutIdx = Unassigned; } DeleteFromAEL(e); if (eMaxPair.OutIdx >= 0) { AddOutPt(eMaxPair, e.Top); eMaxPair.OutIdx = Unassigned; } DeleteFromAEL(eMaxPair); } #endif else throw new ClipperException("DoMaxima error"); } //------------------------------------------------------------------------------ public static void ReversePaths(Paths polys) { foreach (var poly in polys) { poly.Reverse(); } } //------------------------------------------------------------------------------ public static bool Orientation(Path poly) { return Area(poly) >= 0; } //------------------------------------------------------------------------------ private int PointCount(OutPt pts) { if (pts == null) return 0; int result = 0; OutPt p = pts; do { result++; p = p.Next; } while (p != pts); return result; } //------------------------------------------------------------------------------ private void BuildResult(Paths polyg) { polyg.Clear(); polyg.Capacity = m_PolyOuts.Count; for (int i = 0; i < m_PolyOuts.Count; i++) { OutRec outRec = m_PolyOuts[i]; if (outRec.Pts == null) continue; OutPt p = outRec.Pts.Prev; int cnt = PointCount(p); if (cnt < 2) continue; Path pg = new Path(cnt); for (int j = 0; j < cnt; j++) { pg.Add(p.Pt); p = p.Prev; } polyg.Add(pg); } } //------------------------------------------------------------------------------ private void BuildResult2(PolyTree polytree) { polytree.Clear(); //add each output polygon/contour to polytree ... polytree.m_AllPolys.Capacity = m_PolyOuts.Count; for (int i = 0; i < m_PolyOuts.Count; i++) { OutRec outRec = m_PolyOuts[i]; int cnt = PointCount(outRec.Pts); if ((outRec.IsOpen && cnt < 2) || (!outRec.IsOpen && cnt < 3)) continue; FixHoleLinkage(outRec); PolyNode pn = new PolyNode(); polytree.m_AllPolys.Add(pn); outRec.PolyNode = pn; pn.m_polygon.Capacity = cnt; OutPt op = outRec.Pts.Prev; for (int j = 0; j < cnt; j++) { pn.m_polygon.Add(op.Pt); op = op.Prev; } } //fixup PolyNode links etc ... polytree.m_Childs.Capacity = m_PolyOuts.Count; for (int i = 0; i < m_PolyOuts.Count; i++) { OutRec outRec = m_PolyOuts[i]; if (outRec.PolyNode == null) continue; else if (outRec.IsOpen) { outRec.PolyNode.IsOpen = true; polytree.AddChild(outRec.PolyNode); } else if (outRec.FirstLeft != null && outRec.FirstLeft.PolyNode != null) outRec.FirstLeft.PolyNode.AddChild(outRec.PolyNode); else polytree.AddChild(outRec.PolyNode); } } //------------------------------------------------------------------------------ private void FixupOutPolyline(OutRec outrec) { OutPt pp = outrec.Pts; OutPt lastPP = pp.Prev; while (pp != lastPP) { pp = pp.Next; if (pp.Pt == pp.Prev.Pt) { if (pp == lastPP) lastPP = pp.Prev; OutPt tmpPP = pp.Prev; tmpPP.Next = pp.Next; pp.Next.Prev = tmpPP; pp = tmpPP; } } if (pp == pp.Prev) outrec.Pts = null; } //------------------------------------------------------------------------------ private void FixupOutPolygon(OutRec outRec) { //FixupOutPolygon() - removes duplicate points and simplifies consecutive //parallel edges by removing the middle vertex. OutPt lastOK = null; outRec.BottomPt = null; OutPt pp = outRec.Pts; bool preserveCol = PreserveCollinear || StrictlySimple; for (;;) { if (pp.Prev == pp || pp.Prev == pp.Next) { outRec.Pts = null; return; } //test for duplicate points and collinear edges ... if ((pp.Pt == pp.Next.Pt) || (pp.Pt == pp.Prev.Pt) || (SlopesEqual(pp.Prev.Pt, pp.Pt, pp.Next.Pt, m_UseFullRange) && (!preserveCol || !Pt2IsBetweenPt1AndPt3(pp.Prev.Pt, pp.Pt, pp.Next.Pt)))) { lastOK = null; pp.Prev.Next = pp.Next; pp.Next.Prev = pp.Prev; pp = pp.Prev; } else if (pp == lastOK) break; else { if (lastOK == null) lastOK = pp; pp = pp.Next; } } outRec.Pts = pp; } //------------------------------------------------------------------------------ OutPt DupOutPt(OutPt outPt, bool InsertAfter) { OutPt result = new OutPt(); result.Pt = outPt.Pt; result.Idx = outPt.Idx; if (InsertAfter) { result.Next = outPt.Next; result.Prev = outPt; outPt.Next.Prev = result; outPt.Next = result; } else { result.Prev = outPt.Prev; result.Next = outPt; outPt.Prev.Next = result; outPt.Prev = result; } return result; } //------------------------------------------------------------------------------ bool GetOverlap(cInt a1, cInt a2, cInt b1, cInt b2, out cInt Left, out cInt Right) { if (a1 < a2) { if (b1 < b2) {Left = Math.Max(a1, b1); Right = Math.Min(a2, b2); } else {Left = Math.Max(a1, b2); Right = Math.Min(a2, b1); } } else { if (b1 < b2) {Left = Math.Max(a2, b1); Right = Math.Min(a1, b2); } else { Left = Math.Max(a2, b2); Right = Math.Min(a1, b1); } } return Left < Right; } //------------------------------------------------------------------------------ bool JoinHorz(OutPt op1, OutPt op1b, OutPt op2, OutPt op2b, IntPoint Pt, bool DiscardLeft) { Direction Dir1 = (op1.Pt.X > op1b.Pt.X ? Direction.dRightToLeft : Direction.dLeftToRight); Direction Dir2 = (op2.Pt.X > op2b.Pt.X ? Direction.dRightToLeft : Direction.dLeftToRight); if (Dir1 == Dir2) return false; //When DiscardLeft, we want Op1b to be on the Left of Op1, otherwise we //want Op1b to be on the Right. (And likewise with Op2 and Op2b.) //So, to facilitate this while inserting Op1b and Op2b ... //when DiscardLeft, make sure we're AT or RIGHT of Pt before adding Op1b, //otherwise make sure we're AT or LEFT of Pt. (Likewise with Op2b.) if (Dir1 == Direction.dLeftToRight) { while (op1.Next.Pt.X <= Pt.X && op1.Next.Pt.X >= op1.Pt.X && op1.Next.Pt.Y == Pt.Y) op1 = op1.Next; if (DiscardLeft && (op1.Pt.X != Pt.X)) op1 = op1.Next; op1b = DupOutPt(op1, !DiscardLeft); if (op1b.Pt != Pt) { op1 = op1b; op1.Pt = Pt; op1b = DupOutPt(op1, !DiscardLeft); } } else { while (op1.Next.Pt.X >= Pt.X && op1.Next.Pt.X <= op1.Pt.X && op1.Next.Pt.Y == Pt.Y) op1 = op1.Next; if (!DiscardLeft && (op1.Pt.X != Pt.X)) op1 = op1.Next; op1b = DupOutPt(op1, DiscardLeft); if (op1b.Pt != Pt) { op1 = op1b; op1.Pt = Pt; op1b = DupOutPt(op1, DiscardLeft); } } if (Dir2 == Direction.dLeftToRight) { while (op2.Next.Pt.X <= Pt.X && op2.Next.Pt.X >= op2.Pt.X && op2.Next.Pt.Y == Pt.Y) op2 = op2.Next; if (DiscardLeft && (op2.Pt.X != Pt.X)) op2 = op2.Next; op2b = DupOutPt(op2, !DiscardLeft); if (op2b.Pt != Pt) { op2 = op2b; op2.Pt = Pt; op2b = DupOutPt(op2, !DiscardLeft); } } else { while (op2.Next.Pt.X >= Pt.X && op2.Next.Pt.X <= op2.Pt.X && op2.Next.Pt.Y == Pt.Y) op2 = op2.Next; if (!DiscardLeft && (op2.Pt.X != Pt.X)) op2 = op2.Next; op2b = DupOutPt(op2, DiscardLeft); if (op2b.Pt != Pt) { op2 = op2b; op2.Pt = Pt; op2b = DupOutPt(op2, DiscardLeft); } } if ((Dir1 == Direction.dLeftToRight) == DiscardLeft) { op1.Prev = op2; op2.Next = op1; op1b.Next = op2b; op2b.Prev = op1b; } else { op1.Next = op2; op2.Prev = op1; op1b.Prev = op2b; op2b.Next = op1b; } return true; } //------------------------------------------------------------------------------ private bool JoinPoints(Join j, OutRec outRec1, OutRec outRec2) { OutPt op1 = j.OutPt1, op1b; OutPt op2 = j.OutPt2, op2b; //There are 3 kinds of joins for output polygons ... //1. Horizontal joins where Join.OutPt1 & Join.OutPt2 are vertices anywhere //along (horizontal) collinear edges (& Join.OffPt is on the same horizontal). //2. Non-horizontal joins where Join.OutPt1 & Join.OutPt2 are at the same //location at the Bottom of the overlapping segment (& Join.OffPt is above). //3. StrictlySimple joins where edges touch but are not collinear and where //Join.OutPt1, Join.OutPt2 & Join.OffPt all share the same point. bool isHorizontal = (j.OutPt1.Pt.Y == j.OffPt.Y); if (isHorizontal && (j.OffPt == j.OutPt1.Pt) && (j.OffPt == j.OutPt2.Pt)) { //Strictly Simple join ... if (outRec1 != outRec2) return false; op1b = j.OutPt1.Next; while (op1b != op1 && (op1b.Pt == j.OffPt)) op1b = op1b.Next; bool reverse1 = (op1b.Pt.Y > j.OffPt.Y); op2b = j.OutPt2.Next; while (op2b != op2 && (op2b.Pt == j.OffPt)) op2b = op2b.Next; bool reverse2 = (op2b.Pt.Y > j.OffPt.Y); if (reverse1 == reverse2) return false; if (reverse1) { op1b = DupOutPt(op1, false); op2b = DupOutPt(op2, true); op1.Prev = op2; op2.Next = op1; op1b.Next = op2b; op2b.Prev = op1b; j.OutPt1 = op1; j.OutPt2 = op1b; return true; } else { op1b = DupOutPt(op1, true); op2b = DupOutPt(op2, false); op1.Next = op2; op2.Prev = op1; op1b.Prev = op2b; op2b.Next = op1b; j.OutPt1 = op1; j.OutPt2 = op1b; return true; } } else if (isHorizontal) { //treat horizontal joins differently to non-horizontal joins since with //them we're not yet sure where the overlapping is. OutPt1.Pt & OutPt2.Pt //may be anywhere along the horizontal edge. op1b = op1; while (op1.Prev.Pt.Y == op1.Pt.Y && op1.Prev != op1b && op1.Prev != op2) op1 = op1.Prev; while (op1b.Next.Pt.Y == op1b.Pt.Y && op1b.Next != op1 && op1b.Next != op2) op1b = op1b.Next; if (op1b.Next == op1 || op1b.Next == op2) return false; //a flat 'polygon' op2b = op2; while (op2.Prev.Pt.Y == op2.Pt.Y && op2.Prev != op2b && op2.Prev != op1b) op2 = op2.Prev; while (op2b.Next.Pt.Y == op2b.Pt.Y && op2b.Next != op2 && op2b.Next != op1) op2b = op2b.Next; if (op2b.Next == op2 || op2b.Next == op1) return false; //a flat 'polygon' cInt Left, Right; //Op1 -. Op1b & Op2 -. Op2b are the extremites of the horizontal edges if (!GetOverlap(op1.Pt.X, op1b.Pt.X, op2.Pt.X, op2b.Pt.X, out Left, out Right)) return false; //DiscardLeftSide: when overlapping edges are joined, a spike will created //which needs to be cleaned up. However, we don't want Op1 or Op2 caught up //on the discard Side as either may still be needed for other joins ... IntPoint Pt; bool DiscardLeftSide; if (op1.Pt.X >= Left && op1.Pt.X <= Right) { Pt = op1.Pt; DiscardLeftSide = (op1.Pt.X > op1b.Pt.X); } else if (op2.Pt.X >= Left && op2.Pt.X <= Right) { Pt = op2.Pt; DiscardLeftSide = (op2.Pt.X > op2b.Pt.X); } else if (op1b.Pt.X >= Left && op1b.Pt.X <= Right) { Pt = op1b.Pt; DiscardLeftSide = op1b.Pt.X > op1.Pt.X; } else { Pt = op2b.Pt; DiscardLeftSide = (op2b.Pt.X > op2.Pt.X); } j.OutPt1 = op1; j.OutPt2 = op2; return JoinHorz(op1, op1b, op2, op2b, Pt, DiscardLeftSide); } else { //nb: For non-horizontal joins ... // 1. Jr.OutPt1.Pt.Y == Jr.OutPt2.Pt.Y // 2. Jr.OutPt1.Pt > Jr.OffPt.Y //make sure the polygons are correctly oriented ... op1b = op1.Next; while ((op1b.Pt == op1.Pt) && (op1b != op1)) op1b = op1b.Next; bool Reverse1 = ((op1b.Pt.Y > op1.Pt.Y) || !SlopesEqual(op1.Pt, op1b.Pt, j.OffPt, m_UseFullRange)); if (Reverse1) { op1b = op1.Prev; while ((op1b.Pt == op1.Pt) && (op1b != op1)) op1b = op1b.Prev; if ((op1b.Pt.Y > op1.Pt.Y) || !SlopesEqual(op1.Pt, op1b.Pt, j.OffPt, m_UseFullRange)) return false; } op2b = op2.Next; while ((op2b.Pt == op2.Pt) && (op2b != op2)) op2b = op2b.Next; bool Reverse2 = ((op2b.Pt.Y > op2.Pt.Y) || !SlopesEqual(op2.Pt, op2b.Pt, j.OffPt, m_UseFullRange)); if (Reverse2) { op2b = op2.Prev; while ((op2b.Pt == op2.Pt) && (op2b != op2)) op2b = op2b.Prev; if ((op2b.Pt.Y > op2.Pt.Y) || !SlopesEqual(op2.Pt, op2b.Pt, j.OffPt, m_UseFullRange)) return false; } if ((op1b == op1) || (op2b == op2) || (op1b == op2b) || ((outRec1 == outRec2) && (Reverse1 == Reverse2))) return false; if (Reverse1) { op1b = DupOutPt(op1, false); op2b = DupOutPt(op2, true); op1.Prev = op2; op2.Next = op1; op1b.Next = op2b; op2b.Prev = op1b; j.OutPt1 = op1; j.OutPt2 = op1b; return true; } else { op1b = DupOutPt(op1, true); op2b = DupOutPt(op2, false); op1.Next = op2; op2.Prev = op1; op1b.Prev = op2b; op2b.Next = op1b; j.OutPt1 = op1; j.OutPt2 = op1b; return true; } } } //---------------------------------------------------------------------- public static int PointInPolygon(IntPoint pt, Path path) { //returns 0 if false, +1 if true, -1 if pt ON polygon boundary //See "The Point in Polygon Problem for Arbitrary Polygons" by Hormann & Agathos //http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.88.5498&rep=rep1&type=pdf int result = 0, cnt = path.Count; if (cnt < 3) return 0; IntPoint ip = path[0]; for (int i = 1; i <= cnt; ++i) { IntPoint ipNext = (i == cnt ? path[0] : path[i]); if (ipNext.Y == pt.Y) { if ((ipNext.X == pt.X) || (ip.Y == pt.Y && ((ipNext.X > pt.X) == (ip.X < pt.X)))) return -1; } if ((ip.Y < pt.Y) != (ipNext.Y < pt.Y)) { if (ip.X >= pt.X) { if (ipNext.X > pt.X) result = 1 - result; else { double d = (double)(ip.X - pt.X) * (ipNext.Y - pt.Y) - (double)(ipNext.X - pt.X) * (ip.Y - pt.Y); if (d == 0) return -1; else if ((d > 0) == (ipNext.Y > ip.Y)) result = 1 - result; } } else { if (ipNext.X > pt.X) { double d = (double)(ip.X - pt.X) * (ipNext.Y - pt.Y) - (double)(ipNext.X - pt.X) * (ip.Y - pt.Y); if (d == 0) return -1; else if ((d > 0) == (ipNext.Y > ip.Y)) result = 1 - result; } } } ip = ipNext; } return result; } //------------------------------------------------------------------------------ //See "The Point in Polygon Problem for Arbitrary Polygons" by Hormann & Agathos //http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.88.5498&rep=rep1&type=pdf private static int PointInPolygon(IntPoint pt, OutPt op) { //returns 0 if false, +1 if true, -1 if pt ON polygon boundary int result = 0; OutPt startOp = op; cInt ptx = pt.X, pty = pt.Y; cInt poly0x = op.Pt.X, poly0y = op.Pt.Y; do { op = op.Next; cInt poly1x = op.Pt.X, poly1y = op.Pt.Y; if (poly1y == pty) { if ((poly1x == ptx) || (poly0y == pty && ((poly1x > ptx) == (poly0x < ptx)))) return -1; } if ((poly0y < pty) != (poly1y < pty)) { if (poly0x >= ptx) { if (poly1x > ptx) result = 1 - result; else { double d = (double)(poly0x - ptx) * (poly1y - pty) - (double)(poly1x - ptx) * (poly0y - pty); if (d == 0) return -1; if ((d > 0) == (poly1y > poly0y)) result = 1 - result; } } else { if (poly1x > ptx) { double d = (double)(poly0x - ptx) * (poly1y - pty) - (double)(poly1x - ptx) * (poly0y - pty); if (d == 0) return -1; if ((d > 0) == (poly1y > poly0y)) result = 1 - result; } } } poly0x = poly1x; poly0y = poly1y; } while (startOp != op); return result; } //------------------------------------------------------------------------------ private static bool Poly2ContainsPoly1(OutPt outPt1, OutPt outPt2) { OutPt op = outPt1; do { //nb: PointInPolygon returns 0 if false, +1 if true, -1 if pt on polygon int res = PointInPolygon(op.Pt, outPt2); if (res >= 0) return res > 0; op = op.Next; } while (op != outPt1); return true; } //---------------------------------------------------------------------- private void FixupFirstLefts1(OutRec OldOutRec, OutRec NewOutRec) { foreach (OutRec outRec in m_PolyOuts) { OutRec firstLeft = ParseFirstLeft(outRec.FirstLeft); if (outRec.Pts != null && firstLeft == OldOutRec) { if (Poly2ContainsPoly1(outRec.Pts, NewOutRec.Pts)) outRec.FirstLeft = NewOutRec; } } } //---------------------------------------------------------------------- private void FixupFirstLefts2(OutRec innerOutRec, OutRec outerOutRec) { //A polygon has split into two such that one is now the inner of the other. //It's possible that these polygons now wrap around other polygons, so check //every polygon that's also contained by OuterOutRec's FirstLeft container //(including nil) to see if they've become inner to the new inner polygon ... OutRec orfl = outerOutRec.FirstLeft; foreach (OutRec outRec in m_PolyOuts) { if (outRec.Pts == null || outRec == outerOutRec || outRec == innerOutRec) continue; OutRec firstLeft = ParseFirstLeft(outRec.FirstLeft); if (firstLeft != orfl && firstLeft != innerOutRec && firstLeft != outerOutRec) continue; if (Poly2ContainsPoly1(outRec.Pts, innerOutRec.Pts)) outRec.FirstLeft = innerOutRec; else if (Poly2ContainsPoly1(outRec.Pts, outerOutRec.Pts)) outRec.FirstLeft = outerOutRec; else if (outRec.FirstLeft == innerOutRec || outRec.FirstLeft == outerOutRec) outRec.FirstLeft = orfl; } } //---------------------------------------------------------------------- private void FixupFirstLefts3(OutRec OldOutRec, OutRec NewOutRec) { //same as FixupFirstLefts1 but doesn't call Poly2ContainsPoly1() foreach (OutRec outRec in m_PolyOuts) { OutRec firstLeft = ParseFirstLeft(outRec.FirstLeft); if (outRec.Pts != null && firstLeft == OldOutRec) outRec.FirstLeft = NewOutRec; } } //---------------------------------------------------------------------- private static OutRec ParseFirstLeft(OutRec FirstLeft) { while (FirstLeft != null && FirstLeft.Pts == null) FirstLeft = FirstLeft.FirstLeft; return FirstLeft; } //------------------------------------------------------------------------------ private void JoinCommonEdges() { for (int i = 0; i < m_Joins.Count; i++) { Join join = m_Joins[i]; OutRec outRec1 = GetOutRec(join.OutPt1.Idx); OutRec outRec2 = GetOutRec(join.OutPt2.Idx); if (outRec1.Pts == null || outRec2.Pts == null) continue; if (outRec1.IsOpen || outRec2.IsOpen) continue; //get the polygon fragment with the correct hole state (FirstLeft) //before calling JoinPoints() ... OutRec holeStateRec; if (outRec1 == outRec2) holeStateRec = outRec1; else if (OutRec1RightOfOutRec2(outRec1, outRec2)) holeStateRec = outRec2; else if (OutRec1RightOfOutRec2(outRec2, outRec1)) holeStateRec = outRec1; else holeStateRec = GetLowermostRec(outRec1, outRec2); if (!JoinPoints(join, outRec1, outRec2)) continue; if (outRec1 == outRec2) { //instead of joining two polygons, we've just created a new one by //splitting one polygon into two. outRec1.Pts = join.OutPt1; outRec1.BottomPt = null; outRec2 = CreateOutRec(); outRec2.Pts = join.OutPt2; //update all OutRec2.Pts Idx's ... UpdateOutPtIdxs(outRec2); if (Poly2ContainsPoly1(outRec2.Pts, outRec1.Pts)) { //outRec1 contains outRec2 ... outRec2.IsHole = !outRec1.IsHole; outRec2.FirstLeft = outRec1; if (m_UsingPolyTree) FixupFirstLefts2(outRec2, outRec1); if ((outRec2.IsHole ^ ReverseSolution) == (Area(outRec2) > 0)) ReversePolyPtLinks(outRec2.Pts); } else if (Poly2ContainsPoly1(outRec1.Pts, outRec2.Pts)) { //outRec2 contains outRec1 ... outRec2.IsHole = outRec1.IsHole; outRec1.IsHole = !outRec2.IsHole; outRec2.FirstLeft = outRec1.FirstLeft; outRec1.FirstLeft = outRec2; if (m_UsingPolyTree) FixupFirstLefts2(outRec1, outRec2); if ((outRec1.IsHole ^ ReverseSolution) == (Area(outRec1) > 0)) ReversePolyPtLinks(outRec1.Pts); } else { //the 2 polygons are completely separate ... outRec2.IsHole = outRec1.IsHole; outRec2.FirstLeft = outRec1.FirstLeft; //fixup FirstLeft pointers that may need reassigning to OutRec2 if (m_UsingPolyTree) FixupFirstLefts1(outRec1, outRec2); } } else { //joined 2 polygons together ... outRec2.Pts = null; outRec2.BottomPt = null; outRec2.Idx = outRec1.Idx; outRec1.IsHole = holeStateRec.IsHole; if (holeStateRec == outRec2) outRec1.FirstLeft = outRec2.FirstLeft; outRec2.FirstLeft = outRec1; //fixup FirstLeft pointers that may need reassigning to OutRec1 if (m_UsingPolyTree) FixupFirstLefts3(outRec2, outRec1); } } } //------------------------------------------------------------------------------ private void UpdateOutPtIdxs(OutRec outrec) { OutPt op = outrec.Pts; do { op.Idx = outrec.Idx; op = op.Prev; } while (op != outrec.Pts); } //------------------------------------------------------------------------------ private void DoSimplePolygons() { int i = 0; while (i < m_PolyOuts.Count) { OutRec outrec = m_PolyOuts[i++]; OutPt op = outrec.Pts; if (op == null || outrec.IsOpen) continue; do //for each Pt in Polygon until duplicate found do ... { OutPt op2 = op.Next; while (op2 != outrec.Pts) { if ((op.Pt == op2.Pt) && op2.Next != op && op2.Prev != op) { //split the polygon into two ... OutPt op3 = op.Prev; OutPt op4 = op2.Prev; op.Prev = op4; op4.Next = op; op2.Prev = op3; op3.Next = op2; outrec.Pts = op; OutRec outrec2 = CreateOutRec(); outrec2.Pts = op2; UpdateOutPtIdxs(outrec2); if (Poly2ContainsPoly1(outrec2.Pts, outrec.Pts)) { //OutRec2 is contained by OutRec1 ... outrec2.IsHole = !outrec.IsHole; outrec2.FirstLeft = outrec; if (m_UsingPolyTree) FixupFirstLefts2(outrec2, outrec); } else if (Poly2ContainsPoly1(outrec.Pts, outrec2.Pts)) { //OutRec1 is contained by OutRec2 ... outrec2.IsHole = outrec.IsHole; outrec.IsHole = !outrec2.IsHole; outrec2.FirstLeft = outrec.FirstLeft; outrec.FirstLeft = outrec2; if (m_UsingPolyTree) FixupFirstLefts2(outrec, outrec2); } else { //the 2 polygons are separate ... outrec2.IsHole = outrec.IsHole; outrec2.FirstLeft = outrec.FirstLeft; if (m_UsingPolyTree) FixupFirstLefts1(outrec, outrec2); } op2 = op; //ie get ready for the next iteration } op2 = op2.Next; } op = op.Next; } while (op != outrec.Pts); } } //------------------------------------------------------------------------------ public static double Area(Path poly) { int cnt = (int)poly.Count; if (cnt < 3) return 0; double a = 0; for (int i = 0, j = cnt - 1; i < cnt; ++i) { a += ((double)poly[j].X + poly[i].X) * ((double)poly[j].Y - poly[i].Y); j = i; } return -a * 0.5; } //------------------------------------------------------------------------------ internal double Area(OutRec outRec) { return Area(outRec.Pts); } //------------------------------------------------------------------------------ internal double Area(OutPt op) { OutPt opFirst = op; if (op == null) return 0; double a = 0; do { a = a + (double)(op.Prev.Pt.X + op.Pt.X) * (double)(op.Prev.Pt.Y - op.Pt.Y); op = op.Next; } while (op != opFirst); return a * 0.5; } //------------------------------------------------------------------------------ // SimplifyPolygon functions ... // Convert self-intersecting polygons into simple polygons //------------------------------------------------------------------------------ public static Paths SimplifyPolygon(Path poly, PolyFillType fillType = PolyFillType.pftEvenOdd) { Paths result = new Paths(); Clipper c = new Clipper(); c.StrictlySimple = true; c.AddPath(poly, PolyType.ptSubject, true); c.Execute(ClipType.ctUnion, result, fillType, fillType); return result; } //------------------------------------------------------------------------------ public static Paths SimplifyPolygons(Paths polys, PolyFillType fillType = PolyFillType.pftEvenOdd) { Paths result = new Paths(); Clipper c = new Clipper(); c.StrictlySimple = true; c.AddPaths(polys, PolyType.ptSubject, true); c.Execute(ClipType.ctUnion, result, fillType, fillType); return result; } //------------------------------------------------------------------------------ private static double DistanceSqrd(IntPoint pt1, IntPoint pt2) { double dx = ((double)pt1.X - pt2.X); double dy = ((double)pt1.Y - pt2.Y); return (dx * dx + dy * dy); } //------------------------------------------------------------------------------ private static double DistanceFromLineSqrd(IntPoint pt, IntPoint ln1, IntPoint ln2) { //The equation of a line in general form (Ax + By + C = 0) //given 2 points (x¹,y¹) & (x²,y²) is ... //(y¹ - y²)x + (x² - x¹)y + (y² - y¹)x¹ - (x² - x¹)y¹ = 0 //A = (y¹ - y²); B = (x² - x¹); C = (y² - y¹)x¹ - (x² - x¹)y¹ //perpendicular distance of point (x³,y³) = (Ax³ + By³ + C)/Sqrt(A² + B²) //see http://en.wikipedia.org/wiki/Perpendicular_distance double A = ln1.Y - ln2.Y; double B = ln2.X - ln1.X; double C = A * ln1.X + B * ln1.Y; C = A * pt.X + B * pt.Y - C; return (C * C) / (A * A + B * B); } //--------------------------------------------------------------------------- private static bool SlopesNearCollinear(IntPoint pt1, IntPoint pt2, IntPoint pt3, double distSqrd) { //this function is more accurate when the point that's GEOMETRICALLY //between the other 2 points is the one that's tested for distance. //nb: with 'spikes', either pt1 or pt3 is geometrically between the other pts if (Math.Abs(pt1.X - pt2.X) > Math.Abs(pt1.Y - pt2.Y)) { if ((pt1.X > pt2.X) == (pt1.X < pt3.X)) return DistanceFromLineSqrd(pt1, pt2, pt3) < distSqrd; else if ((pt2.X > pt1.X) == (pt2.X < pt3.X)) return DistanceFromLineSqrd(pt2, pt1, pt3) < distSqrd; else return DistanceFromLineSqrd(pt3, pt1, pt2) < distSqrd; } else { if ((pt1.Y > pt2.Y) == (pt1.Y < pt3.Y)) return DistanceFromLineSqrd(pt1, pt2, pt3) < distSqrd; else if ((pt2.Y > pt1.Y) == (pt2.Y < pt3.Y)) return DistanceFromLineSqrd(pt2, pt1, pt3) < distSqrd; else return DistanceFromLineSqrd(pt3, pt1, pt2) < distSqrd; } } //------------------------------------------------------------------------------ private static bool PointsAreClose(IntPoint pt1, IntPoint pt2, double distSqrd) { double dx = (double)pt1.X - pt2.X; double dy = (double)pt1.Y - pt2.Y; return ((dx * dx) + (dy * dy) <= distSqrd); } //------------------------------------------------------------------------------ private static OutPt ExcludeOp(OutPt op) { OutPt result = op.Prev; result.Next = op.Next; op.Next.Prev = result; result.Idx = 0; return result; } //------------------------------------------------------------------------------ public static Path CleanPolygon(Path path, double distance = 1.415) { //distance = proximity in units/pixels below which vertices will be stripped. //Default ~= sqrt(2) so when adjacent vertices or semi-adjacent vertices have //both x & y coords within 1 unit, then the second vertex will be stripped. int cnt = path.Count; if (cnt == 0) return new Path(); OutPt[] outPts = new OutPt[cnt]; for (int i = 0; i < cnt; ++i) outPts[i] = new OutPt(); for (int i = 0; i < cnt; ++i) { outPts[i].Pt = path[i]; outPts[i].Next = outPts[(i + 1) % cnt]; outPts[i].Next.Prev = outPts[i]; outPts[i].Idx = 0; } double distSqrd = distance * distance; OutPt op = outPts[0]; while (op.Idx == 0 && op.Next != op.Prev) { if (PointsAreClose(op.Pt, op.Prev.Pt, distSqrd)) { op = ExcludeOp(op); cnt--; } else if (PointsAreClose(op.Prev.Pt, op.Next.Pt, distSqrd)) { ExcludeOp(op.Next); op = ExcludeOp(op); cnt -= 2; } else if (SlopesNearCollinear(op.Prev.Pt, op.Pt, op.Next.Pt, distSqrd)) { op = ExcludeOp(op); cnt--; } else { op.Idx = 1; op = op.Next; } } if (cnt < 3) cnt = 0; Path result = new Path(cnt); for (int i = 0; i < cnt; ++i) { result.Add(op.Pt); op = op.Next; } outPts = null; return result; } //------------------------------------------------------------------------------ public static Paths CleanPolygons(Paths polys, double distance = 1.415) { Paths result = new Paths(polys.Count); for (int i = 0; i < polys.Count; i++) result.Add(CleanPolygon(polys[i], distance)); return result; } //------------------------------------------------------------------------------ internal static Paths Minkowski(Path pattern, Path path, bool IsSum, bool IsClosed) { int delta = (IsClosed ? 1 : 0); int polyCnt = pattern.Count; int pathCnt = path.Count; Paths result = new Paths(pathCnt); if (IsSum) for (int i = 0; i < pathCnt; i++) { Path p = new Path(polyCnt); foreach (IntPoint ip in pattern) p.Add(new IntPoint(path[i].X + ip.X, path[i].Y + ip.Y)); result.Add(p); } else for (int i = 0; i < pathCnt; i++) { Path p = new Path(polyCnt); foreach (IntPoint ip in pattern) p.Add(new IntPoint(path[i].X - ip.X, path[i].Y - ip.Y)); result.Add(p); } Paths quads = new Paths((pathCnt + delta) * (polyCnt + 1)); for (int i = 0; i < pathCnt - 1 + delta; i++) for (int j = 0; j < polyCnt; j++) { Path quad = new Path(4); quad.Add(result[i % pathCnt][j % polyCnt]); quad.Add(result[(i + 1) % pathCnt][j % polyCnt]); quad.Add(result[(i + 1) % pathCnt][(j + 1) % polyCnt]); quad.Add(result[i % pathCnt][(j + 1) % polyCnt]); if (!Orientation(quad)) quad.Reverse(); quads.Add(quad); } return quads; } //------------------------------------------------------------------------------ public static Paths MinkowskiSum(Path pattern, Path path, bool pathIsClosed) { Paths paths = Minkowski(pattern, path, true, pathIsClosed); Clipper c = new Clipper(); c.AddPaths(paths, PolyType.ptSubject, true); c.Execute(ClipType.ctUnion, paths, PolyFillType.pftNonZero, PolyFillType.pftNonZero); return paths; } //------------------------------------------------------------------------------ private static Path TranslatePath(Path path, IntPoint delta) { Path outPath = new Path(path.Count); for (int i = 0; i < path.Count; i++) outPath.Add(new IntPoint(path[i].X + delta.X, path[i].Y + delta.Y)); return outPath; } //------------------------------------------------------------------------------ public static Paths MinkowskiSum(Path pattern, Paths paths, bool pathIsClosed) { Paths solution = new Paths(); Clipper c = new Clipper(); for (int i = 0; i < paths.Count; ++i) { Paths tmp = Minkowski(pattern, paths[i], true, pathIsClosed); c.AddPaths(tmp, PolyType.ptSubject, true); if (pathIsClosed) { Path path = TranslatePath(paths[i], pattern[0]); c.AddPath(path, PolyType.ptClip, true); } } c.Execute(ClipType.ctUnion, solution, PolyFillType.pftNonZero, PolyFillType.pftNonZero); return solution; } //------------------------------------------------------------------------------ public static Paths MinkowskiDiff(Path poly1, Path poly2) { Paths paths = Minkowski(poly1, poly2, false, true); Clipper c = new Clipper(); c.AddPaths(paths, PolyType.ptSubject, true); c.Execute(ClipType.ctUnion, paths, PolyFillType.pftNonZero, PolyFillType.pftNonZero); return paths; } //------------------------------------------------------------------------------ internal enum NodeType { ntAny, ntOpen, ntClosed }; public static Paths PolyTreeToPaths(PolyTree polytree) { Paths result = new Paths(); result.Capacity = polytree.Total; AddPolyNodeToPaths(polytree, NodeType.ntAny, result); return result; } //------------------------------------------------------------------------------ internal static void AddPolyNodeToPaths(PolyNode polynode, NodeType nt, Paths paths) { bool match = true; switch (nt) { case NodeType.ntOpen: return; case NodeType.ntClosed: match = !polynode.IsOpen; break; default: break; } if (polynode.m_polygon.Count > 0 && match) paths.Add(polynode.m_polygon); foreach (PolyNode pn in polynode.Childs) AddPolyNodeToPaths(pn, nt, paths); } //------------------------------------------------------------------------------ public static Paths OpenPathsFromPolyTree(PolyTree polytree) { Paths result = new Paths(); result.Capacity = polytree.ChildCount; for (int i = 0; i < polytree.ChildCount; i++) if (polytree.Childs[i].IsOpen) result.Add(polytree.Childs[i].m_polygon); return result; } //------------------------------------------------------------------------------ public static Paths ClosedPathsFromPolyTree(PolyTree polytree) { Paths result = new Paths(); result.Capacity = polytree.Total; AddPolyNodeToPaths(polytree, NodeType.ntClosed, result); return result; } //------------------------------------------------------------------------------ } //end Clipper public class ClipperOffset { private Paths m_destPolys; private Path m_srcPoly; private Path m_destPoly; private List<DoublePoint> m_normals = new List<DoublePoint>(); private double m_delta, m_sinA, m_sin, m_cos; private double m_miterLim, m_StepsPerRad; private IntPoint m_lowest; private PolyNode m_polyNodes = new PolyNode(); public double ArcTolerance { get; set; } public double MiterLimit { get; set; } private const double two_pi = Math.PI * 2; private const double def_arc_tolerance = 0.25; public ClipperOffset( double miterLimit = 2.0, double arcTolerance = def_arc_tolerance) { MiterLimit = miterLimit; ArcTolerance = arcTolerance; m_lowest.X = -1; } //------------------------------------------------------------------------------ public void Clear() { m_polyNodes.Childs.Clear(); m_lowest.X = -1; } //------------------------------------------------------------------------------ internal static cInt Round(double value) { return value < 0 ? (cInt)(value - 0.5) : (cInt)(value + 0.5); } //------------------------------------------------------------------------------ public void AddPath(Path path, JoinType joinType, EndType endType) { int highI = path.Count - 1; if (highI < 0) return; PolyNode newNode = new PolyNode(); newNode.m_jointype = joinType; newNode.m_endtype = endType; //strip duplicate points from path and also get index to the lowest point ... if (endType == EndType.etClosedLine || endType == EndType.etClosedPolygon) while (highI > 0 && path[0] == path[highI]) highI--; newNode.m_polygon.Capacity = highI + 1; newNode.m_polygon.Add(path[0]); int j = 0, k = 0; for (int i = 1; i <= highI; i++) if (newNode.m_polygon[j] != path[i]) { j++; newNode.m_polygon.Add(path[i]); if (path[i].Y > newNode.m_polygon[k].Y || (path[i].Y == newNode.m_polygon[k].Y && path[i].X < newNode.m_polygon[k].X)) k = j; } if (endType == EndType.etClosedPolygon && j < 2) return; m_polyNodes.AddChild(newNode); //if this path's lowest pt is lower than all the others then update m_lowest if (endType != EndType.etClosedPolygon) return; if (m_lowest.X < 0) m_lowest = new IntPoint(m_polyNodes.ChildCount - 1, k); else { IntPoint ip = m_polyNodes.Childs[(int)m_lowest.X].m_polygon[(int)m_lowest.Y]; if (newNode.m_polygon[k].Y > ip.Y || (newNode.m_polygon[k].Y == ip.Y && newNode.m_polygon[k].X < ip.X)) m_lowest = new IntPoint(m_polyNodes.ChildCount - 1, k); } } //------------------------------------------------------------------------------ public void AddPaths(Paths paths, JoinType joinType, EndType endType) { foreach (Path p in paths) AddPath(p, joinType, endType); } //------------------------------------------------------------------------------ private void FixOrientations() { //fixup orientations of all closed paths if the orientation of the //closed path with the lowermost vertex is wrong ... if (m_lowest.X >= 0 && !Clipper.Orientation(m_polyNodes.Childs[(int)m_lowest.X].m_polygon)) { for (int i = 0; i < m_polyNodes.ChildCount; i++) { PolyNode node = m_polyNodes.Childs[i]; if (node.m_endtype == EndType.etClosedPolygon || (node.m_endtype == EndType.etClosedLine && Clipper.Orientation(node.m_polygon))) node.m_polygon.Reverse(); } } else { for (int i = 0; i < m_polyNodes.ChildCount; i++) { PolyNode node = m_polyNodes.Childs[i]; if (node.m_endtype == EndType.etClosedLine && !Clipper.Orientation(node.m_polygon)) node.m_polygon.Reverse(); } } } //------------------------------------------------------------------------------ internal static DoublePoint GetUnitNormal(IntPoint pt1, IntPoint pt2) { double dx = (pt2.X - pt1.X); double dy = (pt2.Y - pt1.Y); if ((dx == 0) && (dy == 0)) return new DoublePoint(); double f = 1 * 1.0 / Math.Sqrt(dx * dx + dy * dy); dx *= f; dy *= f; return new DoublePoint(dy, -dx); } //------------------------------------------------------------------------------ private void DoOffset(double delta) { m_destPolys = new Paths(); m_delta = delta; //if Zero offset, just copy any CLOSED polygons to m_p and return ... if (ClipperBase.near_zero(delta)) { m_destPolys.Capacity = m_polyNodes.ChildCount; for (int i = 0; i < m_polyNodes.ChildCount; i++) { PolyNode node = m_polyNodes.Childs[i]; if (node.m_endtype == EndType.etClosedPolygon) m_destPolys.Add(node.m_polygon); } return; } //see offset_triginometry3.svg in the documentation folder ... if (MiterLimit > 2) m_miterLim = 2 / (MiterLimit * MiterLimit); else m_miterLim = 0.5; double y; if (ArcTolerance <= 0.0) y = def_arc_tolerance; else if (ArcTolerance > Math.Abs(delta) * def_arc_tolerance) y = Math.Abs(delta) * def_arc_tolerance; else y = ArcTolerance; //see offset_triginometry2.svg in the documentation folder ... double steps = Math.PI / Math.Acos(1 - y / Math.Abs(delta)); m_sin = Math.Sin(two_pi / steps); m_cos = Math.Cos(two_pi / steps); m_StepsPerRad = steps / two_pi; if (delta < 0.0) m_sin = -m_sin; m_destPolys.Capacity = m_polyNodes.ChildCount * 2; for (int i = 0; i < m_polyNodes.ChildCount; i++) { PolyNode node = m_polyNodes.Childs[i]; m_srcPoly = node.m_polygon; int len = m_srcPoly.Count; if (len == 0 || (delta <= 0 && (len < 3 || node.m_endtype != EndType.etClosedPolygon))) continue; m_destPoly = new Path(); if (len == 1) { if (node.m_jointype == JoinType.jtRound) { double X = 1.0, Y = 0.0; for (int j = 1; j <= steps; j++) { m_destPoly.Add(new IntPoint( Round(m_srcPoly[0].X + X * delta), Round(m_srcPoly[0].Y + Y * delta))); double X2 = X; X = X * m_cos - m_sin * Y; Y = X2 * m_sin + Y * m_cos; } } else { double X = -1.0, Y = -1.0; for (int j = 0; j < 4; ++j) { m_destPoly.Add(new IntPoint( Round(m_srcPoly[0].X + X * delta), Round(m_srcPoly[0].Y + Y * delta))); if (X < 0) X = 1; else if (Y < 0) Y = 1; else X = -1; } } m_destPolys.Add(m_destPoly); continue; } //build m_normals ... m_normals.Clear(); m_normals.Capacity = len; for (int j = 0; j < len - 1; j++) m_normals.Add(GetUnitNormal(m_srcPoly[j], m_srcPoly[j + 1])); if (node.m_endtype == EndType.etClosedLine || node.m_endtype == EndType.etClosedPolygon) m_normals.Add(GetUnitNormal(m_srcPoly[len - 1], m_srcPoly[0])); else m_normals.Add(new DoublePoint(m_normals[len - 2])); if (node.m_endtype == EndType.etClosedPolygon) { int k = len - 1; for (int j = 0; j < len; j++) OffsetPoint(j, ref k, node.m_jointype); m_destPolys.Add(m_destPoly); } else if (node.m_endtype == EndType.etClosedLine) { int k = len - 1; for (int j = 0; j < len; j++) OffsetPoint(j, ref k, node.m_jointype); m_destPolys.Add(m_destPoly); m_destPoly = new Path(); //re-build m_normals ... DoublePoint n = m_normals[len - 1]; for (int j = len - 1; j > 0; j--) m_normals[j] = new DoublePoint(-m_normals[j - 1].X, -m_normals[j - 1].Y); m_normals[0] = new DoublePoint(-n.X, -n.Y); k = 0; for (int j = len - 1; j >= 0; j--) OffsetPoint(j, ref k, node.m_jointype); m_destPolys.Add(m_destPoly); } else { int k = 0; for (int j = 1; j < len - 1; ++j) OffsetPoint(j, ref k, node.m_jointype); IntPoint pt1; if (node.m_endtype == EndType.etOpenButt) { int j = len - 1; pt1 = new IntPoint((cInt)Round(m_srcPoly[j].X + m_normals[j].X * delta), (cInt)Round(m_srcPoly[j].Y + m_normals[j].Y * delta)); m_destPoly.Add(pt1); pt1 = new IntPoint((cInt)Round(m_srcPoly[j].X - m_normals[j].X * delta), (cInt)Round(m_srcPoly[j].Y - m_normals[j].Y * delta)); m_destPoly.Add(pt1); } else { int j = len - 1; k = len - 2; m_sinA = 0; m_normals[j] = new DoublePoint(-m_normals[j].X, -m_normals[j].Y); if (node.m_endtype == EndType.etOpenSquare) DoSquare(j, k); else DoRound(j, k); } //re-build m_normals ... for (int j = len - 1; j > 0; j--) m_normals[j] = new DoublePoint(-m_normals[j - 1].X, -m_normals[j - 1].Y); m_normals[0] = new DoublePoint(-m_normals[1].X, -m_normals[1].Y); k = len - 1; for (int j = k - 1; j > 0; --j) OffsetPoint(j, ref k, node.m_jointype); if (node.m_endtype == EndType.etOpenButt) { pt1 = new IntPoint((cInt)Round(m_srcPoly[0].X - m_normals[0].X * delta), (cInt)Round(m_srcPoly[0].Y - m_normals[0].Y * delta)); m_destPoly.Add(pt1); pt1 = new IntPoint((cInt)Round(m_srcPoly[0].X + m_normals[0].X * delta), (cInt)Round(m_srcPoly[0].Y + m_normals[0].Y * delta)); m_destPoly.Add(pt1); } else { k = 1; m_sinA = 0; if (node.m_endtype == EndType.etOpenSquare) DoSquare(0, 1); else DoRound(0, 1); } m_destPolys.Add(m_destPoly); } } } //------------------------------------------------------------------------------ public void Execute(ref Paths solution, double delta) { solution.Clear(); FixOrientations(); DoOffset(delta); //now clean up 'corners' ... Clipper clpr = new Clipper(); clpr.AddPaths(m_destPolys, PolyType.ptSubject, true); if (delta > 0) { clpr.Execute(ClipType.ctUnion, solution, PolyFillType.pftPositive, PolyFillType.pftPositive); } else { IntRect r = Clipper.GetBounds(m_destPolys); Path outer = new Path(4); outer.Add(new IntPoint(r.left - 10, r.bottom + 10)); outer.Add(new IntPoint(r.right + 10, r.bottom + 10)); outer.Add(new IntPoint(r.right + 10, r.top - 10)); outer.Add(new IntPoint(r.left - 10, r.top - 10)); clpr.AddPath(outer, PolyType.ptSubject, true); clpr.ReverseSolution = true; clpr.Execute(ClipType.ctUnion, solution, PolyFillType.pftNegative, PolyFillType.pftNegative); if (solution.Count > 0) solution.RemoveAt(0); } } //------------------------------------------------------------------------------ public void Execute(ref PolyTree solution, double delta) { solution.Clear(); FixOrientations(); DoOffset(delta); //now clean up 'corners' ... Clipper clpr = new Clipper(); clpr.AddPaths(m_destPolys, PolyType.ptSubject, true); if (delta > 0) { clpr.Execute(ClipType.ctUnion, solution, PolyFillType.pftPositive, PolyFillType.pftPositive); } else { IntRect r = Clipper.GetBounds(m_destPolys); Path outer = new Path(4); outer.Add(new IntPoint(r.left - 10, r.bottom + 10)); outer.Add(new IntPoint(r.right + 10, r.bottom + 10)); outer.Add(new IntPoint(r.right + 10, r.top - 10)); outer.Add(new IntPoint(r.left - 10, r.top - 10)); clpr.AddPath(outer, PolyType.ptSubject, true); clpr.ReverseSolution = true; clpr.Execute(ClipType.ctUnion, solution, PolyFillType.pftNegative, PolyFillType.pftNegative); //remove the outer PolyNode rectangle ... if (solution.ChildCount == 1 && solution.Childs[0].ChildCount > 0) { PolyNode outerNode = solution.Childs[0]; solution.Childs.Capacity = outerNode.ChildCount; solution.Childs[0] = outerNode.Childs[0]; solution.Childs[0].m_Parent = solution; for (int i = 1; i < outerNode.ChildCount; i++) solution.AddChild(outerNode.Childs[i]); } else solution.Clear(); } } //------------------------------------------------------------------------------ void OffsetPoint(int j, ref int k, JoinType jointype) { //cross product ... m_sinA = (m_normals[k].X * m_normals[j].Y - m_normals[j].X * m_normals[k].Y); if (Math.Abs(m_sinA * m_delta) < 1.0) { //dot product ... double cosA = (m_normals[k].X * m_normals[j].X + m_normals[j].Y * m_normals[k].Y); if (cosA > 0) // angle ==> 0 degrees { m_destPoly.Add(new IntPoint(Round(m_srcPoly[j].X + m_normals[k].X * m_delta), Round(m_srcPoly[j].Y + m_normals[k].Y * m_delta))); return; } //else angle ==> 180 degrees } else if (m_sinA > 1.0) m_sinA = 1.0; else if (m_sinA < -1.0) m_sinA = -1.0; if (m_sinA * m_delta < 0) { m_destPoly.Add(new IntPoint(Round(m_srcPoly[j].X + m_normals[k].X * m_delta), Round(m_srcPoly[j].Y + m_normals[k].Y * m_delta))); m_destPoly.Add(m_srcPoly[j]); m_destPoly.Add(new IntPoint(Round(m_srcPoly[j].X + m_normals[j].X * m_delta), Round(m_srcPoly[j].Y + m_normals[j].Y * m_delta))); } else switch (jointype) { case JoinType.jtMiter: { double r = 1 + (m_normals[j].X * m_normals[k].X + m_normals[j].Y * m_normals[k].Y); if (r >= m_miterLim) DoMiter(j, k, r); else DoSquare(j, k); break; } case JoinType.jtSquare: DoSquare(j, k); break; case JoinType.jtRound: DoRound(j, k); break; } k = j; } //------------------------------------------------------------------------------ internal void DoSquare(int j, int k) { double dx = Math.Tan(Math.Atan2(m_sinA, m_normals[k].X * m_normals[j].X + m_normals[k].Y * m_normals[j].Y) / 4); m_destPoly.Add(new IntPoint( Round(m_srcPoly[j].X + m_delta * (m_normals[k].X - m_normals[k].Y * dx)), Round(m_srcPoly[j].Y + m_delta * (m_normals[k].Y + m_normals[k].X * dx)))); m_destPoly.Add(new IntPoint( Round(m_srcPoly[j].X + m_delta * (m_normals[j].X + m_normals[j].Y * dx)), Round(m_srcPoly[j].Y + m_delta * (m_normals[j].Y - m_normals[j].X * dx)))); } //------------------------------------------------------------------------------ internal void DoMiter(int j, int k, double r) { double q = m_delta / r; m_destPoly.Add(new IntPoint(Round(m_srcPoly[j].X + (m_normals[k].X + m_normals[j].X) * q), Round(m_srcPoly[j].Y + (m_normals[k].Y + m_normals[j].Y) * q))); } //------------------------------------------------------------------------------ internal void DoRound(int j, int k) { double a = Math.Atan2(m_sinA, m_normals[k].X * m_normals[j].X + m_normals[k].Y * m_normals[j].Y); int steps = Math.Max((int)Round(m_StepsPerRad * Math.Abs(a)), 1); double X = m_normals[k].X, Y = m_normals[k].Y, X2; for (int i = 0; i < steps; ++i) { m_destPoly.Add(new IntPoint( Round(m_srcPoly[j].X + X * m_delta), Round(m_srcPoly[j].Y + Y * m_delta))); X2 = X; X = X * m_cos - m_sin * Y; Y = X2 * m_sin + Y * m_cos; } m_destPoly.Add(new IntPoint( Round(m_srcPoly[j].X + m_normals[j].X * m_delta), Round(m_srcPoly[j].Y + m_normals[j].Y * m_delta))); } //------------------------------------------------------------------------------ } class ClipperException : Exception { public ClipperException(string description) : base(description) {} } //------------------------------------------------------------------------------ } //end ClipperLib namespace
37.657019
117
0.405035
[ "MIT" ]
AI3SW/ai_job_teacher_unity
AiJobTeacherUnity/Library/PackageCache/[email protected]/Samples~/Extras/Scripts/Clipper.cs
191,322
C#
using RimWorld; using Verse; namespace Ice { [DefOf] public class DesignationCategories { public static DesignationCategoryDef Orders; } }
12.166667
46
0.767123
[ "MIT" ]
OgamLab/Rimedieval-Ice-add-on
1.3/Source/Ice/DesignationCategories.cs
146
C#
using Encountify.Views; using System; using Xamarin.Forms; namespace Encountify { public partial class AdminShell : Shell { public AdminShell() { InitializeComponent(); Routing.RegisterRoute("LocationDetailPage", typeof(LocationDetailPage)); Routing.RegisterRoute("NewLocationPage", typeof(NewLocationPage)); Routing.RegisterRoute("MapPage", typeof(MapPage)); Routing.RegisterRoute("LocationsNearUserPage", typeof(LocationsNearUserPage)); Routing.RegisterRoute("NewLocationMapPage", typeof(NewLocationMapPage)); Routing.RegisterRoute("NewPostPage", typeof(NewPostPage)); } private async void OnMenuItemClicked(object sender, EventArgs e) { await DisplayAlert("Quit", "You want to log out?", "Yes"); await Shell.Current.GoToAsync("//LoginPage"); } } }
34.148148
90
0.650759
[ "MIT" ]
medikornov/Encountify
Encountify/AdminShell.xaml.cs
924
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: EntityRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type OrganizationalBrandingRequest. /// </summary> public partial class OrganizationalBrandingRequest : BaseRequest, IOrganizationalBrandingRequest { /// <summary> /// Constructs a new OrganizationalBrandingRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public OrganizationalBrandingRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Creates the specified OrganizationalBranding using POST. /// </summary> /// <param name="organizationalBrandingToCreate">The OrganizationalBranding to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created OrganizationalBranding.</returns> public async System.Threading.Tasks.Task<OrganizationalBranding> CreateAsync(OrganizationalBranding organizationalBrandingToCreate, CancellationToken cancellationToken = default) { this.ContentType = CoreConstants.MimeTypeNames.Application.Json; this.Method = HttpMethods.POST; var newEntity = await this.SendAsync<OrganizationalBranding>(organizationalBrandingToCreate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(newEntity); return newEntity; } /// <summary> /// Creates the specified OrganizationalBranding using POST and returns a <see cref="GraphResponse{OrganizationalBranding}"/> object. /// </summary> /// <param name="organizationalBrandingToCreate">The OrganizationalBranding to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The <see cref="GraphResponse{OrganizationalBranding}"/> object of the request.</returns> public System.Threading.Tasks.Task<GraphResponse<OrganizationalBranding>> CreateResponseAsync(OrganizationalBranding organizationalBrandingToCreate, CancellationToken cancellationToken = default) { this.ContentType = CoreConstants.MimeTypeNames.Application.Json; this.Method = HttpMethods.POST; return this.SendAsyncWithGraphResponse<OrganizationalBranding>(organizationalBrandingToCreate, cancellationToken); } /// <summary> /// Deletes the specified OrganizationalBranding. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await.</returns> public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken = default) { this.Method = HttpMethods.DELETE; await this.SendAsync<OrganizationalBranding>(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Deletes the specified OrganizationalBranding and returns a <see cref="GraphResponse"/> object. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task of <see cref="GraphResponse"/> to await.</returns> public System.Threading.Tasks.Task<GraphResponse> DeleteResponseAsync(CancellationToken cancellationToken = default) { this.Method = HttpMethods.DELETE; return this.SendAsyncWithGraphResponse(null, cancellationToken); } /// <summary> /// Gets the specified OrganizationalBranding. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The OrganizationalBranding.</returns> public async System.Threading.Tasks.Task<OrganizationalBranding> GetAsync(CancellationToken cancellationToken = default) { this.Method = HttpMethods.GET; var retrievedEntity = await this.SendAsync<OrganizationalBranding>(null, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(retrievedEntity); return retrievedEntity; } /// <summary> /// Gets the specified OrganizationalBranding and returns a <see cref="GraphResponse{OrganizationalBranding}"/> object. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The <see cref="GraphResponse{OrganizationalBranding}"/> object of the request.</returns> public System.Threading.Tasks.Task<GraphResponse<OrganizationalBranding>> GetResponseAsync(CancellationToken cancellationToken = default) { this.Method = HttpMethods.GET; return this.SendAsyncWithGraphResponse<OrganizationalBranding>(null, cancellationToken); } /// <summary> /// Updates the specified OrganizationalBranding using PATCH. /// </summary> /// <param name="organizationalBrandingToUpdate">The OrganizationalBranding to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <exception cref="ClientException">Thrown when an object returned in a response is used for updating an object in Microsoft Graph.</exception> /// <returns>The updated OrganizationalBranding.</returns> public async System.Threading.Tasks.Task<OrganizationalBranding> UpdateAsync(OrganizationalBranding organizationalBrandingToUpdate, CancellationToken cancellationToken = default) { this.ContentType = CoreConstants.MimeTypeNames.Application.Json; this.Method = HttpMethods.PATCH; var updatedEntity = await this.SendAsync<OrganizationalBranding>(organizationalBrandingToUpdate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(updatedEntity); return updatedEntity; } /// <summary> /// Updates the specified OrganizationalBranding using PATCH and returns a <see cref="GraphResponse{OrganizationalBranding}"/> object. /// </summary> /// <param name="organizationalBrandingToUpdate">The OrganizationalBranding to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <exception cref="ClientException">Thrown when an object returned in a response is used for updating an object in Microsoft Graph.</exception> /// <returns>The <see cref="GraphResponse{OrganizationalBranding}"/> object of the request.</returns> public System.Threading.Tasks.Task<GraphResponse<OrganizationalBranding>> UpdateResponseAsync(OrganizationalBranding organizationalBrandingToUpdate, CancellationToken cancellationToken = default) { this.ContentType = CoreConstants.MimeTypeNames.Application.Json; this.Method = HttpMethods.PATCH; return this.SendAsyncWithGraphResponse<OrganizationalBranding>(organizationalBrandingToUpdate, cancellationToken); } /// <summary> /// Updates the specified OrganizationalBranding using PUT. /// </summary> /// <param name="organizationalBrandingToUpdate">The OrganizationalBranding object to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await.</returns> public async System.Threading.Tasks.Task<OrganizationalBranding> PutAsync(OrganizationalBranding organizationalBrandingToUpdate, CancellationToken cancellationToken = default) { this.ContentType = CoreConstants.MimeTypeNames.Application.Json; this.Method = HttpMethods.PUT; var updatedEntity = await this.SendAsync<OrganizationalBranding>(organizationalBrandingToUpdate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(updatedEntity); return updatedEntity; } /// <summary> /// Updates the specified OrganizationalBranding using PUT and returns a <see cref="GraphResponse{OrganizationalBranding}"/> object. /// </summary> /// <param name="organizationalBrandingToUpdate">The OrganizationalBranding object to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await of <see cref="GraphResponse{OrganizationalBranding}"/>.</returns> public System.Threading.Tasks.Task<GraphResponse<OrganizationalBranding>> PutResponseAsync(OrganizationalBranding organizationalBrandingToUpdate, CancellationToken cancellationToken = default) { this.ContentType = CoreConstants.MimeTypeNames.Application.Json; this.Method = HttpMethods.PUT; return this.SendAsyncWithGraphResponse<OrganizationalBranding>(organizationalBrandingToUpdate, cancellationToken); } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IOrganizationalBrandingRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IOrganizationalBrandingRequest Expand(Expression<Func<OrganizationalBranding, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IOrganizationalBrandingRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IOrganizationalBrandingRequest Select(Expression<Func<OrganizationalBranding, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Initializes any collection properties after deserialization, like next requests for paging. /// </summary> /// <param name="organizationalBrandingToInitialize">The <see cref="OrganizationalBranding"/> with the collection properties to initialize.</param> private void InitializeCollectionProperties(OrganizationalBranding organizationalBrandingToInitialize) { if (organizationalBrandingToInitialize != null) { if (organizationalBrandingToInitialize.Localizations != null && organizationalBrandingToInitialize.Localizations.CurrentPage != null) { organizationalBrandingToInitialize.Localizations.InitializeNextPageRequest(this.Client, organizationalBrandingToInitialize.LocalizationsNextLink); // Copy the additional data collection to the page itself so that information is not lost organizationalBrandingToInitialize.Localizations.AdditionalData = organizationalBrandingToInitialize.AdditionalData; } } } } }
53.267176
203
0.664302
[ "MIT" ]
Aliases/msgraph-sdk-dotnet
src/Microsoft.Graph/Generated/requests/OrganizationalBrandingRequest.cs
13,956
C#
using System; using System.ComponentModel; using System.Windows; using System.Windows.Controls; namespace Betting.View { /// <summary> /// Using this behavior on a dataGRid will ensure to display only columns with "Browsable Attributes" /// Eric Ouellet /// </summary> public static class DataGridBehavior { public static readonly DependencyProperty UseBrowsableAttributeOnColumnProperty = DependencyProperty.RegisterAttached("UseBrowsableAttributeOnColumn", typeof(bool), typeof(DataGridBehavior), new UIPropertyMetadata(false, UseBrowsableAttributeOnColumnChanged)); public static bool GetUseBrowsableAttributeOnColumn(DependencyObject obj) { return (bool)obj.GetValue(UseBrowsableAttributeOnColumnProperty); } public static void SetUseBrowsableAttributeOnColumn(DependencyObject obj, bool val) { obj.SetValue(UseBrowsableAttributeOnColumnProperty, val); } private static void UseBrowsableAttributeOnColumnChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e) { if (obj is DataGrid dataGrid) { if ((bool)e.NewValue) { dataGrid.AutoGeneratingColumn += DataGridOnAutoGeneratingColumn; } else { dataGrid.AutoGeneratingColumn -= DataGridOnAutoGeneratingColumn; } } } private static void DataGridOnAutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e) { if (e.PropertyDescriptor is PropertyDescriptor propDesc) { foreach (Attribute att in propDesc.Attributes) { if (att is BrowsableAttribute browsableAttribute) { if (!browsableAttribute.Browsable) { e.Cancel = true; } } // As proposed by "dba" stackoverflow user on webpage: // https://stackoverflow.com/questions/4000132/is-there-a-way-to-hide-a-specific-column-in-a-datagrid-when-autogeneratecolumns // I added few next lines: if (att is DisplayNameAttribute displayName) { e.Column.Header = displayName.DisplayName; } } } } } }
35.972222
146
0.574903
[ "MIT" ]
dt-bet/Betting
Betting.View/Behavior/DataGridBehavior.cs
2,592
C#
using Microsoft.EntityFrameworkCore; using Order.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Order.Data { public class OrderContext : DbContext { public OrderContext(DbContextOptions<OrderContext> options) : base(options) { } public DbSet<OrderDetails> OrderDetails { get; set; } public DbSet<OrderItem> OrderItems { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { // Map the entity to the table modelBuilder.Entity<OrderItem>().ToTable("order_item"); modelBuilder.Entity<OrderDetails>().ToTable("order_details"); // Configure the PK modelBuilder.Entity<OrderItem>().HasKey(itm => itm.Id).HasName("pk_order_item"); modelBuilder.Entity<OrderDetails>().HasKey(x => x.Id).HasName("pk_order_details"); // Auto increments modelBuilder .Entity<OrderItem>() .Property(itm => itm.Id) .ValueGeneratedOnAdd(); modelBuilder .Entity<OrderDetails>() .Property(o => o.Id) .ValueGeneratedOnAdd(); // Set the precision of the decimal modelBuilder.Entity<OrderItem>() .Property(i => i.Price) .HasPrecision(19, 4); modelBuilder.Entity<OrderDetails>() .Property(i => i.TotalPaid) .HasPrecision(19, 4); } } }
32.265306
94
0.581278
[ "MIT" ]
minimac911/HonoursProject
src/Services/Order/Data/OrderContext.cs
1,583
C#
using System; using System.Linq; using System.Reflection; using Autofac; using Autofac.Extensions.DependencyInjection; using Kaftar.Core.Cqrs; using Kaftar.Core.Cqrs.CommandStack; using Kaftar.Core.CQRS.QueryStack.QueryHandler; using Kaftar.Core.Data; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Hangfire; using Hangfire.SqlServer; using Sophia.Data.Contexts; using Sophia.InformationGathering.GitHub; using Polly; using Sophia.WebHooksHandling; using Microsoft.Extensions.Options; using Sophia.Jobs; using System.Data.SqlClient; using Octokit.Bot; using Sophia.WebHooksHandling.Commands; using System.Net.Http; using Polly.Extensions.Http; using System.Threading.Tasks; using Seq.Extensions.Logging; using Microsoft.Extensions.Logging; using Sophia.Jobs.ScaningSteps; namespace Sophia { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public IServiceProvider ConfigureServices(IServiceCollection services) { services.Configure<GitHubOption>(Configuration.GetSection("github")); RepositoryCloningStep.SetBasePath(Configuration.GetValue<string>("git:baseClonePath")); services.AddLogging(loggingBuilder => { loggingBuilder.AddSeq(Configuration.GetSection("Seq")); }); services.Configure<CookiePolicyOptions>(options => { options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddDbContext<SophiaDbContext>( options => options.UseSqlServer(Configuration.GetConnectionString("SophiaConnection"), providerOptions => providerOptions.EnableRetryOnFailure())); services.AddHttpClient<GitHubRepositoryPullRequestService>() .AddTransientHttpErrorPolicy(p => p.WaitAndRetryAsync(10, _ => TimeSpan.FromMilliseconds(600))) .AddPolicyHandler(GetRetryPolicy()); services.AddHangfire(configuration => configuration .SetDataCompatibilityLevel(CompatibilityLevel.Version_170) .UseSimpleAssemblyNameTypeSerializer() .UseRecommendedSerializerSettings() .UseSqlServerStorage(Configuration.GetConnectionString("HangfireConnection"), new SqlServerStorageOptions { CommandBatchMaxTimeout = TimeSpan.FromMinutes(5), SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5), QueuePollInterval = TimeSpan.Zero, UseRecommendedIsolationLevel = true, UsePageLocksOnDequeue = true, DisableGlobalLocks = true })); services.AddScoped<IssuesEventHandler>(); services.AddScoped<IssueCommentEventHandler>(); services.AddScoped<PullRequestEventHandler>(); services.AddScoped<PushEventHandler>(); services.AddScoped<GitHubWebHookHandler>(); services.AddGitHubWebHookHandler(registry=> registry .RegisterHandler<IssueCommentEventHandler>("issue_comment") .RegisterHandler<IssuesEventHandler>("issues") .RegisterHandler<PullRequestEventHandler>("pull_request") .RegisterHandler<PushEventHandler>("push")); CommandHandlerFactory.RegisterCommandHandlers(); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); var containerBuilder = new ContainerBuilder(); containerBuilder.Populate(services); containerBuilder.RegisterModule<DefaultModule>(); containerBuilder.RegisterModule<KaftarBootstrapModule>(); var container = containerBuilder.Build(); GlobalConfiguration.Configuration.UseAutofacActivator(container, false); return new AutofacServiceProvider(container); } static IAsyncPolicy<HttpResponseMessage> GetRetryPolicy() { return Policy .HandleResult<HttpResponseMessage>(m => m.StatusCode == System.Net.HttpStatusCode.Forbidden) .RetryAsync(5, onRetryAsync: async (delegateResult, retryCount) => { var millisecondsToWait = (int)delegateResult.Result.Headers.RetryAfter.Delta.Value.TotalMilliseconds + 1500; await Task.Delay(millisecondsToWait).ConfigureAwait(false); }); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); app.UseHttpsRedirection(); } app.UseStaticFiles(); app.UseCookiePolicy(); app.UseHangfireServer(); app.UseHangfireDashboard(); app.UseMvc(); RecurringJob.AddOrUpdate<ScanRepositoriesJob>(job => job.Scan(), Cron.Minutely); RecurringJob.AddOrUpdate<ApplyPullRequestsJob>(job => job.Apply(), Cron.Minutely); } public class DefaultModule : Autofac.Module { protected override void Load(ContainerBuilder builder) { builder.RegisterType<SophiaDbContext>().As<DbContext>() .InstancePerLifetimeScope(); builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()) .AsClosedTypesOf(typeof(ICommandHandler<,>)).AsImplementedInterfaces(); builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()) .AsClosedTypesOf(typeof(IQueryHandler<,>)).AsImplementedInterfaces(); } } } }
38.163636
121
0.648563
[ "MIT" ]
CESEL/Sofia
src/Sofia/Startup.cs
6,299
C#
using Microsoft.EntityFrameworkCore; using TimeTracker.Domain; namespace TimeTracker.Data { public class TimeTrackerDbContext : DbContext { public TimeTrackerDbContext(DbContextOptions<TimeTrackerDbContext> options) : base (options) { } public DbSet<User> Users { get; set; } public DbSet<Client> Clients { get; set; } public DbSet<Project> Projects { get; set; } public DbSet<TimeEntry> TimeEntries { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity<User>().HasData( new User { Id = 1, Name = "Aleksandar", HourRate = 15m }, new User { Id = 2, Name = "Tanja", HourRate = 20m }); modelBuilder.Entity<Client>().HasData( new Client { Id = 1, Name = "Client 1"}, new Client { Id = 2, Name = "Client 2"}); modelBuilder.Entity<Project>().HasData( new { Id = 1L, Name = "Project 1", ClientId = 1L}, new { Id = 2L, Name = "Project 2", ClientId = 1L}, new { Id = 3L, Name = "Project 3", ClientId = 2L}); } } }
31.6
83
0.557753
[ "MIT" ]
toprek95/TimeTracker
src/TimeTracker/Data/TimeTrackerDbContext.cs
1,266
C#
using EasyConsoleCore; namespace DemoCore.Pages { class Page1A : MenuPage { public Page1A(Program program) : base("Page 1A", program, new Option("Page 1Ai", () => program.NavigateTo<Page1Ai>())) { } } }
19.357143
78
0.531365
[ "MIT" ]
JamieMair/EasyConsoleCore
DemoCore/Pages/Page1A.cs
273
C#
using System; using System.Collections.Generic; namespace OmniSharp.Extensions.LanguageServer.Protocol { public struct Supports<T> : ISupports { private readonly bool? _isSupported; public Supports(bool? isSupported, T value) { _isSupported = isSupported; Value = value; } public Supports(T value) { _isSupported = true; Value = value; } public Supports(bool? isSupported) { _isSupported = isSupported; Value = default!; } public T Value { get; set; } public bool IsSupported => _isSupported ?? false; public Type ValueType => typeof(T); object? ISupports.Value => Value; public static implicit operator T(Supports<T> value) => value.Value; public static implicit operator Supports<T>(T value) => new Supports<T>(!EqualityComparer<T>.Default.Equals(value, default!), value); } public static class Supports { public static Supports<T> OfValue<T>(T value) where T : class? => new Supports<T>(!EqualityComparer<T>.Default.Equals(value, default!), value); public static Supports<T> OfBoolean<T>(bool? isSupported) => new Supports<T>(isSupported); } }
28.195652
151
0.609098
[ "MIT" ]
Devils-Knight/csharp-language-server-protocol
src/Protocol/Supports.cs
1,297
C#
namespace x42.Feature.X42Client.RestClient.Responses { public class GetSpendableTXResponse { public GetSpendableTXResponseTransaction[] transactions { get; set; } } public class GetSpendableTXResponseTransaction { public string id { get; set; } public int index { get; set; } public string address { get; set; } public bool isChange { get; set; } public long amount { get; set; } public string creationTime { get; set; } public int confirmations { get; set; } } }
30.722222
77
0.632911
[ "MIT" ]
psavva/XServer
xServer.D/Feature/X42Client/RestClient/Responses/GetSpendableTXResponse.cs
555
C#
 using UnityEngine; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text.RegularExpressions; namespace Csv { public static class CsvImporter { static readonly ConstructorInfo _csvAsset = null; static CsvImporter() { var flags = BindingFlags.NonPublic | BindingFlags.Instance; var args = new Type[] { typeof(string[]), typeof(int), typeof(int), }; _csvAsset = typeof(CsvAsset).GetConstructor(flags, null, args, null); } /// <summary> Resources フォルダから読み込みを試みる <para> /// 区切り文字は コンマ を使っているものとして扱う </para></summary> public static CsvAsset Load(string path) { return Load(path, Delimiter.comma, ImportOption.Resources); } /// <summary> Resources フォルダから読み込みを試みる </summary> /// <param name="delimiter"> 区切り文字の種類を指定 </param> public static CsvAsset Load(string path, Delimiter delimiter) { return Load(path, delimiter, ImportOption.Resources); } /// <summary> 指定した方法による読み込みを試みる <para> /// 区切り文字は コンマ を使っているものとして扱う </para></summary> public static CsvAsset Load(string path, ImportOption option) { return Load(path, Delimiter.comma, option); } /// <summary> 指定した方法による読み込みを試みる </summary> /// <param name="delimiter"> 区切り文字の種類を指定 </param> public static CsvAsset Load(string path, Delimiter delimiter, ImportOption option) { string[] table = option.LoadAsset(path, delimiter); return _csvAsset.Invoke(new object[] { table, 0, 0, }) as CsvAsset; } // 余計な文字列を取り除くためのパターン static readonly Regex _exclude = new Regex(@"[^\w]"); // 指定したオプションに基づく方法でファイル読み込みを試みる static string[] LoadAsset(this ImportOption option, string path, Delimiter delimiter) { // リソースをオプションに対応する方法で読み込む var resource = Import(option, path); // セルごとに切り分ける var split = Regex.Split(resource, delimiter.split); // セルのデータを整形する var table = split.Select(cell => _exclude.Replace(cell, string.Empty)); // 余計な空データを取り除いたデータ列を返す return table.Where(cell => !string.IsNullOrEmpty(cell)).ToArray(); } // オプションに基づいた方法でファイル読み込みを行う static string Import(ImportOption option, string path) { return ""; } // 各オプションに対応したパスに変換 static string ConvertPath(ImportOption option, string path) { return option != ImportOption.StreamingAssets ? path : "file://" + Application.streamingAssetsPath + "/" + path; } } }
28.222222
86
0.661024
[ "Apache-2.0" ]
tom10987/Unity.Extension.CsvEditor
Assets/Scripts/CSV/CsvImporter.cs
3,096
C#
#region using System; using System.Collections.Generic; using System.Linq; using System.Text; using WinterLeaf.Engine; using WinterLeaf.Engine.Classes; using WinterLeaf.Engine.Containers; using WinterLeaf.Engine.Enums; using System.ComponentModel; using System.Threading; using WinterLeaf.Engine.Classes.Interopt; using WinterLeaf.Engine.Classes.Decorations; using WinterLeaf.Engine.Classes.Extensions; using WinterLeaf.Engine.Classes.Helpers; using Winterleaf.Demo.Full.Dedicated.Models.User.Extendable; #endregion namespace Winterleaf.Demo.Full.Dedicated.Models.Base { /// <summary> /// /// </summary> [TypeConverter(typeof(TypeConverterGeneric<Precipitation_Base>))] public partial class Precipitation_Base: GameBase { #region ProxyObjects Operator Overrides /// <summary> /// /// </summary> /// <param name="ts"></param> /// <param name="simobjectid"></param> /// <returns></returns> public static bool operator ==(Precipitation_Base ts, string simobjectid) { return object.ReferenceEquals(ts, null) ? object.ReferenceEquals(simobjectid, null) : ts.Equals(simobjectid); } /// <summary> /// /// </summary> /// <returns></returns> public override int GetHashCode() { return base.GetHashCode(); } /// <summary> /// /// </summary> /// <param name="obj"></param> /// <returns></returns> public override bool Equals(object obj) { return (this._ID ==(string)myReflections.ChangeType( obj,typeof(string))); } /// <summary> /// /// </summary> /// <param name="ts"></param> /// <param name="simobjectid"></param> /// <returns></returns> public static bool operator !=(Precipitation_Base ts, string simobjectid) { if (object.ReferenceEquals(ts, null)) return !object.ReferenceEquals(simobjectid, null); return !ts.Equals(simobjectid); } /// <summary> /// /// </summary> /// <param name="ts"></param> /// <returns></returns> public static implicit operator string( Precipitation_Base ts) { if (object.ReferenceEquals(ts, null)) return "0"; return ts._ID; } /// <summary> /// /// </summary> /// <param name="ts"></param> /// <returns></returns> public static implicit operator Precipitation_Base(string ts) { uint simobjectid = resolveobject(ts); return (Precipitation_Base) Omni.self.getSimObject(simobjectid,typeof(Precipitation_Base)); } /// <summary> /// /// </summary> /// <param name="ts"></param> /// <returns></returns> public static implicit operator int( Precipitation_Base ts) { return (int)ts._iID; } /// <summary> /// /// </summary> /// <param name="simobjectid"></param> /// <returns></returns> public static implicit operator Precipitation_Base(int simobjectid) { return (Precipitation) Omni.self.getSimObject((uint)simobjectid,typeof(Precipitation_Base)); } /// <summary> /// /// </summary> /// <param name="ts"></param> /// <returns></returns> public static implicit operator uint( Precipitation_Base ts) { return ts._iID; } /// <summary> /// /// </summary> /// <returns></returns> public static implicit operator Precipitation_Base(uint simobjectid) { return (Precipitation_Base) Omni.self.getSimObject(simobjectid,typeof(Precipitation_Base)); } #endregion #region Init Persists /// <summary> /// Set to true to enable splash animations when drops collide with other surfaces. /// </summary> [MemberGroup("Rendering")] public bool animateSplashes { get { return Omni.self.GetVar(_ID + ".animateSplashes").AsBool(); } set { Omni.self.SetVar(_ID + ".animateSplashes", value.AsString()); } } /// <summary> /// Height (vertical dimension) of the precipitation box. /// </summary> [MemberGroup("Precipitation")] public float boxHeight { get { return Omni.self.GetVar(_ID + ".boxHeight").AsFloat(); } set { Omni.self.SetVar(_ID + ".boxHeight", value.AsString()); } } /// <summary> /// Width and depth (horizontal dimensions) of the precipitation box. /// </summary> [MemberGroup("Precipitation")] public float boxWidth { get { return Omni.self.GetVar(_ID + ".boxWidth").AsFloat(); } set { Omni.self.SetVar(_ID + ".boxWidth", value.AsString()); } } /// <summary> /// @brief Allow drops to collide with world objects.\n\n If #animateSplashes is true, drops that collide with another object will produce a simple splash animation.\n @note This can be expensive as each drop will perform a raycast when it is created to determine where it will hit. /// </summary> [MemberGroup("Collision")] public bool doCollision { get { return Omni.self.GetVar(_ID + ".doCollision").AsBool(); } set { Omni.self.SetVar(_ID + ".doCollision", value.AsString()); } } /// <summary> /// @brief Length (in milliseconds) to display each drop frame.\n\n If #dropAnimateMS = 0, drops select a single random frame at creation that does not change throughout the drop's lifetime. If #dropAnimateMS 0, each drop cycles through the the available frames in the drop texture at the given rate. /// </summary> [MemberGroup("Rendering")] public int dropAnimateMS { get { return Omni.self.GetVar(_ID + ".dropAnimateMS").AsInt(); } set { Omni.self.SetVar(_ID + ".dropAnimateMS", value.AsString()); } } /// <summary> /// Size of each drop of precipitation. This will scale the texture. /// </summary> [MemberGroup("Rendering")] public float dropSize { get { return Omni.self.GetVar(_ID + ".dropSize").AsFloat(); } set { Omni.self.SetVar(_ID + ".dropSize", value.AsString()); } } /// <summary> /// The distance at which drops begin to fade out. /// </summary> [MemberGroup("Rendering")] public float fadeDist { get { return Omni.self.GetVar(_ID + ".fadeDist").AsFloat(); } set { Omni.self.SetVar(_ID + ".fadeDist", value.AsString()); } } /// <summary> /// The distance at which drops are completely faded out. /// </summary> [MemberGroup("Rendering")] public float fadeDistEnd { get { return Omni.self.GetVar(_ID + ".fadeDistEnd").AsFloat(); } set { Omni.self.SetVar(_ID + ".fadeDistEnd", value.AsString()); } } /// <summary> /// @brief Controls whether the Precipitation system follows the camera or remains where it is first placed in the scene.\n\n Set to true to make it seem like it is raining everywhere in the level (ie. the Player will always be in the rain). Set to false to have a single area affected by rain (ie. the Player can move in and out of the rainy area). /// </summary> [MemberGroup("Movement")] public bool followCam { get { return Omni.self.GetVar(_ID + ".followCam").AsBool(); } set { Omni.self.SetVar(_ID + ".followCam", value.AsString()); } } /// <summary> /// Set to 0 to disable the glow or or use it to control the intensity of each channel. /// </summary> [MemberGroup("Rendering")] public ColorF glowIntensity { get { return Omni.self.GetVar(_ID + ".glowIntensity").AsColorF(); } set { Omni.self.SetVar(_ID + ".glowIntensity", value.AsString()); } } /// <summary> /// Allow drops to collide with Player objects; only valid if #doCollision is true. /// </summary> [MemberGroup("Collision")] public bool hitPlayers { get { return Omni.self.GetVar(_ID + ".hitPlayers").AsBool(); } set { Omni.self.SetVar(_ID + ".hitPlayers", value.AsString()); } } /// <summary> /// Allow drops to collide with Vehicle objects; only valid if #doCollision is true. /// </summary> [MemberGroup("Collision")] public bool hitVehicles { get { return Omni.self.GetVar(_ID + ".hitVehicles").AsBool(); } set { Omni.self.SetVar(_ID + ".hitVehicles", value.AsString()); } } /// <summary> /// @brief Maximum mass of a drop.\n\n Drop mass determines how strongly the drop is affected by wind and turbulence. On creation, the drop will be assigned a random speed between #minMass and #minMass. /// </summary> [MemberGroup("Movement")] public float maxMass { get { return Omni.self.GetVar(_ID + ".maxMass").AsFloat(); } set { Omni.self.SetVar(_ID + ".maxMass", value.AsString()); } } /// <summary> /// @brief Maximum speed at which a drop will fall.\n\n On creation, the drop will be assigned a random speed between #minSpeed and #maxSpeed. /// </summary> [MemberGroup("Movement")] public float maxSpeed { get { return Omni.self.GetVar(_ID + ".maxSpeed").AsFloat(); } set { Omni.self.SetVar(_ID + ".maxSpeed", value.AsString()); } } /// <summary> /// Radius at which precipitation drops spiral when turbulence is enabled. /// </summary> [MemberGroup("Turbulence")] public float maxTurbulence { get { return Omni.self.GetVar(_ID + ".maxTurbulence").AsFloat(); } set { Omni.self.SetVar(_ID + ".maxTurbulence", value.AsString()); } } /// <summary> /// @brief Minimum mass of a drop.\n\n Drop mass determines how strongly the drop is affected by wind and turbulence. On creation, the drop will be assigned a random speed between #minMass and #minMass. /// </summary> [MemberGroup("Movement")] public float minMass { get { return Omni.self.GetVar(_ID + ".minMass").AsFloat(); } set { Omni.self.SetVar(_ID + ".minMass", value.AsString()); } } /// <summary> /// @brief Minimum speed at which a drop will fall.\n\n On creation, the drop will be assigned a random speed between #minSpeed and #maxSpeed. /// </summary> [MemberGroup("Movement")] public float minSpeed { get { return Omni.self.GetVar(_ID + ".minSpeed").AsFloat(); } set { Omni.self.SetVar(_ID + ".minSpeed", value.AsString()); } } /// <summary> /// @brief Maximum number of drops allowed to exist in the precipitation box at any one time.\n\n The actual number of drops in the effect depends on the current percentage, which can change over time using modifyStorm(). /// </summary> [MemberGroup("Precipitation")] public int numDrops { get { return Omni.self.GetVar(_ID + ".numDrops").AsInt(); } set { Omni.self.SetVar(_ID + ".numDrops", value.AsString()); } } /// <summary> /// @brief This enables precipitation rendering during reflection passes.\n\n @note This is expensive. /// </summary> [MemberGroup("Rendering")] public bool reflect { get { return Omni.self.GetVar(_ID + ".reflect").AsBool(); } set { Omni.self.SetVar(_ID + ".reflect", value.AsString()); } } /// <summary> /// Set to true to include the camera velocity when calculating drop rotation speed. /// </summary> [MemberGroup("Rendering")] public bool rotateWithCamVel { get { return Omni.self.GetVar(_ID + ".rotateWithCamVel").AsBool(); } set { Omni.self.SetVar(_ID + ".rotateWithCamVel", value.AsString()); } } /// <summary> /// Lifetime of splashes in milliseconds. /// </summary> [MemberGroup("Rendering")] public int splashMS { get { return Omni.self.GetVar(_ID + ".splashMS").AsInt(); } set { Omni.self.SetVar(_ID + ".splashMS", value.AsString()); } } /// <summary> /// Size of each splash animation when a drop collides with another surface. /// </summary> [MemberGroup("Rendering")] public float splashSize { get { return Omni.self.GetVar(_ID + ".splashSize").AsFloat(); } set { Omni.self.SetVar(_ID + ".splashSize", value.AsString()); } } /// <summary> /// Speed at which precipitation drops spiral when turbulence is enabled. /// </summary> [MemberGroup("Turbulence")] public float turbulenceSpeed { get { return Omni.self.GetVar(_ID + ".turbulenceSpeed").AsFloat(); } set { Omni.self.SetVar(_ID + ".turbulenceSpeed", value.AsString()); } } /// <summary> /// Set to true to enable shading of the drops and splashes by the sun color. /// </summary> [MemberGroup("Rendering")] public bool useLighting { get { return Omni.self.GetVar(_ID + ".useLighting").AsBool(); } set { Omni.self.SetVar(_ID + ".useLighting", value.AsString()); } } /// <summary> /// Set to true to make drops true (non axis-aligned) billboards. /// </summary> [MemberGroup("Rendering")] public bool useTrueBillboards { get { return Omni.self.GetVar(_ID + ".useTrueBillboards").AsBool(); } set { Omni.self.SetVar(_ID + ".useTrueBillboards", value.AsString()); } } /// <summary> /// Check to enable turbulence. This causes precipitation drops to spiral while falling. /// </summary> [MemberGroup("Turbulence")] public bool useTurbulence { get { return Omni.self.GetVar(_ID + ".useTurbulence").AsBool(); } set { Omni.self.SetVar(_ID + ".useTurbulence", value.AsString()); } } /// <summary> /// Controls whether drops are affected by wind.\n @see ForestWindEmitter /// </summary> [MemberGroup("Movement")] public bool useWind { get { return Omni.self.GetVar(_ID + ".useWind").AsBool(); } set { Omni.self.SetVar(_ID + ".useWind", value.AsString()); } } #endregion #region Member Functions /// <summary> /// Smoothly change the maximum number of drops in the effect (from current /// value to #numDrops * @a percentage). /// This method can be used to simulate a storm building or fading in intensity /// as the number of drops in the Precipitation box changes. /// @param percentage New maximum number of drops value (as a percentage of /// #numDrops). Valid range is 0-1. /// @param seconds Length of time (in seconds) over which to increase the drops /// percentage value. Set to 0 to change instantly. /// @tsexample /// %percentage = 0.5; // The percentage, from 0 to 1, of the maximum drops to display /// %seconds = 5.0; // The length of time over which to make the change. /// %precipitation.modifyStorm( %percentage, %seconds ); /// @endtsexample ) /// /// </summary> [MemberFunctionConsoleInteraction(true)] public void modifyStorm(float percentage = 1.0f, float seconds = 5.0f){ pInvokes.m_ts.fnPrecipitation_modifyStorm(_ID, percentage, seconds); } /// <summary> /// Sets the maximum number of drops in the effect, as a percentage of #numDrops. /// The change occurs instantly (use modifyStorm() to change the number of drops /// over a period of time. /// @param percentage New maximum number of drops value (as a percentage of /// #numDrops). Valid range is 0-1. /// @tsexample /// %percentage = 0.5; // The percentage, from 0 to 1, of the maximum drops to display /// %precipitation.setPercentage( %percentage ); /// @endtsexample /// @see modifyStorm ) /// /// </summary> [MemberFunctionConsoleInteraction(true)] public void setPercentage(float percentage = 1.0f){ pInvokes.m_ts.fnPrecipitation_setPercentage(_ID, percentage); } /// <summary> /// Smoothly change the turbulence parameters over a period of time. /// @param max New #maxTurbulence value. Set to 0 to disable turbulence. /// @param speed New #turbulenceSpeed value. /// @param seconds Length of time (in seconds) over which to interpolate the /// turbulence settings. Set to 0 to change instantly. /// @tsexample /// %turbulence = 0.5; // Set the new turbulence value. Set to 0 to disable turbulence. /// %speed = 5.0; // The new speed of the turbulance effect. /// %seconds = 5.0; // The length of time over which to make the change. /// %precipitation.setTurbulence( %turbulence, %speed, %seconds ); /// @endtsexample ) /// /// </summary> [MemberFunctionConsoleInteraction(true)] public void setTurbulence(float max = 1.0f, float speed = 5.0f, float seconds = 5.0f){ pInvokes.m_ts.fnPrecipitation_setTurbulence(_ID, max, speed, seconds); } #endregion #region T3D Callbacks #endregion public Precipitation_Base (){} }}
31.063725
375
0.551891
[ "MIT", "Unlicense" ]
RichardRanft/OmniEngine.Net
Templates/C#-Full-Ded/WinterLeaf.Demo.Full.Dedicated/Models.Base/Precipitation_Base.cs
18,400
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System.Collections.Generic; using Aliyun.Acs.Core; using Aliyun.Acs.Core.Http; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.Core.Utils; using Aliyun.Acs.cloudesl.Transform; using Aliyun.Acs.cloudesl.Transform.V20200201; namespace Aliyun.Acs.cloudesl.Model.V20200201 { public class DeleteApDeviceRequest : RpcAcsRequest<DeleteApDeviceResponse> { public DeleteApDeviceRequest() : base("cloudesl", "2020-02-01", "DeleteApDevice", "cloudesl", "openAPI") { if (this.GetType().GetProperty("ProductEndpointMap") != null && this.GetType().GetProperty("ProductEndpointType") != null) { this.GetType().GetProperty("ProductEndpointMap").SetValue(this, Endpoint.endpointMap, null); this.GetType().GetProperty("ProductEndpointType").SetValue(this, Endpoint.endpointRegionalType, null); } Method = MethodType.POST; } private string extraParams; private string apMac; private string storeId; public string ExtraParams { get { return extraParams; } set { extraParams = value; DictionaryUtil.Add(BodyParameters, "ExtraParams", value); } } public string ApMac { get { return apMac; } set { apMac = value; DictionaryUtil.Add(BodyParameters, "ApMac", value); } } public string StoreId { get { return storeId; } set { storeId = value; DictionaryUtil.Add(BodyParameters, "StoreId", value); } } public override bool CheckShowJsonItemName() { return false; } public override DeleteApDeviceResponse GetResponse(UnmarshallerContext unmarshallerContext) { return DeleteApDeviceResponseUnmarshaller.Unmarshall(unmarshallerContext); } } }
27
134
0.674897
[ "Apache-2.0" ]
awei1688/aliyun-openapi-net-sdk
aliyun-net-sdk-cloudesl/Cloudesl/Model/V20200201/DeleteApDeviceRequest.cs
2,673
C#
/* Copyright (c) 2014 <a href="http://www.gutgames.com">James Craig</a> 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.Diagnostics.Contracts; using System.IO; using System.Linq; using System.Net; using Utilities.DataTypes; using Utilities.IO.Enums; using Utilities.IO.FileSystem.BaseClasses; using Utilities.IO.FileSystem.Interfaces; namespace Utilities.IO.FileSystem.Default { /// <summary> /// Directory class /// </summary> public class FtpDirectory : DirectoryBase<Uri, FtpDirectory> { /// <summary> /// Constructor /// </summary> public FtpDirectory() { } /// <summary> /// Constructor /// </summary> /// <param name="Path">Path to the directory</param> /// <param name="Domain">Domain of the user (optional)</param> /// <param name="Password">Password to be used to access the directory (optional)</param> /// <param name="UserName">User name to be used to access the directory (optional)</param> public FtpDirectory(string Path, string UserName = "", string Password = "", string Domain = "") : this(string.IsNullOrEmpty(Path) ? null : new Uri(Path), UserName, Password, Domain) { } /// <summary> /// Constructor /// </summary> /// <param name="Directory">Internal directory</param> /// <param name="Domain">Domain of the user (optional)</param> /// <param name="Password">Password to be used to access the directory (optional)</param> /// <param name="UserName">User name to be used to access the directory (optional)</param> public FtpDirectory(Uri Directory, string UserName = "", string Password = "", string Domain = "") : base(Directory, UserName, Password, Domain) { } /// <summary> /// returns now /// </summary> public override DateTime Accessed { get { return DateTime.Now; } } /// <summary> /// returns now /// </summary> public override DateTime Created { get { return DateTime.Now; } } /// <summary> /// returns true /// </summary> public override bool Exists { get { return true; } } /// <summary> /// Full path /// </summary> public override string FullName { get { return InternalDirectory == null ? "" : InternalDirectory.AbsolutePath; } } /// <summary> /// returns now /// </summary> public override DateTime Modified { get { return DateTime.Now; } } /// <summary> /// Full path /// </summary> public override string Name { get { return InternalDirectory == null ? "" : InternalDirectory.AbsolutePath; } } /// <summary> /// Full path /// </summary> public override IDirectory Parent { get { return InternalDirectory == null ? null : new FtpDirectory((string)InternalDirectory.AbsolutePath.Take(InternalDirectory.AbsolutePath.LastIndexOf("/", StringComparison.OrdinalIgnoreCase) - 1), UserName, Password, Domain); } } /// <summary> /// Root /// </summary> public override IDirectory Root { get { return InternalDirectory == null ? null : new FtpDirectory(InternalDirectory.Scheme + "://" + InternalDirectory.Host, UserName, Password, Domain); } } /// <summary> /// Size (returns 0) /// </summary> public override long Size { get { return 0; } } /// <summary> /// Not used /// </summary> public override void Create() { var Request = WebRequest.Create(InternalDirectory) as FtpWebRequest; Request.Method = WebRequestMethods.Ftp.MakeDirectory; SetupData(Request, null); SetupCredentials(Request); SendRequest(Request); } /// <summary> /// Not used /// </summary> public override void Delete() { var Request = WebRequest.Create(InternalDirectory) as FtpWebRequest; Request.Method = WebRequestMethods.Ftp.RemoveDirectory; SetupData(Request, null); SetupCredentials(Request); SendRequest(Request); } /// <summary> /// Not used /// </summary> /// <param name="SearchPattern"></param> /// <param name="Options"></param> /// <returns></returns> public override IEnumerable<IDirectory> EnumerateDirectories(string SearchPattern, SearchOption Options = SearchOption.TopDirectoryOnly) { var Request = WebRequest.Create(InternalDirectory) as FtpWebRequest; Request.Method = WebRequestMethods.Ftp.ListDirectory; SetupData(Request, null); SetupCredentials(Request); string Data = SendRequest(Request); string[] Folders = Data.Split(new string[] { System.Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); Request.Method = WebRequestMethods.Ftp.ListDirectoryDetails; SetupData(Request, null); SetupCredentials(Request); Data = SendRequest(Request); string[] DetailedFolders = Data.Split(new string[] { System.Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); var Directories = new List<IDirectory>(); foreach (string Folder in Folders) { string DetailedFolder = DetailedFolders.FirstOrDefault(x => x.EndsWith(Folder, StringComparison.OrdinalIgnoreCase)); if (!string.IsNullOrEmpty(DetailedFolder)) { if (DetailedFolder.StartsWith("d", StringComparison.OrdinalIgnoreCase) && !DetailedFolder.EndsWith(".", StringComparison.OrdinalIgnoreCase)) { Directories.Add(new DirectoryInfo(FullName + "/" + Folder, UserName, Password, Domain)); } } } return Directories; } /// <summary> /// Not used /// </summary> /// <param name="SearchPattern"></param> /// <param name="Options"></param> /// <returns></returns> public override IEnumerable<IFile> EnumerateFiles(string SearchPattern = "*", SearchOption Options = SearchOption.TopDirectoryOnly) { var Request = WebRequest.Create(InternalDirectory) as FtpWebRequest; Request.Method = WebRequestMethods.Ftp.ListDirectory; SetupData(Request, null); SetupCredentials(Request); string Data = SendRequest(Request); string[] Folders = Data.Split(new string[] { System.Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); Request.Method = WebRequestMethods.Ftp.ListDirectoryDetails; SetupData(Request, null); SetupCredentials(Request); Data = SendRequest(Request); string[] DetailedFolders = Data.Split(new string[] { System.Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); var Directories = new List<IFile>(); foreach (string Folder in Folders) { string DetailedFolder = DetailedFolders.FirstOrDefault(x => x.EndsWith(Folder, StringComparison.OrdinalIgnoreCase)); if (!string.IsNullOrEmpty(DetailedFolder)) { if (!DetailedFolder.StartsWith("d", StringComparison.OrdinalIgnoreCase)) { Directories.Add(new FileInfo(FullName + "/" + Folder, UserName, Password, Domain)); } } } return Directories; } /// <summary> /// Not used /// </summary> /// <param name="Name"></param> public override void Rename(string Name) { var Request = WebRequest.Create(InternalDirectory) as FtpWebRequest; Request.Method = WebRequestMethods.Ftp.Rename; Request.RenameTo = Name; SetupData(Request, null); SetupCredentials(Request); SendRequest(Request); InternalDirectory = new Uri(FullName + "/" + Name); } /// <summary> /// Sends the request to the URL specified /// </summary> /// <param name="Request">The web request object</param> /// <returns>The string returned by the service</returns> private static string SendRequest(FtpWebRequest Request) { Contract.Requires<ArgumentNullException>(Request != null, "Request"); using (FtpWebResponse Response = Request.GetResponse() as FtpWebResponse) { using (StreamReader Reader = new StreamReader(Response.GetResponseStream())) { return Reader.ReadToEnd(); } } } /// <summary> /// Sets up any credentials (basic authentication, for OAuth, please use the OAuth class to /// create the /// URL) /// </summary> /// <param name="Request">The web request object</param> private void SetupCredentials(FtpWebRequest Request) { if (!string.IsNullOrEmpty(UserName) && !string.IsNullOrEmpty(Password)) { Request.Credentials = new NetworkCredential(UserName, Password); } } /// <summary> /// Sets up any data that needs to be sent /// </summary> /// <param name="Request">The web request object</param> /// <param name="Data">Data to send with the request</param> private void SetupData(FtpWebRequest Request, byte[] Data) { Contract.Requires<ArgumentNullException>(Request != null, "Request"); Contract.Requires<NullReferenceException>(!string.IsNullOrEmpty(Name), "Name"); Request.UsePassive = true; Request.KeepAlive = false; Request.UseBinary = true; Request.EnableSsl = Name.ToUpperInvariant().StartsWith("FTPS", StringComparison.OrdinalIgnoreCase); if (Data == null) { Request.ContentLength = 0; return; } Request.ContentLength = Data.Length; using (Stream RequestStream = Request.GetRequestStream()) { RequestStream.Write(Data, 0, Data.Length); } } } }
39.306452
242
0.572097
[ "MIT" ]
sealong/Craig-s-Utility-Library
Utilities.IO/IO/FileSystem/Default/FtpDirectory.cs
12,187
C#
using System.ComponentModel; using System.Runtime.CompilerServices; using System.Windows.Controls; using DistrictEnergy.Annotations; using DistrictEnergy.ViewModels; namespace DistrictEnergy.Views.ResultViews { /// <summary> /// Interaction logic for Costs.xaml /// </summary> public partial class Costs : UserControl { public Costs() { InitializeComponent(); DataContext = new CostsViewModel(); } } }
23.75
47
0.667368
[ "MIT" ]
MITSustainableDesignLab/DistrictEnergyPlugIn
DistrictEnergy/Views/ResultViews/Costs.xaml.cs
477
C#
using System; namespace Built.Grpc { /// <summary> /// Settings specifying a service endpoint in the form of a host name and port. /// This class is immutable and thread-safe. /// </summary> public sealed class ServiceEndpoint : IEquatable<ServiceEndpoint> { /// <summary> /// The host name to connect to. Never null or empty. /// </summary> public string Host { get; } /// <summary> /// The port to connect to, in the range 1 to 65535 inclusive. /// </summary> public int Port { get; } /// <summary> /// Creates a new endpoint with the given host and port. /// </summary> /// <param name="host">The host name to connect to. Must not be null or empty.</param> /// <param name="port">The port to connect to, in the range 1 to 65535 inclusive.</param> public ServiceEndpoint(string host, int port) { Host = GaxPreconditions.CheckNotNullOrEmpty(host, nameof(host)); Port = GaxPreconditions.CheckArgumentRange(port, nameof(port), 1, 65535); } /// <summary> /// Creates a new endpoint with the same port but the given host. /// </summary> /// <param name="host">The host name to connect to. Must not be null or empty.</param> /// <returns>A new endpoint with the current port and the specified host.</returns> public ServiceEndpoint WithHost(string host) => new ServiceEndpoint(host, Port); /// <summary> /// Creates a new endpoint with the same host but the given port. /// </summary> /// <param name="port">The port to connect to, in the range 1 to 65535 inclusive.</param> /// <returns>A new endpoint with the current host and the specified port.</returns> public ServiceEndpoint WithPort(int port) => new ServiceEndpoint(Host, port); /// <summary> /// Returns this endpoint's data in the format "host:port". /// </summary> /// <returns>This endpoint's data in the format "host:port".</returns> public override string ToString() => $"{Host}:{Port}"; /// <summary> /// Determines equality between this object and <paramref name="obj"/>. /// </summary> /// <param name="obj">The object to compare with this one.</param> /// <returns><c>true</c> if <paramref name="obj"/> is a <see cref="ServiceEndpoint"/> /// with the same host and port; <c>false</c> otherwise.</returns> public override bool Equals(object obj) => Equals(obj as ServiceEndpoint); /// <summary> /// Returns a hash code for this object, consistent with <see cref="Equals(ServiceEndpoint)"/>. /// </summary> /// <returns>A hash code for this object.</returns> public override int GetHashCode() => unchecked(Host.GetHashCode() * 31 + Port); /// <summary> /// Determines equality between this endpoint and <paramref name="other"/>. /// </summary> /// <param name="other">The object to compare with this one.</param> /// <returns><c>true</c> if <paramref name="other"/> is a <see cref="ServiceEndpoint"/> /// with the same host and port; <c>false</c> otherwise.</returns> public bool Equals(ServiceEndpoint other) => other != null && other.Host == Host && other.Port == Port; } }
46.148649
111
0.60205
[ "MIT" ]
BuiltCloud/Built
src/Built.Grpc/GrpcPool/ServiceEndpoint.cs
3,417
C#
/* * Doto-Content-Unlocker, tool for unlocking custom dota2 content. * * Copyright (c) 2014 Teq, https://github.com/Teq2/Doto-Content-Unlocker * * 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.Drawing; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace Doto_Unlocker.Model { static class Utils { /// <summary> /// Keeps directories, deletes files only /// </summary> /// <param name="dir"></param> public static void ClearDir(string dir) { var di = new DirectoryInfo(dir); foreach (var file in di.GetFiles()) { file.Delete(); } foreach (var subDir in di.GetDirectories()) { ClearDir(subDir.FullName); } } public static void CheckAndCreateDirectory(string fullPath) { var dir = Path.GetDirectoryName(fullPath); if (!Directory.Exists(dir)) Directory.CreateDirectory(dir); } public static float GetRatio(this Image i) { return (float)i.Height / (float)i.Width; } } }
34.940299
89
0.659974
[ "MIT" ]
Teq2/Doto-Content-Unlocker
Model/Utils.cs
2,343
C#
// <file> // <copyright see="prj:///doc/copyright.txt"/> // <license see="prj:///doc/license.txt"/> // <owner name="Mike Krüger" email="[email protected]"/> // <version>$Revision$</version> // </file> using System; using System.Collections.Generic; namespace ICSharpCode.TextEditor.Undo { /// <summary> /// This class implements an undo stack /// </summary> public class UndoStack { Stack<IUndoableOperation> undostack = new Stack<IUndoableOperation>(); Stack<IUndoableOperation> redostack = new Stack<IUndoableOperation>(); public TextEditorControlBase TextEditorControl = null; /// <summary> /// </summary> public event EventHandler ActionUndone; /// <summary> /// </summary> public event EventHandler ActionRedone; public event OperationEventHandler OperationPushed; /// <summary> /// Gets/Sets if changes to the document are protocolled by the undo stack. /// Used internally to disable the undo stack temporarily while undoing an action. /// </summary> internal bool AcceptChanges = true; /// <summary> /// Gets if there are actions on the undo stack. /// </summary> public bool CanUndo { get { return undostack.Count > 0; } } /// <summary> /// Gets if there are actions on the redo stack. /// </summary> public bool CanRedo { get { return redostack.Count > 0; } } /// <summary> /// Gets the number of actions on the undo stack. /// </summary> public int UndoItemCount { get { return undostack.Count; } } /// <summary> /// Gets the number of actions on the redo stack. /// </summary> public int RedoItemCount { get { return redostack.Count; } } int undoGroupDepth; int actionCountInUndoGroup; public void StartUndoGroup() { if (undoGroupDepth == 0) { actionCountInUndoGroup = 0; } undoGroupDepth++; //Util.LoggingService.Debug("Open undo group (new depth=" + undoGroupDepth + ")"); } public void EndUndoGroup() { if (undoGroupDepth == 0) throw new InvalidOperationException("There are no open undo groups"); undoGroupDepth--; //Util.LoggingService.Debug("Close undo group (new depth=" + undoGroupDepth + ")"); if (undoGroupDepth == 0 && actionCountInUndoGroup > 1) { UndoQueue op = new UndoQueue(undostack, actionCountInUndoGroup); undostack.Push(op); if (OperationPushed != null) { OperationPushed(this, new OperationEventArgs(op)); } } } public void AssertNoUndoGroupOpen() { if (undoGroupDepth != 0) { undoGroupDepth = 0; throw new InvalidOperationException("No undo group should be open at this point"); } } /// <summary> /// Call this method to undo the last operation on the stack /// </summary> public void Undo() { AssertNoUndoGroupOpen(); if (undostack.Count > 0) { IUndoableOperation uedit = (IUndoableOperation)undostack.Pop(); redostack.Push(uedit); uedit.Undo(); OnActionUndone(); } } /// <summary> /// Call this method to redo the last undone operation /// </summary> public void Redo() { AssertNoUndoGroupOpen(); if (redostack.Count > 0) { IUndoableOperation uedit = (IUndoableOperation)redostack.Pop(); undostack.Push(uedit); uedit.Redo(); OnActionRedone(); } } /// <summary> /// Call this method to push an UndoableOperation on the undostack, the redostack /// will be cleared, if you use this method. /// </summary> public void Push(IUndoableOperation operation) { if (operation == null) { throw new ArgumentNullException("operation"); } if (AcceptChanges) { StartUndoGroup(); undostack.Push(operation); actionCountInUndoGroup++; if (TextEditorControl != null) { undostack.Push(new UndoableSetCaretPosition(this, TextEditorControl.ActiveTextAreaControl.Caret.Position)); actionCountInUndoGroup++; } EndUndoGroup(); ClearRedoStack(); } } /// <summary> /// Call this method, if you want to clear the redo stack /// </summary> public void ClearRedoStack() { redostack.Clear(); } /// <summary> /// Clears both the undo and redo stack. /// </summary> public void ClearAll() { AssertNoUndoGroupOpen(); undostack.Clear(); redostack.Clear(); actionCountInUndoGroup = 0; } /// <summary> /// </summary> protected void OnActionUndone() { if (ActionUndone != null) { ActionUndone(null, null); } } /// <summary> /// </summary> protected void OnActionRedone() { if (ActionRedone != null) { ActionRedone(null, null); } } class UndoableSetCaretPosition : IUndoableOperation { UndoStack stack; TextLocation pos; TextLocation redoPos; public UndoableSetCaretPosition(UndoStack stack, TextLocation pos) { this.stack = stack; this.pos = pos; } public void Undo() { redoPos = stack.TextEditorControl.ActiveTextAreaControl.Caret.Position; stack.TextEditorControl.ActiveTextAreaControl.Caret.Position = pos; stack.TextEditorControl.ActiveTextAreaControl.SelectionManager.ClearSelection(); } public void Redo() { stack.TextEditorControl.ActiveTextAreaControl.Caret.Position = redoPos; stack.TextEditorControl.ActiveTextAreaControl.SelectionManager.ClearSelection(); } } } public class OperationEventArgs : EventArgs { public OperationEventArgs(IUndoableOperation op) { this.op = op; } IUndoableOperation op; public IUndoableOperation Operation { get { return op; } } } public delegate void OperationEventHandler(object sender, OperationEventArgs e); }
28.338403
127
0.504226
[ "MIT" ]
BarisYildiz/LiteDB.Studio
LiteDB.Studio/ICSharpCode.TextEditor/Undo/UndoStack.cs
7,456
C#
/* * The MIT License (MIT) * * Copyright (c) 2013 Alistair Leslie-Hughes * * 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; namespace Microsoft.DirectX.DirectInput { public enum Key { Next = 209, Right = 205, Left = 203, Convert = 121, Decimal = 83, N = 49, Q = 16, Circumflex = 144, PageDown = 209, DownArrow = 208, RightArrow = 205, LeftArrow = 203, PageUp = 201, UpArrow = 200, RightAlt = 184, NumPadSlash = 181, NumPadPeriod = 83, NumPadPlus = 78, NumPadMinus = 74, CapsLock = 58, LeftAlt = 56, NumPadStar = 55, BackSpace = 14, MediaSelect = 237, Mail = 236, MyComputer = 235, WebBack = 234, WebForward = 233, WebStop = 232, WebRefresh = 231, WebFavorites = 230, WebSearch = 229, Wake = 227, Sleep = 223, Power = 222, Apps = 221, RightWindows = 220, LeftWindows = 219, Delete = 211, Insert = 210, Down = 208, End = 207, Prior = 201, Up = 200, Home = 199, Pause = 197, RightMenu = 184, SysRq = 183, Divide = 181, NumPadComma = 179, WebHome = 178, VolumeUp = 176, VolumeDown = 174, MediaStop = 164, PlayPause = 162, Calculator = 161, Mute = 160, RightControl = 157, NumPadEnter = 156, NextTrack = 153, Unlabeled = 151, AX = 150, Stop = 149, Kanji = 148, Underline = 147, Colon = 146, At = 145, PrevTrack = 144, NumPadEquals = 141, AbntC2 = 126, Yen = 125, NoConvert = 123, AbntC1 = 115, Kana = 112, F15 = 102, F14 = 101, F13 = 100, F12 = 88, F11 = 87, OEM102 = 86, NumPad0 = 82, NumPad3 = 81, NumPad2 = 80, NumPad1 = 79, Add = 78, NumPad6 = 77, NumPad5 = 76, NumPad4 = 75, Subtract = 74, NumPad9 = 73, NumPad8 = 72, NumPad7 = 71, Numlock = 69, F10 = 68, F9 = 67, F8 = 66, F7 = 65, F6 = 64, F5 = 63, F4 = 62, F3 = 61, F2 = 60, F1 = 59, Capital = 58, Space = 57, LeftMenu = 56, Multiply = 55, RightShift = 54, Slash = 53, Period = 52, Comma = 51, M = 50, B = 48, V = 47, C = 46, X = 45, BackSlash = 43, LeftShift = 42, Grave = 41, Apostrophe = 40, SemiColon = 39, L = 38, K = 37, J = 36, H = 35, G = 34, F = 33, D = 32, S = 31, A = 30, LeftControl = 29, Return = 28, RightBracket = 27, LeftBracket = 26, P = 25, O = 24, I = 23, U = 22, Y = 21, T = 20, R = 19, E = 18, W = 17, Tab = 15, Back = 14, Equals = 13, Minus = 12, D0 = 11, D9 = 10, D8 = 9, D7 = 8, D6 = 7, D5 = 6, D4 = 5, D3 = 4, D2 = 3, D1 = 2, Z = 44, Escape = 1, Scroll = 70 } }
18.786458
83
0.606876
[ "MIT" ]
alesliehughes/monoDX
Microsoft.DirectX.DirectInput/Microsoft.DirectX.DirectInput/Key.cs
3,607
C#
using System; using System.IO; using System.Linq; using System.Xml.XPath; using System.Xml.Linq; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; namespace Xamarin.Android.Tasks { public static class XDocumentExtensions { const string PathsElementName = "Paths"; public static ITaskItem[] GetPathsAsTaskItems (this XDocument doc, params string[] paths) { var e = doc.Elements (PathsElementName); foreach (var p in paths) e = e.Elements (p); return e.Select (ToTaskItem).ToArray (); } static ITaskItem ToTaskItem (XElement element) { var taskItem = new TaskItem (element.Value); foreach (var attribute in element.Attributes ()) { taskItem.SetMetadata (attribute.Name.LocalName, attribute.Value); } return taskItem; } public static string[] GetPaths (this XDocument doc, params string[] paths) { var e = doc.Elements (PathsElementName); foreach (var p in paths) e = e.Elements (p); return e.Select (p => p.Value).ToArray (); } public static string ToFullString (this XElement element) { return element.ToString (SaveOptions.DisableFormatting); } public static bool SaveIfChanged (this XDocument document, string fileName) { var tempFile = System.IO.Path.GetTempFileName (); try { using (var stream = File.OpenWrite (tempFile)) using (var xw = new Monodroid.LinePreservedXmlWriter (new StreamWriter (stream))) xw.WriteNode (document.CreateNavigator (), false); return MonoAndroidHelper.CopyIfChanged (tempFile, fileName); } finally { File.Delete (tempFile); } } } }
26.683333
91
0.710181
[ "MIT" ]
brendanzagaeski/xamarin-android
src/Xamarin.Android.Build.Tasks/Utilities/XDocumentExtensions.cs
1,603
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the firehose-2015-08-04.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.KinesisFirehose.Model { /// <summary> /// Describes an update for a destination in Amazon ES. /// </summary> public partial class ElasticsearchDestinationUpdate { private ElasticsearchBufferingHints _bufferingHints; private CloudWatchLoggingOptions _cloudWatchLoggingOptions; private string _domainARN; private string _indexName; private ElasticsearchIndexRotationPeriod _indexRotationPeriod; private ProcessingConfiguration _processingConfiguration; private ElasticsearchRetryOptions _retryOptions; private string _roleARN; private S3DestinationUpdate _s3Update; private string _typeName; /// <summary> /// Gets and sets the property BufferingHints. /// <para> /// The buffering options. If no value is specified, <b>ElasticsearchBufferingHints</b> /// object default values are used. /// </para> /// </summary> public ElasticsearchBufferingHints BufferingHints { get { return this._bufferingHints; } set { this._bufferingHints = value; } } // Check to see if BufferingHints property is set internal bool IsSetBufferingHints() { return this._bufferingHints != null; } /// <summary> /// Gets and sets the property CloudWatchLoggingOptions. /// <para> /// The CloudWatch logging options for your delivery stream. /// </para> /// </summary> public CloudWatchLoggingOptions CloudWatchLoggingOptions { get { return this._cloudWatchLoggingOptions; } set { this._cloudWatchLoggingOptions = value; } } // Check to see if CloudWatchLoggingOptions property is set internal bool IsSetCloudWatchLoggingOptions() { return this._cloudWatchLoggingOptions != null; } /// <summary> /// Gets and sets the property DomainARN. /// <para> /// The ARN of the Amazon ES domain. The IAM role must have permissions for <code>DescribeElasticsearchDomain</code>, /// <code>DescribeElasticsearchDomains</code>, and <code>DescribeElasticsearchDomainConfig</code> after /// assuming the IAM role specified in <b>RoleARN</b>. /// </para> /// </summary> public string DomainARN { get { return this._domainARN; } set { this._domainARN = value; } } // Check to see if DomainARN property is set internal bool IsSetDomainARN() { return this._domainARN != null; } /// <summary> /// Gets and sets the property IndexName. /// <para> /// The Elasticsearch index name. /// </para> /// </summary> public string IndexName { get { return this._indexName; } set { this._indexName = value; } } // Check to see if IndexName property is set internal bool IsSetIndexName() { return this._indexName != null; } /// <summary> /// Gets and sets the property IndexRotationPeriod. /// <para> /// The Elasticsearch index rotation period. Index rotation appends a timestamp to IndexName /// to facilitate the expiration of old data. For more information, see <a href="http://docs.aws.amazon.com/firehose/latest/dev/basic-deliver.html#es-index-rotation">Index /// Rotation for Amazon Elasticsearch Service Destination</a>. Default value is <code>OneDay</code>. /// </para> /// </summary> public ElasticsearchIndexRotationPeriod IndexRotationPeriod { get { return this._indexRotationPeriod; } set { this._indexRotationPeriod = value; } } // Check to see if IndexRotationPeriod property is set internal bool IsSetIndexRotationPeriod() { return this._indexRotationPeriod != null; } /// <summary> /// Gets and sets the property ProcessingConfiguration. /// <para> /// The data processing configuration. /// </para> /// </summary> public ProcessingConfiguration ProcessingConfiguration { get { return this._processingConfiguration; } set { this._processingConfiguration = value; } } // Check to see if ProcessingConfiguration property is set internal bool IsSetProcessingConfiguration() { return this._processingConfiguration != null; } /// <summary> /// Gets and sets the property RetryOptions. /// <para> /// The retry behavior in the event that Firehose is unable to deliver documents to Amazon /// ES. Default value is 300 (5 minutes). /// </para> /// </summary> public ElasticsearchRetryOptions RetryOptions { get { return this._retryOptions; } set { this._retryOptions = value; } } // Check to see if RetryOptions property is set internal bool IsSetRetryOptions() { return this._retryOptions != null; } /// <summary> /// Gets and sets the property RoleARN. /// <para> /// The ARN of the IAM role to be assumed by Firehose for calling the Amazon ES Configuration /// API and for indexing documents. For more information, see <a href="http://docs.aws.amazon.com/firehose/latest/dev/controlling-access.html#using-iam-s3">Amazon /// S3 Bucket Access</a>. /// </para> /// </summary> public string RoleARN { get { return this._roleARN; } set { this._roleARN = value; } } // Check to see if RoleARN property is set internal bool IsSetRoleARN() { return this._roleARN != null; } /// <summary> /// Gets and sets the property S3Update. /// <para> /// The Amazon S3 destination. /// </para> /// </summary> public S3DestinationUpdate S3Update { get { return this._s3Update; } set { this._s3Update = value; } } // Check to see if S3Update property is set internal bool IsSetS3Update() { return this._s3Update != null; } /// <summary> /// Gets and sets the property TypeName. /// <para> /// The Elasticsearch type name. /// </para> /// </summary> public string TypeName { get { return this._typeName; } set { this._typeName = value; } } // Check to see if TypeName property is set internal bool IsSetTypeName() { return this._typeName != null; } } }
33.489362
179
0.594536
[ "Apache-2.0" ]
Bynder/aws-sdk-net
sdk/src/Services/KinesisFirehose/Generated/Model/ElasticsearchDestinationUpdate.cs
7,873
C#
/* Copyright (c) 2008-2010 by the President and Fellows of Harvard College. All rights reserved. Profiles Research Networking Software was developed under the supervision of Griffin M Weber, MD, PhD., and Harvard Catalyst: The Harvard Clinical and Translational Science Center, with support from the National Center for Research Resources and Harvard University. Code licensed under a BSD License. For details, see: LICENSE.txt */ using System.Collections.Generic; using System.Runtime.Serialization; namespace Connects.Profiles.Service.DataContracts { [DataContract(Name = "InternalID")] public partial class InternalID { private string nameField; private string textField; /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute("Name")] [DataMember(IsRequired = false, Name = "Name", Order = 1)] public string Name { get { return this.nameField; } set { this.nameField = value; } } [System.Xml.Serialization.XmlTextAttribute()] [DataMember(IsRequired = false, Name = "Text")] public string Text { get { return this.textField; } set { this.textField = value; } } } [System.Xml.Serialization.XmlTypeAttribute()] [DataContract(Name = "InternalIDList")] public partial class InternalIDList { private List<InternalID> internalIdField; [System.Xml.Serialization.XmlElementAttribute("InternalID")] [DataMember(IsRequired = false, Name = "InternalID", Order = 1)] public List<InternalID> InternalID { get { return this.internalIdField; } set { this.internalIdField = value; } } } }
27.350649
108
0.546059
[ "BSD-3-Clause" ]
CTSIatUCSF/ProfilesRNS
Website/SourceCode/ProfilesBetaAPI/Connects.Profiles.Service.DataContracts/InternalId.cs
2,108
C#
// <auto-generated> // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.ResourceManager { using System; using System.Collections.Generic; using System.Linq; internal static partial class SdkInfo { public static IEnumerable<Tuple<string, string, string>> ApiInfo_FeatureClient { get { return new Tuple<string, string, string>[] { new Tuple<string, string, string>("Features", "Features", "2015-12-01"), new Tuple<string, string, string>("Features", "ListOperations", "2015-12-01"), }.AsEnumerable(); } } } }
27.517241
94
0.620301
[ "MIT" ]
0rland0Wats0n/azure-sdk-for-net
sdk/resources/Microsoft.Azure.Management.Resource/src/Generated/SdkInfo_FeatureClient.cs
798
C#
#region License /** * Copyright (c) 2015, 何志祥 ([email protected]). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * without warranties or conditions of any kind, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #endregion using System; using System.Linq.Expressions; namespace Expression2Sql { internal class Expression2SqlProvider { private static IExpression2Sql GetExpression2Sql(Expression expression) { if (expression == null) { throw new ArgumentNullException("expression", "Cannot be null"); } if (expression is BinaryExpression) { return new BinaryExpression2Sql(); } if (expression is BlockExpression) { throw new NotImplementedException("Unimplemented BlockExpression2Sql"); } if (expression is ConditionalExpression) { throw new NotImplementedException("Unimplemented ConditionalExpression2Sql"); } if (expression is ConstantExpression) { return new ConstantExpression2Sql(); } if (expression is DebugInfoExpression) { throw new NotImplementedException("Unimplemented DebugInfoExpression2Sql"); } if (expression is DefaultExpression) { throw new NotImplementedException("Unimplemented DefaultExpression2Sql"); } if (expression is DynamicExpression) { throw new NotImplementedException("Unimplemented DynamicExpression2Sql"); } if (expression is GotoExpression) { throw new NotImplementedException("Unimplemented GotoExpression2Sql"); } if (expression is IndexExpression) { throw new NotImplementedException("Unimplemented IndexExpression2Sql"); } if (expression is InvocationExpression) { throw new NotImplementedException("Unimplemented InvocationExpression2Sql"); } if (expression is LabelExpression) { throw new NotImplementedException("Unimplemented LabelExpression2Sql"); } if (expression is LambdaExpression) { throw new NotImplementedException("Unimplemented LambdaExpression2Sql"); } if (expression is ListInitExpression) { throw new NotImplementedException("Unimplemented ListInitExpression2Sql"); } if (expression is LoopExpression) { throw new NotImplementedException("Unimplemented LoopExpression2Sql"); } if (expression is MemberExpression) { return new MemberExpression2Sql(); } if (expression is MemberInitExpression) { throw new NotImplementedException("Unimplemented MemberInitExpression2Sql"); } if (expression is MethodCallExpression) { return new MethodCallExpression2Sql(); } if (expression is NewArrayExpression) { return new NewArrayExpression2Sql(); } if (expression is NewExpression) { return new NewExpression2Sql(); } if (expression is ParameterExpression) { return new ParameterExpression2Sql(); } if (expression is RuntimeVariablesExpression) { throw new NotImplementedException("Unimplemented RuntimeVariablesExpression2Sql"); } if (expression is SwitchExpression) { throw new NotImplementedException("Unimplemented SwitchExpression2Sql"); } if (expression is TryExpression) { throw new NotImplementedException("Unimplemented TryExpression2Sql"); } if (expression is TypeBinaryExpression) { throw new NotImplementedException("Unimplemented TypeBinaryExpression2Sql"); } if (expression is UnaryExpression) { return new UnaryExpression2Sql(); } throw new NotImplementedException("Unimplemented Expression2Sql"); } public static void Insert(Expression expression, SqlBuilder sqlBuilder) { GetExpression2Sql(expression).Insert(expression, sqlBuilder); } public static void Update(Expression expression, SqlBuilder sqlBuilder) { GetExpression2Sql(expression).Update(expression, sqlBuilder); } public static void Select(Expression expression, SqlBuilder sqlBuilder) { GetExpression2Sql(expression).Select(expression, sqlBuilder); } public static void Join(Expression expression, SqlBuilder sqlBuilder) { GetExpression2Sql(expression).Join(expression, sqlBuilder); } public static void Where(Expression expression, SqlBuilder sqlBuilder) { GetExpression2Sql(expression).Where(expression, sqlBuilder); } public static void In(Expression expression, SqlBuilder sqlBuilder) { GetExpression2Sql(expression).In(expression, sqlBuilder); } public static void GroupBy(Expression expression, SqlBuilder sqlBuilder) { GetExpression2Sql(expression).GroupBy(expression, sqlBuilder); } public static void OrderBy(Expression expression, SqlBuilder sqlBuilder) { GetExpression2Sql(expression).OrderBy(expression, sqlBuilder); } public static void Max(Expression expression, SqlBuilder sqlBuilder) { GetExpression2Sql(expression).Max(expression, sqlBuilder); } public static void Min(Expression expression, SqlBuilder sqlBuilder) { GetExpression2Sql(expression).Min(expression, sqlBuilder); } public static void Avg(Expression expression, SqlBuilder sqlBuilder) { GetExpression2Sql(expression).Avg(expression, sqlBuilder); } public static void Count(Expression expression, SqlBuilder sqlBuilder) { GetExpression2Sql(expression).Count(expression, sqlBuilder); } public static void Sum(Expression expression, SqlBuilder sqlBuilder) { GetExpression2Sql(expression).Sum(expression, sqlBuilder); } } }
35.576355
98
0.601911
[ "Artistic-2.0" ]
cnark/Expression2Sql
Expression2Sql/Expression2SqlProvider.cs
7,230
C#