content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System.Runtime.Serialization; using System.Text.Json.Serialization; namespace Plotly.Models.Traces.DensityMapBoxs.HoverLabels { /// <summary> /// Sets the horizontal alignment of the text content within hover label box. /// Has an effect only if the hover label text spans more two or more lines /// </summary> [JsonConverter(typeof(EnumConverter))] public enum AlignEnum { [EnumMember(Value = @"auto")] Auto = 0, [EnumMember(Value = @"left")] Left, [EnumMember(Value = @"right")] Right } }
25.565217
85
0.629252
[ "MIT" ]
trmcnealy/Plotly.WPF
Plotly/Models/Traces/DensityMapBoxs/HoverLabels/AlignEnum.cs
588
C#
using ProjectHermes.ShoppingList.Api.Domain.ShoppingLists.Models; using ProjectHermes.ShoppingList.Api.Domain.Stores.Models; namespace ProjectHermes.ShoppingList.Api.Domain.Common.Exceptions.Reason { public class SectionAlreadyInShoppingListReason : IReason { public SectionAlreadyInShoppingListReason(ShoppingListId shoppingListId, SectionId sectionId) { Message = $"Section {sectionId} is already part of shopping list {shoppingListId}."; } public string Message { get; } public ErrorReasonCode ErrorCode => ErrorReasonCode.SectionAlreadyInShoppingList; } }
36.882353
101
0.751196
[ "MIT" ]
Velociraptor45/ProjectHermes-ShoppingList
Api/ShoppingList.Api.Domain/Common/Exceptions/Reason/SectionAlreadyInShoppingListReason.cs
629
C#
// Instance generated by TankLibHelper.InstanceBuilder // ReSharper disable All namespace TankLib.STU.Types { [STUAttribute(0x1ABBAD1D)] public class STU_1ABBAD1D : STU_C7C085F6 { [STUFieldAttribute(0xB91CFF97, "m_base")] public teStructuredDataAssetRef<ulong> m_base; [STUFieldAttribute(0xAB4E1359)] public teStructuredDataAssetRef<ulong> m_AB4E1359; [STUFieldAttribute(0x37D84DA4)] public teStructuredDataAssetRef<ulong> m_37D84DA4; [STUFieldAttribute(0x5620DA50, "m_globalWeightMultipliers", ReaderType = typeof(InlineInstanceFieldReader))] public STUAnimGlobalWeightMultipliers m_globalWeightMultipliers; [STUFieldAttribute(0xEC42051A, "m_userWeights", ReaderType = typeof(InlineInstanceFieldReader))] public STUAnimUserWeights m_userWeights; [STUFieldAttribute(0xF0E4656D, "m_globalLayerMultipliers", ReaderType = typeof(InlineInstanceFieldReader))] public STUAnimGlobalLayerMultipliers m_globalLayerMultipliers; [STUFieldAttribute(0xDF9357CF)] public float m_DF9357CF; [STUFieldAttribute(0xE8502460)] public float m_E8502460; [STUFieldAttribute(0x83CE3EB5)] public float m_83CE3EB5; } }
35.942857
116
0.740859
[ "MIT" ]
ekin1106/OWLib
TankLib/STU/Types/STU_1ABBAD1D.cs
1,258
C#
/* Generated SBE (Simple Binary Encoding) message codec */ using System; using System.Text; using System.Collections.Generic; using Adaptive.Agrona; namespace Adaptive.Cluster.Codecs { public class ClusterMembersChangeEncoder { public const ushort BLOCK_LENGTH = 12; public const ushort TEMPLATE_ID = 71; public const ushort SCHEMA_ID = 111; public const ushort SCHEMA_VERSION = 6; private ClusterMembersChangeEncoder _parentMessage; private IMutableDirectBuffer _buffer; protected int _offset; protected int _limit; public ClusterMembersChangeEncoder() { _parentMessage = this; } public ushort SbeBlockLength() { return BLOCK_LENGTH; } public ushort SbeTemplateId() { return TEMPLATE_ID; } public ushort SbeSchemaId() { return SCHEMA_ID; } public ushort SbeSchemaVersion() { return SCHEMA_VERSION; } public string SbeSemanticType() { return ""; } public IMutableDirectBuffer Buffer() { return _buffer; } public int Offset() { return _offset; } public ClusterMembersChangeEncoder Wrap(IMutableDirectBuffer buffer, int offset) { this._buffer = buffer; this._offset = offset; Limit(offset + BLOCK_LENGTH); return this; } public ClusterMembersChangeEncoder WrapAndApplyHeader( IMutableDirectBuffer buffer, int offset, MessageHeaderEncoder headerEncoder) { headerEncoder .Wrap(buffer, offset) .BlockLength(BLOCK_LENGTH) .TemplateId(TEMPLATE_ID) .SchemaId(SCHEMA_ID) .Version(SCHEMA_VERSION); return Wrap(buffer, offset + MessageHeaderEncoder.ENCODED_LENGTH); } public int EncodedLength() { return _limit - _offset; } public int Limit() { return _limit; } public void Limit(int limit) { this._limit = limit; } public static int CorrelationIdEncodingOffset() { return 0; } public static int CorrelationIdEncodingLength() { return 8; } public static long CorrelationIdNullValue() { return -9223372036854775808L; } public static long CorrelationIdMinValue() { return -9223372036854775807L; } public static long CorrelationIdMaxValue() { return 9223372036854775807L; } public ClusterMembersChangeEncoder CorrelationId(long value) { _buffer.PutLong(_offset + 0, value, ByteOrder.LittleEndian); return this; } public static int LeaderMemberIdEncodingOffset() { return 8; } public static int LeaderMemberIdEncodingLength() { return 4; } public static int LeaderMemberIdNullValue() { return -2147483648; } public static int LeaderMemberIdMinValue() { return -2147483647; } public static int LeaderMemberIdMaxValue() { return 2147483647; } public ClusterMembersChangeEncoder LeaderMemberId(int value) { _buffer.PutInt(_offset + 8, value, ByteOrder.LittleEndian); return this; } public static int ActiveMembersId() { return 3; } public static string ActiveMembersCharacterEncoding() { return "US-ASCII"; } public static string ActiveMembersMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static int ActiveMembersHeaderLength() { return 4; } public ClusterMembersChangeEncoder PutActiveMembers(IDirectBuffer src, int srcOffset, int length) { if (length > 1073741824) { throw new InvalidOperationException("length > maxValue for type: " + length); } int headerLength = 4; int limit = _parentMessage.Limit(); _parentMessage.Limit(limit + headerLength + length); _buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian); _buffer.PutBytes(limit + headerLength, src, srcOffset, length); return this; } public ClusterMembersChangeEncoder PutActiveMembers(byte[] src, int srcOffset, int length) { if (length > 1073741824) { throw new InvalidOperationException("length > maxValue for type: " + length); } int headerLength = 4; int limit = _parentMessage.Limit(); _parentMessage.Limit(limit + headerLength + length); _buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian); _buffer.PutBytes(limit + headerLength, src, srcOffset, length); return this; } public ClusterMembersChangeEncoder ActiveMembers(string value) { int length = value.Length; if (length > 1073741824) { throw new InvalidOperationException("length > maxValue for type: " + length); } int headerLength = 4; int limit = _parentMessage.Limit(); _parentMessage.Limit(limit + headerLength + length); _buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian); _buffer.PutStringWithoutLengthAscii(limit + headerLength, value); return this; } public static int PassiveMembersId() { return 4; } public static string PassiveMembersCharacterEncoding() { return "US-ASCII"; } public static string PassiveMembersMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static int PassiveMembersHeaderLength() { return 4; } public ClusterMembersChangeEncoder PutPassiveMembers(IDirectBuffer src, int srcOffset, int length) { if (length > 1073741824) { throw new InvalidOperationException("length > maxValue for type: " + length); } int headerLength = 4; int limit = _parentMessage.Limit(); _parentMessage.Limit(limit + headerLength + length); _buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian); _buffer.PutBytes(limit + headerLength, src, srcOffset, length); return this; } public ClusterMembersChangeEncoder PutPassiveMembers(byte[] src, int srcOffset, int length) { if (length > 1073741824) { throw new InvalidOperationException("length > maxValue for type: " + length); } int headerLength = 4; int limit = _parentMessage.Limit(); _parentMessage.Limit(limit + headerLength + length); _buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian); _buffer.PutBytes(limit + headerLength, src, srcOffset, length); return this; } public ClusterMembersChangeEncoder PassiveMembers(string value) { int length = value.Length; if (length > 1073741824) { throw new InvalidOperationException("length > maxValue for type: " + length); } int headerLength = 4; int limit = _parentMessage.Limit(); _parentMessage.Limit(limit + headerLength + length); _buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian); _buffer.PutStringWithoutLengthAscii(limit + headerLength, value); return this; } public override string ToString() { return AppendTo(new StringBuilder(100)).ToString(); } public StringBuilder AppendTo(StringBuilder builder) { ClusterMembersChangeDecoder writer = new ClusterMembersChangeDecoder(); writer.Wrap(_buffer, _offset, BLOCK_LENGTH, SCHEMA_VERSION); return writer.AppendTo(builder); } } }
25.051205
102
0.633882
[ "Apache-2.0" ]
23dproject/Aeron.NET
src/Adaptive.Cluster/Codecs/ClusterMembersChangeEncoder.cs
8,317
C#
// Copyright (c) Peter Vrenken. All rights reserved. See the license on https://github.com/vrenken/EtAlii.Ubigia namespace EtAlii.Ubigia.Api.Functional.Context { internal interface IMutationValueProcessor : IFragmentProcessor<ValueFragment> { } }
29
113
0.762452
[ "MIT" ]
vrenken/EtAlii.Ubigia
Source/Api/EtAlii.Ubigia.Api.Functional/Context/3. Processing/Mutations/Values/IMutationValueProcessor.cs
263
C#
#region Apache License Version 2.0 /*---------------------------------------------------------------- Copyright 2021 Jeffrey Su & Suzhou Senparc Network Technology Co.,Ltd. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Detail: https://github.com/JeffreySu/WeiXinMPSDK/blob/master/license.md ----------------------------------------------------------------*/ #endregion Apache License Version 2.0 /*---------------------------------------------------------------- Copyright (C) 2021 Senparc 文件名:QueryUserAuthorizationReturnJson.cs 文件功能描述:商圈积分授权查询返回Json类 创建标识:Senparc - 20210925 ----------------------------------------------------------------*/ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Senparc.Weixin.TenPayV3.Apis.Entities; namespace Senparc.Weixin.TenPayV3.Apis.BusinessCircle { /// <summary> /// 商圈积分授权查询返回Json类 /// <para>详细请参考微信支付官方文档 https://pay.weixin.qq.com/wiki/doc/apiv3/apis/chapter8_6_4.shtml </para> /// </summary> public class QueryUserAuthorizationReturnJson : ReturnJsonBase { /// <summary> /// 含参构造函数 /// </summary> /// <param name="openid">顾客openid <para>顾客授权时使用的小程序上的openid</para><para>示例值:oWmnN4xxxxxxxxxxe92NHIGf1xd8</para></param> /// <param name="authorize_state">授权状态 <para>顾客授权商圈积分结果UNAUTHORIZED:未授权AUTHORIZED:已授权DEAUTHORIZED:已取消授权</para><para>示例值:UNAUTHORIZED</para></param> /// <param name="authorize_time">授权时间 <para>顾客成功授权商圈积分的时间,遵循rfc3339标准格式,格式为YYYY-MM-DDTHH:mm:ss+TIMEZONE,YYYY-MM-DD表示年月日,T出现在字符串中,表示time元素的开头,HH:mm:ss表示时分秒毫秒,TIMEZONE表示时区(+08:00表示东八区时间,领先UTC8小时,即北京时间)。例如:2015-05-20T13:29:35+08:00表示北京时间2015年05月20日13点29分35秒(需要增加所有跟时间有关的参数的描述)</para><para>示例值:2020-05-20T13:29:35+08:00</para><para>可为null</para></param> /// <param name="deauthorize_time">取消授权时间 <para>顾客关闭授权商圈积分的时间,遵循rfc3339标准格式,格式为YYYY-MM-DDTHH:mm:ss+TIMEZONE,YYYY-MM-DD表示年月日,T出现在字符串中,表示time元素的开头,HH:mm:ss表示时分秒毫秒,TIMEZONE表示时区(+08:00表示东八区时间,领先UTC8小时,即北京时间)。例如:2015-05-20T13:29:35+08:00表示北京时间2015年05月20日13点29分35秒(需要增加所有跟时间有关的参数的描述)</para><para>示例值:2020-05-20T13:29:35+08:00</para><para>可为null</para></param> public QueryUserAuthorizationReturnJson(string openid, string authorize_state, string authorize_time, string deauthorize_time) { this.openid = openid; this.authorize_state = authorize_state; this.authorize_time = authorize_time; this.deauthorize_time = deauthorize_time; } /// <summary> /// 无参构造函数 /// </summary> public QueryUserAuthorizationReturnJson() { } /// <summary> /// 顾客openid /// <para>顾客授权时使用的小程序上的openid </para> /// <para>示例值:oWmnN4xxxxxxxxxxe92NHIGf1xd8</para> /// </summary> public string openid { get; set; } /// <summary> /// 授权状态 /// <para>顾客授权商圈积分结果 UNAUTHORIZED:未授权 AUTHORIZED:已授权 DEAUTHORIZED:已取消授权 </para> /// <para>示例值:UNAUTHORIZED</para> /// </summary> public string authorize_state { get; set; } /// <summary> /// 授权时间 /// <para>顾客成功授权商圈积分的时间,遵循rfc3339标准格式,格式为YYYY-MM-DDTHH:mm:ss+TIMEZONE,YYYY-MM-DD表示年月日,T出现在字符串中,表示time元素的开头,HH:mm:ss表示时分秒毫秒,TIMEZONE表示时区(+08:00表示东八区时间,领先UTC 8小时,即北京时间)。例如:2015-05-20T13:29:35+08:00表示北京时间2015年05月20日13点29分35秒(需要增加所有跟时间有关的参数的描述) </para> /// <para>示例值:2020-05-20T13:29:35+08:00</para> /// <para>可为null</para> /// </summary> public string authorize_time { get; set; } /// <summary> /// 取消授权时间 /// <para>顾客关闭授权商圈积分的时间,遵循rfc3339标准格式,格式为YYYY-MM-DDTHH:mm:ss+TIMEZONE,YYYY-MM-DD表示年月日,T出现在字符串中,表示time元素的开头,HH:mm:ss表示时分秒毫秒,TIMEZONE表示时区(+08:00表示东八区时间,领先UTC 8小时,即北京时间)。例如:2015-05-20T13:29:35+08:00表示北京时间2015年05月20日13点29分35秒(需要增加所有跟时间有关的参数的描述) </para> /// <para>示例值:2020-05-20T13:29:35+08:00</para> /// <para>可为null</para> /// </summary> public string deauthorize_time { get; set; } } }
43.371429
361
0.651735
[ "Apache-2.0" ]
554393109/WeiXinMPSDK
src/Senparc.Weixin.TenPay/Senparc.Weixin.TenPayV3/Apis/BusinessCircle/Entities/ReturnJson/QueryUserAuthorizationReturnJson.cs
5,878
C#
// !! // FoxSsh - https://github.com/FoxCouncil/FoxSsh // *.-". // MIT License // | | // Copyright 2021 The Fox Council using System.Collections.Generic; namespace FoxSsh.Common.Messages { public class ServiceAcceptMessage : ISshMessage { public SshMessageType Type => SshMessageType.ServiceAccept; public IReadOnlyCollection<byte> Raw { get; set; } public string Name { get; set; } public void LoadRawData(SshDataStream stream) { } public void WriteRawData(SshDataStream stream) { stream.WriteAscii(Name); } } }
25.166667
67
0.635762
[ "MIT" ]
FoxCouncil/FoxSsh
FoxSsh/Common/Messages/ServiceAcceptMessage.cs
606
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("Countdown.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Countdown.Tests")] [assembly: AssemblyCopyright("Copyright © 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("5f640195-bb9b-479c-b925-c2921b7dc5fb")] // 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.783784
84
0.747496
[ "MIT" ]
geegee4iee/countdown
Countdown.Tests/Properties/AssemblyInfo.cs
1,401
C#
namespace ClassLib062 { public class Class034 { public static string Property => "ClassLib062"; } }
15
55
0.633333
[ "MIT" ]
333fred/performance
src/scenarios/weblarge2.0/src/ClassLib062/Class034.cs
120
C#
namespace Core.UX { partial class ContrastColourGenerator { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ContrastColourGenerator)); this.kryptonPanel1 = new ComponentFactory.Krypton.Toolkit.KryptonPanel(); this.kchkKeepOpacityValues = new ComponentFactory.Krypton.Toolkit.KryptonCheckBox(); this.kchkAutomateColourContrastValues = new ComponentFactory.Krypton.Toolkit.KryptonCheckBox(); this.kbtnOk = new ComponentFactory.Krypton.Toolkit.KryptonButton(); this.pictureBox1 = new System.Windows.Forms.PictureBox(); this.kryptonPanel2 = new ComponentFactory.Krypton.Toolkit.KryptonPanel(); this.kbtnUtiliseContrastColour = new ComponentFactory.Krypton.Toolkit.KryptonButton(); this.kbtnUtiliseBaseColour = new ComponentFactory.Krypton.Toolkit.KryptonButton(); this.kryptonButton1 = new ComponentFactory.Krypton.Toolkit.KryptonButton(); this.kryptonButton3 = new ComponentFactory.Krypton.Toolkit.KryptonButton(); this.kryptonButton4 = new ComponentFactory.Krypton.Toolkit.KryptonButton(); this.kbtnGenerateBaseAlphaValue = new ComponentFactory.Krypton.Toolkit.KryptonButton(); this.kbtnInvertColours = new ComponentFactory.Krypton.Toolkit.KryptonButton(); this.kbtnGenerateComplementaryColour = new ComponentFactory.Krypton.Toolkit.KryptonButton(); this.kbtnGenerateBlueValue = new ComponentFactory.Krypton.Toolkit.KryptonButton(); this.kbtnGenerateGreenValue = new ComponentFactory.Krypton.Toolkit.KryptonButton(); this.kbtnGenerateRedValue = new ComponentFactory.Krypton.Toolkit.KryptonButton(); this.knumContrastAlphaChannelValue = new ComponentFactory.Krypton.Toolkit.KryptonNumericUpDown(); this.kryptonLabel5 = new ComponentFactory.Krypton.Toolkit.KryptonLabel(); this.knumContrastBlueChannelValue = new ComponentFactory.Krypton.Toolkit.KryptonNumericUpDown(); this.knumContrastGreenChannelValue = new ComponentFactory.Krypton.Toolkit.KryptonNumericUpDown(); this.knumContrastRedChannelValue = new ComponentFactory.Krypton.Toolkit.KryptonNumericUpDown(); this.kryptonLabel6 = new ComponentFactory.Krypton.Toolkit.KryptonLabel(); this.kryptonLabel7 = new ComponentFactory.Krypton.Toolkit.KryptonLabel(); this.kryptonLabel8 = new ComponentFactory.Krypton.Toolkit.KryptonLabel(); this.knumBaseAlphaChannelValue = new ComponentFactory.Krypton.Toolkit.KryptonNumericUpDown(); this.kryptonLabel10 = new ComponentFactory.Krypton.Toolkit.KryptonLabel(); this.knumBaseBlueChannelValue = new ComponentFactory.Krypton.Toolkit.KryptonNumericUpDown(); this.knumBaseGreenChannelValue = new ComponentFactory.Krypton.Toolkit.KryptonNumericUpDown(); this.knumBaseRedChannelValue = new ComponentFactory.Krypton.Toolkit.KryptonNumericUpDown(); this.kryptonLabel4 = new ComponentFactory.Krypton.Toolkit.KryptonLabel(); this.kryptonLabel3 = new ComponentFactory.Krypton.Toolkit.KryptonLabel(); this.kryptonLabel2 = new ComponentFactory.Krypton.Toolkit.KryptonLabel(); this.kryptonLabel1 = new ComponentFactory.Krypton.Toolkit.KryptonLabel(); this.cpbContrastColour = new ExtendedControls.ExtendedToolkit.Controls.CircularPictureBox(); this.cpbBaseColour = new ExtendedControls.ExtendedToolkit.Controls.CircularPictureBox(); this.kryptonLabel12 = new ComponentFactory.Krypton.Toolkit.KryptonLabel(); this.tmrUpdateUI = new System.Windows.Forms.Timer(this.components); this.ttInformation = new System.Windows.Forms.ToolTip(this.components); ((System.ComponentModel.ISupportInitialize)(this.kryptonPanel1)).BeginInit(); this.kryptonPanel1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.kryptonPanel2)).BeginInit(); this.kryptonPanel2.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.cpbContrastColour)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.cpbBaseColour)).BeginInit(); this.SuspendLayout(); // // kryptonPanel1 // this.kryptonPanel1.Controls.Add(this.kchkKeepOpacityValues); this.kryptonPanel1.Controls.Add(this.kchkAutomateColourContrastValues); this.kryptonPanel1.Controls.Add(this.kbtnOk); this.kryptonPanel1.Dock = System.Windows.Forms.DockStyle.Bottom; this.kryptonPanel1.Location = new System.Drawing.Point(0, 560); this.kryptonPanel1.Name = "kryptonPanel1"; this.kryptonPanel1.Size = new System.Drawing.Size(879, 52); this.kryptonPanel1.TabIndex = 0; // // kchkKeepOpacityValues // this.kchkKeepOpacityValues.Location = new System.Drawing.Point(286, 14); this.kchkKeepOpacityValues.Name = "kchkKeepOpacityValues"; this.kchkKeepOpacityValues.Size = new System.Drawing.Size(174, 26); this.kchkKeepOpacityValues.StateCommon.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.kchkKeepOpacityValues.TabIndex = 94; this.kchkKeepOpacityValues.Values.Text = "Keep &Opacity Values"; // // kchkAutomateColourContrastValues // this.kchkAutomateColourContrastValues.Location = new System.Drawing.Point(12, 14); this.kchkAutomateColourContrastValues.Name = "kchkAutomateColourContrastValues"; this.kchkAutomateColourContrastValues.Size = new System.Drawing.Size(268, 26); this.kchkAutomateColourContrastValues.StateCommon.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.kchkAutomateColourContrastValues.TabIndex = 93; this.kchkAutomateColourContrastValues.Values.Text = "&Automate Colour Contrast Values"; // // kbtnOk // this.kbtnOk.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.kbtnOk.AutoSize = true; this.kbtnOk.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.kbtnOk.Location = new System.Drawing.Point(835, 10); this.kbtnOk.Name = "kbtnOk"; this.kbtnOk.Size = new System.Drawing.Size(32, 30); this.kbtnOk.StateCommon.Content.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.kbtnOk.TabIndex = 92; this.kbtnOk.Values.Text = "&Ok"; // // pictureBox1 // this.pictureBox1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64))))); this.pictureBox1.Dock = System.Windows.Forms.DockStyle.Bottom; this.pictureBox1.Location = new System.Drawing.Point(0, 558); this.pictureBox1.Name = "pictureBox1"; this.pictureBox1.Size = new System.Drawing.Size(879, 2); this.pictureBox1.TabIndex = 1; this.pictureBox1.TabStop = false; // // kryptonPanel2 // this.kryptonPanel2.Controls.Add(this.kbtnUtiliseContrastColour); this.kryptonPanel2.Controls.Add(this.kbtnUtiliseBaseColour); this.kryptonPanel2.Controls.Add(this.kryptonButton1); this.kryptonPanel2.Controls.Add(this.kryptonButton3); this.kryptonPanel2.Controls.Add(this.kryptonButton4); this.kryptonPanel2.Controls.Add(this.kbtnGenerateBaseAlphaValue); this.kryptonPanel2.Controls.Add(this.kbtnInvertColours); this.kryptonPanel2.Controls.Add(this.kbtnGenerateComplementaryColour); this.kryptonPanel2.Controls.Add(this.kbtnGenerateBlueValue); this.kryptonPanel2.Controls.Add(this.kbtnGenerateGreenValue); this.kryptonPanel2.Controls.Add(this.kbtnGenerateRedValue); this.kryptonPanel2.Controls.Add(this.knumContrastAlphaChannelValue); this.kryptonPanel2.Controls.Add(this.kryptonLabel5); this.kryptonPanel2.Controls.Add(this.knumContrastBlueChannelValue); this.kryptonPanel2.Controls.Add(this.knumContrastGreenChannelValue); this.kryptonPanel2.Controls.Add(this.knumContrastRedChannelValue); this.kryptonPanel2.Controls.Add(this.kryptonLabel6); this.kryptonPanel2.Controls.Add(this.kryptonLabel7); this.kryptonPanel2.Controls.Add(this.kryptonLabel8); this.kryptonPanel2.Controls.Add(this.knumBaseAlphaChannelValue); this.kryptonPanel2.Controls.Add(this.kryptonLabel10); this.kryptonPanel2.Controls.Add(this.knumBaseBlueChannelValue); this.kryptonPanel2.Controls.Add(this.knumBaseGreenChannelValue); this.kryptonPanel2.Controls.Add(this.knumBaseRedChannelValue); this.kryptonPanel2.Controls.Add(this.kryptonLabel4); this.kryptonPanel2.Controls.Add(this.kryptonLabel3); this.kryptonPanel2.Controls.Add(this.kryptonLabel2); this.kryptonPanel2.Controls.Add(this.kryptonLabel1); this.kryptonPanel2.Controls.Add(this.cpbContrastColour); this.kryptonPanel2.Controls.Add(this.cpbBaseColour); this.kryptonPanel2.Controls.Add(this.kryptonLabel12); this.kryptonPanel2.Dock = System.Windows.Forms.DockStyle.Fill; this.kryptonPanel2.Location = new System.Drawing.Point(0, 0); this.kryptonPanel2.Name = "kryptonPanel2"; this.kryptonPanel2.Size = new System.Drawing.Size(879, 558); this.kryptonPanel2.TabIndex = 2; // // kbtnUtiliseContrastColour // this.kbtnUtiliseContrastColour.AutoSize = true; this.kbtnUtiliseContrastColour.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.kbtnUtiliseContrastColour.Location = new System.Drawing.Point(580, 516); this.kbtnUtiliseContrastColour.Name = "kbtnUtiliseContrastColour"; this.kbtnUtiliseContrastColour.Size = new System.Drawing.Size(255, 30); this.kbtnUtiliseContrastColour.StateCommon.Content.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.kbtnUtiliseContrastColour.TabIndex = 93; this.ttInformation.SetToolTip(this.kbtnUtiliseContrastColour, "Utilise Contrast Colour for Palette Generation"); this.kbtnUtiliseContrastColour.Values.Text = "Utilise &Contrast Colour for Palette"; // // kbtnUtiliseBaseColour // this.kbtnUtiliseBaseColour.AutoSize = true; this.kbtnUtiliseBaseColour.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.kbtnUtiliseBaseColour.Location = new System.Drawing.Point(57, 516); this.kbtnUtiliseBaseColour.Name = "kbtnUtiliseBaseColour"; this.kbtnUtiliseBaseColour.Size = new System.Drawing.Size(227, 30); this.kbtnUtiliseBaseColour.StateCommon.Content.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.kbtnUtiliseBaseColour.TabIndex = 92; this.ttInformation.SetToolTip(this.kbtnUtiliseBaseColour, "Utilise Base Colour for Palette Generation"); this.kbtnUtiliseBaseColour.Values.Text = "Utilise &Base Colour for Palette"; this.kbtnUtiliseBaseColour.Click += new System.EventHandler(this.kbtnUtiliseBaseColour_Click); // // kryptonButton1 // this.kryptonButton1.AutoSize = true; this.kryptonButton1.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.kryptonButton1.Location = new System.Drawing.Point(740, 452); this.kryptonButton1.Name = "kryptonButton1"; this.kryptonButton1.Size = new System.Drawing.Size(114, 30); this.kryptonButton1.StateCommon.Content.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.kryptonButton1.TabIndex = 91; this.kryptonButton1.Values.Text = "Generate &Blue"; // // kryptonButton3 // this.kryptonButton3.AutoSize = true; this.kryptonButton3.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.kryptonButton3.Location = new System.Drawing.Point(740, 437); this.kryptonButton3.Name = "kryptonButton3"; this.kryptonButton3.Size = new System.Drawing.Size(126, 30); this.kryptonButton3.StateCommon.Content.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.kryptonButton3.TabIndex = 90; this.kryptonButton3.Values.Text = "Generate &Green"; // // kryptonButton4 // this.kryptonButton4.AutoSize = true; this.kryptonButton4.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.kryptonButton4.Location = new System.Drawing.Point(740, 393); this.kryptonButton4.Name = "kryptonButton4"; this.kryptonButton4.Size = new System.Drawing.Size(111, 30); this.kryptonButton4.StateCommon.Content.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.kryptonButton4.TabIndex = 89; this.kryptonButton4.Values.Text = "Generate &Red"; // // kbtnGenerateBaseAlphaValue // this.kbtnGenerateBaseAlphaValue.AutoSize = true; this.kbtnGenerateBaseAlphaValue.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.kbtnGenerateBaseAlphaValue.Location = new System.Drawing.Point(222, 348); this.kbtnGenerateBaseAlphaValue.Name = "kbtnGenerateBaseAlphaValue"; this.kbtnGenerateBaseAlphaValue.Size = new System.Drawing.Size(125, 30); this.kbtnGenerateBaseAlphaValue.StateCommon.Content.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.kbtnGenerateBaseAlphaValue.TabIndex = 88; this.kbtnGenerateBaseAlphaValue.Values.Text = "Generate &Alpha"; this.kbtnGenerateBaseAlphaValue.Click += new System.EventHandler(this.kbtnGenerateBaseAlphaValue_Click); // // kbtnInvertColours // this.kbtnInvertColours.AutoSize = true; this.kbtnInvertColours.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.kbtnInvertColours.Location = new System.Drawing.Point(430, 173); this.kbtnInvertColours.Name = "kbtnInvertColours"; this.kbtnInvertColours.Size = new System.Drawing.Size(36, 30); this.kbtnInvertColours.StateCommon.Content.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.kbtnInvertColours.TabIndex = 87; this.ttInformation.SetToolTip(this.kbtnInvertColours, "Inverse Colours"); this.kbtnInvertColours.Values.Text = "<&--"; this.kbtnInvertColours.Click += new System.EventHandler(this.kbtnInvertColours_Click); // // kbtnGenerateComplementaryColour // this.kbtnGenerateComplementaryColour.AutoSize = true; this.kbtnGenerateComplementaryColour.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.kbtnGenerateComplementaryColour.Location = new System.Drawing.Point(430, 109); this.kbtnGenerateComplementaryColour.Name = "kbtnGenerateComplementaryColour"; this.kbtnGenerateComplementaryColour.Size = new System.Drawing.Size(36, 30); this.kbtnGenerateComplementaryColour.StateCommon.Content.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.kbtnGenerateComplementaryColour.TabIndex = 86; this.ttInformation.SetToolTip(this.kbtnGenerateComplementaryColour, "Generate Contrast Colours"); this.kbtnGenerateComplementaryColour.Values.Text = "--&>"; this.kbtnGenerateComplementaryColour.Click += new System.EventHandler(this.kbtnGenerateComplementaryColour_Click); // // kbtnGenerateBlueValue // this.kbtnGenerateBlueValue.AutoSize = true; this.kbtnGenerateBlueValue.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.kbtnGenerateBlueValue.Location = new System.Drawing.Point(222, 452); this.kbtnGenerateBlueValue.Name = "kbtnGenerateBlueValue"; this.kbtnGenerateBlueValue.Size = new System.Drawing.Size(114, 30); this.kbtnGenerateBlueValue.StateCommon.Content.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.kbtnGenerateBlueValue.TabIndex = 85; this.kbtnGenerateBlueValue.Values.Text = "Generate &Blue"; this.kbtnGenerateBlueValue.Click += new System.EventHandler(this.kbtnGenerateBlueValue_Click); // // kbtnGenerateGreenValue // this.kbtnGenerateGreenValue.AutoSize = true; this.kbtnGenerateGreenValue.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.kbtnGenerateGreenValue.Location = new System.Drawing.Point(222, 437); this.kbtnGenerateGreenValue.Name = "kbtnGenerateGreenValue"; this.kbtnGenerateGreenValue.Size = new System.Drawing.Size(126, 30); this.kbtnGenerateGreenValue.StateCommon.Content.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.kbtnGenerateGreenValue.TabIndex = 84; this.kbtnGenerateGreenValue.Values.Text = "Generate &Green"; this.kbtnGenerateGreenValue.Click += new System.EventHandler(this.kbtnGenerateGreenValue_Click); // // kbtnGenerateRedValue // this.kbtnGenerateRedValue.AutoSize = true; this.kbtnGenerateRedValue.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.kbtnGenerateRedValue.Location = new System.Drawing.Point(222, 393); this.kbtnGenerateRedValue.Name = "kbtnGenerateRedValue"; this.kbtnGenerateRedValue.Size = new System.Drawing.Size(111, 30); this.kbtnGenerateRedValue.StateCommon.Content.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.kbtnGenerateRedValue.TabIndex = 83; this.kbtnGenerateRedValue.Values.Text = "Generate &Red"; this.kbtnGenerateRedValue.Click += new System.EventHandler(this.kbtnGenerateRedValue_Click); // // knumContrastAlphaChannelValue // this.knumContrastAlphaChannelValue.Location = new System.Drawing.Point(614, 348); this.knumContrastAlphaChannelValue.Maximum = new decimal(new int[] { 255, 0, 0, 0}); this.knumContrastAlphaChannelValue.Name = "knumContrastAlphaChannelValue"; this.knumContrastAlphaChannelValue.Size = new System.Drawing.Size(120, 28); this.knumContrastAlphaChannelValue.StateCommon.Content.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.knumContrastAlphaChannelValue.TabIndex = 82; this.knumContrastAlphaChannelValue.Value = new decimal(new int[] { 255, 0, 0, 0}); // // kryptonLabel5 // this.kryptonLabel5.Location = new System.Drawing.Point(546, 348); this.kryptonLabel5.Name = "kryptonLabel5"; this.kryptonLabel5.Size = new System.Drawing.Size(62, 26); this.kryptonLabel5.StateCommon.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.kryptonLabel5.TabIndex = 81; this.kryptonLabel5.Values.Text = "Alpha:"; // // knumContrastBlueChannelValue // this.knumContrastBlueChannelValue.Location = new System.Drawing.Point(614, 452); this.knumContrastBlueChannelValue.Maximum = new decimal(new int[] { 255, 0, 0, 0}); this.knumContrastBlueChannelValue.Name = "knumContrastBlueChannelValue"; this.knumContrastBlueChannelValue.Size = new System.Drawing.Size(120, 28); this.knumContrastBlueChannelValue.StateCommon.Back.Color1 = System.Drawing.Color.Blue; this.knumContrastBlueChannelValue.StateCommon.Content.Color1 = System.Drawing.Color.White; this.knumContrastBlueChannelValue.StateCommon.Content.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.knumContrastBlueChannelValue.TabIndex = 80; // // knumContrastGreenChannelValue // this.knumContrastGreenChannelValue.Location = new System.Drawing.Point(614, 437); this.knumContrastGreenChannelValue.Maximum = new decimal(new int[] { 255, 0, 0, 0}); this.knumContrastGreenChannelValue.Name = "knumContrastGreenChannelValue"; this.knumContrastGreenChannelValue.Size = new System.Drawing.Size(120, 28); this.knumContrastGreenChannelValue.StateCommon.Back.Color1 = System.Drawing.Color.Lime; this.knumContrastGreenChannelValue.StateCommon.Content.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.knumContrastGreenChannelValue.TabIndex = 79; // // knumContrastRedChannelValue // this.knumContrastRedChannelValue.Location = new System.Drawing.Point(614, 393); this.knumContrastRedChannelValue.Maximum = new decimal(new int[] { 255, 0, 0, 0}); this.knumContrastRedChannelValue.Name = "knumContrastRedChannelValue"; this.knumContrastRedChannelValue.Size = new System.Drawing.Size(120, 28); this.knumContrastRedChannelValue.StateCommon.Back.Color1 = System.Drawing.Color.Red; this.knumContrastRedChannelValue.StateCommon.Content.Color1 = System.Drawing.Color.White; this.knumContrastRedChannelValue.StateCommon.Content.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.knumContrastRedChannelValue.TabIndex = 78; // // kryptonLabel6 // this.kryptonLabel6.Location = new System.Drawing.Point(546, 482); this.kryptonLabel6.Name = "kryptonLabel6"; this.kryptonLabel6.Size = new System.Drawing.Size(50, 26); this.kryptonLabel6.StateCommon.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.kryptonLabel6.TabIndex = 77; this.kryptonLabel6.Values.Text = "Blue:"; // // kryptonLabel7 // this.kryptonLabel7.Location = new System.Drawing.Point(546, 437); this.kryptonLabel7.Name = "kryptonLabel7"; this.kryptonLabel7.Size = new System.Drawing.Size(62, 26); this.kryptonLabel7.StateCommon.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.kryptonLabel7.TabIndex = 76; this.kryptonLabel7.Values.Text = "Green:"; // // kryptonLabel8 // this.kryptonLabel8.Location = new System.Drawing.Point(546, 395); this.kryptonLabel8.Name = "kryptonLabel8"; this.kryptonLabel8.Size = new System.Drawing.Size(46, 26); this.kryptonLabel8.StateCommon.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.kryptonLabel8.TabIndex = 75; this.kryptonLabel8.Values.Text = "Red:"; // // knumBaseAlphaChannelValue // this.knumBaseAlphaChannelValue.Location = new System.Drawing.Point(96, 346); this.knumBaseAlphaChannelValue.Maximum = new decimal(new int[] { 255, 0, 0, 0}); this.knumBaseAlphaChannelValue.Name = "knumBaseAlphaChannelValue"; this.knumBaseAlphaChannelValue.Size = new System.Drawing.Size(120, 28); this.knumBaseAlphaChannelValue.StateCommon.Content.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.knumBaseAlphaChannelValue.TabIndex = 74; this.knumBaseAlphaChannelValue.Value = new decimal(new int[] { 255, 0, 0, 0}); // // kryptonLabel10 // this.kryptonLabel10.Location = new System.Drawing.Point(28, 346); this.kryptonLabel10.Name = "kryptonLabel10"; this.kryptonLabel10.Size = new System.Drawing.Size(62, 26); this.kryptonLabel10.StateCommon.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.kryptonLabel10.TabIndex = 73; this.kryptonLabel10.Values.Text = "Alpha:"; // // knumBaseBlueChannelValue // this.knumBaseBlueChannelValue.Location = new System.Drawing.Point(96, 478); this.knumBaseBlueChannelValue.Maximum = new decimal(new int[] { 255, 0, 0, 0}); this.knumBaseBlueChannelValue.Name = "knumBaseBlueChannelValue"; this.knumBaseBlueChannelValue.Size = new System.Drawing.Size(120, 28); this.knumBaseBlueChannelValue.StateCommon.Back.Color1 = System.Drawing.Color.Blue; this.knumBaseBlueChannelValue.StateCommon.Content.Color1 = System.Drawing.Color.White; this.knumBaseBlueChannelValue.StateCommon.Content.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.knumBaseBlueChannelValue.TabIndex = 72; // // knumBaseGreenChannelValue // this.knumBaseGreenChannelValue.Location = new System.Drawing.Point(96, 435); this.knumBaseGreenChannelValue.Maximum = new decimal(new int[] { 255, 0, 0, 0}); this.knumBaseGreenChannelValue.Name = "knumBaseGreenChannelValue"; this.knumBaseGreenChannelValue.Size = new System.Drawing.Size(120, 28); this.knumBaseGreenChannelValue.StateCommon.Back.Color1 = System.Drawing.Color.Lime; this.knumBaseGreenChannelValue.StateCommon.Content.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.knumBaseGreenChannelValue.TabIndex = 71; // // knumBaseRedChannelValue // this.knumBaseRedChannelValue.Location = new System.Drawing.Point(96, 391); this.knumBaseRedChannelValue.Maximum = new decimal(new int[] { 255, 0, 0, 0}); this.knumBaseRedChannelValue.Name = "knumBaseRedChannelValue"; this.knumBaseRedChannelValue.Size = new System.Drawing.Size(120, 28); this.knumBaseRedChannelValue.StateCommon.Back.Color1 = System.Drawing.Color.Red; this.knumBaseRedChannelValue.StateCommon.Content.Color1 = System.Drawing.Color.White; this.knumBaseRedChannelValue.StateCommon.Content.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.knumBaseRedChannelValue.TabIndex = 70; // // kryptonLabel4 // this.kryptonLabel4.Location = new System.Drawing.Point(28, 452); this.kryptonLabel4.Name = "kryptonLabel4"; this.kryptonLabel4.Size = new System.Drawing.Size(50, 26); this.kryptonLabel4.StateCommon.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.kryptonLabel4.TabIndex = 69; this.kryptonLabel4.Values.Text = "Blue:"; // // kryptonLabel3 // this.kryptonLabel3.Location = new System.Drawing.Point(28, 435); this.kryptonLabel3.Name = "kryptonLabel3"; this.kryptonLabel3.Size = new System.Drawing.Size(62, 26); this.kryptonLabel3.StateCommon.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.kryptonLabel3.TabIndex = 68; this.kryptonLabel3.Values.Text = "Green:"; // // kryptonLabel2 // this.kryptonLabel2.Location = new System.Drawing.Point(28, 393); this.kryptonLabel2.Name = "kryptonLabel2"; this.kryptonLabel2.Size = new System.Drawing.Size(46, 26); this.kryptonLabel2.StateCommon.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.kryptonLabel2.TabIndex = 67; this.kryptonLabel2.Values.Text = "Red:"; // // kryptonLabel1 // this.kryptonLabel1.Location = new System.Drawing.Point(633, 21); this.kryptonLabel1.Name = "kryptonLabel1"; this.kryptonLabel1.Size = new System.Drawing.Size(174, 33); this.kryptonLabel1.StateCommon.ShortText.Font = new System.Drawing.Font("Segoe UI", 15.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.kryptonLabel1.TabIndex = 66; this.kryptonLabel1.Values.Text = "Contrast Colour"; // // cpbContrastColour // this.cpbContrastColour.BackColor = System.Drawing.Color.Transparent; this.cpbContrastColour.Location = new System.Drawing.Point(598, 71); this.cpbContrastColour.Name = "cpbContrastColour"; this.cpbContrastColour.Size = new System.Drawing.Size(256, 256); this.cpbContrastColour.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize; this.cpbContrastColour.TabIndex = 65; this.cpbContrastColour.TabStop = false; this.cpbContrastColour.BackColorChanged += new System.EventHandler(this.cpbContrastColour_BackColorChanged); // // cpbBaseColour // this.cpbBaseColour.BackColor = System.Drawing.Color.Transparent; this.cpbBaseColour.Location = new System.Drawing.Point(28, 71); this.cpbBaseColour.Name = "cpbBaseColour"; this.cpbBaseColour.Size = new System.Drawing.Size(256, 256); this.cpbBaseColour.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize; this.cpbBaseColour.TabIndex = 3; this.cpbBaseColour.TabStop = false; this.cpbBaseColour.BackColorChanged += new System.EventHandler(this.cpbBaseColour_BackColorChanged); // // kryptonLabel12 // this.kryptonLabel12.Location = new System.Drawing.Point(82, 21); this.kryptonLabel12.Name = "kryptonLabel12"; this.kryptonLabel12.Size = new System.Drawing.Size(134, 33); this.kryptonLabel12.StateCommon.ShortText.Font = new System.Drawing.Font("Segoe UI", 15.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.kryptonLabel12.TabIndex = 64; this.kryptonLabel12.Values.Text = "Base Colour"; // // tmrUpdateUI // this.tmrUpdateUI.Enabled = true; this.tmrUpdateUI.Interval = 250; this.tmrUpdateUI.Tick += new System.EventHandler(this.tmrUpdateUI_Tick); // // ContrastColourGenerator // this.AcceptButton = this.kbtnOk; this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(879, 612); this.Controls.Add(this.kryptonPanel2); this.Controls.Add(this.pictureBox1); this.Controls.Add(this.kryptonPanel1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "ContrastColourGenerator"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Contrast Colour Generator"; this.TextExtra = "(Beta)"; this.Load += new System.EventHandler(this.ContrastColourGenerator_Load); ((System.ComponentModel.ISupportInitialize)(this.kryptonPanel1)).EndInit(); this.kryptonPanel1.ResumeLayout(false); this.kryptonPanel1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.kryptonPanel2)).EndInit(); this.kryptonPanel2.ResumeLayout(false); this.kryptonPanel2.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.cpbContrastColour)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.cpbBaseColour)).EndInit(); this.ResumeLayout(false); } #endregion private ComponentFactory.Krypton.Toolkit.KryptonPanel kryptonPanel1; private System.Windows.Forms.PictureBox pictureBox1; private ComponentFactory.Krypton.Toolkit.KryptonPanel kryptonPanel2; private ExtendedControls.ExtendedToolkit.Controls.CircularPictureBox cpbContrastColour; private ExtendedControls.ExtendedToolkit.Controls.CircularPictureBox cpbBaseColour; private ComponentFactory.Krypton.Toolkit.KryptonLabel kryptonLabel12; private ComponentFactory.Krypton.Toolkit.KryptonLabel kryptonLabel1; private ComponentFactory.Krypton.Toolkit.KryptonNumericUpDown knumContrastAlphaChannelValue; private ComponentFactory.Krypton.Toolkit.KryptonLabel kryptonLabel5; private ComponentFactory.Krypton.Toolkit.KryptonNumericUpDown knumContrastBlueChannelValue; private ComponentFactory.Krypton.Toolkit.KryptonNumericUpDown knumContrastGreenChannelValue; private ComponentFactory.Krypton.Toolkit.KryptonNumericUpDown knumContrastRedChannelValue; private ComponentFactory.Krypton.Toolkit.KryptonLabel kryptonLabel6; private ComponentFactory.Krypton.Toolkit.KryptonLabel kryptonLabel7; private ComponentFactory.Krypton.Toolkit.KryptonLabel kryptonLabel8; private ComponentFactory.Krypton.Toolkit.KryptonNumericUpDown knumBaseAlphaChannelValue; private ComponentFactory.Krypton.Toolkit.KryptonLabel kryptonLabel10; private ComponentFactory.Krypton.Toolkit.KryptonNumericUpDown knumBaseBlueChannelValue; private ComponentFactory.Krypton.Toolkit.KryptonNumericUpDown knumBaseGreenChannelValue; private ComponentFactory.Krypton.Toolkit.KryptonNumericUpDown knumBaseRedChannelValue; private ComponentFactory.Krypton.Toolkit.KryptonLabel kryptonLabel4; private ComponentFactory.Krypton.Toolkit.KryptonLabel kryptonLabel3; private ComponentFactory.Krypton.Toolkit.KryptonLabel kryptonLabel2; private ComponentFactory.Krypton.Toolkit.KryptonButton kbtnGenerateBaseAlphaValue; private ComponentFactory.Krypton.Toolkit.KryptonButton kbtnInvertColours; private ComponentFactory.Krypton.Toolkit.KryptonButton kbtnGenerateComplementaryColour; private ComponentFactory.Krypton.Toolkit.KryptonButton kbtnGenerateBlueValue; private ComponentFactory.Krypton.Toolkit.KryptonButton kbtnGenerateGreenValue; private ComponentFactory.Krypton.Toolkit.KryptonButton kbtnGenerateRedValue; private ComponentFactory.Krypton.Toolkit.KryptonButton kbtnOk; private ComponentFactory.Krypton.Toolkit.KryptonButton kryptonButton1; private ComponentFactory.Krypton.Toolkit.KryptonButton kryptonButton3; private ComponentFactory.Krypton.Toolkit.KryptonButton kryptonButton4; private System.Windows.Forms.Timer tmrUpdateUI; private ComponentFactory.Krypton.Toolkit.KryptonCheckBox kchkAutomateColourContrastValues; private ComponentFactory.Krypton.Toolkit.KryptonCheckBox kchkKeepOpacityValues; private ComponentFactory.Krypton.Toolkit.KryptonButton kbtnUtiliseContrastColour; private System.Windows.Forms.ToolTip ttInformation; private ComponentFactory.Krypton.Toolkit.KryptonButton kbtnUtiliseBaseColour; } }
65.242718
209
0.673438
[ "BSD-3-Clause" ]
Wagnerp/Krypton-Toolkit-Suite-Extended-NET-5.452
Source/Krypton Toolkit Suite Extended/Shared/Tooling/UX/Colours/ContrastColourGenerator.Designer.cs
40,322
C#
using System; using System.Collections.Generic; using System.ComponentModel; namespace InceptionCore { static class AnonymousTypeToDictionaryConverter { public static IDictionary<string, object> Convert(object values) { return Convert<object>(values); } public static IDictionary<string, T> Convert<T>(object values) { var result = new Dictionary<string, T>(); foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(values)) { result.Add(descriptor.Name, (T)descriptor.GetValue(values)); } return result; } } }
26.115385
91
0.618557
[ "BSD-2-Clause" ]
bradleyjford/inception
src/InceptionCore/AnonymousTypeToDictionaryConverter.cs
681
C#
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; namespace Dotmim.Sync { [DataContract(Name = "s"), Serializable] public class SyncSetup : IEquatable<SyncSetup> { /// <summary> /// Gets or Sets the tables involved in the sync /// </summary> [DataMember(Name = "tbls", IsRequired = false, EmitDefaultValue = false, Order = 1)] public SetupTables Tables { get; set; } /// <summary> /// Gets or Sets the filters involved in the sync /// </summary> [DataMember(Name = "fils", IsRequired = false, EmitDefaultValue = false, Order = 2)] public SetupFilters Filters { get; set; } /// <summary> /// Specify a prefix for naming stored procedure. Default is empty string /// </summary> [DataMember(Name = "spp", IsRequired = false, EmitDefaultValue = false, Order = 3)] public string StoredProceduresPrefix { get; set; } /// <summary> /// Specify a suffix for naming stored procedures. Default is empty string /// </summary> [DataMember(Name = "sps", IsRequired = false, EmitDefaultValue = false, Order = 4)] public string StoredProceduresSuffix { get; set; } /// <summary> /// Specify a prefix for naming stored procedure. Default is empty string /// </summary> [DataMember(Name = "tf", IsRequired = false, EmitDefaultValue = false, Order = 5)] public string TriggersPrefix { get; set; } /// <summary> /// Specify a suffix for naming stored procedures. Default is empty string /// </summary> [DataMember(Name = "ts", IsRequired = false, EmitDefaultValue = false, Order = 6)] public string TriggersSuffix { get; set; } /// <summary> /// Specify a prefix for naming tracking tables. Default is empty string /// </summary> [DataMember(Name = "ttp", IsRequired = false, EmitDefaultValue = false, Order = 7)] public string TrackingTablesPrefix { get; set; } /// <summary> /// Specify a suffix for naming tracking tables. /// </summary> [DataMember(Name = "tts", IsRequired = false, EmitDefaultValue = false, Order = 8)] public string TrackingTablesSuffix { get; set; } ///// <summary> ///// Gets or Sets the current Setup version. ///// </summary> //[DataMember(Name = "v", IsRequired = false, EmitDefaultValue = false, Order = 9)] //public string Version { get; set; } /// <summary> /// Create a list of tables to be added to the sync process /// </summary> public SyncSetup(IEnumerable<string> tables) : this() => this.Tables.AddRange(tables); /// <summary> /// ctor /// </summary> public SyncSetup() { this.Tables = new SetupTables(); this.Filters = new SetupFilters(); //this.Version = SyncVersion.Current.ToString(); } /// <summary> /// Check if Setup has tables /// </summary> public bool HasTables => this.Tables?.Count > 0; /// <summary> /// Check if Setup has at least one table with columns /// </summary> public bool HasColumns => this.Tables?.SelectMany(t => t.Columns).Count() > 0; // using SelectMany to get columns and not Collection<Column> /// <summary> /// Check if Setup has a table that has columns /// </summary> public bool HasTableWithColumns(string tableName) => this.Tables[tableName]?.Columns?.Count > 0; /// <summary> /// Check if two setups have the same local options /// </summary> public bool HasSameOptions(SyncSetup otherSetup) { if (otherSetup == null) return false; var sc = SyncGlobalization.DataSourceStringComparison; if (!string.Equals(this.StoredProceduresPrefix, otherSetup.StoredProceduresPrefix, sc) || !string.Equals(this.StoredProceduresSuffix, otherSetup.StoredProceduresSuffix, sc) || !string.Equals(this.TrackingTablesPrefix, otherSetup.TrackingTablesPrefix, sc) || !string.Equals(this.TrackingTablesSuffix, otherSetup.TrackingTablesSuffix, sc) || !string.Equals(this.TriggersPrefix, otherSetup.TriggersPrefix, sc) || !string.Equals(this.TriggersSuffix, otherSetup.TriggersSuffix, sc)) return false; return true; } /// <summary> /// Check if two setups have the same tables / filters structure /// </summary> public bool HasSameStructure(SyncSetup otherSetup) { if (otherSetup == null) return false; // Checking inner lists if (!this.Tables.CompareWith(otherSetup.Tables)) return false; if (!this.Filters.CompareWith(otherSetup.Filters)) return false; return true; } public bool EqualsByProperties(SyncSetup otherSetup) { if (otherSetup == null) return false; if (!HasSameOptions(otherSetup)) return false; if (!HasSameStructure(otherSetup)) return false; return true; } public override string ToString() => $"{this.Tables.Count} tables"; /// <summary> /// Gets a true boolean if other instance is defined as same based on all properties /// </summary> public bool Equals(SyncSetup other) => this.EqualsByProperties(other); /// <summary> /// Gets a true boolean if other instance is defined as same based on all properties /// </summary> public override bool Equals(object obj) => this.EqualsByProperties(obj as SyncSetup); public override int GetHashCode() => base.GetHashCode(); } }
36.830303
149
0.587132
[ "MIT" ]
Varamil/Dotmim.Sync
Projects/Dotmim.Sync.Core/Setup/SyncSetup.cs
6,079
C#
using NHapi.Base.Parser; using NHapi.Base; using NHapi.Base.Log; using System; using System.Collections.Generic; using NHapi.Model.V23.Segment; using NHapi.Model.V23.Datatype; using NHapi.Base.Model; namespace NHapi.Model.V23.Group { ///<summary> ///Represents the SRM_S03_LOCATION_RESOURCE 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: AIL (Appointment Information - Location Resource) </li> ///<li>1: APR (Appointment Preferences) optional </li> ///<li>2: NTE (Notes and comments segment) optional repeating</li> ///</ol> ///</summary> [Serializable] public class SRM_S03_LOCATION_RESOURCE : AbstractGroup { ///<summary> /// Creates a new SRM_S03_LOCATION_RESOURCE Group. ///</summary> public SRM_S03_LOCATION_RESOURCE(IGroup parent, IModelClassFactory factory) : base(parent, factory){ try { this.add(typeof(AIL), true, false); this.add(typeof(APR), false, false); this.add(typeof(NTE), false, true); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error creating SRM_S03_LOCATION_RESOURCE - this is probably a bug in the source code generator.", e); } } ///<summary> /// Returns AIL (Appointment Information - Location Resource) - creates it if necessary ///</summary> public AIL AIL { get{ AIL ret = null; try { ret = (AIL)this.GetStructure("AIL"); } 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 APR (Appointment Preferences) - creates it if necessary ///</summary> public APR APR { get{ APR ret = null; try { ret = (APR)this.GetStructure("APR"); } 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 first repetition of NTE (Notes and comments segment) - creates it if necessary ///</summary> public NTE GetNTE() { NTE ret = null; try { ret = (NTE)this.GetStructure("NTE"); } 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 a specific repetition of NTE /// * (Notes and comments segment) - creates it if necessary /// throws HL7Exception if the repetition requested is more than one /// greater than the number of existing repetitions. ///</summary> public NTE GetNTE(int rep) { return (NTE)this.GetStructure("NTE", rep); } /** * Returns the number of existing repetitions of NTE */ public int NTERepetitionsUsed { get{ int reps = -1; try { reps = this.GetAll("NTE").Length; } catch (HL7Exception e) { string message = "Unexpected error accessing data - this is probably a bug in the source code generator."; HapiLogFactory.GetHapiLog(GetType()).Error(message, e); throw new System.Exception(message); } return reps; } } /** * Enumerate over the NTE results */ public IEnumerable<NTE> NTEs { get { for (int rep = 0; rep < NTERepetitionsUsed; rep++) { yield return (NTE)this.GetStructure("NTE", rep); } } } ///<summary> ///Adds a new NTE ///</summary> public NTE AddNTE() { return this.AddStructure("NTE") as NTE; } ///<summary> ///Removes the given NTE ///</summary> public void RemoveNTE(NTE toRemove) { this.RemoveStructure("NTE", toRemove); } ///<summary> ///Removes the NTE at the given index ///</summary> public void RemoveNTEAt(int index) { this.RemoveRepetition("NTE", index); } } }
28.701987
164
0.643286
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
afaonline/nHapi
src/NHapi.Model.V23/Group/SRM_S03_LOCATION_RESOURCE.cs
4,334
C#
using MelonLoader; using System.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly: AssemblyTitle(Random_slowmo.BuildInfo.Name)] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany(Random_slowmo.BuildInfo.Company)] [assembly: AssemblyProduct(Random_slowmo.BuildInfo.Name)] [assembly: AssemblyCopyright("Created by " + Random_slowmo.BuildInfo.Author)] [assembly: AssemblyTrademark(Random_slowmo.BuildInfo.Company)] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] //[assembly: Guid("")] [assembly: AssemblyVersion(Random_slowmo.BuildInfo.Version)] [assembly: AssemblyFileVersion(Random_slowmo.BuildInfo.Version)] [assembly: NeutralResourcesLanguage("en")] [assembly: MelonInfo(typeof(Random_slowmo.RandomSlowmo), Random_slowmo.BuildInfo.Name, Random_slowmo.BuildInfo.Version, Random_slowmo.BuildInfo.Author, Random_slowmo.BuildInfo.DownloadLink)] // Create and Setup a MelonModGame to mark a Mod as Universal or Compatible with specific Games. // If no MelonModGameAttribute is found or any of the Values for any MelonModGame on the Mod is null or empty it will be assumed the Mod is Universal. // Values for MelonModGame can be found in the Game's app.info file or printed at the top of every log directly beneath the Unity version. [assembly: MelonGame(null, null)]
55.56
191
0.795536
[ "MIT" ]
extraes/Random_Slowmo
Properties/AssemblyInfo.cs
1,391
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Linq; using WinFormsMVC.Request; using WinFormsMVC.Request.Item; using WinFormsMVC.View; using WinFormsMVCUnitTest.Test.View; namespace WinFormsMVCUnitTest.Test.Services.Base.GivenFormsManagementTest.TestCase { [TestClass] public class SimplyConnectedGivenFormsUndoTest : SimplyConnectedGivenFormsTest { public SimplyConnectedGivenFormsUndoTest() { } protected override void AssertAction(Action<List<Command>, List<BaseForm>> modified, Action<IEnumerable<Command>, IEnumerable<BaseForm>> assert) { base.AssertMemorableAction(modified, assert); } [TestMethod, TestCategory("差分")] [DataTestMethod] [DataRow(null, null, null)] public virtual void CalledBySelf_RootInvoker(Action<List<Command>, List<BaseForm>> modified, Action<IEnumerable<Command>, IEnumerable<BaseForm>> assert, Action<IEnumerable<Command>, IEnumerable<BaseForm>> assert_undo) { TestActionMode = ActionMode.MEMORABLE_ACTION; base.CalledBySelf_RootInvoker(modified, assert); Define(ref assert_undo, (commands, forms) => { CommonCommandStatus.AssertUndoButNotTarget(); foreach (var form in forms) { Assert.AreEqual(DefaultBaseForm.Text, form.Text); } }); AssertUndo(assert_undo); } [TestMethod, TestCategory("差分")] [DataTestMethod] [DataRow(null, null, null)] public virtual void CalledByRootInvoker(Action<List<Command>, List<BaseForm>> modified, Action<IEnumerable<Command>, IEnumerable<BaseForm>> assert, Action<IEnumerable<Command>, IEnumerable<BaseForm>> assert_undo) { TestActionMode = ActionMode.MEMORABLE_ACTION; base.CalledByRootInvoker(modified, assert); Define(ref assert_undo, (commands, forms) => { CommonCommandStatus.AssertUndo(); foreach (var form in forms) { Assert.AreEqual(DefaultBaseForm.Text, form.Text); } }); AssertUndo(assert_undo); } [TestMethod, TestCategory("差分")] [DataTestMethod] [DataRow(null, null, null)] public virtual void CalledBySelf_LastInvoker(Action<List<Command>, List<BaseForm>> modified, Action<IEnumerable<Command>, IEnumerable<BaseForm>> assert, Action<IEnumerable<Command>, IEnumerable<BaseForm>> assert_undo) { TestActionMode = ActionMode.MEMORABLE_ACTION; base.CalledBySelf_LastInvoker(modified, assert); Define(ref assert_undo, (commands, forms) => { CommonCommandStatus.AssertUndoButNotTarget(); foreach (var form in forms) { Assert.AreEqual(DefaultBaseForm.Text, form.Text); } }); AssertUndo(assert_undo); } [TestMethod, TestCategory("差分")] [DataTestMethod] [DataRow(null, null, null)] public virtual void CalledByLastInvoker(Action<List<Command>, List<BaseForm>> modified, Action<IEnumerable<Command>, IEnumerable<BaseForm>> assert, Action<IEnumerable<Command>, IEnumerable<BaseForm>> assert_undo) { TestActionMode = ActionMode.MEMORABLE_ACTION; base.CalledByLastInvoker(modified, assert); Define(ref assert_undo, (commands, forms) => { CommonCommandStatus.AssertUndoButNotTarget(); foreach (var form in forms) { Assert.AreEqual(DefaultBaseForm.Text, form.Text); } }); AssertUndo(assert_undo); } [TestMethod, TestCategory("差分")] [DataTestMethod] [DataRow(null, null, null)] public virtual void CalledByFirstAndLastInvoker(Action<List<Command>, List<BaseForm>> modified, Action<IEnumerable<Command>, IEnumerable<BaseForm>> assert, Action<IEnumerable<Command>, IEnumerable<BaseForm>> assert_undo) { TestActionMode = ActionMode.MEMORABLE_ACTION; base.CalledByFirstAndLastInvoker(modified, assert); Define(ref assert_undo, (commands, forms) => { CommonCommandStatus.AssertUndo(); foreach (var form in forms) { Assert.AreEqual(DefaultBaseForm.Text, form.Text); } }); AssertUndo(assert_undo); } [TestMethod, TestCategory("差分")] [DataTestMethod] [DataRow(null, null, null)] public virtual void CalledByNullInvoker(Action<List<Command>, List<BaseForm>> modified, Action<IEnumerable<Command>, IEnumerable<BaseForm>> assert, Action<IEnumerable<Command>, IEnumerable<BaseForm>> assert_undo) { TestActionMode = ActionMode.MEMORABLE_ACTION; base.CalledByNullInvoker(modified, assert); Define(ref assert_undo, (commands, forms) => { CommonCommandStatus.AssertUndoButNotTarget(); foreach (var form in forms) { Assert.AreEqual(DefaultBaseForm.Text, form.Text); } }); AssertUndo(assert_undo); } [TestMethod, TestCategory("差分")] [DataTestMethod] [DataRow(null, null, null)] public virtual void RecursiveFromRootInvoker(Action<List<Command>, List<BaseForm>> modified, Action<IEnumerable<Command>, IEnumerable<BaseForm>> assert, Action<IEnumerable<Command>, IEnumerable<BaseForm>> assert_undo) { TestActionMode = ActionMode.MEMORABLE_ACTION; base.RecursiveFromRootInvoker(modified, assert); Define(ref assert_undo, (commands, forms) => { CommonCommandStatus.AssertUndo(); foreach (var form in forms) { Assert.AreEqual(DefaultBaseForm.Text, form.Text); } }); AssertUndo(assert_undo); } [TestMethod, TestCategory("差分")] [DataTestMethod] [DataRow(null, null, null)] public virtual void RecursiveFromLastInvoker(Action<List<Command>, List<BaseForm>> modified, Action<IEnumerable<Command>, IEnumerable<BaseForm>> assert, Action<IEnumerable<Command>, IEnumerable<BaseForm>> assert_undo) { TestActionMode = ActionMode.MEMORABLE_ACTION; base.RecursiveFromLastInvoker(modified, assert); Define(ref assert_undo, (commands, forms) => { CommonCommandStatus.AssertUndoButNotTarget(); foreach (var form in forms) { Assert.AreEqual(DefaultBaseForm.Text, form.Text); } }); AssertUndo(assert_undo); } [TestMethod, TestCategory("差分")] [DataTestMethod] [DataRow(null, null, null)] public virtual void ValidationError(Action<List<Command>, List<BaseForm>> modified, Action<IEnumerable<Command>, IEnumerable<BaseForm>> assert, Action<IEnumerable<Command>, IEnumerable<BaseForm>> assert_undo) { TestActionMode = ActionMode.MEMORABLE_ACTION; base.ValidationError(modified, assert); Define(ref assert_undo, (commands, forms) => { CommonCommandStatus.AssertValidationError(); foreach (var form in forms) { Assert.AreEqual(DefaultBaseForm.Text, form.Text); } }); AssertUndo(assert_undo); } [TestMethod, TestCategory("差分")] [DataTestMethod] [DataRow(null, null, null)] public virtual void ValidationNullCheck(Action<List<Command>, List<BaseForm>> modified, Action<IEnumerable<Command>, IEnumerable<BaseForm>> assert, Action<IEnumerable<Command>, IEnumerable<BaseForm>> assert_undo) { TestActionMode = ActionMode.MEMORABLE_ACTION; base.ValidationNullCheck(modified, assert); Define(ref assert_undo, (commands, forms) => { CommonCommandStatus.AssertNullValidating(); foreach (var form in forms) { Assert.AreEqual(DefaultBaseForm.Text, form.Text); } }); AssertUndo(assert_undo); } } }
33.612319
153
0.564514
[ "MIT" ]
belre/WinFormsMVC
WinFormsMVCUnitTest/Test/Services/Base/GivenFormsManagementTest/TestCase/SimplyConnectedGivenFormsUndoTest.cs
9,319
C#
using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using PureCloudPlatform.Client.V2.Client; namespace PureCloudPlatform.Client.V2.Model { /// <summary> /// IgnoredActivityCategories /// </summary> [DataContract] public partial class IgnoredActivityCategories : IEquatable<IgnoredActivityCategories> { /// <summary> /// Gets or Sets Values /// </summary> [JsonConverter(typeof(UpgradeSdkEnumConverter))] public enum ValuesEnum { /// <summary> /// Your SDK version is out of date and an unknown enum value was encountered. /// Please upgrade the SDK using the command "Upgrade-Package PureCloudApiSdk" /// in the Package Manager Console /// </summary> [EnumMember(Value = "OUTDATED_SDK_VERSION")] OutdatedSdkVersion, /// <summary> /// Enum Onqueuework for "OnQueueWork" /// </summary> [EnumMember(Value = "OnQueueWork")] Onqueuework, /// <summary> /// Enum Break for "Break" /// </summary> [EnumMember(Value = "Break")] Break, /// <summary> /// Enum Meal for "Meal" /// </summary> [EnumMember(Value = "Meal")] Meal, /// <summary> /// Enum Meeting for "Meeting" /// </summary> [EnumMember(Value = "Meeting")] Meeting, /// <summary> /// Enum Offqueuework for "OffQueueWork" /// </summary> [EnumMember(Value = "OffQueueWork")] Offqueuework, /// <summary> /// Enum Timeoff for "TimeOff" /// </summary> [EnumMember(Value = "TimeOff")] Timeoff, /// <summary> /// Enum Training for "Training" /// </summary> [EnumMember(Value = "Training")] Training, /// <summary> /// Enum Unavailable for "Unavailable" /// </summary> [EnumMember(Value = "Unavailable")] Unavailable, /// <summary> /// Enum Unscheduled for "Unscheduled" /// </summary> [EnumMember(Value = "Unscheduled")] Unscheduled } /// <summary> /// Initializes a new instance of the <see cref="IgnoredActivityCategories" /> class. /// </summary> /// <param name="Values">Activity categories list.</param> public IgnoredActivityCategories(List<ValuesEnum> Values = null) { this.Values = Values; } /// <summary> /// Activity categories list /// </summary> /// <value>Activity categories list</value> [DataMember(Name="values", EmitDefaultValue=false)] public List<ValuesEnum> Values { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class IgnoredActivityCategories {\n"); sb.Append(" Values: ").Append(Values).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as IgnoredActivityCategories); } /// <summary> /// Returns true if IgnoredActivityCategories instances are equal /// </summary> /// <param name="other">Instance of IgnoredActivityCategories to be compared</param> /// <returns>Boolean</returns> public bool Equals(IgnoredActivityCategories other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return true && ( this.Values == other.Values || this.Values != null && this.Values.SequenceEqual(other.Values) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.Values != null) hash = hash * 59 + this.Values.GetHashCode(); return hash; } } } }
30.376289
93
0.494994
[ "MIT" ]
nmusco/platform-client-sdk-dotnet
build/src/PureCloudPlatform.Client.V2/Model/IgnoredActivityCategories.cs
5,893
C#
/* The MIT License (MIT) * * Copyright (c) 2015 Marc Clifton * * 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 Clifton.Core.Workflow { /// <summary> /// Thread-specific instance that preserves the workflow continuation context for that thread. /// </summary> public class WorkflowContinuation<T> { public int WorkflowStep { get; set; } public bool Abort { get; set; } public bool Defer { get; set; } public bool Deferred { get; set; } public bool Done { get; set; } public Workflow<T> Workflow { get; protected set; } public WorkflowContinuation(Workflow<T> workflow) { Workflow = workflow; } } }
36.217391
95
0.744298
[ "MIT" ]
cliftonm/clifton
Clifton.Core/Clifton.Core.Workflow/WorkflowContinuation.cs
1,668
C#
/******************************************************************************* * Copyright 2012-2019 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. * ***************************************************************************** * * AWS Tools for Windows (TM) PowerShell (TM) * */ using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Text; using Amazon.PowerShell.Common; using Amazon.Runtime; using Amazon.ElasticBeanstalk; using Amazon.ElasticBeanstalk.Model; namespace Amazon.PowerShell.Cmdlets.EB { /// <summary> /// Update the list of tags applied to an AWS Elastic Beanstalk resource. Two lists can /// be passed: <code>TagsToAdd</code> for tags to add or update, and <code>TagsToRemove</code>. /// /// /// <para> /// Currently, Elastic Beanstalk only supports tagging of Elastic Beanstalk environments. /// For details about environment tagging, see <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/using-features.tagging.html">Tagging /// Resources in Your Elastic Beanstalk Environment</a>. /// </para><para> /// If you create a custom IAM user policy to control permission to this operation, specify /// one of the following two virtual actions (or both) instead of the API operation name: /// </para><dl><dt>elasticbeanstalk:AddTags</dt><dd><para> /// Controls permission to call <code>UpdateTagsForResource</code> and pass a list of /// tags to add in the <code>TagsToAdd</code> parameter. /// </para></dd><dt>elasticbeanstalk:RemoveTags</dt><dd><para> /// Controls permission to call <code>UpdateTagsForResource</code> and pass a list of /// tag keys to remove in the <code>TagsToRemove</code> parameter. /// </para></dd></dl><para> /// For details about creating a custom user policy, see <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/AWSHowTo.iam.managed-policies.html#AWSHowTo.iam.policies">Creating /// a Custom User Policy</a>. /// </para> /// </summary> [Cmdlet("Update", "EBResourceTag", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.Medium)] [OutputType("None")] [AWSCmdlet("Calls the AWS Elastic Beanstalk UpdateTagsForResource API operation.", Operation = new[] {"UpdateTagsForResource"}, SelectReturnType = typeof(Amazon.ElasticBeanstalk.Model.UpdateTagsForResourceResponse))] [AWSCmdletOutput("None or Amazon.ElasticBeanstalk.Model.UpdateTagsForResourceResponse", "This cmdlet does not generate any output." + "The service response (type Amazon.ElasticBeanstalk.Model.UpdateTagsForResourceResponse) can be referenced from properties attached to the cmdlet entry in the $AWSHistory stack." )] public partial class UpdateEBResourceTagCmdlet : AmazonElasticBeanstalkClientCmdlet, IExecutor { #region Parameter ResourceArn /// <summary> /// <para> /// <para>The Amazon Resource Name (ARN) of the resouce to be updated.</para><para>Must be the ARN of an Elastic Beanstalk environment.</para> /// </para> /// </summary> #if !MODULAR [System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true)] #else [System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true, Mandatory = true)] [System.Management.Automation.AllowEmptyString] [System.Management.Automation.AllowNull] #endif [Amazon.PowerShell.Common.AWSRequiredParameter] public System.String ResourceArn { get; set; } #endregion #region Parameter TagsToAdd /// <summary> /// <para> /// <para>A list of tags to add or update.</para><para>If a key of an existing tag is added, the tag's value is updated.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public Amazon.ElasticBeanstalk.Model.Tag[] TagsToAdd { get; set; } #endregion #region Parameter TagsToRemove /// <summary> /// <para> /// <para>A list of tag keys to remove.</para><para>If a tag key doesn't exist, it is silently ignored.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public System.String[] TagsToRemove { get; set; } #endregion #region Parameter Select /// <summary> /// Use the -Select parameter to control the cmdlet output. The cmdlet doesn't have a return value by default. /// Specifying -Select '*' will result in the cmdlet returning the whole service response (Amazon.ElasticBeanstalk.Model.UpdateTagsForResourceResponse). /// Specifying -Select '^ParameterName' will result in the cmdlet returning the selected cmdlet parameter value. /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public string Select { get; set; } = "*"; #endregion #region Parameter PassThru /// <summary> /// Changes the cmdlet behavior to return the value passed to the ResourceArn parameter. /// The -PassThru parameter is deprecated, use -Select '^ResourceArn' instead. This parameter will be removed in a future version. /// </summary> [System.Obsolete("The -PassThru parameter is deprecated, use -Select '^ResourceArn' instead. This parameter will be removed in a future version.")] [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter PassThru { get; set; } #endregion #region Parameter Force /// <summary> /// This parameter overrides confirmation prompts to force /// the cmdlet to continue its operation. This parameter should always /// be used with caution. /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter Force { get; set; } #endregion protected override void ProcessRecord() { base.ProcessRecord(); var resourceIdentifiersText = FormatParameterValuesForConfirmationMsg(nameof(this.ResourceArn), MyInvocation.BoundParameters); if (!ConfirmShouldProceed(this.Force.IsPresent, resourceIdentifiersText, "Update-EBResourceTag (UpdateTagsForResource)")) { return; } var context = new CmdletContext(); // allow for manipulation of parameters prior to loading into context PreExecutionContextLoad(context); #pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute if (ParameterWasBound(nameof(this.Select))) { context.Select = CreateSelectDelegate<Amazon.ElasticBeanstalk.Model.UpdateTagsForResourceResponse, UpdateEBResourceTagCmdlet>(Select) ?? throw new System.ArgumentException("Invalid value for -Select parameter.", nameof(this.Select)); if (this.PassThru.IsPresent) { throw new System.ArgumentException("-PassThru cannot be used when -Select is specified.", nameof(this.Select)); } } else if (this.PassThru.IsPresent) { context.Select = (response, cmdlet) => this.ResourceArn; } #pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute context.ResourceArn = this.ResourceArn; #if MODULAR if (this.ResourceArn == null && ParameterWasBound(nameof(this.ResourceArn))) { WriteWarning("You are passing $null as a value for parameter ResourceArn which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues."); } #endif if (this.TagsToAdd != null) { context.TagsToAdd = new List<Amazon.ElasticBeanstalk.Model.Tag>(this.TagsToAdd); } if (this.TagsToRemove != null) { context.TagsToRemove = new List<System.String>(this.TagsToRemove); } // allow further manipulation of loaded context prior to processing PostExecutionContextLoad(context); var output = Execute(context) as CmdletOutput; ProcessOutput(output); } #region IExecutor Members public object Execute(ExecutorContext context) { var cmdletContext = context as CmdletContext; // create request var request = new Amazon.ElasticBeanstalk.Model.UpdateTagsForResourceRequest(); if (cmdletContext.ResourceArn != null) { request.ResourceArn = cmdletContext.ResourceArn; } if (cmdletContext.TagsToAdd != null) { request.TagsToAdd = cmdletContext.TagsToAdd; } if (cmdletContext.TagsToRemove != null) { request.TagsToRemove = cmdletContext.TagsToRemove; } CmdletOutput output; // issue call var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint); try { var response = CallAWSServiceOperation(client, request); object pipelineOutput = null; pipelineOutput = cmdletContext.Select(response, this); output = new CmdletOutput { PipelineOutput = pipelineOutput, ServiceResponse = response }; } catch (Exception e) { output = new CmdletOutput { ErrorResponse = e }; } return output; } public ExecutorContext CreateContext() { return new CmdletContext(); } #endregion #region AWS Service Operation Call private Amazon.ElasticBeanstalk.Model.UpdateTagsForResourceResponse CallAWSServiceOperation(IAmazonElasticBeanstalk client, Amazon.ElasticBeanstalk.Model.UpdateTagsForResourceRequest request) { Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "AWS Elastic Beanstalk", "UpdateTagsForResource"); try { #if DESKTOP return client.UpdateTagsForResource(request); #elif CORECLR return client.UpdateTagsForResourceAsync(request).GetAwaiter().GetResult(); #else #error "Unknown build edition" #endif } catch (AmazonServiceException exc) { var webException = exc.InnerException as System.Net.WebException; if (webException != null) { throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException); } throw; } } #endregion internal partial class CmdletContext : ExecutorContext { public System.String ResourceArn { get; set; } public List<Amazon.ElasticBeanstalk.Model.Tag> TagsToAdd { get; set; } public List<System.String> TagsToRemove { get; set; } public System.Func<Amazon.ElasticBeanstalk.Model.UpdateTagsForResourceResponse, UpdateEBResourceTagCmdlet, object> Select { get; set; } = (response, cmdlet) => null; } } }
46.886447
282
0.618281
[ "Apache-2.0" ]
5u5hma/aws-tools-for-powershell
modules/AWSPowerShell/Cmdlets/ElasticBeanstalk/Basic/Update-EBResourceTag-Cmdlet.cs
12,800
C#
using System.Diagnostics; using Microsoft.AspNetCore.Mvc; using VueDemo.Models; namespace VueDemo.Controllers { public class HomeController : Controller { public IActionResult Index() { return View(); } public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } } }
21.4
112
0.621495
[ "MIT" ]
adams85/bundles
samples/VueDemo/Controllers/HomeController.cs
430
C#
using FarseerPhysics; using FarseerPhysics.Dynamics; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Input; using Nez.Farseer; using Nez.Svg; namespace Nez.Samples { [SampleScene( "SVG to Farseer Physics", 85, "This demo shows how you can turn an SVG image into Farseer physics objects\nPress Space to start the physics simulation\nClick and drag to interact with physics shapes" )] public class FarseerSVGScene : SampleScene { public override void initialize() { clearColor = Color.Black; addRenderer( new DefaultRenderer() ); Screen.setSize( 1280, 720 ); Settings.maxPolygonVertices = 12; // create a physics world to manage the physics simulation var world = getOrCreateSceneComponent<FSWorld>() .setEnableMousePicking( true ); world.setEnabled( false ); // add a FSDebugView so that we can see the physics objects createEntity( "debug-view" ) .addComponent( new PressKeyToPerformAction( Keys.Space, () => world.setEnabled( true ) ) ) .addComponent( new FSDebugView( world ) ) .appendFlags( FSDebugView.DebugViewFlags.ContactPoints ); // load up the SVG document. This particular SVG only has one group so we can fetch it straight away var svgDoc = SvgDocument.open( TitleContainer.OpenStream( "Content/SVG/farseer-svg.svg" ) ); var svgGroup = svgDoc.groups[0]; // rectangles if( svgGroup.rectangles != null ) addRectangles( svgGroup ); // circles if( svgGroup.circles != null ) addCircles( svgGroup ); // lines if( svgGroup.lines != null ) addLines( svgGroup ); // paths: TODO: why is System.Drawing.Drawing2D.GraphicsPath never returning on macOS?!?! //if( svgGroup.paths != null ) // addPaths( svgGroup ); // ellipses if( svgGroup.ellipses != null ) addEllipses( svgGroup ); // polygons if( svgGroup.polygons != null ) addPolygons( svgGroup ); } /// <summary> /// adds dynamic rectangle physics objects for each rect in the SVG /// </summary> /// <param name="group">Group.</param> void addRectangles( SvgGroup group ) { foreach( var rect in group.rectangles ) { var boxEntity = createEntity( rect.id ); boxEntity.setPosition( rect.center ) .setRotationDegrees( rect.rotationDegrees ) .addComponent( new FSRigidBody() ) .setBodyType( BodyType.Dynamic ) .addComponent( new FSCollisionBox( rect.width, rect.height ) ); } } /// <summary> /// adds dynamic circle physics objects for each circle in the SVG /// </summary> /// <param name="group">Group.</param> void addCircles( SvgGroup group ) { foreach( var circle in group.circles ) { createEntity( circle.id ) .setPosition( circle.centerX, circle.centerY ) .addComponent( new FSRigidBody() ) .setBodyType( BodyType.Dynamic ) .addComponent( new FSCollisionCircle( circle.radius ) ); } } /// <summary> /// adds static edge physics objects for each line in the SVG /// </summary> /// <param name="group">Group.</param> void addLines( SvgGroup group ) { foreach( var line in group.lines ) { var pts = line.getTransformedPoints(); createEntity( line.id ) .addComponent<FSRigidBody>() .addComponent( new FSCollisionEdge() ) .setVertices( pts[0], pts[1] ); } } /// <summary> /// adds static chain physics objects for each path in the SVG /// </summary> /// <param name="group">Group.</param> void addPaths( SvgGroup group ) { var svgPathBuilder = new SvgPathBuilder(); foreach( var path in group.paths ) { var pts = path.getTransformedDrawingPoints( svgPathBuilder ); createEntity( path.id ) .addComponent<FSRigidBody>() .addComponent( new FSCollisionChain() ) .setVertices( pts ); } } /// <summary> /// adds dynamic ellipse physics objects for each ellipse in the SVG /// </summary> /// <param name="group">Group.</param> void addEllipses( SvgGroup group ) { foreach( var ellipse in group.ellipses ) { createEntity( ellipse.id ) .setPosition( ellipse.centerX, ellipse.centerY ) .addComponent<FSRigidBody>() .setBodyType( BodyType.Dynamic ) .addComponent( new FSCollisionEllipse( ellipse.radiusX, ellipse.radiusY ) ); } } /// <summary> /// adds dynamic polygon physics objects for each polygon in the SVG /// </summary> /// <param name="group">Group.</param> void addPolygons( SvgGroup group ) { foreach( var polygon in group.polygons ) { createEntity( polygon.id ) .setPosition( polygon.centerX, polygon.centerY ) .addComponent<FSRigidBody>() .setBodyType( BodyType.Dynamic ) .addComponent( new FSCollisionPolygon( polygon.getRelativePoints() ) ); } } } }
27.853801
217
0.670796
[ "MIT" ]
skibum3d/Nez-Samples
Nez.Samples/Scenes/Farseer SVG/FarseerSVGScene.cs
4,765
C#
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Numerics; namespace Tasks { using mint = F.ModuloInteger; public class F { public static void Main(string[] args) { var sw = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false }; Console.SetOut(sw); Solve(); Console.Out.Flush(); } public static void Solve() { var S = Scanner.Scan<string>(); var N = S.Length; var fact = new mint[N + 1]; var ifact = new mint[N + 1]; fact[0] = ifact[0] = 1; for (var i = 1; i <= N; i++) { fact[i] = fact[i - 1] * i; ifact[i] = 1 / fact[i]; } mint Combination(int n, int k) { if (n < k || n < 0 || k < 0) return 0; return fact[n] * ifact[k] * ifact[n - k]; } var count = new int[26]; foreach (var c in S) { count[c - 'a']++; } var dp = new mint[27, N + 1]; dp[0, 0] = 1; for (var i = 0; i < 26; i++) { for (var j = 0; j <= N; j++) { for (var k = 0; k <= Math.Min(j, count[i]); k++) { dp[i + 1, j] += dp[i, j - k] * Combination(j, k); } } } mint answer = 0; for (var i = 1; i <= N; i++) { answer += dp[26, i]; } Console.WriteLine(answer); } public readonly struct ModuloInteger : IEquatable<ModuloInteger> { public long Value { get; } // public static long Modulo { get; set; } = 998244353; // The modulo will be used as an editable property. // The constant modulo will be recommended to use for performances in use cases. public const long Modulo = 998244353; public ModuloInteger(int value) => Value = value % Modulo >= 0 ? value % Modulo : value % Modulo + Modulo; public ModuloInteger(long value) => Value = value % Modulo >= 0 ? value % Modulo : value % Modulo + Modulo; public static implicit operator int(ModuloInteger mint) => (int)mint.Value; public static implicit operator long(ModuloInteger mint) => mint.Value; public static implicit operator ModuloInteger(int value) => new ModuloInteger(value); public static implicit operator ModuloInteger(long value) => new ModuloInteger(value); public static ModuloInteger operator +(in ModuloInteger a, in ModuloInteger b) => a.Value + b.Value; public static ModuloInteger operator -(in ModuloInteger a, in ModuloInteger b) => a.Value - b.Value; public static ModuloInteger operator *(in ModuloInteger a, in ModuloInteger b) => a.Value * b.Value; public static ModuloInteger operator /(in ModuloInteger a, in ModuloInteger b) => a * b.Inverse(); public static ModuloInteger operator +(in ModuloInteger a, int b) => a.Value + b; public static ModuloInteger operator +(int a, in ModuloInteger b) => a + b.Value; public static ModuloInteger operator -(in ModuloInteger a, int b) => a.Value - b; public static ModuloInteger operator -(int a, in ModuloInteger b) => a - b.Value; public static ModuloInteger operator *(in ModuloInteger a, int b) => a.Value * b; public static ModuloInteger operator *(int a, in ModuloInteger b) => a * b.Value; public static ModuloInteger operator /(in ModuloInteger a, int b) => a * Inverse(b); public static ModuloInteger operator /(int a, in ModuloInteger b) => a * b.Inverse(); public static ModuloInteger operator +(in ModuloInteger a, long b) => a.Value + b; public static ModuloInteger operator +(long a, in ModuloInteger b) => a + b.Value; public static ModuloInteger operator -(in ModuloInteger a, long b) => a.Value - b; public static ModuloInteger operator -(long a, in ModuloInteger b) => a - b.Value; public static ModuloInteger operator *(in ModuloInteger a, long b) => a.Value * b; public static ModuloInteger operator *(long a, in ModuloInteger b) => a * b.Value; public static ModuloInteger operator /(in ModuloInteger a, long b) => a * Inverse(b); public static ModuloInteger operator /(long a, in ModuloInteger b) => a * b.Inverse(); public static bool operator ==(in ModuloInteger a, in ModuloInteger b) => a.Value == b.Value; public static bool operator !=(in ModuloInteger a, in ModuloInteger b) => a.Value != b.Value; public bool Equals(ModuloInteger other) => Value == other.Value; public override bool Equals(object obj) => obj is ModuloInteger other && Equals(other); public override int GetHashCode() => Value.GetHashCode(); public override string ToString() => Value.ToString(); public ModuloInteger Inverse() => Inverse(Value); public static ModuloInteger Inverse(long value) { if (value == 0) return 0; var (s, t, m0, m1) = (Modulo, value, 0L, 1L); while (t > 0) { var u = s / t; s -= t * u; m0 -= m1 * u; (s, t) = (t, s); (m0, m1) = (m1, m0); } if (m0 < 0) m0 += Modulo / s; return m0; } public ModuloInteger Power(long n) => Power(Value, n); public static ModuloInteger Power(long value, long n) { if (n < 0) throw new ArgumentException(); var ret = 1L; while (n > 0) { if ((n & 1) > 0) ret = ret * value % Modulo; value = value * value % Modulo; n >>= 1; } return ret; } } public static class Scanner { public static T Scan<T>() where T : IConvertible => Convert<T>(ScanLine()[0]); public static (T1, T2) Scan<T1, T2>() where T1 : IConvertible where T2 : IConvertible { var line = ScanLine(); return (Convert<T1>(line[0]), Convert<T2>(line[1])); } public static (T1, T2, T3) Scan<T1, T2, T3>() where T1 : IConvertible where T2 : IConvertible where T3 : IConvertible { var line = ScanLine(); return (Convert<T1>(line[0]), Convert<T2>(line[1]), Convert<T3>(line[2])); } public static (T1, T2, T3, T4) Scan<T1, T2, T3, T4>() where T1 : IConvertible where T2 : IConvertible where T3 : IConvertible where T4 : IConvertible { var line = ScanLine(); return (Convert<T1>(line[0]), Convert<T2>(line[1]), Convert<T3>(line[2]), Convert<T4>(line[3])); } public static (T1, T2, T3, T4, T5) Scan<T1, T2, T3, T4, T5>() where T1 : IConvertible where T2 : IConvertible where T3 : IConvertible where T4 : IConvertible where T5 : IConvertible { var line = ScanLine(); return (Convert<T1>(line[0]), Convert<T2>(line[1]), Convert<T3>(line[2]), Convert<T4>(line[3]), Convert<T5>(line[4])); } public static (T1, T2, T3, T4, T5, T6) Scan<T1, T2, T3, T4, T5, T6>() where T1 : IConvertible where T2 : IConvertible where T3 : IConvertible where T4 : IConvertible where T5 : IConvertible where T6 : IConvertible { var line = ScanLine(); return (Convert<T1>(line[0]), Convert<T2>(line[1]), Convert<T3>(line[2]), Convert<T4>(line[3]), Convert<T5>(line[4]), Convert<T6>(line[5])); } public static IEnumerable<T> ScanEnumerable<T>() where T : IConvertible => ScanLine().Select(Convert<T>); private static T Convert<T>(string value) where T : IConvertible => (T)System.Convert.ChangeType(value, typeof(T)); private static string[] ScanLine() => Console.ReadLine()?.Trim().Split(' ') ?? Array.Empty<string>(); } } }
48.925714
225
0.527447
[ "CC0-1.0" ]
AconCavy/AtCoder.Tasks.CS
ABC/ABC234/Tasks/F.cs
8,562
C#
// Authors: // Rafael Mizrahi <rafim@mainsoft.com> // Erez Lotan <erezl@mainsoft.com> // Oren Gurfinkel <oreng@mainsoft.com> // Ofer Borstein // // Copyright (c) 2004 Mainsoft Co. // // 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.Data; using NUnit.Framework; using GHTUtils; using GHTUtils.Base; namespace tests.system_data_dll.System_Data { [TestFixture] public class ForeignKeyConstraint_acceptRejectRule : GHTBase { public static void Main() { ForeignKeyConstraint_acceptRejectRule tc = new ForeignKeyConstraint_acceptRejectRule(); Exception exp = null; try { tc.BeginTest("ForeignKeyConstraint_acceptRejectRule"); tc.run(); } catch(Exception ex) { exp = ex; } finally { tc.EndTest(exp); } } //Activate This Construntor to log All To Standard output //public TestClass():base(true){} //Activate this constructor to log Failures to a log file //public TestClass(System.IO.TextWriter tw):base(tw, false){} //Activate this constructor to log All to a log file //public TestClass(System.IO.TextWriter tw):base(tw, true){} //BY DEFAULT LOGGING IS DONE TO THE STANDARD OUTPUT ONLY FOR FAILURES public void run() { Exception exp = null; try { BeginCase("ForeignKeyConstraint_acceptRejectRule"); ForeignKeyConstraint_acceptRejectRule1(); } catch(Exception ex) { exp = ex; } finally { EndCase(exp); exp = null; } } [Test] public void ForeignKeyConstraint_acceptRejectRule1() { DataSet ds = getNewDataSet(); ForeignKeyConstraint fc = new ForeignKeyConstraint(ds.Tables[0].Columns[0],ds.Tables[1].Columns[0]); fc.AcceptRejectRule= AcceptRejectRule.Cascade; ds.Tables[1].Constraints.Add(fc); //Update the parent ds.Tables[0].Rows[0]["ParentId"] = 777; Compare(ds.Tables[1].Select("ParentId=777").Length > 0 ,true); ds.Tables[0].RejectChanges(); Compare(ds.Tables[1].Select("ParentId=777").Length , 0); } private DataSet getNewDataSet() { DataSet ds1 = new DataSet(); ds1.Tables.Add(DataProvider.CreateParentDataTable()); ds1.Tables.Add(DataProvider.CreateChildDataTable()); // ds1.Tables.Add(DataProvider.CreateChildDataTable()); ds1.Tables[0].PrimaryKey= new DataColumn[] {ds1.Tables[0].Columns[0]}; return ds1; } } }
27.75
102
0.724925
[ "Apache-2.0" ]
121468615/mono
mcs/class/System.Data/Test/System.Data.Tests.Mainsoft/System.Data/ForeignKeyConstraint/ForeignKeyConstraint_acceptRejectRule.cs
3,330
C#
using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using PureCloudPlatform.Client.V2.Client; namespace PureCloudPlatform.Client.V2.Model { /// <summary> /// WebDeploymentsDeploymentTopicWebMessagingDeploymentChangeEventBody /// </summary> [DataContract] public partial class WebDeploymentsDeploymentTopicWebMessagingDeploymentChangeEventBody : IEquatable<WebDeploymentsDeploymentTopicWebMessagingDeploymentChangeEventBody> { /// <summary> /// Gets or Sets Status /// </summary> [JsonConverter(typeof(UpgradeSdkEnumConverter))] public enum StatusEnum { /// <summary> /// Your SDK version is out of date and an unknown enum value was encountered. /// Please upgrade the SDK using the command "Upgrade-Package PureCloudApiSdk" /// in the Package Manager Console /// </summary> [EnumMember(Value = "OUTDATED_SDK_VERSION")] OutdatedSdkVersion, /// <summary> /// Enum Pending for "Pending" /// </summary> [EnumMember(Value = "Pending")] Pending, /// <summary> /// Enum Active for "Active" /// </summary> [EnumMember(Value = "Active")] Active, /// <summary> /// Enum Inactive for "Inactive" /// </summary> [EnumMember(Value = "Inactive")] Inactive, /// <summary> /// Enum Error for "Error" /// </summary> [EnumMember(Value = "Error")] Error, /// <summary> /// Enum Deleting for "Deleting" /// </summary> [EnumMember(Value = "Deleting")] Deleting } /// <summary> /// Gets or Sets Status /// </summary> [DataMember(Name="status", EmitDefaultValue=false)] public StatusEnum? Status { get; set; } /// <summary> /// Initializes a new instance of the <see cref="WebDeploymentsDeploymentTopicWebMessagingDeploymentChangeEventBody" /> class. /// </summary> /// <param name="Id">Id.</param> /// <param name="Configuration">Configuration.</param> /// <param name="Status">Status.</param> public WebDeploymentsDeploymentTopicWebMessagingDeploymentChangeEventBody(string Id = null, WebDeploymentsDeploymentTopicWebMessagingConfigChangeEventBody Configuration = null, StatusEnum? Status = null) { this.Id = Id; this.Configuration = Configuration; this.Status = Status; } /// <summary> /// Gets or Sets Id /// </summary> [DataMember(Name="id", EmitDefaultValue=false)] public string Id { get; set; } /// <summary> /// Gets or Sets Configuration /// </summary> [DataMember(Name="configuration", EmitDefaultValue=false)] public WebDeploymentsDeploymentTopicWebMessagingConfigChangeEventBody Configuration { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class WebDeploymentsDeploymentTopicWebMessagingDeploymentChangeEventBody {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Configuration: ").Append(Configuration).Append("\n"); sb.Append(" Status: ").Append(Status).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, new JsonSerializerSettings { MetadataPropertyHandling = MetadataPropertyHandling.Ignore, Formatting = Formatting.Indented }); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as WebDeploymentsDeploymentTopicWebMessagingDeploymentChangeEventBody); } /// <summary> /// Returns true if WebDeploymentsDeploymentTopicWebMessagingDeploymentChangeEventBody instances are equal /// </summary> /// <param name="other">Instance of WebDeploymentsDeploymentTopicWebMessagingDeploymentChangeEventBody to be compared</param> /// <returns>Boolean</returns> public bool Equals(WebDeploymentsDeploymentTopicWebMessagingDeploymentChangeEventBody other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return true && ( this.Id == other.Id || this.Id != null && this.Id.Equals(other.Id) ) && ( this.Configuration == other.Configuration || this.Configuration != null && this.Configuration.Equals(other.Configuration) ) && ( this.Status == other.Status || this.Status != null && this.Status.Equals(other.Status) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.Id != null) hash = hash * 59 + this.Id.GetHashCode(); if (this.Configuration != null) hash = hash * 59 + this.Configuration.GetHashCode(); if (this.Status != null) hash = hash * 59 + this.Status.GetHashCode(); return hash; } } } }
33.004566
211
0.524073
[ "MIT" ]
F-V-L/platform-client-sdk-dotnet
build/src/PureCloudPlatform.Client.V2/Model/WebDeploymentsDeploymentTopicWebMessagingDeploymentChangeEventBody.cs
7,228
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; namespace Aliyun.Acs.imm.Model.V20170906 { public class DeleteFaceSearchGroupResponse : AcsResponse { private string requestId; public string RequestId { get { return requestId; } set { requestId = value; } } } }
26.465116
63
0.718805
[ "Apache-2.0" ]
AxiosCros/aliyun-openapi-net-sdk
aliyun-net-sdk-imm/Imm/Model/V20170906/DeleteFaceSearchGroupResponse.cs
1,138
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using GreenBot_Base; namespace WpfApp1 { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { /// <summary> /// when user types in Console send it to the chat /// </summary> static string userCommand; /// <summary> /// read only array of strings for Bot keywords /// </summary> private static readonly string[] reservedWords = new string[] { "w", "stop", "close", "enter" }; /// <summary> /// Currently only supports one bot /// TODO: multiple bot support? /// </summary> TwitchChatBot.TwitchChatBot twitchChatBot = new TwitchChatBot.TwitchChatBot(); public bool isOnline = false; public MainWindow() { InitializeComponent(); } private void TextBox_TextChanged(object sender, TextChangedEventArgs e) { userNameTB.Text = } private void TextBox_TextChanged_1(object sender, TextChangedEventArgs e) { } private void TextBox_TextChanged_2(object sender, TextChangedEventArgs e) { } private void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e) { } private void messageCommand(string commandArgs) { TwitchChatBot.TwitchChatBot twitchChatBot = new TwitchChatBot.TwitchChatBot(); string[] messageArgs; userCommand = Console.ReadLine(); // determine if the command is a message, whisper or a command if (!reservedWords.Contains(userCommand)) { twitchChatBot.SendMessage(TwitchInfo.ChannelName, userCommand); } // command - whisper else if (userCommand == "w") { EnterCommand: Console.WriteLine("BOT -- Recipient,Message"); string userparam = Console.ReadLine(); messageArgs = userparam.Split(','); try { twitchChatBot.SendWhisper(messageArgs[0], messageArgs[1]); } catch { Console.WriteLine("BOT -- please enter something valid"); goto EnterCommand; } } // rest of commands TODO: } private void sendToChatWindow(string ) { Chat } } }
27.259259
104
0.572351
[ "MIT" ]
BoSkeet/GreenBot
ChatController/MainWindow.xaml.cs
2,946
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Inch_to_cm { class Program { static void Main(string[] args) { Console.Write("Inch = "); double inch = double.Parse(Console.ReadLine()); double cm = inch * 2.54; Console.WriteLine("Centimeters = {0}",cm); } } }
21.15
59
0.583924
[ "MIT" ]
penchev/Programming-Basics
Simple Calculations/Inch_to_cm/Program.cs
425
C#
using System; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("AWSSDK.EC2InstanceConnect")] #if BCL35 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - AWS EC2 Instance Connect. Amazon EC2 Instance Connect is a simple and secure way to connect to your instances using Secure Shell (SSH). With EC2 Instance Connect, you can control SSH access to your instances using AWS Identity and Access Management (IAM) policies as well as audit connection requests with AWS CloudTrail events. In addition, you can leverage your existing SSH keys or further enhance your security posture by generating one-time use SSH keys each time an authorized user connects.")] #elif BCL45 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (4.5) - AWS EC2 Instance Connect. Amazon EC2 Instance Connect is a simple and secure way to connect to your instances using Secure Shell (SSH). With EC2 Instance Connect, you can control SSH access to your instances using AWS Identity and Access Management (IAM) policies as well as audit connection requests with AWS CloudTrail events. In addition, you can leverage your existing SSH keys or further enhance your security posture by generating one-time use SSH keys each time an authorized user connects.")] #elif NETSTANDARD20 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 2.0) - AWS EC2 Instance Connect. Amazon EC2 Instance Connect is a simple and secure way to connect to your instances using Secure Shell (SSH). With EC2 Instance Connect, you can control SSH access to your instances using AWS Identity and Access Management (IAM) policies as well as audit connection requests with AWS CloudTrail events. In addition, you can leverage your existing SSH keys or further enhance your security posture by generating one-time use SSH keys each time an authorized user connects.")] #elif NETCOREAPP3_1 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (.NET Core 3.1) - AWS EC2 Instance Connect. Amazon EC2 Instance Connect is a simple and secure way to connect to your instances using Secure Shell (SSH). With EC2 Instance Connect, you can control SSH access to your instances using AWS Identity and Access Management (IAM) policies as well as audit connection requests with AWS CloudTrail events. In addition, you can leverage your existing SSH keys or further enhance your security posture by generating one-time use SSH keys each time an authorized user connects.")] #else #error Unknown platform constant - unable to set correct AssemblyDescription #endif [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Amazon Web Services SDK for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("3.3")] [assembly: AssemblyFileVersion("3.7.1.111")] [assembly: System.CLSCompliant(true)] #if BCL [assembly: System.Security.AllowPartiallyTrustedCallers] #endif
76.941176
589
0.786442
[ "Apache-2.0" ]
pcameron-/aws-sdk-net
sdk/src/Services/EC2InstanceConnect/Properties/AssemblyInfo.cs
3,924
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; class Program { static void Main(string[] args) { Dog dog = new Dog(); dog.Eat(); dog.Bark(); Cat cat = new Cat(); cat.Eat(); cat.Meow(); } }
16.05
35
0.563863
[ "MIT" ]
ChrisPam/CSharpOOP
05.InheritanceLab/03.HierarchicalInheritance/Program.cs
323
C#
// Copyright 2016 Datalust, Superpower Contributors, Sprache Contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Superpower.Model; using Superpower.Util; using System; using Superpower.Display; namespace Superpower { /// <summary> /// General parsing helper methods. /// </summary> public static class Parse { /// <summary> /// Parse a sequence of similar operands connected by left-associative operators. /// </summary> /// <typeparam name="T">The type being parsed.</typeparam> /// <typeparam name="TOperator">The type of the operator.</typeparam> /// <param name="operator">A parser matching operators.</param> /// <param name="operand">A parser matching operands.</param> /// <param name="apply">A function combining an operator and two operands into the result.</param> /// <returns>The result of calling <paramref name="apply"/> successively on pairs of operands.</returns> /// <seealso cref="Combinators.Chain{TResult,TOperator,TOperand}"/> public static TextParser<T> Chain<T, TOperator>( TextParser<TOperator> @operator, TextParser<T> operand, Func<TOperator, T, T, T> apply) { return operand.Chain(@operator, operand, apply); } /// <summary> /// Parse a sequence of operands connected by right-associative operators. /// </summary> /// <typeparam name="T">The type being parsed.</typeparam> /// <typeparam name="TOperator">The type of the operator.</typeparam> /// <param name="operator">A parser matching operators.</param> /// <param name="operand">A parser matching operands.</param> /// <param name="apply">A function combining an operator and two operands into the result.</param> /// <returns>The result of calling <paramref name="apply"/> successively on pairs of operands.</returns> public static TextParser<T> ChainRight<T, TOperator>( TextParser<TOperator> @operator, TextParser<T> operand, Func<TOperator, T, T, T> apply) { if (@operator == null) throw new ArgumentNullException(nameof(@operator)); if (operand == null) throw new ArgumentNullException(nameof(operand)); if (apply == null) throw new ArgumentNullException(nameof(apply)); return operand.Then(first => ChainRightOperatorRest(first, @operator, operand, apply)); } static TextParser<T> ChainRightOperatorRest<T, TOperator>( T lastOperand, TextParser<TOperator> @operator, TextParser<T> operand, Func<TOperator, T, T, T> apply) { if (@operator == null) throw new ArgumentNullException(nameof(@operator)); if (operand == null) throw new ArgumentNullException(nameof(operand)); if (apply == null) throw new ArgumentNullException(nameof(apply)); return @operator.Then(opvalue => operand.Then(operandValue => ChainRightOperatorRest(operandValue, @operator, operand, apply)).Then(r => Return(apply(opvalue, lastOperand, r)))) .Or(Return(lastOperand)); } /// <summary> /// Parse a sequence of similar operands connected by left-associative operators. /// </summary> /// <typeparam name="T">The type being parsed.</typeparam> /// <typeparam name="TOperator">The type of the operator.</typeparam> /// <typeparam name="TKind">The kind of token being parsed.</typeparam> /// <param name="operator">A parser matching operators.</param> /// <param name="operand">A parser matching operands.</param> /// <param name="apply">A function combining an operator and two operands into the result.</param> /// <returns>The result of calling <paramref name="apply"/> successively on pairs of operands.</returns> /// <seealso cref="Combinators.Chain{TKind, TResult,TOperator,TOperand}"/> public static TokenListParser<TKind, T> Chain<TKind, T, TOperator>( TokenListParser<TKind, TOperator> @operator, TokenListParser<TKind, T> operand, Func<TOperator, T, T, T> apply) { return operand.Chain(@operator, operand, apply); } /// <summary> /// Parse a sequence of operands connected by right-associative operators. /// </summary> /// <typeparam name="T">The type being parsed.</typeparam> /// <typeparam name="TOperator">The type of the operator.</typeparam> /// <typeparam name="TKind">The kind of token being parsed.</typeparam> /// <param name="operator">A parser matching operators.</param> /// <param name="operand">A parser matching operands.</param> /// <param name="apply">A function combining an operator and two operands into the result.</param> /// <returns>The result of calling <paramref name="apply"/> successively on pairs of operands.</returns> public static TokenListParser<TKind, T> ChainRight<TKind, T, TOperator>( TokenListParser<TKind, TOperator> @operator, TokenListParser<TKind, T> operand, Func<TOperator, T, T, T> apply) { if (@operator == null) throw new ArgumentNullException(nameof(@operator)); if (operand == null) throw new ArgumentNullException(nameof(operand)); if (apply == null) throw new ArgumentNullException(nameof(apply)); return operand.Then(first => ChainRightOperatorRest(first, @operator, operand, apply)); } static TokenListParser<TKind, T> ChainRightOperatorRest<TKind, T, TOperator>( T lastOperand, TokenListParser<TKind, TOperator> @operator, TokenListParser<TKind, T> operand, Func<TOperator, T, T, T> apply) { if (@operator == null) throw new ArgumentNullException(nameof(@operator)); if (operand == null) throw new ArgumentNullException(nameof(operand)); if (apply == null) throw new ArgumentNullException(nameof(apply)); return @operator.Then(opvalue => operand.Then(operandValue => ChainRightOperatorRest(operandValue, @operator, operand, apply)).Then(r => Return<TKind, T>(apply(opvalue, lastOperand, r)))) .Or(Return<TKind, T>(lastOperand)); } /// <summary> /// Constructs a parser that will fail if the given parser succeeds, /// and will succeed if the given parser fails. In any case, it won't /// consume any input. It's like a negative look-ahead in a regular expression. /// </summary> /// <typeparam name="T">The result type of the given parser</typeparam> /// <param name="parser">The parser to wrap</param> /// <returns>A parser that is the negation of the given parser.</returns> public static TextParser<Unit> Not<T>(TextParser<T> parser) { if (parser == null) throw new ArgumentNullException(nameof(parser)); return input => { var result = parser(input); if (result.HasValue) return Result.Empty<Unit>(input, $"unexpected successful parsing of `{input.Until(result.Remainder)}`"); return Result.Value(Unit.Value, input, input); }; } /// <summary> /// Constructs a parser that will fail if the given parser succeeds, /// and will succeed if the given parser fails. In any case, it won't /// consume any input. It's like a negative look-ahead in a regular expression. /// </summary> /// <typeparam name="T">The result type of the given parser.</typeparam> /// <typeparam name="TKind">The kind of token being parsed.</typeparam> /// <param name="parser">The parser to wrap</param> /// <returns>A parser that is the negation of the given parser.</returns> public static TokenListParser<TKind, Unit> Not<TKind, T>(TokenListParser<TKind, T> parser) { if (parser == null) throw new ArgumentNullException(nameof(parser)); return input => { var result = parser(input); if (result.HasValue) { // This is usually a success case for Not(), so the allocations here are a bit of a pity. var current = input.ConsumeToken(); var last = result.Remainder.ConsumeToken(); if (current.HasValue) { var span = last.HasValue ? current.Value.Span.Source.Substring(current.Value.Position.Absolute, last.Value.Position.Absolute - current.Value.Position.Absolute) : current.Value.Span.Source.Substring(current.Value.Position.Absolute); return TokenListParserResult.Empty<TKind, Unit>(input, $"unexpected successful parsing of {Presentation.FormatLiteral(Friendly.Clip(span, 12))}"); } return TokenListParserResult.Empty<TKind, Unit>(input, "unexpected successful parsing"); } return TokenListParserResult.Value(Unit.Value, input, input); }; } /// <summary> /// Lazily construct a parser, so that circular dependencies are possible. /// </summary> /// <param name="reference">A function creating the parser, when required.</param> /// <typeparam name="T">The type of value being parsed.</typeparam> /// <returns>A parser that lazily evaluates <paramref name="reference"/>.</returns> /// <exception cref="ArgumentNullException"><paramref name="reference"/> is null.</exception> public static TextParser<T> Ref<T>(Func<TextParser<T>> reference) { if (reference == null) throw new ArgumentNullException(nameof(reference)); TextParser<T> parser = null; return i => { if (parser == null) parser = reference(); return parser(i); }; } /// <summary> /// Lazily construct a parser, so that circular dependencies are possible. /// </summary> /// <param name="reference">A function creating the parser, when required.</param> /// <typeparam name="T">The type of value being parsed.</typeparam> /// <typeparam name="TKind">The kind of token being parsed.</typeparam> /// <returns>A parser that lazily evaluates <paramref name="reference"/>.</returns> /// <exception cref="ArgumentNullException"><paramref name="reference"/> is null.</exception> public static TokenListParser<TKind, T> Ref<TKind, T>(Func<TokenListParser<TKind, T>> reference) { if (reference == null) throw new ArgumentNullException(nameof(reference)); TokenListParser<TKind, T> parser = null; return i => { if (parser == null) parser = reference(); return parser(i); }; } /// <summary> /// Construct a parser with a fixed value. /// </summary> /// <param name="value">The value returned by the parser.</param> /// <typeparam name="T">The type of <paramref name="value"/>.</typeparam> /// <returns>The parser.</returns> public static TextParser<T> Return<T>(T value) { return input => Result.Value(value, input, input); } /// <summary> /// Construct a parser with a fixed value. /// </summary> /// <param name="value">The value returned by the parser.</param> /// <typeparam name="T">The type of <paramref name="value"/>.</typeparam> /// <typeparam name="TKind">The kind of token being parsed.</typeparam> /// <returns>The parser.</returns> public static TokenListParser<TKind, T> Return<TKind, T>(T value) { return input => TokenListParserResult.Value(value, input, input); } /// <summary> /// Construct a parser applies two parsers in order and returns a tuple of their results. /// </summary> /// <typeparam name="TKind">The kind of the tokens being parsed.</typeparam> /// <typeparam name="T">The type of the first value parsed.</typeparam> /// <typeparam name="U">The type of the second value parsed.</typeparam> /// <param name="parser1">The first parser to apply.</param> /// <param name="parser2">The second parser to apply.</param> /// <returns>The resulting parser.</returns> public static TokenListParser<TKind, (T, U)> Sequence<TKind, T, U>( TokenListParser<TKind, T> parser1, TokenListParser<TKind, U> parser2) { if (parser1 == null) throw new ArgumentNullException(nameof(parser1)); if (parser2 == null) throw new ArgumentNullException(nameof(parser2)); return input => { var rt = parser1(input); if (!rt.HasValue) return TokenListParserResult.CastEmpty<TKind, T, (T, U)>(rt); var ru = parser2(rt.Remainder); if (!ru.HasValue) return TokenListParserResult.CastEmpty<TKind, U, (T, U)>(ru); return TokenListParserResult.Value((rt.Value, ru.Value), input, ru.Remainder); }; } /// <summary> /// Construct a parser applies three parsers in order and returns a tuple of their results. /// </summary> /// <typeparam name="TKind">The kind of the tokens being parsed.</typeparam> /// <typeparam name="T">The type of the first value parsed.</typeparam> /// <typeparam name="U">The type of the second value parsed.</typeparam> /// <typeparam name="V">The type of the third value parsed.</typeparam> /// <param name="parser1">The first parser to apply.</param> /// <param name="parser2">The second parser to apply.</param> /// <param name="parser3">The third parser to apply.</param> /// <returns>The resulting parser.</returns> public static TokenListParser<TKind, (T, U, V)> Sequence<TKind, T, U, V>( TokenListParser<TKind, T> parser1, TokenListParser<TKind, U> parser2, TokenListParser<TKind, V> parser3) { if (parser1 == null) throw new ArgumentNullException(nameof(parser1)); if (parser2 == null) throw new ArgumentNullException(nameof(parser2)); if (parser3 == null) throw new ArgumentNullException(nameof(parser3)); return input => { var rt = parser1(input); if (!rt.HasValue) return TokenListParserResult.CastEmpty<TKind, T, (T, U, V)>(rt); var ru = parser2(rt.Remainder); if (!ru.HasValue) return TokenListParserResult.CastEmpty<TKind, U, (T, U, V)>(ru); var rv = parser3(ru.Remainder); if (!rv.HasValue) return TokenListParserResult.CastEmpty<TKind, V, (T, U, V)>(rv); return TokenListParserResult.Value((rt.Value, ru.Value, rv.Value), input, rv.Remainder); }; } /// <summary> /// Construct a parser applies four parsers in order and returns a tuple of their results. /// </summary> /// <typeparam name="TKind">The kind of the tokens being parsed.</typeparam> /// <typeparam name="T">The type of the first value parsed.</typeparam> /// <typeparam name="U">The type of the second value parsed.</typeparam> /// <typeparam name="V">The type of the third value parsed.</typeparam> /// <typeparam name="W">The type of the fourth value parsed.</typeparam> /// <param name="parser1">The first parser to apply.</param> /// <param name="parser2">The second parser to apply.</param> /// <param name="parser3">The third parser to apply.</param> /// <param name="parser4">The fourth parser to apply.</param> /// <returns>The resulting parser.</returns> public static TokenListParser<TKind, (T, U, V, W)> Sequence<TKind, T, U, V, W>( TokenListParser<TKind, T> parser1, TokenListParser<TKind, U> parser2, TokenListParser<TKind, V> parser3, TokenListParser<TKind, W> parser4) { if (parser1 == null) throw new ArgumentNullException(nameof(parser1)); if (parser2 == null) throw new ArgumentNullException(nameof(parser2)); if (parser3 == null) throw new ArgumentNullException(nameof(parser3)); if (parser4 == null) throw new ArgumentNullException(nameof(parser4)); return input => { var rt = parser1(input); if (!rt.HasValue) return TokenListParserResult.CastEmpty<TKind, T, (T, U, V, W)>(rt); var ru = parser2(rt.Remainder); if (!ru.HasValue) return TokenListParserResult.CastEmpty<TKind, U, (T, U, V, W)>(ru); var rv = parser3(ru.Remainder); if (!rv.HasValue) return TokenListParserResult.CastEmpty<TKind, V, (T, U, V, W)>(rv); var rw = parser4(rv.Remainder); if (!rw.HasValue) return TokenListParserResult.CastEmpty<TKind, W, (T, U, V, W)>(rw); return TokenListParserResult.Value((rt.Value, ru.Value, rv.Value, rw.Value), input, rw.Remainder); }; } /// <summary> /// Construct a parser applies five parsers in order and returns a tuple of their results. /// </summary> /// <typeparam name="TKind">The kind of the tokens being parsed.</typeparam> /// <typeparam name="T">The type of the first value parsed.</typeparam> /// <typeparam name="U">The type of the second value parsed.</typeparam> /// <typeparam name="V">The type of the third value parsed.</typeparam> /// <typeparam name="W">The type of the fourth value parsed.</typeparam> /// <typeparam name="X">The type of the fifth value parsed.</typeparam> /// <param name="parser1">The first parser to apply.</param> /// <param name="parser2">The second parser to apply.</param> /// <param name="parser3">The third parser to apply.</param> /// <param name="parser4">The fourth parser to apply.</param> /// <param name="parser5">The fifth parser to apply.</param> /// <returns>The resulting parser.</returns> public static TokenListParser<TKind, (T, U, V, W, X)> Sequence<TKind, T, U, V, W, X>( TokenListParser<TKind, T> parser1, TokenListParser<TKind, U> parser2, TokenListParser<TKind, V> parser3, TokenListParser<TKind, W> parser4, TokenListParser<TKind, X> parser5) { if (parser1 == null) throw new ArgumentNullException(nameof(parser1)); if (parser2 == null) throw new ArgumentNullException(nameof(parser2)); if (parser3 == null) throw new ArgumentNullException(nameof(parser3)); if (parser4 == null) throw new ArgumentNullException(nameof(parser4)); if (parser5 == null) throw new ArgumentNullException(nameof(parser5)); return input => { var rt = parser1(input); if (!rt.HasValue) return TokenListParserResult.CastEmpty<TKind, T, (T, U, V, W, X)>(rt); var ru = parser2(rt.Remainder); if (!ru.HasValue) return TokenListParserResult.CastEmpty<TKind, U, (T, U, V, W, X)>(ru); var rv = parser3(ru.Remainder); if (!rv.HasValue) return TokenListParserResult.CastEmpty<TKind, V, (T, U, V, W, X)>(rv); var rw = parser4(rv.Remainder); if (!rw.HasValue) return TokenListParserResult.CastEmpty<TKind, W, (T, U, V, W, X)>(rw); var rx = parser5(rw.Remainder); if (!rx.HasValue) return TokenListParserResult.CastEmpty<TKind, X, (T, U, V, W, X)>(rx); return TokenListParserResult.Value((rt.Value, ru.Value, rv.Value, rw.Value, rx.Value), input, rx.Remainder); }; } /// <summary> /// Construct a parser applies two parsers in order and returns a tuple of their results. /// </summary> /// <typeparam name="T">The type of the first value parsed.</typeparam> /// <typeparam name="U">The type of the second value parsed.</typeparam> /// <param name="parser1">The first parser to apply.</param> /// <param name="parser2">The second parser to apply.</param> /// <returns>The resulting parser.</returns> public static TextParser<(T, U)> Sequence<T, U>( TextParser<T> parser1, TextParser<U> parser2) { if (parser1 == null) throw new ArgumentNullException(nameof(parser1)); if (parser2 == null) throw new ArgumentNullException(nameof(parser2)); return input => { var rt = parser1(input); if (!rt.HasValue) return Result.CastEmpty<T, (T, U)>(rt); var ru = parser2(rt.Remainder); if (!ru.HasValue) return Result.CastEmpty<U, (T, U)>(ru); return Result.Value((rt.Value, ru.Value), input, ru.Remainder); }; } /// <summary> /// Construct a parser applies three parsers in order and returns a tuple of their results. /// </summary> /// <typeparam name="T">The type of the first value parsed.</typeparam> /// <typeparam name="U">The type of the second value parsed.</typeparam> /// <typeparam name="V">The type of the third value parsed.</typeparam> /// <param name="parser1">The first parser to apply.</param> /// <param name="parser2">The second parser to apply.</param> /// <param name="parser3">The third parser to apply.</param> /// <returns>The resulting parser.</returns> public static TextParser<(T, U, V)> Sequence<T, U, V>( TextParser<T> parser1, TextParser<U> parser2, TextParser<V> parser3) { if (parser1 == null) throw new ArgumentNullException(nameof(parser1)); if (parser2 == null) throw new ArgumentNullException(nameof(parser2)); if (parser3 == null) throw new ArgumentNullException(nameof(parser3)); return input => { var rt = parser1(input); if (!rt.HasValue) return Result.CastEmpty<T, (T, U, V)>(rt); var ru = parser2(rt.Remainder); if (!ru.HasValue) return Result.CastEmpty<U, (T, U, V)>(ru); var rv = parser3(ru.Remainder); if (!rv.HasValue) return Result.CastEmpty<V, (T, U, V)>(rv); return Result.Value((rt.Value, ru.Value, rv.Value), input, rv.Remainder); }; } /// <summary> /// Construct a parser applies four parsers in order and returns a tuple of their results. /// </summary> /// <typeparam name="T">The type of the first value parsed.</typeparam> /// <typeparam name="U">The type of the second value parsed.</typeparam> /// <typeparam name="V">The type of the third value parsed.</typeparam> /// <typeparam name="W">The type of the fourth value parsed.</typeparam> /// <param name="parser1">The first parser to apply.</param> /// <param name="parser2">The second parser to apply.</param> /// <param name="parser3">The third parser to apply.</param> /// <param name="parser4">The fourth parser to apply.</param> /// <returns>The resulting parser.</returns> public static TextParser<(T, U, V, W)> Sequence<T, U, V, W>( TextParser<T> parser1, TextParser<U> parser2, TextParser<V> parser3, TextParser<W> parser4) { if (parser1 == null) throw new ArgumentNullException(nameof(parser1)); if (parser2 == null) throw new ArgumentNullException(nameof(parser2)); if (parser3 == null) throw new ArgumentNullException(nameof(parser3)); if (parser4 == null) throw new ArgumentNullException(nameof(parser4)); return input => { var rt = parser1(input); if (!rt.HasValue) return Result.CastEmpty<T, (T, U, V, W)>(rt); var ru = parser2(rt.Remainder); if (!ru.HasValue) return Result.CastEmpty<U, (T, U, V, W)>(ru); var rv = parser3(ru.Remainder); if (!rv.HasValue) return Result.CastEmpty<V, (T, U, V, W)>(rv); var rw = parser4(rv.Remainder); if (!rw.HasValue) return Result.CastEmpty<W, (T, U, V, W)>(rw); return Result.Value((rt.Value, ru.Value, rv.Value, rw.Value), input, rw.Remainder); }; } /// <summary> /// Construct a parser applies five parsers in order and returns a tuple of their results. /// </summary> /// <typeparam name="T">The type of the first value parsed.</typeparam> /// <typeparam name="U">The type of the second value parsed.</typeparam> /// <typeparam name="V">The type of the third value parsed.</typeparam> /// <typeparam name="W">The type of the fourth value parsed.</typeparam> /// <typeparam name="X">The type of the fifth value parsed.</typeparam> /// <param name="parser1">The first parser to apply.</param> /// <param name="parser2">The second parser to apply.</param> /// <param name="parser3">The third parser to apply.</param> /// <param name="parser4">The fourth parser to apply.</param> /// <param name="parser5">The fifth parser to apply.</param> /// <returns>The resulting parser.</returns> public static TextParser<(T, U, V, W, X)> Sequence<T, U, V, W, X>( TextParser<T> parser1, TextParser<U> parser2, TextParser<V> parser3, TextParser<W> parser4, TextParser<X> parser5) { if (parser1 == null) throw new ArgumentNullException(nameof(parser1)); if (parser2 == null) throw new ArgumentNullException(nameof(parser2)); if (parser3 == null) throw new ArgumentNullException(nameof(parser3)); if (parser4 == null) throw new ArgumentNullException(nameof(parser4)); if (parser5 == null) throw new ArgumentNullException(nameof(parser5)); return input => { var rt = parser1(input); if (!rt.HasValue) return Result.CastEmpty<T, (T, U, V, W, X)>(rt); var ru = parser2(rt.Remainder); if (!ru.HasValue) return Result.CastEmpty<U, (T, U, V, W, X)>(ru); var rv = parser3(ru.Remainder); if (!rv.HasValue) return Result.CastEmpty<V, (T, U, V, W, X)>(rv); var rw = parser4(rv.Remainder); if (!rw.HasValue) return Result.CastEmpty<W, (T, U, V, W, X)>(rw); var rx = parser5(rw.Remainder); if (!rx.HasValue) return Result.CastEmpty<X, (T, U, V, W, X)>(rx); return Result.Value((rt.Value, ru.Value, rv.Value, rw.Value, rx.Value), input, rx.Remainder); }; } /// <summary> /// Creates a parser which applies one of the specified parsers. /// </summary> /// <typeparam name="TKind">The kind of the tokens being parsed.</typeparam> /// <typeparam name="T">The type of value being parsed.</typeparam> /// <param name="parsers">The parsers to try from left to right.</param> /// <returns>A parser which applies one of the specified parsers.</returns> public static TokenListParser<TKind, T> OneOf<TKind, T>(params TokenListParser<TKind, T>[] parsers) { if (parsers == null) throw new ArgumentNullException(nameof(parsers)); if (parsers.Length == 0) { return i => TokenListParserResult.Empty<TKind, T>(TokenList<TKind>.Empty); } TokenListParser<TKind, T> c = parsers[0]; for (int i = 1; i < parsers.Length; i++) { c = c.Or(parsers[i]); } return c; } /// <summary> /// Creates a parser which applies one of the specified parsers. /// </summary> /// <typeparam name="T">The type of value being parsed.</typeparam> /// <param name="parsers">The parser to try from left to right.</param> /// <returns>A parser which applies one of the specified parsers.</returns> public static TextParser<T> OneOf<T>(params TextParser<T>[] parsers) { if (parsers == null) throw new ArgumentNullException(nameof(parsers)); if (parsers.Length == 0) { return i => Result.Empty<T>(TextSpan.None); } TextParser<T> c = parsers[0]; for (int i = 1; i < parsers.Length; i++) { c = c.Or(parsers[i]); } return c; } } }
47.815504
170
0.573976
[ "Apache-2.0" ]
Ellested/superpower
src/Superpower/Parse.cs
30,843
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. */ namespace NVelocity.Runtime.Directive { using App.Event; using Context; using Exception; using Parser.Node; using System.Collections.Generic; /// <summary> Pluggable directive that handles the <code>#parse()</code> /// statement in VTL. /// /// <pre> /// Notes: /// ----- /// 1) The parsed source material can only come from somewhere in /// the TemplateRoot tree for security reasons. There is no way /// around this. If you want to include content from elsewhere on /// your disk, use a link from somwhere under Template Root to that /// content. /// /// 2) There is a limited parse depth. It is set as a property /// "directive.parse.max.depth = 10" by default. This 10 deep /// limit is a safety feature to prevent infinite loops. /// </pre> /// /// </summary> /// <author> <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a> /// </author> /// <author> <a href="mailto:jvanzyl@apache.org">Jason van Zyl</a> /// </author> /// <author> <a href="mailto:Christoph.Reck@dlr.de">Christoph Reck</a> /// </author> /// <version> $Id: Parse.java 724825 2008-12-09 18:56:06Z nbubna $ /// </version> public class Parse : InputBase { /// <summary> Return type of this directive.</summary> /// <returns> The type of this directive. /// </returns> override public int Type { get { return NVelocity.Runtime.Directive.DirectiveType.LINE; } } private int maxDepth; /// <summary> Return name of this directive.</summary> /// <returns> The name of this directive. /// </returns> public override string Name { get { return "parse"; } } /// <summary> Init's the #parse directive.</summary> /// <param name="rs"> /// </param> /// <param name="context"> /// </param> /// <param name="node"> /// </param> /// <throws> TemplateInitException </throws> public override void Init(IRuntimeServices rs, IInternalContextAdapter context, INode node) { base.Init(rs, context, node); this.maxDepth = rsvc.GetInt(NVelocity.Runtime.RuntimeConstants.PARSE_DIRECTIVE_MAXDEPTH, 10); } /// <summary> iterates through the argument list and renders every /// argument that is appropriate. Any non appropriate /// arguments are logged, but render() continues. /// </summary> /// <param name="context"> /// </param> /// <param name="writer"> /// </param> /// <param name="node"> /// </param> /// <returns> True if the directive rendered successfully. /// </returns> /// <throws> IOException </throws> /// <throws> ResourceNotFoundException </throws> /// <throws> ParseErrorException </throws> /// <throws> MethodInvocationException </throws> public override bool Render(IInternalContextAdapter context, System.IO.TextWriter writer, INode node) { /* * if rendering is no longer allowed (after a stop), we can safely * skip execution of all the parse directives. */ if (!context.AllowRendering) { return true; } /* * did we Get an argument? */ if (node.GetChild(0) == null) { rsvc.Log.Error("#parse() null argument"); return false; } /* * does it have a value? If you have a null reference, then no. */ object value = node.GetChild(0).Value(context); if (value == null) { rsvc.Log.Error("#parse() null argument"); return false; } /* * Get the path */ string sourcearg = value.ToString(); /* * check to see if the argument will be changed by the event cartridge */ string arg = EventHandlerUtil.IncludeEvent(rsvc, context, sourcearg, context.CurrentTemplateName, Name); /* * a null return value from the event cartridge indicates we should not * input a resource. */ bool blockinput = false; if (arg == null) blockinput = true; if (maxDepth > 0) { /* * see if we have exceeded the configured depth. */ object[] templateStack = context.TemplateNameStack; if (templateStack.Length >= maxDepth) { System.Text.StringBuilder path = new System.Text.StringBuilder(); for (int i = 0; i < templateStack.Length; ++i) { path.Append(" > " + templateStack[i]); } rsvc.Log.Error("Max recursion depth reached (" + templateStack.Length + ')' + " File stack:" + path); return false; } } /* * now use the Runtime resource loader to Get the template */ Template t = null; try { if (!blockinput) t = rsvc.GetTemplate(arg, GetInputEncoding(context)); } catch (ResourceNotFoundException rnfe) { /* * the arg wasn't found. Note it and throw */ rsvc.Log.Error("#parse(): cannot find template '" + arg + "', called at " + Log.Log.FormatFileString(this)); throw rnfe; } catch (ParseErrorException pee) { /* * the arg was found, but didn't parse - syntax Error * note it and throw */ rsvc.Log.Error("#parse(): syntax error in #parse()-ed template '" + arg + "', called at " + Log.Log.FormatFileString(this)); throw pee; } /** * pass through application level runtime exceptions */ catch (System.SystemException e) { rsvc.Log.Error("Exception rendering #parse(" + arg + ") at " + Log.Log.FormatFileString(this)); throw e; } catch (System.Exception e) { string msg = "Exception rendering #parse(" + arg + ") at " + Log.Log.FormatFileString(this); rsvc.Log.Error(msg, e); throw new VelocityException(msg, e); } /** * Add the template name to the macro libraries list */ System.Collections.IList macroLibraries = context.MacroLibraries; /** * if macroLibraries are not set create a new one */ if (macroLibraries == null) { macroLibraries = new List<object>(); } context.MacroLibraries = macroLibraries; macroLibraries.Add(arg); /* * and render it */ try { if (!blockinput) { context.PushCurrentTemplateName(arg); ((SimpleNode)t.Data).Render(context, writer); } } /** * pass through application level runtime exceptions */ catch (System.SystemException e) { /** * LogMessage #parse errors so the user can track which file called which. */ rsvc.Log.Error("Exception rendering #parse(" + arg + ") at " + Log.Log.FormatFileString(this)); throw e; } catch (System.Exception e) { string msg = "Exception rendering #parse(" + arg + ") at " + Log.Log.FormatFileString(this); rsvc.Log.Error(msg, e); throw new VelocityException(msg, e); } finally { if (!blockinput) context.PopCurrentTemplateName(); } /* * note - a blocked input is still a successful operation as this is * expected behavior. */ return true; } } }
33.313589
140
0.506537
[ "Apache-2.0" ]
abelli85/nvelocity
NVelocity/NVelocitySL/Runtime/Directive/Parse.cs
9,561
C#
using CRM.CommonFiles.Interfaces; using CRM.CommonFiles.Models; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.Entity; namespace CRM.DAL { public class CRMRepository : ICRMRepository { public IEnumerable<ClientType> GetClientTypes() { using (PhoneCompanyContext context = new PhoneCompanyContext()) { var t = context.ClientTypes.ToList(); return t; } } public void AddClient(Client client) { if (client != null) using (PhoneCompanyContext context = new PhoneCompanyContext()) { context.Entry(client.TypeId).State = System.Data.Entity.EntityState.Unchanged; context.Entry(client).State = System.Data.Entity.EntityState.Added; context.Clients.Add(client); context.SaveChanges(); } } public Client GetClientById(string Id) { using (PhoneCompanyContext context = new PhoneCompanyContext()) { return context.Clients.FirstOrDefault(c => c.Id == Id); } } public IEnumerable<Line> GetLinesByClientId(string Id) { using (PhoneCompanyContext context = new PhoneCompanyContext()) { //var x=context.Lines.Include(li=>li.Package).Where(l=>l.ClientId==Id).ToList(); //var x = context.Clients.Include(c => c.Lines).Where(c => c.Id == Id).ToList(); var t = context.Lines.Where(l => l.ClientId == Id).ToList(); return t; } } public void SendCall(Call call) { if (call != null) using (PhoneCompanyContext context = new PhoneCompanyContext()) { try { //context.Entry(call.Line).State = System.Data.Entity.EntityState.Unchanged; //context.Entry(call.Line.Package).State = System.Data.Entity.EntityState.Unchanged; context.Entry(call).State = System.Data.Entity.EntityState.Added; context.Calls.Add(call); context.SaveChanges(); } catch (Exception x) { Debug.Write(x.Message); throw; } } } public void SendCall(SMS sMS) { if (sMS != null) using (PhoneCompanyContext context = new PhoneCompanyContext()) { context.Entry(sMS.Line).State = System.Data.Entity.EntityState.Unchanged; //context.Entry(sMS.Line.Package).State = System.Data.Entity.EntityState.Unchanged; context.Entry(sMS).State = System.Data.Entity.EntityState.Added; context.SMSs.Add(sMS); context.SaveChanges(); } } public IEnumerable<Client> GetClients() { using (PhoneCompanyContext context = new PhoneCompanyContext()) { var t = context.Clients; if (t != null) return t.ToList(); else return null; } } public IEnumerable<Line> GetLines() { using (PhoneCompanyContext context = new PhoneCompanyContext()) { var t = context.Lines.ToList(); return t; } } public IEnumerable<Package> GetPackages() { using (PhoneCompanyContext context = new PhoneCompanyContext()) { var t = context.Packages.ToList(); return t; } } public void AddLine(Line line) { if (line != null) using (PhoneCompanyContext context = new PhoneCompanyContext()) { try { //if(line.Client != null) //{ // line.ClientId = line.Client.Id; // line.Client = null; //} //if (line.Package != null) //{ // line.PackageId = line.Package.Id; // line.Package = null; //} context.Lines.Add(line); //context.Entry(line.Client).State = System.Data.Entity.EntityState.Unchanged; //context.Entry(line.Package).State = System.Data.Entity.EntityState.Unchanged; context.Entry(line).State = System.Data.Entity.EntityState.Added; context.SaveChanges(); } catch (Exception x) { Debug.Write(x.Message); } } } public void AddPackageDetails(PackageInclude packageInclude) { if (packageInclude != null) using (PhoneCompanyContext context = new PhoneCompanyContext()) { try { context.Entry(packageInclude.Package).State = System.Data.Entity.EntityState.Unchanged; context.Entry(packageInclude).State = System.Data.Entity.EntityState.Added; context.PackageIncludes.Add(packageInclude); context.SaveChanges(); } catch (Exception x) { Debug.Write(x.Message); } } } public IEnumerable<Line> GetLinesofClient(Client c) { using (PhoneCompanyContext context = new PhoneCompanyContext()) { var t = context.Lines.Where(l => l.ClientId == c.Id).ToList(); return t; } } public IEnumerable<SMS> GetSMSsOfClient(string clintId) { using (PhoneCompanyContext context = new PhoneCompanyContext()) { List<Line> lines = GetLinesByClientId(clintId).ToList(); List<SMS> smss = new List<SMS>(); for (int i = 0; i < lines.Count; i++) { //לא עובד! //calls.AddRange(context.Calls.Where(c => c.LineId == lines[i].Id)); //כן עובד! foreach (var item in context.SMSs) { if (item.LineId == lines[i].Id) { smss.Add(item); } } } return smss; } } public IEnumerable<Call> GetCallsOfClient(string clintId) { using (PhoneCompanyContext context = new PhoneCompanyContext()) { List<Line> lines = GetLinesByClientId(clintId).ToList(); List<Call> calls = new List<Call>(); for (int i = 0; i < lines.Count; i++) { //לא עובד! //calls.AddRange(context.Calls.Where(c => c.LineId == lines[i].Id)); //כן עובד! foreach (var item in context.Calls) { if (item.LineId == lines[i].Id) { calls.Add(item); } } } return calls; } } public IEnumerable<Call> GetCallsOfLine(int lineId) { using (PhoneCompanyContext context = new PhoneCompanyContext()) { List<Call> calls = new List<Call>(); foreach (var item in context.Calls) { if (item.LineId == lineId) { calls.Add(item); } } return calls; } } private bool method(Call c, Line line) { if (c.LineId == line.Id) return true; else return false; } public ClientType GetClientType(Client client) { using (PhoneCompanyContext context = new PhoneCompanyContext()) { return context.ClientTypes.FirstOrDefault(c => c.Id == client.ClientTypeId); } } #region /* //public T ExecuteDbFunction<T>(Func<PhoneCompanyContext, T> functions) //{ // using (PhoneCompanyContext context = new PhoneCompanyContext()) // { // var res = functions(context); // context.SaveChanges(); // return res; // } //} public T ExecuteDbAction(params Func<PhoneCompanyContext>[] actions) { using (PhoneCompanyContext context = new PhoneCompanyContext()) { foreach (var action in actions) { action(context); } context.SaveChanges(); } } public void ExecuteDbAction<T>( Func<PhoneCompanyContext,T> function) { using (PhoneCompanyContext context = new PhoneCompanyContext()) { function(context); context.SaveChanges(); } } //public void SendCall2(Call call) => ExecuteDbAction((context) => Sendcallwithcontext(context, call)); public void Sendcallwithcontext(PhoneCompanyContext context, Call call) { context.Entry(call.Line).State = System.Data.Entity.EntityState.Unchanged; context.Entry(call).State = System.Data.Entity.EntityState.Added; context.Calls.Add(call); } public void SendCallANDSMS2(Call call, SMS sms) { ExecuteDbAction((context) => Sendcallwithcontext(context, call), (context) => Sendcallwithcontext(context, sms)); } private void Sendcallwithcontext(PhoneCompanyContext context, SMS sms) { //adds sms to context } */ #endregion public IEnumerable<SMS> GetSMSsOfLine(int lineId) { using (PhoneCompanyContext context = new PhoneCompanyContext()) { List<SMS> smss = new List<SMS>(); foreach (var item in context.SMSs) { if (item.LineId == lineId) { smss.Add(item); } } return smss; } } public Package GetPackage(int id) { using (PhoneCompanyContext context = new PhoneCompanyContext()) { return context.Packages.FirstOrDefault(p => p.Id == id); } } public Client DeleteClient(Client client) { using (PhoneCompanyContext context = new PhoneCompanyContext()) { return context.Clients.Remove(client); } } public Line DeleteLine(Line line) { using (PhoneCompanyContext context = new PhoneCompanyContext()) { return context.Lines.Remove(line); } } public Package GetPackage(string name) { using (PhoneCompanyContext context = new PhoneCompanyContext()) { return context.Packages.FirstOrDefault(p => p.Name == name); } } } }
33.315934
125
0.466645
[ "MIT" ]
shayutut/CellPhoneServiceCompanyProject
CellPhoneService/CRM.DAL/CRMRepository.cs
12,153
C#
using AutoMapper; using FilmesAPI.Data.Dtos; using FilmesAPI.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace FilmesAPI.Profiles { public class FilmeProfile : Profile { public FilmeProfile() { CreateMap<CreateFilmeDto, Filme>(); CreateMap<Filme, ReadFilmeDto>(); CreateMap<UpdateFilmeDto, Filme>(); } } }
21.190476
47
0.658427
[ "MIT" ]
g-aleprojetos/Curso_Alura
API Rest com dotNet5/alura-csharp-1/FilmesApi/Profiles/FilmeProfile.cs
447
C#
//////////////////////////////////////////////////////////////////////////////// //NUnit tests for "EF Core Provider for LCPI OLE DB" // IBProvider and Contributors. 02.05.2021. using System; using System.Data; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using Microsoft.EntityFrameworkCore; using NUnit.Framework; using xdb=lcpi.data.oledb; namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D1.Query.Operators.SET_001.GreaterThan.Complete.Int64.NullableInt16{ //////////////////////////////////////////////////////////////////////////////// using T_DATA1 =System.Int64; using T_DATA2 =System.Nullable<System.Int16>; //////////////////////////////////////////////////////////////////////////////// //class TestSet_504__param__02__VN public static class TestSet_504__param__02__VN { private const string c_NameOf__TABLE ="DUAL"; private sealed class MyContext:TestBaseDbContext { [Table(c_NameOf__TABLE)] public sealed class TEST_RECORD { [Key] [Column("ID")] public System.Int32? TEST_ID { get; set; } };//class TEST_RECORD //---------------------------------------------------------------------- public DbSet<TEST_RECORD> testTable { get; set; } //---------------------------------------------------------------------- public MyContext(xdb.OleDbTransaction tr) :base(tr) { }//MyContext };//class MyContext //----------------------------------------------------------------------- [Test] public static void Test_001() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { T_DATA1 vv1=3; T_DATA2 vv2=null; var recs=db.testTable.Where(r => vv1 /*OP{*/ > /*}OP*/ vv2); foreach(var r in recs) { TestServices.ThrowSelectedRow(); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE NULL")); }//using db tr.Commit(); }//using tr }//using cn }//Test_001 //----------------------------------------------------------------------- [Test] public static void Test_002() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { T_DATA1 vv1=3; T_DATA2 vv2=null; var recs=db.testTable.Where(r => !(vv1 /*OP{*/ > /*}OP*/ vv2)); foreach(var r in recs) { TestServices.ThrowSelectedRow(); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE NULL")); }//using db tr.Commit(); }//using tr }//using cn }//Test_002 };//class TestSet_504__param__02__VN //////////////////////////////////////////////////////////////////////////////// }//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D1.Query.Operators.SET_001.GreaterThan.Complete.Int64.NullableInt16
27.758333
138
0.533473
[ "MIT" ]
ibprovider/Lcpi.EFCore.LcpiOleDb
Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D1/Query/Operators/SET_001/GreaterThan/Complete/Int64/NullableInt16/TestSet_504__param__02__VN.cs
3,333
C#
 using System; namespace Decorator { //Concrete Component public class DataSet: DataSetBase { public override void Write() { //salvar dados dataset. Console.WriteLine("DataSet.Write() invocado!!"); } } }
16.875
60
0.562963
[ "Apache-2.0" ]
Rafael-Prado/Padroes-de-Projeto-C_Sharp
PadroesDeProjetoCsharp/Decorator/DataSet.cs
272
C#
/* * Copyright 2010-2013 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. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Threading; #if AWS_ASYNC_API using System.Threading.Tasks; #endif namespace Amazon.Runtime.Internal.Util { internal class EventStream : WrapperStream { internal delegate void ReadProgress(int bytesRead); internal event ReadProgress OnRead; bool disableClose; //Stream wrappedStream; internal EventStream(Stream stream, bool disableClose) : base(stream) { //this.wrappedStream = stream; this.disableClose = disableClose; } protected override void Dispose(bool disposing) { } public override bool CanRead { get { return BaseStream.CanRead; } } public override bool CanSeek { get { return BaseStream.CanSeek; } } public override bool CanTimeout { get { return BaseStream.CanTimeout; } } public override bool CanWrite { get { return BaseStream.CanWrite; } } public override long Length { get { return BaseStream.Length; } } public override long Position { get { return BaseStream.Position; } set { BaseStream.Position = value; } } public override int ReadTimeout { get { return BaseStream.ReadTimeout; } set { BaseStream.ReadTimeout = value; } } public override int WriteTimeout { get { return BaseStream.WriteTimeout; } set { BaseStream.WriteTimeout = value; } } public override void Flush() { BaseStream.Flush(); } public override int Read(byte[] buffer, int offset, int count) { int bytesRead = BaseStream.Read(buffer, offset, count); if (this.OnRead != null) { this.OnRead(bytesRead); } return bytesRead; } public override long Seek(long offset, SeekOrigin origin) { return BaseStream.Seek(offset, origin); } public override void SetLength(long value) { BaseStream.SetLength(value); } public override void Write(byte[] buffer, int offset, int count) { throw new NotImplementedException(); } public override void WriteByte(byte value) { throw new NotImplementedException(); } #if AWS_ASYNC_API public override Task FlushAsync(CancellationToken cancellationToken) { return BaseStream.FlushAsync(cancellationToken); } public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { int bytesRead = await BaseStream.ReadAsync(buffer, offset, count, cancellationToken).ConfigureAwait(false); if (this.OnRead != null) { this.OnRead(bytesRead); } return bytesRead; } public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { throw new NotImplementedException(); } #endif #if !NETSTANDARD public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state) { var result = new AsyncResult() { AsyncState = state, CompletedSynchronously = true, IsCompleted = true, AsyncWaitHandle = new ManualResetEvent(true) }; try { int bytesRead = this.Read(buffer, offset, count); result.Return = bytesRead; } catch (Exception e) { result.Return = e; } if (callback != null) callback(result); return result; } public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state) { throw new NotImplementedException(); } public override void Close() { if (!disableClose) { BaseStream.Close(); } } public override int EndRead(IAsyncResult asyncResult) { var result = asyncResult as AsyncResult; if (result == null) throw new ArgumentException("Parameter asyncResult was not of type Amazon.Runtime.Internal.Util.AsyncResult", "asyncResult"); if (result.Return is Exception) throw (Exception)result.Return; return Convert.ToInt32(result.Return, CultureInfo.InvariantCulture); } public override void EndWrite(IAsyncResult asyncResult) { throw new NotImplementedException(); } class AsyncResult : IAsyncResult { public object AsyncState { get; internal set; } public WaitHandle AsyncWaitHandle { get; internal set; } public bool CompletedSynchronously { get; internal set; } public bool IsCompleted { get; internal set; } internal object Return { get; set; } } #endif } }
27.9
141
0.575595
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Core/Amazon.Runtime/Internal/Util/EventStream.cs
6,140
C#
using PMDToolkit.Core; using PMDToolkit.Data; using PMDToolkit.Graphics; using PMDToolkit.Logic.Gameplay; using PMDToolkit.Maps; using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Threading; using System.Windows.Forms; namespace PMDToolkit.Editors { public partial class MapEditor : Form { private object drawLock; private bool runningAnim; private volatile int animationTimer; private Thread animThread; private int animFrame; private static List<Image> tiles; public static int currentTileset; public static bool mapEditing; private static string fileName; public enum EditLayer { Data = 0, Ground = 1, PropBack = 2, PropFront = 3, Fringe = 4 } public static bool showDataLayer; public static List<bool> showGroundLayer; public static List<bool> showPropBackLayer; public static List<bool> showPropFrontLayer; public static List<bool> showFringeLayer; public static EditLayer chosenEditLayer; public static int chosenLayer; public enum TileEditMode { Draw = 0, Fill = 1, Eyedrop = 2 } public static TileEditMode chosenEditMode; private static bool inAnimMode; private static Loc2D chosenTile; private static int chosenTileset; private static TileAnim chosenAnim; public delegate void RefreshCallback(); public MapEditor() { drawLock = new object(); inAnimMode = false; chosenTile = new Loc2D(); chosenTileset = 0; chosenAnim = new TileAnim(); SetupLayerVisibility(); InitializeComponent(); if (tiles == null) { tiles = new List<Image>(); for (int i = 0; i < 10; i++) { tiles.Add(new Bitmap(Paths.TilesPath + "Tiles" + i + ".png")); } } RefreshTitle(); if (!Directory.Exists(Paths.MapPath)) Directory.CreateDirectory(Paths.MapPath); openFileDialog.InitialDirectory = Directory.GetCurrentDirectory() + "\\" + Paths.MapPath; saveFileDialog.InitialDirectory = Directory.GetCurrentDirectory() + "\\" + Paths.MapPath; tbTileset.Value = 0; nudTimeLimit.Maximum = int.MaxValue; for (int i = 0; i < 12; i++) { cbWeather.Items.Add(((Enums.Weather)i).ToString()); } nudDarkness.Maximum = int.MaxValue; nudFrameLength.Maximum = int.MaxValue; RefreshTileset(); RefreshAnimControls(); ReloadMusic(); LoadMapProperties(); } private void NewToolStripMenuItem_Click(object sender, EventArgs e) { Game.UpdateLoadMsg("Loading Map..."); MainPanel.EnterLoadPhase(Game.GameLoadState.Loading); Processor.StartMap("", Processor.Seed); Logic.Display.Screen.ForceReady(); RefreshTitle(); LoadMapProperties(); SetupLayerVisibility(); if (MainPanel.CurrentMapLayerEditor != null) MainPanel.CurrentMapLayerEditor.LoadLayers(); MainPanel.EnterLoadPhase(Game.GameLoadState.Loaded); } private void OpenToolStripMenuItem_Click(object sender, EventArgs e) { DialogResult result = openFileDialog.ShowDialog(); if (result == DialogResult.OK) { Game.UpdateLoadMsg("Loading Map..."); MainPanel.EnterLoadPhase(Game.GameLoadState.Loading); fileName = openFileDialog.FileName; Processor.StartMap(fileName, Processor.Seed); Logic.Display.Screen.ForceReady(); RefreshTitle(); LoadMapProperties(); SetupLayerVisibility(); if (MainPanel.CurrentMapLayerEditor != null) MainPanel.CurrentMapLayerEditor.LoadLayers(); MainPanel.EnterLoadPhase(Game.GameLoadState.Loaded); } } private void SaveAsToolStripMenuItem_Click(object sender, EventArgs e) { DialogResult result = saveFileDialog.ShowDialog(); if (result == DialogResult.OK) { fileName = saveFileDialog.FileName; BasicMap map = Processor.CurrentMap; using (FileStream fileStream = File.Create(fileName)) { using (BinaryWriter writer = new BinaryWriter(fileStream)) { map.Save(writer); } } RefreshTitle(); } } private void SaveToolStripMenuItem_Click(object sender, EventArgs e) { if (fileName == "") { DialogResult result = saveFileDialog.ShowDialog(); if (result == DialogResult.OK) { fileName = saveFileDialog.FileName; BasicMap map = Processor.CurrentMap; using (FileStream fileStream = File.Create(fileName)) { using (BinaryWriter writer = new BinaryWriter(fileStream)) { map.Save(writer); } } } RefreshTitle(); } else { BasicMap map = Processor.CurrentMap; using (FileStream fileStream = File.Create(fileName)) { using (BinaryWriter writer = new BinaryWriter(fileStream)) { map.Save(writer); } } } } private void RefreshTitle() { if (string.IsNullOrWhiteSpace(fileName)) fileName = ""; if (fileName == "") Text = "New Map"; else { string[] fileEnd = fileName.Split('\\'); Text = fileEnd[fileEnd.Length - 1]; } } private void RefreshTileset() { lblTileset.Text = "Tileset: " + tbTileset.Value; RefreshScrollMaximums(); RefreshPic(); } private void RefreshPic() { int picX = picTileset.Size.Width / TextureManager.TILE_SIZE; int picY = picTileset.Size.Height / TextureManager.TILE_SIZE; TextureManager.GetTilesetTileDimensions(currentTileset, out int tileX, out int tileY); UpdatePreviewTile(false); Image endImage = new Bitmap(picTileset.Width, picTileset.Height); using (var graphics = System.Drawing.Graphics.FromImage(endImage)) { int width = picX; if (tileX - hScroll.Value < width) width = tileX - hScroll.Value; int height = picY; if (tileY - vScroll.Value < height) height = tileY - vScroll.Value; lock (drawLock) { graphics.DrawImage(tiles[currentTileset], 0, 0, new Rectangle(hScroll.Value * TextureManager.TILE_SIZE, vScroll.Value * TextureManager.TILE_SIZE, width * TextureManager.TILE_SIZE, height * TextureManager.TILE_SIZE), GraphicsUnit.Pixel); } //draw red square if (currentTileset == chosenTileset && chosenTile.X >= hScroll.Value && chosenTile.X < hScroll.Value + width && chosenTile.Y >= vScroll.Value && chosenTile.Y < vScroll.Value + height) { graphics.DrawRectangle(new Pen(Color.Red, 2), new Rectangle((chosenTile.X - hScroll.Value) * TextureManager.TILE_SIZE + 1, (chosenTile.Y - vScroll.Value) * TextureManager.TILE_SIZE + 1, TextureManager.TILE_SIZE - 2, TextureManager.TILE_SIZE - 2)); } } picTileset.Image = endImage; } private void RefreshTileSelect() { chkAnimationMode.Checked = inAnimMode; tbTileset.Value = currentTileset; lblTileset.Text = "Tileset: " + tbTileset.Value; RefreshScrollMaximums(); int picX = picTileset.Size.Width / TextureManager.TILE_SIZE; int picY = picTileset.Size.Height / TextureManager.TILE_SIZE; bool refreshedPic = false; //check if selected tile is within current scroll view if (chosenTile.X < hScroll.Value || chosenTile.X >= hScroll.Value + picX) { //if not, move it within scroll view int newVal = chosenTile.X - picX / 2; refreshedPic |= (hScroll.Value == newVal); hScroll.Value = Math.Max(newVal, 0); } //check if selected tile is within current scroll view if (chosenTile.Y < vScroll.Value || chosenTile.Y >= vScroll.Value + picY) { //if not, move it within scroll view int newVal = chosenTile.Y - picY / 2; refreshedPic |= (vScroll.Value == newVal); vScroll.Value = Math.Max(newVal, 0); } if (!refreshedPic) RefreshPic(); } private void RefreshScrollMaximums() { int picX = picTileset.Size.Width / TextureManager.TILE_SIZE; int picY = picTileset.Size.Height / TextureManager.TILE_SIZE; TextureManager.GetTilesetTileDimensions(currentTileset, out int tileX, out int tileY); if (tileX - picX <= 0) { hScroll.Maximum = 0; hScroll.Enabled = false; } else { hScroll.Maximum = tileX - picX; } if (tileY - picY <= 0) { vScroll.Maximum = 0; vScroll.Enabled = false; } else { vScroll.Maximum = tileY - picY; } } private void ReloadMusic() { lbxMusic.Items.Clear(); string[] files = Directory.GetFiles(Paths.MusicPath, "*.ogg", SearchOption.TopDirectoryOnly); lbxMusic.Items.Add("None"); lbxMusic.SelectedIndex = 0; for (int i = 0; i < files.Length; i++) { string song = files[i].Substring((Paths.MusicPath).Length); lbxMusic.Items.Add(song); } } private void LoadMapProperties() { txtMapName.Text = Processor.CurrentMap.Title; nudTimeLimit.Value = Processor.CurrentMap.TimeLimit; cbWeather.SelectedIndex = (int)Processor.CurrentMap.Weather; nudDarkness.Value = Processor.CurrentMap.Darkness; chkIndoors.Checked = Processor.CurrentMap.Indoors; for (int i = 0; i < lbxMusic.Items.Count; i++) { string song = (string)lbxMusic.Items[i]; if (song == Processor.CurrentMap.Music) { lbxMusic.SelectedIndex = i; break; } } } private void SetupLayerVisibility() { showDataLayer = false; showGroundLayer = new List<bool>(); for (int i = 0; i < Processor.CurrentMap.GroundLayers.Count; i++) { showGroundLayer.Add(true); } showPropBackLayer = new List<bool>(); for (int i = 0; i < Processor.CurrentMap.PropBackLayers.Count; i++) { showPropBackLayer.Add(true); } showPropFrontLayer = new List<bool>(); for (int i = 0; i < Processor.CurrentMap.PropFrontLayers.Count; i++) { showPropFrontLayer.Add(true); } showFringeLayer = new List<bool>(); for (int i = 0; i < Processor.CurrentMap.FringeLayers.Count; i++) { showFringeLayer.Add(true); } } private void VScroll_Scroll(object sender, ScrollEventArgs e) { RefreshPic(); } private void HScroll_Scroll(object sender, ScrollEventArgs e) { RefreshPic(); } private void MapEditor_Load(object sender, EventArgs e) { mapEditing = true; } private void MapEditor_FormClosing(object sender, FormClosingEventArgs e) { //end animation thread if (animThread != null) { lock (drawLock) runningAnim = false; } } private void MapEditor_FormClosed(object sender, FormClosedEventArgs e) { MainPanel.CurrentMapEditor = null; if (MainPanel.CurrentMapLayerEditor != null) { MainPanel.CurrentMapLayerEditor.Close(); } MainPanel.CurrentMapLayerEditor = null; mapEditing = false; } private void PicTileset_Click(object sender, EventArgs e) { MouseEventArgs args = e as MouseEventArgs; TextureManager.GetTilesetTileDimensions(currentTileset, out int tileX, out int tileY); int clickedX = args.X / TextureManager.TILE_SIZE + hScroll.Value; int clickedY = args.Y / TextureManager.TILE_SIZE + vScroll.Value; if (clickedX < tileX && clickedY < tileY) { chosenTileset = currentTileset; chosenTile = new Loc2D(clickedX, clickedY); RefreshPic(); if (inAnimMode) { if (lbxFrames.SelectedIndex > -1) chosenAnim.Frames[lbxFrames.SelectedIndex] = new TileTexture(chosenTile, chosenTileset); else chosenAnim.Frames.Add(new TileTexture(chosenTile, chosenTileset)); UpdateAnimFrames(); } } } private void TbTileset_Scroll(object sender, EventArgs e) { if (tbTileset.Value == currentTileset) return; currentTileset = tbTileset.Value; RefreshTileset(); } private void BtnReloadSongs_Click(object sender, EventArgs e) { ReloadMusic(); } private void TxtMapName_TextChanged(object sender, EventArgs e) { Processor.CurrentMap.Title = txtMapName.Text; } private void NudTimeLimit_TextChanged(object sender, EventArgs e) { SetIntFromNumeric(ref Processor.CurrentMap.TimeLimit, nudTimeLimit); } private void SetIntFromNumeric(ref int setInt, IntNumericUpDown nud) { int value = nud.Text.ToInt(); if (value >= nud.Minimum && value <= nud.Maximum) setInt = nud.Text.ToInt(); else setInt = (int)nud.Value; } private void CbWeather_SelectedIndexChanged(object sender, EventArgs e) { Processor.CurrentMap.Weather = (Enums.Weather)cbWeather.SelectedIndex; } private void NudDarkness_TextChanged(object sender, EventArgs e) { SetIntFromNumeric(ref Processor.CurrentMap.Darkness, nudDarkness); } private void ChkIndoors_CheckedChanged(object sender, EventArgs e) { Processor.CurrentMap.Indoors = chkIndoors.Checked; } private void LbxMusic_SelectedIndexChanged(object sender, EventArgs e) { if (lbxMusic.SelectedIndex <= 0) { Processor.CurrentMap.Music = ""; } else { string fileName = (string)lbxMusic.Items[lbxMusic.SelectedIndex]; Processor.CurrentMap.Music = fileName; } MainPanel.GameNeedWait = true; while (!MainPanel.GameWaiting) Thread.Sleep(100); Logic.Display.Screen.AddResult(new Logic.Results.BGM(Logic.Gameplay.Processor.CurrentMap.Music, true)); MainPanel.GameNeedWait = false; while (MainPanel.GameWaiting) Thread.Sleep(100); } private void ResizeMapToolStripMenuItem_Click(object sender, EventArgs e) { MapResizeWindow window = new MapResizeWindow(Processor.CurrentMap.Width, Processor.CurrentMap.Height); if (window.ShowDialog() == DialogResult.OK) { Game.UpdateLoadMsg("Resizing Map..."); MainPanel.EnterLoadPhase(Game.GameLoadState.Loading); Loc2D diff = Operations.GetResizeOffset(Processor.CurrentMap.Width, Processor.CurrentMap.Height, window.Width, window.Height, Operations.ReverseDir(window.ResizeDir)); Processor.FocusedCharacter.CharLoc += diff; if (Processor.FocusedCharacter.CharLoc.X < 0) Processor.FocusedCharacter.CharLoc.X = 0; else if (Processor.FocusedCharacter.CharLoc.X >= window.Width) Processor.FocusedCharacter.CharLoc.X = window.Width - 1; if (Processor.FocusedCharacter.CharLoc.Y < 0) Processor.FocusedCharacter.CharLoc.Y = 0; else if (Processor.FocusedCharacter.CharLoc.Y >= window.Height) Processor.FocusedCharacter.CharLoc.Y = window.Height - 1; PMDToolkit.Logic.Display.Screen.AddResult(new PMDToolkit.Logic.Results.Loc(Processor.FocusedCharIndex, Processor.FocusedCharacter.CharLoc)); Processor.CurrentMap.Resize(window.Width, window.Height, Operations.ReverseDir(window.ResizeDir)); PMDToolkit.Logic.Display.Screen.AddResult(new PMDToolkit.Logic.Results.SetMap(Processor.CurrentMap, 0)); MainPanel.EnterLoadPhase(Game.GameLoadState.Loaded); } } private void LayersToolStripMenuItem_Click(object sender, EventArgs e) { if (MainPanel.CurrentMapLayerEditor == null) { MainPanel.CurrentMapLayerEditor = new MapLayerEditor(); } MainPanel.CurrentMapLayerEditor.Show(); } private void ChkTexEyeDropper_CheckedChanged(object sender, EventArgs e) { if (chkTexEyeDropper.Checked) { chkFill.Checked = false; chosenEditMode = TileEditMode.Eyedrop; } else { chosenEditMode = TileEditMode.Draw; } } private void ChkFill_CheckedChanged(object sender, EventArgs e) { if (chkFill.Checked) { chkTexEyeDropper.Checked = false; chosenEditMode = TileEditMode.Fill; } else { chosenEditMode = TileEditMode.Draw; } } private static MapLayer GetChosenEditLayer() { switch (chosenEditLayer) { case EditLayer.Data: return null; case EditLayer.Ground: return Processor.CurrentMap.GroundLayers[chosenLayer]; case EditLayer.PropBack: return Processor.CurrentMap.PropBackLayers[chosenLayer]; case EditLayer.PropFront: return Processor.CurrentMap.PropFrontLayers[chosenLayer]; case EditLayer.Fringe: return Processor.CurrentMap.FringeLayers[chosenLayer]; } return null; } public static void PaintTile(Loc2D loc, TileAnim anim) { if (!Operations.IsInBound(Processor.CurrentMap.Width, Processor.CurrentMap.Height, loc.X, loc.Y)) return; switch (chosenEditLayer) { case EditLayer.Data: { break; } case EditLayer.Ground: case EditLayer.PropBack: case EditLayer.PropFront: case EditLayer.Fringe: { GetChosenEditLayer().Tiles[loc.X, loc.Y] = anim; break; } } Logic.Display.Screen.AddResult(new Logic.Results.SetTile(Processor.CurrentMap, loc)); } public static void EyedropTile(Loc2D loc) { if (!Operations.IsInBound(Processor.CurrentMap.Width, Processor.CurrentMap.Height, loc.X, loc.Y)) return; switch (chosenEditLayer) { case EditLayer.Data: { break; } case EditLayer.Ground: case EditLayer.PropBack: case EditLayer.PropFront: case EditLayer.Fringe: { GetTileTexFromTileAnim(GetChosenEditLayer().Tiles[loc.X, loc.Y]); break; } } } public static TileAnim GetBrush() { TileAnim anim; if (inAnimMode) anim = new TileAnim(chosenAnim); else anim = new TileAnim(chosenTile, chosenTileset); return anim; } public static void FillTile(Loc2D loc, TileAnim anim) { if (!Operations.IsInBound(Processor.CurrentMap.Width, Processor.CurrentMap.Height, loc.X, loc.Y)) return; switch (chosenEditLayer) { case EditLayer.Data: { break; } case EditLayer.Ground: case EditLayer.PropBack: case EditLayer.PropFront: case EditLayer.Fringe: { TileAnim oldAnim = GetChosenEditLayer().Tiles[loc.X, loc.Y]; if (oldAnim != anim) { Operations.FillArray(GetChosenEditLayer().Tiles.GetLength(0), GetChosenEditLayer().Tiles.GetLength(1), (int x, int y) => { return GetChosenEditLayer().Tiles[x, y] == oldAnim; }, (int x, int y) => { GetChosenEditLayer().Tiles[x, y] = new TileAnim(anim); Logic.Display.Screen.AddResult(new Logic.Results.SetTile(Processor.CurrentMap, new Loc2D(x, y))); }, loc); } break; } } } private static void GetTileTexFromTileAnim(TileAnim anim) { if (anim.Frames.Count == 1) { inAnimMode = false; chosenTileset = anim.Frames[0].Sheet; chosenTile = anim.Frames[0].Texture; currentTileset = chosenTileset; //refresh RefreshCallback refresh = new RefreshCallback(MainPanel.CurrentMapEditor.RefreshTileSelect); MainPanel.CurrentMapEditor.Invoke(refresh); } else if (anim.Frames.Count > 1) { inAnimMode = true; chosenAnim = new TileAnim(anim); //refresh RefreshCallback refresh = new RefreshCallback(MainPanel.CurrentMapEditor.RefreshTileSelect); MainPanel.CurrentMapEditor.Invoke(refresh); } } private void ChkAnimationMode_CheckedChanged(object sender, EventArgs e) { if (inAnimMode != chkAnimationMode.Checked) { inAnimMode = chkAnimationMode.Checked; if (inAnimMode) { chosenAnim = new TileAnim(chosenTile, chosenTileset); } else { if (chosenAnim.Frames.Count > 0) { chosenTile = chosenAnim.Frames[0].Texture; chosenTileset = chosenAnim.Frames[0].Sheet; } else { chosenTile = new Loc2D(); chosenTileset = 0; } currentTileset = chosenTileset; } } UpdateAnimFrames(); RefreshTileSelect(); RefreshAnimControls(); } private void RefreshAnimControls() { bool show = inAnimMode; lblFrameLength.Visible = show; nudFrameLength.Value = chosenAnim.FrameLength.ToMillisecs(); nudFrameLength.Visible = show; lblFrames.Visible = show; lbxFrames.Visible = show; btnAddFrame.Visible = show; btnRemoveFrame.Visible = show; } private void ChangeAnimationTimer() { lock (drawLock) { if (inAnimMode) { if (animThread == null) { runningAnim = true; animThread = new Thread(UpdatePreviewTileTimer); animThread.Start(); } animationTimer = chosenAnim.FrameLength.ToMillisecs(); } } } private void UpdatePreviewTileTimer() { while (true) { lock (drawLock) { if (!runningAnim) return; if (inAnimMode) { animFrame++; if (animFrame >= chosenAnim.Frames.Count) animFrame = 0; UpdatePreviewTile(true); } } for (int i = 0; i < animationTimer; i++) { Thread.Sleep(1); } } } private void UpdatePreviewTile(bool timer) { if (inAnimMode) { if (timer) { Image endTileImage = new Bitmap(picTileset.Width, picTileset.Height); using (var graphics = System.Drawing.Graphics.FromImage(endTileImage)) { TileTexture tex = chosenAnim.Frames[animFrame]; graphics.DrawImage(tiles[tex.Sheet], 0, 0, new Rectangle(tex.Texture.X * Graphics.TextureManager.TILE_SIZE, tex.Texture.Y * Graphics.TextureManager.TILE_SIZE, Graphics.TextureManager.TILE_SIZE, Graphics.TextureManager.TILE_SIZE), GraphicsUnit.Pixel); } picTile.Image = endTileImage; } else { lblTileInfo.Text = "[Animation]"; } } else { Image endTileImage = new Bitmap(picTileset.Width, picTileset.Height); lock (drawLock) { using (var graphics = System.Drawing.Graphics.FromImage(endTileImage)) { graphics.DrawImage(tiles[chosenTileset], 0, 0, new Rectangle(chosenTile.X * Graphics.TextureManager.TILE_SIZE, chosenTile.Y * Graphics.TextureManager.TILE_SIZE, Graphics.TextureManager.TILE_SIZE, Graphics.TextureManager.TILE_SIZE), GraphicsUnit.Pixel); } picTile.Image = endTileImage; } lblTileInfo.Text = "Tile" + chosenTileset + " X" + chosenTile.X + " Y" + chosenTile.Y; } } private void UpdateAnimFrames() { int selection = lbxFrames.SelectedIndex; lbxFrames.Items.Clear(); for (int i = 0; i < chosenAnim.Frames.Count; i++) { lbxFrames.Items.Add("Tile" + chosenAnim.Frames[i].Sheet + " X" + chosenAnim.Frames[i].Texture.X + " Y" + chosenAnim.Frames[i].Texture.Y); } if (selection < lbxFrames.Items.Count) lbxFrames.SelectedIndex = selection; ChangeAnimationTimer(); } private void NudFrameLength_TextChanged(object sender, EventArgs e) { int millisecs = 0; SetIntFromNumeric(ref millisecs, nudFrameLength); chosenAnim.FrameLength = RenderTime.FromMillisecs(millisecs); ChangeAnimationTimer(); } private void BtnAddFrame_Click(object sender, EventArgs e) { lock (drawLock) { if (lbxFrames.SelectedIndex > -1) chosenAnim.Frames.Insert(lbxFrames.SelectedIndex, new TileTexture()); else chosenAnim.Frames.Add(new TileTexture()); } UpdateAnimFrames(); } private void BtnRemoveFrame_Click(object sender, EventArgs e) { lock (drawLock) { if (chosenAnim.Frames.Count > 1) { if (lbxFrames.SelectedIndex > -1) chosenAnim.Frames.RemoveAt(lbxFrames.SelectedIndex); else chosenAnim.Frames.RemoveAt(lbxFrames.Items.Count - 1); } if (animFrame > chosenAnim.Frames.Count) animFrame = 0; } UpdateAnimFrames(); } private void LbxFrames_SelectedIndexChanged(object sender, EventArgs e) { if (lbxFrames.SelectedIndex > -1) { chosenTileset = chosenAnim.Frames[lbxFrames.SelectedIndex].Sheet; currentTileset = chosenTileset; chosenTile = chosenAnim.Frames[lbxFrames.SelectedIndex].Texture; RefreshTileSelect(); } } private void BtnReloadTiles_Click(object sender, EventArgs e) { Game.UpdateLoadMsg("Reloading Tiles..."); MainPanel.EnterLoadPhase(Game.GameLoadState.Loading); lock (drawLock) { tiles = new List<Image>(); for (int i = 0; i < 10; i++) { tiles.Add(new Bitmap(Paths.TilesPath + "Tiles" + i + ".png")); } } RefreshTileset(); Conversion.CompileAllTiles(Paths.TilesPath, Paths.CachedGFXPath + "Tile"); TextureManager.NeedTileReload = true; MainPanel.EnterLoadPhase(Game.GameLoadState.Loaded); } private void ClearLayerToolStripMenuItem_Click(object sender, EventArgs e) { MapLayer layer = GetChosenEditLayer(); layer = new MapLayer(layer.Name, layer.Tiles.GetLength(0), layer.Tiles.GetLength(1)); Logic.Display.Screen.AddResult(new Logic.Results.SetMap(Processor.CurrentMap, 0)); } } }
34.159283
212
0.509496
[ "MIT" ]
SupaFresh/PMD-Toolkit
PMDToolkit/Editors/MapEditor.cs
32,385
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:2.0.50727.5446 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ public partial class CMSModules_Blogs_MyBlogs_MyBlogs_Comments_List { /// <summary> /// ucBlogComments control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::CMSModules_Blogs_Controls_Blogs_Comments ucBlogComments; }
33.125
82
0.522013
[ "MIT" ]
CMeeg/kentico-contrib
src/CMS/CMSModules/Blogs/MyBlogs/MyBlogs_Comments_List.aspx.designer.cs
797
C#
/* * MessageMediaLookups.Tests */ using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; using APIMATIC.SDK.Common; using APIMATIC.SDK.Http.Client; using APIMATIC.SDK.Http.Request; using APIMATIC.SDK.Http.Response; using System.Security.Cryptography; using Newtonsoft.Json.Linq; namespace MessageMedia.Lookups.Helpers { static class TestHelper { /// <summary> /// Convert an InputStream to a string (utility function) /// </summary> /// <param name="inStream">The input stream to read</param> /// <returns>string read from the stream</returns> internal static string ConvertStreamToString(Stream inStream) { using (StreamReader reader = new StreamReader(inStream)) { var str = reader.ReadToEnd(); return str; } } /// <summary> /// Recursively check whether the leftTree is a proper subset of the right tree /// </summary> /// <param name="lefrTree">Left tree</param> /// <param name="rightTree">Right tree</param> /// <param name="checkValues">Check primitive values for equality?</param> /// <param name="allowExtra">Are extra elements allowed in right array?</param> /// <param name="isOrdered">Should elements in right be compared in order to left?</param> /// <returns></returns> private static bool IsProperSubsetOf( JObject leftTree, JObject rightTree, bool checkValues, bool allowExtra, bool isOrdered) { foreach (var property in leftTree.Properties()) { // Check if key exists if (rightTree.Property(property.Name) == null) return false; object leftVal = property.Value; object rightVal = rightTree.Property(property.Name).Value; if (leftVal is JObject) { // If left value is tree, right value should be be tree too if (rightVal is JObject) { if (!IsProperSubsetOf( (JObject)leftVal, (JObject)rightVal, checkValues, allowExtra, isOrdered)) { return false; } } else { return false; } } else { // Value comparison if checkValues if (checkValues) { // If left value is a primitive, check if it equals right value if (leftVal == null) { if (rightVal != null) { return false; } } else if (leftVal is JArray) { if (!(rightVal is JArray)) return false; //is array of objects if (((JArray)leftVal).First is JObject) { if (!IsArrayOfJsonObjectsProperSubsetOf( (JArray)leftVal, (JArray)rightVal, checkValues, allowExtra, isOrdered)) return false; } else { if (!IsListProperSubsetOf( (JArray)leftVal, (JArray)rightVal, allowExtra, isOrdered)) return false; } } else if (!leftVal.Equals(rightVal)) { return false; } } } } return true; } /// <summary> /// Check if left array of objects is a subset of right array /// </summary> /// <param name="leftObject">Left array as a JSON string</param> /// <param name="rightObject">Right array as a JSON string</param> /// <param name="checkValues">Check primitive values for equality?</param> /// <param name="allowExtra">Are extra elements allowed in right array?</param> /// <param name="isOrdered">Should elements in right be compared in order to left?</param> /// <returns>True if it is a subset</returns> public static bool IsArrayOfJsonObjectsProperSubsetOf( string leftObject, string rightObject, bool checkValues, bool allowExtra, bool isOrdered) { // Deserialize left and right objects from their respective strings JArray left = APIHelper.JsonDeserialize<dynamic>(leftObject); JArray right = APIHelper.JsonDeserialize<dynamic>(rightObject); return IsArrayOfJsonObjectsProperSubsetOf(left, right, checkValues, allowExtra, isOrdered); } /// <summary> /// Check if left array of objects is a subset of right array /// </summary> /// <param name="leftList">Left array</param> /// <param name="rightList">Right array</param> /// <param name="checkValues">Check primitive values for equality?</param> /// <param name="allowExtra">Are extra elements allowed in right array?</param> /// <param name="isOrdered">Should elements in right be compared in order to left?</param> /// <returns>True if it is a subset</returns> public static bool IsArrayOfJsonObjectsProperSubsetOf( JArray leftList, JArray rightList, bool checkValues, bool allowExtra, bool isOrdered) { // Return false if size different and checking was strict if ((!allowExtra) && (rightList.Count != leftList.Count)) return false; // Create list iterators var leftIter = leftList.GetEnumerator(); var rightIter = rightList.GetEnumerator(); // Iterate left list and check if each value is present in the right list while (leftIter.MoveNext()) { var leftTree = leftIter.Current; bool found = false; //restart right iterator if ordered comparision is not required if (!isOrdered) rightIter = rightList.GetEnumerator(); while (rightIter.MoveNext()) { if (IsProperSubsetOf((JObject)leftTree, (JObject)rightIter.Current, checkValues, allowExtra, isOrdered)) { found = true; break; } } if (!found) return false; } return true; } /// <summary> /// Check whether the a list (as JSON string) is a subset of another list (as JSON string) /// </summary> /// <param name="leftList">Expected List</param> /// <param name="rightList">List to check</param> /// <param name="allowExtra">Are extras allowed in the list to check?</param> /// <param name="isOrdered">Should checking be in order?</param> /// <returns></returns> public static bool IsListProperSubsetOf(string leftListJson, string rightListJson, bool allowExtra, bool isOrdered) { // Deserialize left and right lists from their respective strings JArray left = APIHelper.JsonDeserialize<dynamic>(leftListJson); JArray right = APIHelper.JsonDeserialize<dynamic>(rightListJson); return IsListProperSubsetOf(left, right, allowExtra, isOrdered); } /// <summary> /// Check whether the a list is a subset of another list /// </summary> /// <param name="leftList">Expected List</param> /// <param name="rightList">List to check</param> /// <param name="allowExtra">Are extras allowed in the list to check?</param> /// <param name="isOrdered">Should checking be in order?</param> /// <returns></returns> public static bool IsListProperSubsetOf(JArray leftList, JArray rightList, bool allowExtra, bool isOrdered) { if (isOrdered) { if ((!allowExtra) && (rightList.Count != leftList.Count)) return false; else if (rightList.Count < leftList.Count) return false; int rIndex = 0, lIndex = 0; while (rIndex < rightList.Count) { if(rightList[rIndex].ToString() == leftList[lIndex].ToString()) { lIndex++; } rIndex++; } return (lIndex == leftList.Count); } else { if ((!allowExtra) && (rightList.Count != leftList.Count)) return false; HashSet<object> rHashSet = new HashSet<object>(rightList); return rHashSet.IsSupersetOf(leftList); } } /// <summary> /// Recursively check whether the left JSON object is a proper subset of the right JSON object /// </summary> /// <param name="leftObject">Left JSON object as string</param> /// <param name="rightObject">rightObject Right JSON object as string</param> /// <param name="checkValues">Check primitive values for equality?</param> /// <param name="allowExtra">Are extra elements allowed in right array?</param> /// <param name="isOrdered">Should elements in right be compared in order to left?</param> /// <returns>True, if the given object is a proper subset of other other</returns> internal static bool IsJsonObjectProperSubsetOf(string leftObject, string rightObject, bool checkValues, bool allowExtra, bool isOrdered) { return IsProperSubsetOf( APIHelper.JsonDeserialize<dynamic>(leftObject), APIHelper.JsonDeserialize<dynamic>(rightObject), checkValues, allowExtra, isOrdered); } /// <summary> /// Recursively check whether the left headers map is a proper subset of the right headers map /// </summary> /// <param name="leftDict">Left headers map</param> /// <param name="rightDict">Right headers map</param> /// <returns></returns> public static bool AreHeadersProperSubsetOf( Dictionary<string, string> leftDict, Dictionary<string, string> rightDict) { Dictionary<string, string> leftDictInv = new Dictionary<string, string>(leftDict, StringComparer.CurrentCultureIgnoreCase); Dictionary<string, string> rightDictInv = new Dictionary<string, string>(rightDict, StringComparer.CurrentCultureIgnoreCase); foreach (var leftKey in leftDictInv.Keys) { if (!leftDictInv.ContainsKey(leftKey)) return false; if (null == leftDictInv[leftKey]) continue; if (!leftDictInv[leftKey].Equals(rightDictInv[leftKey])) return false; } return true; } /// <summary> /// Compare the input stream to file byte-by-byte /// </summary> /// <param name="file">First input</param> /// <param name="input">Second input</param> /// <returns>True if stream contains the same content as the file</returns> public static bool IsSameAsFile(string file, Stream input) { return IsSameInputStream(GetFile(file).FileStream, input); } /// <summary> /// Compare two input streams /// </summary> /// <param name="input1">First stream</param> /// <param name="input2">Second stream</param> /// <returns>True if streams contain the same content</returns> public static bool IsSameInputStream(Stream input1, Stream input2) { if (input1 == input2) { return true; } int ch = input1.ReadByte(); while (ch != -1) { int ch2 = input2.ReadByte(); if (ch != ch2) { return false; } ch = input1.ReadByte(); } //should reach end of stream bool input2Finished = (input2.ReadByte() == -1); try { input1.Dispose(); } catch { } try { input2.Dispose(); } catch { } return input2Finished; } /// <summary> /// Downloads a given url and return a path to its local version. /// Files are cached.Second call for the same URL will return cached version. /// </summary> /// <param name="url">URL to download</param> /// <returns>Absolute path to the local downloaded version of file</returns> public static FileStreamInfo GetFile(string url) { string originalFileName = Path.GetFileName(url); string filename = "sdk_tests" + toSHA1(url) + ".tmp"; string tmpPath = Path.GetTempPath(); string filePath = Path.Combine(tmpPath, filename); FileInfo fileInfo = new FileInfo(filePath); FileStream fileStream = null; // if file does not exist locally, download it if (!fileInfo.Exists) { IHttpClient client = ControllerTestBase.GetClient().SharedHttpClient; HttpRequest req = client.Get(url, null, null); req.Headers = new Dictionary<string, string> { {"user-agent", "APIMATIC 2.0" } }; HttpResponse resp = client.ExecuteAsBinary(req); fileStream = System.IO.File.Create(filePath); byte[] buffer = new byte[2048]; int len = resp.RawBody.Read(buffer, 0, 2048); while (len > 0) { fileStream.Write(buffer, 0, len); len = resp.RawBody.Read(buffer, 0, 2048); } fileStream.Position = 0; } else { fileStream = System.IO.File.OpenRead(filePath); } return new FileStreamInfo(fileStream, originalFileName); } /// <summary> /// Get SHA1 hash of a string /// </summary> /// <param name="convertme">The string to convert</param> /// <returns>SHA1 hash</returns> public static string toSHA1(string convertme) { byte[] bytes = Encoding.UTF8.GetBytes(convertme); using (var sha1 = SHA1.Create()) { byte[] hashBytes = sha1.ComputeHash(bytes); return ByteArrayToHexString(hashBytes); } } /// <summary> /// Convert byte array to the hexadecimal representation in string /// </summary> /// <param name="bytes">Byte array to convert</param> /// <returns>Hex representation in string</returns> public static string ByteArrayToHexString(byte[] bytes) { var sb = new StringBuilder(); foreach (byte b in bytes) { var hex = b.ToString("x2"); sb.Append(hex); } return sb.ToString(); } /// <summary> /// Checks if the left items set is the superset of right items set /// </summary> /// <typeparam name="T">Type of items</typeparam> /// <param name="left">Left items set</param> /// <param name="right">Right items set</param> /// <returns>True if the left has all items of right</returns> public static bool IsSuperSetOf<T>(this IEnumerable<T> left, IEnumerable<T> right) { HashSet<T> lHashSet = new HashSet<T>(left); return lHashSet.IsSupersetOf(right); } /// <summary> /// Checks if the left items ordered set is the ordered superset of right items ordered set /// </summary> /// <typeparam name="T">Type of items</typeparam> /// <param name="left">Left items set</param> /// <param name="right">Right items set</param> /// <param name="checkSize">Should the size of left and right be equal as well</param> /// <returns>True if the left has all items of right in the same order</returns> public static bool IsOrderedSupersetOf<T>(this IEnumerable<T> left, IEnumerable<T> right, bool checkSize = false) { var lItr = left.GetEnumerator(); var rItr = right.GetEnumerator(); while(lItr.MoveNext()) { T lCurrent = lItr.Current; //right list ended prematurely if (!rItr.MoveNext()) return false; T rCurrent = rItr.Current; if (!lCurrent.Equals(rCurrent)) return false; } //left and right should also of the same size if(checkSize) { //right items should have been exhaustively read? if (rItr.MoveNext()) return false; } return true; } } }
39.489224
137
0.515472
[ "Apache-2.0" ]
messagemedia/lookups-csharp-sdk
MessageMediaLookups.Tests/Helpers/TestHelper.cs
18,323
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; using Microsoft.PowerFx.Core.Functions; using Microsoft.PowerFx.Core.Localization; using Microsoft.PowerFx.Core.Types; using Microsoft.PowerFx.Core.Utils; namespace Microsoft.PowerFx.Core.Texl.Builtins { // UTCNow() internal sealed class UTCNowFunction : BuiltinFunction { // Multiple invocations may produce different return values. public override bool IsStateless => false; public override bool IsGlobalReliant => true; public override bool IsSelfContained => true; public UTCNowFunction() : base("UTCNow", TexlStrings.AboutUTCNow, FunctionCategories.DateTime, DType.DateTime, 0, 0, 0) { } public override IEnumerable<TexlStrings.StringGetter[]> GetSignatures() { return EnumerableUtils.Yield<TexlStrings.StringGetter[]>(); } } }
29.363636
107
0.69453
[ "MIT" ]
ScriptBox99/Power-Fx
src/libraries/Microsoft.PowerFx.Core/Texl/Builtins/UTCNow.cs
971
C#
using Entitas; [Input] public sealed class CollisionComponent : IComponent { public GameEntity from; public GameEntity to; }
19
53
0.75188
[ "MIT" ]
Milambeer/unity-entitas-infinite-runner
Assets/Sources/Features/Input/CollisionComponent.cs
133
C#
using SF.Feature.Handlebars.SXA.Models; using Sitecore.ContentSearch.Linq; using Sitecore.XA.Foundation.Mvc.Repositories.Base; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace SF.Feature.Handlebars.SXA.Repositories { public class HandlebarQueryContainerRepository : ModelRepository, IHandlebarQueryContainerRepository { public override IRenderingModelBase GetModel() { var model = new HandlebarQueryContainerModel(); FillBaseProperties(model); model.EnablePagination = ((Sitecore.Data.Fields.CheckboxField)model.Item.Fields["Enable Pagination"]).Checked; int itemsPerPage = 10; int.TryParse(model.Item.Fields["Items Per Page"].Value, out itemsPerPage); model.ItemsPerPage = itemsPerPage; model.QueryStringParam = model.Item.Fields["Querystring Parameter"].Value; int currentPage = 1; int.TryParse(HttpContext.Current.Request.QueryString[model.QueryStringParam], out currentPage); model.CurrentPage = currentPage < 1 ? 1 : currentPage; model.CurrentUrl = HttpContext.Current.Request.Url.PathAndQuery; model.CurrentUrl = model.CurrentUrl.Replace(model.QueryStringParam + "=" + model.CurrentPage, ""); if (model.CurrentUrl.IndexOf("?") > -1) { if (!model.CurrentUrl.EndsWith("?") && !model.CurrentUrl.EndsWith("&")) { model.CurrentUrl += "&"; } } else { model.CurrentUrl += "?"; } return model; } } }
34.714286
122
0.619636
[ "MIT" ]
mtelligent/Handlebars-For-Sitecore
src/Feature/Handlebars.SXA/code/Repositories/HandlebarQueryContainerRepository.cs
1,703
C#
using ImageSort.Actions; using ImageSort.Localization; using ReactiveUI; using System; using System.Collections.Generic; using System.Reactive; using System.Reactive.Linq; namespace ImageSort.ViewModels { public class ActionsViewModel : ReactiveObject { private readonly Stack<IReversibleAction> done = new Stack<IReversibleAction>(); private readonly Stack<IReversibleAction> undone = new Stack<IReversibleAction>(); private readonly ObservableAsPropertyHelper<string> lastDone; public string LastDone => lastDone.Value; private readonly ObservableAsPropertyHelper<string> lastUndone; public string LastUndone => lastUndone.Value; public Interaction<string, Unit> NotifyUserOfError { get; } = new Interaction<string, Unit>(); public ReactiveCommand<IReversibleAction, Unit> Execute { get; } public ReactiveCommand<Unit, Unit> Undo { get; } public ReactiveCommand<Unit, Unit> Redo { get; } public ReactiveCommand<Unit, Unit> Clear { get; } public ActionsViewModel() { Execute = ReactiveCommand.CreateFromTask<IReversibleAction>(async action => { try { action.Act(); } catch (Exception ex) { await NotifyUserOfError.Handle(Text.CouldNotActErrorText .Replace("{ErrorMessage}", ex.Message, StringComparison.OrdinalIgnoreCase) .Replace("{ActMessage}", action.DisplayName, StringComparison.OrdinalIgnoreCase)); return; } done.Push(action); undone.Clear(); }); Undo = ReactiveCommand.CreateFromTask(async () => { if (done.TryPop(out var action)) { try { action.Revert(); } catch (Exception ex) { await NotifyUserOfError.Handle(Text.CouldNotUndoErrorText .Replace("{ErrorMessage}", ex.Message, StringComparison.OrdinalIgnoreCase) .Replace("{ActMessage}", action.DisplayName, StringComparison.OrdinalIgnoreCase)); return; } undone.Push(action); } }); Redo = ReactiveCommand.CreateFromTask(async () => { if (undone.TryPop(out var action)) { try { action.Act(); } catch (Exception ex) { await NotifyUserOfError.Handle(Text.CouldNotRedoErrorText .Replace("{ErrorMessage}", ex.Message, StringComparison.OrdinalIgnoreCase) .Replace("{ActMessage}", action.DisplayName, StringComparison.OrdinalIgnoreCase)); return; } done.Push(action); } }); Clear = ReactiveCommand.Create(() => { done.Clear(); undone.Clear(); }); var historyChanges = Execute.Merge(Undo).Merge(Redo).Merge(Clear); lastDone = historyChanges .Select(_ => { if (done.TryPeek(out var action)) return action.DisplayName; return null; }) .ToProperty(this, vm => vm.LastDone); lastUndone = historyChanges .Select(_ => { if (undone.TryPeek(out var action)) return action.DisplayName; return null; }) .ToProperty(this, vm => vm.LastUndone); } } }
33.541667
110
0.498137
[ "MIT" ]
Lolle2000la/Image-Sort
src/ImageSort/ViewModels/ActionsViewModel.cs
4,027
C#
namespace Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801 { using Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.PowerShell; /// <summary> /// A PowerShell PSTypeConverter to support converting to an instance of <see cref="PremierAddOnProperties" /> /// </summary> public partial class PremierAddOnPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter { /// <summary> /// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" /> /// parameter. /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <returns> /// <c>true</c> if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" /> /// parameter, otherwise <c>false</c>. /// </returns> public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); /// <summary> /// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" /> /// parameter. /// </summary> /// <param name="sourceValue">the <see cref="System.Object" /> instance to check if it can be converted to the <see cref="PremierAddOnProperties" /// /> type.</param> /// <returns> /// <c>true</c> if the instance could be converted to a <see cref="PremierAddOnProperties" /> type, otherwise <c>false</c> /// </returns> public static bool CanConvertFrom(dynamic sourceValue) { if (null == sourceValue) { return true; } global::System.Type type = sourceValue.GetType(); if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) { // we say yest to PSObjects return true; } if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) { // we say yest to Hashtables/dictionaries return true; } try { if (null != sourceValue.ToJsonString()) { return true; } } catch { // Not one of our objects } try { string text = sourceValue.ToString()?.Trim(); return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonType.Object; } catch { // Doesn't look like it can be treated as JSON } return false; } /// <summary> /// Determines if the <see cref="sourceValue" /> parameter can be converted to the <see cref="destinationType" /> parameter /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <returns> /// <c>true</c> if the converter can convert the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> /// parameter, otherwise <c>false</c> /// </returns> public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; /// <summary> /// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider" /// /> and <see cref="ignoreCase" /> /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <param name="formatProvider">not used by this TypeConverter.</param> /// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param> /// <returns> /// an instance of <see cref="PremierAddOnProperties" />, or <c>null</c> if there is no suitable conversion. /// </returns> public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); /// <summary> /// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider" /// /> and <see cref="ignoreCase" /> /// </summary> /// <param name="sourceValue">the value to convert into an instance of <see cref="PremierAddOnProperties" />.</param> /// <returns> /// an instance of <see cref="PremierAddOnProperties" />, or <c>null</c> if there is no suitable conversion. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IPremierAddOnProperties ConvertFrom(dynamic sourceValue) { if (null == sourceValue) { return null; } global::System.Type type = sourceValue.GetType(); if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IPremierAddOnProperties).IsAssignableFrom(type)) { return sourceValue; } try { return PremierAddOnProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; } catch { // Unable to use JSON pattern } if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) { return PremierAddOnProperties.DeserializeFromPSObject(sourceValue); } if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) { return PremierAddOnProperties.DeserializeFromDictionary(sourceValue); } return null; } /// <summary>NotImplemented -- this will return <c>null</c></summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <param name="formatProvider">not used by this TypeConverter.</param> /// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param> /// <returns>will always return <c>null</c>.</returns> public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; } }
51.915493
249
0.586408
[ "MIT" ]
3quanfeng/azure-powershell
src/Functions/generated/api/Models/Api20190801/PremierAddOnProperties.TypeConverter.cs
7,231
C#
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. // // Microsoft Bot Framework: http://botframework.com // // Bot Builder SDK Github: // https://github.com/Microsoft/BotBuilder // // Copyright (c) Microsoft Corporation // All rights reserved. // // 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.Linq; using System.Globalization; using System.Threading; using System.Threading.Tasks; using Microsoft.Bot.Connector; using Microsoft.Bot.Builder.Dialogs; using Microsoft.Bot.Builder.Dialogs.Internals; using Microsoft.Bot.Builder.Internals.Fibers; using Moq; using Autofac; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Microsoft.Bot.Builder.Tests { [TestClass] public sealed class LocalizationTests : DialogTestBase { public interface ILocalizedDialog : IDialog<CultureInfo> { Task FirstMessage(IDialogContext context, IAwaitable<IMessageActivity> message); } public static CultureInfo CurrentCulture { get { return Thread.CurrentThread.CurrentUICulture; } } public async static Task UI_Culture_From_Message(string language, CultureInfo current, CultureInfo expected) { var dialog = new Mock<ILocalizedDialog>(); CultureInfo actual = null; dialog .Setup(d => d.StartAsync(It.IsAny<IDialogContext>())) .Returns<IDialogContext>(async c => { c.Wait(dialog.Object.FirstMessage); }); dialog .Setup(d => d.FirstMessage(It.IsAny<IDialogContext>(), It.IsAny<IAwaitable<IMessageActivity>>())) .Returns<IDialogContext, IAwaitable<IMessageActivity>>(async (c, m) => actual = CurrentCulture); Func<IDialog<object>> MakeRoot = () => dialog.Object; using (new FiberTestBase.ResolveMoqAssembly(dialog.Object)) using (var container = Build(Options.None, dialog.Object)) { var toBot = MakeTestMessage(); toBot.Locale = language; using (var scope = DialogModule.BeginLifetimeScope(container, toBot)) { DialogModule_MakeRoot.Register(scope, MakeRoot); var task = scope.Resolve<IPostToBot>(); Assert.AreEqual(current, CurrentCulture); await task.PostAsync(toBot, CancellationToken.None); Assert.AreEqual(current, CurrentCulture); Assert.AreEqual(actual, expected); } } } [TestMethod] public async Task UI_Culture_From_Message_Valid() { var current = CurrentCulture; var cultures = CultureInfo.GetCultures(CultureTypes.SpecificCultures); var expected = cultures.First(c => c != current); await UI_Culture_From_Message(expected.Name, current, expected); } [TestMethod] public async Task UI_Culture_From_Message_Invalid() { string language = "no such language"; var current = CurrentCulture; var expected = current; await UI_Culture_From_Message(language, current, expected); } } }
36.707317
117
0.636545
[ "MIT" ]
Chelimin/MSBotBuilder
CSharp/Tests/Microsoft.Bot.Builder.Tests/LocalizationTests.cs
4,517
C#
using ChainUtils.BouncyCastle.Math; namespace ChainUtils.BouncyCastle.Crypto.Parameters { /** * Public key parameters for NaccacheStern cipher. For details on this cipher, * please see * * http://www.gemplus.com/smart/rd/publications/pdf/NS98pkcs.pdf */ public class NaccacheSternKeyParameters : AsymmetricKeyParameter { private readonly BigInteger g, n; private readonly int lowerSigmaBound; /** * @param privateKey */ public NaccacheSternKeyParameters(bool privateKey, BigInteger g, BigInteger n, int lowerSigmaBound) : base(privateKey) { this.g = g; this.n = n; this.lowerSigmaBound = lowerSigmaBound; } /** * @return Returns the g. */ public BigInteger G { get { return g; } } /** * @return Returns the lowerSigmaBound. */ public int LowerSigmaBound { get { return lowerSigmaBound; } } /** * @return Returns the n. */ public BigInteger Modulus { get { return n; } } } }
23.162791
102
0.655622
[ "MIT" ]
assinnata/ChainUtils
ChainUtils.BouncyCastle/crypto/parameters/NaccacheSternKeyParameters.cs
996
C#
using System; using Debug = UnityEngine.Debug; using Unity.Collections; using Unity.Collections.LowLevel.Unsafe; using Unity.Mathematics; using Unity.Jobs; using Unity.Burst; using UnitySceneExtensions; using Vector3 = UnityEngine.Vector3; using System.Runtime.CompilerServices; namespace Chisel.Core { [Serializable] public struct ChiselExtrudedShape : IBranchGenerator { public readonly static ChiselExtrudedShape DefaultValues = new ChiselExtrudedShape { curveSegments = 8 }; public int curveSegments; [UnityEngine.HideInInspector, NonSerialized] public ChiselBlobAssetReference<ChiselPathBlob> pathBlob; [UnityEngine.HideInInspector, NonSerialized] public ChiselBlobAssetReference<ChiselCurve2DBlob> curveBlob; [UnityEngine.HideInInspector, NonSerialized] internal UnsafeList<SegmentVertex> polygonVerticesList; [UnityEngine.HideInInspector, NonSerialized] internal UnsafeList<int> polygonVerticesSegments; #region Generate [BurstCompile] public int PrepareAndCountRequiredBrushMeshes() { if (!curveBlob.IsCreated) return 0; ref var curve = ref curveBlob.Value; if (!curve.ConvexPartition(curveSegments, out polygonVerticesList, out polygonVerticesSegments, Allocator.Persistent)) return 0; return polygonVerticesSegments.Length; } [BurstCompile] public bool GenerateNodes(ChiselBlobAssetReference<NativeChiselSurfaceDefinition> surfaceDefinitionBlob, NativeList<GeneratedNode> nodes, Allocator allocator) { // TODO: maybe just not bother with pathblob and just convert to path-matrices directly? using (var pathMatrices = pathBlob.Value.GetUnsafeMatrices(Allocator.Temp)) using (var generatedBrushMeshes = new NativeList<ChiselBlobAssetReference<BrushMeshBlob>>(nodes.Length, Allocator.Temp)) { generatedBrushMeshes.Resize(nodes.Length, NativeArrayOptions.ClearMemory); if (!BrushMeshFactory.GenerateExtrudedShape(generatedBrushMeshes, in polygonVerticesList, in polygonVerticesSegments, in pathMatrices, in surfaceDefinitionBlob, allocator)) { for (int i = 0; i < generatedBrushMeshes.Length; i++) { if (generatedBrushMeshes[i].IsCreated) generatedBrushMeshes[i].Dispose(); } return false; } for (int i = 0; i < generatedBrushMeshes.Length; i++) nodes[i] = GeneratedNode.GenerateBrush(generatedBrushMeshes[i]); return true; } } public void Dispose() { if (pathBlob.IsCreated) pathBlob.Dispose(); if (curveBlob.IsCreated) curveBlob.Dispose(); if (polygonVerticesList.IsCreated) polygonVerticesList.Dispose(); if (polygonVerticesSegments.IsCreated) polygonVerticesSegments.Dispose(); pathBlob = default; curveBlob = default; polygonVerticesList = default; polygonVerticesSegments = default; } #endregion #region Surfaces [BurstDiscard] public int RequiredSurfaceCount { get { return 2 + (curveBlob.IsCreated ? curveBlob.Value.controlPoints.Length : 3); } } [BurstDiscard] public void UpdateSurfaces(ref ChiselSurfaceDefinition surfaceDefinition) { } #endregion #region Validation public void Validate() { } [BurstDiscard] public void GetWarningMessages(IChiselMessageHandler messages) { } #endregion #region Reset public void Reset() { this = DefaultValues; } #endregion } [Serializable] public class ChiselExtrudedShapeDefinition : SerializedBranchGenerator<ChiselExtrudedShape> { public const string kNodeTypeName = "Extruded Shape"; public static readonly Curve2D kDefaultShape = new Curve2D(new[]{ new CurveControlPoint2D(-1,-1), new CurveControlPoint2D( 1,-1), new CurveControlPoint2D( 1, 1), new CurveControlPoint2D(-1, 1) }); public Curve2D shape; public ChiselPath path; //[NamedItems(overflow = "Surface {0}")] //public ChiselSurfaceDefinition surfaceDefinition; public override void Reset() { shape = new Curve2D(kDefaultShape); path = new ChiselPath(ChiselPath.Default); base.Reset(); } public override int RequiredSurfaceCount { get { return 2 + shape.controlPoints.Length; } } public override void Validate() { shape ??= new Curve2D(kDefaultShape); path ??= new ChiselPath(ChiselPath.Default); base.Validate(); } public override ChiselExtrudedShape GetBranchGenerator() { settings.pathBlob = ChiselPathBlob.Convert(path, Allocator.TempJob); settings.curveBlob = ChiselCurve2DBlob.Convert(shape, Allocator.TempJob); return base.GetBranchGenerator(); } #region OnEdit // // TODO: code below needs to be cleaned up & simplified // const float kLineDash = 2.0f; const float kVertLineThickness = 0.75f; const float kHorzLineThickness = 1.0f; const float kCapLineThickness = 1.0f; const float kCapLineThicknessSelected = 2.5f; public override void OnEdit(IChiselHandles handles) { var baseColor = handles.color; var noZTestcolor = handles.GetStateColor(baseColor, false, true); var zTestcolor = handles.GetStateColor(baseColor, false, false); path.UpgradeIfNecessary(); for (int i = 0; i < path.segments.Length; i++) { var pathPoint = path.segments[i]; var currMatrix = pathPoint.ToMatrix(); handles.color = baseColor; handles.DoShapeHandle(ref shape, currMatrix); if (i == 0) { if (handles.DoDirectionHandle(ref pathPoint.position, -(pathPoint.rotation * Vector3.forward))) { path.segments[i] = pathPoint; path = new ChiselPath(path); } } else if (i == path.segments.Length - 1) { if (handles.DoDirectionHandle(ref pathPoint.position, (pathPoint.rotation * Vector3.forward))) { path.segments[i] = pathPoint; path = new ChiselPath(path); } } // Draw lines between different segments if (i + 1 < path.segments.Length) { var nextPoint = path.segments[i + 1]; var nextMatrix = nextPoint.ToMatrix(); var controlPoints = shape.controlPoints; for (int c = 0; c < controlPoints.Length; c++) { var controlPoint = controlPoints[c].position; var pointA = currMatrix.MultiplyPoint(controlPoint); var pointB = nextMatrix.MultiplyPoint(controlPoint); handles.color = noZTestcolor; handles.DrawLine(pointA, pointB, lineMode: LineMode.NoZTest, thickness: kCapLineThickness, dashSize: kLineDash); handles.color = zTestcolor; handles.DrawLine(pointA, pointB, lineMode: LineMode.ZTest, thickness: kCapLineThickness, dashSize: kLineDash); } { var pointA = currMatrix.MultiplyPoint(Vector3.zero); var pointB = nextMatrix.MultiplyPoint(Vector3.zero); handles.color = zTestcolor; handles.DrawLine(pointA, pointB, lineMode: LineMode.NoZTest, thickness: kCapLineThickness, dashSize: kLineDash); handles.color = zTestcolor; handles.DrawLine(pointA, pointB, lineMode: LineMode.ZTest, thickness: kCapLineThickness, dashSize: kLineDash); } handles.color = baseColor; } // TODO: cannot rotate so far that one path plane intersects with shape on another plane // ... or just fail when it's wrong? } for (int i = 0; i < path.segments.Length; i++) { var pathPoint = path.segments[i]; if (handles.DoPathPointHandle(ref pathPoint)) { var originalSegments = path.segments; var newPath = new ChiselPath(new ChiselPathPoint[originalSegments.Length]); System.Array.Copy(originalSegments, newPath.segments, originalSegments.Length); newPath.segments[i] = pathPoint; path = newPath; } } // TODO: draw curved path } #endregion } }
40.446281
215
0.559665
[ "MIT" ]
FV7VR3/Chisel.Prototype
Packages/com.chisel.core/Chisel/Core/Generators/ExtrudedShape/ChiselExtrudedShapeDefinition.cs
9,788
C#
// ------------------------------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See LICENSE in the repo root for license information. // ------------------------------------------------------------------------------------------------- using System; using System.Collections.Generic; using Microsoft.AspNetCore.Http; using Microsoft.Health.Dicom.Api.Extensions; using Microsoft.Health.Dicom.Core.Messages.Retrieve; using NSubstitute; using Xunit; namespace Microsoft.Health.Dicom.Api.UnitTests.Extensions { public class HttpRequestExtensionsTests { [Fact] public void GivenEmptyHeaders_WhenGetAcceptHeaders_ThenShouldReturnEmpty() { var httpRequest = Substitute.For<HttpRequest>(); IHeaderDictionary headers = new HeaderDictionary(); httpRequest.Headers.Returns(headers); IEnumerable<AcceptHeader> acceptHeaders = httpRequest.GetAcceptHeaders(); Assert.Empty(acceptHeaders); } [Fact] public void GivenNonEmptyHeaders_WhenGetAcceptHeaders_ThenShouldReturnHeaders() { var httpRequest = Substitute.For<HttpRequest>(); IHeaderDictionary headers = new HeaderDictionary(); headers.Add("accept", "application/dicom"); httpRequest.Headers.Returns(headers); IEnumerable<AcceptHeader> acceptHeaders = httpRequest.GetAcceptHeaders(); Assert.Single(acceptHeaders); } [Fact] public void GivenNullHttpRequest_WhenGetAcceptHeaders_ThenShouldThrowException() { Assert.Throws<ArgumentNullException>(() => HttpRequestExtensions.GetAcceptHeaders(null)); } } }
39.565217
101
0.618132
[ "MIT" ]
10thmagnitude/dicom-server
src/Microsoft.Health.Dicom.Api.UnitTests/Extensions/HttpRequestExtensionsTests.cs
1,822
C#
// Released under the MIT License. // // Copyright (c) 2018 Ntreev Soft co., Ltd. // Copyright (c) 2020 Jeesu Choi // // 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. // // Forked from https://github.com/NtreevSoft/Crema // Namespaces and files starting with "Ntreev" have been renamed to "JSSoft". using JSSoft.Library; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; namespace JSSoft.Crema.Data { public static class CremaDataRowUtility { public static bool GetEnabled(object component) { if (component == null) return true; if (component is DataRowView dataRowView && dataRowView.Row is InternalDataRow dataRow) return dataRow.IsEnabled; throw new ArgumentException(nameof(component)); } public static TagInfo GetTags(object component) { if (component == null) return TagInfo.All; if (component is DataRowView dataRowView && dataRowView.Row is InternalDataRow dataRow) return dataRow.Tags; throw new ArgumentException(nameof(component)); } public static TagInfo GetParentTags(object component) { if (component == null) return TagInfo.All; if (component is DataRowView dataRowView && dataRowView.Row is InternalDataRow dataRow) { if (dataRow.ParentRow == null) return TagInfo.All; return dataRow.ParentRow.Tags; } throw new ArgumentException(nameof(component)); } public static string GetTableName(object component) { if (component is DataRowView == false) throw new ArgumentException(); var rowView = component as DataRowView; return rowView.Row.Table.TableName; } public static object[] GetKeys(object component) { if (component is DataRowView == false) throw new ArgumentException(); var rowView = component as DataRowView; return CremaDomainUtility.GetKeys(rowView); } public static string GetKeysExpression(object component) { if (component is DataRowView == false) throw new ArgumentException(); var rowView = component as DataRowView; return CremaDomainUtility.GetKeysExpression(rowView); } public static object[] GetFields(object component) { if (component is DataRowView == false) throw new ArgumentException(); return CremaDomainUtility.GetFields(component as DataRowView); } public static object[] GetFields(object component, string fieldName, object value) { if (component is DataRowView == false) throw new ArgumentException(); return CremaDomainUtility.GetFields(component as DataRowView, fieldName, value); } public static object[] GetInsertionFields(object parentComponent, string tableName) { if (parentComponent is DataRowView == false) throw new ArgumentException(); return CremaDomainUtility.GetInsertionFields(parentComponent as DataRowView, tableName); } public static object[] GetResetFields(object component, string[] fieldNames) { if (component is DataRowView == false) throw new ArgumentException(); return CremaDomainUtility.GetResetFields(component as DataRowView, fieldNames); } public static string[] GetColumnNames(ITypedList typedList) { var props = typedList.GetItemProperties(null); var columnList = new List<string>(props.Count); for (var i = 0; i < props.Count; i++) { if (props[i].PropertyType == typeof(IBindingList)) continue; columnList.Add(props[i].Name); } return columnList.ToArray(); } } }
37.410072
121
0.635385
[ "MIT" ]
s2quake/JSSoft.Crema
common/JSSoft.Crema.Data/CremaDataRowUtility.cs
5,202
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("Xenko.Metrics.ServerApp")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Xenko.Metrics.ServerApp")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("28003a34-b49f-4334-9fd0-945d0620ddc7")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.166667
84
0.752547
[ "MIT" ]
Beefr/xenko
sources/metrics/Xenko.Metrics.ServerApp/Properties/AssemblyInfo.cs
1,377
C#
//----------------------------------------------------------------------------- // Filename: Program.cs // // Description: A getting started program to demonstrate how to use the SIPTransport class to respond to // OPTIONS requests. // // Author(s): // Aaron Clauson (aaron@sipsorcery.com) // // History: // 13 Oct 2019 Aaron Clauson Created, Dublin, Ireland. // // License: // BSD 3-Clause "New" or "Revised" License, see included LICENSE.md file. //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // Notes: // // A convenient tool to test SIP applications is [SIPp] (https://github.com/SIPp/sipp). The OPTIONS request handling can // be tested from Ubuntu or [WSL] (https://docs.microsoft.com/en-us/windows/wsl/install-win10) using the steps below. // // $ sudo apt install sip-tester // $ wget https://raw.githubusercontent.com/saghul/sipp-scenarios/master/sipp_uac_options.xml // $ sipp -sf sipp_uac_options.xml -max_socket 1 -r 1 -p 5062 -rp 1000 -trace_err 127.0.0.1 // //----------------------------------------------------------------------------- using System; using System.Net; using SIPSorcery.SIP; namespace demo { class Program { static void Main() { Console.WriteLine("SIPSorcery Getting Started Demo"); var sipTransport = new SIPTransport(); var sipChannel = new SIPUDPChannel(IPAddress.Loopback, 5060); sipTransport.AddSIPChannel(sipChannel); sipTransport.SIPTransportRequestReceived += (SIPEndPoint localSIPEndPoint, SIPEndPoint remoteEndPoint, SIPRequest sipRequest) => { Console.WriteLine($"Request received {localSIPEndPoint.ToString()}<-{remoteEndPoint.ToString()}: {sipRequest.StatusLine}"); if (sipRequest.Method == SIPMethodsEnum.OPTIONS) { SIPResponse optionsResponse = SIPResponse.GetResponse(sipRequest, SIPResponseStatusCodesEnum.Ok, null); sipTransport.SendResponse(optionsResponse); } }; Console.Write("press any key to exit..."); Console.Read(); sipTransport.Shutdown(); } } }
37.31746
141
0.547427
[ "BSD-3-Clause" ]
FrankPfattheicher/sipsorcery
examples/GetStarted/Program.cs
2,353
C#
using Microsoft.AppCenter.Crashes; using System; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Xamarin.Essentials; namespace GeoContacts.Services { public static class GeolocationService { public static async Task<Location> GetCurrentPositionAsync() { Location position = null; try { position = await Geolocation.GetLastKnownLocationAsync(); if (position != null) { //got a cahched position, so let's use it. return position; } position = await Geolocation.GetLocationAsync(new GeolocationRequest { DesiredAccuracy = GeolocationAccuracy.Medium, Timeout = TimeSpan.FromSeconds(30) }); } catch (Exception ex) { Crashes.TrackError(ex); Debug.WriteLine("Unable to get location: " + ex); } if (position == null) return null; Debug.WriteLine($"Location = {position.Latitude}, {position.Longitude} | Time: {position.Timestamp} | Accuracty {position.Accuracy}"); return position; } public static async Task<Placemark> GetAddressAsync(Location position) { try { var addresses = await Geocoding.GetPlacemarksAsync(position); var address = addresses.FirstOrDefault(); if (address == null) Console.WriteLine("No address found for position."); else Console.WriteLine("Addresss: {0} {1} {2}", address.Thoroughfare, address.Locality, address.CountryCode); return address; } catch (Exception ex) { Crashes.TrackError(ex); Debug.WriteLine("Unable to get address: " + ex); } return null; } } }
28.743243
146
0.510578
[ "MIT" ]
sbovo/app-geocontacts
src/GeoContacts/GeoContacts/Services/Geolocation.cs
2,129
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/MsHTML.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. using System.Runtime.InteropServices; namespace TerraFX.Interop { [Guid("305105CB-98B5-11CF-BB82-00AA00BDCE0B")] public partial struct SVGPathSegLinetoVerticalRel { } }
31.4
145
0.757962
[ "MIT" ]
DaZombieKiller/terrafx.interop.windows
sources/Interop/Windows/um/MsHTML/SVGPathSegLinetoVerticalRel.cs
473
C#
using System; namespace SalesApp.Core.Exceptions.OTA { /// <summary> /// Exception to signal that access to OTA was made before initialization of database /// </summary> public class OtaTableMissingException : Exception { } }
22.818182
89
0.685259
[ "Apache-2.0" ]
mkopadev/salesapp
SalesApp.Core/Exceptions/OTA/OTATableMissingException.cs
253
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AecCloud.WebAPI.Models { public class ProjectInvitationDto : EntityDto { public long ProjectId { get; set; } public long InviterId { get; set; } public long InviteePartId { get; set; } public long InviteeId { get; set; } public string InviteeEmail { get; set; } public string InvitationMessage { get; set; } public string InviteeConfirmMessage { get; set; } public bool Accepted { get; set; } } }
21.714286
57
0.651316
[ "MIT" ]
FinchYang/test
AecPrivateCloud.ALL/Core/AecCloud.WebAPI.Models/Dtoes/ProjectInvitationDto.cs
610
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** 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.Aws.WafV2.Inputs { public sealed class RuleGroupRuleStatementAndStatementStatementLabelMatchStatementGetArgs : Pulumi.ResourceArgs { /// <summary> /// The string to match against. /// </summary> [Input("key", required: true)] public Input<string> Key { get; set; } = null!; /// <summary> /// Specify whether you want to match using the label name or just the namespace. Valid values are `LABEL` or `NAMESPACE`. /// </summary> [Input("scope", required: true)] public Input<string> Scope { get; set; } = null!; public RuleGroupRuleStatementAndStatementStatementLabelMatchStatementGetArgs() { } } }
32.71875
130
0.661891
[ "ECL-2.0", "Apache-2.0" ]
RafalSumislawski/pulumi-aws
sdk/dotnet/WafV2/Inputs/RuleGroupRuleStatementAndStatementStatementLabelMatchStatementGetArgs.cs
1,047
C#
using System; using System.Runtime.Serialization; using Elasticsearch.Net; namespace Nest { public static class IndexSortSettings { public const string Fields = "index.sort.field"; public const string Missing = "index.sort.missing"; public const string Mode = "index.sort.mode"; public const string Order = "index.sort.order"; } [StringEnum] public enum IndexSortMode { [EnumMember(Value = "min")] Minimum, [EnumMember(Value = "max")] Maximum } [StringEnum] public enum IndexSortMissing { [EnumMember(Value = "_first")] First, [EnumMember(Value = "_last")] Last } [StringEnum] public enum IndexSortOrder { [EnumMember(Value = "asc")] Ascending, [EnumMember(Value = "desc")] Descending } public interface ISortingSettings { /// <summary> /// The list of fields used to sort the index. Only boolean, numeric, date and keyword fields with doc_values are allowed /// here. /// </summary> Fields Fields { get; set; } /// <summary> /// The missing parameter specifies how docs which are missing the field should be treated. The missing value can have the /// following values: /// <see cref="IndexSortMissing.Last" />: Documents without value for the field are sorted last. /// <see cref="IndexSortMissing.First" />: Documents without value for the field are sorted first. /// </summary> IndexSortMissing[] Missing { get; set; } /// <summary> /// The mode option controls what value, from a multi-value field, is picked to sort the document. /// The mode option can have the following values: /// <see cref="IndexSortMode.Minimum" />: Pick the lowest value. /// <see cref="IndexSortMode.Maximum" />: Pick the highest value. /// </summary> IndexSortMode[] Mode { get; set; } /// <summary> /// The sort order to use for each field. The order option can have the following values: /// <see cref="IndexSortOrder.Ascending" /> and /// <see cref="IndexSortOrder.Descending" />. /// </summary> IndexSortOrder[] Order { get; set; } } public class SortingSettings : ISortingSettings { /// <inheritdoc /> public Fields Fields { get; set; } /// <inheritdoc /> public IndexSortMissing[] Missing { get; set; } /// <inheritdoc /> public IndexSortMode[] Mode { get; set; } /// <inheritdoc /> public IndexSortOrder[] Order { get; set; } } public class SortingSettingsDescriptor<T> : DescriptorBase<SortingSettingsDescriptor<T>, ISortingSettings>, ISortingSettings where T : class { Fields ISortingSettings.Fields { get; set; } IndexSortMissing[] ISortingSettings.Missing { get; set; } IndexSortMode[] ISortingSettings.Mode { get; set; } IndexSortOrder[] ISortingSettings.Order { get; set; } public SortingSettingsDescriptor<T> Fields(Func<FieldsDescriptor<T>, IPromise<Fields>> fields) => Assign(fields, (a, v) => a.Fields = v?.Invoke(new FieldsDescriptor<T>())?.Value); public SortingSettingsDescriptor<T> Fields(Fields fields) => Assign(fields, (a, v) => a.Fields = v); public SortingSettingsDescriptor<T> Order(params IndexSortOrder[] order) => Assign(order, (a, v) => a.Order = v); public SortingSettingsDescriptor<T> Mode(params IndexSortMode[] mode) => Assign(mode, (a, v) => a.Mode = v); public SortingSettingsDescriptor<T> Missing(params IndexSortMissing[] missing) => Assign(missing, (a, v) => a.Missing = v); } }
30.315315
141
0.69153
[ "Apache-2.0" ]
591094733/elasticsearch-net
src/Nest/IndexModules/IndexSettings/Sorting/ISortingSettings.cs
3,365
C#
using System; using System.Collections.Generic; using System.Text; using System.Data.Common; using Bdo.Schema.Definition; using Bdo.Objects.Base; namespace Bdo.Objects { /// <summary> /// Filtro NOTLIKE /// </summary> public class FilterNOTLIKE : FilterBase { /// <summary> /// Costruttore base /// </summary> /// <param name="propName"></param> /// <param name="op"></param> /// <param name="propValue"></param> public FilterNOTLIKE(string fieldName, object fieldValue) :base(fieldName, EOperator.NotLike, fieldValue) { } } }
23.107143
65
0.584235
[ "MIT" ]
simonep77/bdo
Business.Data.Objects/Objects/Filters/Spec/FilterNOTLIKE.cs
649
C#
using System; using System.IO; namespace RecommendationSystem.Models { public interface IModelPartSaver { Type Type { get; } void SaveModelProperties(IModel model, TextWriter writer); void SaveModelData(IModel model, TextWriter writer); } }
22.384615
67
0.666667
[ "Apache-2.0" ]
gligoran/RecommendationSystem
RecommendationSystem/Models/IModelPartSaver.cs
293
C#
using Bb.Workflows; using Bb.Workflows.Models; using System; using System.Linq; using System.Text; namespace Bb.Workflows.Templates { internal class TemplatesProviders { public static Func<ResultAction, DynObject> Reminder = (r) => DynObject .Create("Name", Constants.PushReminder) .Add("delayInMinute", WorkflowClock.Now().AddMinutes(r.Delay).ToString()) //.Add("canal", (ctx) => "IncomingEvent") // --read configuration where canal can be found ; public static Func<ResultAction, DynObject> __cancelReminderAction = (r) => DynObject.Create("Uuid", (ctx) => Guid.NewGuid()) .Add("CurrentState", (ctx) => ctx.Workflow.CurrentState) .Add("TaskUuid", (ctx) => $"{ctx.Workflow.ExternalId}_{ctx.Workflow.Events.Count() - 1}_{ctx.Workflow.LastEvent.FromState}_Expiration") ; public static Func<ResultAction, DynObject> __expired = (r) => DynObject .Create("Uuid", (ctx) => $"{ctx.Workflow.ExternalId}_{ctx.Workflow.Events.Count()}_{ctx.Workflow.CurrentState}_Expiration") .Add("Name", Constants.Events.ExpiredEventName) .Add("WorkflowId", (ctx) => ctx.Workflow.Uuid) .Add("CurrentState", (ctx) => ctx.Workflow.CurrentState) ; } }
34.7
151
0.600865
[ "BSD-3-Clause" ]
Moleculars/Sample
src/Black.Beard.Web.Workflow/Templates/TemplatesProviders.cs
1,390
C#
using System; using System.Collections.Generic; using AdventOfCode.Solvers.Base; using AdventOfCode.Utils; using AdventOfCode.Utils.Extensions; namespace AdventOfCode.Solvers.AoC2020; /// <summary> /// Solver for 2020 Day 01 /// </summary> public class Day01 : Solver<int[]> { #region Constants /// <summary> /// Target total /// </summary> private const int TARGET = 2020; #endregion #region Fields private readonly HashSet<int> values; #endregion #region Constructors /// <summary> /// Creates a new <see cref="Day01"/> Solver with the input data properly parsed /// </summary> /// <param name="input">Puzzle input</param> /// <exception cref="InvalidOperationException">Thrown if the conversion to <see cref="int"/> fails</exception> public Day01(string input) : base(input) => this.values = new HashSet<int>(this.Data); #endregion #region Methods /// <inheritdoc cref="Solver.Run"/> public override void Run() { FindTwoMatching(); FindThreeMatching(); } ///<inheritdoc cref="Solver{T}.Convert"/> protected override int[] Convert(string[] rawInput) => rawInput.ConvertAll(int.Parse); /// <summary> /// First part solving /// </summary> private void FindTwoMatching() { foreach (int expense in this.Data) { int match = TARGET - expense; if (this.values.Contains(match)) { AoCUtils.LogPart1(expense * match); return; } } } /// <summary> /// Second part solving /// </summary> private void FindThreeMatching() { this.Data.Sort(); for (int i = 0; i < this.Data.Length - 2; /*i++*/) { int first = this.Data[i]; foreach (int second in this.Data[++i..^1]) { int total = first + second; if (total >= TARGET) { break; } int third = TARGET - total; if (this.values.Contains(third)) { AoCUtils.LogPart2(first * second * third); return; } } } } #endregion }
25.786517
115
0.537255
[ "MIT" ]
ChrisViral/AdventOfCode
CSharp/Solvers/AoC2020/Day01.cs
2,297
C#
using Solaris.Web.SolarApi.Core.Rabbit.Helpers.Setup; namespace Solaris.Web.SolarApi.Core.Models.Helpers.Commons { public class AppSettings { public RabbitMqSettings RabbitMq { get; set; } public RabbitMqQueues RabbitMqQueues { get; set; } } }
24.909091
58
0.708029
[ "MIT" ]
GagiuFilip1/Solaris.Web.SolarApi
Solaris.Web.SolarApi/Solaris.Web.SolarApi.Core/Models/Helpers/Commons/AppSettings.cs
276
C#
using System; using NUnit.Framework; using Punku; [TestFixture] [Category ("Validate")] public class Validate_PersonalIdentityNumberSweden { [Test] public void IsPersonnummer01 () { Assert.AreEqual (PersonalIdentityNumberSweden.IsValid ("8112189876"), true); } [Test] public void IsPersonnummer02 () { Assert.AreEqual (PersonalIdentityNumberSweden.IsValid ("5566848635"), false); } [Test] public void IsMale01 () { Assert.AreEqual (PersonalIdentityNumberSweden.IsMale ("8112189876"), true); } [Test] public void IsFemale01 () { Assert.AreEqual (PersonalIdentityNumberSweden.IsFemale ("8112189876"), false); } [Test] public void ParseDateTime01 () { var x = PersonalIdentityNumberSweden.ToDateTime ("811218-9876"); Assert.AreEqual (x.Year, 1981); Assert.AreEqual (x.Month, 12); Assert.AreEqual (x.Day, 18); } [Test] [ExpectedException (typeof(FormatException))] public void ParseDateTime02 () { PersonalIdentityNumberSweden.ToDateTime ("801232-0000"); } [Test] [ExpectedException (typeof(FormatException))] public void ParseDateTime03 () { PersonalIdentityNumberSweden.ToDateTime ("abc123-0000"); } }
20.678571
80
0.734888
[ "MIT" ]
martinlindhe/Punku
PunkuTests/Validate/PersonalIdentityNumberSweden.cs
1,160
C#
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ using System; namespace Microsoft.Azure.PowerShell.Cmdlets.DedicatedHsm.Runtime.Json { public sealed partial class JsonNumber : JsonNode { private readonly string value; private readonly bool overflows = false; internal JsonNumber(string value) { this.value = value ?? throw new ArgumentNullException(nameof(value)); } internal JsonNumber(int value) { this.value = value.ToString(); } internal JsonNumber(long value) { this.value = value.ToString(); if (value > 9007199254740991) { overflows = true; } } internal JsonNumber(float value) { this.value = value.ToString(System.Globalization.CultureInfo.InvariantCulture); } internal JsonNumber(double value) { this.value = value.ToString(System.Globalization.CultureInfo.InvariantCulture); } internal override JsonType Type => JsonType.Number; internal string Value => value; #region Helpers internal bool Overflows => overflows; internal bool IsInteger => !value.Contains("."); internal bool IsFloat => value.Contains("."); #endregion #region Casting public static implicit operator byte(JsonNumber number) => byte.Parse(number.Value); public static implicit operator short(JsonNumber number) => short.Parse(number.Value); public static implicit operator int(JsonNumber number) => int.Parse(number.Value); public static implicit operator long(JsonNumber number) => long.Parse(number.value); public static implicit operator UInt16(JsonNumber number) => ushort.Parse(number.Value); public static implicit operator UInt32(JsonNumber number) => uint.Parse(number.Value); public static implicit operator UInt64(JsonNumber number) => ulong.Parse(number.Value); public static implicit operator decimal(JsonNumber number) => decimal.Parse(number.Value, System.Globalization.CultureInfo.InvariantCulture); public static implicit operator Double(JsonNumber number) => double.Parse(number.value, System.Globalization.CultureInfo.InvariantCulture); public static implicit operator float(JsonNumber number) => float.Parse(number.value, System.Globalization.CultureInfo.InvariantCulture); public static implicit operator JsonNumber(short data) => new JsonNumber(data.ToString()); public static implicit operator JsonNumber(int data) => new JsonNumber(data); public static implicit operator JsonNumber(long data) => new JsonNumber(data); public static implicit operator JsonNumber(Single data) => new JsonNumber(data.ToString()); public static implicit operator JsonNumber(double data) => new JsonNumber(data.ToString()); #endregion public override string ToString() => value; } }
33.449541
97
0.583653
[ "MIT" ]
AlanFlorance/azure-powershell
src/DedicatedHsm/generated/runtime/Nodes/JsonNumber.cs
3,540
C#
using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Web; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OpenCodeDev.Blazor.Foundation.Components.Media { public partial class OrbitSlide : ComponentBase { [Parameter] public RenderFragment ChildContent { get; set; } /// <summary> /// IsDefault (False by Default) is the first visible slide. /// </summary> [Parameter] public bool IsDefault { get; set; } = false; [Parameter(CaptureUnmatchedValues = true)] public IDictionary<string, object> AdditionalAttributes { get; set; } } }
27.692308
77
0.684722
[ "MIT" ]
OpenCodeDev/OpenCodeDev.Blazor.Foundation
Blazor_Foundation_6_Lib/Components/Media/OrbitSlide.razor.cs
722
C#
namespace EDiary.Web.ViewModels.Teachers.SubjectsClasses.OutputViewModels { using EDiary.Data.Models; using EDiary.Data.Models.Enums; using EDiary.Services.Mapping; public class SubjectClassInfoStudents : IMapFrom<SubjectClass> { public int Id { get; set; } public string SubjectName { get; set; } public Class Class { get; set; } public TypeOfClass TypeOfClass { get; set; } public string SchoolName { get; set; } } }
24.45
74
0.664622
[ "MIT" ]
markodjunev/E-Diary
EDiary/Web/EDiary.Web.ViewModels/Teachers/SubjectsClasses/OutputViewModels/SubjectClassInfoStudents.cs
491
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Security; [SecuritySafeCritical] class TestApp { //***** TEST CODE ***** static double test_0_0(double num, AA init, AA zero) { return init.q; } static double test_0_1(double num, AA init, AA zero) { zero.q=num; return zero.q; } static double test_0_2(double num, AA init, AA zero) { return init.q+zero.q; } static double test_0_3(double num, AA init, AA zero) { return checked(init.q-zero.q); } static double test_0_4(double num, AA init, AA zero) { zero.q+=num; return zero.q; } static double test_0_5(double num, AA init, AA zero) { zero.q+=init.q; return zero.q; } static double test_0_6(double num, AA init, AA zero) { if (init.q==num) return 100; else return zero.q; } static double test_0_7(double num, AA init, AA zero) { return init.q<num+1 ? 100 : -1; } static double test_0_8(double num, AA init, AA zero) { return (init.q>zero.q?1:0)+99; } static double test_0_9(double num, AA init, AA zero) { object bb=init.q; return (double)bb; } static double test_0_10(double num, AA init, AA zero) { double dbl=init.q; return (double)dbl; } static double test_0_11(double num, AA init, AA zero) { return AA.call_target(init.q); } static double test_0_12(double num, AA init, AA zero) { return AA.call_target_ref(ref init.q); } static double test_1_0(double num, ref AA r_init, ref AA r_zero) { return r_init.q; } static double test_1_1(double num, ref AA r_init, ref AA r_zero) { r_zero.q=num; return r_zero.q; } static double test_1_2(double num, ref AA r_init, ref AA r_zero) { return r_init.q+r_zero.q; } static double test_1_3(double num, ref AA r_init, ref AA r_zero) { return checked(r_init.q-r_zero.q); } static double test_1_4(double num, ref AA r_init, ref AA r_zero) { r_zero.q+=num; return r_zero.q; } static double test_1_5(double num, ref AA r_init, ref AA r_zero) { r_zero.q+=r_init.q; return r_zero.q; } static double test_1_6(double num, ref AA r_init, ref AA r_zero) { if (r_init.q==num) return 100; else return r_zero.q; } static double test_1_7(double num, ref AA r_init, ref AA r_zero) { return r_init.q<num+1 ? 100 : -1; } static double test_1_8(double num, ref AA r_init, ref AA r_zero) { return (r_init.q>r_zero.q?1:0)+99; } static double test_1_9(double num, ref AA r_init, ref AA r_zero) { object bb=r_init.q; return (double)bb; } static double test_1_10(double num, ref AA r_init, ref AA r_zero) { double dbl=r_init.q; return (double)dbl; } static double test_1_11(double num, ref AA r_init, ref AA r_zero) { return AA.call_target(r_init.q); } static double test_1_12(double num, ref AA r_init, ref AA r_zero) { return AA.call_target_ref(ref r_init.q); } static double test_2_0(double num) { return AA.a_init[(int)num].q; } static double test_2_1(double num) { AA.a_zero[(int)num].q=num; return AA.a_zero[(int)num].q; } static double test_2_2(double num) { return AA.a_init[(int)num].q+AA.a_zero[(int)num].q; } static double test_2_3(double num) { return checked(AA.a_init[(int)num].q-AA.a_zero[(int)num].q); } static double test_2_4(double num) { AA.a_zero[(int)num].q+=num; return AA.a_zero[(int)num].q; } static double test_2_5(double num) { AA.a_zero[(int)num].q+=AA.a_init[(int)num].q; return AA.a_zero[(int)num].q; } static double test_2_6(double num) { if (AA.a_init[(int)num].q==num) return 100; else return AA.a_zero[(int)num].q; } static double test_2_7(double num) { return AA.a_init[(int)num].q<num+1 ? 100 : -1; } static double test_2_8(double num) { return (AA.a_init[(int)num].q>AA.a_zero[(int)num].q?1:0)+99; } static double test_2_9(double num) { object bb=AA.a_init[(int)num].q; return (double)bb; } static double test_2_10(double num) { double dbl=AA.a_init[(int)num].q; return (double)dbl; } static double test_2_11(double num) { return AA.call_target(AA.a_init[(int)num].q); } static double test_2_12(double num) { return AA.call_target_ref(ref AA.a_init[(int)num].q); } static double test_3_0(double num) { return AA.aa_init[0,(int)num-1,(int)num/100].q; } static double test_3_1(double num) { AA.aa_zero[0,(int)num-1,(int)num/100].q=num; return AA.aa_zero[0,(int)num-1,(int)num/100].q; } static double test_3_2(double num) { return AA.aa_init[0,(int)num-1,(int)num/100].q+AA.aa_zero[0,(int)num-1,(int)num/100].q; } static double test_3_3(double num) { return checked(AA.aa_init[0,(int)num-1,(int)num/100].q-AA.aa_zero[0,(int)num-1,(int)num/100].q); } static double test_3_4(double num) { AA.aa_zero[0,(int)num-1,(int)num/100].q+=num; return AA.aa_zero[0,(int)num-1,(int)num/100].q; } static double test_3_5(double num) { AA.aa_zero[0,(int)num-1,(int)num/100].q+=AA.aa_init[0,(int)num-1,(int)num/100].q; return AA.aa_zero[0,(int)num-1,(int)num/100].q; } static double test_3_6(double num) { if (AA.aa_init[0,(int)num-1,(int)num/100].q==num) return 100; else return AA.aa_zero[0,(int)num-1,(int)num/100].q; } static double test_3_7(double num) { return AA.aa_init[0,(int)num-1,(int)num/100].q<num+1 ? 100 : -1; } static double test_3_8(double num) { return (AA.aa_init[0,(int)num-1,(int)num/100].q>AA.aa_zero[0,(int)num-1,(int)num/100].q?1:0)+99; } static double test_3_9(double num) { object bb=AA.aa_init[0,(int)num-1,(int)num/100].q; return (double)bb; } static double test_3_10(double num) { double dbl=AA.aa_init[0,(int)num-1,(int)num/100].q; return (double)dbl; } static double test_3_11(double num) { return AA.call_target(AA.aa_init[0,(int)num-1,(int)num/100].q); } static double test_3_12(double num) { return AA.call_target_ref(ref AA.aa_init[0,(int)num-1,(int)num/100].q); } static double test_4_0(double num) { return BB.f_init.q; } static double test_4_1(double num) { BB.f_zero.q=num; return BB.f_zero.q; } static double test_4_2(double num) { return BB.f_init.q+BB.f_zero.q; } static double test_4_3(double num) { return checked(BB.f_init.q-BB.f_zero.q); } static double test_4_4(double num) { BB.f_zero.q+=num; return BB.f_zero.q; } static double test_4_5(double num) { BB.f_zero.q+=BB.f_init.q; return BB.f_zero.q; } static double test_4_6(double num) { if (BB.f_init.q==num) return 100; else return BB.f_zero.q; } static double test_4_7(double num) { return BB.f_init.q<num+1 ? 100 : -1; } static double test_4_8(double num) { return (BB.f_init.q>BB.f_zero.q?1:0)+99; } static double test_4_9(double num) { object bb=BB.f_init.q; return (double)bb; } static double test_4_10(double num) { double dbl=BB.f_init.q; return (double)dbl; } static double test_4_11(double num) { return AA.call_target(BB.f_init.q); } static double test_4_12(double num) { return AA.call_target_ref(ref BB.f_init.q); } static double test_5_0(double num) { return ((AA)AA.b_init).q; } static unsafe double test_7_0(double num, void *ptr_init, void *ptr_zero) { return (*((AA*)ptr_init)).q; } static unsafe double test_7_1(double num, void *ptr_init, void *ptr_zero) { (*((AA*)ptr_zero)).q=num; return (*((AA*)ptr_zero)).q; } static unsafe double test_7_2(double num, void *ptr_init, void *ptr_zero) { return (*((AA*)ptr_init)).q+(*((AA*)ptr_zero)).q; } static unsafe double test_7_3(double num, void *ptr_init, void *ptr_zero) { return checked((*((AA*)ptr_init)).q-(*((AA*)ptr_zero)).q); } static unsafe double test_7_4(double num, void *ptr_init, void *ptr_zero) { (*((AA*)ptr_zero)).q+=num; return (*((AA*)ptr_zero)).q; } static unsafe double test_7_5(double num, void *ptr_init, void *ptr_zero) { (*((AA*)ptr_zero)).q+=(*((AA*)ptr_init)).q; return (*((AA*)ptr_zero)).q; } static unsafe double test_7_6(double num, void *ptr_init, void *ptr_zero) { if ((*((AA*)ptr_init)).q==num) return 100; else return (*((AA*)ptr_zero)).q; } static unsafe double test_7_7(double num, void *ptr_init, void *ptr_zero) { return (*((AA*)ptr_init)).q<num+1 ? 100 : -1; } static unsafe double test_7_8(double num, void *ptr_init, void *ptr_zero) { return ((*((AA*)ptr_init)).q>(*((AA*)ptr_zero)).q?1:0)+99; } static unsafe double test_7_9(double num, void *ptr_init, void *ptr_zero) { object bb=(*((AA*)ptr_init)).q; return (double)bb; } static unsafe double test_7_10(double num, void *ptr_init, void *ptr_zero) { double dbl=(*((AA*)ptr_init)).q; return (double)dbl; } static unsafe double test_7_11(double num, void *ptr_init, void *ptr_zero) { return AA.call_target((*((AA*)ptr_init)).q); } static unsafe double test_7_12(double num, void *ptr_init, void *ptr_zero) { return AA.call_target_ref(ref (*((AA*)ptr_init)).q); } //***** MAIN CODE ***** static unsafe int Main() { AA.reset(); if (test_0_0(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_0() failed."); return 101; } AA.verify_all(); AA.reset(); if (test_0_1(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_1() failed."); return 102; } AA.verify_all(); AA.reset(); if (test_0_2(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_2() failed."); return 103; } AA.verify_all(); AA.reset(); if (test_0_3(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_3() failed."); return 104; } AA.verify_all(); AA.reset(); if (test_0_4(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_4() failed."); return 105; } AA.verify_all(); AA.reset(); if (test_0_5(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_5() failed."); return 106; } AA.verify_all(); AA.reset(); if (test_0_6(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_6() failed."); return 107; } AA.verify_all(); AA.reset(); if (test_0_7(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_7() failed."); return 108; } AA.verify_all(); AA.reset(); if (test_0_8(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_8() failed."); return 109; } AA.verify_all(); AA.reset(); if (test_0_9(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_9() failed."); return 110; } AA.verify_all(); AA.reset(); if (test_0_10(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_10() failed."); return 111; } AA.verify_all(); AA.reset(); if (test_0_11(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_11() failed."); return 112; } AA.verify_all(); AA.reset(); if (test_0_12(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_12() failed."); return 113; } AA.verify_all(); AA.reset(); if (test_1_0(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_0() failed."); return 114; } AA.verify_all(); AA.reset(); if (test_1_1(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_1() failed."); return 115; } AA.verify_all(); AA.reset(); if (test_1_2(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_2() failed."); return 116; } AA.verify_all(); AA.reset(); if (test_1_3(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_3() failed."); return 117; } AA.verify_all(); AA.reset(); if (test_1_4(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_4() failed."); return 118; } AA.verify_all(); AA.reset(); if (test_1_5(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_5() failed."); return 119; } AA.verify_all(); AA.reset(); if (test_1_6(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_6() failed."); return 120; } AA.verify_all(); AA.reset(); if (test_1_7(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_7() failed."); return 121; } AA.verify_all(); AA.reset(); if (test_1_8(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_8() failed."); return 122; } AA.verify_all(); AA.reset(); if (test_1_9(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_9() failed."); return 123; } AA.verify_all(); AA.reset(); if (test_1_10(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_10() failed."); return 124; } AA.verify_all(); AA.reset(); if (test_1_11(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_11() failed."); return 125; } AA.verify_all(); AA.reset(); if (test_1_12(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_12() failed."); return 126; } AA.verify_all(); AA.reset(); if (test_2_0(100) != 100) { Console.WriteLine("test_2_0() failed."); return 127; } AA.verify_all(); AA.reset(); if (test_2_1(100) != 100) { Console.WriteLine("test_2_1() failed."); return 128; } AA.verify_all(); AA.reset(); if (test_2_2(100) != 100) { Console.WriteLine("test_2_2() failed."); return 129; } AA.verify_all(); AA.reset(); if (test_2_3(100) != 100) { Console.WriteLine("test_2_3() failed."); return 130; } AA.verify_all(); AA.reset(); if (test_2_4(100) != 100) { Console.WriteLine("test_2_4() failed."); return 131; } AA.verify_all(); AA.reset(); if (test_2_5(100) != 100) { Console.WriteLine("test_2_5() failed."); return 132; } AA.verify_all(); AA.reset(); if (test_2_6(100) != 100) { Console.WriteLine("test_2_6() failed."); return 133; } AA.verify_all(); AA.reset(); if (test_2_7(100) != 100) { Console.WriteLine("test_2_7() failed."); return 134; } AA.verify_all(); AA.reset(); if (test_2_8(100) != 100) { Console.WriteLine("test_2_8() failed."); return 135; } AA.verify_all(); AA.reset(); if (test_2_9(100) != 100) { Console.WriteLine("test_2_9() failed."); return 136; } AA.verify_all(); AA.reset(); if (test_2_10(100) != 100) { Console.WriteLine("test_2_10() failed."); return 137; } AA.verify_all(); AA.reset(); if (test_2_11(100) != 100) { Console.WriteLine("test_2_11() failed."); return 138; } AA.verify_all(); AA.reset(); if (test_2_12(100) != 100) { Console.WriteLine("test_2_12() failed."); return 139; } AA.verify_all(); AA.reset(); if (test_3_0(100) != 100) { Console.WriteLine("test_3_0() failed."); return 140; } AA.verify_all(); AA.reset(); if (test_3_1(100) != 100) { Console.WriteLine("test_3_1() failed."); return 141; } AA.verify_all(); AA.reset(); if (test_3_2(100) != 100) { Console.WriteLine("test_3_2() failed."); return 142; } AA.verify_all(); AA.reset(); if (test_3_3(100) != 100) { Console.WriteLine("test_3_3() failed."); return 143; } AA.verify_all(); AA.reset(); if (test_3_4(100) != 100) { Console.WriteLine("test_3_4() failed."); return 144; } AA.verify_all(); AA.reset(); if (test_3_5(100) != 100) { Console.WriteLine("test_3_5() failed."); return 145; } AA.verify_all(); AA.reset(); if (test_3_6(100) != 100) { Console.WriteLine("test_3_6() failed."); return 146; } AA.verify_all(); AA.reset(); if (test_3_7(100) != 100) { Console.WriteLine("test_3_7() failed."); return 147; } AA.verify_all(); AA.reset(); if (test_3_8(100) != 100) { Console.WriteLine("test_3_8() failed."); return 148; } AA.verify_all(); AA.reset(); if (test_3_9(100) != 100) { Console.WriteLine("test_3_9() failed."); return 149; } AA.verify_all(); AA.reset(); if (test_3_10(100) != 100) { Console.WriteLine("test_3_10() failed."); return 150; } AA.verify_all(); AA.reset(); if (test_3_11(100) != 100) { Console.WriteLine("test_3_11() failed."); return 151; } AA.verify_all(); AA.reset(); if (test_3_12(100) != 100) { Console.WriteLine("test_3_12() failed."); return 152; } AA.verify_all(); AA.reset(); if (test_4_0(100) != 100) { Console.WriteLine("test_4_0() failed."); return 153; } AA.verify_all(); AA.reset(); if (test_4_1(100) != 100) { Console.WriteLine("test_4_1() failed."); return 154; } AA.verify_all(); AA.reset(); if (test_4_2(100) != 100) { Console.WriteLine("test_4_2() failed."); return 155; } AA.verify_all(); AA.reset(); if (test_4_3(100) != 100) { Console.WriteLine("test_4_3() failed."); return 156; } AA.verify_all(); AA.reset(); if (test_4_4(100) != 100) { Console.WriteLine("test_4_4() failed."); return 157; } AA.verify_all(); AA.reset(); if (test_4_5(100) != 100) { Console.WriteLine("test_4_5() failed."); return 158; } AA.verify_all(); AA.reset(); if (test_4_6(100) != 100) { Console.WriteLine("test_4_6() failed."); return 159; } AA.verify_all(); AA.reset(); if (test_4_7(100) != 100) { Console.WriteLine("test_4_7() failed."); return 160; } AA.verify_all(); AA.reset(); if (test_4_8(100) != 100) { Console.WriteLine("test_4_8() failed."); return 161; } AA.verify_all(); AA.reset(); if (test_4_9(100) != 100) { Console.WriteLine("test_4_9() failed."); return 162; } AA.verify_all(); AA.reset(); if (test_4_10(100) != 100) { Console.WriteLine("test_4_10() failed."); return 163; } AA.verify_all(); AA.reset(); if (test_4_11(100) != 100) { Console.WriteLine("test_4_11() failed."); return 164; } AA.verify_all(); AA.reset(); if (test_4_12(100) != 100) { Console.WriteLine("test_4_12() failed."); return 165; } AA.verify_all(); AA.reset(); if (test_5_0(100) != 100) { Console.WriteLine("test_5_0() failed."); return 166; } AA.verify_all(); AA.reset(); fixed (void *p_init = &AA._init, p_zero = &AA._zero) { if (test_7_0(100, p_init, p_zero) != 100) { Console.WriteLine("test_7_0() failed."); return 168; } } AA.verify_all(); AA.reset(); fixed (void *p_init = &AA._init, p_zero = &AA._zero) { if (test_7_1(100, p_init, p_zero) != 100) { Console.WriteLine("test_7_1() failed."); return 169; } } AA.verify_all(); AA.reset(); fixed (void *p_init = &AA._init, p_zero = &AA._zero) { if (test_7_2(100, p_init, p_zero) != 100) { Console.WriteLine("test_7_2() failed."); return 170; } } AA.verify_all(); AA.reset(); fixed (void *p_init = &AA._init, p_zero = &AA._zero) { if (test_7_3(100, p_init, p_zero) != 100) { Console.WriteLine("test_7_3() failed."); return 171; } } AA.verify_all(); AA.reset(); fixed (void *p_init = &AA._init, p_zero = &AA._zero) { if (test_7_4(100, p_init, p_zero) != 100) { Console.WriteLine("test_7_4() failed."); return 172; } } AA.verify_all(); AA.reset(); fixed (void *p_init = &AA._init, p_zero = &AA._zero) { if (test_7_5(100, p_init, p_zero) != 100) { Console.WriteLine("test_7_5() failed."); return 173; } } AA.verify_all(); AA.reset(); fixed (void *p_init = &AA._init, p_zero = &AA._zero) { if (test_7_6(100, p_init, p_zero) != 100) { Console.WriteLine("test_7_6() failed."); return 174; } } AA.verify_all(); AA.reset(); fixed (void *p_init = &AA._init, p_zero = &AA._zero) { if (test_7_7(100, p_init, p_zero) != 100) { Console.WriteLine("test_7_7() failed."); return 175; } } AA.verify_all(); AA.reset(); fixed (void *p_init = &AA._init, p_zero = &AA._zero) { if (test_7_8(100, p_init, p_zero) != 100) { Console.WriteLine("test_7_8() failed."); return 176; } } AA.verify_all(); AA.reset(); fixed (void *p_init = &AA._init, p_zero = &AA._zero) { if (test_7_9(100, p_init, p_zero) != 100) { Console.WriteLine("test_7_9() failed."); return 177; } } AA.verify_all(); AA.reset(); fixed (void *p_init = &AA._init, p_zero = &AA._zero) { if (test_7_10(100, p_init, p_zero) != 100) { Console.WriteLine("test_7_10() failed."); return 178; } } AA.verify_all(); AA.reset(); fixed (void *p_init = &AA._init, p_zero = &AA._zero) { if (test_7_11(100, p_init, p_zero) != 100) { Console.WriteLine("test_7_11() failed."); return 179; } } AA.verify_all(); AA.reset(); fixed (void *p_init = &AA._init, p_zero = &AA._zero) { if (test_7_12(100, p_init, p_zero) != 100) { Console.WriteLine("test_7_12() failed."); return 180; } } AA.verify_all(); Console.WriteLine("All tests passed."); return 100; } }
27.92027
131
0.629979
[ "MIT" ]
2m0nd/runtime
src/tests/Regressions/coreclr/0041/body_double.cs
20,661
C#
/** * */ using System.Text; namespace DotNetXri.Client.Resolve { using java.io.ByteArrayInputStream; using java.io.IOException; using java.io.InputStream; using java.io.UnsupportedEncodingException; using java.net.HttpURLConnection; using java.net.URI; using java.net.URISyntaxException; using java.net.URLEncoder; using java.text.ParseException; using java.util.ArrayList; using java.util.HashMap; using java.util.Iterator; using java.util.LinkedHashMap; using java.util.List; using java.util.Properties; using java.util.Vector; using org.apache.xerces.parsers.DOMParser; using org.apache.xml.security.exceptions.XMLSecurityException; using org.apache.xml.security.keys.KeyInfo; using org.openxri.AuthorityPath; using org.openxri.IRIAuthority; using org.openxri.XRI; using org.openxri.XRIAbsolutePath; using org.openxri.XRIAuthority; using org.openxri.XRIParseException; using org.openxri.XRIPath; using org.openxri.XRIQuery; using org.openxri.XRISegment; using org.openxri.XRISubSegment; using org.openxri.http.BaseFetcher; using org.openxri.resolve.exception.InvalidAuthorityURIException; using org.openxri.resolve.exception.PartialResolutionException; using org.openxri.resolve.exception.XRIResolutionException; using org.openxri.saml.Assertion; using org.openxri.saml.Attribute; using org.openxri.saml.AttributeStatement; using org.openxri.saml.NameID; using org.openxri.saml.Subject; using org.openxri.util.DOMUtils; using org.openxri.util.IO; using org.openxri.util.PrioritizedList; using org.openxri.xml.CanonicalEquivID; using org.openxri.xml.CanonicalID; using org.openxri.xml.EquivID; using org.openxri.xml.LocalID; using org.openxri.xml.Ref; using org.openxri.xml.SEPUri; using org.openxri.xml.ServerStatus; using org.openxri.xml.Service; using org.openxri.xml.SimpleXMLElement; using org.openxri.xml.Status; using org.openxri.xml.Tags; using org.openxri.xml.XRD; using org.openxri.xml.XRDS; using org.openxri.xml.Redirect; using org.w3c.dom.Document; using org.w3c.dom.Element; using org.xml.sax.InputSource; using org.xml.sax.SAXException; /** * @author wtan * */ public class Resolver :BaseFetcher { private static org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog(Resolver.class.getName()); protected HashMap root = null; protected int maxFollowRefs = -1; protected int maxRequests = -1; protected URI proxyURI = null; private int maxTotalBytes = -1; private int maxBytesPerRequest = -1; private HashMap needNoHttps = null; /** * Creates a Resolver obj. */ public Resolver() { root = new HashMap(); needNoHttps = new HashMap(); } /** * This is the recommended API to use for performing authority resolution an an XRI * @param qxri * @param flags - ResolverFlag * @param state - ResolverState * @return * @throws PartialResolutionException */ public XRDS resolveAuthToXRDS(XRI qxri, ResolverFlags flags, ResolverState state) throws PartialResolutionException { log.trace("resolveAuthToXRDS(s'" + qxri + "', flags: " + flags + ")"); if (proxyURI != null) return resolveViaProxy(qxri, null, null, false, flags, state); XRDS xrds = resolveAuthority(qxri, flags, state); if (flags.isUric()) { constructURIinXRD(xrds.getFinalXRD(), qxri); } return xrds; } /** * * @param qxri * @param flags ResolverFlags * @param state * @return * @throws PartialResolutionException */ public XRD resolveAuthToXRD(XRI qxri, ResolverFlags flags, ResolverState state) throws PartialResolutionException { log.trace("resolveAuthToXRD(s'" + qxri + "', flags: " + flags + ")"); if (proxyURI != null) { XRDS xrds = resolveViaProxy(qxri, null, null, false, flags, state); return xrds.getFinalXRD(); } XRDS xrds = resolveAuthority(qxri, flags, state); XRD finalXRD = xrds.getFinalXRD(); if (flags.isUric()) { constructURIinXRD(finalXRD, qxri); } return finalXRD; } public XRDS resolveSEPToXRDS(XRI qxri, String sepType, String sepMediaType, ResolverFlags flags, ResolverState state) throws PartialResolutionException { log.trace("resolveSEPToXRDS('" + qxri + "', sepType=" + sepType + ", sepMediaType=" + sepMediaType + ", flags:" + flags + ")"); if (proxyURI != null) return resolveViaProxy(qxri, sepType, sepMediaType, true, flags, state); XRDS xrds = resolveAuthority(qxri, flags, state); XRD finalXRD = xrds.getFinalXRD(); selectServiceFromXRD(xrds, finalXRD, qxri, sepType, sepMediaType, flags, state); if (flags.isUric()) { constructURIinXRD(xrds.getFinalXRD(), qxri); } return xrds; } public XRD resolveSEPToXRD(XRI qxri, String sepType, String sepMediaType, ResolverFlags flags, ResolverState state) throws PartialResolutionException { log.trace("resolveSEPToXRD('" + qxri + "', sepType=" + sepType + ", sepMediaType=" + sepMediaType + ", flags: " + flags + ")"); XRDS xrds = resolveSEPToXRDS(qxri, sepType, sepMediaType, flags, state); return xrds.getFinalXRD(); } public ArrayList resolveSEPToURIList(XRI qxri, String sepType, String sepMediaType, ResolverFlags flags, ResolverState state) throws PartialResolutionException { log.trace("resolveSEPToURIList('" + qxri + "', sepType=" + sepType + ", sepMediaType=" + sepMediaType + ", flags: " + flags + ")"); // no need to do uric flags.setUric(false); XRD xrd = resolveSEPToXRD(qxri, sepType, sepMediaType, flags, state); if (xrd == null) return new ArrayList(); if (xrd.getSelectedServices().getList().size() < 1) { log.error("SEP Selection succeeded but no Service found!?"); return new ArrayList(); } Service topService = (Service) xrd.getSelectedServices().getList().get(0); ArrayList urisOut = new ArrayList(); ArrayList uris = topService.getPrioritizedURIs(); for (int i = 0; uris != null && i < uris.size(); i++) { SEPUri uri = (SEPUri) uris.get(i); String append = uri.getAppend(); urisOut.add(constructURI(uri.getURI(), append, qxri)); } return urisOut; } public String resolveSEPToTextURIList(XRI qxri, String sepType, String sepMediaType, ResolverFlags flags, ResolverState state) throws PartialResolutionException { log.trace("resolveSEPToTextURIList('" + qxri + ", sepType=" + sepType + ", sepMediaType=" + sepMediaType + ", flags: " + flags + ")"); ArrayList uris = resolveSEPToURIList(qxri, sepType, sepMediaType, flags, state); StringBuilder buf = new StringBuilder(); for (int i = 0; uris != null && i < uris.size(); i++) { buf.append(uris.get(i).toString()); buf.append("\n"); } return buf.toString(); } ///////////////////////////////////////////////////////////////////////// // BEGIN DEPRECATED APIS // ///////////////////////////////////////////////////////////////////////// /** * @deprecated */ public XRDS resolveAuthToXRDS(String qxri, TrustType trustType, bool followRefs) throws PartialResolutionException { return resolveAuthToXRDS(qxri, trustType, followRefs, new ResolverState()); } /** * @deprecated */ public XRDS resolveAuthToXRDS(String qxri, TrustType trustType, bool followRefs, ResolverState state) throws PartialResolutionException { XRI xri = parseAbsoluteQXRIOrError(qxri); return resolveAuthToXRDS(xri, trustType, followRefs, state); } /** * @deprecated */ public XRDS resolveAuthToXRDS(XRI qxri, TrustType trustType, bool followRefs) throws PartialResolutionException { return resolveAuthToXRDS(qxri, trustType, followRefs, new ResolverState()); } /** * @deprecated */ public XRDS resolveAuthToXRDS(XRI qxri, TrustType trustType, bool followRefs, ResolverState state) throws PartialResolutionException { ResolverFlags f = new ResolverFlags(trustType, followRefs); return resolveAuthToXRDS(qxri, f, state); } /** * @deprecated */ public XRD resolveAuthToXRD(String qxri, TrustType trustType, bool followRefs) throws PartialResolutionException { return resolveAuthToXRD(qxri, trustType, followRefs, new ResolverState()); } /** * @deprecated */ public XRD resolveAuthToXRD(String qxri, TrustType trustType, bool followRefs, ResolverState state) throws PartialResolutionException { log.trace("resolveAuthToXRD(s'" + qxri + "', trustType=" + trustType + ", followRefs=" + followRefs + ")"); XRI xri = parseAbsoluteQXRIOrError(qxri); return resolveAuthToXRD(xri, trustType, followRefs, state); } /** * @deprecated */ public XRD resolveAuthToXRD(XRI qxri, TrustType trustType, bool followRefs) throws PartialResolutionException { return resolveAuthToXRD(qxri, trustType, followRefs, new ResolverState()); } /** * @deprecated */ public XRD resolveAuthToXRD(XRI qxri, TrustType trustType, bool followRefs, ResolverState state) throws PartialResolutionException { log.trace("resolveAuthToXRD('" + qxri + "', trustType=" + trustType + ", followRefs=" + followRefs + ")"); ResolverFlags f = new ResolverFlags(trustType, followRefs); return resolveAuthToXRD(qxri, f, state); } /** * @deprecated */ public XRDS resolveSEPToXRDS(String qxri, TrustType trustType, String sepType, String sepMediaType, bool followRefs) throws PartialResolutionException { return resolveSEPToXRDS(qxri, trustType, sepType, sepMediaType, followRefs, new ResolverState()); } /** * @deprecated */ public XRDS resolveSEPToXRDS(String qxri, TrustType trustType, String sepType, String sepMediaType, bool followRefs, ResolverState state) throws PartialResolutionException { log.trace("resolveSEPToXRDS(s'" + qxri + "', trustType=" + trustType + ", sepType=" + sepType + ", sepMediaType=" + sepMediaType + ", followRefs=" + followRefs + ")"); XRI xri = parseAbsoluteQXRIOrError(qxri); return resolveSEPToXRDS(xri, trustType, sepType, sepMediaType, followRefs, state); } /** * @deprecated */ public XRDS resolveSEPToXRDS(XRI qxri, TrustType trustType, String sepType, String sepMediaType, bool followRefs) throws PartialResolutionException { return resolveSEPToXRDS(qxri, trustType, sepType, sepMediaType, followRefs, new ResolverState()); } /** * @deprecated */ public XRDS resolveSEPToXRDS(XRI qxri, TrustType trustType, String sepType, String sepMediaType, bool followRefs, ResolverState state) throws PartialResolutionException { log.trace("resolveSEPToXRDS('" + qxri + "', trustType=" + trustType + ", sepType=" + sepType + ", sepMediaType=" + sepMediaType + ", followRefs=" + followRefs + ")"); ResolverFlags f = new ResolverFlags(trustType, followRefs); return resolveSEPToXRDS(qxri, sepType, sepMediaType, f, state); } /** * @deprecated */ public XRD resolveSEPToXRD(String qxri, TrustType trustType, String sepType, String sepMediaType, bool followRefs) throws PartialResolutionException { return resolveSEPToXRD(qxri, trustType, sepType, sepMediaType, followRefs, new ResolverState()); } /** * @deprecated */ public XRD resolveSEPToXRD(String qxri, TrustType trustType, String sepType, String sepMediaType, bool followRefs, ResolverState state) throws PartialResolutionException { log.trace("resolveSEPToXRD(s'" + qxri + "', trustType=" + trustType + ", sepType=" + sepType + ", sepMediaType=" + sepMediaType + ", followRefs=" + followRefs + ")"); XRI xri = parseAbsoluteQXRIOrError(qxri); return resolveSEPToXRD(xri, trustType, sepType, sepMediaType, followRefs, state); } /** * @deprecated */ public XRD resolveSEPToXRD(XRI qxri, TrustType trustType, String sepType, String sepMediaType, bool followRefs) throws PartialResolutionException { return resolveSEPToXRD(qxri, trustType, sepType, sepMediaType, followRefs, new ResolverState()); } /** * @deprecated */ public XRD resolveSEPToXRD(XRI qxri, TrustType trustType, String sepType, String sepMediaType, bool followRefs, ResolverState state) throws PartialResolutionException { log.trace("resolveSEPToXRD('" + qxri + "', trustType=" + trustType + ", sepType=" + sepType + ", sepMediaType=" + sepMediaType + ", followRefs=" + followRefs + ")"); XRDS xrds = resolveSEPToXRDS(qxri, trustType, sepType, sepMediaType, followRefs, state); return xrds.getFinalXRD(); } /** * @deprecated */ public ArrayList resolveSEPToURIList(String qxri, TrustType trustType, String sepType, String sepMediaType, bool followRefs) throws PartialResolutionException { return resolveSEPToURIList(qxri, trustType, sepType, sepMediaType, followRefs, new ResolverState()); } /** * @deprecated */ public ArrayList resolveSEPToURIList(String qxri, TrustType trustType, String sepType, String sepMediaType, bool followRefs, ResolverState state) throws PartialResolutionException { log.trace("resolveSEPToURIList(s'" + qxri + "', trustType=" + trustType + ", sepType=" + sepType + ", sepMediaType=" + sepMediaType + ", followRefs=" + followRefs + ")"); XRI xri = parseAbsoluteQXRIOrError(qxri); return resolveSEPToURIList(xri, trustType, sepType, sepMediaType, followRefs, state); } /** * @deprecated */ public ArrayList resolveSEPToURIList(XRI qxri, TrustType trustType, String sepType, String sepMediaType, bool followRefs) throws PartialResolutionException { return resolveSEPToURIList(qxri, trustType, sepType, sepMediaType, followRefs, new ResolverState()); } /** * @deprecated */ public ArrayList resolveSEPToURIList(XRI qxri, TrustType trustType, String sepType, String sepMediaType, bool followRefs, ResolverState state) throws PartialResolutionException { ResolverFlags f = new ResolverFlags(trustType, followRefs); return resolveSEPToURIList(qxri, sepType, sepMediaType, f, state); } /** * @deprecated */ public String resolveSEPToTextURIList(String qxri, TrustType trustType, String sepType, String sepMediaType, bool followRefs) throws PartialResolutionException { return resolveSEPToTextURIList(qxri, trustType, sepType, sepMediaType, followRefs, new ResolverState()); } /** * @deprecated */ public String resolveSEPToTextURIList(String qxri, TrustType trustType, String sepType, String sepMediaType, bool followRefs, ResolverState state) throws PartialResolutionException { ResolverFlags f = new ResolverFlags(trustType, followRefs); XRI xri = parseAbsoluteQXRIOrError(qxri); return resolveSEPToTextURIList(xri, sepType, sepMediaType, f, state); } ///////////////////////////////////////////////////////////////////////// // END DEPRECATED APIS // ///////////////////////////////////////////////////////////////////////// /** * Resolve the given <code>qxri</code> according to its type. * If it is an XRIAuthority, get its first authority XRD and resolve the rest of the segment. * If it is an IRIAuthority, just resolve it directly. * @param xrdsOut * @param qxri - QXRI with IRIAuthority or XRIAuthority (GCS or XRef) * @param flags - ResolverFlags * @return */ public XRDS resolveAuthority(XRI qxri, ResolverFlags flags, ResolverState state) throws PartialResolutionException { log.trace("resolveAuthority(s'" + qxri + "', flags: " + flags + ")"); XRDS xrdsOut = new XRDS(); xrdsOut.setRef("xri://" + qxri.getAuthorityPath().toString()); // determine the authority type AuthorityPath ap = qxri.getAuthorityPath(); try { XRDS newXRDS; if (ap is XRIAuthority) newXRDS = resolveXRIAuth(qxri, (XRIAuthority)ap, flags, state); else if (ap is IRIAuthority) newXRDS = resolveIRIAuth((IRIAuthority) ap, flags, state); else throw new RuntimeException("Unknown authority type"); xrdsOut.addAll(newXRDS); return xrdsOut; } catch (PartialResolutionException e) { xrdsOut.addAll(e.getPartialXRDS()); throw new PartialResolutionException(xrdsOut); } } protected XRDS resolveXRIAuth(XRI origQXRI, XRIAuthority xriAuth, ResolverFlags flags, ResolverState state) throws PartialResolutionException { String rootAuth = xriAuth.getRootAuthority(); if (rootAuth == null) { throw new RuntimeException("First subsegment of '" + xriAuth + "' is null"); } XRD rootXRD = getAuthority(rootAuth); if (rootXRD == null) { XRDS xrdsOut = new XRDS(); // unknown root XRD err = createErrorXRD( xriAuth.toURINormalForm(), Status.UNKNOWN_ROOT, "Authority '" + rootAuth + "' is not configured" ); xrdsOut.add(err); throw new PartialResolutionException(xrdsOut); } XRISegment segment = xriAuth.getXRISegment(); // resolve segment (list of subsegments not including root) against root XRD return resolveAuthSegment(origQXRI, rootXRD, segment, flags, state); } protected XRDS resolveIRIAuth(IRIAuthority iriAuth, ResolverFlags flags, ResolverState state) throws PartialResolutionException { log.trace("resolveIRIAuth('" + iriAuth + "', flags: " + flags + ")"); XRDS xrdsOut = new XRDS(); if (flags.isSaml()) { XRD err = createErrorXRD(iriAuth.toURINormalForm(), Status.NOT_IMPLEMENTED, "SAML is not supported for an IRI authority"); xrdsOut.add(err); throw new PartialResolutionException(xrdsOut); } // only use http for insecure and https for secure String scheme = flags.isHttps() ? "https" : "http"; URI uri = null; try { uri = new URI(scheme, iriAuth.getIUserInfo(), iriAuth.getIHost(), iriAuth.getPort(), null, null, null); } catch (java.net.URISyntaxException e) { XRD err = createErrorXRD(iriAuth.toURINormalForm(), Status.INVALID_INPUT, "Unable to construct URI to resolve IRI authority: " + e.getMessage()); xrdsOut.add(err); throw new PartialResolutionException(xrdsOut); } // now that we've constructed the new URI, try to return the stream from it InputStream in = null; try { in = getDataFromURI(uri, uri.toString(), flags, state); } catch (Exception e) { XRD err = createErrorXRD(iriAuth.toURINormalForm(), Status.NETWORK_ERROR, "Network error occurred while resolving IRI authority: " + e.getMessage()); xrdsOut.add(err); throw new PartialResolutionException(xrdsOut); } if (in == null) { throw new RuntimeException( "resolveIRIAuth - getDataFromURI returned null"); } // read the descriptors try { xrdsOut = readXRDS(in); if (xrdsOut.getNumChildren() != 1) { XRD err = createErrorXRD(iriAuth.toURINormalForm(), Status.UNEXPECTED_RESPONSE, "Expected 1 XRD from IRI authority, got " + xrdsOut.getNumChildren() + " instead"); xrdsOut.add(err); throw new PartialResolutionException(xrdsOut); } } catch (XRIResolutionException e) { XRD err = createErrorXRD(iriAuth.toURINormalForm(), Status.UNEXPECTED_RESPONSE, "Error reading XRDS from server: " + e.getMessage()); xrdsOut.add(err); throw new PartialResolutionException(xrdsOut); } // add the descriptor, but only if is is valid XRD xrd = xrdsOut.getDescriptorAt(0); if (!xrd.isValid()) { XRD err = createErrorXRD(iriAuth.toURINormalForm(), Status.UNEXPECTED_XRD, "XRD is invalid"); xrdsOut.add(err); throw new PartialResolutionException(xrdsOut); } return xrdsOut; } protected XRDS resolveViaProxy(XRI qxri, String serviceType, String serviceMediaType, bool sepSelect, ResolverFlags flags, ResolverState state) throws PartialResolutionException { log.trace("resolveViaProxy('" + qxri + ", serviceType=" + serviceType + ", serviceMediaType=" + serviceMediaType + ", flags: " + flags + ")"); XRDS xrdsOut = new XRDS(); // build the new URI for the proxy URI newURI = null; try { StringBuilder query = new StringBuilder(); if (serviceType != null) { query.append("_xrd_t="); query.append(URLEncoder.encode(serviceType, "UTF-8")); query.append('&'); } if (serviceMediaType != null) { query.append("_xrd_m="); query.append(URLEncoder.encode(serviceMediaType, "UTF-8")); query.append('&'); } query.append("_xrd_r="); query.append(Tags.CONTENT_TYPE_XRDS); query.append(';'); query.append(flags.getTrustParameters()); query.append(";sep="); query.append(sepSelect); query.append(";ref="); query.append(flags.isRefs()); query.append('&'); if (proxyURI.getQuery() != null) { query.append(proxyURI.getQuery()); } StringBuilder uriBuf = new StringBuilder(); uriBuf.append(proxyURI.getScheme()); uriBuf.append("://"); uriBuf.append(proxyURI.getAuthority()); uriBuf.append(proxyURI.getPath()); if (uriBuf.charAt(uriBuf.length() - 1) != '/') uriBuf.append('/'); StringBuilder qxriNoQuery = new StringBuilder(qxri.getAuthorityPath().toIRINormalForm()); if (sepSelect) { qxriNoQuery.append(qxri.getXRIPath().toURINormalForm()); } uriBuf.append(URLEncoder.encode(qxriNoQuery.toString(), "UTF-8")); uriBuf.append('?'); uriBuf.append(query); log.trace("resolveViaProxy - constructed proxy query URI '" + uriBuf + "'"); newURI = new URI(uriBuf.toString()); } catch (java.net.URISyntaxException oEx) { XRD err = createErrorXRD(qxri.getAuthorityPath().toURINormalForm(), Status.INVALID_INPUT, "Unable to construct URI to access proxy resolution service"); xrdsOut.add(err); throw new PartialResolutionException(xrdsOut); } catch (UnsupportedEncodingException e) { // thrown from URLEncoder.encode() - this should never happen since the // US-ASCII encoding should be supported on every computer or so we hope :) XRD err = createErrorXRD(qxri.getAuthorityPath().toURINormalForm(), Status.INVALID_INPUT, "Charset not supported"); xrdsOut.add(err); throw new PartialResolutionException(xrdsOut); } catch (Exception e) { XRD err = createErrorXRD(qxri.getAuthorityPath().toURINormalForm(), Status.PERM_FAIL, "Unexpected error while constructing proxy URI: " + e.getMessage()); xrdsOut.add(err); throw new PartialResolutionException(xrdsOut); } InputStream in = null; try { // try to get the data from it in = getDataFromURI(newURI, qxri.toURINormalForm(), flags, state); XRDS xrds = readXRDS(in); XRD finalXRD = xrds.getFinalXRD(); String code = finalXRD.getStatusCode(); if ((flags.isRefs() && !code.equals(Status.SUCCESS) && !code .equals(Status.REF_NOT_FOLLOWED)) || !code.equals(Status.SUCCESS)) { // got either a non-SUCCESS code or // followRefs is on but we got non-SUCCESS and non-REF_NOT_FOLLOWED throw new PartialResolutionException(xrds); } return xrds; } catch (PartialResolutionException e) { // re-throw throw e; } catch (Exception e) { XRD err = createErrorXRD(qxri.getAuthorityPath().toURINormalForm(), Status.PERM_FAIL, "Error fetching XRDS from proxy: " + e.getMessage()); xrdsOut.add(err); throw new PartialResolutionException(xrdsOut); } } protected XRDS processRedirects(XRI qxri, XRD parent, ResolverFlags flags, ResolverState state) throws PartialResolutionException { log.trace("processRedirects (qxri=" + qxri + ")"); XRDS xrdsOut = new XRDS(); XRDS tmpXRDS; List redirects = parent.getPrioritizedRedirects(); Iterator it = redirects.iterator(); // there must be some redirects! if (!it.hasNext()) throw new RuntimeException("processRedirects: No redirect to process!"); // do a depth-first following of redirects while (it.hasNext()) { Redirect r = (Redirect)it.next(); log.debug("processRedirects - Got redirect " + r); URI uri; try { uri = new URI(r.getValue()); if (r.getAppend() != null) { // construct URI String constructedURI = constructURI(uri, r.getAppend(), qxri); uri = new URI(constructedURI); } } catch (URISyntaxException e) { // skip invalid URIs log.warn("processRedirects - Encountered invalid URI while constructing Redirect URI"); continue; } try { log.info("processRedirects - Fetching URI (" + uri + ")"); tmpXRDS = fetchRedirectXRDS(uri, parent, qxri, flags, state); xrdsOut.add(tmpXRDS); /* XRD finalXRD = tmpXRDS.getFinalXRD(); if (finalXRD.getNumRedirects() > 0) { tmpXRDS = processRedirects(qxri, finalXRD, flags, state); } */ return xrdsOut; // we're done! } catch (PartialResolutionException e) { xrdsOut.add(e.getPartialXRDS()); // fall through to continue to the next } } log.info("processRedirects - exhausted list of Redirects. Throwing PRE"); throw new PartialResolutionException(xrdsOut); } protected String verifyCID(XRD prevXRD, XRD xrd) { CanonicalID parentCID = prevXRD.getCanonicalID(); CanonicalID thisCID = xrd.getCanonicalID(); if (parentCID == null) { log.warn("verifyCID: no parent CID!"); return Status.CID_FAILED; } if (thisCID == null) return Status.CID_ABSENT; try { XRI parentCIDXRI = new XRI(parentCID.getValue()); XRI thisCIDXRI = new XRI(thisCID.getValue()); if (parentCIDXRI.isRelative()) return Status.CID_FAILED; if (thisCIDXRI.isRelative()) return Status.CID_FAILED; AuthorityPath parentAuthorityAP = parentCIDXRI.getAuthorityPath(); if (parentAuthorityAP == null) return Status.CID_FAILED; AuthorityPath thisAuthorityAP = thisCIDXRI.getAuthorityPath(); if (thisAuthorityAP == null) return Status.CID_FAILED; if (!(thisAuthorityAP is XRIAuthority)) return Status.CID_FAILED; XRI thisAuthorityParentXRI = ((XRIAuthority)thisAuthorityAP).getParentAsXRI(); if (thisAuthorityParentXRI == null) return Status.CID_FAILED; String parentXRIStr = parentAuthorityAP.toIRINormalForm(); String thisParentXRIStr = thisAuthorityParentXRI.getAuthorityPath().toIRINormalForm(); if (parentXRIStr.equalsIgnoreCase(thisParentXRIStr)) return Status.CID_VERIFIED; else return Status.CID_FAILED; } catch (Exception e) { log.warn("verifyCID - exception caught: " + e); } return Status.CID_FAILED; } /** * check that each synonym element in the Redirect xrd is present in the parent * @param xrd * @param parent * @return */ protected String verifyRedirectXRD(XRD xrd, XRD parent) { CanonicalID cid = xrd.getCanonicalID(); CanonicalID cid2 = parent.getCanonicalID(); if (cid != null && cid2 == null) return "CanonicalID element is not present in parent XRD"; if (cid != null) { if (!verifySynonymElement(cid, cid2)) return "CanonicalID element is different from parent's"; } CanonicalEquivID ceid = xrd.getCanonicalEquivID(); CanonicalEquivID ceid2 = parent.getCanonicalEquivID(); if (ceid != null && ceid2 == null) return "CanonicalEquivID element is not present in parent XRD"; if (ceid != null) { if (!verifySynonymElement(ceid, ceid2)) return "CanonicalEquivID element is different from parent's"; } for (int i = 0; i < xrd.getNumLocalIDs(); i++) { LocalID l = xrd.getLocalIDAt(i); // search for it in parent bool found = false; for (int j = 0; j < parent.getNumLocalIDs(); j++) { if (verifySynonymElement(l, parent.getLocalIDAt(j))) { found = true; break; } } if (!found) { return "LocalID element " + l.getValue() + " is not present in parent XRD"; } } for (int i = 0; i < xrd.getNumEquivIDs(); i++) { EquivID e = xrd.getEquivIDAt(i); // search for it in parent bool found = false; for (int j = 0; j < parent.getNumEquivIDs(); j++) { if (verifySynonymElement(e, parent.getEquivIDAt(j))) { found = true; break; } } if (!found) { return "EquivID element " + e.getValue() + " is not present in parent XRD"; } } return null; } private bool verifySynonymElement(SimpleXMLElement e1, SimpleXMLElement e2) { try { XRI x1 = XRI.fromURINormalForm(e1.getValue()); XRI x2 = XRI.fromURINormalForm(e2.getValue()); return x1.equals(x2); } catch (XRIParseException e) { // CanonicalID not an XRI, we ignore here } try { URI u1 = new URI(e1.getValue()); URI u2 = new URI(e2.getValue()); if (!u1.equals(u2)) return false; } catch (URISyntaxException e) { return false; } return true; } protected String verifyCEID(XRI qxri, XRD xrd, ResolverFlags flags, ResolverState state) throws PartialResolutionException { CanonicalEquivID ceid = xrd.getCanonicalEquivID(); if (ceid == null) { log.debug("verifyCEID - No CEID in the XRD"); return Status.CID_ABSENT; } log.debug("verifyCEID - Verifying CEID (" + ceid.getValue() + ")"); CanonicalID cid = xrd.getCanonicalID(); if (cid == null) { log.debug("verifyCEID - No CID in the XRD"); return Status.CID_FAILED; } XRI cidX; try { cidX = XRI.fromURINormalForm(cid.getValue()); } catch (Exception e) { log.debug("verifyCEID - Unable to parse CID"); return Status.CID_FAILED; } if (ceid.getValue().equals(cid.getValue())) { log.debug("verifyCEID - CID is character-for-character equivalent to CEID."); return Status.CID_VERIFIED; } try { XRI ceidX = XRI.fromURINormalForm(ceid.getValue()); log.info("verifyCEID - resolving CEID"); XRD ceidXRD = resolveAuthToXRD(ceidX, flags, state); Status s = ceidXRD.getStatus(); if (!s.getCID().equals(Status.CID_VERIFIED)) { log.debug("verifyCEID - XRD for CEID is not CID verified"); return Status.CID_FAILED; } CanonicalID cid2 = ceidXRD.getCanonicalID(); if (cid2 == null) { log.debug("verifyCEID - no CID in the XRD in CEID"); return Status.CID_FAILED; } XRI cidX2 = XRI.fromURINormalForm(cid2.getValue()); if (!cidX2.toURINormalForm().equals(cidX.toURINormalForm())) { log.debug("verifyCEID - CEID's XRD's CID is not equivalent to the original CID"); return Status.CID_FAILED; } /// look for an EquivID or CanonicalEquivID backpointer to the original CID CanonicalEquivID ceid2 = ceidXRD.getCanonicalEquivID(); XRI ceidX2 = XRI.fromURINormalForm(ceid2.getValue()); if (ceidX2.toURINormalForm().equals(cidX.toURINormalForm())) { log.debug("verifyCEID - CEID backpointer found"); return Status.CID_VERIFIED; } for (int i = 0; i < ceidXRD.getNumEquivIDs(); i++) { EquivID e = ceidXRD.getEquivIDAt(i); XRI eX = XRI.fromURINormalForm(e.getValue()); if (eX.toURINormalForm().equals(cidX.toURINormalForm())) { log.debug("verifyCEID - EquivID backpointer found"); return Status.CID_VERIFIED; } } } catch (Exception e) { log.debug("verifyCEID - unknown error: " + e); } return Status.CID_FAILED; } /** * * @param uri * @param parent * @param parentService * @param segment * @param flags * @param state * @return * @throws PartialResolutionException */ protected XRDS fetchAuthXRDSHelper(XRI qxri, URI uri, XRD parent, Service parentService, XRISegment segment, ResolverFlags flags, ResolverState state) throws PartialResolutionException { XRDS xrdsOut = new XRDS(); String query = segment.getSubSegmentAt(0).toURINormalForm(true); URI newURI; try { newURI = constructAuthResURI(uri.toString(), segment.toURINormalForm(true)); log.trace("fetchAuthXRDS - newURI = " + newURI); } catch (java.net.URISyntaxException oEx) { throw makeResolutionException(xrdsOut, query, Status.AUTH_RES_ERROR, "Invalid URI for authority resolution service"); } XRDS tmpXRDS = null; // now that we've constructed the new URI, try to return the stream from it try { InputStream in = getDataFromURI(newURI, segment.toString(), flags, state); tmpXRDS = readXRDS(in); log.debug("fetchAuthXRDS - got XRDS = " + tmpXRDS.toString()); } catch (IOException e) { log.trace("fetchAuthXRDS - got IOException from URI " + newURI); throw makeResolutionException(xrdsOut, query, Status.NETWORK_ERROR, "Networking error encountered"); } catch (Exception e) { log.trace("fetchAuthXRDS - " + e); throw makeResolutionException(xrdsOut, query, Status.AUTH_RES_ERROR, e.getMessage()); } //// sanity checks // there should be at least one child element if (tmpXRDS.getNumChildren() < 1) { throw makeResolutionException(xrdsOut, query, Status.INVALID_XRDS, "Invalid XRDS document"); } if (tmpXRDS.getNumChildren() > segment.getNumSubSegments()) { throw makeResolutionException(xrdsOut, query, Status.INVALID_XRDS, "Invalid XRDS document: too many XRD elements returned"); } XRD prevXRD = parent; // check each child for (int d = 0; d < tmpXRDS.getNumChildren(); d++) { if (!tmpXRDS.isXRDAt(d)) throw makeResolutionException(xrdsOut, query, Status.INVALID_XRDS, "Authority XRDS document should not contain XRDS element"); XRD xrd = tmpXRDS.getDescriptorAt(d); xrdsOut.add(xrd); // status is not success ServerStatus sstat = xrd.getServerStatus(); Status stat; if (sstat == null) { // compatibility: if no ServerStatus, look for Status stat = xrd.getStatus(); if (stat != null) { xrd.setServerStatus(new ServerStatus(stat.getCode(), stat.getText())); } } else { stat = new Status(sstat.getCode(), sstat.getText()); xrd.setStatus(stat); } if (stat == null) throw makeResolutionException(xrdsOut, query, Status.INVALID_XRDS, "Missing ServerStatus or Status element in XRD"); if (!stat.getCode().equals(Status.SUCCESS)) { throw new PartialResolutionException(xrdsOut); } // check the basic properties of the descriptor if (!xrd.isValid()) { xrd.setStatus(new Status(Status.UNEXPECTED_RESPONSE, "XRD is not valid (stale?)")); throw new PartialResolutionException(xrdsOut); } if (flags.isCid()) { Status parentStatus = parent.getStatus(); Status s = xrd.getStatus(); String parentCIDStat = parentStatus.getCID(); if (parentCIDStat.equals(Status.CID_FAILED)) { s.setCID(Status.CID_FAILED); } else { s.setCID(verifyCID(prevXRD, xrd)); } } // if we need to do trusted resolution checking if (flags.isSaml()) { // Each descriptor must be validated independently as well as // against the one that preceded (described) it in the // descriptor chain. // TODO: there could be more than one Authority Resolution Service // in the final XRD /* bool valid = isTrustedDescriptor(segment.getSubSegmentAt(d), xrd, parentService); // bail if the descriptor is not valid if (!valid) { xrd.setStatus(new Status(Status.UNVERIFIED_SIGNATURE, "Signature verification failed.")); throw new PartialResolutionException(xrdsOut); } */ } prevXRD = xrd; } return xrdsOut; } /** * Fetches the XRDS document given the authResServices * @param qxri * @param parent * @param authResServices * @param segment * @param flags * @param state * @return * @throws PartialResolutionException */ protected XRDS fetchAuthXRDS(XRI qxri, XRD parent, List authResServices, XRISegment segment, ResolverFlags flags, ResolverState state) throws PartialResolutionException { XRDS xrdsOut = null; XRD errXRD = null; String query = segment.getSubSegmentAt(0).toURINormalForm(true); //// TODO verify synonyms ///// Try each URI in each selected service in turn Exception savedException = null; Iterator srvIterator = authResServices.iterator(); while (srvIterator.hasNext()) { Service srv = (Service) srvIterator.next(); Iterator uriIterator = srv.getPrioritizedURIs().iterator(); while (uriIterator.hasNext()) { SEPUri sepURI = (SEPUri) uriIterator.next(); URI uri = sepURI.getURI(); log.trace("fetchAuthXRDS - trying URI='" + uri + "'"); // skip non-HTTPS URIs if HTTPS was requested if (flags.isHttps() && !uri.getScheme().equals(HTTPS)) { log.trace("fetchAuthXRDS - skipping non HTTPS URI"); continue; } try { xrdsOut = fetchAuthXRDSHelper(qxri, uri, parent, srv, segment, flags, state); // if no error, return immediately return xrdsOut; } catch (PartialResolutionException e) { xrdsOut = e.getPartialXRDS(); } } } if (xrdsOut == null) { // no appropriate URI found xrdsOut = new XRDS(); String code = flags.isHttps()? Status.TRUSTED_RES_ERROR : Status.AUTH_RES_ERROR; xrdsOut.add(createErrorXRD(query, code, "No URI found for authority resolution")); } throw new PartialResolutionException(xrdsOut); } protected void checkMaxRequests(XRDS xrdsOut, String query, ResolverState state) throws PartialResolutionException { if (maxRequests >= 0 && state.getNumRequests() >= maxRequests) { XRD finalXRD = xrdsOut.getFinalXRD(); if (finalXRD == null) { finalXRD = createErrorXRD(query, Status.LIMIT_EXCEEDED, "Maximum of authority resolution requests exceeded"); xrdsOut.add(finalXRD); } else { finalXRD.setStatus(new Status(Status.LIMIT_EXCEEDED, "Maximum of authority resolution requests exceeded")); } throw new PartialResolutionException(xrdsOut); } } private PartialResolutionException makeResolutionException(XRDS targetXRDS, String query, String status, String message) { XRD x = createErrorXRD(query, status, message); targetXRDS.add(x); return new PartialResolutionException(targetXRDS); } /** * Resolve the given authority segment (without root) from the * <code>parent</code> (root-authority) XRD. It will follow references if told to do so. * @param xrdsOut - the resulting XRDS document (nested if need be) * @param parent * @param segment * @param flags * @return bool <code>true</code> if the given segment is completely resolved. */ public XRDS resolveAuthSegment(XRI qxri, XRD parent, XRISegment segment, ResolverFlags flags, ResolverState state) throws PartialResolutionException { log.trace("resolveAuthSegment - segment='" + segment + "'"); XRDS xrdsOut = new XRDS(); XRDS tmpXRDS = null; CanonicalID parentCID = null; bool authResComplete = false; ResolverFlags currentFlags = null; // this is only for overriding by HttpsBypassAuthority settings String parentXRI = ((XRIAuthority)qxri.getAuthorityPath()).getRootAuthority(); XRISegment remainingSegment = segment; while (remainingSegment != null && remainingSegment.getNumSubSegments() > 0) { // clone flags currentFlags = new ResolverFlags(flags); // more subsegments to resolve String query = remainingSegment.getSubSegmentAt(0).toURINormalForm(true); log.debug("resolveAuthSegment - resolving subsegment '" + query + "'"); checkMaxRequests(xrdsOut, query, state); // if HTTPS is requested and what we are resolving is allowed to bypass HTTPS, we turn off the HTTPS flag // for auth-res service selection if (currentFlags.isHttps() && isHttpsBypassAuthority(parentXRI)) { log.debug("Bypassing HTTPS for " + parentXRI); currentFlags.setHttps(false); } //// perform service selection String authResMediaType = Tags.CONTENT_TYPE_XRDS + ";" + currentFlags.getTrustParameters(); List authResServices = selectServices(parent.getServices(), Tags.SERVICE_AUTH_RES, null, authResMediaType, currentFlags); if (authResServices.size() < 1) { log.debug("resolveAuthSegment - no authority resolution service found!"); throw makeResolutionException( xrdsOut, query, Status.AUTH_RES_NOT_FOUND, "Authority Resolution Service Not Found" ); } try { // retrieve XRDS documents for the given subsegment log.trace("resolveAuthSegment - fetching XRDS"); tmpXRDS = fetchAuthXRDS(qxri, parent, authResServices, remainingSegment, currentFlags, state); } catch (PartialResolutionException e) { log.trace("got PRE: " + e.getPartialXRDS()); log.trace("xrdsOut.n = " + xrdsOut.getNumChildren() + ", partialXRDS.n=" + e.getPartialXRDS().getNumChildren()); xrdsOut.add(e.getPartialXRDS()); throw new PartialResolutionException(xrdsOut); } //// add the subsegments xrdsOut.addAll(tmpXRDS); //// replace parent XRD parent = tmpXRDS.getFinalXRD(); for (int k = 0; k < tmpXRDS.getNumChildren(); k++) { XRISubSegment subseg = remainingSegment.getSubSegmentAt(k); parentXRI = parentXRI + subseg; } remainingSegment = remainingSegment.getRemainder(tmpXRDS.getNumChildren()); tmpXRDS = null; try { if (parent.getNumRedirects() > 0) { log.debug("resolveAuthSegment - processing Redirect(s)"); tmpXRDS = processRedirects(qxri, parent, currentFlags, state); xrdsOut.addAll(tmpXRDS); // replace parent parent = tmpXRDS.getFinalXRD(); } else if (parent.getNumRefs() > 0) { if (!currentFlags.isRefs()) { throw makeResolutionException( xrdsOut, query, Status.REF_NOT_FOLLOWED, "Ref not followed"); } log.debug("resolveAuthSegment - processing Ref(s)"); tmpXRDS = processRefs(parent, currentFlags, state); xrdsOut.addAll(tmpXRDS); // replace parent parent = tmpXRDS.getFinalXRD(); } } catch (PartialResolutionException e) { xrdsOut.addAll(e.getPartialXRDS()); log.debug("resolveAuthSegment - got PRE while processing Ref or Redirect"); throw new PartialResolutionException(xrdsOut); } } log.debug("resolveAuthSegment - successfully resolved all subsegments"); if (parent.getStatus().getCID().equals(Status.CID_VERIFIED) && parent.getCanonicalEquivID() != null) { log.debug("resolveAuthSegment - final XRD contains a CanonicalEquivID. Verifying..."); String vStat = verifyCEID(qxri, parent, currentFlags, state); parent.getStatus().setCEID(vStat); } return xrdsOut; } protected XRDS processRefs(XRD parent, ResolverFlags flags, ResolverState state) throws PartialResolutionException { XRDS xrdsOut = new XRDS(); //// get all the Refs in the parent XRD List refs = parent.getPrioritizedRefs(); Iterator it = refs.iterator(); //// try each one in turn while (it.hasNext()) { Ref ref = (Ref)it.next(); checkMaxRefs(xrdsOut, ref.getValue(), state); XRI refXRI; try { refXRI = parseAbsoluteQXRIOrError(ref.getValue()); } catch (PartialResolutionException e) { xrdsOut.add(e.getPartialXRDS()); continue; } // record that we are following a ref state.pushFollowingRef(refXRI); try { XRDS tmpXRDS = resolveAuthority(refXRI, flags, state); xrdsOut.add(tmpXRDS); break; } catch (PartialResolutionException e) { xrdsOut.add(e.getPartialXRDS()); if (!it.hasNext()) // last ref, throw the exception (otherwise, continue) throw new PartialResolutionException(xrdsOut); } } return xrdsOut; } protected void checkMaxRefs(XRDS xrdsOut, String query, ResolverState state) { } protected bool isTrustedDescriptor(XRISubSegment subseg, XRD xrd, Service parentService) { // Descriptor must provide an XML ID for SAML assertion validation String sXMLID = xrd.getXmlID(); if ((sXMLID == null) || (sXMLID.length() == 0)) { return false; } // Must contain an authority id String sAuthorityID = xrd.getProviderID(); if ((sAuthorityID == null) || (sAuthorityID.length() == 0)) { return false; } // The resolved element must match the subsegment we were looking for String sSubsegment = subseg.toString(); if ((xrd.getQuery() == null) || (!xrd.getQuery().equals(sSubsegment))) { return false; } // Must contain a SAML assertion Assertion oAssertion = xrd.getSAMLAssertion(); if (oAssertion == null) { return false; } // Assertion must also be valid if (!oAssertion.isValid()) { return false; } // Subject must have correct info Subject oSubject = oAssertion.getSubject(); if (oSubject == null) { return false; } NameID oNameID = oSubject.getNameID(); if (oNameID == null) { return false; } if (!sSubsegment.equals(oNameID.getValue())) { return false; } if (!sAuthorityID.equals(oNameID.getNameQualifier())) { return false; } // must contain a SAML Attribute statement AttributeStatement oAttrStmt = oAssertion.getAttributeStatement(); if (oAttrStmt == null) { return false; } // Attribute must describe the XML ID reference Attribute oAttr = oAttrStmt.getAttribute(); if ((oAttr.getName() == null) || (!oAttr.getName().equals(Tags.NS_XRD_V2))) { return false; } String sValue = oAttr.getValue(); if ((sValue == null) || (!sValue.equals("#" + sXMLID))) { return false; } // The describing descriptor must contain an authority if (parentService == null) { return false; } // Describing authority id must match this descriptor's authority id if ((parentService.getProviderId() == null) || (!parentService.getProviderId().equals(sAuthorityID))) { return false; } // Describing authority must provide KeyInfo KeyInfo oKeyInfo = parentService.getKeyInfo(); if (oKeyInfo == null) { log.debug("KeyInfo is missing from describing Authority."); return false; } // Verify assertion try { xrd.verifySignature(oKeyInfo.getPublicKey()); } catch (XMLSecurityException oEx) { log.debug("Assertion verification failed.", oEx); return false; } return true; } /** * @param xrd * @param qxri * @param sepType * @param sepMediaType * @param flags * @param state * @return * @throws PartialResolutionException */ public List selectServiceFromXRD(XRDS xrdsOut, XRD xrd, XRI qxri, String sepType, String sepMediaType, ResolverFlags flags, ResolverState state) throws PartialResolutionException { // get the QXRI path String path = null; XRIAbsolutePath absPath = qxri.getXRIAbsolutePath(); if (absPath != null) path = absPath.toURINormalForm(); // find services List selectedSvcs = selectServices(xrd.getServices(), sepType, path, sepMediaType, flags); xrd.setSelectedServices(selectedSvcs); if (selectedSvcs.size() == 0) { Status s = xrd.getStatus(); s.setCode(Status.SEP_NOT_FOUND); s.setText("Requested service endpoint not found"); throw new PartialResolutionException(xrdsOut); } // check if first Service has Redirect of Ref Service srv = (Service)selectedSvcs.get(0); if (srv.getNumRedirects() > 0) { // try to follow each redirect (which will recurse back into this method if the XRDS was fetched successfully.) selectedSvcs = processServiceRedirects(xrdsOut, srv, xrd, qxri, sepType, sepMediaType, flags, state); } else if (srv.getNumRefs() > 0) { selectedSvcs = processServiceRefs(xrdsOut, srv, xrd, qxri, sepType, sepMediaType, flags, state); } return selectedSvcs; } /** * * @param xrdsOut Each * @param srv * @param parent * @param qxri * @param sepType * @param sepMediaType * @param flags * @param state * @return * @throws PartialResolutionException */ private List processServiceRedirects(XRDS xrdsOut, Service srv, XRD parent, XRI qxri, String sepType, String sepMediaType, ResolverFlags flags, ResolverState state) throws PartialResolutionException { List redirects = srv.getPrioritizedRedirects(); Iterator it = redirects.iterator(); // there must be some redirects! if (!it.hasNext()) throw new RuntimeException("processServiceRedirects: No redirect to process!"); // do a depth-first following of redirects while (it.hasNext()) { Redirect r = (Redirect)it.next(); URI uri; try { uri = new URI(r.getValue()); if (r.getAppend() != null) { // construct URI String constructedURI = constructURI(uri, r.getAppend(), qxri); uri = new URI(constructedURI); } } catch (URISyntaxException e) { XRDS tmpXRDS = new XRDS(); XRD err = createErrorXRD(r.getValue(), Status.INVALID_REDIRECT, "Invalid Redirect URI"); tmpXRDS.add(err); xrdsOut.add(tmpXRDS); continue; } try { XRDS tmpXRDS = fetchRedirectXRDS(uri, parent, qxri, flags, state); xrdsOut.add(tmpXRDS); XRD finalXRD = tmpXRDS.getFinalXRD(); tmpXRDS = new XRDS(); List services = selectServiceFromXRD(tmpXRDS, finalXRD, qxri, sepType, sepMediaType, flags, state); xrdsOut.addAll(tmpXRDS); return services; // we're done! } catch (XRIResolutionException e) { XRDS tmpXRDS = new XRDS(); XRD err = createErrorXRD(uri.toString(), Status.REDIRECT_ERROR, "Error fetching XRDS: " + e.getMessage()); tmpXRDS.add(err); xrdsOut.add(tmpXRDS); // fall through to continue to the next } } throw new PartialResolutionException(xrdsOut); } protected List processServiceRefs(XRDS xrdsOut, Service srv, XRD parent, XRI qxri, String sepType, String sepMediaType, ResolverFlags flags, ResolverState state) throws PartialResolutionException { //// get all the Refs in the parent XRD List refs = srv.getPrioritizedRefs(); Iterator it = refs.iterator(); //// try each one in turn while (it.hasNext()) { Ref ref = (Ref)it.next(); checkMaxRefs(xrdsOut, ref.getValue(), state); XRI refXRI; try { refXRI = parseAbsoluteQXRIOrError(ref.getValue()); } catch (PartialResolutionException e) { xrdsOut.add(e.getPartialXRDS()); continue; } // record that we are following a ref state.pushFollowingRef(refXRI); try { XRDS tmpXRDS = resolveSEPToXRDS(refXRI, sepType, sepMediaType, flags, state); xrdsOut.add(tmpXRDS); return tmpXRDS.getFinalXRD().getSelectedServices().getList(); } catch (PartialResolutionException e) { xrdsOut.add(e.getPartialXRDS()); // fall through to continue to the next } } throw new PartialResolutionException(xrdsOut); } /** * Filter <code>services</code> based on the given <code>type</code>, <code>path</code> * and <code>mediaType</code> criteria and return a prioritized list of services. * @param services * @param type * @param path * @param mediaType * @return ArrayList containing Services in priority order */ protected ArrayList selectServices( Vector services, String type, String path, String mediaType, ResolverFlags flags) { if (services == null || services.size() == 0) return new ArrayList(); SEPSelector selector = new SEPSelector(new ArrayList(services)); // ArrayList selectedServices = selector.getSelectedSEPs(type, mediaType, path); List selectedServices = SEPSelector.select(services, type, mediaType, path, flags); if (selectedServices == null || selectedServices.size() == 0) return new ArrayList(); PrioritizedList list = new PrioritizedList(); for (int i = 0; i < selectedServices.size(); i++) { Service s = (Service) selectedServices.get(i); String priority = (s.getPriority() == null) ? PrioritizedList.PRIORITY_NULL : s.getPriority().toString(); list.addObject(priority, s); } return list.getList(); } /** * Gets an InputStream from the URI according the XRI HTTP Bindings. * * @param uri - * The URI to get data from * @param flags - * ResolverFlags * @return InputStream if HTTP OK is received, null if HTTP Not found * @throws XRIResolutionException * if HTTP response is not OK or Not Found */ protected InputStream getDataFromURI(URI uri, String query, ResolverFlags flags, ResolverState state) throws XRIResolutionException, IOException { // Post request HttpURLConnection conn = null; InputStream in = null; try { // add the appropriate accept header LinkedHashMap requestProp = new LinkedHashMap(); String sContentType = Tags.CONTENT_TYPE_XRDS + ";" + flags.getTrustParameters(); requestProp.put(Tags.HEADER_ACCEPT, sContentType); conn = IO.getConnectionToURI(uri, "GET", requestProp, moSocketFactory, maxHttpRedirects, false); if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) { conn.disconnect(); throw new XRIResolutionException( "Got bad response code from URI: " + uri.toString() + ", code = " + conn.getResponseCode()); } // read the bytes int bufSize = 4096; byte[] buf = new byte[bufSize]; int bufIndex = 0; in = conn.getInputStream(); while (true) { int n = in.read(); if (n == -1) // EOF break; if (maxBytesPerRequest >= 0 && bufIndex >= maxBytesPerRequest) { throw new XRIResolutionException(Status.LIMIT_EXCEEDED, "Maximum response size exceeded"); } if (maxTotalBytes >= 0 && state.getNumBytesReceived() + bufIndex >= maxTotalBytes) { throw new XRIResolutionException(Status.LIMIT_EXCEEDED, "Maximum total received bytes exceeded"); } if (bufIndex >= bufSize) { byte[] newBuf = new byte[bufSize * 2]; System.arraycopy(buf, 0, newBuf, 0, bufSize); buf = newBuf; bufSize *= 2; } buf[bufIndex++] = (byte) n; } // using Latin1 allows the length() method to return the exact bytes String bufString = new String(buf, 0, bufIndex, "iso-8859-1"); state.pushResolved(query, flags.toString(), bufString, uri); return new ByteArrayInputStream(buf, 0, bufIndex); } catch (java.io.IOException e) { // There was a communication error log.warn("Failed XRI lookup from " + uri.toString() + ". IOException " + e); throw e; } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } } } protected XRDS fetchRedirectXRDS(URI uri, XRD parent, XRI qxri, ResolverFlags flags, ResolverState state) throws PartialResolutionException { XRDS xrdsOut = new XRDS(); String query = qxri.toURINormalForm(); xrdsOut.setRedirect(uri.toString()); XRDS tmpXRDS = null; try { log.info("fetchRedirectXRDS - fetching from URI(" + uri + ")"); InputStream in = getDataFromURI(uri, query, flags, state); log.info("fetchRedirectXRDS - reading content from URI(" + uri + ")"); tmpXRDS = readXRDS(in); log.debug("fetchRedirectXRDS - got XRDS = " + tmpXRDS.toString()); } catch (IOException e) { log.error("fetchRedirectXRDS - got IOException from URI " + uri); throw makeResolutionException(xrdsOut, query, Status.NETWORK_ERROR, "Networking error encountered"); } catch (Exception e) { log.error("fetchRedirectXRDS - unexpected error: " + e); e.printStackTrace(); throw makeResolutionException(xrdsOut, query, Status.AUTH_RES_ERROR, e.getMessage()); } //// sanity checks // there should be exactly one child element if (tmpXRDS.getNumChildren() != 1 || !tmpXRDS.isXRDAt(0)) { throw makeResolutionException(xrdsOut, query, Status.INVALID_XRDS, "Invalid XRDS document: single XRD element expected"); } if (!tmpXRDS.isXRDAt(0)) throw makeResolutionException(xrdsOut, query, Status.INVALID_XRDS, "Authority XRDS document should not contain XRDS element"); XRD xrd = tmpXRDS.getDescriptorAt(0); xrdsOut.add(xrd); ServerStatus sstat = xrd.getServerStatus(); Status stat; if (sstat == null) { // compatibility: if no ServerStatus, look for Status stat = xrd.getStatus(); } else { stat = new Status(sstat.getCode(), sstat.getText()); xrd.setStatus(stat); } if (stat == null) throw makeResolutionException(xrdsOut, query, Status.INVALID_XRDS, "Missing ServerStatus or Status element in Redirect XRD"); if (!stat.getCode().equals(Status.SUCCESS)) { throw new PartialResolutionException(xrdsOut); } // check the basic properties of the descriptor if (!xrd.isValid()) { xrd.setStatus(new Status(Status.UNEXPECTED_RESPONSE, "XRD is not valid (stale?)")); throw new PartialResolutionException(xrdsOut); } String err = verifyRedirectXRD(xrd, parent); if (err != null) { xrd.setStatus(new Status(Status.REDIRECT_VERIFY_FAILED, err)); throw new PartialResolutionException(xrdsOut); } // copy parent Status cid attribute if present stat.setCID(xrd.getCanonicalID() == null? Status.CID_ABSENT : parent.getStatus().getCID()); // copy parent Status ceid attribute (without checking if present since it is supposed to be "off" for // non-final XRD, and we don't know whether this is a final XRD.) stat.setCEID(parent.getStatus().getCEID()); try { if (xrd.getNumRedirects() > 0) { log.info("fetchRedirectXRDS - XRD at URI(" + uri + ") contains Redirect(s), following.."); tmpXRDS = processRedirects(qxri, xrd, flags, state); xrdsOut.addAll(tmpXRDS); } else if (xrd.getNumRefs() > 0) { if (!flags.isRefs()) { throw makeResolutionException( xrdsOut, query, Status.REF_NOT_FOLLOWED, "Ref not followed"); } log.info("fetchRedirectXRDS - XRD at URI(" + uri + ") contains Ref(s), following.."); tmpXRDS = processRefs(xrd, flags, state); xrdsOut.addAll(tmpXRDS); } } catch (PartialResolutionException e) { xrdsOut.addAll(e.getPartialXRDS()); throw new PartialResolutionException(xrdsOut); } return xrdsOut; } protected XRDS readXRDS(InputStream in) throws XRIResolutionException { XRDS xrds = null; if (in == null) { return xrds; } // Read response into DOM structure try { log.debug("readXRDS - parsing input stream"); DOMParser domParser = DOMUtils.getDOMParser(); domParser.parse(new InputSource(in)); Document doc = domParser.getDocument(); Element element = doc.getDocumentElement(); log.debug("readXRDS - successfully read XML document into DOM"); xrds = new XRDS(element, true); log.debug("readXRDS - successfully parsed XRDS document"); } catch (IOException e) { throw new XRIResolutionException("I/O error while reading XRDS document: " + e, e); } catch (SAXException e) { throw new XRIResolutionException("Invalid XRDS document: " + e, e); } catch (URISyntaxException e) { throw new XRIResolutionException("Error parsing XRDS document (URISyntaxException): " + e, e); } catch (ParseException e) { throw new XRIResolutionException("Error parsing XRDS document (ParseException)", e); } finally { try { in.close(); } catch (IOException e) { } } return xrds; } /** * Creates a Resolver obj configured by properties. * @throws ParseException * @throws URISyntaxException */ public Resolver(Properties properties) throws URISyntaxException, ParseException { this(); int maxFollowRedirects = Integer.parseInt(properties.getProperty( "MaxHttpRedirectAllowed", "10")); int maxFollowRefs = Integer.parseInt(properties.getProperty( "MaxFollowRefs", "10")); int maxRequests = Integer.parseInt(properties.getProperty( "MaxRequests", "10")); int maxTotalBytes = Integer.parseInt(properties.getProperty( "MaxTotalBytes", "1048576")); // 1Mb int maxBytesPerRequest = Integer.parseInt(properties.getProperty( "MaxBytesPerRequest", "512000")); // 500Kb XRD equalsAuthority = XRD.parseXRD(properties .getProperty("EqualsAuthority"), false); XRD atAuthority = XRD.parseXRD(properties.getProperty("AtAuthority"), false); XRD bangAuthority = XRD.parseXRD(properties .getProperty("BangAuthority"), false); String supports = properties.getProperty("SupportedResMediaTypes"); this.setMaxHttpRedirects(maxFollowRedirects); this.setMaxFollowRefs(maxFollowRefs); this.setMaxRequests(maxRequests); this.setMaxTotalBytes(maxTotalBytes); this.setMaxBytesPerRequest(maxBytesPerRequest); this.setAuthority("=", equalsAuthority); this.setAuthority("@", atAuthority); this.setAuthority("!", bangAuthority); } public XRD createErrorXRD(String query, String code, String msg) { XRD err = new XRD(); err.setQuery(query); Status stat = new Status(code, msg); err.setStatus(stat); return err; } public URI constructAuthResURI(String sepURI, String segment) throws URISyntaxException { if (false) { // old construction rules URI uri = new URI(sepURI); StringBuilder sepURIStr = new StringBuilder(uri.getScheme()); sepURIStr.append("://"); sepURIStr.append(uri.getAuthority()); sepURIStr.append(uri.getPath()); if (sepURIStr.length() < 0 || sepURIStr.charAt(sepURIStr.length() - 1) != '/') sepURIStr.append('/'); sepURIStr.append(segment); if (uri.getQuery() != null) { sepURIStr.append("?"); sepURIStr.append(uri.getQuery()); } URI newURI = new URI(sepURIStr.toString()); return newURI; } StringBuilder sb = new StringBuilder(sepURI.toString()); if (sb.length() == 0 || sb.charAt(sb.length() - 1) != '/') sb.append('/'); sb.append(segment); return new URI(sb.toString()); } public String constructURI(URI sepURI, String append, XRI qxri) { log.trace("constructURI - sepURI=" + sepURI + ", append=" + append + ", qxri=" + qxri); if (append == null) return sepURI.toString(); StringBuilder result = new StringBuilder(sepURI.toString()); if (append.equals(SEPUri.APPEND_NONE)) { } else if (append.equals(SEPUri.APPEND_LOCAL)) { XRIPath path = qxri.getXRIPath(); if (path != null) { result.append(path.toURINormalForm()); } XRIQuery query = qxri.getQuery(); if (query != null) { result.append('?'); result.append(query); } } else if (append.equals(SEPUri.APPEND_AUTHORITY)) { AuthorityPath a = qxri.getAuthorityPath(); if (a != null) result.append(a.toURINormalForm()); } else if (append.equals(SEPUri.APPEND_PATH)) { XRIAbsolutePath p = qxri.getXRIAbsolutePath(); if (p != null) result.append(p.toURINormalForm()); } else if (append.equals(SEPUri.APPEND_QUERY)) { XRIQuery q = qxri.getQuery(); if (q != null && q.toString().length() > 0) result.append("?" + q.toString()); } else if (append.equals(SEPUri.APPEND_QXRI)) { String qxriParam = qxri.toURINormalForm(); if (qxriParam.startsWith("xri://")) qxriParam = qxriParam.substring(6); result.append(qxriParam); } log.trace("constructURI - returning '" + result + "'"); return result.toString(); } private void constructURIinXRD(XRD finalXRD, XRI qxri) { List seps = finalXRD.getSelectedServices().getList(); // does not clone Iterator it = seps.iterator(); log.debug("constructURIinXRD()"); while (it.hasNext()) { log.debug("constructURIinXRD() got selected service"); Service sep = (Service)it.next(); List uris = sep.getURIs(); Iterator itURI = uris.iterator(); while (itURI.hasNext()) { SEPUri uri = (SEPUri)itURI.next(); String append = uri.getAppend(); if (append != null) { String r = constructURI(uri.getURI(), uri.getAppend(), qxri); try { uri.setURI(new URI(r)); uri.setAppend(null); } catch (URISyntaxException e) {} } } } for (int i = 0; i < finalXRD.getNumServices(); i++) { log.debug("constructURIinXRD() got service"); Service sep = (Service)finalXRD.getServiceAt(i); List uris = sep.getURIs(); Iterator itURI = uris.iterator(); while (itURI.hasNext()) { SEPUri uri = (SEPUri)itURI.next(); String append = uri.getAppend(); if (append != null) { String r = constructURI(uri.getURI(), uri.getAppend(), qxri); try { uri.setURI(new URI(r)); uri.setAppend(null); } catch (URISyntaxException e) {} } } } } /** * Parse the given absolute <code>qxri</code>. * @param qxri QXRI to parse * @return XRI */ private XRI parseAbsoluteQXRIOrError(String qxri) throws PartialResolutionException { try { XRI xri = new XRI(qxri); if (xri.isRelative()) { XRD err = createErrorXRD(qxri, Status.INVALID_QXRI, "QXRI is not absolute."); throw new PartialResolutionException(err); } return xri; } catch (XRIParseException e) { XRD err = createErrorXRD(qxri, Status.INVALID_QXRI, "QXRI parse error: " + e.getMessage()); throw new PartialResolutionException(err); } catch (Exception e) { XRD err = createErrorXRD(qxri, Status.PERM_FAIL, "Unexpected error while parsing input: " + e.getMessage()); throw new PartialResolutionException(err); } } protected XRI parseAbsoluteXRI(String qxri) { try { XRI xri = new XRI(qxri); if (xri.isRelative()) { log.warn("parseAbsoluteXRI - '" + qxri + "' is not absolute!"); return null; } return xri; } catch (XRIParseException e) { log.warn("parseAbsoluteXRI - failed to parse '" + qxri + "' - " + e.getMessage()); return null; } } /** * @param maxFollowRefs The maxFollowRefs to set. */ public void setMaxFollowRefs(int maxFollowRefs) { this.maxFollowRefs = maxFollowRefs; } /** * @param maxRequests The maxRequests to set. */ public void setMaxRequests(int maxRequests) { this.maxRequests = maxRequests; } /** * @param maxTotalBytes The maxTotalBytes to set. */ public void setMaxTotalBytes(int maxTotalBytes) { this.maxTotalBytes = maxTotalBytes; } /** * @param maxBytesPerRequest The maxBytesPerRequest to set. */ public void setMaxBytesPerRequest(int maxBytesPerRequest) { this.maxBytesPerRequest = maxBytesPerRequest; } /** * Queries the resolver to see if the given authority has been configured. * @param auth - authority to query * @return true if authority is configured, false otherwise. */ public bool hasAuthority(String auth) { return root.containsKey(auth); } /** * Returns the <code>XRD</code> representing the given authority. * @param auth - authority to query * @return XRD representing the authority */ public XRD getAuthority(String auth) { Object xrd = root.get(auth); return (xrd == null) ? null : (XRD) xrd; } /** * Configures the Resolver to use the given <code>XRD</code> for the authority. * @param auth - GCS or Cross Reference authority to configure * @param authXRD - XRD representing the authority */ public void setAuthority(String auth, XRD authXRD) { root.put(auth, authXRD); } /** * Configures the Resolver to bypass HTTPS for the given authorities, while satisfying the https=true requirement. */ public void addHttpsBypassAuthority(String auth) { needNoHttps.put(auth.toLowerCase(), Boolean.TRUE); } /** * Tests to see if resolving names at the given authority can bypass HTTPS while satisfying the https=true requirement. */ public bool isHttpsBypassAuthority(String auth) { if (needNoHttps.containsKey(auth.toLowerCase())) { return true; } return false; } /** * @return Returns the proxyURI. */ public URI getProxyURI() { return proxyURI; } /** * @param proxyURI The proxyURI to set. */ public void setProxyURI(URI proxyURI) { this.proxyURI = proxyURI; } } }
30.002244
169
0.685272
[ "Apache-2.0" ]
tt/dotnetxri
src/DotNetXri/Client/Resolve/Resolver.cs
66,845
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace Assembly_Planner { class consoleFrontEnd { public static string getPartsDirectory() { bool done = false; string theDir = Directory.GetCurrentDirectory(); string theInput; while (!done) { Console.Write("\n\nEnter assembly directory path (relative):"); Console.Write("\n>>"); theInput=Console.ReadLine(); try { if (directoryHasModelFiles(theInput)) { return theInput; } else { Console.Write("\n\nGiven directory does not contain valid part files"); lookForSomeModels(theInput); } } catch (Exception) { Console.Write("\n\nInvalid Path\n\n"); } } return "Impossible Return Value"; } private static bool directoryHasModelFiles(string theDirectory) { string[] files = Directory.GetFiles(theDirectory); string theExtension; int pos = 0; int lim = files.Length; while (pos < lim) { theExtension=grabExtension(files[pos]); theExtension=theExtension.ToLower(); if ( theExtension.Equals("stl") || theExtension.Equals("3mf") || theExtension.Equals("off") || theExtension.Equals("ply")) { return true; } pos++; } return false; } private static string grabExtension(string theFileName) { int pos = 0; int lim = theFileName.Length; int last=-1; while(pos < lim) { if (theFileName[pos] == '.') { last = pos; } pos++; } if(last==lim-1 || last == -1) { return ""; } else { return theFileName.Substring(last+1); } } private static void lookForSomeModels(string theDirectory) { Console.Write("\nSubdirectories containing valid parts files:\n"); bool done = false; List<string> directories=new List<string>(); directories.Add(theDirectory); List<string> directoryHolder=new List<string>(); List<string> subDirectories= new List<string>(); string holder; while(!done) { subDirectories.Clear(); foreach(string dir in directories) { directoryHolder.Clear(); directoryHolder = (Directory.GetDirectories(dir)).ToList<string>(); foreach(string subdir in directoryHolder) { subDirectories.Add(subdir); } } directories = subDirectories; if (directories.Count != 0) { foreach (string dir in directories) { Console.Write("\n" + dir); } } else { done = true; } } } } }
25.693333
95
0.417488
[ "MIT" ]
atulmishrachdi/AutomatedAssemblyPlanner
src/AutomatedAssemblyPlannerLibrary/Input/consoleFrontEnd.cs
3,856
C#
using System; using System.Collections.Generic; using Skclusive.Mobx.Observable; namespace Skclusive.Mobx.StateTree { public class ObjectTypeConfig<S, T> : IObjectTypeConfig<S, T> { public string Name { set; get; } public Func<object, object> PreProcessor { set; get; } public Func<IObservableObject<T, INode>, T> Proxify { set; get; } public Func<S> Snapshoty { set; get; } public IReadOnlyDictionary<Hook, List<Action<object[]>>> Hooks { set; get; } = new Dictionary<Hook, List<Action<object[]>>>(); public IReadOnlyCollection<Func<object, object>> Initializers { set; get; } = new List<Func<object, object>>(); public IReadOnlyCollection<IMutableProperty> Mutables { set; get; } = new List<IMutableProperty>(); public IReadOnlyCollection<IVolatileProperty> Volatiles { set; get; } = new List<IVolatileProperty>(); public IReadOnlyCollection<IViewProperty> Views { set; get; } = new List<IViewProperty>(); public IReadOnlyCollection<IActionProperty> Actions { set; get; } = new List<IActionProperty>(); } }
37.1
134
0.679245
[ "MIT" ]
BlazorHub/Skclusive.Mobx.StateTree
src/StateTree/Complex/ObjectTypeConfig.cs
1,115
C#
using UnityEngine; using System.Collections; using System.Collections.Generic; using UnityEngine.UI; using LuaInterface; namespace LuaFramework { public class PanelManager : MonoBehaviour { /// <summary> /// 所有UI的父节点 /// </summary> private Transform _parent; Transform Parent { get { if (_parent == null) { GameObject go = GameObject.Find("NguiCamera"); _parent = go.transform; Util.ClearChild(_parent); } return _parent; } } public Transform CreateLayer(int layer_order) { Transform tr = Parent.FindChild("layer_" + layer_order); if(tr == null) { GameObject go = new GameObject(); var rect = go.AddComponent<RectTransform>(); rect.anchorMax = new Vector2(1, 1); rect.anchorMin = new Vector2(0, 0); rect.offsetMin = new Vector2(0, 0); rect.offsetMax = new Vector2(0, 0); go.name = "layer_" + layer_order; go.transform.SetParent(_parent, false); var canvas = go.AddComponent<Canvas>(); canvas.overrideSorting = true; canvas.sortingOrder = layer_order; go.AddComponent<GraphicRaycaster>(); tr = rect; } return tr; } public Transform CreateNguiLayer(int layer_order) { Transform tr = Parent.FindChild("ngui_layer_" + layer_order); if (tr == null) { GameObject go = new GameObject(); var ui_panel = go.AddComponent<UIPanel>(); ui_panel.depth = layer_order; go.name = "layer_" + layer_order; go.transform.SetParent(_parent, false); tr = go.transform; } return tr; } public GameObject CreatePanelSync(int lua_id, string asset_name) { GameObject template = AppFacade.ResManager.GetRes<GameObject>(asset_name); GameObject go = GameObject.Instantiate(template) as GameObject; //go.name = asset_name; //go.layer = LayerMask.NameToLayer("Default"); go.transform.SetParent(Parent, false); LuaBehaviour behaviour = go.AddComponent<LuaBehaviour>(); behaviour.m_lua_id = lua_id; return go; } /// <summary> /// 获取预制物体,不实例化,应该是获取阈值物体吧 /// </summary> /// <param name="asset_name"></param> /// <returns></returns> public GameObject GetGameObject(string asset_name) { var go = AppFacade.ResManager.GetRes(asset_name); return go; } } }
32.847826
87
0.499007
[ "MIT" ]
treert/unity_lua_simple_framework
Assets/LuaFramework/Script/misc/PanelManager.cs
3,080
C#
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. namespace System.Web.Razor.Utils { internal static class CharUtils { internal static bool IsNonNewLineWhitespace(char c) { return Char.IsWhiteSpace(c) && !IsNewLine(c); } internal static bool IsNewLine(char c) { return c == 0x000d // Carriage return || c == 0x000a // Linefeed || c == 0x2028 // Line separator || c == 0x2029; // Paragraph separator } } }
29.571429
122
0.563607
[ "Apache-2.0" ]
Distrotech/mono
external/aspnetwebstack/src/System.Web.Razor/Utils/CharUtils.cs
623
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace TownSim.Animation { public enum Easing { Linear, EaseInQuad, EaseOutQuad, EaseInOutQuad, EaseInCubic, EaseOutCubic, EaseInOutCubic, EaseInQuart, EaseOutQuart, EaseInOutQuart, EaseInQuint, EaseOutQuint, EaseInOutQuint, EaseInSine, EaseOutSine, EaseInOutSine, EaseInExpo, EaseOutExpo, EaseInOutExpo, EaseInCirc, EaseOutCirc, EaseInOutCirc, EaseInElastic, EaseOutElastic, EaseInOutElastic, EaseInBack, EaseOutBack, EaseInOutBack, EaseInBounce, EaseOutBounce, EaseInOutBounce } public delegate void Callback(float i); public delegate float EasingFunction(float t, float start, float change, float duration); public static class Transition { public static float Linear(float t, float b, float c, float d) { return c * (t / d) + b; } public static float EaseInQuad(float t, float b, float c, float d) { return c * (t /= d) * t + b; } public static float EaseOutQuad(float t, float b, float c, float d) { return -c * (t /= d) * (t - 2) + b; } public static float EaseInOutQuad(float t, float b, float c, float d) { if ((t /= d / 2) < 1) return c / 2 * t * t + b; return -c / 2 * ((--t) * (t - 2) - 1) + b; } public static float EaseInCubic(float t, float b, float c, float d) { return c * (t /= d) * t * t + b; } public static float EaseOutCubic(float t, float b, float c, float d) { return c * ((t = t / d - 1) * t * t + 1) + b; } public static float EaseInOutCubic(float t, float b, float c, float d) { if ((t /= d / 2) < 1) return c / 2 * t * t * t + b; return c / 2 * ((t -= 2) * t * t + 2) + b; } public static float EaseInQuart(float t, float b, float c, float d) { return c * (t /= d) * t * t * t + b; } public static float EaseOutQuart(float t, float b, float c, float d) { return -c * ((t = t / d - 1) * t * t * t - 1) + b; } public static float EaseInOutQuart(float t, float b, float c, float d) { if ((t /= d / 2) < 1) return c / 2 * t * t * t * t + b; return -c / 2 * ((t -= 2) * t * t * t - 2) + b; } public static float EaseInQuint(float t, float b, float c, float d) { return c * (t /= d) * t * t * t * t + b; } public static float EaseOutQuint(float t, float b, float c, float d) { return c * ((t = t / d - 1) * t * t * t * t + 1) + b; } public static float EaseInOutQuint(float t, float b, float c, float d) { if ((t /= d / 2) < 1) return c / 2 * t * t * t * t * t + b; return c / 2 * ((t -= 2) * t * t * t * t + 2) + b; } public static float EaseInSine(float t, float b, float c, float d) { return -c * Mathf.Cos(t / d * (Mathf.PI / 2)) + c + b; } public static float EaseOutSine(float t, float b, float c, float d) { return c * Mathf.Sin(t / d * (Mathf.PI / 2)) + b; } public static float EaseInOutSine(float t, float b, float c, float d) { return -c / 2 * (Mathf.Cos(Mathf.PI * t / d) - 1) + b; } public static float EaseInExpo(float t, float b, float c, float d) { return (t <= 0) ? b : c * Mathf.Pow(2, 10 * (t / d - 1)) + b; } public static float EaseOutExpo(float t, float b, float c, float d) { return (t >= d) ? b + c : c * (-Mathf.Pow(2, -10 * t / d) + 1) + b; } public static float EaseInOutExpo(float t, float b, float c, float d) { if (t <= 0) return b; if (t >= d) return b + c; if ((t /= d / 2) < 1) return c / 2 * Mathf.Pow(2, 10 * (t - 1)) + b; return c / 2 * (-Mathf.Pow(2, -10 * --t) + 2) + b; } public static float EaseInCirc(float t, float b, float c, float d) { return -c * (Mathf.Sqrt(1 - (t /= d) * t) - 1) + b; } public static float EaseOutCirc(float t, float b, float c, float d) { return c * Mathf.Sqrt(1 - (t = t / d - 1) * t) + b; } public static float EaseInOutCirc(float t, float b, float c, float d) { if ((t /= d / 2) < 1) return -c / 2 * (Mathf.Sqrt(1 - t * t) - 1) + b; return c / 2 * (Mathf.Sqrt(1 - (t -= 2) * t) + 1) + b; } public static float EaseInElastic(float t, float b, float c, float d) { if (t <= 0) return b; if ((t /= d) >= 1) return b + c; float p = d * .3f; float a = c; float s = a < Mathf.Abs(c) ? (p / 4) : (p / (2 * Mathf.PI) * Mathf.Asin(c / a)); return -(a * Mathf.Pow(2, 10 * (t -= 1)) * Mathf.Sin((t * d - s) * (2 * Mathf.PI) / p)) + b; } public static float EaseOutElastic(float t, float b, float c, float d) { if (t <= 0) return b; if ((t /= d) >= 1) return b + c; float p = d * .3f; float a = c; float s = a < Mathf.Abs(c) ? (p / 4) : (p / (2 * Mathf.PI) * Mathf.Asin(c / a)); return a * Mathf.Pow(2, -10 * t) * Mathf.Sin((t * d - s) * (2 * Mathf.PI) / p) + c + b; } public static float EaseInOutElastic(float t, float b, float c, float d) { if (t <= 0) return b; if ((t /= d / 2) >= 2) return b + c; float p = d * (.3f * 1.5f); float a = c; float s = a < Mathf.Abs(c) ? (p / 4) : (p / (2 * Mathf.PI) * Mathf.Asin(c / a)); if (t < 1) return -.5f * (a * Mathf.Pow(2, 10 * (t -= 1)) * Mathf.Sin((t * d - s) * (2 * Mathf.PI) / p)) + b; return a * Mathf.Pow(2, -10 * (t -= 1)) * Mathf.Sin((t * d - s) * (2 * Mathf.PI) / p) * .5f + c + b; } public static float EaseInBack(float t, float b, float c, float d) { float s = 1.70158f; return c * (t /= d) * t * ((s + 1) * t - s) + b; } public static float EaseOutBack(float t, float b, float c, float d) { float s = 1.70158f; return c * ((t = t / d - 1) * t * ((s + 1) * t + s) + 1) + b; } public static float EaseInOutBack(float t, float b, float c, float d) { float s = 1.70158f; if ((t /= d / 2) < 1) return c / 2 * (t * t * (((s *= (1.525f)) + 1) * t - s)) + b; return c / 2 * ((t -= 2) * t * (((s *= (1.525f)) + 1) * t + s) + 2) + b; } public static float EaseInBounce(float t, float b, float c, float d) { return c - EaseOutBounce(d - t, 0, c, d) + b; } public static float EaseOutBounce(float t, float b, float c, float d) { if ((t /= d) < (1 / 2.75f)) { return c * (7.5625f * t * t) + b; } else if (t < (2 / 2.75f)) { return c * (7.5625f * (t -= (1.5f / 2.75f)) * t + .75f) + b; } else if (t < (2.5 / 2.75)) { return c * (7.5625f * (t -= (2.25f / 2.75f)) * t + .9375f) + b; } else { return c * (7.5625f * (t -= (2.625f / 2.75f)) * t + .984375f) + b; } } public static float EaseInOutBounce(float t, float b, float c, float d) { if (t < d / 2) return EaseInBounce(t * 2, 0, c, d) * .5f + b; return EaseOutBounce(t * 2 - d, 0, c, d) * .5f + c * .5f + b; } public static EasingFunction Function(Easing easing) { switch (easing) { case Easing.Linear: return Linear; case Easing.EaseInQuad: return EaseInQuad; case Easing.EaseOutQuad: return EaseOutQuad; case Easing.EaseInOutQuad: return EaseInOutQuad; case Easing.EaseInCubic: return EaseInCubic; case Easing.EaseOutCubic: return EaseOutCubic; case Easing.EaseInOutCubic: return EaseInOutCubic; case Easing.EaseInQuart: return EaseInQuart; case Easing.EaseOutQuart: return EaseOutQuart; case Easing.EaseInOutQuart: return EaseInOutQuart; case Easing.EaseInQuint: return EaseInQuint; case Easing.EaseOutQuint: return EaseOutQuint; case Easing.EaseInOutQuint: return EaseInOutQuint; case Easing.EaseInSine: return EaseInSine; case Easing.EaseOutSine: return EaseOutSine; case Easing.EaseInOutSine: return EaseInOutSine; case Easing.EaseInExpo: return EaseInExpo; case Easing.EaseOutExpo: return EaseOutExpo; case Easing.EaseInOutExpo: return EaseInOutExpo; case Easing.EaseInCirc: return EaseInCirc; case Easing.EaseOutCirc: return EaseOutCirc; case Easing.EaseInOutCirc: return EaseInOutCirc; case Easing.EaseInElastic: return EaseInElastic; case Easing.EaseOutElastic: return EaseOutElastic; case Easing.EaseInOutElastic: return EaseInOutElastic; case Easing.EaseInBack: return EaseInBack; case Easing.EaseOutBack: return EaseOutBack; case Easing.EaseInOutBack: return EaseInOutBack; case Easing.EaseInBounce: return EaseInBounce; case Easing.EaseOutBounce: return EaseOutBounce; case Easing.EaseInOutBounce: return EaseInOutBounce; default: return Linear; } } public static float Value(float t, float start, float change, float duration, Easing easing) { return Function(easing)(t, start, change, duration); } public static IEnumerator AnimateEasing(float start, float change, float duration, Easing easing, Callback callback, bool useUnscaledDeltaTime) { return AnimateEasing(start, change, duration, Function(easing), callback, useUnscaledDeltaTime); } public static IEnumerator AnimateEasing(float start, float change, float duration, EasingFunction easing, Callback callback, bool useUnscaledDeltaTime) { for (float t = 0; t < duration; t += useUnscaledDeltaTime ? Time.unscaledDeltaTime : Time.deltaTime) { callback(easing(t, start, change, duration)); yield return null; } callback(easing(duration, start, change, duration)); } public static IEnumerator AnimateCurve(float start, float change, float duration, AnimationCurve easing, Callback callback, bool useUnscaledDeltaTime) { for (float t = 0; t < duration; t += useUnscaledDeltaTime ? Time.unscaledDeltaTime : Time.deltaTime) { callback(start + easing.Evaluate(t / duration) * change); yield return null; } callback(start + easing.Evaluate(1) * change); } public delegate void Set<T>(T x); public static IEnumerator AnimateFloat(float start, float target, Set<float> setter, float duration, Easing easing, bool useUnscaledDeltaTime) { return AnimateFloat(start, target, setter, duration, Function(easing), useUnscaledDeltaTime); } public static IEnumerator AnimateFloat(float start, float target, Set<float> setter, float duration, EasingFunction easing, bool useUnscaledDeltaTime) { float change = target - start; for (float t = 0; t < duration; t += useUnscaledDeltaTime ? Time.unscaledDeltaTime : Time.deltaTime) { setter(easing(t, start, change, duration)); yield return null; } setter(easing(duration, start, change, duration)); } public static IEnumerator AnimateFloat(float start, float target, Set<float> setter, float duration, AnimationCurve easing, bool useUnscaledDeltaTime) { float change = target - start; for (float t = 0; t < duration; t += useUnscaledDeltaTime ? Time.unscaledDeltaTime : Time.deltaTime) { setter(start + easing.Evaluate(t / duration) * change); yield return null; } setter(start + easing.Evaluate(1) * change); } public static IEnumerator AnimateVector3(Vector3 start, Vector3 target, Set<Vector3> setter, float duration, Easing easing, bool useUnscaledDeltaTime) { return AnimateVector3(start, target, setter, duration, Function(easing), useUnscaledDeltaTime); } public static IEnumerator AnimateVector3(Vector3 start, Vector3 target, Set<Vector3> setter, float duration, EasingFunction easing, bool useUnscaledDeltaTime) { Vector3 delta = target - start; for (float t = 0; t < duration; t += useUnscaledDeltaTime ? Time.unscaledDeltaTime : Time.deltaTime) { setter(start + easing(t, 0, 1, duration) * delta); yield return null; } setter(start + easing(duration, 0, 1, duration) * delta); } public static IEnumerator AnimateVector3(Vector3 start, Vector3 target, Set<Vector3> setter, float duration, AnimationCurve easing, bool useUnscaledDeltaTime) { Vector3 delta = target - start; for (float t = 0; t < duration; t += useUnscaledDeltaTime ? Time.unscaledDeltaTime : Time.deltaTime) { setter(start + easing.Evaluate(t / duration) * delta); yield return null; } setter(start + easing.Evaluate(1) * delta); } public static IEnumerator AnimateRotation(Quaternion start, Quaternion target, Set<Quaternion> setter, float duration, Easing easing, bool useUnscaledDeltaTime) { return AnimateRotation(start, target, setter, duration, Function(easing), useUnscaledDeltaTime); } public static IEnumerator AnimateRotation(Quaternion start, Quaternion target, Set<Quaternion> setter, float duration, EasingFunction easing, bool useUnscaledDeltaTime) { for (float t = 0; t < duration; t += useUnscaledDeltaTime ? Time.unscaledDeltaTime : Time.deltaTime) { setter(Quaternion.LerpUnclamped(start, target, easing(t, 0, 1, duration))); yield return null; } setter(target); } public static IEnumerator AnimateRotation(Quaternion start, Quaternion target, Set<Quaternion> setter, float duration, AnimationCurve easing, bool useUnscaledDeltaTime) { for (float t = 0; t < duration; t += useUnscaledDeltaTime ? Time.unscaledDeltaTime : Time.deltaTime) { setter(Quaternion.LerpUnclamped(start, target, easing.Evaluate(t / duration))); yield return null; } setter(target); } public static IEnumerator AnimatePosition(this Transform transform, Vector3 target, float duration, AnimationCurve easing, bool useUnscaledDeltaTime) { return AnimateVector3(transform.position, target, (Vector3 p) => transform.position = p, duration, easing, useUnscaledDeltaTime); } public static IEnumerator AnimatePosition(this Transform transform, Vector3 target, float duration, EasingFunction easing, bool useUnscaledDeltaTime) { return AnimateVector3(transform.position, target, (Vector3 p) => transform.position = p, duration, easing, useUnscaledDeltaTime); } public static IEnumerator AnimatePosition(this Transform transform, Vector3 target, float duration, Easing easing, bool useUnscaledDeltaTime) { return AnimateVector3(transform.position, target, (Vector3 p) => transform.position = p, duration, easing, useUnscaledDeltaTime); } public static IEnumerator AnimateLocalPosition(this Transform transform, Vector3 target, float duration, AnimationCurve easing, bool useUnscaledDeltaTime) { return AnimateVector3(transform.localPosition, target, (Vector3 p) => transform.localPosition = p, duration, easing, useUnscaledDeltaTime); } public static IEnumerator AnimateLocalPosition(this Transform transform, Vector3 target, float duration, EasingFunction easing, bool useUnscaledDeltaTime) { return AnimateVector3(transform.localPosition, target, (Vector3 p) => transform.localPosition = p, duration, easing, useUnscaledDeltaTime); } public static IEnumerator AnimateLocalPosition(this Transform transform, Vector3 target, float duration, Easing easing, bool useUnscaledDeltaTime) { return AnimateVector3(transform.localPosition, target, (Vector3 p) => transform.localPosition = p, duration, easing, useUnscaledDeltaTime); } public static IEnumerator AnimateLocalScale(this Transform transform, Vector3 target, float duration, AnimationCurve easing, bool useUnscaledDeltaTime) { return AnimateVector3(transform.localScale, target, (Vector3 p) => transform.localScale = p, duration, easing, useUnscaledDeltaTime); } public static IEnumerator AnimateLocalScale(this Transform transform, Vector3 target, float duration, EasingFunction easing, bool useUnscaledDeltaTime) { return AnimateVector3(transform.localScale, target, (Vector3 p) => transform.localScale = p, duration, easing, useUnscaledDeltaTime); } public static IEnumerator AnimateLocalScale(this Transform transform, Vector3 target, float duration, Easing easing, bool useUnscaledDeltaTime) { return AnimateVector3(transform.localScale, target, (Vector3 p) => transform.localScale = p, duration, easing, useUnscaledDeltaTime); } public static IEnumerator AnimateLocalRotation(this Transform transform, Vector3 target, float duration, AnimationCurve easing, bool useUnscaledDeltaTime) { return AnimateRotation(transform.localRotation, Quaternion.Euler(target), (Quaternion q) => transform.localRotation = q, duration, easing, useUnscaledDeltaTime); } public static IEnumerator AnimateLocalRotation(this Transform transform, Vector3 target, float duration, EasingFunction easing, bool useUnscaledDeltaTime) { return AnimateRotation(transform.localRotation, Quaternion.Euler(target), (Quaternion q) => transform.localRotation = q, duration, easing, useUnscaledDeltaTime); } public static IEnumerator AnimateLocalRotation(this Transform transform, Vector3 target, float duration, Easing easing, bool useUnscaledDeltaTime) { return AnimateRotation(transform.localRotation, Quaternion.Euler(target), (Quaternion q) => transform.localRotation = q, duration, easing, useUnscaledDeltaTime); } public static IEnumerator AnimateLocalRotation(this Transform transform, Quaternion target, float duration, AnimationCurve easing, bool useUnscaledDeltaTime) { return AnimateRotation(transform.localRotation, target, (Quaternion q) => transform.localRotation = q, duration, easing, useUnscaledDeltaTime); } public static IEnumerator AnimateLocalRotation(this Transform transform, Quaternion target, float duration, EasingFunction easing, bool useUnscaledDeltaTime) { return AnimateRotation(transform.localRotation, target, (Quaternion q) => transform.localRotation = q, duration, easing, useUnscaledDeltaTime); } public static IEnumerator AnimateLocalRotation(this Transform transform, Quaternion target, float duration, Easing easing, bool useUnscaledDeltaTime) { return AnimateRotation(transform.localRotation, target, (Quaternion q) => transform.localRotation = q, duration, easing, useUnscaledDeltaTime); } public static IEnumerator AnimateRotation(this Transform transform, Vector3 target, float duration, AnimationCurve easing, bool useUnscaledDeltaTime) { return AnimateRotation(transform.rotation, Quaternion.Euler(target), (Quaternion q) => transform.rotation = q, duration, easing, useUnscaledDeltaTime); } public static IEnumerator AnimateRotation(this Transform transform, Vector3 target, float duration, EasingFunction easing, bool useUnscaledDeltaTime) { return AnimateRotation(transform.rotation, Quaternion.Euler(target), (Quaternion q) => transform.rotation = q, duration, easing, useUnscaledDeltaTime); } public static IEnumerator AnimateRotation(this Transform transform, Vector3 target, float duration, Easing easing, bool useUnscaledDeltaTime) { return AnimateRotation(transform.rotation, Quaternion.Euler(target), (Quaternion q) => transform.rotation = q, duration, easing, useUnscaledDeltaTime); } public static IEnumerator AnimateRotation(this Transform transform, Quaternion target, float duration, AnimationCurve easing, bool useUnscaledDeltaTime) { return AnimateRotation(transform.rotation, target, (Quaternion q) => transform.rotation = q, duration, easing, useUnscaledDeltaTime); } public static IEnumerator AnimateRotation(this Transform transform, Quaternion target, float duration, EasingFunction easing, bool useUnscaledDeltaTime) { return AnimateRotation(transform.rotation, target, (Quaternion q) => transform.rotation = q, duration, easing, useUnscaledDeltaTime); } public static IEnumerator AnimateRotation(this Transform transform, Quaternion target, float duration, Easing easing, bool useUnscaledDeltaTime) { return AnimateRotation(transform.rotation, target, (Quaternion q) => transform.rotation = q, duration, easing, useUnscaledDeltaTime); } } }
47.47561
176
0.57522
[ "MIT" ]
danzabarr/TownSim
Assets/Easings/Transition.cs
23,360
C#
namespace SharpDebug.Engine { /// <summary> /// All constants used in the project /// </summary> internal class Constants { /// <summary> /// The maximum length of file name /// </summary> public const int MaxFileName = 65536; /// <summary> /// The maximum length of symbol name /// </summary> public const int MaxSymbolName = 4096; /// <summary> /// The maximum base type identifier /// </summary> public const uint MaxBaseTypeId = 2000000000; /// <summary> /// The maximum length of string to be read /// </summary> public const uint MaxStringReadLength = 10240; } }
25
54
0.547586
[ "MIT" ]
sdmaclea/SharpDebug
Source/SharpDebug.Engine/Engine/Constants.cs
727
C#
/* * Created by SharpDevelop. * Date: 10.10.2017 * Time: 22:13 * */ using System.Windows.Controls; namespace RFiDGear.View { /// <summary> /// Interaction logic for TabPageMifareDesfireDataExplorerView.xaml /// </summary> public partial class TabPageMifareDesfireDataExplorerView : UserControl { public TabPageMifareDesfireDataExplorerView() { InitializeComponent(); } } }
20
75
0.652273
[ "MIT" ]
c3rebro/RFiDGear
RFiDGear/View/TaskViews/RFIDTasks/MifareDesfireTask/MifareDesfireTaskTabPages/TabPageMifareDesfireDataExplorerView.xaml.cs
442
C#
using Microsoft.Extensions.DependencyInjection; using System; using System.Linq; using System.Reflection; namespace Creekdream.Dependency { /// <summary> /// Used to convert registration abstract classes /// </summary> public abstract class ConventionalRegistrarBase : IConventionalRegistrar { /// <inheritdoc /> public virtual void AddAssembly(IServiceCollection services, Assembly assembly) { var types = assembly.GetTypes() .Where( type => type != null && type.IsClass && !type.IsAbstract && !type.IsGenericType ).ToArray(); AddTypes(services, types); } /// <inheritdoc /> public virtual void AddTypes(IServiceCollection services, params Type[] types) { foreach (var type in types) { AddType(services, type); } } /// <inheritdoc /> public abstract void AddType(IServiceCollection services, Type type); } }
28.25
87
0.544248
[ "MIT" ]
zengqinglei/Creekdream.AspNetCore
src/Creekdream.Core/Dependency/Conventionals/ConventionalRegistrarBase.cs
1,132
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.ContainerService.V20201201.Outputs { [OutputType] public sealed class ManagedClusterIdentityResponse { /// <summary> /// The principal id of the system assigned identity which is used by master components. /// </summary> public readonly string PrincipalId; /// <summary> /// The tenant id of the system assigned identity which is used by master components. /// </summary> public readonly string TenantId; /// <summary> /// The type of identity used for the managed cluster. Type 'SystemAssigned' will use an implicitly created identity in master components and an auto-created user assigned identity in MC_ resource group in agent nodes. Type 'None' will not use MSI for the managed cluster, service principal will be used instead. /// </summary> public readonly string? Type; /// <summary> /// The user identity associated with the managed cluster. This identity will be used in control plane and only one user assigned identity is allowed. The user identity dictionary key references will be ARM resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'. /// </summary> public readonly ImmutableDictionary<string, Outputs.ManagedClusterIdentityResponseUserAssignedIdentities>? UserAssignedIdentities; [OutputConstructor] private ManagedClusterIdentityResponse( string principalId, string tenantId, string? type, ImmutableDictionary<string, Outputs.ManagedClusterIdentityResponseUserAssignedIdentities>? userAssignedIdentities) { PrincipalId = principalId; TenantId = tenantId; Type = type; UserAssignedIdentities = userAssignedIdentities; } } }
45.28
384
0.70318
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/ContainerService/V20201201/Outputs/ManagedClusterIdentityResponse.cs
2,264
C#
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ using System; using JavaScriptEngineSwitcher.ChakraCore; using JavaScriptEngineSwitcher.Core; namespace React.Sample.ConsoleApp { class Program { static void Main(string[] args) { Initialize(); ReactSiteConfiguration.Configuration .SetReuseJavaScriptEngines(false) .AddScript("Sample.jsx"); JsEngineSwitcher.Current.DefaultEngineName = ChakraCoreJsEngine.EngineName; JsEngineSwitcher.Current.EngineFactories.AddChakraCore(); var environment = ReactEnvironment.Current; var component = environment.CreateComponent("HelloWorld", new { name = "Daniel" }); // renderServerOnly omits the data-reactid attributes var html = component.RenderHtml(renderServerOnly: true); Console.WriteLine(html); Console.ReadKey(); } private static void Initialize() { Initializer.Initialize(registration => registration.AsSingleton()); var container = React.AssemblyRegistration.Container; // Register some components that are normally provided by the integration library // (eg. React.AspNet or React.Web.Mvc4) container.Register<ICache, NullCache>(); container.Register<IFileSystem, SimpleFileSystem>(); } } }
28.829787
86
0.751292
[ "MIT" ]
AlaminJust/React.NET
src/React.Sample.ConsoleApp/Program.cs
1,355
C#
namespace SmartConnect.Web.Controllers.Contracts { using System.Web.Mvc; using Common.Constants; using Data.Models; using Services.Common.Contracts; [Authorize(Roles = Roles.Admin)] public abstract class BaseAjaxAdministrationController : BaseAjaxController { public BaseAjaxAdministrationController(IDataService<User, string> users) : base(users) { } } }
23.777778
82
0.679907
[ "MIT" ]
vassildinev/Smart-Connect
Source/Web/SmartConnect.Web.Controllers/Contracts/BaseAjaxAdministrationController.cs
430
C#
using System; namespace Alex.Utils { public class MapColor { public static MapColor[] COLORS = new MapColor[64]; public static MapColor[] BLOCK_COLORS = new MapColor[16]; public static MapColor AIR = new MapColor(0, 0); public static MapColor GRASS = new MapColor(1, 8368696); public static MapColor SAND = new MapColor(2, 16247203); public static MapColor CLOTH = new MapColor(3, 13092807); public static MapColor TNT = new MapColor(4, 16711680); public static MapColor ICE = new MapColor(5, 10526975); public static MapColor IRON = new MapColor(6, 10987431); public static MapColor FOLIAGE = new MapColor(7, 31744); public static MapColor SNOW = new MapColor(8, 16777215); public static MapColor CLAY = new MapColor(9, 10791096); public static MapColor DIRT = new MapColor(10, 9923917); public static MapColor STONE = new MapColor(11, 7368816); public static MapColor WATER = new MapColor(12, 4210943); public static MapColor WOOD = new MapColor(13, 9402184); public static MapColor QUARTZ = new MapColor(14, 16776437); public static MapColor ADOBE = new MapColor(15, 14188339); public static MapColor MAGENTA = new MapColor(16, 11685080); public static MapColor LIGHT_BLUE = new MapColor(17, 6724056); public static MapColor YELLOW = new MapColor(18, 15066419); public static MapColor LIME = new MapColor(19, 8375321); public static MapColor PINK = new MapColor(20, 15892389); public static MapColor GRAY = new MapColor(21, 5000268); public static MapColor SILVER = new MapColor(22, 10066329); public static MapColor CYAN = new MapColor(23, 5013401); public static MapColor PURPLE = new MapColor(24, 8339378); public static MapColor BLUE = new MapColor(25, 3361970); public static MapColor BROWN = new MapColor(26, 6704179); public static MapColor GREEN = new MapColor(27, 6717235); public static MapColor RED = new MapColor(28, 10040115); public static MapColor BLACK = new MapColor(29, 1644825); public static MapColor GOLD = new MapColor(30, 16445005); public static MapColor DIAMOND = new MapColor(31, 6085589); public static MapColor LAPIS = new MapColor(32, 4882687); public static MapColor EMERALD = new MapColor(33, 55610); public static MapColor OBSIDIAN = new MapColor(34, 8476209); public static MapColor NETHERRACK = new MapColor(35, 7340544); public static MapColor WHITE_STAINED_HARDENED_CLAY = new MapColor(36, 13742497); public static MapColor ORANGE_STAINED_HARDENED_CLAY = new MapColor(37, 10441252); public static MapColor MAGENTA_STAINED_HARDENED_CLAY = new MapColor(38, 9787244); public static MapColor LIGHT_BLUE_STAINED_HARDENED_CLAY = new MapColor(39, 7367818); public static MapColor YELLOW_STAINED_HARDENED_CLAY = new MapColor(40, 12223780); public static MapColor LIME_STAINED_HARDENED_CLAY = new MapColor(41, 6780213); public static MapColor PINK_STAINED_HARDENED_CLAY = new MapColor(42, 10505550); public static MapColor GRAY_STAINED_HARDENED_CLAY = new MapColor(43, 3746083); public static MapColor SILVER_STAINED_HARDENED_CLAY = new MapColor(44, 8874850); public static MapColor CYAN_STAINED_HARDENED_CLAY = new MapColor(45, 5725276); public static MapColor PURPLE_STAINED_HARDENED_CLAY = new MapColor(46, 8014168); public static MapColor BLUE_STAINED_HARDENED_CLAY = new MapColor(47, 4996700); public static MapColor BROWN_STAINED_HARDENED_CLAY = new MapColor(48, 4993571); public static MapColor GREEN_STAINED_HARDENED_CLAY = new MapColor(49, 5001770); public static MapColor RED_STAINED_HARDENED_CLAY = new MapColor(50, 9321518); public static MapColor BLACK_STAINED_HARDENED_CLAY = new MapColor(51, 2430480); public int colorValue; public int colorIndex; private MapColor(int index, int color) { if (index >= 0 && index <= 63) { this.colorIndex = index; this.colorValue = color; COLORS[index] = this; } else { throw new IndexOutOfRangeException("Map colour ID must be between 0 and 63 (inclusive)"); } } public int GetMapColor(int index) { int i = 220; if (index == 3) { i = 135; } if (index == 2) { i = 255; } if (index == 1) { i = 220; } if (index == 0) { i = 180; } int j = (this.colorValue >> 16 & 255) * i / 255; int k = (this.colorValue >> 8 & 255) * i / 255; int l = (this.colorValue & 255) * i / 255; return -16777216 | j << 16 | k << 8 | l; } } }
40.651376
93
0.727827
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
TruDan/Alex
src/Alex/Utils/MapColor.cs
4,433
C#
using System; using ENode.Commanding; using Eventual2PC.Commands; namespace ENode.Eventual2PC.Commands { /// <summary> /// 事务参与方提交命令 /// </summary> [Serializable] public abstract class TransactionParticipantCommitCommandBase<TAggregateRootId> : Command<TAggregateRootId>, ITransactionParticipantCommitCommand { /// <summary> /// 事务参与方提交命令 /// </summary> public TransactionParticipantCommitCommandBase() : base() { } /// <summary> /// 事务参与方提交命令 /// </summary> /// <param name="aggregateRootId">聚合根ID</param> /// <param name="transactionId">事务ID</param> public TransactionParticipantCommitCommandBase(TAggregateRootId aggregateRootId, string transactionId) : base(aggregateRootId) { TransactionId = transactionId; } /// <summary> /// 事务ID /// </summary> public string TransactionId { get; set; } } }
27.243243
110
0.600198
[ "MIT" ]
berkaroad/ENode.Eventual2PC
src/ENode.Eventual2PC/Commands/TransactionParticipantCommitCommandBase.cs
1,076
C#
using System; using System.Collections.Generic; using System.Text; namespace ECO.Rainbow_Connection { class Hap { } }
12
33
0.704545
[ "Unlicense" ]
The-Somerton-Star/Consonance
ECO/Rainbow Connection/Hap.cs
134
C#
using SpaceService.Database.Entities; using System; using System.Collections.Generic; using Common.Interfaces; using SpaceService.Filters; namespace SpaceService.Repository.Interfaces { public interface ISpaceRepository : IGet<Guid, DbSpace>, IFindAll<SpaceFilter, IEnumerable<DbSpace>>, IUpdate<DbSpace, DbSpace>, ICreate<DbSpace, DbSpace>, IDelete<DbSpace> { } }
21.833333
48
0.75827
[ "MIT" ]
lanit-office-map/OfficeMap
OfficeMapApi/SpaceService/SpaceService/Repository/Interfaces/ISpaceRepository.cs
395
C#
// ----------------------------------------------------------------------- // <copyright file="LogonType.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // ----------------------------------------------------------------------- namespace Microsoft.Partner.SmartOffice.Models.Graph { using Newtonsoft.Json; [JsonConverter(typeof(EnumConverter))] public enum LogonType { Unknown = 0, Interactive = 1, RemoteInteractive = 2, Network = 3, Batch = 4, Service = 5, UnknownFutureValue = 127 } }
28.363636
75
0.471154
[ "MIT" ]
CypBnk/PSO-Mod
src/SmartOffice.Models/Graph/LogonType.cs
626
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the voice-id-2021-09-27.normal.json service model. */ using System; using Amazon.Runtime; using Amazon.Util.Internal; namespace Amazon.VoiceID { /// <summary> /// Configuration for accessing Amazon VoiceID service /// </summary> public partial class AmazonVoiceIDConfig : ClientConfig { private static readonly string UserAgentString = InternalSDKUtils.BuildUserAgentString("3.7.0.10"); private string _userAgent = UserAgentString; /// <summary> /// Default constructor /// </summary> public AmazonVoiceIDConfig() { this.AuthenticationServiceName = "voiceid"; } /// <summary> /// The constant used to lookup in the region hash the endpoint. /// </summary> public override string RegionEndpointServiceName { get { return "voiceid"; } } /// <summary> /// Gets the ServiceVersion property. /// </summary> public override string ServiceVersion { get { return "2021-09-27"; } } /// <summary> /// Gets the value of UserAgent property. /// </summary> public override string UserAgent { get { return _userAgent; } } } }
25.9
106
0.583977
[ "Apache-2.0" ]
bgrainger/aws-sdk-net
sdk/src/Services/VoiceID/Generated/AmazonVoiceIDConfig.cs
2,072
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; namespace MoLIC_WOz_Web.Account { public partial class Register : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { RegisterUser.ContinueDestinationPageUrl = Request.QueryString["ReturnUrl"]; } protected void RegisterUser_CreatedUser(object sender, EventArgs e) { FormsAuthentication.SetAuthCookie(RegisterUser.UserName, false /* createPersistentCookie */); string continueUrl = RegisterUser.ContinueDestinationPageUrl; if (String.IsNullOrEmpty(continueUrl)) { continueUrl = "~/"; } Response.Redirect(continueUrl); } } }
26.636364
105
0.65529
[ "MIT" ]
gustavomirandag/MoLIC_WOz
MoLIC_WOz_Web/Account/Register.aspx.cs
881
C#
// *** WARNING: this file was generated by pulumigen. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Kubernetes.Types.Outputs.Core.V1 { /// <summary> /// ObjectFieldSelector selects an APIVersioned field of an object. /// </summary> [OutputType] public sealed class ObjectFieldSelector { /// <summary> /// Version of the schema the FieldPath is written in terms of, defaults to "v1". /// </summary> public readonly string ApiVersion; /// <summary> /// Path of the field to select in the specified API version. /// </summary> public readonly string FieldPath; [OutputConstructor] private ObjectFieldSelector( string apiVersion, string fieldPath) { ApiVersion = apiVersion; FieldPath = fieldPath; } } }
27.589744
89
0.628253
[ "Apache-2.0" ]
AaronFriel/pulumi-kubernetes
sdk/dotnet/Core/V1/Outputs/ObjectFieldSelector.cs
1,076
C#
using System; using System.Drawing; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; using CKAN.Extensions; using CKAN.Versioning; namespace CKAN { public partial class ChooseRecommendedMods : UserControl { public ChooseRecommendedMods() { InitializeComponent(); } public void LoadRecommendations( IRegistryQuerier registry, HashSet<CkanModule> toInstall, HashSet<CkanModule> toUninstall, GameVersionCriteria GameVersion, NetModuleCache cache, Dictionary<CkanModule, Tuple<bool, List<string>>> recommendations, Dictionary<CkanModule, List<string>> suggestions, Dictionary<CkanModule, HashSet<string>> supporters ) { this.registry = registry; this.toInstall = toInstall; this.toUninstall = toUninstall; this.GameVersion = GameVersion; Util.Invoke(this, () => { RecommendedModsToggleCheckbox.Checked = true; RecommendedModsListView.Items.AddRange( getRecSugRows(cache, recommendations, suggestions, supporters).ToArray()); MarkConflicts(); }); } public HashSet<CkanModule> Wait() { if (Platform.IsMono) { // Workaround: make sure the ListView headers are drawn Util.Invoke(this, () => RecommendedModsListView.EndUpdate()); } task = new TaskCompletionSource<HashSet<CkanModule>>(); return task.Task.Result; } public ListView.SelectedListViewItemCollection SelectedItems { get { return RecommendedModsListView.SelectedItems; } } public event Action<ListView.SelectedListViewItemCollection> OnSelectedItemsChanged; public event Action<string> OnConflictFound; private void RecommendedModsListView_SelectedIndexChanged(object sender, EventArgs e) { if (OnSelectedItemsChanged != null) { OnSelectedItemsChanged(RecommendedModsListView.SelectedItems); } } private void RecommendedModsListView_ItemChecked(object sender, ItemCheckedEventArgs e) { var module = e.Item.Tag as CkanModule; if (module?.IsDLC ?? false) { if (e.Item.Checked) { e.Item.Checked = false; } } else { MarkConflicts(); } } private void MarkConflicts() { try { var conflicts = FindConflicts(); foreach (var item in RecommendedModsListView.Items.Cast<ListViewItem>() // Apparently ListView handes AddRange by: // 1. Expanding the Items list to the new size by filling it with nulls // 2. One by one, replace each null with a real item and call _ItemChecked // ... so the Items list can contain null!! .Where(it => it != null)) { item.BackColor = conflicts.ContainsKey(item.Tag as CkanModule) ? Color.LightCoral : Color.Empty; } RecommendedModsContinueButton.Enabled = !conflicts.Any(); if (OnConflictFound != null) { OnConflictFound(conflicts.Any() ? conflicts.First().Value : ""); } } catch (DependencyNotSatisfiedKraken k) { var row = RecommendedModsListView.Items.Cast<ListViewItem>() .FirstOrDefault(it => (it?.Tag as CkanModule) == k.parent); if (row != null) { row.BackColor = Color.LightCoral; } RecommendedModsContinueButton.Enabled = false; OnConflictFound?.Invoke(k.Message); } } private static readonly RelationshipResolverOptions conflictOptions = new RelationshipResolverOptions() { without_toomanyprovides_kraken = true, proceed_with_inconsistencies = true, without_enforce_consistency = true, with_recommends = false }; private Dictionary<CkanModule, String> FindConflicts() { return new RelationshipResolver( RecommendedModsListView.CheckedItems.Cast<ListViewItem>() .Select(item => item.Tag as CkanModule) .Concat(toInstall) .Distinct(), toUninstall, conflictOptions, registry, GameVersion ).ConflictList; } private IEnumerable<ListViewItem> getRecSugRows( NetModuleCache cache, Dictionary<CkanModule, Tuple<bool, List<string>>> recommendations, Dictionary<CkanModule, List<string>> suggestions, Dictionary<CkanModule, HashSet<string>> supporters ) { foreach (var kvp in recommendations) { yield return getRecSugItem(cache, kvp.Key, string.Join(", ", kvp.Value.Item2), RecommendationsGroup, kvp.Value.Item1); } foreach (var kvp in suggestions) { yield return getRecSugItem(cache, kvp.Key, string.Join(", ", kvp.Value), SuggestionsGroup, false); } foreach (var kvp in supporters .ToDictionary(kvp => kvp.Key, kvp => string.Join(", ", kvp.Value.OrderBy(s => s))) .OrderBy(kvp => kvp.Value) ) { yield return getRecSugItem(cache, kvp.Key, string.Join(", ", kvp.Value), SupportedByGroup, false); } } private ListViewItem getRecSugItem(NetModuleCache cache, CkanModule module, string descrip, ListViewGroup group, bool check) { return new ListViewItem(new string[] { module.IsDLC ? module.name : cache.IsMaybeCachedZip(module) ? string.Format(Properties.Resources.MainChangesetCached, module.name, module.version) : string.Format(Properties.Resources.MainChangesetHostSize, module.name, module.version, module.download?.Host ?? "", CkanModule.FmtSize(module.download_size)), descrip, module.@abstract }) { Tag = module, Checked = check, Group = group }; } private void RecommendedModsToggleCheckbox_CheckedChanged(object sender, EventArgs e) { var state = ((CheckBox)sender).Checked; RecommendedModsListView.BeginUpdate(); foreach (ListViewItem item in RecommendedModsListView.Items) { if (item.Checked != state) item.Checked = state; } RecommendedModsListView.EndUpdate(); } private void RecommendedModsCancelButton_Click(object sender, EventArgs e) { task?.SetResult(null); RecommendedModsListView.Items.Clear(); } private void RecommendedModsContinueButton_Click(object sender, EventArgs e) { task?.SetResult( RecommendedModsListView.CheckedItems.Cast<ListViewItem>() .Select(item => item.Tag as CkanModule) .ToHashSet() ); RecommendedModsListView.Items.Clear(); } private IRegistryQuerier registry; private HashSet<CkanModule> toInstall; private HashSet<CkanModule> toUninstall; private GameVersionCriteria GameVersion; private TaskCompletionSource<HashSet<CkanModule>> task; } }
36.561947
184
0.547622
[ "MIT" ]
050644zf/CKAN
GUI/Controls/ChooseRecommendedMods.cs
8,263
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the codedeploy-2014-10-06.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.CodeDeploy.Model { /// <summary> /// The deployed state filter was specified in an invalid format. /// </summary> #if !NETSTANDARD [Serializable] #endif public partial class InvalidDeployedStateFilterException : AmazonCodeDeployException { /// <summary> /// Constructs a new InvalidDeployedStateFilterException with the specified error /// message. /// </summary> /// <param name="message"> /// Describes the error encountered. /// </param> public InvalidDeployedStateFilterException(string message) : base(message) {} /// <summary> /// Construct instance of InvalidDeployedStateFilterException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> public InvalidDeployedStateFilterException(string message, Exception innerException) : base(message, innerException) {} /// <summary> /// Construct instance of InvalidDeployedStateFilterException /// </summary> /// <param name="innerException"></param> public InvalidDeployedStateFilterException(Exception innerException) : base(innerException) {} /// <summary> /// Construct instance of InvalidDeployedStateFilterException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public InvalidDeployedStateFilterException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, innerException, errorType, errorCode, requestId, statusCode) {} /// <summary> /// Construct instance of InvalidDeployedStateFilterException /// </summary> /// <param name="message"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public InvalidDeployedStateFilterException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, errorType, errorCode, requestId, statusCode) {} #if !NETSTANDARD /// <summary> /// Constructs a new instance of the InvalidDeployedStateFilterException class with serialized data. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception> /// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception> protected InvalidDeployedStateFilterException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } /// <summary> /// Sets the <see cref="T:System.Runtime.Serialization.SerializationInfo" /> with information about the exception. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is a null reference (Nothing in Visual Basic). </exception> #if BCL35 [System.Security.Permissions.SecurityPermission( System.Security.Permissions.SecurityAction.LinkDemand, Flags = System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)] #endif [System.Security.SecurityCritical] // These FxCop rules are giving false-positives for this method [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2134:MethodsMustOverrideWithConsistentTransparencyFxCopRule")] public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { base.GetObjectData(info, context); } #endif } }
48.282258
178
0.687991
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/CodeDeploy/Generated/Model/InvalidDeployedStateFilterException.cs
5,987
C#
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. * Use of this file is governed by the BSD 3-clause license that * can be found in the LICENSE.txt file in the project root. */ using Antlr4.Runtime; using Antlr4.Runtime.Sharpen; namespace Antlr4.Runtime { /// <summary> /// This signifies any kind of mismatched input exceptions such as /// when the current input does not match the expected token. /// </summary> /// <remarks> /// This signifies any kind of mismatched input exceptions such as /// when the current input does not match the expected token. /// </remarks> [System.Serializable] public class InputMismatchException : RecognitionException { private const long serialVersionUID = 1532568338707443067L; public InputMismatchException(Parser recognizer) : base(recognizer, ((ITokenStream)recognizer.InputStream), recognizer.RuleContext) { this.OffendingToken = recognizer.CurrentToken; } } }
33.966667
85
0.698724
[ "BSD-3-Clause" ]
charwliu/antlr4
runtime/CSharp/runtime/CSharp/Antlr4.Runtime/InputMismatchException.cs
1,019
C#
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.CompilerServices; using DataStructuresLib.BitManipulation; using GeometricAlgebraFulcrumLib.Algebra.GeometricAlgebra.Basis; using GeometricAlgebraFulcrumLib.Processors.GeometricAlgebra.GuidedBinaryTraversal.Multivectors; using GeometricAlgebraFulcrumLib.Processors.ScalarAlgebra; using GeometricAlgebraFulcrumLib.Storage.LinearAlgebra.Vectors; using GeometricAlgebraFulcrumLib.Storage.LinearAlgebra.Vectors.Graded; using GeometricAlgebraFulcrumLib.Storage.LinearAlgebra.Vectors.Sparse; using GeometricAlgebraFulcrumLib.Utilities.Extensions; using GeometricAlgebraFulcrumLib.Utilities.Factories; using GeometricAlgebraFulcrumLib.Utilities.Structures.Records; namespace GeometricAlgebraFulcrumLib.Storage.GeometricAlgebra { /// <summary> /// Can store the scalar coefficients of a k-vector of any dimension. /// The scalars are assumed to be of immutable type such as T, complex, etc. /// </summary> /// <typeparam name="T"></typeparam> public record KVectorStorage<T> : IMultivectorGradedStorage<T> { public static KVectorStorage<T> ZeroScalar { get; } = new KVectorStorage<T>(0); public static VectorStorage<T> ZeroVector { get; } = new VectorStorage<T>(); public static BivectorStorage<T> ZeroBivector { get; } = new BivectorStorage<T>(); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static KVectorStorage<T> CreateKVectorZero(uint grade) { return grade switch { 0 => ZeroScalar, 1 => ZeroVector, 2 => ZeroBivector, _ => new KVectorStorage<T>(grade) }; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static KVectorStorage<T> CreateKVectorScalar(T scalar) { return new KVectorStorage<T>( new LinVectorSingleScalarGradedStorage<T>(0, scalar) ); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static KVectorStorage<T> CreateKVector(ulong id, T scalar) { var (grade, index) = id.BasisBladeIdToGradeIndex(); return grade switch { 0 => index == 0 ? CreateKVectorScalar(scalar) : throw new InvalidOperationException(), 1 => VectorStorage<T>.CreateVector(index, scalar), 2 => BivectorStorage<T>.CreateBivector(index, scalar), _ => new KVectorStorage<T>(new LinVectorSingleScalarGradedStorage<T>(grade, index, scalar)) }; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static KVectorStorage<T> CreateKVector(uint grade, ulong index, T scalar) { return grade switch { 0 => index == 0 ? CreateKVectorScalar(scalar) : throw new InvalidOperationException(), 1 => VectorStorage<T>.CreateVector(index, scalar), 2 => BivectorStorage<T>.CreateBivector(index, scalar), _ => new KVectorStorage<T>(new LinVectorSingleScalarGradedStorage<T>(grade, index, scalar)) }; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static KVectorStorage<T> CreateKVector(uint grade, params T[] indexScalarList) { return grade switch { 0 => indexScalarList.Length > 1 ? throw new InvalidOperationException() : indexScalarList.Length == 1 ? new KVectorStorage<T>(new LinVectorSingleScalarGradedStorage<T>(0, indexScalarList[0])) : ZeroScalar, 1 => VectorStorage<T>.CreateVector(indexScalarList), 2 => BivectorStorage<T>.CreateBivector(indexScalarList), _ => indexScalarList.Length switch { 0 => CreateKVectorZero(grade), 1 => new KVectorStorage<T>( new LinVectorSingleScalarGradedStorage<T>(grade, indexScalarList[0])), _ => new KVectorStorage<T>(indexScalarList.CreateLinVectorDenseStorage() .CreateLinVectorSingleGradeStorage(grade)) } }; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static KVectorStorage<T> CreateKVector(uint grade, IReadOnlyList<T> indexScalarList) { var count = indexScalarList.Count; return grade switch { 0 => count > 1 ? throw new InvalidOperationException() : count == 1 ? new KVectorStorage<T>(new LinVectorSingleScalarGradedStorage<T>(0, indexScalarList[0])) : ZeroScalar, 1 => VectorStorage<T>.CreateVector(indexScalarList), 2 => BivectorStorage<T>.CreateBivector(indexScalarList), _ => count switch { 0 => CreateKVectorZero(grade), 1 => new KVectorStorage<T>( new LinVectorSingleScalarGradedStorage<T>(grade, indexScalarList[0])), _ => new KVectorStorage<T>(indexScalarList.CreateLinVectorDenseStorage() .CreateLinVectorSingleGradeStorage(grade)) } }; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static KVectorStorage<T> CreateKVector(uint grade, IEnumerable<T> indexScalarList) { return CreateKVector(grade, indexScalarList.ToArray()); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static KVectorStorage<T> CreateKVector(uint grade, Dictionary<ulong, T> indexScalarDictionary) { if (grade == 0) { if (indexScalarDictionary.Count == 0) return ZeroScalar; if (indexScalarDictionary.Count > 1) throw new InvalidOperationException(); var (index, scalar) = indexScalarDictionary.First(); if (index > 0) throw new InvalidOperationException(); return CreateKVectorScalar(scalar); } return grade switch { 1 => VectorStorage<T>.CreateVector(indexScalarDictionary), 2 => BivectorStorage<T>.CreateBivector(indexScalarDictionary), _ => indexScalarDictionary.Count switch { 0 => CreateKVectorZero(grade), 1 => new KVectorStorage<T>(grade, indexScalarDictionary.First()), _ => new KVectorStorage<T>(indexScalarDictionary.CreateLinVectorSparseStorage().CreateLinVectorSingleGradeStorage(grade)) } }; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static KVectorStorage<T> CreateKVector(uint grade, ILinVectorSingleScalarStorage<T> indexScalarList) { return grade switch { 1 => VectorStorage<T>.CreateVector(indexScalarList), 2 => BivectorStorage<T>.CreateBivector(indexScalarList), _ => indexScalarList.IsEmpty() ? CreateKVectorZero(grade) : new KVectorStorage<T>(grade, indexScalarList) }; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static KVectorStorage<T> CreateKVector(uint grade, ILinVectorStorage<T> indexScalarList) { if (grade == 0) { if (indexScalarList.IsEmpty()) return ZeroScalar; if (indexScalarList.GetSparseCount() > 1 || !indexScalarList.TryGetScalar(0, out var scalar)) throw new InvalidOperationException(); return CreateKVectorScalar(scalar); } return grade switch { 1 => VectorStorage<T>.CreateVector(indexScalarList), 2 => BivectorStorage<T>.CreateBivector(indexScalarList), _ => indexScalarList.IsEmpty() ? CreateKVectorZero(grade) : new KVectorStorage<T>(grade, indexScalarList) }; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static KVectorStorage<T> CreateKVector(ILinVectorSingleGradeStorage<T> singleGradeIndexScalarList) { return singleGradeIndexScalarList.Grade switch { 1 => VectorStorage<T>.CreateVector(singleGradeIndexScalarList), 2 => BivectorStorage<T>.CreateBivector(singleGradeIndexScalarList), _ => new KVectorStorage<T>(singleGradeIndexScalarList) }; } protected uint? VSpaceDimension { get; set; } protected ILinVectorSingleGradeStorage<T> SingleGradeVectorStorage { get; } public virtual uint MinVSpaceDimension => VSpaceDimension ??= GetLinVectorIndexScalarStorage().GetMinVSpaceDimensionOfKVector(Grade); public int GradesCount => 1; public uint Grade => GetLinVectorSingleGradeStorage().Grade; public int TermsCount => GetLinVectorIndexScalarStorage().GetSparseCount(); public bool IsEven => false; public bool IsGraded => true; protected KVectorStorage(uint grade) { SingleGradeVectorStorage = new LinVectorEmptySingleGradeStorage<T>(grade); } protected KVectorStorage(uint grade, KeyValuePair<ulong, T> indexScalarPair) { var (index, scalar) = indexScalarPair; SingleGradeVectorStorage = new LinVectorSingleScalarGradedStorage<T>(grade, index, scalar); } protected KVectorStorage(uint grade, [NotNull] ILinVectorSingleScalarStorage<T> singleScalarVectorStorage) { SingleGradeVectorStorage = new LinVectorSingleScalarGradedStorage<T>(grade, singleScalarVectorStorage); } protected KVectorStorage(uint grade, [NotNull] ILinVectorStorage<T> singleScalarVectorStorage) { SingleGradeVectorStorage = new LinVectorSingleGradeStorage<T>(grade, singleScalarVectorStorage); } protected KVectorStorage([NotNull] ILinVectorSingleGradeStorage<T> gradeIndexScalarList) { SingleGradeVectorStorage = gradeIndexScalarList; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ulong GetMinIndex() { return GetLinVectorIndexScalarStorage().GetMinIndex(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ulong GetMaxIndex() { return GetLinVectorIndexScalarStorage().GetMaxIndex(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool ContainsTerm(ulong id) { id.BasisBladeIdToGradeIndex(out var grade, out var index); return Grade == grade && GetLinVectorIndexScalarStorage().ContainsIndex(index); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool ContainsTerm(uint grade, ulong index) { return grade == Grade && GetLinVectorIndexScalarStorage().ContainsIndex(index); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool ContainsScalarPart() { return Grade == 0 && !GetLinVectorSingleGradeStorage().IsEmpty(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool ContainsVectorPart() { return Grade == 1 && !GetLinVectorSingleGradeStorage().IsEmpty(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool ContainsBivectorPart() { return Grade == 2 && !GetLinVectorSingleGradeStorage().IsEmpty(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool ContainsKVectorPart(uint grade) { return Grade == grade && !GetLinVectorSingleGradeStorage().IsEmpty(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool ContainsTermWithIndex(ulong index) { return GetLinVectorSingleGradeStorage().ContainsIndex(Grade, index); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool IsEmpty() { return GetLinVectorIndexScalarStorage().IsEmpty(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool IsScalar() { return Grade == 0; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool IsVector() { return Grade == 1; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool IsBivector() { return Grade == 2; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool IsKVector() { return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool IsKVector(uint grade) { return Grade == grade; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ulong GetMinId() { return GetLinVectorIndexScalarStorage().GetMinIndex().BasisBladeIndexToId(Grade); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ulong GetMaxId() { return GetLinVectorIndexScalarStorage().GetMaxIndex().BasisBladeIndexToId(Grade); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ulong GetMinId(uint grade) { return grade == Grade ? GetLinVectorIndexScalarStorage().GetMinIndex() : throw new InvalidOperationException(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ulong GetMaxId(uint grade) { return grade == Grade ? GetLinVectorIndexScalarStorage().GetMaxIndex() : throw new InvalidOperationException(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public uint GetMinGrade() { return Grade; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public uint GetMaxGrade() { return Grade; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ulong GetMinIndex(uint grade) { return GetLinVectorIndexScalarStorage().GetMinIndex(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ulong GetMaxIndex(uint grade) { return GetLinVectorIndexScalarStorage().GetMaxIndex(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public IEnumerable<uint> GetGrades() { yield return Grade; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ulong GetStoredGradesBitPattern() { return 1UL << (int) Grade; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool TryGetTermScalarByIndex(ulong index, out T value) { if (GetLinVectorIndexScalarStorage().TryGetScalar(index, out value)) return true; value = default; return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool TryGetTermScalar(ulong id, out T value) { id.BasisBladeIdToGradeIndex(out var grade, out var index); if (Grade == grade && GetLinVectorIndexScalarStorage().TryGetScalar(index, out value)) return true; value = default; return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool TryGetTermScalar(uint grade, ulong index, out T value) { if (grade == Grade) return GetLinVectorIndexScalarStorage().TryGetScalar(index, out value); value = default; return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public IEnumerable<IndexScalarRecord<T>> GetIndexScalarRecords() { return GetLinVectorSingleGradeStorage().VectorStorage.GetIndexScalarRecords(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public KVectorStorage<T> GetKVectorCopy() { return this switch { VectorStorage<T> vector => vector.GetVectorCopy(), BivectorStorage<T> bivector => bivector.GetBivectorCopy(), _ => KVectorStorage<T>.CreateKVector( Grade, GetLinVectorIndexScalarStorage().GetCopy() ) }; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public KVectorStorage<T2> MapKVectorScalars<T2>(Func<T, T2> scalarMapping) { return this switch { VectorStorage<T> vector => vector.MapVectorScalars(scalarMapping), BivectorStorage<T> bivector => bivector.MapBivectorScalars(scalarMapping), _ => KVectorStorage<T2>.CreateKVector( Grade, GetLinVectorIndexScalarStorage().MapScalars(scalarMapping) ) }; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public KVectorStorage<T2> MapKVectorScalarsById<T2>(Func<ulong, T, T2> idScalarMapping) { return this switch { VectorStorage<T> vector => vector.MapVectorScalarsById(idScalarMapping), BivectorStorage<T> bivector => bivector.MapBivectorScalarsById(idScalarMapping), _ => KVectorStorage<T2>.CreateKVector( Grade, GetLinVectorIndexScalarStorage().MapScalars( (index, scalar) => idScalarMapping(index.BasisBladeIndexToId(Grade), scalar) ) ) }; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public KVectorStorage<T2> MapKVectorScalarsByIndex<T2>(Func<ulong, T, T2> indexScalarMapping) { return this switch { VectorStorage<T> vector => vector.MapVectorScalarsByIndex(indexScalarMapping), BivectorStorage<T> bivector => bivector.MapBivectorScalarsByIndex(indexScalarMapping), _ => KVectorStorage<T2>.CreateKVector( Grade, GetLinVectorIndexScalarStorage().MapScalars(indexScalarMapping) ) }; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public KVectorStorage<T2> MapKVectorScalarsByGradeIndex<T2>(Func<uint, ulong, T, T2> gradeIndexScalarMapping) { return this switch { VectorStorage<T> vector => vector.MapVectorScalarsByGradeIndex(gradeIndexScalarMapping), BivectorStorage<T> bivector => bivector.MapBivectorScalarsByGradeIndex(gradeIndexScalarMapping), _ => KVectorStorage<T2>.CreateKVector( Grade, GetLinVectorIndexScalarStorage().MapScalars( (index, scalar) => gradeIndexScalarMapping(Grade, index, scalar) ) ) }; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public IMultivectorGradedStorage<T> GetGradedMultivectorCopy() { return GetKVectorCopy(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public IMultivectorGradedStorage<T2> MapGradedMultivectorScalars<T2>(Func<T, T2> scalarMapping) { return MapKVectorScalars(scalarMapping); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public IMultivectorGradedStorage<T2> MapGradedMultivectorScalarsById<T2>(Func<ulong, T, T2> idScalarMapping) { return MapKVectorScalarsByIndex( (index, scalar) => idScalarMapping(index.BasisBladeIndexToId(Grade), scalar) ); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public IMultivectorGradedStorage<T2> MapGradedMultivectorScalarsByIndex<T2>(Func<ulong, T, T2> indexScalarMapping) { return MapKVectorScalarsByIndex(indexScalarMapping); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public IMultivectorGradedStorage<T2> MapGradedMultivectorScalarsByGradeIndex<T2>(Func<uint, ulong, T, T2> gradeIndexScalarMapping) { return MapKVectorScalarsByIndex( (index, scalar) => gradeIndexScalarMapping(Grade, index, scalar) ); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public KVectorStorage<T> FilterKVectorByScalar(Func<T, bool> scalarFilter) { return this switch { VectorStorage<T> vector => vector.FilterVectorByScalar(scalarFilter), BivectorStorage<T> bivector => bivector.FilterBivectorByScalar(scalarFilter), _ => KVectorStorage<T>.CreateKVector( Grade, GetLinVectorIndexScalarStorage().FilterByScalar(scalarFilter) ) }; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public KVectorStorage<T> FilterKVectorByIndexScalar(Func<ulong, T, bool> indexScalarFilter) { return this switch { VectorStorage<T> vector => vector.FilterVectorByIndexScalar(indexScalarFilter), BivectorStorage<T> bivector => bivector.FilterBivectorByIndexScalar(indexScalarFilter), _ => KVectorStorage<T>.CreateKVector( Grade, GetLinVectorIndexScalarStorage().FilterByIndexScalar(indexScalarFilter) ) }; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public KVectorStorage<T> FilterKVectorByIndex(Func<ulong, bool> indexFilter) { return this switch { VectorStorage<T> vector => vector.FilterVectorByIndex(indexFilter), BivectorStorage<T> bivector => bivector.FilterBivectorByIndex(indexFilter), _ => KVectorStorage<T>.CreateKVector( Grade, GetLinVectorIndexScalarStorage().FilterByIndex(indexFilter) ) }; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ILinVectorStorage<T> GetScalarPartList() { return Grade == 0 && !GetLinVectorIndexScalarStorage().IsEmpty() ? GetLinVectorIndexScalarStorage() : LinVectorEmptyStorage<T>.EmptyStorage; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ILinVectorStorage<T> GetVectorPartList() { return Grade == 1 && !GetLinVectorIndexScalarStorage().IsEmpty() ? GetLinVectorIndexScalarStorage() : LinVectorEmptyStorage<T>.EmptyStorage; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ILinVectorStorage<T> GetBivectorPartList() { return Grade == 2 && !GetLinVectorIndexScalarStorage().IsEmpty() ? GetLinVectorIndexScalarStorage() : LinVectorEmptyStorage<T>.EmptyStorage; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ILinVectorStorage<T> GetKVectorPartList(uint grade) { return Grade == grade && !GetLinVectorIndexScalarStorage().IsEmpty() ? GetLinVectorIndexScalarStorage() : LinVectorEmptyStorage<T>.EmptyStorage; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool TryGetVectorPart(out VectorStorage<T> vector) { if (Grade == 1 && this is VectorStorage<T> vectorStorage) { vector = vectorStorage; return true; } vector = null; return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool TryGetBivectorPart(out BivectorStorage<T> bivector) { if (Grade == 2 && this is BivectorStorage<T> bivectorStorage) { bivector = bivectorStorage; return true; } bivector = null; return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool TryGetKVectorPart(uint grade, out KVectorStorage<T> kVector) { if (Grade == grade) { kVector = this; return true; } kVector = null; return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool TryGetScalarPartList(out ILinVectorStorage<T> indexScalarList) { if (Grade == 0 && !GetLinVectorIndexScalarStorage().IsEmpty()) { indexScalarList = GetLinVectorIndexScalarStorage(); return true; } indexScalarList = null; return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool TryGetVectorPartList(out ILinVectorStorage<T> indexScalarList) { if (Grade == 1 && !GetLinVectorIndexScalarStorage().IsEmpty()) { indexScalarList = GetLinVectorIndexScalarStorage(); return true; } indexScalarList = null; return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool TryGetBivectorPartList(out ILinVectorStorage<T> indexScalarList) { if (Grade == 2 && !GetLinVectorIndexScalarStorage().IsEmpty()) { indexScalarList = GetLinVectorIndexScalarStorage(); return true; } indexScalarList = LinVectorEmptyStorage<T>.EmptyStorage; return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool TryGetKVectorPartList(uint grade, out ILinVectorStorage<T> indexScalarList) { if (Grade == grade && !GetLinVectorIndexScalarStorage().IsEmpty()) { indexScalarList = GetLinVectorIndexScalarStorage(); return true; } indexScalarList = LinVectorEmptyStorage<T>.EmptyStorage; return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ILinVectorStorage<T> GetLinVectorIndexScalarStorage() { return GetLinVectorSingleGradeStorage().VectorStorage; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ILinVectorStorage<T> GetLinVectorIdScalarStorage() { return GetLinVectorIndexScalarStorage().GetPermutation( index => index.BasisBladeIndexToId(Grade) ); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ILinVectorGradedStorage<T> GetLinVectorGradedStorage() { return GetLinVectorSingleGradeStorage(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ILinVectorStorage<T> GetLinVectorIndexScalarStorage(uint grade) { return grade == Grade ? GetLinVectorIndexScalarStorage() : LinVectorEmptyStorage<T>.EmptyStorage; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public IEnumerable<ulong> GetIds() { return GetLinVectorIndexScalarStorage().GetIndices().Select( index => index.BasisBladeIndexToId(Grade) ); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public IEnumerable<ulong> GetIndices() { return GetLinVectorIndexScalarStorage().GetIndices(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public IEnumerable<GradeIndexRecord> GetGradeIndexRecords() { return GetLinVectorIndexScalarStorage().GetIndices().Select(index => new GradeIndexRecord(Grade, index)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public IEnumerable<T> GetScalars() { return GetLinVectorIndexScalarStorage().GetScalars(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public IEnumerable<IndexScalarRecord<T>> GetIdScalarRecords() { return GetLinVectorIndexScalarStorage().GetIndexScalarRecords().Select( pair => new IndexScalarRecord<T>( pair.Index.BasisBladeIndexToId(Grade), pair.Scalar ) ); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public IEnumerable<IndexScalarRecord<T>> GetIndexScalarRecords(uint grade) { return grade == Grade ? GetLinVectorIndexScalarStorage().GetIndexScalarRecords() : Enumerable.Empty<IndexScalarRecord<T>>(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public IEnumerable<GradeIndexScalarRecord<T>> GetGradeIndexScalarRecords() { return GetLinVectorSingleGradeStorage().GetGradeIndexScalarRecords(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public LinVectorTreeStorage<T> GetBinaryTree(int treeDepth) { if (treeDepth < MinVSpaceDimension) throw new InvalidOperationException(); var dict = GetIdScalarRecords() .ToDictionary( pair => pair.Index, pair => pair.Scalar ); return new LinVectorTreeStorage<T>(treeDepth, dict); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public IGeoGbtMultivectorStorageStack1<T> CreateGbtStack(int treeDepth, int capacity, IScalarAlgebraProcessor<T> scalarProcessor) { //return GeoGbtKVectorStorageStack1<T>.Create(capacity, treeDepth, this); //return GeoGbtMultivectorStorageGradedStack1<T>.Create(capacity, treeDepth, this); return GeoGbtMultivectorStorageUniformStack1<T>.Create( capacity, treeDepth, scalarProcessor, this ); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public MultivectorStorage<T> ToMultivectorStorage() { var idScalarDictionary = GetLinVectorIndexScalarStorage().GetPermutation(BasisBladeUtils.BasisBladeIdToIndex); return MultivectorStorage<T>.Create( idScalarDictionary ); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public MultivectorGradedStorage<T> ToMultivectorGradedStorage() { return SingleGradeVectorStorage.CreateMultivectorGradedStorage(); } public virtual bool TryGetScalar(out T value) { value = default; return false; } public virtual bool TryGetTermByIndex(int index, out BasisTerm<T> term) { var i = (ulong) index; if (GetLinVectorIndexScalarStorage().TryGetScalar(i, out var value)) { term = value.CreateBasisTerm(Grade, index); return true; } term = null; return false; } public virtual bool TryGetTermByIndex(ulong index, out BasisTerm<T> term) { if (GetLinVectorIndexScalarStorage().TryGetScalar(index, out var value)) { term = value.CreateBasisTerm(Grade, index); return true; } term = null; return false; } public virtual bool TryGetTerm(ulong id, out BasisTerm<T> term) { id.BasisBladeIdToGradeIndex(out var grade, out var index); if (grade == Grade && GetLinVectorIndexScalarStorage().TryGetScalar(index, out var value)) { term = value.CreateBasisTerm(Grade, index); return true; } term = null; return false; } public virtual bool TryGetTerm(uint grade, ulong index, out BasisTerm<T> term) { if (grade == Grade && GetLinVectorIndexScalarStorage().TryGetScalar(index, out var value)) { term = value.CreateBasisTerm(Grade, index); return true; } term = null; return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public virtual ILinVectorSingleGradeStorage<T> GetLinVectorSingleGradeStorage() { return SingleGradeVectorStorage; } public virtual VectorStorage<T> GetVectorPart() { return VectorStorage<T>.ZeroVector; } public virtual VectorStorage<T> GetVectorPart(Func<T, bool> scalarSelection) { return VectorStorage<T>.ZeroVector; } public virtual VectorStorage<T> GetVectorPart(Func<ulong, T, bool> indexScalarSelection) { return VectorStorage<T>.ZeroVector; } public virtual VectorStorage<T> GetVectorPart(Func<ulong, bool> indexSelection) { return VectorStorage<T>.ZeroVector; } public virtual BivectorStorage<T> GetBivectorPart() { return BivectorStorage<T>.ZeroBivector; } public virtual BivectorStorage<T> GetBivectorPart(Func<T, bool> scalarSelection) { return BivectorStorage<T>.ZeroBivector; } public virtual BivectorStorage<T> GetBivectorPart(Func<ulong, T, bool> indexScalarSelection) { return BivectorStorage<T>.ZeroBivector; } public virtual BivectorStorage<T> GetBivectorPart(Func<ulong, bool> indexSelection) { return BivectorStorage<T>.ZeroBivector; } public virtual KVectorStorage<T> GetKVectorPart(uint grade) { return grade == Grade ? this : CreateKVectorZero(grade); } public virtual KVectorStorage<T> GetKVectorPart(uint grade, Func<T, bool> scalarSelection) { if (grade != Grade) return CreateKVectorZero(grade); var indexScalarDictionary = GetLinVectorIndexScalarStorage().FilterByScalar(scalarSelection); return CreateKVector(Grade, indexScalarDictionary); } public virtual KVectorStorage<T> GetKVectorPart(uint grade, Func<ulong, T, bool> indexScalarSelection) { if (grade != Grade) return CreateKVectorZero(grade); var indexScalarDictionary = GetLinVectorIndexScalarStorage().FilterByIndexScalar(indexScalarSelection); return CreateKVector(Grade, indexScalarDictionary); } public virtual KVectorStorage<T> GetKVectorPart(uint grade, Func<ulong, bool> indexSelection) { if (grade != Grade) return CreateKVectorZero(grade); var indexScalarDictionary = GetLinVectorIndexScalarStorage().FilterByIndex(indexSelection); return CreateKVector(Grade, indexScalarDictionary); } public virtual IMultivectorStorage<T> GetMultivectorPart(Func<ulong, bool> idSelection) { var indexScalarDictionary = GetLinVectorIndexScalarStorage().FilterByIndex( index => idSelection(index.BasisBladeIndexToId(Grade)) ); return CreateKVector(Grade, indexScalarDictionary); } public virtual IMultivectorStorage<T> GetMultivectorPart(Func<uint, ulong, bool> gradeIndexSelection) { var indexScalarDictionary = GetLinVectorIndexScalarStorage().FilterByIndex( index => gradeIndexSelection(Grade, index) ); return CreateKVector(Grade, indexScalarDictionary); } public virtual IMultivectorStorage<T> GetMultivectorPart(Func<T, bool> scalarSelection) { var indexScalarDictionary = GetLinVectorIndexScalarStorage().FilterByScalar(scalarSelection); return CreateKVector(Grade, indexScalarDictionary); } public virtual IMultivectorStorage<T> GetMultivectorPart(Func<ulong, T, bool> idScalarSelection) { var indexScalarDictionary = GetLinVectorIndexScalarStorage().FilterByIndexScalar( (index, value) => idScalarSelection( index.BasisBladeIndexToId(Grade), value ) ); return CreateKVector(Grade, indexScalarDictionary); } public virtual IMultivectorStorage<T> GetMultivectorPart(Func<uint, ulong, T, bool> gradeIndexScalarSelection) { var indexScalarDictionary = GetLinVectorIndexScalarStorage().FilterByIndexScalar( (index, scalar) => gradeIndexScalarSelection(Grade, index, scalar) ); return CreateKVector(Grade, indexScalarDictionary); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Tuple<IMultivectorStorage<T>, IMultivectorStorage<T>> SplitEvenOddParts() { return Grade.IsEven() ? new Tuple<IMultivectorStorage<T>, IMultivectorStorage<T>>( this, MultivectorStorage<T>.ZeroMultivector ) : new Tuple<IMultivectorStorage<T>, IMultivectorStorage<T>>( MultivectorStorage<T>.ZeroMultivector, this ); } public virtual Tuple<VectorStorage<T>, VectorStorage<T>> SplitVectorPart(Func<ulong, bool> indexSelection) { if (Grade != 1) return new Tuple<VectorStorage<T>, VectorStorage<T>>( VectorStorage<T>.ZeroVector, VectorStorage<T>.ZeroVector ); var indexScalarDictionary1 = new Dictionary<ulong, T>(); var indexScalarDictionary2 = new Dictionary<ulong, T>(); foreach (var (index, scalar) in GetLinVectorIndexScalarStorage().GetIndexScalarRecords()) { if (indexSelection(index)) indexScalarDictionary1.Add(index, scalar); else indexScalarDictionary2.Add(index, scalar); } return new Tuple<VectorStorage<T>, VectorStorage<T>>( indexScalarDictionary1.CreateVectorStorage(), indexScalarDictionary2.CreateVectorStorage() ); } public virtual Tuple<VectorStorage<T>, VectorStorage<T>> SplitVectorPart(Func<ulong, T, bool> indexScalarSelection) { if (Grade != 1) return new Tuple<VectorStorage<T>, VectorStorage<T>>( VectorStorage<T>.ZeroVector, VectorStorage<T>.ZeroVector ); var indexScalarDictionary1 = new Dictionary<ulong, T>(); var indexScalarDictionary2 = new Dictionary<ulong, T>(); foreach (var (index, scalar) in GetLinVectorIndexScalarStorage().GetIndexScalarRecords()) { if (indexScalarSelection(index, scalar)) indexScalarDictionary1.Add(index, scalar); else indexScalarDictionary2.Add(index, scalar); } return new Tuple<VectorStorage<T>, VectorStorage<T>>( indexScalarDictionary1.CreateVectorStorage(), indexScalarDictionary2.CreateVectorStorage() ); } public virtual Tuple<VectorStorage<T>, VectorStorage<T>> SplitVectorPart(Func<T, bool> scalarSelection) { if (Grade != 1) return new Tuple<VectorStorage<T>, VectorStorage<T>>( VectorStorage<T>.ZeroVector, VectorStorage<T>.ZeroVector ); var indexScalarDictionary1 = new Dictionary<ulong, T>(); var indexScalarDictionary2 = new Dictionary<ulong, T>(); foreach (var (index, scalar) in GetLinVectorIndexScalarStorage().GetIndexScalarRecords()) { if (scalarSelection(scalar)) indexScalarDictionary1.Add(index, scalar); else indexScalarDictionary2.Add(index, scalar); } return new Tuple<VectorStorage<T>, VectorStorage<T>>( indexScalarDictionary1.CreateVectorStorage(), indexScalarDictionary2.CreateVectorStorage() ); } public virtual IEnumerable<BasisBlade> GetBasisBlades() { return GetLinVectorIndexScalarStorage().GetIndexScalarRecords().Select(pair => Grade.CreateBasisBlade(pair.Index) ); } public virtual IEnumerable<BasisTerm<T>> GetTerms() { return GetLinVectorIndexScalarStorage().GetIndexScalarRecords().Select(pair => pair.Scalar.CreateBasisTerm(Grade, pair.Index) ); } public virtual IEnumerable<BasisTerm<T>> GetTerms(Func<ulong, bool> idSelection) { foreach (var (index, scalar) in GetLinVectorIndexScalarStorage().GetIndexScalarRecords()) { var id = index.BasisBladeIndexToId(Grade); if (idSelection(id)) yield return scalar.CreateBasisTerm(Grade, index); } } public virtual IEnumerable<BasisTerm<T>> GetTerms(Func<uint, ulong, bool> gradeIndexSelection) { foreach (var (index, scalar) in GetLinVectorIndexScalarStorage().GetIndexScalarRecords()) { if (gradeIndexSelection(Grade, index)) yield return scalar.CreateBasisTerm(Grade, index); } } public virtual IEnumerable<BasisTerm<T>> GetTerms(Func<T, bool> scalarSelection) { foreach (var (index, scalar) in GetLinVectorIndexScalarStorage().GetIndexScalarRecords()) { if (scalarSelection(scalar)) yield return scalar.CreateBasisTerm(Grade, index); } } public virtual IEnumerable<BasisTerm<T>> GetTerms(Func<ulong, T, bool> idScalarSelection) { foreach (var (index, scalar) in GetLinVectorIndexScalarStorage().GetIndexScalarRecords()) { var id = index.BasisBladeIndexToId(Grade); if (idScalarSelection(id, scalar)) yield return scalar.CreateBasisTerm(Grade, index); } } public virtual IEnumerable<BasisTerm<T>> GetTerms(Func<uint, ulong, T, bool> gradeIndexScalarSelection) { foreach (var (index, scalar) in GetLinVectorIndexScalarStorage().GetIndexScalarRecords()) { if (gradeIndexScalarSelection(Grade, index, scalar)) yield return scalar.CreateBasisTerm(Grade, index); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public override string ToString() { return this.GetMultivectorText(); } } }
36.341091
141
0.589828
[ "MIT" ]
ga-explorer/GeometricAlgebraFulcrumLib
GeometricAlgebraFulcrumLib/GeometricAlgebraFulcrumLib/Storage/GeometricAlgebra/KVectorStorage.cs
45,283
C#
using NSubstitute; using NUnit.Framework; using System; namespace ManualDi.Main.Tests { public class TestDiContainerDispose { [Test] public void TestDispose() { var instance = new object(); var disposeAction = Substitute.For<Action>(); IDiContainer container = new DiContainerBuilder().WithInstallDelegate(x => { x.Bind<object>() .FromInstance(instance) .RegisterDispose((o, c) => disposeAction); }).Build(); _ = container.Resolve<object>(); disposeAction.DidNotReceive().Invoke(); container.Dispose(); disposeAction.Received(1).Invoke(); disposeAction.ClearReceivedCalls(); container.Dispose(); disposeAction.DidNotReceive().Invoke(); } } }
25.162162
87
0.52739
[ "MIT" ]
GabLeRoux/ManualDi.Main
ManualDi.Main.Tests/TestDiContainerDispose.cs
933
C#
using System; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("AWSSDK.Amplify")] #if BCL35 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - AWS Amplify. Amplify is a fully managed continuous deployment and hosting service for modern web apps.")] #elif BCL45 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (4.5) - AWS Amplify. Amplify is a fully managed continuous deployment and hosting service for modern web apps.")] #elif NETSTANDARD13 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 1.3) - AWS Amplify. Amplify is a fully managed continuous deployment and hosting service for modern web apps.")] #elif NETSTANDARD20 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 2.0) - AWS Amplify. Amplify is a fully managed continuous deployment and hosting service for modern web apps.")] #elif NETCOREAPP3_1 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (.NET Core 3.1) - AWS Amplify. Amplify is a fully managed continuous deployment and hosting service for modern web apps.")] #else #error Unknown platform constant - unable to set correct AssemblyDescription #endif [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Amazon Web Services SDK for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("3.3")] [assembly: AssemblyFileVersion("3.5.2.2")] [assembly: System.CLSCompliant(true)] #if BCL [assembly: System.Security.AllowPartiallyTrustedCallers] #endif
48.037736
194
0.768264
[ "Apache-2.0" ]
augustoproiete-forks/aws--aws-sdk-net
sdk/src/Services/Amplify/Properties/AssemblyInfo.cs
2,546
C#
using System; using System.Windows.Markup; namespace Nefarius.DsHidMini.Util.WPF { public class EnumBindingSourceExtension : MarkupExtension { private Type _enumType; public EnumBindingSourceExtension() { } public EnumBindingSourceExtension(Type enumType) { EnumType = enumType; } public Type EnumType { get => _enumType; set { if (value != _enumType) { if (null != value) { var enumType = Nullable.GetUnderlyingType(value) ?? value; if (!enumType.IsEnum) throw new ArgumentException("Type must be for an Enum."); } _enumType = value; } } } public override object ProvideValue(IServiceProvider serviceProvider) { if (null == _enumType) throw new InvalidOperationException("The EnumType must be specified."); var actualEnumType = Nullable.GetUnderlyingType(_enumType) ?? _enumType; var enumValues = Enum.GetValues(actualEnumType); if (actualEnumType == _enumType) return enumValues; var tempArray = Array.CreateInstance(actualEnumType, enumValues.Length + 1); enumValues.CopyTo(tempArray, 1); return tempArray; } } }
28.166667
88
0.521368
[ "BSD-3-Clause" ]
Kanuan/DsHidMini
DSHMC/Util/WPF/EnumBindingSourceExtension.cs
1,523
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Optimization; using System.Web.Routing; using System.Web.Security; using System.Web.SessionState; namespace file_manager { public class Global : HttpApplication { void Application_Start(object sender, EventArgs e) { // Code that runs on application startup RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } } }
25.52381
62
0.705224
[ "MIT" ]
pvorotnikov/file-manager
file-manager/Global.asax.cs
538
C#
using System; using Cake.Core; using Cake.Core.IO; namespace Cake.Dotfuscator { /// <summary> /// Strong name resolver. /// </summary> public sealed class DotfuscatorResolver : IDotfuscatorToolResolver { private readonly IFileSystem _fileSystem; private readonly ICakeEnvironment _environment; private FilePath _exePath = null; private FilePath _ilasmPath = null; private FilePath _ildasmPath = null; /// <summary> /// Initializes a new instance of the <see cref="Cake.Dotfuscator.DotfuscatorResolver"/> class. /// </summary> /// <param name="fileSystem">The filesystem.</param> /// <param name="environment">The environment.</param> public DotfuscatorResolver(IFileSystem fileSystem, ICakeEnvironment environment) { _fileSystem = fileSystem; _environment = environment; if (fileSystem == null) { throw new ArgumentNullException("fileSystem"); } if (environment == null) { throw new ArgumentNullException("environment"); } } /// <summary> /// Resolves the path to the dotfuscaotr tool (dotfuscaotr.exe) /// </summary> /// <returns>The path to dotfuscaotr.exe</returns> public FilePath GetToolPath() { if (_exePath != null) return _exePath; // Get the path to program files. var programFilesPath = _environment.GetSpecialPath(SpecialPath.ProgramFilesX86); _exePath = programFilesPath.Combine(@"PreEmptive Solutions\Dotfuscator Professional Edition 4.9").CombineWithFilePath("dotfuscator.exe"); if (_fileSystem.Exist(_exePath)) return _exePath; else throw new CakeException("Failed to find dotfuscator.exe."); } /// <summary> /// /// </summary> /// <returns></returns> public FilePath GetILASMPath() { if (_ilasmPath != null) return _ilasmPath; var windowsPath = _environment.GetSpecialPath(SpecialPath.Windows); _ilasmPath = windowsPath.Combine(@"Microsoft.NET\Framework\v4.0.30319").CombineWithFilePath("ilasm.exe"); if (_fileSystem.Exist(_ilasmPath)) return _ilasmPath; else throw new CakeException("Failed to find ilasm.exe."); } /// <summary> /// /// </summary> /// <returns></returns> public FilePath GetILDASMPath() { if (_ildasmPath != null) return _ildasmPath; var programFilesPath = _environment.GetSpecialPath(SpecialPath.ProgramFilesX86); _ildasmPath = programFilesPath.Combine(@"Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6 Tools").CombineWithFilePath("ildasm.exe"); if (_fileSystem.Exist(_ildasmPath)) return _ildasmPath; _ildasmPath = programFilesPath.Combine(@"Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools").CombineWithFilePath("ildasm.exe"); if (_fileSystem.Exist(_ildasmPath)) return _ildasmPath; else throw new CakeException("Failed to find ildasm.exe."); } } }
37.662791
149
0.61377
[ "MIT" ]
xiaokun/Cake.Dotfuscator
src/Cake.Dotfuscator/DotfuscatorResolver.cs
3,239
C#
namespace GUI_OVFTOOL { partial class ISO_UpldVCD_ondem { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ISO_UpldVCD_ondem)); this.txtpwd = new System.Windows.Forms.TextBox(); this.txtui = new System.Windows.Forms.TextBox(); this.label8 = new System.Windows.Forms.Label(); this.label7 = new System.Windows.Forms.Label(); this.txtres = new System.Windows.Forms.TextBox(); this.txtsynx = new System.Windows.Forms.TextBox(); this.btnrun = new System.Windows.Forms.Button(); this.txtapp = new System.Windows.Forms.TextBox(); this.txtorg = new System.Windows.Forms.TextBox(); this.txtdtn = new System.Windows.Forms.TextBox(); this.txtsrc = new System.Windows.Forms.TextBox(); this.label5 = new System.Windows.Forms.Label(); this.label6 = new System.Windows.Forms.Label(); this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog(); this.label4 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.btnsrc = new System.Windows.Forms.Button(); this.label1 = new System.Windows.Forms.Label(); this.label9 = new System.Windows.Forms.Label(); this.progressBar1 = new System.Windows.Forms.ProgressBar(); this.toolTip1 = new System.Windows.Forms.ToolTip(this.components); this.help = new System.Windows.Forms.Button(); this.label10 = new System.Windows.Forms.Label(); this.label11 = new System.Windows.Forms.Label(); this.label12 = new System.Windows.Forms.Label(); this.label13 = new System.Windows.Forms.Label(); this.label14 = new System.Windows.Forms.Label(); this.chklog = new System.Windows.Forms.CheckBox(); this.btnlog = new System.Windows.Forms.Button(); this.backgroundWorker1 = new System.ComponentModel.BackgroundWorker(); this.cmblog = new System.Windows.Forms.ComboBox(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.btn_vdc_cat = new System.Windows.Forms.Button(); this.cmbcat = new System.Windows.Forms.ComboBox(); this.cmbvdc = new System.Windows.Forms.ComboBox(); this.label17 = new System.Windows.Forms.Label(); this.label16 = new System.Windows.Forms.Label(); this.label15 = new System.Windows.Forms.Label(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.groupBox1.SuspendLayout(); this.groupBox2.SuspendLayout(); this.SuspendLayout(); // // txtpwd // this.txtpwd.Font = new System.Drawing.Font("Times New Roman", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.txtpwd.Location = new System.Drawing.Point(249, 119); this.txtpwd.Name = "txtpwd"; this.txtpwd.PasswordChar = '*'; this.txtpwd.Size = new System.Drawing.Size(275, 22); this.txtpwd.TabIndex = 3; this.txtpwd.MouseHover += new System.EventHandler(this.txtpwd_MouseHover); // // txtui // this.txtui.Font = new System.Drawing.Font("Times New Roman", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.txtui.Location = new System.Drawing.Point(249, 70); this.txtui.Name = "txtui"; this.txtui.Size = new System.Drawing.Size(275, 22); this.txtui.TabIndex = 2; this.txtui.MouseHover += new System.EventHandler(this.txtui_MouseHover); // // label8 // this.label8.AutoSize = true; this.label8.BackColor = System.Drawing.Color.Transparent; this.label8.Font = new System.Drawing.Font("Times New Roman", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label8.Location = new System.Drawing.Point(22, 123); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(120, 15); this.label8.TabIndex = 37; this.label8.Text = "vCloud Air Password"; // // label7 // this.label7.AutoSize = true; this.label7.BackColor = System.Drawing.Color.Transparent; this.label7.Font = new System.Drawing.Font("Times New Roman", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label7.Location = new System.Drawing.Point(22, 73); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(109, 15); this.label7.TabIndex = 36; this.label7.Text = "vCloud Air User ID"; // // txtres // this.txtres.Font = new System.Drawing.Font("Times New Roman", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.txtres.Location = new System.Drawing.Point(38, 426); this.txtres.Multiline = true; this.txtres.Name = "txtres"; this.txtres.ScrollBars = System.Windows.Forms.ScrollBars.Both; this.txtres.Size = new System.Drawing.Size(1000, 298); this.txtres.TabIndex = 6; // // txtsynx // this.txtsynx.BackColor = System.Drawing.SystemColors.Window; this.txtsynx.Font = new System.Drawing.Font("Times New Roman", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.txtsynx.Location = new System.Drawing.Point(248, 13); this.txtsynx.Name = "txtsynx"; this.txtsynx.ReadOnly = true; this.txtsynx.Size = new System.Drawing.Size(777, 22); this.txtsynx.TabIndex = 1; this.txtsynx.Text = "Syntax"; // // btnrun // this.btnrun.Font = new System.Drawing.Font("Times New Roman", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.btnrun.Location = new System.Drawing.Point(25, 13); this.btnrun.Name = "btnrun"; this.btnrun.Size = new System.Drawing.Size(147, 25); this.btnrun.TabIndex = 0; this.btnrun.Text = "Run"; this.btnrun.UseVisualStyleBackColor = true; this.btnrun.Click += new System.EventHandler(this.btnrun_Click); // // txtapp // this.txtapp.Font = new System.Drawing.Font("Times New Roman", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.txtapp.Location = new System.Drawing.Point(742, 66); this.txtapp.Name = "txtapp"; this.txtapp.Size = new System.Drawing.Size(275, 22); this.txtapp.TabIndex = 4; this.txtapp.MouseHover += new System.EventHandler(this.txtapp_MouseHover); // // txtorg // this.txtorg.Font = new System.Drawing.Font("Times New Roman", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.txtorg.Location = new System.Drawing.Point(742, 19); this.txtorg.Name = "txtorg"; this.txtorg.Size = new System.Drawing.Size(275, 22); this.txtorg.TabIndex = 30; // // txtdtn // this.txtdtn.Font = new System.Drawing.Font("Times New Roman", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.txtdtn.Location = new System.Drawing.Point(249, 169); this.txtdtn.Name = "txtdtn"; this.txtdtn.Size = new System.Drawing.Size(275, 22); this.txtdtn.TabIndex = 5; this.txtdtn.MouseHover += new System.EventHandler(this.txtdtn_MouseHover); // // txtsrc // this.txtsrc.AllowDrop = true; this.txtsrc.Font = new System.Drawing.Font("Times New Roman", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.txtsrc.Location = new System.Drawing.Point(249, 19); this.txtsrc.Name = "txtsrc"; this.txtsrc.Size = new System.Drawing.Size(275, 22); this.txtsrc.TabIndex = 1; this.txtsrc.Text = "Drag and drop source file"; this.txtsrc.DragDrop += new System.Windows.Forms.DragEventHandler(this.txtsrc_DragDrop); this.txtsrc.DragEnter += new System.Windows.Forms.DragEventHandler(this.txtsrc_DragEnter); // // label5 // this.label5.AutoSize = true; this.label5.BackColor = System.Drawing.Color.Transparent; this.label5.Font = new System.Drawing.Font("Times New Roman", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label5.Location = new System.Drawing.Point(603, 69); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(72, 15); this.label5.TabIndex = 25; this.label5.Text = "Media name"; // // label6 // this.label6.AutoSize = true; this.label6.BackColor = System.Drawing.Color.Transparent; this.label6.Enabled = false; this.label6.Font = new System.Drawing.Font("Times New Roman", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label6.Location = new System.Drawing.Point(603, 143); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(81, 15); this.label6.TabIndex = 26; this.label6.Text = "Catalog Name"; // // openFileDialog1 // this.openFileDialog1.FileName = "Source"; this.openFileDialog1.Filter = "|*.iso*"; // // label4 // this.label4.AutoSize = true; this.label4.BackColor = System.Drawing.Color.Transparent; this.label4.Font = new System.Drawing.Font("Times New Roman", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label4.Location = new System.Drawing.Point(603, 22); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(43, 15); this.label4.TabIndex = 24; this.label4.Text = "Org ID"; // // label3 // this.label3.AutoSize = true; this.label3.BackColor = System.Drawing.Color.Transparent; this.label3.Enabled = false; this.label3.Font = new System.Drawing.Font("Times New Roman", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label3.Location = new System.Drawing.Point(603, 190); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(48, 15); this.label3.TabIndex = 23; this.label3.Text = "VDC ID"; // // label2 // this.label2.AutoSize = true; this.label2.BackColor = System.Drawing.Color.Transparent; this.label2.Font = new System.Drawing.Font("Times New Roman", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label2.Location = new System.Drawing.Point(22, 172); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(96, 15); this.label2.TabIndex = 22; this.label2.Text = "Destination URL"; // // btnsrc // this.btnsrc.Font = new System.Drawing.Font("Times New Roman", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.btnsrc.Location = new System.Drawing.Point(25, 19); this.btnsrc.Name = "btnsrc"; this.btnsrc.Size = new System.Drawing.Size(147, 25); this.btnsrc.TabIndex = 0; this.btnsrc.Text = "Browse ISO Source File"; this.btnsrc.UseVisualStyleBackColor = true; this.btnsrc.Click += new System.EventHandler(this.btnsrc_Click); this.btnsrc.MouseHover += new System.EventHandler(this.btnsrc_MouseHover); // // label1 // this.label1.AutoSize = true; this.label1.BackColor = System.Drawing.Color.Transparent; this.label1.Font = new System.Drawing.Font("Times New Roman", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.Location = new System.Drawing.Point(469, 34); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(180, 19); this.label1.TabIndex = 20; this.label1.Text = "Upload ISO - On Demand"; // // label9 // this.label9.AutoSize = true; this.label9.BackColor = System.Drawing.Color.Transparent; this.label9.Font = new System.Drawing.Font("Times New Roman", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label9.Location = new System.Drawing.Point(512, 383); this.label9.Name = "label9"; this.label9.Size = new System.Drawing.Size(95, 15); this.label9.TabIndex = 8; this.label9.Text = "Overall Progress"; // // progressBar1 // this.progressBar1.Location = new System.Drawing.Point(170, 405); this.progressBar1.Name = "progressBar1"; this.progressBar1.Size = new System.Drawing.Size(777, 15); this.progressBar1.TabIndex = 7; // // help // this.help.Font = new System.Drawing.Font("Times New Roman", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.help.Image = global::GUI_OVFTOOL.Properties.Resources.vcd_help; this.help.Location = new System.Drawing.Point(530, 166); this.help.Name = "help"; this.help.Size = new System.Drawing.Size(27, 26); this.help.TabIndex = 81; this.help.UseVisualStyleBackColor = true; this.help.Click += new System.EventHandler(this.help_Click); // // label10 // this.label10.AutoSize = true; this.label10.BackColor = System.Drawing.Color.Transparent; this.label10.Font = new System.Drawing.Font("Times New Roman", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label10.ForeColor = System.Drawing.Color.Red; this.label10.Location = new System.Drawing.Point(6, 24); this.label10.Name = "label10"; this.label10.Size = new System.Drawing.Size(14, 15); this.label10.TabIndex = 82; this.label10.Text = "*"; // // label11 // this.label11.AutoSize = true; this.label11.BackColor = System.Drawing.Color.Transparent; this.label11.Font = new System.Drawing.Font("Times New Roman", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label11.ForeColor = System.Drawing.Color.Red; this.label11.Location = new System.Drawing.Point(6, 75); this.label11.Name = "label11"; this.label11.Size = new System.Drawing.Size(14, 15); this.label11.TabIndex = 83; this.label11.Text = "*"; // // label12 // this.label12.AutoSize = true; this.label12.BackColor = System.Drawing.Color.Transparent; this.label12.Font = new System.Drawing.Font("Times New Roman", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label12.ForeColor = System.Drawing.Color.Red; this.label12.Location = new System.Drawing.Point(6, 125); this.label12.Name = "label12"; this.label12.Size = new System.Drawing.Size(14, 15); this.label12.TabIndex = 84; this.label12.Text = "*"; // // label13 // this.label13.AutoSize = true; this.label13.BackColor = System.Drawing.Color.Transparent; this.label13.Font = new System.Drawing.Font("Times New Roman", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label13.ForeColor = System.Drawing.Color.Red; this.label13.Location = new System.Drawing.Point(588, 73); this.label13.Name = "label13"; this.label13.Size = new System.Drawing.Size(14, 15); this.label13.TabIndex = 85; this.label13.Text = "*"; // // label14 // this.label14.AutoSize = true; this.label14.BackColor = System.Drawing.Color.Transparent; this.label14.Font = new System.Drawing.Font("Times New Roman", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label14.ForeColor = System.Drawing.Color.Red; this.label14.Location = new System.Drawing.Point(6, 172); this.label14.Name = "label14"; this.label14.Size = new System.Drawing.Size(14, 15); this.label14.TabIndex = 86; this.label14.Text = "*"; // // chklog // this.chklog.AutoSize = true; this.chklog.BackColor = System.Drawing.Color.Transparent; this.chklog.Font = new System.Drawing.Font("Times New Roman", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.chklog.ForeColor = System.Drawing.Color.Blue; this.chklog.Location = new System.Drawing.Point(37, 364); this.chklog.Name = "chklog"; this.chklog.Size = new System.Drawing.Size(92, 19); this.chklog.TabIndex = 2; this.chklog.Text = "Enable Logs"; this.chklog.UseVisualStyleBackColor = false; this.chklog.CheckedChanged += new System.EventHandler(this.chklog_CheckedChanged); // // btnlog // this.btnlog.Font = new System.Drawing.Font("Times New Roman", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.btnlog.Location = new System.Drawing.Point(898, 360); this.btnlog.Name = "btnlog"; this.btnlog.Size = new System.Drawing.Size(140, 29); this.btnlog.TabIndex = 5; this.btnlog.Text = "Export Diagnostic Logs"; this.btnlog.UseVisualStyleBackColor = true; this.btnlog.Visible = false; this.btnlog.Click += new System.EventHandler(this.button1_Click); // // backgroundWorker1 // this.backgroundWorker1.WorkerReportsProgress = true; this.backgroundWorker1.WorkerSupportsCancellation = true; this.backgroundWorker1.DoWork += new System.ComponentModel.DoWorkEventHandler(this.backgroundWorker1_DoWork); this.backgroundWorker1.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(this.backgroundWorker1_ProgressChanged); this.backgroundWorker1.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.backgroundWorker1_RunWorkerCompleted); // // cmblog // this.cmblog.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cmblog.Font = new System.Drawing.Font("Times New Roman", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.cmblog.ForeColor = System.Drawing.SystemColors.ControlText; this.cmblog.FormattingEnabled = true; this.cmblog.Items.AddRange(new object[] { "verbose", "trivia"}); this.cmblog.Location = new System.Drawing.Point(261, 362); this.cmblog.Name = "cmblog"; this.cmblog.Size = new System.Drawing.Size(194, 23); this.cmblog.TabIndex = 3; this.cmblog.Visible = false; // // groupBox1 // this.groupBox1.BackColor = System.Drawing.Color.Transparent; this.groupBox1.Controls.Add(this.btn_vdc_cat); this.groupBox1.Controls.Add(this.cmbcat); this.groupBox1.Controls.Add(this.cmbvdc); this.groupBox1.Controls.Add(this.label17); this.groupBox1.Controls.Add(this.label16); this.groupBox1.Controls.Add(this.label15); this.groupBox1.Controls.Add(this.label14); this.groupBox1.Controls.Add(this.label13); this.groupBox1.Controls.Add(this.label12); this.groupBox1.Controls.Add(this.label11); this.groupBox1.Controls.Add(this.label10); this.groupBox1.Controls.Add(this.help); this.groupBox1.Controls.Add(this.txtpwd); this.groupBox1.Controls.Add(this.txtui); this.groupBox1.Controls.Add(this.label8); this.groupBox1.Controls.Add(this.label7); this.groupBox1.Controls.Add(this.txtapp); this.groupBox1.Controls.Add(this.txtorg); this.groupBox1.Controls.Add(this.txtdtn); this.groupBox1.Controls.Add(this.txtsrc); this.groupBox1.Controls.Add(this.label5); this.groupBox1.Controls.Add(this.label6); this.groupBox1.Controls.Add(this.label4); this.groupBox1.Controls.Add(this.label3); this.groupBox1.Controls.Add(this.label2); this.groupBox1.Controls.Add(this.btnsrc); this.groupBox1.Font = new System.Drawing.Font("Times New Roman", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.groupBox1.Location = new System.Drawing.Point(12, 81); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(1077, 213); this.groupBox1.TabIndex = 0; this.groupBox1.TabStop = false; // // btn_vdc_cat // this.btn_vdc_cat.Location = new System.Drawing.Point(591, 106); this.btn_vdc_cat.Name = "btn_vdc_cat"; this.btn_vdc_cat.Size = new System.Drawing.Size(138, 23); this.btn_vdc_cat.TabIndex = 92; this.btn_vdc_cat.Text = "Get VDC and Catalog"; this.btn_vdc_cat.UseVisualStyleBackColor = true; this.btn_vdc_cat.Click += new System.EventHandler(this.btn_vdc_cat_Click); // // cmbcat // this.cmbcat.Enabled = false; this.cmbcat.FormattingEnabled = true; this.cmbcat.Location = new System.Drawing.Point(742, 140); this.cmbcat.Name = "cmbcat"; this.cmbcat.Size = new System.Drawing.Size(275, 23); this.cmbcat.TabIndex = 91; // // cmbvdc // this.cmbvdc.Enabled = false; this.cmbvdc.FormattingEnabled = true; this.cmbvdc.Location = new System.Drawing.Point(742, 186); this.cmbvdc.Name = "cmbvdc"; this.cmbvdc.Size = new System.Drawing.Size(275, 23); this.cmbvdc.TabIndex = 90; // // label17 // this.label17.AutoSize = true; this.label17.BackColor = System.Drawing.Color.Transparent; this.label17.Font = new System.Drawing.Font("Times New Roman", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label17.ForeColor = System.Drawing.Color.Red; this.label17.Location = new System.Drawing.Point(588, 190); this.label17.Name = "label17"; this.label17.Size = new System.Drawing.Size(14, 15); this.label17.TabIndex = 89; this.label17.Text = "*"; // // label16 // this.label16.AutoSize = true; this.label16.BackColor = System.Drawing.Color.Transparent; this.label16.Font = new System.Drawing.Font("Times New Roman", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label16.ForeColor = System.Drawing.Color.Red; this.label16.Location = new System.Drawing.Point(588, 22); this.label16.Name = "label16"; this.label16.Size = new System.Drawing.Size(14, 15); this.label16.TabIndex = 88; this.label16.Text = "*"; // // label15 // this.label15.AutoSize = true; this.label15.BackColor = System.Drawing.Color.Transparent; this.label15.Font = new System.Drawing.Font("Times New Roman", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label15.ForeColor = System.Drawing.Color.Red; this.label15.Location = new System.Drawing.Point(588, 142); this.label15.Name = "label15"; this.label15.Size = new System.Drawing.Size(14, 15); this.label15.TabIndex = 87; this.label15.Text = "*"; // // groupBox2 // this.groupBox2.BackColor = System.Drawing.Color.Transparent; this.groupBox2.Controls.Add(this.txtsynx); this.groupBox2.Controls.Add(this.btnrun); this.groupBox2.Location = new System.Drawing.Point(13, 302); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(1075, 47); this.groupBox2.TabIndex = 4; this.groupBox2.TabStop = false; // // ISO_UpldVCD_ondem // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackgroundImage = global::GUI_OVFTOOL.Properties.Resources.template; this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; this.ClientSize = new System.Drawing.Size(1119, 741); this.Controls.Add(this.groupBox2); this.Controls.Add(this.groupBox1); this.Controls.Add(this.cmblog); this.Controls.Add(this.btnlog); this.Controls.Add(this.chklog); this.Controls.Add(this.progressBar1); this.Controls.Add(this.label9); this.Controls.Add(this.txtres); this.Controls.Add(this.label1); this.DoubleBuffered = true; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Name = "ISO_UpldVCD_ondem"; this.Text = "OVF - Migration Tool"; this.Load += new System.EventHandler(this.ISO_UpldVCD_Load); this.KeyUp += new System.Windows.Forms.KeyEventHandler(this.ISO_UpldVCD_KeyUp); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.groupBox2.ResumeLayout(false); this.groupBox2.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.TextBox txtpwd; private System.Windows.Forms.TextBox txtui; private System.Windows.Forms.Label label8; private System.Windows.Forms.Label label7; private System.Windows.Forms.TextBox txtres; private System.Windows.Forms.TextBox txtsynx; private System.Windows.Forms.Button btnrun; private System.Windows.Forms.TextBox txtapp; private System.Windows.Forms.TextBox txtorg; private System.Windows.Forms.TextBox txtdtn; private System.Windows.Forms.TextBox txtsrc; private System.Windows.Forms.Label label5; private System.Windows.Forms.Label label6; private System.Windows.Forms.OpenFileDialog openFileDialog1; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label2; private System.Windows.Forms.Button btnsrc; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label9; private System.Windows.Forms.ProgressBar progressBar1; private System.Windows.Forms.ToolTip toolTip1; private System.Windows.Forms.Button help; private System.Windows.Forms.Label label10; private System.Windows.Forms.Label label11; private System.Windows.Forms.Label label12; private System.Windows.Forms.Label label13; private System.Windows.Forms.Label label14; private System.Windows.Forms.CheckBox chklog; private System.Windows.Forms.Button btnlog; private System.ComponentModel.BackgroundWorker backgroundWorker1; private System.Windows.Forms.ComboBox cmblog; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.Label label16; private System.Windows.Forms.Label label17; private System.Windows.Forms.Label label15; private System.Windows.Forms.Button btn_vdc_cat; private System.Windows.Forms.ComboBox cmbcat; private System.Windows.Forms.ComboBox cmbvdc; } }
53.956376
167
0.587381
[ "MIT" ]
internsaccount/ovfwrapper
ISO_UpldVCD_ondem.Designer.cs
32,160
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/UIAnimation.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace TerraFX.Interop { [Guid("83FA9B74-5F86-4618-BC6A-A2FAC19B3F44")] [NativeTypeName("struct IUIAnimationPriorityComparison : IUnknown")] [NativeInheritance("IUnknown")] public unsafe partial struct IUIAnimationPriorityComparison { public void** lpVtbl; [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(0)] [return: NativeTypeName("HRESULT")] public int QueryInterface([NativeTypeName("const IID &")] Guid* riid, void** ppvObject) { return ((delegate* unmanaged<IUIAnimationPriorityComparison*, Guid*, void**, int>)(lpVtbl[0]))((IUIAnimationPriorityComparison*)Unsafe.AsPointer(ref this), riid, ppvObject); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(1)] [return: NativeTypeName("ULONG")] public uint AddRef() { return ((delegate* unmanaged<IUIAnimationPriorityComparison*, uint>)(lpVtbl[1]))((IUIAnimationPriorityComparison*)Unsafe.AsPointer(ref this)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(2)] [return: NativeTypeName("ULONG")] public uint Release() { return ((delegate* unmanaged<IUIAnimationPriorityComparison*, uint>)(lpVtbl[2]))((IUIAnimationPriorityComparison*)Unsafe.AsPointer(ref this)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(3)] [return: NativeTypeName("HRESULT")] public int HasPriority(IUIAnimationStoryboard* scheduledStoryboard, IUIAnimationStoryboard* newStoryboard, UI_ANIMATION_PRIORITY_EFFECT priorityEffect) { return ((delegate* unmanaged<IUIAnimationPriorityComparison*, IUIAnimationStoryboard*, IUIAnimationStoryboard*, UI_ANIMATION_PRIORITY_EFFECT, int>)(lpVtbl[3]))((IUIAnimationPriorityComparison*)Unsafe.AsPointer(ref this), scheduledStoryboard, newStoryboard, priorityEffect); } } }
45.365385
285
0.710894
[ "MIT" ]
DaZombieKiller/terrafx.interop.windows
sources/Interop/Windows/um/UIAnimation/IUIAnimationPriorityComparison.cs
2,361
C#
using System.Collections.Generic; using System.Threading.Tasks; namespace SparkPost { public interface IRecipientLists { /// <summary> /// Creates a recipient list. /// </summary> /// <param name="recipientList">The properties of the recipientList to create.</param> /// <returns>The response from the API.</returns> Task<SendRecipientListsResponse> Create(RecipientList recipientList); /// <summary> /// Retrieves a recipient list. /// </summary> /// <param name="recipientListsId">The id of the recipient list to retrieve.</param> /// <returns>The response from the API.</returns> Task<RecipientList> Retrieve(string recipientListsId); /// <summary> /// Deletes a recipient list. /// </summary> /// <param name="id"></param> /// <returns>A success or failure.</returns> Task<bool> Delete(string id); /// <summary> /// Updates a recipient list. /// </summary> /// <param name="recipientList"></param> /// <returns></returns> Task<UpdateRecipientListResponse> Update(RecipientList recipientList); } }
33.583333
94
0.599669
[ "Apache-2.0" ]
pedrommuller/csharp-sparkpost
src/SparkPost/IRecipientLists.cs
1,211
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("Rent a car")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Rent a car")] [assembly: AssemblyCopyright("Copyright © 2022")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: ComVisible(false)]
35.758621
84
0.736741
[ "MIT" ]
gabrijelvlasicek/Rent-A-car
Properties/AssemblyInfo.cs
1,040
C#
using System.Runtime.CompilerServices; using Unity.Mathematics; namespace MaxMath { unsafe public static partial class maxmath { /// <summary> Returns a <see cref="bool"/> indicating for a <see cref="half"/> whether it is an infinite floating point value. </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool isinf(half h) { return (h.value & 0x7FFF) == 0x7C00; } /// <summary> Returns a <see cref="bool"/> indicating for a <see cref="half"/> whether it is a finite floating point value. </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool isfinite(half h) { return (h.value & 0x7FFF) < 0x7C00; } ///<summary> Returns a <see cref="bool"/> indicating for a <see cref="half"/> whether it is a NaN (not a number) floating point value. </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool isnan(half h) { return (h.value & 0x7FFF) > 0x7C00; } ///<summary> Returns a <see cref="bool2"/> indicating for each component of a <see cref="half2"/> whether it is an infinite floating point value. </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool2 isinf(half2 h) { return (asushort(h) & 0x7FFF) == 0x7C00; } ///<summary> Returns a <see cref="bool2"/> indicating for each component of a <see cref="half2"/> whether it is a finite floating point value. </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool2 isfinite(half2 h) { return (asushort(h) & 0x7FFF) < 0x7C00; } ///<summary> Returns a <see cref="bool2"/> indicating for each component of a <see cref="half2"/> whether it is a NaN (not a number) floating point value. </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool2 isnan(half2 h) { return (asushort(h) & 0x7FFF) > 0x7C00; } ///<summary> Returns a <see cref="bool3"/> indicating for each component of a <see cref="half3"/> whether it is an infinite floating point value. </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool3 isinf(half3 h) { return (asushort(h) & 0x7FFF) == 0x7C00; } ///<summary> Returns a <see cref="bool3"/> indicating for each component of a <see cref="half3"/> whether it is a finite floating point value. </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool3 isfinite(half3 h) { return (asushort(h) & 0x7FFF) < 0x7C00; } ///<summary> Returns a <see cref="bool3"/> indicating for each component of a <see cref="half3"/> whether it is a NaN (not a number) floating point value. </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool3 isnan(half3 h) { return (asushort(h) & 0x7FFF) > 0x7C00; } ///<summary> Returns a <see cref="bool4"/> indicating for each component of a <see cref="half4"/> whether it is an infinite floating point value. </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool4 isinf(half4 h) { return (asushort(h) & 0x7FFF) == 0x7C00; } ///<summary> Returns a <see cref="bool4"/> indicating for each component of a <see cref="half4"/> whether it is a finite floating point value. </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool4 isfinite(half4 h) { return (asushort(h) & 0x7FFF) < 0x7C00; } ///<summary> Returns a <see cref="bool4"/> indicating for each component of a <see cref="half4"/> whether it is a NaN (not a number) floating point value. </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool4 isnan(half4 h) { return (asushort(h) & 0x7FFF) > 0x7C00; } ///<summary> Returns a <see cref="MaxMath.bool8"/> indicating for each component of a <see cref="MaxMath.half8"/> whether it is an infinite floating point value. </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool8 isinf(half8 h) { return (asushort(h) & 0x7FFF) == 0x7C00; } ///<summary> Returns a <see cref="MaxMath.bool8"/> indicating for each component of a <see cref="MaxMath.half8"/> whether it is a finite floating point value. </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool8 isfinite(half8 h) { return (asushort(h) & 0x7FFF) < 0x7C00; } ///<summary> Returns a <see cref="MaxMath.bool8"/> indicating for each component of a <see cref="MaxMath.half8"/> whether it is a NaN (not a number) floating point value. </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool8 isnan(half8 h) { return (asushort(h) & 0x7FFF) > 0x7C00; } } }
46.931624
199
0.603533
[ "Apache-2.0" ]
MrUnbelievable92/MaxMath
Runtime/Functions/Arithmetic/Floating Point/half Utilty.cs
5,493
C#