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 static TACTLib.Core.Product.Tank.ManifestCryptoHandler; using static TACTLib.Core.Product.Tank.ResourceGraph; namespace TACTLib.Core.Product.Tank.TRG { [ManifestCrypto(AutoDetectVersion = true, Product = TACTProduct.Overwatch)] public class ProTRG_80550 : ITRGEncryptionProc { public byte[] Key(TRGHeader header, int length) { byte[] buffer = new byte[length]; uint kidx, okidx; kidx = okidx = Keytable[header.m_buildVersion & 511]; for (uint i = 0; i != length; ++i) { buffer[i] = Keytable[SignedMod(kidx, 512)]; kidx += (uint)header.m_packageCount; } return buffer; } public byte[] IV(TRGHeader header, byte[] digest, int length) { byte[] buffer = new byte[length]; uint kidx, okidx; kidx = okidx = Keytable[((3 * digest[11]) - length) & 511]; for (int i = 0; i != length; ++i) { buffer[i] = Keytable[SignedMod(kidx, 512)]; kidx += okidx % 29; buffer[i] ^= (byte)(digest[SignedMod(kidx + header.m_buildVersion, SHA1_DIGESTSIZE)] + 1); } return buffer; } private static readonly byte[] Keytable = { 0x87, 0xD3, 0x74, 0xCE, 0xEF, 0x52, 0x8A, 0x14, 0x22, 0x05, 0x10, 0xDB, 0xE8, 0xCC, 0xD5, 0x8F, 0xEE, 0xB5, 0x66, 0x7C, 0x01, 0x27, 0x57, 0xCD, 0x5E, 0x18, 0x57, 0xCA, 0x9E, 0x48, 0xD8, 0x9C, 0x63, 0x27, 0xE1, 0x7C, 0x81, 0x83, 0x4D, 0xF7, 0x0A, 0xF1, 0xB1, 0xC6, 0xDA, 0xB3, 0x0C, 0x79, 0xCE, 0x9A, 0x15, 0xBA, 0xDA, 0x2D, 0xA8, 0x8A, 0x3D, 0x9B, 0x48, 0x3A, 0x1F, 0x25, 0x86, 0x52, 0x9D, 0x45, 0x39, 0xF2, 0xB1, 0xC2, 0xB6, 0x04, 0x92, 0xCB, 0x46, 0x63, 0xB6, 0x7D, 0xE4, 0xA2, 0xCB, 0x8D, 0x63, 0x1C, 0x26, 0xE6, 0x4B, 0x44, 0x76, 0x5A, 0x8C, 0xD3, 0x1C, 0xA5, 0xB7, 0x21, 0x7A, 0x3E, 0xDF, 0x75, 0xCF, 0xE0, 0x70, 0x2A, 0xE0, 0xDE, 0x51, 0x4F, 0x20, 0x3A, 0x7E, 0x14, 0xC6, 0xB5, 0x3E, 0xD3, 0xA8, 0x19, 0xE8, 0xD8, 0xC3, 0x2E, 0xF6, 0x64, 0xA5, 0x17, 0xDF, 0x84, 0x54, 0x58, 0x1D, 0x2D, 0x86, 0x46, 0xF8, 0x64, 0xF0, 0xB9, 0xCA, 0x27, 0x75, 0xAB, 0x07, 0xC6, 0x1C, 0x86, 0xF3, 0x95, 0x48, 0x4C, 0x1E, 0x8E, 0x1A, 0xAA, 0xE9, 0x8F, 0x85, 0xE9, 0x8A, 0xA0, 0xAF, 0x3B, 0x97, 0x8C, 0x76, 0x13, 0x05, 0xD8, 0x35, 0x5B, 0xAC, 0x68, 0xF7, 0xA7, 0x8B, 0x6F, 0xFB, 0xDA, 0xFB, 0x46, 0x94, 0xB1, 0xC2, 0x9C, 0xCF, 0x27, 0x10, 0xB5, 0x1D, 0x54, 0x72, 0xBD, 0xE1, 0x77, 0xB7, 0xC5, 0x9B, 0x9A, 0xF2, 0x00, 0x7F, 0xF9, 0xAA, 0x67, 0xA9, 0x2E, 0x5E, 0xAD, 0x1E, 0xF2, 0x63, 0x97, 0x40, 0x5B, 0xB2, 0x68, 0x36, 0x25, 0xBC, 0xDB, 0xD7, 0x91, 0x48, 0x7E, 0xEF, 0x6A, 0x6F, 0x34, 0x4E, 0x7F, 0xD9, 0x69, 0x4A, 0xB2, 0xAA, 0xC2, 0xC2, 0x39, 0x0C, 0x94, 0x34, 0x62, 0x09, 0x46, 0x8F, 0x5A, 0x0B, 0x16, 0xA1, 0xF8, 0x2C, 0x71, 0x66, 0x78, 0xD1, 0x4A, 0xD4, 0x72, 0x47, 0x4B, 0x87, 0xAD, 0x64, 0x4E, 0xDC, 0x5A, 0x8F, 0x5C, 0x4B, 0x53, 0x98, 0x3C, 0x5C, 0x40, 0x96, 0xDE, 0xE4, 0x29, 0xFF, 0x55, 0x3D, 0x5A, 0x4B, 0xA7, 0x8A, 0x83, 0xD8, 0x6F, 0x64, 0x46, 0x5F, 0xD6, 0xD8, 0x2F, 0x60, 0x13, 0x10, 0x6B, 0x30, 0x6D, 0x83, 0x49, 0xD2, 0xD2, 0xB4, 0x41, 0xD2, 0x4D, 0xAD, 0x07, 0xE8, 0x1A, 0x78, 0x47, 0xFC, 0x0A, 0x6E, 0xA1, 0x28, 0x50, 0x03, 0x85, 0x85, 0x05, 0x32, 0x8E, 0x80, 0x3A, 0xC1, 0xD1, 0xB3, 0xDE, 0xF6, 0x02, 0x03, 0x68, 0xBC, 0xF7, 0xAD, 0x39, 0x6C, 0xDA, 0x0D, 0x43, 0xA4, 0x15, 0x8E, 0x19, 0x14, 0xBE, 0xD6, 0xB4, 0x81, 0xCA, 0x71, 0xDB, 0xDA, 0x9E, 0x62, 0xE5, 0x64, 0x28, 0xDA, 0x85, 0x15, 0xFA, 0xF7, 0xBE, 0x91, 0x86, 0x6A, 0x7F, 0xC6, 0x92, 0xFE, 0x8B, 0x5D, 0xE8, 0xF8, 0x87, 0x88, 0x1D, 0xE3, 0x2B, 0xC5, 0x79, 0x95, 0xDB, 0x62, 0x2B, 0xFD, 0x45, 0x6D, 0xB0, 0xB4, 0x92, 0x2C, 0x0D, 0xF8, 0x17, 0xBB, 0x0C, 0xCB, 0x87, 0x77, 0xC2, 0xB3, 0x84, 0x99, 0x4B, 0x90, 0x01, 0x14, 0xF2, 0x77, 0x9A, 0x4C, 0xCB, 0xC7, 0xA1, 0x5C, 0x3C, 0xEC, 0xE5, 0x43, 0x98, 0x6F, 0x5B, 0x6A, 0xE5, 0x48, 0x25, 0x90, 0x36, 0x0C, 0x44, 0xED, 0x34, 0x53, 0x5C, 0x1F, 0xC9, 0x36, 0xC7, 0x30, 0xE6, 0x81, 0x08, 0x72, 0x99, 0xCD, 0x76, 0xB3, 0x0E, 0x7D, 0xF8, 0xFB, 0x09, 0x89, 0x0A, 0x0A, 0xBC, 0xFD, 0xDE, 0x57, 0xE5, 0x15, 0x83, 0xB5, 0x49, 0x4E, 0x17, 0x6C, 0x37, 0xC9, 0x5A, 0x6A, 0xB5, 0x17, 0x30, 0x3C, 0x3E, 0x15, 0x54, 0x82, 0x7E, 0xCB, 0x01, 0x95, 0x77, 0x66, 0xBE, 0xB5, 0x4B, 0x2A, 0xA4, 0xDE, 0xDA, 0x35, 0xA4, 0x35, 0x3F, 0x11, 0x23, 0x04, 0x41, 0xE7, 0x05, 0x0B, 0x53, 0x76, 0x85 }; } }
58.876712
99
0.644951
[ "MIT" ]
HellPie/TACTLib
TACTLib/Core/Product/Tank/TRG/ProTRG_80550.cs
4,298
C#
using PlasticApps.Components; using PlasticApps.Components.Ease; using Unity.Entities; using Unity.Jobs; using Unity.Mathematics; using PlasticApps.Systems.Groups; using Unity.Burst; namespace PlasticApps.Systems.Ease { [UpdateInGroup(typeof(TweenEasesSystems))] public class EaseInOutBackSystem : JobComponentSystem { [BurstCompile] [ExcludeComponent(typeof(TweenPaused), typeof(TweenComplete))] [RequireComponentTag(typeof(TweenEaseInOutBack))] struct EaseJob : IJobForEach<TweenBase> { public void Execute(ref TweenBase tween) { float value = tween.NormalizedTime; float s = 1.70158f; value /= .5f; if (value < 1) { s *= 1.525f; tween.Value = 0.5f * (value * value * ((s + 1) * value - s)); } else { value -= 2; s *= (1.525f); tween.Value = 0.5f * (value * value * ((s + 1) * value + s) + 2); } } } protected override JobHandle OnUpdate(JobHandle inputDeps) { var job = new EaseJob(); return job.Schedule(this, inputDeps); } } }
30.136364
85
0.514329
[ "MIT" ]
Hengle/PlasticTween
Assets/PlasticApps/Systems/Ease/Back/EaseInOutBackSystem.cs
1,328
C#
namespace DevMark.Model.SystemInformation { public class CpuInfo { public string Name { get; set; } public string Description { get; set; } public string Architecture { get; set; } public int MaxClockSpeed { get; set; } public int CurrentClockSpeed { get; set; } public int Cores { get; set; } public int LogicalProcessors { get; set; } public string Socket { get; set; } } }
30.2
50
0.602649
[ "Apache-2.0" ]
Johand86/DevMark
Source/DevMark.Model/SystemInformation/CpuInfo.cs
455
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace bluebean.UGFramework { public class ThreeDSceneLayer : SceneLayer { public override Camera LayerCamera { get { var cameras = GetComponentsInChildren<Camera>(); if(cameras.Length == 0) { return null; } return cameras[0]; } } } }
20.5
64
0.497967
[ "MIT" ]
CyberSys/Mugen3D
Client/Assets/Framework/SceneTree/Scripts/ThreeDSceneLayer.cs
494
C#
using UnityEngine; using System.Collections; public class ScreenTouch : MonoBehaviour { void OnEnable(){ EasyTouch.On_TouchStart += On_TouchStart; } void OnDisable(){ UnsubscribeEvent(); } void OnDestroy(){ UnsubscribeEvent(); } void UnsubscribeEvent(){ EasyTouch.On_TouchStart -= On_TouchStart; } // Simple tap message void On_TouchStart(Gesture gesture){ if (gesture.pickObject==null){ // Transforms 2D coordinate tap position in 3D world position Vector3 position = gesture.GetTouchToWordlPoint(8); // ... GameObject sphere = Instantiate(Resources.Load("GlowDisk01"), position , Quaternion.identity) as GameObject; float size = Random.Range(0.5f,0.8f); sphere.transform.localScale = new Vector3(size,size,size); GameObject spot= Instantiate(Resources.Load("Spot"), position , Quaternion.identity) as GameObject; spot.transform.localScale = sphere.transform.localScale/2; spot.transform.SetParent(sphere.transform); // Random color int rndColor = Random.Range(1,6); Color color = Color.white; switch (rndColor){ case 1: color = new Color(1, Random.Range(0.0f,0.8f),Random.Range(0.0f,0.8f), Random.Range(0.3f,0.9f)); break; case 2: color = new Color(Random.Range(0.0f,0.8f),1,Random.Range(0.0f,0.8f), Random.Range(0.3f,0.9f)); break; case 3: color = new Color(Random.Range(0.0f,0.8f),1,1, Random.Range(0.3f,0.9f)); break; case 4: color = new Color(1,Random.Range(0.0f,0.8f),1, Random.Range(0.3f,0.9f)); break; case 5: color = new Color(1,Random.Range(0.0f,0.8f),Random.Range(0.0f,0.8f), Random.Range(0.3f,0.9f)); break; case 6: color = new Color(Random.Range(0.0f,0.8f),Random.Range(0.0f,0.8f),1, Random.Range(0.3f,0.9f)); break; } sphere.GetComponent<Renderer>().material.SetColor ("_TintColor", color); spot.GetComponent<Renderer>().material.SetColor ("_TintColor",color); // assign the layer for auto detection sphere.layer=8; // Add a script to react with the touchs sphere.AddComponent<ObjectTouch>(); sphere.GetComponent<Rigidbody>().mass = size; } } }
28.363636
111
0.667582
[ "MIT" ]
gdgeek/7dcar
Assets/Addons/EasyTouch/Example/C# Example/Examples for EasyTouch/Example-Multiplefingers/ScreenTouch.cs
2,184
C#
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://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. // Generated code. DO NOT EDIT! namespace Google.Cloud.Talent.V4Beta1.Snippets { using Google.Cloud.Talent.V4Beta1; public sealed partial class GeneratedJobServiceClientStandaloneSnippets { /// <summary>Snippet for CreateJob</summary> /// <remarks> /// This snippet has been automatically generated for illustrative purposes only. /// It may require modifications to work in your environment. /// </remarks> public void CreateJobRequestObject() { // Create client JobServiceClient jobServiceClient = JobServiceClient.Create(); // Initialize request argument(s) CreateJobRequest request = new CreateJobRequest { ParentAsTenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), Job = new Job(), }; // Make the request Job response = jobServiceClient.CreateJob(request); } } }
36.837209
91
0.662879
[ "Apache-2.0" ]
googleapis/googleapis-gen
google/cloud/talent/v4beta1/google-cloud-talent-v4beta1-csharp/Google.Cloud.Talent.V4Beta1.StandaloneSnippets/JobServiceClient.CreateJobRequestObjectSnippet.g.cs
1,584
C#
using Microsoft.EntityFrameworkCore.Migrations; namespace P5.Migrations { public partial class InitialMigration : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Customers", columns: table => new { CustId = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), CustName = table.Column<string>(type: "nvarchar(max)", nullable: true), CustPassword = table.Column<string>(type: "nvarchar(max)", nullable: true) }, constraints: table => { table.PrimaryKey("PK_Customers", x => x.CustId); }); migrationBuilder.CreateTable( name: "Products", columns: table => new { ProdId = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), ProdName = table.Column<string>(type: "nvarchar(max)", nullable: true), ProdPrice = table.Column<double>(type: "float", nullable: false) }, constraints: table => { table.PrimaryKey("PK_Products", x => x.ProdId); }); migrationBuilder.CreateTable( name: "Baskets", columns: table => new { BasketId = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), BasketStatus = table.Column<string>(type: "nvarchar(max)", nullable: true), CustId = table.Column<int>(type: "int", nullable: false) }, constraints: table => { table.PrimaryKey("PK_Baskets", x => x.BasketId); table.ForeignKey( name: "FK_Baskets_Customers_CustId", column: x => x.CustId, principalTable: "Customers", principalColumn: "CustId", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Feedbacks", columns: table => new { FeedId = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), FeedBody = table.Column<string>(type: "nvarchar(max)", nullable: true), CustId = table.Column<int>(type: "int", nullable: false) }, constraints: table => { table.PrimaryKey("PK_Feedbacks", x => x.FeedId); table.ForeignKey( name: "FK_Feedbacks_Customers_CustId", column: x => x.CustId, principalTable: "Customers", principalColumn: "CustId", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Sales", columns: table => new { SaleId = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), SaleStatus = table.Column<string>(type: "nvarchar(max)", nullable: true), CustId = table.Column<int>(type: "int", nullable: false) }, constraints: table => { table.PrimaryKey("PK_Sales", x => x.SaleId); table.ForeignKey( name: "FK_Sales_Customers_CustId", column: x => x.CustId, principalTable: "Customers", principalColumn: "CustId", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "BasketWithProducts", columns: table => new { BasketId = table.Column<int>(type: "int", nullable: false), ProdId = table.Column<int>(type: "int", nullable: false), Name = table.Column<string>(type: "nvarchar(max)", nullable: true), Qty = table.Column<int>(type: "int", nullable: false) }, constraints: table => { table.PrimaryKey("PK_BasketWithProducts", x => new { x.BasketId, x.ProdId }); table.ForeignKey( name: "FK_BasketWithProducts_Baskets_BasketId", column: x => x.BasketId, principalTable: "Baskets", principalColumn: "BasketId", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_BasketWithProducts_Products_ProdId", column: x => x.ProdId, principalTable: "Products", principalColumn: "ProdId", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "SaleWithProducts", columns: table => new { ProdId = table.Column<int>(type: "int", nullable: false), SaleId = table.Column<int>(type: "int", nullable: false), Qty = table.Column<int>(type: "int", nullable: false) }, constraints: table => { table.PrimaryKey("PK_SaleWithProducts", x => new { x.SaleId, x.ProdId }); table.ForeignKey( name: "FK_SaleWithProducts_Products_ProdId", column: x => x.ProdId, principalTable: "Products", principalColumn: "ProdId", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_SaleWithProducts_Sales_SaleId", column: x => x.SaleId, principalTable: "Sales", principalColumn: "SaleId", onDelete: ReferentialAction.Cascade); }); migrationBuilder.InsertData( table: "Customers", columns: new[] { "CustId", "CustName", "CustPassword" }, values: new object[,] { { 1, "Customer1", "123123" }, { 2, "Customer2", "123123" }, { 3, "Customer3", "123123" } }); migrationBuilder.InsertData( table: "Products", columns: new[] { "ProdId", "ProdName", "ProdPrice" }, values: new object[,] { { 1, "Car", 300.0 }, { 2, "Smartphone", 99.989999999999995 }, { 3, "Watch", 30.5 } }); migrationBuilder.CreateIndex( name: "IX_Baskets_CustId", table: "Baskets", column: "CustId"); migrationBuilder.CreateIndex( name: "IX_BasketWithProducts_ProdId", table: "BasketWithProducts", column: "ProdId"); migrationBuilder.CreateIndex( name: "IX_Feedbacks_CustId", table: "Feedbacks", column: "CustId"); migrationBuilder.CreateIndex( name: "IX_Sales_CustId", table: "Sales", column: "CustId"); migrationBuilder.CreateIndex( name: "IX_SaleWithProducts_ProdId", table: "SaleWithProducts", column: "ProdId"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "BasketWithProducts"); migrationBuilder.DropTable( name: "Feedbacks"); migrationBuilder.DropTable( name: "SaleWithProducts"); migrationBuilder.DropTable( name: "Baskets"); migrationBuilder.DropTable( name: "Products"); migrationBuilder.DropTable( name: "Sales"); migrationBuilder.DropTable( name: "Customers"); } } }
40.808219
97
0.453396
[ "Unlicense" ]
drfrank66613/SUTS3-4-1
P5/Migrations/20211204042306_InitialMigration.cs
8,939
C#
using System; using System.Collections.Generic; using System.Collections; /// <summary> /// DictionaryEnumerator.IDictionaryEnumerator.get_Entry /// </summary> public class DictionaryEnumeratorIDictionaryEnumeratorget_Entry { public static int Main() { DictionaryEnumeratorIDictionaryEnumeratorget_Entry dicEnumIDicEnumget_Entry = new DictionaryEnumeratorIDictionaryEnumeratorget_Entry(); TestLibrary.TestFramework.BeginTestCase("DictionaryEnumeratorIDictionaryEnumeratorget_Entry"); if (dicEnumIDicEnumget_Entry.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; return retVal; } #region PositiveTest public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("Return the property get_Entry in the IDictionaryEnumerator 1"); try { Dictionary<string, string> dictionary = new Dictionary<string, string>(); dictionary.Add("str1", "helloworld"); Dictionary<string, string>.Enumerator enumer = dictionary.GetEnumerator(); IDictionaryEnumerator idicEnumer = (IDictionaryEnumerator)enumer; if (idicEnumer.MoveNext()) { DictionaryEntry entryVal = idicEnumer.Entry; if (entryVal.Key.ToString() != "str1" || entryVal.Value.ToString() != "helloworld") { TestLibrary.TestFramework.LogError("001", "the ExpectResult is not the ActualResult"); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("Return the property get_Entry in the IDictionaryEnumerator 2"); try { Dictionary<TestClass,TestClass> dictionary = new Dictionary<TestClass,TestClass>(); TestClass Tkey1 = new TestClass(); TestClass TVal1 = new TestClass(); dictionary.Add(Tkey1,TVal1); Dictionary<TestClass,TestClass>.Enumerator enumer = dictionary.GetEnumerator(); IDictionaryEnumerator idicEnumer = (IDictionaryEnumerator)enumer; if (idicEnumer.MoveNext()) { DictionaryEntry entryVal = idicEnumer.Entry; if (entryVal.Key != Tkey1 || entryVal.Value != TVal1) { TestLibrary.TestFramework.LogError("003", "the ExpectResult is not the ActualResult"); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpect exception:" + e); retVal = false; } return retVal; } #endregion #region NegativeTest public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1:The enumerator is positioned before the first element of the collection"); try { Dictionary<string, string> dictionary = new Dictionary<string, string>(); dictionary.Add("str1", "helloworld"); Dictionary<string, string>.Enumerator enumer = dictionary.GetEnumerator(); IDictionaryEnumerator idicEnumer = (IDictionaryEnumerator)enumer; DictionaryEntry entryVal = idicEnumer.Entry; TestLibrary.TestFramework.LogError("N001", "The enumerator is positioned before the first element of the collection but not throw exception"); retVal = false; } catch (InvalidOperationException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("N002", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool NegTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest2:The enumerator is positioned after the last element of the collection"); try { Dictionary<string, string> dictionary = new Dictionary<string, string>(); dictionary.Add("str1", "helloworld"); Dictionary<string, string>.Enumerator enumer = dictionary.GetEnumerator(); IDictionaryEnumerator idicEnumer = (IDictionaryEnumerator)enumer; if (idicEnumer.MoveNext()) { DictionaryEntry entryVal1 = idicEnumer.Entry; } if (!idicEnumer.MoveNext()) { DictionaryEntry entryVal2 = idicEnumer.Entry; TestLibrary.TestFramework.LogError("N002", "The enumerator is positioned after the last element of the collection but not throw exception"); retVal = false; } } catch (InvalidOperationException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpect exception:" + e); retVal = false; } return retVal; } #endregion #region ForTestClass public class TestClass { } #endregion }
38.109677
156
0.602336
[ "MIT" ]
CyberSys/coreclr-mono
tests/src/CoreMangLib/cti/system/collections/generic/dictionaryenumerator/dictionaryenumeratoridictionaryenumeratorget_entry.cs
5,907
C#
namespace NanoFabric.Docimax.Heroes.Api { internal class Permission { public string Name { get; internal set; } public string Predicate { get; internal set; } public string Url { get; internal set; } } }
26.666667
54
0.633333
[ "MIT" ]
geffzhang/NanoFabric.Docimax
src/NanoFabric.Docimax.Heroes.Api/Permission.cs
242
C#
using System.IO; using NUnit.Framework; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using SlackClient.DependencyInjection; using FluentAssertions; namespace SlackClient.Tests { public class Tests { private ServiceProvider _serviceProvider; [SetUp] public void Setup() { var configurationBuilder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .AddEnvironmentVariables(); var configuration = configurationBuilder.Build(); _serviceProvider = new ServiceCollection() .ConfigureSlackClient(configuration) .BuildServiceProvider(); } [Test] public void ClientMustBeOfExpectedType() { _serviceProvider.GetRequiredService<ISlackClient>().Should().BeOfType<SlackClient>(); } } }
29.514286
97
0.6515
[ "MIT" ]
ivelten/SlackClient
tests/SlackClient.Tests/ServiceCollectionExtensionsTests.cs
1,033
C#
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://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. // Generated code. DO NOT EDIT! namespace Google.Cloud.ContactCenterInsights.V1.Snippets { using Google.Cloud.ContactCenterInsights.V1; public sealed partial class GeneratedContactCenterInsightsClientStandaloneSnippets { /// <summary>Snippet for GetPhraseMatcher</summary> /// <remarks> /// This snippet has been automatically generated for illustrative purposes only. /// It may require modifications to work in your environment. /// </remarks> public void GetPhraseMatcherRequestObject() { // Create client ContactCenterInsightsClient contactCenterInsightsClient = ContactCenterInsightsClient.Create(); // Initialize request argument(s) GetPhraseMatcherRequest request = new GetPhraseMatcherRequest { PhraseMatcherName = PhraseMatcherName.FromProjectLocationPhraseMatcher("[PROJECT]", "[LOCATION]", "[PHRASE_MATCHER]"), }; // Make the request PhraseMatcher response = contactCenterInsightsClient.GetPhraseMatcher(request); } } }
40.809524
134
0.69895
[ "Apache-2.0" ]
googleapis/googleapis-gen
google/cloud/contactcenterinsights/v1/google-cloud-contactcenterinsights-v1-csharp/Google.Cloud.ContactCenterInsights.V1.StandaloneSnippets/ContactCenterInsightsClient.GetPhraseMatcherRequestObjectSnippet.g.cs
1,714
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace Microsoft.EntityFrameworkCore.Diagnostics; /// <summary> /// Combines <see cref="ILogger" /> and <see cref="DiagnosticSource" /> /// for use by all EF Core logging so that events can be sent to both <see cref="ILogger" /> /// for ASP.NET and <see cref="DiagnosticSource" /> for everything else. /// </summary> /// <remarks> /// <para> /// Also intercepts messages such that warnings can be either logged or thrown, and such that a decision as to whether to log /// sensitive data or not can be made. /// </para> /// <para> /// The service lifetime is <see cref="ServiceLifetime.Scoped" />. This means that each /// <see cref="DbContext" /> instance will use its own instance of this service. /// The implementation may depend on other services registered with any lifetime. /// The implementation does not need to be thread-safe. /// </para> /// <para> /// See <see href="https://aka.ms/efcore-docs-providers">Implementation of database providers and extensions</see> /// for more information and examples. /// </para> /// </remarks> public interface IDiagnosticsLogger<TLoggerCategory> : IDiagnosticsLogger where TLoggerCategory : LoggerCategory<TLoggerCategory>, new() { }
46.064516
133
0.673669
[ "MIT" ]
Applesauce314/efcore
src/EFCore/Diagnostics/IDiagnosticsLogger`.cs
1,428
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Polyperfect.People { [ExecuteInEditMode] public class PolyIk : MonoBehaviour { public List<HumanBoneOffset> rotationOffsets = new List<HumanBoneOffset>(); //Ik Targets public Transform leftFootTarget, rightFootTarget, LeftHandTarget, rightHandTarget, lookAtTarget; public Transform leftFootPole, rightFootPole, LeftHandPole, rightHandPole; //Weights [Range(0, 1)] public float rotationWeightLeftFoot, rotationWeightRightFoot, rotationWeightLeftHand, rotationWeightRightHand; [Range(0, 1)] public float lookAtWeight, lookAtHeadWeight, LookAtEyesWeight, rightHandWeight, leftHandWeight, rightFootWeight, leftFootWeight; public bool leftFootIk, lookAtIk, rightHandIk, leftHandIk, rightFootIk; public Animator animator; // Use this for initialization void Start() { animator = GetComponent<Animator>(); if (!animator.isHuman) { this.enabled = false; Debug.Log("The rig needs to be humanoid for this script to work"); } } // Update is called once per frame void Update() { if (Application.isEditor) { animator.Update(0); } } private void OnAnimatorIK(int layerIndex) { SetIkTargetsAndWeights(); foreach (var item in rotationOffsets) { if (item.active) { OffsetSpine(item.bone, item.rotationOffset); } } } void SetIkTargetsAndWeights() { if (leftFootTarget != null && leftFootIk) { animator.SetIKPositionWeight(AvatarIKGoal.LeftFoot, leftFootWeight); animator.SetIKPosition(AvatarIKGoal.LeftFoot, leftFootTarget.position); animator.SetIKRotation(AvatarIKGoal.LeftFoot, leftFootTarget.rotation); animator.SetIKRotationWeight(AvatarIKGoal.LeftFoot, rotationWeightLeftFoot); animator.SetIKHintPosition(AvatarIKHint.LeftKnee, leftFootPole.position); animator.SetIKHintPositionWeight(AvatarIKHint.LeftKnee, leftFootWeight); } if (rightFootTarget != null && rightFootIk) { animator.SetIKPositionWeight(AvatarIKGoal.RightFoot, rightFootWeight); animator.SetIKPosition(AvatarIKGoal.RightFoot, rightFootTarget.position); animator.SetIKRotation(AvatarIKGoal.RightFoot, rightFootTarget.rotation); animator.SetIKRotationWeight(AvatarIKGoal.RightFoot, rotationWeightRightFoot); animator.SetIKHintPosition(AvatarIKHint.RightKnee, rightFootPole.position); animator.SetIKHintPositionWeight(AvatarIKHint.RightKnee, rightFootWeight); } if (LeftHandTarget != null && leftHandIk) { animator.SetIKPositionWeight(AvatarIKGoal.LeftHand, leftHandWeight); animator.SetIKPosition(AvatarIKGoal.LeftHand, LeftHandTarget.position); animator.SetIKRotation(AvatarIKGoal.LeftHand, LeftHandTarget.rotation); animator.SetIKRotationWeight(AvatarIKGoal.LeftHand, rotationWeightLeftHand); animator.SetIKHintPosition(AvatarIKHint.LeftElbow, LeftHandPole.position); animator.SetIKHintPositionWeight(AvatarIKHint.LeftElbow, leftHandWeight); } if (rightHandTarget != null && rightHandIk) { animator.SetIKPositionWeight(AvatarIKGoal.RightHand, rightHandWeight); animator.SetIKPosition(AvatarIKGoal.RightHand, rightHandTarget.position); animator.SetIKRotation(AvatarIKGoal.RightHand, rightHandTarget.rotation); animator.SetIKRotationWeight(AvatarIKGoal.RightHand, rotationWeightRightHand); animator.SetIKHintPosition(AvatarIKHint.RightElbow, rightHandPole.position); animator.SetIKHintPositionWeight(AvatarIKHint.RightElbow, rightHandWeight); } if (lookAtTarget != null && lookAtIk) { animator.SetLookAtWeight(lookAtWeight, 0, lookAtHeadWeight, LookAtEyesWeight, 0); animator.SetLookAtPosition(lookAtTarget.position); } } public void OffsetSpine(HumanBodyBones bone, Vector3 target) { Quaternion startRotation = animator.GetBoneTransform(bone).localRotation; Quaternion targetRotation = Quaternion.Euler(target); animator.SetBoneLocalRotation(bone, Quaternion.Inverse(startRotation) * targetRotation); } } }
40.404959
136
0.640417
[ "MIT" ]
BitHighlander/EthDenverHackathon
EthDenver2022/Assets/polyperfect/Low Poly Animated People/- Scripts/IK/PolyIk.cs
4,891
C#
namespace popp { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; /// <summary> /// Provides some file related extension methods for List<> /// </summary> public static class FileListExtensions { static bool? _fileSystemIsCaseSensitive = null; /// <summary> /// Returns the index of filename in list, or -1 if list does not contain filename. /// If the file system is case-sensitive, then a case-sensitive search will be performed /// </summary> public static int IndexOfFileInList(this List<string> list, string filename) { int result = -1; // No special search optimization is needed, the list will normally be 2 or fewer entries int index = 0; foreach (string item in list) { bool match = FileSystemIsCaseSensitive ? (filename == item) : (filename.ToLowerInvariant() == item.ToLowerInvariant()); if (match) { result = index; break; } index++; } return result; } static bool FileSystemIsCaseSensitive { get { if (_fileSystemIsCaseSensitive == null) { _fileSystemIsCaseSensitive = false; try { string filebase = Path.GetTempPath() + Guid.NewGuid().ToString(); string file1 = filebase + "a"; string file2 = filebase + "A"; File.CreateText(file1).Close(); _fileSystemIsCaseSensitive = !File.Exists(file2); File.Delete(file1); } catch { // Don't care, I tried. } } return _fileSystemIsCaseSensitive.Value; } } } }
30.826087
102
0.475317
[ "MIT" ]
Treer/POpp
popp/FileListExtensions.cs
2,129
C#
/**************************************************************************** * * Copyright (c) 2020 CRI Middleware Co., Ltd. * ****************************************************************************/ using System.Runtime.InteropServices; using System; /*========================================================================== * CRI Atom Native Wrapper *=========================================================================*/ /** * \addtogroup CRIATOM_NATIVE_WRAPPER * @{ */ /** * <summary>AtomExTweenクラス</summary> * <remarks> * <para header='説明'>プレイヤーにアタッチすることで、パラメータのアニメーションを行います。</para> * </remarks> * <seealso cref='CriAtomExPlayer.AttachTween(CriAtomExTween)'/> * <seealso cref='CriAtomExPlayer.DetachTween(CriAtomExTween)'/> * <seealso cref='CriAtomExPlayer.DetachTweenAll'/> */ public class CriAtomExTween : CriDisposable { internal IntPtr nativeHandle { get { return this.handle; } } /** * <summary>Tweenパラメータ種別</summary> */ public enum ParameterType : System.Int32 { /** * <summary>ボリューム、ピッチなど基本的なパラメータの操作</summary> * <seealso cref='CriAtomEx.Parameter'/> */ Basic, /** * <summary>AISACコントロール値の操作</summary> */ Aisac } [StructLayout(LayoutKind.Sequential)] struct Config { public Target target; public ParameterType parameterType; [StructLayout(LayoutKind.Explicit)] public struct Target { [FieldOffset(0)] public CriAtomEx.Parameter parameterId; [FieldOffset(0)] public UInt32 aisacIds; } } /** * <summary>AtomExTweenの作成</summary> * <returns>AtomExTweenオブジェクト</returns> * <remarks> * <para header='備考'>このコンストラクタによって作成されたAtomExTweenはボリュームの操作を行います。</para> * </remarks> */ public CriAtomExTween() : this(CriAtomEx.Parameter.Volume) { } /** * <summary>AtomExTweenの作成(基本パラメータ操作)</summary> * <returns>AtomExTweenオブジェクト</returns> * <param name='parameterId'>パラメータのID</param> * <seealso cref='CriAtomEx.Parameter'/> */ public CriAtomExTween(CriAtomEx.Parameter parameterId) : this(ParameterType.Basic, (UInt32)parameterId) { } /** * <summary>AtomExTweenの作成(AISAC操作)</summary> * <returns>AtomExTweenオブジェクト</returns> * <param name='aisacId'>AISACコントロールID</param> */ public CriAtomExTween(uint aisacId) : this(ParameterType.Aisac, aisacId) { } public CriAtomExTween(ParameterType parameterType, UInt32 targetId) { /* Initialize Library */ if (!CriAtomPlugin.IsLibraryInitialized()) throw new Exception("CriAtomPlugin is not initialized."); /* aplly config */ Config config = new Config(); config.parameterType = parameterType; config.target.parameterId = (CriAtomEx.Parameter)targetId; /* create instance */ handle = criAtomExTween_Create(ref config, IntPtr.Zero, 0); CriDisposableObjectManager.Register(this, CriDisposableObjectManager.ModuleType.Atom); } /** * <summary>AtomExTweenの破棄</summary> * <remarks> * <para header='注意'>AtomExTweenをアタッチしたAtomExPlayerが音声を再生している状態で本関数を実行すると、<br/> * 破棄済みのAtomExTweenへの参照が発生します。 <br/> * 必ずAtomExPlayerからデタッチした後に本関数を実行してください。</para> * </remarks> */ public override void Dispose() { CriDisposableObjectManager.Unregister(this); /* destroy instance */ criAtomExTween_Destroy(handle); handle = IntPtr.Zero; GC.SuppressFinalize(this); } /** * <summary>AtomExTweenが持っているパラメータの現在値を取得</summary> * <returns>パラメータの現在値</returns> */ public float Value { get { return criAtomExTween_GetValue(handle); } } /** * <summary>現在変化中であるかを取得</summary> * <returns>パラメータが変化中であるかどうか</returns> */ public bool IsActive { get { return criAtomExTween_IsActive(handle); } } /** * <summary>パラメータを現在値から指定値に変化</summary> * <remarks> * <para header='説明'>指定した時間をかけて、パラメータを呼び出し時の現在値から指定値まで変化させます。<br/> * 変化カーブタイプはリニア(線形)です。</para> * </remarks> * <param name='durationMs'>変化に要する時間 (ミリ秒)</param> * <param name='value'>変化後の最終値</param> */ public void MoveTo(ushort durationMs, float value) { criAtomExTween_MoveTo(handle, durationMs, value); } /** * <summary>パラメータを指定値から現在値に変化</summary> * <remarks> * <para header='説明'>指定した時間をかけて、パラメータを指定値から呼び出し時の現在値まで変化させます。<br/> * 変化カーブタイプはリニア(線形)です。</para> * </remarks> * <param name='durationMs'>変化に要する時間 (ミリ秒)</param> * <param name='value'>変化前の開始値</param> */ public void MoveFrom(ushort durationMs, float value) { criAtomExTween_MoveFrom(handle, durationMs, value); } /** * <summary>AtomExTweenの停止</summary> * <remarks> * <para header='説明'>AtomExTweenによるパラメータの時間変化を停止します。 <br/> * パラメータの値は停止時の現在値となります。</para> * </remarks> */ public void Stop() { criAtomExTween_Stop(handle); } /** * <summary>AtomExTweenのリセット</summary> * <remarks> * <para header='説明'>AtomExTweenを停止してパラメータを初期値にリセットします。<br/> * 基本パラメータの場合 : 各パラメータの初期値<br/> * AISACコントロール値の場合 : 0.0</para> * </remarks> */ public void Reset() { criAtomExTween_Reset(handle); } #region Internal ~CriAtomExTween() { Dispose(); } IntPtr handle = IntPtr.Zero; #endregion #region DLL Import #if !CRIWARE_ENABLE_HEADLESS_MODE [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] private static extern IntPtr criAtomExTween_Create(ref Config config, IntPtr work, int work_size); [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] private static extern void criAtomExTween_Destroy(IntPtr tween); [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] private static extern Single criAtomExTween_GetValue(IntPtr tween); [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] private static extern void criAtomExTween_MoveTo(IntPtr tween, UInt16 time_ms, Single value); [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] private static extern void criAtomExTween_MoveFrom(IntPtr tween, UInt16 time_ms, Single value); [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] private static extern void criAtomExTween_Stop(IntPtr tween); [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] private static extern void criAtomExTween_Reset(IntPtr tween); [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] private static extern bool criAtomExTween_IsActive(IntPtr tween); #else private static IntPtr criAtomExTween_Create(ref Config config, IntPtr work, int work_size) { return IntPtr.Zero; } private static void criAtomExTween_Destroy(IntPtr tween) { } private static Single criAtomExTween_GetValue(IntPtr tween) { return 0f; } private static void criAtomExTween_MoveTo(IntPtr tween, UInt16 time_ms, Single value) { } private static void criAtomExTween_MoveFrom(IntPtr tween, UInt16 time_ms, Single value) { } private static void criAtomExTween_Stop(IntPtr tween) { } private static void criAtomExTween_Reset(IntPtr tween) { } private static bool criAtomExTween_IsActive(IntPtr tween) { return false; } #endif #endregion } /** * @} */ /* --- end of file --- */
32.222222
119
0.622167
[ "MIT" ]
smpny7/VIVACE
Assets/Plugins/CriWare/CriAtom/NativeClasses/CriAtomExTween.cs
9,302
C#
using System; using GenericRepository.Interfaces; using SqlCodeGenerator.Attributes; namespace PACEWebApiCore.Entities { public class BaseEntity : IEntity { protected BaseEntity() { Created = DateTime.UtcNow; Modified = DateTime.UtcNow; } public DateTime Created { get; set; } public DateTime Modified { get; set; } public string CreatedBy { get; set; } public string ModifiedBy { get; set; } [NonStored] public int TotalCount { get; set; } } }
24.909091
55
0.618613
[ "MIT" ]
firstcrazydeveloper/Temprory
PACE/WebApi/src/PACEWebApiCore.Entities/BaseEntity.cs
550
C#
using UnityEngine; namespace CyberJellyFish.Managers { public abstract class ManagerBase<T> : MonoBehaviour where T : MonoBehaviour { #region VARIABLES [Header("Manager Settings")] [Tooltip("Do Not Destroy this Object when Loading Scenes.")] public bool IsPersistent = false; [Tooltip("Call Initialize Singleton to create a Singleton Instance, only works if DoNotDestroyOnLoad is True.")] public bool IsSingleton = false; private static T _instance; private readonly object _lock = new object(); #endregion #region PROPERTIES public static T Instance { get { if (_instance) return _instance; Debug.LogWarning($"This {_instance.name} is not Initialized. Please use the InitializeSingleton method in Awake."); return null; } } #endregion #region UNITY METHODS public virtual void Awake() { MakePersistent(); } #endregion #region METHODS /// <summary> /// Make this Object Persist regardless of Scene Loading. /// </summary> private void MakePersistent() { if (!IsPersistent) return; if (transform.parent != null) transform.parent = null; DontDestroyOnLoad(this); } /// <summary> /// Initialize the Singleton Instance. Call during Awake! /// </summary> /// <param name="instance"></param> public void InitializeSingleton(T instance) { if (!IsPersistent || !IsSingleton) return; lock (_lock) { if (_instance) return; T[] instances = FindObjectsOfType<T>(); int count = instances.Length; if (count == 0) return; if (count == 1) { _instance = instance; return; } for (int i = 1; i < count; i++) { Destroy(instances[i].gameObject); } _instance = instance; } } #endregion } }
26.275862
131
0.507874
[ "MIT" ]
Macawls/vega_project_2A
Assets/Addons/CyberJellyFish/Scripts/Runtime/Managers/Base/ManagerBase.cs
2,288
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace CarreraAviones { public partial class Aviones : Form { enum Direccion { Izquierda, Derecha }; Direccion direccion; List<PictureBox> enemigos; int distancia; public Aviones() { InitializeComponent(); this.DoubleBuffered = true; distancia = 0; //Generar coleccion de aviones enemigos enemigos = new List<PictureBox>(); enemigos.Add(pic_enemigo_1); enemigos.Add(pic_enemigo_2); enemigos.Add(pic_enemigo_3); enemigos.Add(pic_enemigo_4); enemigos.Add(pic_enemigo_5); foreach (var enemigo in enemigos) { enemigo.Visible = false; enemigo.Top = -enemigo.Height; } } private void Aviones_Load(object sender, EventArgs e) { //rotar las imagenes ya que se encuentran boca arriba pic_enemigo_1.Image.RotateFlip(RotateFlipType.Rotate180FlipX); pic_enemigo_2.Image.RotateFlip(RotateFlipType.Rotate180FlipX); pic_enemigo_3.Image.RotateFlip(RotateFlipType.Rotate180FlipX); pic_enemigo_4.Image.RotateFlip(RotateFlipType.Rotate180FlipX); pic_enemigo_5.Image.RotateFlip(RotateFlipType.Rotate180FlipX); } private void Nube1_Tick(object sender, EventArgs e) { Random enemyRnd = new Random(); distancia++; //Paralax de nubes Random cordY = new Random(); pic_nube_1.Top += 6; pic_nube_2.Top += 4; pic_nube_3.Top += 2; if (pic_nube_1.Top >= this.Height) { pic_nube_1.Top = -pic_nube_1.Height; pic_nube_1.Left = cordY.Next(10, 400); } if (pic_nube_2.Top >= this.Height) { pic_nube_2.Top = -pic_nube_2.Height; pic_nube_2.Left = cordY.Next(10, 400); } if (pic_nube_3.Top >= this.Height) { pic_nube_3.Top = -pic_nube_3.Height; pic_nube_3.Left = cordY.Next(10, 400); } //Movimiento del Jugador switch (direccion) { case Direccion.Izquierda: pic_Jugador.Left -= 5; break; case Direccion.Derecha: pic_Jugador.Left += 5; break; } //control de colision con bordes derecho e izquierdo del formulario if (pic_Jugador.Location.X <= 10) pic_Jugador.Left = 10; if (pic_Jugador.Location.X >= 379) pic_Jugador.Left = 379; //enemigos foreach (var enemigo in enemigos) { var alto = enemigo.Height; if(enemigo.Top > this.Height) { //No esta en la pantalla - vuelve arriba enemigo.Top -= this.Height + enemigo.Height; if (enemyRnd.Next(1, 10) > 5) //basicamente 50% chance que haya un spawn enemigo.Visible = true; else enemigo.Visible = false; } else { enemigo.Top += 6; } } //distancia lbl_Distancia.Text = "Distancia: " + distancia.ToString(); //colision foreach (var enemigo in enemigos) { if (enemigo.Visible) { if (enemigo.Bounds.IntersectsWith(pic_Jugador.Bounds)) { img_explosion.Top = pic_Jugador.Location.Y; img_explosion.Left = pic_Jugador.Location.X; img_explosion.Visible = true; nube1.Stop(); Bun.Visible = true; break; } } } } private void Aviones_KeyDown(object sender, KeyEventArgs e) { switch (e.KeyCode) { case Keys.Left: direccion = Direccion.Izquierda; break; case Keys.Right: direccion = Direccion.Derecha; break; } } } }
27.368715
92
0.472954
[ "MIT" ]
Cactus-ar/C-Sharp-Juegos
CarreraAviones/CarreraAviones/Form1.cs
4,901
C#
using System.Threading; using System.Threading.Tasks; using GS.DecoupleIt.Contextual.UnitOfWork; using GS.DecoupleIt.Operations; using JetBrains.Annotations; using Samples.Clients.Command.Contracts.Events; using Samples.Clients.Command.Model; using Samples.Clients.Command.Model.Entities; namespace Samples.Clients.Command.InternalEventHandlers { internal sealed class ClientCreatedOnEmissionHandler : OnEmissionInternalEventHandlerBase<ClientCreated> { public ClientCreatedOnEmissionHandler([NotNull] IUnitOfWorkAccessor unitOfWorkAccessor) { _unitOfWorkAccessor = unitOfWorkAccessor; } protected override async ValueTask HandleAsync(ClientCreated @event, CancellationToken cancellationToken = default) { await using var context = _unitOfWorkAccessor.Get<ClientsDbContext>(); var clientsBasket = new ClientsBasket(@event.ClientId); await context.AddAsync(clientsBasket, cancellationToken); await context.SaveChangesAsync(cancellationToken); } [NotNull] private readonly IUnitOfWorkAccessor _unitOfWorkAccessor; } }
34.058824
123
0.749568
[ "MIT" ]
krzysztofdudek/DecoupleIt
Samples/Samples.Clients.Command/InternalEventHandlers/ClientCreatedOnEmissionHandler.cs
1,158
C#
/* * Copyright(c) 2017 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace Tizen.NUI { internal class ButtonSignal : global::System.IDisposable { private global::System.Runtime.InteropServices.HandleRef swigCPtr; protected bool swigCMemOwn; internal ButtonSignal(global::System.IntPtr cPtr, bool cMemoryOwn) { swigCMemOwn = cMemoryOwn; swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, cPtr); } internal static global::System.Runtime.InteropServices.HandleRef getCPtr(ButtonSignal obj) { return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr; } //A Flag to check who called Dispose(). (By User or DisposeQueue) private bool isDisposeQueued = false; //A Flat to check if it is already disposed. protected bool disposed = false; ~ButtonSignal() { if (!isDisposeQueued) { isDisposeQueued = true; DisposeQueue.Instance.Add(this); } } public void Dispose() { //Throw excpetion if Dispose() is called in separate thread. if (!Window.IsInstalled()) { throw new System.InvalidOperationException("This API called from separate thread. This API must be called from MainThread."); } if (isDisposeQueued) { Dispose(DisposeTypes.Implicit); } else { Dispose(DisposeTypes.Explicit); System.GC.SuppressFinalize(this); } } protected virtual void Dispose(DisposeTypes type) { if (disposed) { return; } if (type == DisposeTypes.Explicit) { //Called by User //Release your own managed resources here. //You should release all of your own disposable objects here. } //Release your own unmanaged resources here. //You should not access any managed member here except static instance. //because the execution order of Finalizes is non-deterministic. if (swigCPtr.Handle != global::System.IntPtr.Zero) { if (swigCMemOwn) { swigCMemOwn = false; NDalicPINVOKE.delete_ButtonSignal(swigCPtr); } swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero); } disposed = true; } public bool Empty() { bool ret = NDalicPINVOKE.ButtonSignal_Empty(swigCPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } public uint GetConnectionCount() { uint ret = NDalicPINVOKE.ButtonSignal_GetConnectionCount(swigCPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } public void Connect(System.Delegate func) { System.IntPtr ip = System.Runtime.InteropServices.Marshal.GetFunctionPointerForDelegate<System.Delegate>(func); { NDalicPINVOKE.ButtonSignal_Connect(swigCPtr, new System.Runtime.InteropServices.HandleRef(this, ip)); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } } public void Disconnect(System.Delegate func) { System.IntPtr ip = System.Runtime.InteropServices.Marshal.GetFunctionPointerForDelegate<System.Delegate>(func); { NDalicPINVOKE.ButtonSignal_Disconnect(swigCPtr, new System.Runtime.InteropServices.HandleRef(this, ip)); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } } public bool Emit(Tizen.NUI.UIComponents.Button arg) { bool ret = NDalicPINVOKE.ButtonSignal_Emit(swigCPtr, Tizen.NUI.UIComponents.Button.getCPtr(arg)); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } public ButtonSignal() : this(NDalicPINVOKE.new_ButtonSignal(), true) { if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } } }
35.56
141
0.612298
[ "Apache-2.0" ]
EwoutH/TizenFX
src/Tizen.NUI/src/internal/ButtonSignal.cs
5,334
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("Lab_04_AverageDoubles")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Lab_04_AverageDoubles")] [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("ba7f21f0-d61d-4b52-b885-8f6e239131d9")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.108108
84
0.751064
[ "MIT" ]
Brankovanov/SoftUniCourses
3.CSharpAdvanced/08_BuiltInQueryMethodsLINQ/Lab_04_AverageDoubles/Properties/AssemblyInfo.cs
1,413
C#
using OVO.Data.Contracts; namespace OVO.Data { public class SaveContext : ISaveContext { private readonly OVOMsSqlDbContext context; public SaveContext(OVOMsSqlDbContext context) { this.context = context; } public void Commit() { this.context.SaveChanges(); } } }
18
53
0.575
[ "MIT" ]
jorosoft/OnlineVehicleOrganizer
OVO.Data/SaveContext.cs
362
C#
//////////////////////////////////////////////////////////////////////////////// // The MIT License (MIT) // // Copyright (c) 2015 Tim Stair // // 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.Windows.Forms; namespace Support.UI { public static class ControlExtensions { /// <summary> /// Invokes the desired action if required /// </summary> /// <param name="zControl">Control to invoke upon</param> /// <param name="zAction">The Action to take</param> /// <returns>false if the action was invoked, true otherwise</returns> public static bool InvokeActionIfRequired(this Control zControl, Action zAction) { if (zControl.InvokeRequired) { zControl.Invoke(zAction); return false; } return true; } /// <summary> /// Invokes the desired action /// </summary> /// <param name="zControl">Control to invoke upon</param> /// <param name="zAction">The Action to take</param> public static void InvokeAction(this Control zControl, Action zAction) { if (zControl.InvokeRequired) { zControl.Invoke(zAction); } else { zAction(); } } /// <summary> /// Invokes the desired func as necessary /// </summary> /// <typeparam name="T">Template type for return value</typeparam> /// <param name="zControl">Control to invoke upon</param> /// <param name="zFunc">The Func to execute</param> /// <returns>The return value of the Func</returns> public static T InvokeFunc<T>(this Control zControl, Func<T> zFunc) { if (zControl.InvokeRequired) { return(T) zControl.Invoke(zFunc); } return zFunc(); } /// <summary> /// Extensions for string formatting /// </summary> /// <param name="str"></param> /// <param name="list"></param> /// <returns></returns> public static string FormatString(this string str, params object[] list) { return string.Format(str, list); } } }
36.978495
88
0.578947
[ "MIT" ]
nhmkdev/pdfconstruct
PdfConstruct/Support/UI/Extensions.cs
3,439
C#
using System; namespace SBaier.Input { public abstract class PinchInputRegistry : InputRegistry { public abstract void Subscribe(PinchState state, Action<PinchInputEventArgs> listener); public abstract void Unsubscribe(PinchState state, Action<PinchInputEventArgs> listener); } }
28.8
91
0.809028
[ "MIT" ]
BlackLambert/unity-sbaier-input
Input/Assets/Plugins/SBaier/SBaier-Input/Runtime/PinchInput/PinchInputRegistry.cs
290
C#
namespace ModIO.UI { public interface IModRatingAddedReceiver { void OnModRatingAdded(int modId, ModRatingValue rating); } }
18.125
64
0.703448
[ "MIT" ]
DBolical/modioUNITY
Runtime/Interfaces/IModRatingAddedReceiver.cs
145
C#
using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; namespace MoreAsyncLINQ { static partial class MoreAsyncEnumerable { private static async IAsyncEnumerable<TResult> Zip<T1, T2, T3, T4, TResult>( this IAsyncEnumerable<T1> first, IAsyncEnumerable<T2> second, IAsyncEnumerable<T3>? third, IAsyncEnumerable<T4>? fourth, Func<T1, T2, T3, T4, TResult> resultSelector, int limit, Func<bool[], Exception>? errorSelector = null, [EnumeratorCancellation] CancellationToken cancellationToken = default) { ConfiguredCancelableAsyncEnumerable<T1>.Enumerator? firstEnumerator = null; ConfiguredCancelableAsyncEnumerable<T2>.Enumerator? secondEnumerator = null; ConfiguredCancelableAsyncEnumerable<T3>.Enumerator? thirdEnumerator = null; ConfiguredCancelableAsyncEnumerable<T4>.Enumerator? fourthEnumerator = null; var terminations = 0; try { firstEnumerator = first.WithCancellation(cancellationToken).ConfigureAwait(false).GetAsyncEnumerator(); secondEnumerator = second.WithCancellation(cancellationToken).ConfigureAwait(false).GetAsyncEnumerator(); thirdEnumerator = third?.WithCancellation(cancellationToken).ConfigureAwait(false).GetAsyncEnumerator(); fourthEnumerator = fourth?.WithCancellation(cancellationToken).ConfigureAwait(false).GetAsyncEnumerator(); while (true) { T1 firstElement; T2 secondElement; T3 thirdElement; T4 fourthElement; bool terminated; var calls = 0; calls++; (firstElement, terminated) = await GetElementAsync(firstEnumerator).ConfigureAwait(false); if (terminated) { firstEnumerator = null; Validate(calls); } calls++; (secondElement, terminated) = await GetElementAsync(secondEnumerator).ConfigureAwait(false); if (terminated) { secondEnumerator = null; Validate(calls); } calls++; (thirdElement, terminated) = await GetElementAsync(thirdEnumerator).ConfigureAwait(false); if (terminated) { thirdEnumerator = null; Validate(calls); } calls++; (fourthElement, terminated) = await GetElementAsync(fourthEnumerator).ConfigureAwait(false); if (terminated) { fourthEnumerator = null; Validate(calls); } if (terminations <= limit) { yield return resultSelector(firstElement, secondElement, thirdElement, fourthElement); } else { yield break; } } } finally { if (firstEnumerator is not null) { await firstEnumerator.Value.DisposeAsync(); } if (secondEnumerator is not null) { await secondEnumerator.Value.DisposeAsync(); } if (thirdEnumerator is not null) { await thirdEnumerator.Value.DisposeAsync(); } if (fourthEnumerator is not null) { await fourthEnumerator.Value.DisposeAsync(); } } async ValueTask<(T element, bool terminated)> GetElementAsync<T>(ConfiguredCancelableAsyncEnumerable<T>.Enumerator? enumerator) { if (enumerator is null || terminations > limit) { return (default!, false); } if (await enumerator.Value.MoveNextAsync()) { var element = enumerator.Value.Current; return (element, false); } await enumerator.Value.DisposeAsync(); terminations++; return (default!, true); } void Validate(int calls) { if (errorSelector is not null && terminations > 0 && terminations < calls) { throw errorSelector( new[] { firstEnumerator is null, secondEnumerator is null, thirdEnumerator is null, fourthEnumerator is null }); } } } private static async IAsyncEnumerable<TResult> ZipAwait<T1, T2, T3, T4, TResult>( this IAsyncEnumerable<T1> first, IAsyncEnumerable<T2> second, IAsyncEnumerable<T3>? third, IAsyncEnumerable<T4>? fourth, Func<T1, T2, T3, T4, ValueTask<TResult>> resultSelector, int limit, Func<bool[], Exception>? errorSelector = null, [EnumeratorCancellation] CancellationToken cancellationToken = default) { ConfiguredCancelableAsyncEnumerable<T1>.Enumerator? firstEnumerator = null; ConfiguredCancelableAsyncEnumerable<T2>.Enumerator? secondEnumerator = null; ConfiguredCancelableAsyncEnumerable<T3>.Enumerator? thirdEnumerator = null; ConfiguredCancelableAsyncEnumerable<T4>.Enumerator? fourthEnumerator = null; var terminations = 0; try { firstEnumerator = first.WithCancellation(cancellationToken).ConfigureAwait(false).GetAsyncEnumerator(); secondEnumerator = second.WithCancellation(cancellationToken).ConfigureAwait(false).GetAsyncEnumerator(); thirdEnumerator = third?.WithCancellation(cancellationToken).ConfigureAwait(false).GetAsyncEnumerator(); fourthEnumerator = fourth?.WithCancellation(cancellationToken).ConfigureAwait(false).GetAsyncEnumerator(); while (true) { T1 firstElement; T2 secondElement; T3 thirdElement; T4 fourthElement; bool terminated; var calls = 0; calls++; (firstElement, terminated) = await GetElementAsync(firstEnumerator).ConfigureAwait(false); if (terminated) { firstEnumerator = null; Validate(calls); } calls++; (secondElement, terminated) = await GetElementAsync(secondEnumerator).ConfigureAwait(false); if (terminated) { secondEnumerator = null; Validate(calls); } calls++; (thirdElement, terminated) = await GetElementAsync(thirdEnumerator).ConfigureAwait(false); if (terminated) { thirdEnumerator = null; Validate(calls); } calls++; (fourthElement, terminated) = await GetElementAsync(fourthEnumerator).ConfigureAwait(false); if (terminated) { fourthEnumerator = null; Validate(calls); } if (terminations <= limit) { yield return await resultSelector(firstElement, secondElement, thirdElement, fourthElement).ConfigureAwait(false); } else { yield break; } } } finally { if (firstEnumerator is not null) { await firstEnumerator.Value.DisposeAsync(); } if (secondEnumerator is not null) { await secondEnumerator.Value.DisposeAsync(); } if (thirdEnumerator is not null) { await thirdEnumerator.Value.DisposeAsync(); } if (fourthEnumerator is not null) { await fourthEnumerator.Value.DisposeAsync(); } } async ValueTask<(T element, bool terminated)> GetElementAsync<T>(ConfiguredCancelableAsyncEnumerable<T>.Enumerator? enumerator) { if (enumerator is null || terminations > limit) { return (default!, false); } if (await enumerator.Value.MoveNextAsync()) { var element = enumerator.Value.Current; return (element, false); } await enumerator.Value.DisposeAsync(); terminations++; return (default!, true); } void Validate(int calls) { if (errorSelector is not null && terminations > 0 && terminations < calls) { throw errorSelector( new[] { firstEnumerator is null, secondEnumerator is null, thirdEnumerator is null, fourthEnumerator is null }); } } } } }
38.271062
139
0.4799
[ "Apache-2.0" ]
i3arnon/MoreAsyncLINQ
src/MoreAsyncLINQ/Operators/Zip/Zip.cs
10,450
C#
using System; using System.Collections.Generic; using System.Text; namespace TrafficViewerControls { public enum RequestViewerTabs { Unknown, HttpTraffic, Entities, Browser, DOM, LogSync } }
12.529412
33
0.7277
[ "Apache-2.0" ]
Bhaskers-Blu-Org1/HTTP-BlackOps
TrafficViewerControls/RequestViewerTabs.cs
213
C#
namespace EFCore.Sharding { internal static partial class Extention { /// <summary> /// 获取稳定的HashCode(原HashCode不稳定,会改变) /// </summary> /// <param name="str">字符串</param> /// <returns></returns> public static int GetStableHashCode(this string str) { unchecked { int hash1 = 5381; int hash2 = hash1; for (int i = 0; i < str.Length && str[i] != '\0'; i += 2) { hash1 = ((hash1 << 5) + hash1) ^ str[i]; if (i == str.Length - 1 || str[i + 1] == '\0') break; hash2 = ((hash2 << 5) + hash2) ^ str[i + 1]; } return hash1 + (hash2 * 1566083941); } } } }
27.966667
73
0.392133
[ "Apache-2.0" ]
731315163/EFCore.Sharding
src/EFCore.Sharding/Util/Extention.String.cs
877
C#
/* Copyright 2012-2020 Marco De Salvo 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 RDFSharp.Query; using System.Collections.Generic; namespace RDFSharp.Model { /// <summary> /// RDFQualifiedValueShapeConstraint represents a SHACL constraint requiring min/max occurrencies of the specified shape for a given RDF term /// </summary> public class RDFQualifiedValueShapeConstraint : RDFConstraint { #region Properties /// <summary> /// Identifier of the shape against which the given RDF term must be validated /// </summary> public RDFResource QualifiedValueShapeUri { get; internal set; } /// <summary> /// Indicates the minimum required occurrences for a given RDF term /// </summary> public int? QualifiedValueMinCount { get; internal set; } /// <summary> /// Indicates the maximum required occurrences for a given RDF term /// </summary> public int? QualifiedValueMaxCount { get; internal set; } #endregion #region Ctors /// <summary> /// Default-ctor to build a qualified value shape constraint with the given property shape identifier and min/max counters /// </summary> public RDFQualifiedValueShapeConstraint(RDFResource qualifiedValueShapeUri, int? qualifiedValueMinCount, int? qualifiedValueMaxCount) : base() { if (qualifiedValueShapeUri != null) { this.QualifiedValueShapeUri = qualifiedValueShapeUri; if (qualifiedValueMinCount.HasValue) this.QualifiedValueMinCount = qualifiedValueMinCount < 0 ? 0 : qualifiedValueMinCount; if (qualifiedValueMaxCount.HasValue) this.QualifiedValueMaxCount = qualifiedValueMaxCount < 0 ? 0 : qualifiedValueMaxCount; } else { throw new RDFModelException("Cannot create RDFQualifiedValueShapeConstraint because given \"qualifiedValueShapeUri\" parameter is null."); } } #endregion #region Methods /// <summary> /// Evaluates this constraint against the given data graph /// </summary> internal override RDFValidationReport ValidateConstraint(RDFShapesGraph shapesGraph, RDFGraph dataGraph, RDFShape shape, RDFPatternMember focusNode, List<RDFPatternMember> valueNodes) { RDFValidationReport report = new RDFValidationReport(); //Search for given qualified value shape RDFShape qualifiedValueShape = shapesGraph.SelectShape(this.QualifiedValueShapeUri.ToString()); if (qualifiedValueShape == null) return report; #region Evaluation if (this.QualifiedValueMinCount.HasValue || this.QualifiedValueMaxCount.HasValue) { int conformingValues = 0; foreach (RDFPatternMember valueNode in valueNodes) { RDFValidationReport qualifiedValueShapeReport = RDFValidationEngine.ValidateShape(shapesGraph, dataGraph, qualifiedValueShape, new List<RDFPatternMember>() { valueNode }); if (qualifiedValueShapeReport.Conforms) conformingValues++; } if (this.QualifiedValueMinCount.HasValue && conformingValues < this.QualifiedValueMinCount) report.AddResult(new RDFValidationResult(shape, RDFVocabulary.SHACL.QUALIFIED_MIN_COUNT_CONSTRAINT_COMPONENT, focusNode, shape is RDFPropertyShape ? ((RDFPropertyShape)shape).Path : null, null, shape.Messages, shape.Severity)); if (this.QualifiedValueMaxCount.HasValue && conformingValues > this.QualifiedValueMaxCount) report.AddResult(new RDFValidationResult(shape, RDFVocabulary.SHACL.QUALIFIED_MAX_COUNT_CONSTRAINT_COMPONENT, focusNode, shape is RDFPropertyShape ? ((RDFPropertyShape)shape).Path : null, null, shape.Messages, shape.Severity)); } #endregion return report; } /// <summary> /// Gets a graph representation of this constraint /// </summary> internal override RDFGraph ToRDFGraph(RDFShape shape) { RDFGraph result = new RDFGraph(); if (shape != null) { //sh:qualifiedValueShape result.AddTriple(new RDFTriple(shape, RDFVocabulary.SHACL.QUALIFIED_VALUE_SHAPE, this.QualifiedValueShapeUri)); //sh:qualifiedMinCount if (this.QualifiedValueMinCount.HasValue) result.AddTriple(new RDFTriple(shape, RDFVocabulary.SHACL.QUALIFIED_MIN_COUNT, new RDFTypedLiteral(this.QualifiedValueMinCount.ToString(), RDFModelEnums.RDFDatatypes.XSD_INTEGER))); //sh:qualifiedMaxCount if (this.QualifiedValueMaxCount.HasValue) result.AddTriple(new RDFTriple(shape, RDFVocabulary.SHACL.QUALIFIED_MAX_COUNT, new RDFTypedLiteral(this.QualifiedValueMaxCount.ToString(), RDFModelEnums.RDFDatatypes.XSD_INTEGER))); } return result; } #endregion } }
45.985816
201
0.584978
[ "Apache-2.0" ]
BME-MIT-IET/iet-hf2021-create-a-new-team
RDFSharp/Model/Validation/Abstractions/Constraints/RDFQualifiedValueShapeConstraint.cs
6,486
C#
namespace UptimeKumaRemoteProbe.Services; public class DbService { private readonly ILogger<TcpService> _logger; private readonly PushService _pushService; public DbService(ILogger<TcpService> logger, PushService pushService) { _logger = logger; _pushService = pushService; } public async Task CheckDbAsync(Endpoint endpoint) { var stopwatch = Stopwatch.StartNew(); var dbContext = new ApplicationDbContext(endpoint); string status = null; try { switch (endpoint.Brand) { case "MSSQL": status = dbContext.DbVersion?.FromSqlRaw("Select @@VERSION AS Version").First().Version; break; case "MYSQL": status = dbContext.DbVersion?.FromSqlRaw("Select VERSION() AS Version").First().Version; break; default: break; } } catch { _logger.LogError("Error trying get {endpoint.Brand} at: {DateTimeOffset.Now}", endpoint.Brand, DateTimeOffset.Now); } if (status is not null) { await _pushService.PushAsync(endpoint.PushUri, stopwatch.ElapsedMilliseconds); } } }
27.851064
127
0.566845
[ "MIT" ]
zimbres/UptimeKumaRemoteProbe
UptimeKumaRemoteProbe/Services/DbService.cs
1,311
C#
using System.Web.Mvc; using Umbraco.Core.Composing; using Umbraco.Web.Models; namespace Umbraco.Web.Mvc { /// <summary> /// The interface that must be implemented for a controller to be designated to execute for route hijacking /// </summary> public interface IRenderMvcController : IRenderController, IDiscoverable { /// <summary> /// The default action to render the front-end view /// </summary> /// <param name="model"></param> /// <returns></returns> ActionResult Index(ContentModel model); } }
28.7
111
0.646341
[ "MIT" ]
0Neji/Umbraco-CMS
src/Umbraco.Web/Mvc/IRenderMvcController.cs
576
C#
using System.Text.Json; using controllers.ApiModels; using Microsoft.AspNetCore.Mvc; namespace controllers.Controllers; [ApiController] [Route("Demo")] public class DemoController : ControllerBase { // different methods that return an author [HttpGet("getobject")] public object GetObject() { return GetBook(); } // returns a 204 no content with no body // response type header is not set [HttpGet("getobjectnull")] public object GetObjectNull() { return null; } // will set response type to text/plain [HttpGet("getstring")] public string GetString() { return JsonSerializer.Serialize(GetBook()); } [HttpGet("getjson")] public JsonResult GetJson() { return new JsonResult(GetBook()); } [HttpGet("getiactionresult")] public IActionResult GetIActionResult() { return Ok(GetBook()); } [HttpGet("getiactionresult<T>")] public ActionResult<BookDto> GetActionResultOfT() { return Ok(GetBook()); } private BookDto GetBook() { return new BookDto(1, "1234-5678", "Warren Piece", "Steve Smith"); } }
18.350877
68
0.713193
[ "MIT" ]
ardalis/WebApiBestPractices
api_templates/controllers/Controllers/DemoController.cs
1,048
C#
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VideoConverter.Common { public abstract partial class VideoConverterApplicationBase { private static Encoding SerializationEncoding => Encoding.UTF8; protected static byte[] SerializeFile(ConverterFileInfo file) => file is null ? null : SerializationEncoding.GetBytes(JsonConvert.SerializeObject(file)); protected static ConverterFileInfo DeserializeFile(byte[] body) => body is null ? null : (ConverterFileInfo)JsonConvert.DeserializeObject(SerializationEncoding.GetString(body), typeof(ConverterFileInfo)); protected readonly string mqServerHost; protected virtual IEqualityComparer<string> ArgKeyEqualityComparer => StringComparer.OrdinalIgnoreCase; protected readonly IReadOnlyDictionary<string, string> argDictionary; private IReadOnlyDictionary<string, string> ParseArgs(string[] args, string[] argKeys) { string getArgValue(string argKey) => args .SkipWhile(arg => !this.ArgKeyEqualityComparer.Equals(arg, argKey)) .Skip(1) .FirstOrDefault(); return argKeys.ToDictionary( argKey => argKey, argKey => getArgValue(argKey), this.ArgKeyEqualityComparer); } public VideoConverterApplicationBase(string mqServerHost, string[] args, string[] argKeys) { this.mqServerHost = mqServerHost; T[] normalizeArray<T>(T[] array) => array ?? new T[] { }; this.argDictionary = this.ParseArgs( normalizeArray(args), normalizeArray(argKeys)); } public abstract Task RunAsync(); } }
33.910714
127
0.646656
[ "MIT" ]
andreigit/VideoConverterBalancer
VideoConverter.Common/VideoConverterApplicationBase.cs
1,901
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 backup-2018-11-15.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.Backup.Model { /// <summary> /// Container for the parameters to the ListProtectedResources operation. /// Returns an array of resources successfully backed up by Backup, including the time /// the resource was saved, an Amazon Resource Name (ARN) of the resource, and a resource /// type. /// </summary> public partial class ListProtectedResourcesRequest : AmazonBackupRequest { private int? _maxResults; private string _nextToken; /// <summary> /// Gets and sets the property MaxResults. /// <para> /// The maximum number of items to be returned. /// </para> /// </summary> [AWSProperty(Min=1, Max=1000)] public int MaxResults { get { return this._maxResults.GetValueOrDefault(); } set { this._maxResults = value; } } // Check to see if MaxResults property is set internal bool IsSetMaxResults() { return this._maxResults.HasValue; } /// <summary> /// Gets and sets the property NextToken. /// <para> /// The next item following a partial list of returned items. For example, if a request /// is made to return <code>maxResults</code> number of items, <code>NextToken</code> /// allows you to return more items in your list starting at the location pointed to by /// the next token. /// </para> /// </summary> public string NextToken { get { return this._nextToken; } set { this._nextToken = value; } } // Check to see if NextToken property is set internal bool IsSetNextToken() { return this._nextToken != null; } } }
32.39759
104
0.633321
[ "Apache-2.0" ]
EbstaLimited/aws-sdk-net
sdk/src/Services/Backup/Generated/Model/ListProtectedResourcesRequest.cs
2,689
C#
namespace Umbraco.Cms.Core.Notifications { public class UserLockedNotification : UserNotification { public UserLockedNotification(string ipAddress, string affectedUserId, string performingUserId) : base(ipAddress, affectedUserId, performingUserId) { } } }
29.2
155
0.729452
[ "MIT" ]
Ambertvu/Umbraco-CMS
src/Umbraco.Core/Notifications/UserLockedNotification.cs
292
C#
using System; namespace Common { [Serializable] public class CEnemyClosing : Message { public CEnemyClosing() : base(Command.C_ENEMY_CLOSING) { } public int entityId; public int enemyId; } }
17.923077
66
0.630901
[ "Apache-2.0" ]
Scottdyt/3DGamekitWeb
Frontend/Assets/3DGamekit/Scripts/Common/FEMessage/CEnemyClosing.cs
235
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class BlockInput : MonoBehaviour { public ActiveButton buttonCheck; public Transform platformPrefab; public Transform jumpPadPrefab; public Transform hazardPrefab; private int shapesPlaced; private Transform activePrefab; // Start is called before the first frame update void Awake() { buttonCheck.GetComponent<ActiveButton>(); } // Update is called once per frame void Update() { if (buttonCheck.isPlatformActive) { activePrefab = platformPrefab; } else if (buttonCheck.isJumpPadActive) { activePrefab = jumpPadPrefab; } else if (buttonCheck.isHazardActive) { activePrefab = hazardPrefab; } else { activePrefab = null; } Vector2 screenPos = new Vector2(Input.mousePosition.x, Input.mousePosition.y); Vector2 worldSpacePos = Camera.main.ScreenToWorldPoint(screenPos); if (Input.GetMouseButtonDown(0) && buttonCheck.isPlatformActive) { Color c = new Color(Random.Range(0.5f, 1f), Random.Range(0.5f, 1f), Random.Range(0.5f, 1f)); ICommand command = new PlaceCubeCommand(worldSpacePos, c, platformPrefab); CommandInvoker.AddCommand(command); shapesPlaced++; buttonCheck.isPlatformActive = false; } if (Input.GetMouseButtonDown(0) && buttonCheck.isJumpPadActive) { Color c = new Color(Random.Range(0.5f, 1f), Random.Range(0.5f, 1f), Random.Range(0.5f, 1f)); ICommand command = new PlaceCubeCommand(worldSpacePos, c, jumpPadPrefab); CommandInvoker.AddCommand(command); shapesPlaced++; buttonCheck.isJumpPadActive = false; } if (Input.GetMouseButtonDown(0) && buttonCheck.isHazardActive) { Color c = new Color(Random.Range(0.5f, 1f), Random.Range(0.5f, 1f), Random.Range(0.5f, 1f)); //CubePlacer.PlaceCube(hitInfo.point, c, cubePrefab); ICommand command = new PlaceCubeCommand(worldSpacePos, c, hazardPrefab); CommandInvoker.AddCommand(command); //CubePlace cube = new CubePlace(); //cube.PlaceShape(hitInfo.point, c, cubePrefab); shapesPlaced++; buttonCheck.isHazardActive = false; } } }
27.527473
104
0.61517
[ "MIT" ]
DayeFubara16/Assignment-1
Assets/Scripts/Command Scripts/BlockInput.cs
2,505
C#
using UnityEngine; using System.Collections; using SS; public class EventToEvent : EventListener { public EventArray eventArray; [ContextMenu("Do Event")] public void DoEvent() { eventArray.Broadcast(this); } protected override void OnEvent(EventMessage em, ref object paramRef) { base.OnEvent(em, ref paramRef); DoEvent(); } }
16.809524
70
0.72238
[ "MIT" ]
Farl/SSCore2017
Packages/com.prototyper.stringevent/Runtime/ToEvent/EventToEvent.cs
355
C#
// This is an open source non-commercial project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com // ReSharper disable CheckNamespace // ReSharper disable CommentTypo // ReSharper disable InconsistentNaming /* JobDescription.cs -- совмещенное описание задания и триггера * Ars Magna project, http://arsmagna.ru * ------------------------------------------------------- */ #region Using directives using System; using System.IO; using Newtonsoft.Json; using Newtonsoft.Json.Linq; #endregion namespace QuartzShelf.Jobs { /// <summary> /// Совмещенное описание задания и триггера. /// </summary> public sealed class JobDescription { #region Properties /// <summary> /// Идентификатор задания. /// </summary> [JsonProperty("name")] public string Name { get; set; } /// <summary> /// Группа. /// </summary> [JsonProperty("group")] public string Group { get; set; } /// <summary> /// Словесное описание задания. /// </summary> [JsonProperty ("description")] public string Description { get; set; } /// <summary> /// Задание разрешено? /// </summary> [JsonProperty ("enabled")] public bool Enabled { get; set; } /// <summary> /// Тип задания (полностью специфицированный, /// с указанием сборки). /// </summary> [JsonProperty("type")] public string Type { get; set; } /// <summary> /// Cron-выражение. /// </summary> [JsonProperty("cron")] public string CronExpression { get; set; } #endregion #region Public methods /// <summary> /// Загрузка массива заданий из файла. /// </summary> public static JobDescription[] ReadJobs ( string fileName ) { var text = File.ReadAllText(fileName); var rootObject = JObject.Parse(text); var firstProperty = (JProperty) rootObject.First; if (ReferenceEquals(firstProperty, null)) { throw new ApplicationException("Bad jobs file format"); } var array = (JArray) firstProperty.Value; var result = array.ToObject<JobDescription[]>(); return result; } #endregion #region Object members /// <inheritdoc /> public override string ToString() { return Name ?? "(null)"; } #endregion } }
25.682243
84
0.524745
[ "MIT" ]
amironov73/templates
NetService/Sources/Jobs/JobDescription.cs
2,976
C#
using System; namespace Amazon.Elb { public sealed class DeleteLoadBalancerRequest : IElbRequest { public DeleteLoadBalancerRequest(string loadBalancerArn) { LoadBalancerArn = loadBalancerArn ?? throw new ArgumentNullException(nameof(loadBalancerArn)); } public string Action => "DeleteLoadBalancer"; public string LoadBalancerArn { get; } } }
27.125
107
0.645161
[ "MIT" ]
JTOne123/Amazon
src/Amazon.Elb/Actions/DeleteLoadBalancerRequest.cs
436
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using UnityEditor; using UnityEngine; using UnityEngine.Serialization; namespace QFramework.PackageKit { public class PackageKitWindow : IMGUIEditorWindow { class LocaleText { public static string QFrameworkSettings { get { return Language.IsChinese ? "QFramework 设置" : "QFramework Settings"; } } } private const float toolbarHeight = 20; class Styles { public static GUIStyle box = "box"; public static GUIStyle in_title = new GUIStyle("IN Title") {fixedHeight = toolbarHeight + 5}; public static GUIStyle toolbarSeachTextFieldPopup = "ToolbarSeachTextFieldPopup"; public static GUIStyle searchCancelButton = "ToolbarSeachCancelButton"; public static GUIStyle searchCancelButtonEmpty = "ToolbarSeachCancelButtonEmpty"; public static GUIStyle foldout = "Foldout"; public static GUIStyle toolbarDropDown = "ToolbarDropDown"; public static GUIStyle selectionRect = "SelectionRect"; } [MenuItem(FrameworkMenuItems.Preferences, false, FrameworkMenuItemsPriorities.Preferences)] [MenuItem(FrameworkMenuItems.PackageKit, false, FrameworkMenuItemsPriorities.Preferences)] private static void Open() { var packageKitWindow = Create<PackageKitWindow>(true); packageKitWindow.titleContent = new GUIContent(LocaleText.QFrameworkSettings); packageKitWindow.position = new Rect(50, 100, 1000, 800); packageKitWindow.Show(); } private const string URL_FEEDBACK = "http://feathub.com/liangxiegame/QFramework"; [MenuItem(FrameworkMenuItems.Feedback, false, FrameworkMenuItemsPriorities.Feedback)] private static void Feedback() { Application.OpenURL(URL_FEEDBACK); } public override void OnUpdate() { mPackageKitViewRenderInfos.ForEach(view => view.Interface.OnUpdate()); } public class PacakgeKitViewRenderInfo { public QFramework.IPackageKitView Interface { get; private set; } public string DisplayName { get; private set; } public int RenderOrder { get; private set; } public PacakgeKitViewRenderInfo(QFramework.IPackageKitView @interface) { Interface = @interface; var displayName = @interface.GetType().GetCustomAttributes(typeof(DisplayNameAttribute), false) .FirstOrDefault() as DisplayNameAttribute; DisplayName = displayName != null ? displayName.DisplayName : @interface.GetType().Name; var renderOrder = @interface.GetType() .GetCustomAttributes(typeof(PackageKitRenderOrderAttribute), false) .FirstOrDefault() as PackageKitRenderOrderAttribute; RenderOrder = renderOrder != null ? renderOrder.Order : int.MaxValue; } } [FormerlySerializedAs("mPackageKitViews")] public List<PacakgeKitViewRenderInfo> mPackageKitViewRenderInfos = null; private int count = 0; protected override void Init() { var label = GUI.skin.label; PackageApplication.Container = null; RemoveAllChidren(); mPackageKitViewRenderInfos = PackageApplication.Container .ResolveAll<IPackageKitView>() .Select(view => new PacakgeKitViewRenderInfo(view)) .OrderBy(renderInfo => renderInfo.RenderOrder) .ToList(); mSelectedViewRender = mPackageKitViewRenderInfos.FirstOrDefault(); PackageApplication.Container.RegisterInstance(this); PackageApplication.Container.RegisterInstance<EditorWindow>(this); // 创建双屏 mSplitView = new VerticalSplitView { fistPan = rect => { GUILayout.BeginArea(rect); GUILayout.BeginVertical(); GUILayout.Space(toolbarHeight); GUILayout.EndVertical(); LeftSelectView(""); GUILayout.EndArea(); }, secondPan = rect => { GUILayout.BeginArea(rect); GUILayout.BeginVertical(); GUILayout.Space(toolbarHeight); GUILayout.EndVertical(); if (mSelectedViewRender != null) { mSelectedViewRender.Interface.OnGUI(); } GUILayout.EndArea(); } }; } private VerticalSplitView mSplitView; public override void OnGUI() { base.OnGUI(); GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); GUILayout.Label(DateTime.Now.ToLongTimeString(), Styles.selectionRect); GUILayout.EndHorizontal(); var r = GUILayoutUtility.GetLastRect(); mSplitView.OnGUI(new Rect(new Vector2(0, r.yMax), new Vector2(position.width, position.height - r.height))); RenderEndCommandExecuter.ExecuteCommand(); } private PacakgeKitViewRenderInfo mSelectedViewRender = null; private void LeftSelectView(string search) { for (int i = 0; i < mPackageKitViewRenderInfos.Count; i++) { var drawer = mPackageKitViewRenderInfos[i]; GUILayout.BeginHorizontal(Styles.in_title); GUILayout.Label(drawer.DisplayName); GUILayout.FlexibleSpace(); // GUILayout.Label("v0.0.1"); GUILayout.EndHorizontal(); Rect rect = GUILayoutUtility.GetLastRect(); if (mSelectedViewRender == drawer) { GUI.Box(rect, "", Styles.selectionRect); } if (rect.Contains(Event.current.mousePosition) && Event.current.type == EventType.MouseUp) { mSelectedViewRender = drawer; Event.current.Use(); } GUILayout.Label("", Styles.in_title, GUILayout.Height(0)); } } public override void OnClose() { if (mPackageKitViewRenderInfos != null) { mPackageKitViewRenderInfos.Where(view => view != null).ToList().ForEach(view => view.Interface.OnDispose()); } RemoveAllChidren(); } } }
35.677083
124
0.58
[ "MIT" ]
gKev1n/UnityFrameWorkDesign
Assets/QFramework/Framework/0.PackageKit/Editor/Framework/Window/PackageKitWindow.cs
6,862
C#
namespace Castle.Facilities.ServiceFabricIntegration { using System; using Castle.Core; using Castle.Core.Internal; using Castle.Facilities.ServiceFabricIntegration.Resolvers; using Castle.MicroKernel; using Castle.MicroKernel.SubSystems.Conversion; using MicroKernel.Registration; using Microsoft.ServiceFabric.Actors; using Microsoft.ServiceFabric.Actors.Runtime; internal class ActorModule : IServiceFabricModule { public void Init(IKernel kernel) { kernel.Register( Component.For<ActorDeactivationInterceptor>() .LifestyleTransient(), Component.For<ActorService>() .LifestyleTransient() .DependsOn(Dependency.OnValue("stateManagerFactory", null)) .DependsOn(Dependency.OnValue("stateProvider", null)) .DependsOn(Dependency.OnValue("settings", null)) ); } public void Contribute(IKernel kernel, ComponentModel model) { var actorFlag = IsActorType(model) && HasActorAttributeSet(model, kernel.GetConversionManager()); model.SetProperty(FacilityConstants.ActorKey, actorFlag); if (actorFlag) { var actorServiceType = GetActorServiceTypeAttribute(model, kernel.GetConversionManager()) ?? typeof(ActorService); model.SetProperty(FacilityConstants.ActorServiceTypeKey, actorServiceType); } } public bool CanRegister(IHandler handler) { return Helpers.IsFlag(handler, FacilityConstants.ActorKey); } public void RegisterComponent(IKernel kernel, IHandler handler) { var actorModel = handler.ComponentModel; var actorType = actorModel.Implementation; var serviceType = handler.GetProperty<Type>(FacilityConstants.ActorServiceTypeKey); var serviceHandler = kernel.GetHandler(serviceType); if (serviceHandler == null) { throw new ComponentRegistrationException($"Component for ActorService {serviceType} must be registered before Actor {actorType}"); } var serviceModel = serviceHandler.ComponentModel; var stateManagerFactory = actorModel.GetProperty<Func<ActorBase, IActorStateProvider, IActorStateManager>>(typeof(Func<ActorBase, IActorStateProvider, IActorStateManager>)); if (stateManagerFactory != null && serviceModel.GetDependencyFor(typeof(Func<ActorBase, IActorStateProvider, IActorStateManager>)) == null) { throw new ComponentRegistrationException($"Failed to register Actor {actorType}. Could not locate a valid dependency on {serviceType} that accepts {typeof(Func<ActorBase, IActorStateProvider, IActorStateManager>)} when StateManagerFactory delegate is set."); } var actorServiceSettings = actorModel.GetProperty<ActorServiceSettings>(typeof(ActorServiceSettings)); if (actorServiceSettings != null && serviceModel.GetDependencyFor(typeof(ActorServiceSettings)) == null) { throw new ComponentRegistrationException($"Failed to register Actor {actorType}. Could not locate a valid dependency on {serviceType} that accepts {typeof(ActorServiceSettings)} when ActorServiceSettings is set."); } actorModel.Interceptors.Add(new InterceptorReference(typeof(ActorDeactivationInterceptor))); var serviceResolver = new ActorServiceResolver(kernel, serviceType) { ActorFactory = new ActorResolver(kernel, actorType).Resolve, StateManagerFactory = stateManagerFactory, StateProvider = null, Settings = actorServiceSettings }; new RuntimeRegistration(actorType) .RegisterAsync(serviceResolver.Resolve) .GetAwaiter() .GetResult(); } private static bool IsActorType(ComponentModel model) { return model.Implementation.Is<IActor>(); } private static bool HasActorAttributeSet(ComponentModel model, ITypeConverter converter) { return Helpers.IsFlag(model, converter, FacilityConstants.ActorKey); } private static Type GetActorServiceTypeAttribute(ComponentModel model, ITypeConverter converter) { return Helpers.GetType(model, converter, FacilityConstants.ActorServiceTypeKey); } } }
45.087379
274
0.656115
[ "MIT" ]
Daedeross/Castle.Facilities.ServiceFabricIntegration
Castle.Facilities.ServiceFabricIntegration.Actors/ActorModule.cs
4,646
C#
using System; using System.IO; using System.Linq; using System.Text; using ArgData.Entities; using ArgData.Internals; using ArgData.IO; namespace ArgData { /// <summary> /// Reads a name file from disk. /// </summary> public class NameFileReader { /// <summary> /// Read a name file. /// </summary> /// <param name="path">Path to file.</param> /// <returns>NameFile with teams, engines and driver names.</returns> public NameFile Read(string path) { ValidateFile(path); using (var reader = new BinaryReader(StreamProvider.Invoke(path))) { byte[] nameData = reader.ReadAllBytes(); var drivers = ParseDrivers(nameData); var teams = ParseTeams(nameData); return new NameFile(drivers, teams); } } private static void ValidateFile(string path) { if (!File.Exists(path)) { throw new FileNotFoundException("Could not find name file", path); } var fileInfo = new FileInfo(path); if (fileInfo.Length != 1484) { throw new ArgumentException($"The file '{path}' does not appear to be a name file."); } } private static NameFileDriverList ParseDrivers(byte[] nameData) { var drivers = new NameFileDriverList(); for (int driverIndex = 0; driverIndex < Constants.NumberOfDrivers; driverIndex++) { int position = driverIndex * NameFileConstants.DriverNameLength; var name = GetNameAtPosition(nameData, position); drivers[driverIndex].Name = name; } return drivers; } private static NameFileTeamList ParseTeams(byte[] nameData) { var teams = new NameFileTeamList(); for (int teamIndex = 0; teamIndex < Constants.NumberOfTeams; teamIndex++) { int position = 960 + (teamIndex * NameFileConstants.TeamNameLength); string name = GetNameAtPosition(nameData, position); int enginePosition = position + 260; string engine = GetNameAtPosition(nameData, enginePosition); teams[teamIndex].Name = name; teams[teamIndex].Engine = engine; } return teams; } private static string GetNameAtPosition(byte[] nameData, int position) { byte[] nameBytes = nameData.Skip(position).TakeWhile(b => b != 0).ToArray(); string name = Encoding.ASCII.GetString(nameBytes); return name; } /// <summary> /// Default FileStream provider. Can be overridden in tests. /// </summary> internal Func<string, Stream> StreamProvider = FileStreamProvider.Open; } /// <summary> /// Writes a name file to disk. /// </summary> public class NameFileWriter { /// <summary> /// Write name file. /// </summary> /// <param name="path"></param> /// <param name="drivers">List of drivers, where index indicates driver number.</param> /// <param name="teams">List of teams.</param> public void Write(string path, NameFileDriverList drivers, NameFileTeamList teams) { var byteList = new ByteList(); foreach (var driver in drivers) { string driverName = PadTruncate(driver.Name, NameFileConstants.DriverNameLength); byte[] nameBytes = Encoding.ASCII.GetBytes(driverName); byteList.AddBytes(nameBytes); } foreach (var team in teams) { string teamName = PadTruncate(team.Name, NameFileConstants.TeamNameLength); byte[] teamNameBytes = Encoding.ASCII.GetBytes(teamName); byteList.AddBytes(teamNameBytes); } foreach (var team in teams) { string engineName = PadTruncate(team.Engine, NameFileConstants.TeamNameLength); byte[] engineNameBytes = Encoding.ASCII.GetBytes(engineName); byteList.AddBytes(engineNameBytes); } var checksum = new ChecksumCalculator().Calculate(byteList.GetBytes()); using (var writer = new BinaryWriter(StreamProvider.Invoke(path))) { writer.Write(byteList.GetBytes()); writer.Write((ushort)checksum.Checksum1); writer.Write((ushort)checksum.Checksum2); } } private static string PadTruncate(string value, int wantedLength) { var trimmedValue = value.Length < wantedLength ? value : value.Substring(0, wantedLength - 1); return trimmedValue.PadRight(wantedLength, '\0'); } /// <summary> /// Default FileStream provider. Can be overridden in tests. /// </summary> internal Func<string, Stream> StreamProvider = FileStreamProvider.OpenWriter; } internal static class NameFileConstants { internal const int DriverNameLength = 24; internal const int TeamNameLength = 13; } }
32.253012
106
0.568547
[ "MIT" ]
JTOne123/ArgData
Source/ArgData/NameFiles.cs
5,354
C#
using UnityEngine; using UnityEngine.UI; using System.Collections; using System.Collections.Generic; using itfantasy.igui; using UImage = UnityEngine.UI.Image; namespace itfantasy.igui.u { public class ProgressBar : UIBehaviour, IProgressBar { UImage _image; protected override void OnInitUI() { _image = this.transform.Find("Foreground").GetComponent<UImage>(); base.OnInitUI(); } public float value { get { return _image.fillAmount; } set { _image.fillAmount = value; } } } }
19.970588
78
0.543446
[ "Apache-2.0" ]
itfantasy/igui
Assets/itfantasy/igui/u/ProgressBar.cs
681
C#
using UnityEngine; using UnityEngine.SceneManagement; using System.Collections; public class ApplicationManager : MonoBehaviour { public string modelScene; // Use this for initialization void Start () { if (modelScene!=null) { //SceneManager.LoadScene (modelScene, LoadSceneMode.Additive); } else { print ("No Valid Scene!"); } } // Update is called once per frame void Update () { if (Input.GetKey("escape") || Input.GetKey("q")) { Application.Quit(); } } }
20.458333
65
0.686354
[ "MIT" ]
thechosi/CAVE
Examples/BasicTestScene/Assets/Cave/Tracking/Scripts/ApplicationManager.cs
493
C#
using System; using System.Collections.Generic; namespace ConvergeLL { public class Program { public static void Main(string[] args) { Console.WriteLine("Determine if 2 LLs converge. If they do, find that conversion point."); LinkedList<Node> LLA = new LinkedList<Node>(); LLA.AddFirst(new Node(30)); LLA.AddFirst(new Node(15)); LLA.AddFirst(new Node(9)); LLA.AddFirst(new Node(6)); LLA.AddFirst(new Node(3)); //Console.WriteLine($"LLA head is {LLA.First.Value.Value}"); //Print(LLA.First); LinkedList<Node> LLB = new LinkedList<Node>(); LLB.AddFirst(new Node(30)); LLB.AddFirst(new Node(15)); LLB.AddFirst(new Node(10)); //Console.WriteLine($"LLB head is {LLB.First.Value.Value}"); //Print(LLB.First); StartFindPoint(LLA.First, LLB.First); } /// <summary> /// Initial method to start the problem solving /// </summary> /// <param name="nodeA"></param> /// <param name="nodeB"></param> public static void StartFindPoint(LinkedListNode<Node> nodeA, LinkedListNode<Node> nodeB) { //get counts of both LLs int countA = Count(nodeA); int countB = Count(nodeB); int diff = Math.Abs(countA - countB); //depending on which LL is longer, travel up to that difference within the longer LL if (countA > countB) { LinkedListNode<Node> startNodeA = CountTheDifference(diff, nodeA); Console.WriteLine($"We are at {startNodeA.Value.Value} on LLA"); FindConvergePoint(startNodeA, nodeB); } else { LinkedListNode<Node> startNodeB = CountTheDifference(diff, nodeB); Console.WriteLine($"We are at {startNodeB.Value.Value} on LLB"); FindConvergePoint(startNodeB, nodeA); } } /// <summary> /// Counts the lengths of a LL /// </summary> /// <param name="node">starting node</param> /// <returns>the count, which represents the length of the LL</returns> public static int Count(LinkedListNode<Node> node) { int counter = 0; LinkedListNode<Node> current = node; while (current != null) { counter++; current = current.Next; } return counter; } /// <summary> /// Iterates to the point where /// </summary> /// <param name="diff">difference in lengths between the 2 LLs</param> /// <param name="node">node to start iterating at</param> /// <returns>the node at which the main iteration will start at</returns> public static LinkedListNode<Node> CountTheDifference(int diff, LinkedListNode<Node> node) { while (diff != 0) { diff--; node = node.Next; } return node; } /// <summary> /// Travel through both LLs until a node has the same value for both LLs /// </summary> /// <param name="node1"></param> /// <param name="node2"></param> /// <returns></returns> public static LinkedListNode<Node> FindConvergePoint(LinkedListNode<Node> node1, LinkedListNode<Node> node2) { while (node1 != null && node2 != null) { if (node1.Value.Value == node2.Value.Value) { Console.WriteLine($" The LLs converged on {node1.Value.Value}"); return node1; } node1 = node1.Next; node2 = node2.Next; } return null; } /// <summary> /// prints all the nodes in an LL /// </summary> /// <param name="node">node that we start printing at</param> public static void Print(LinkedListNode<Node> node) { while(node.Next != null) { Console.Write($" {node.Value.Value} -> "); node = node.Next; } Console.Write($" {node.Value.Value} "); Console.WriteLine(""); } } }
26.969466
110
0.64591
[ "MIT" ]
jcqnly/data-structures-and-algorithms
Challenges/ConvergeLL/ConvergeLL/Program.cs
3,535
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace DND_Monster { public static class BrassDragon { public static void Add(DragonAge age) { switch (age) { case DragonAge.Ancient: Ancient(); break; case DragonAge.Adult: Adult(); break; case DragonAge.Young: Young(); break; case DragonAge.Wyrmling: Wyrmling(); break; } } private static void Ancient() { // new OGL_Ability() { OGL_Creature = "Brass Dragon", Title = "", attack = null, isDamage = false, isSpell = false, saveDC = 0, Description = "" }, OGLContent.OGL_Abilities.AddRange(new List<OGL_Ability>() { new OGL_Ability() { OGL_Creature = "Ancient Brass Dragon", Title = "Legendary Resistance (3/Day)", attack = null, isDamage = false, isSpell = false, saveDC = 0, Description = "If the {CREATURENAME} fails a saving throw, it can choose to succeed instead." }, }); // template #region // new OGL_Ability() { OGL_Creature = "Brass Dragon", Title = "", isDamage = false, isSpell = false, saveDC = 0, Description = ""}, // new OGL_Ability() { OGL_Creature = "Brass Dragon", Title = "", isDamage = true, isSpell = false, saveDC = 0, Description = "", attack = new Attack() //{ // _Attack = "Melee Weapon Attack", // Bonus = "1", // Reach = 5, // RangeClose = 0, // RangeFar = 0, // Target = "one target", // HitDiceNumber = 2, // HitDiceSize = 6, // HitDamageBonus = 3, // HitAverageDamage = 10, // HitText = "", // HitDamageType = "fire" //} //}, #endregion OGLContent.OGL_Actions.AddRange(new List<OGL_Ability>() { new OGL_Ability() { OGL_Creature = "Ancient Brass Dragon", Title = "Multiattack", isDamage = false, isSpell = false, saveDC = 0, Description = "The {CREATURENAME} can use its Frightful Presence. It then makes three attacks: one with its bite and two with its claws."}, new OGL_Ability() { OGL_Creature = "Ancient Brass Dragon", Title = "Bite", isDamage = true, isSpell = false, saveDC = 0, Description = "", attack = new Attack() { _Attack = "Melee Weapon Attack", Bonus = "14", Reach = 15, RangeClose = 0, RangeFar = 0, Target = "one target", HitDiceNumber = 2, HitDiceSize = 10, HitDamageBonus = 8, HitAverageDamage = 19, HitText = "", HitDamageType = "piercing" } }, new OGL_Ability() { OGL_Creature = "Ancient Brass Dragon", Title = "Claw", isDamage = true, isSpell = false, saveDC = 0, Description = "", attack = new Attack() { _Attack = "Melee Weapon Attack", Bonus = "14", Reach = 10, RangeClose = 0, RangeFar = 0, Target = "one target", HitDiceNumber = 2, HitDiceSize = 6, HitDamageBonus = 8, HitAverageDamage = 15, HitText = "", HitDamageType = "slashing" } }, new OGL_Ability() { OGL_Creature = "Ancient Brass Dragon", Title = "Tail", isDamage = true, isSpell = false, saveDC = 0, Description = "", attack = new Attack() { _Attack = "Melee Weapon Attack", Bonus = "14", Reach = 20, RangeClose = 0, RangeFar = 0, Target = "one target", HitDiceNumber = 2, HitDiceSize = 8, HitDamageBonus = 8, HitAverageDamage = 17, HitText = "", HitDamageType = "bludgeoning" } }, new OGL_Ability() { OGL_Creature = "Ancient Brass Dragon", Title = "Frightful Presence", isDamage = false, isSpell = false, saveDC = 0, Description = "Each creature of the {CREATURENAME}'s choice that is within 120 feet of the {CREATURENAME} and aware of it must succeed on a DC 18 Wisdom saving throw or become frightened for 1 minute. A creature can repeat the saving throw at the end of each of its turns, ending the effect on itself on a success. If a creature's saving throw is successful or the effect ends for it, the creature is immune to the {CREATURENAME}'s Frightful Presence for the next 24 hours."}, new OGL_Ability() { OGL_Creature = "Ancient Brass Dragon", Title = "Breath Weapons (Recharge 5-6)", isDamage = false, isSpell = false, saveDC = 0, Description = "The {CREATURENAME} uses one of the following breath weapons: " + "<p><b>Fire Breath.</b> The {CREATURENAME} exhales fire in a 90-foot cone. Each creature in the area must make a DC 21 Dexterity saving throw, taking 56 (16d6) fire damage on a failed save, or half as much damage on a saving throw. </p>" + "<p><b>Sleep Breath.</b> The {CREATURENAME} exhales sleep gas in a 90-foot cone. Each creature in that area must succeed on a DC 21 Consitution saving throw or fall unconscious for 10 minutes. This effect ends for a creature if the creature takes damage or someone uses an action to wake it.</p>"}, new OGL_Ability() { OGL_Creature = "Ancient Brass Dragon", Title = "Change Shape", isDamage = false, isSpell = false, saveDC = 0, Description = "The {CREATURENAME} magically polymorphs into a humanoid or beast that has a challenge rating no higher than its own, or back into its true form. It reverts to its true form if it dies. Any equipment it is wearing or carrying is absorbed or borne by the new form (the {CREATURENAME}'s choice). </br> In a new form, the {CREATURENAME} retains its alignment, hit points, Hit Dice, ability to speak, proficiencies, Legendary Resistance, lair actions and Intelligence, Wisdom and, Charisma scores, as well as this action. Its statistics and capabilities are otherwise replaced by those of the new form, except any class features or legendary actions of that form."}, }); // new OGL_Ability() { OGL_Creature = "Brass Dragon", Title = "", attack = null, isDamage = false, isSpell = false, saveDC = 0, Description = "" } OGLContent.OGL_Reactions.AddRange(new List<OGL_Ability>() { }); // Template #region //new OGL_Legendary() //{ // OGL_Creature = "Brass Dragon", // Title = "", // Traits = new List<LegendaryTrait>() // { // new LegendaryTrait("", "") // } //}, #endregion OGLContent.OGL_Legendary.AddRange(new List<OGL_Legendary>() { new OGL_Legendary() { OGL_Creature = "Ancient Brass Dragon", Title = "Ancient Brass Dragon Legendary Actions", Traits = new List<LegendaryTrait>() { new LegendaryTrait("Detect", "The {CREATURENAME} makes a Wisdom (Perception) check."), new LegendaryTrait("Tail Attack", "The {CREATURENAME} makes a tail attack."), new LegendaryTrait("Wing Attack (Costs 2 Actions)", "The {CREATURENAME} beats its wings. Each creature within 15 feet of the {CREATURENAME} must succeed on a DC 22 Dexterity saving throw or take 15 (2d6 + 8) bludgeoning damage and be knocked prone. The {CREATURENAME} can then fly up to half its flying speed."), } }, }); OGLContent.OGL_Creatures.Add("Ancient Brass Dragon"); } private static void Adult() { // new OGL_Ability() { OGL_Creature = "Brass Dragon", Title = "", attack = null, isDamage = false, isSpell = false, saveDC = 0, Description = "" }, OGLContent.OGL_Abilities.AddRange(new List<OGL_Ability>() { new OGL_Ability() { OGL_Creature = "Adult Brass Dragon", Title = "Legendary Resistance (3/Day)", attack = null, isDamage = false, isSpell = false, saveDC = 0, Description = "If the {CREATURENAME} fails a saving throw, it can choose to succeed instead." }, }); // template #region // new OGL_Ability() { OGL_Creature = "Brass Dragon", Title = "", isDamage = false, isSpell = false, saveDC = 0, Description = ""}, // new OGL_Ability() { OGL_Creature = "Brass Dragon", Title = "", isDamage = true, isSpell = false, saveDC = 0, Description = "", attack = new Attack() //{ // _Attack = "Melee Weapon Attack", // Bonus = "1", // Reach = 5, // RangeClose = 0, // RangeFar = 0, // Target = "one target", // HitDiceNumber = 2, // HitDiceSize = 6, // HitDamageBonus = 3, // HitAverageDamage = 10, // HitText = "", // HitDamageType = "fire" //} //}, #endregion OGLContent.OGL_Actions.AddRange(new List<OGL_Ability>() { new OGL_Ability() { OGL_Creature = "Adult Brass Dragon", Title = "Multiattack", isDamage = false, isSpell = false, saveDC = 0, Description = "The {CREATURENAME} can use its Frightful Presence. It then makes three attacks: one with its bite and two with its claws."}, new OGL_Ability() { OGL_Creature = "Adult Brass Dragon", Title = "Bite", isDamage = true, isSpell = false, saveDC = 0, Description = "", attack = new Attack() { _Attack = "Melee Weapon Attack", Bonus = "11", Reach = 10, RangeClose = 0, RangeFar = 0, Target = "one target", HitDiceNumber = 2, HitDiceSize = 10, HitDamageBonus = 6, HitAverageDamage = 17, HitText = "", HitDamageType = "piercing" } }, new OGL_Ability() { OGL_Creature = "Adult Brass Dragon", Title = "Claw", isDamage = true, isSpell = false, saveDC = 0, Description = "", attack = new Attack() { _Attack = "Melee Weapon Attack", Bonus = "11", Reach = 5, RangeClose = 0, RangeFar = 0, Target = "one target", HitDiceNumber = 2, HitDiceSize = 6, HitDamageBonus = 6, HitAverageDamage = 13, HitText = "", HitDamageType = "slashing" } }, new OGL_Ability() { OGL_Creature = "Adult Brass Dragon", Title = "Tail", isDamage = true, isSpell = false, saveDC = 0, Description = "", attack = new Attack() { _Attack = "Melee Weapon Attack", Bonus = "11", Reach = 15, RangeClose = 0, RangeFar = 0, Target = "one target", HitDiceNumber = 2, HitDiceSize = 8, HitDamageBonus = 6, HitAverageDamage = 15, HitText = "", HitDamageType = "bludgeoning" } }, new OGL_Ability() { OGL_Creature = "Adult Brass Dragon", Title = "Frightful Presence", isDamage = false, isSpell = false, saveDC = 0, Description = "Each creature of the {CREATURENAME}'s choice that is within 120 feet of the {CREATURENAME} and aware of it must succeed on a DC 16 Wisdom saving throw or become frightened for 1 minute. A creature can repeat the saving throw at the end of each of its turns, ending the effect on itself on a success. If a creature's saving throw is successful or the effect ends for it, the creature is immune to the {CREATURENAME}'s Frightful Presence for the next 24 hours."}, new OGL_Ability() { OGL_Creature = "Adult Brass Dragon", Title = "Breath Weapons (Recharge 5-6)", isDamage = false, isSpell = false, saveDC = 0, Description = "The {CREATURENAME} uses one of the following breath weapons: " + "<p><b>Fire Breath.</b> The {CREATURENAME} exhales fire in a 60-foot cone. Each creature in the area must make a DC 18 Dexterity saving throw, taking 45 (13d6) fire damage on a failed save, or half as much damage on a saving throw. </p>" + "<p><b>Sleep Breath.</b> The {CREATURENAME} exhales sleep gas in a 60-foot cone. Each creature in that area must succeed on a DC 18 Consitution saving throw or fall unconscious for 10 minutes. This effect ends for a creature if the creature takes damage or someone uses an action to wake it.</p>"}, }); // new OGL_Ability() { OGL_Creature = "Brass Dragon", Title = "", attack = null, isDamage = false, isSpell = false, saveDC = 0, Description = "" } OGLContent.OGL_Reactions.AddRange(new List<OGL_Ability>() { }); // Template #region //new OGL_Legendary() //{ // OGL_Creature = "Brass Dragon", // Title = "", // Traits = new List<LegendaryTrait>() // { // new LegendaryTrait("", "") // } //}, #endregion OGLContent.OGL_Legendary.AddRange(new List<OGL_Legendary>() { new OGL_Legendary() { OGL_Creature = "Adult Brass Dragon", Title = "Adult Brass Dragon Legendary Actions", Traits = new List<LegendaryTrait>() { new LegendaryTrait("Detect", "The {CREATURENAME} makes a Wisdom (Perception) check."), new LegendaryTrait("Tail Attack", "The {CREATURENAME} makes a tail attack."), new LegendaryTrait("Wing Attack (Costs 2 Actions)", "The {CREATURENAME} beats its wings. Each creature within 15 feet of the {CREATURENAME} must succeed on a DC 19 Dexterity saving throw or take 13 (2d6 + 6) bludgeoning damage and be knocked prone. The {CREATURENAME} can then fly up to half its flying speed."), } }, }); OGLContent.OGL_Creatures.Add("Adult Brass Dragon"); } private static void Young() { // new OGL_Ability() { OGL_Creature = "Brass Dragon", Title = "", attack = null, isDamage = false, isSpell = false, saveDC = 0, Description = "" }, OGLContent.OGL_Abilities.AddRange(new List<OGL_Ability>() { }); // template #region // new OGL_Ability() { OGL_Creature = "Brass Dragon", Title = "", isDamage = false, isSpell = false, saveDC = 0, Description = ""}, // new OGL_Ability() { OGL_Creature = "Brass Dragon", Title = "", isDamage = true, isSpell = false, saveDC = 0, Description = "", attack = new Attack() //{ // _Attack = "Melee Weapon Attack", // Bonus = "1", // Reach = 5, // RangeClose = 0, // RangeFar = 0, // Target = "one target", // HitDiceNumber = 2, // HitDiceSize = 6, // HitDamageBonus = 3, // HitAverageDamage = 10, // HitText = "", // HitDamageType = "fire" //} //}, #endregion OGLContent.OGL_Actions.AddRange(new List<OGL_Ability>() { new OGL_Ability() { OGL_Creature = "Young Brass Dragon", Title = "Multiattack", isDamage = false, isSpell = false, saveDC = 0, Description = "The {CREATURENAME} makes three attacks: one with its bite and two with its claws."}, new OGL_Ability() { OGL_Creature = "Young Brass Dragon", Title = "Bite", isDamage = true, isSpell = false, saveDC = 0, Description = "", attack = new Attack() { _Attack = "Melee Weapon Attack", Bonus = "7", Reach = 10, RangeClose = 0, RangeFar = 0, Target = "one target", HitDiceNumber = 2, HitDiceSize = 10, HitDamageBonus = 4, HitAverageDamage = 15, HitText = "", HitDamageType = "piercing" } }, new OGL_Ability() { OGL_Creature = "Young Brass Dragon", Title = "Claw", isDamage = true, isSpell = false, saveDC = 0, Description = "", attack = new Attack() { _Attack = "Melee Weapon Attack", Bonus = "7", Reach = 5, RangeClose = 0, RangeFar = 0, Target = "one target", HitDiceNumber = 2, HitDiceSize = 6, HitDamageBonus = 4, HitAverageDamage = 11, HitText = "", HitDamageType = "slashing" } }, new OGL_Ability() { OGL_Creature = "Young Brass Dragon", Title = "Breath Weapons (Recharge 5-6)", isDamage = false, isSpell = false, saveDC = 0, Description = "The {CREATURENAME} uses one of the following breath weapons: " + "<p><b>Fire Breath.</b> The {CREATURENAME} exhales fire in a 30-foot cone. Each creature in the area must make a DC 14 Dexterity saving throw, taking 42 (12d6) fire damage on a failed save, or half as much damage on a saving throw. </p>" + "<p><b>Sleep Breath.</b> The {CREATURENAME} exhales sleep gas in a 30-foot cone. Each creature in that area must succeed on a DC 14 Consitution saving throw or fall unconscious for 5 minutes. This effect ends for a creature if the creature takes damage or someone uses an action to wake it.</p>"}, }); // new OGL_Ability() { OGL_Creature = "Brass Dragon", Title = "", attack = null, isDamage = false, isSpell = false, saveDC = 0, Description = "" } OGLContent.OGL_Reactions.AddRange(new List<OGL_Ability>() { }); OGLContent.OGL_Creatures.Add("Young Brass Dragon"); } private static void Wyrmling() { // new OGL_Ability() { OGL_Creature = "Brass Dragon", Title = "", attack = null, isDamage = false, isSpell = false, saveDC = 0, Description = "" }, OGLContent.OGL_Abilities.AddRange(new List<OGL_Ability>() { }); // template #region // new OGL_Ability() { OGL_Creature = "Brass Dragon", Title = "", isDamage = false, isSpell = false, saveDC = 0, Description = ""}, // new OGL_Ability() { OGL_Creature = "Brass Dragon", Title = "", isDamage = true, isSpell = false, saveDC = 0, Description = "", attack = new Attack() //{ // _Attack = "Melee Weapon Attack", // Bonus = "1", // Reach = 5, // RangeClose = 0, // RangeFar = 0, // Target = "one target", // HitDiceNumber = 2, // HitDiceSize = 6, // HitDamageBonus = 3, // HitAverageDamage = 10, // HitText = "", // HitDamageType = "fire" //} //}, #endregion OGLContent.OGL_Actions.AddRange(new List<OGL_Ability>() { new OGL_Ability() { OGL_Creature = "Brass Dragon Wyrmling", Title = "Bite", isDamage = true, isSpell = false, saveDC = 0, Description = "", attack = new Attack() { _Attack = "Melee Weapon Attack", Bonus = "4", Reach = 5, RangeClose = 0, RangeFar = 0, Target = "one target", HitDiceNumber = 1, HitDiceSize = 10, HitDamageBonus = 2, HitAverageDamage = 7, HitText = "", HitDamageType = "piercing" } }, new OGL_Ability() { OGL_Creature = "Young Brass Dragon", Title = "Breath Weapons (Recharge 5-6)", isDamage = false, isSpell = false, saveDC = 0, Description = "The {CREATURENAME} uses one of the following breath weapons: " + "<p><b>Fire Breath.</b> The {CREATURENAME} exhales fire in a 15-foot cone. Each creature in the area must make a DC 14 Dexterity saving throw, taking 14 (4d6) fire damage on a failed save, or half as much damage on a saving throw. </p>" + "<p><b>Sleep Breath.</b> The {CREATURENAME} exhales sleep gas in a 15-foot cone. Each creature in that area must succeed on a DC 11 Consitution saving throw or fall unconscious for 1 minutes. This effect ends for a creature if the creature takes damage or someone uses an action to wake it.</p>"}, }); OGLContent.OGL_Creatures.Add("Brass Dragon Wyrmling"); } } }
56.928571
828
0.503223
[ "Apache-2.0" ]
FallenWyvern/DnD-Monster-Generator
DND_Monster/OGL_Content/D/Dragons - Metallic/BrassDragon.cs
23,115
C#
namespace Trybot.Tests.CircuitBreakerTests { internal enum State { Open, Closed, HalfOpen } }
13.1
43
0.564885
[ "MIT" ]
z4kn4fein/trybot
test/CircuitBreakerTests/State.cs
133
C#
using System.Drawing; using SharpDX.Direct3D9; using SAModel.Direct3D; using SAModel.SAEditorCommon.Properties; using Mesh = SAModel.Direct3D.Mesh; //using SAModel.SAEditorCommon.DataTypes; namespace SAModel.SAEditorCommon.UI { /// <summary> /// Houses elements common to several kinds of gizmos / helpers. /// </summary> public static class Gizmo { // 'null' meshes - for when no transforms are available, but users still want to know that something *is* selected public static Mesh XNullMesh { get; set; } public static Mesh YNullMesh { get; set; } public static Mesh ZNullMesh { get; set; } // movement meshes - used for both display and mouse picking public static Mesh XMoveMesh { get; set; } public static Mesh YMoveMesh { get; set; } public static Mesh ZMoveMesh { get; set; } public static Mesh XYMoveMesh { get; set; } public static Mesh ZXMoveMesh { get; set; } public static Mesh ZYMoveMesh { get; set; } // rotation meshes - used for both display and mouse picking public static Mesh XRotateMesh { get; set; } public static Mesh YRotateMesh { get; set; } public static Mesh ZRotateMesh { get; set; } // scale meshes - used for both display and mouse picking public static Mesh XScaleMesh { get; set; } public static Mesh YScaleMesh { get; set; } public static Mesh ZScaleMesh { get; set; } // box mesh - you know, just in case you need one. public static Mesh BoxMesh { get; set; } // materials for rendering the above meshes public static NJS_MATERIAL XMaterial { get; set; } public static NJS_MATERIAL YMaterial { get; set; } public static NJS_MATERIAL ZMaterial { get; set; } public static NJS_MATERIAL DoubleAxisMaterial { get; set; } public static NJS_MATERIAL HighlightMaterial { get; set; } public static NJS_MATERIAL StandardMaterial { get; set; } public static Texture ATexture { get; set; } public static Texture BTexture { get; set; } public static void InitGizmo(Device d3dDevice) { Attach attach = new ModelFile(Resources.x_null).Model.Attach; attach.ProcessVertexData(); XNullMesh = attach.CreateD3DMesh(); attach = new ModelFile(Resources.y_null).Model.Attach; attach.ProcessVertexData(); YNullMesh = attach.CreateD3DMesh(); attach = new ModelFile(Resources.z_null).Model.Attach; attach.ProcessVertexData(); ZNullMesh = attach.CreateD3DMesh(); attach = new ModelFile(Resources.x_move).Model.Attach; attach.ProcessVertexData(); XMoveMesh = attach.CreateD3DMesh(); XMaterial = ((BasicAttach)attach).Material[0]; attach = new ModelFile(Resources.y_move).Model.Attach; attach.ProcessVertexData(); YMoveMesh = attach.CreateD3DMesh(); YMaterial = ((BasicAttach)attach).Material[0]; attach = new ModelFile(Resources.z_move).Model.Attach; attach.ProcessVertexData(); ZMoveMesh = attach.CreateD3DMesh(); ZMaterial = ((BasicAttach)attach).Material[0]; attach = new ModelFile(Resources.xy_move).Model.Attach; attach.ProcessVertexData(); XYMoveMesh = attach.CreateD3DMesh(); DoubleAxisMaterial = ((BasicAttach)attach).Material[0]; attach = new ModelFile(Resources.zx_move).Model.Attach; attach.ProcessVertexData(); ZXMoveMesh = attach.CreateD3DMesh(); attach = new ModelFile(Resources.zy_move).Model.Attach; attach.ProcessVertexData(); ZYMoveMesh = attach.CreateD3DMesh(); attach = new ModelFile(Resources.x_rotation).Model.Attach; attach.ProcessVertexData(); XRotateMesh = attach.CreateD3DMesh(); attach = new ModelFile(Resources.y_rotation).Model.Attach; attach.ProcessVertexData(); YRotateMesh = attach.CreateD3DMesh(); attach = new ModelFile(Resources.z_rotation).Model.Attach; attach.ProcessVertexData(); ZRotateMesh = attach.CreateD3DMesh(); attach = new ModelFile(Resources.x_scale).Model.Attach; attach.ProcessVertexData(); XScaleMesh = attach.CreateD3DMesh(); attach = new ModelFile(Resources.y_scale).Model.Attach; attach.ProcessVertexData(); YScaleMesh = attach.CreateD3DMesh(); attach = new ModelFile(Resources.z_scale).Model.Attach; attach.ProcessVertexData(); ZScaleMesh = attach.CreateD3DMesh(); BoxMesh = Mesh.Box(1, 1, 1); HighlightMaterial = new NJS_MATERIAL() { DiffuseColor = Color.LightGoldenrodYellow, Exponent = 0f, UseTexture = false, IgnoreLighting = true, IgnoreSpecular = true }; ATexture = Resources.PointATexture.ToTexture(d3dDevice); BTexture = Resources.PointBTexture.ToTexture(d3dDevice); StandardMaterial = new NJS_MATERIAL() { DiffuseColor = Color.Gray, IgnoreLighting = true, IgnoreSpecular = true, UseAlpha = false, UseTexture = true, Exponent = 100f }; } } }
35.946154
171
0.73165
[ "MIT", "BSD-3-Clause" ]
X-Hax/sa_tools
Libraries/SAEditorCommon/UI/Gizmo.cs
4,675
C#
namespace BBX.Entity { public class ShowbonusPagePostInfo : ShowtopicPagePostInfo { private int m_bonus; public int Bonus { get { return m_bonus; } set { m_bonus = value; } } private int m_isbest; public int Isbest { get { return m_isbest; } set { m_isbest = value; } } private int m_bonusextid; public int Bonusextid { get { return m_bonusextid; } set { m_bonusextid = value; } } } }
30.333333
92
0.617582
[ "MIT" ]
NewLifeX/BBX
BBX.Entity/_OLD/ShowbonusPagePostInfo.cs
455
C#
using System; using System.IO; using System.Text; using AutoMapper; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.Configuration; namespace EggsAndHoney.WebApi.Tests { public class OrdersApiTestBase : IDisposable { protected readonly TestServer _server; protected readonly System.Net.Http.HttpClient _client; protected const string __postContentType = "application/json"; protected readonly Encoding _defaultEncoding = Encoding.UTF8; protected const string __apiPrefix = "/api/v1"; protected static readonly string _ordersEndpoint = $"{__apiPrefix}/orders"; protected static readonly string _ordersCountEndpoint = $"{__apiPrefix}/orders/count"; protected static readonly string _resolvedOrdersEndpoint = $"{__apiPrefix}/resolvedorders"; protected static readonly string _addOrderEndpoint = $"{_ordersEndpoint}/add"; protected static readonly string _resolveOrderEndpoint = $"{_ordersEndpoint}/resolve"; protected static readonly string _unresolveOrderEndpoint = $"{_resolvedOrdersEndpoint}/unresolve"; public OrdersApiTestBase() { // Quick way to avoid Automapper reinitialization warnings // https://stackoverflow.com/a/47552436/240424 ServiceCollectionExtensions.UseStaticRegistration = false; var configuration = new ConfigurationBuilder() .AddJsonFile("appsettings.json", optional: false) .Build(); _server = new TestServer(new WebHostBuilder().UseConfiguration(configuration).UseStartup<Startup>()); Program.EnsureInMemoryDataExists(_server.Host.Services); _client = _server.CreateClient(); } public void Dispose() { _server.Dispose(); _client.Dispose(); } } }
39.571429
113
0.682826
[ "MIT" ]
Yakimych/EggsAndHoneyWebApi
src/EggsAndHoney.WebApi.Tests/OrdersApiTestBase.cs
1,941
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Linq; using System.Threading.Tasks; using Azure.AI.FormRecognizer.Training; using Azure.Core.TestFramework; using NUnit.Framework; namespace Azure.AI.FormRecognizer.Tests { /// <summary> /// The suite of tests for the <see cref="FormTrainingClient"/> class. /// </summary> /// <remarks> /// These tests have a dependency on live Azure services and may incur costs for the associated /// Azure subscription. /// </remarks> public class FormTrainingClientLiveTests : FormRecognizerLiveTestBase { /// <summary> /// Initializes a new instance of the <see cref="FormTrainingClientLiveTests"/> class. /// </summary> /// <param name="isAsync">A flag used by the Azure Core Test Framework to differentiate between tests for asynchronous and synchronous methods.</param> public FormTrainingClientLiveTests(bool isAsync) : base(isAsync) { } [Test] public async Task FormTrainingClientCanAuthenticateWithTokenCredential() { var client = CreateInstrumentedFormTrainingClient(useTokenCredential: true); var trainingFilesUri = new Uri(TestEnvironment.BlobContainerSasUrl); TrainingOperation operation; // TODO: sanitize body and enable body recording here. using (Recording.DisableRequestBodyRecording()) { operation = await client.StartTrainingAsync(trainingFilesUri, useTrainingLabels: false); } // Sanity check to make sure we got an actual response back from the service. CustomFormModel model = await operation.WaitForCompletionAsync(); Assert.IsNotNull(model.ModelId); Assert.AreEqual(CustomFormModelStatus.Ready, model.Status); Assert.IsNotNull(model.Errors); Assert.AreEqual(0, model.Errors.Count); } [Test] [TestCase(true)] [TestCase(false)] public async Task StartTraining(bool labeled) { var client = CreateInstrumentedFormTrainingClient(); var trainingFilesUri = new Uri(TestEnvironment.BlobContainerSasUrl); TrainingOperation operation; // TODO: sanitize body and enable body recording here. using (Recording.DisableRequestBodyRecording()) { operation = await client.StartTrainingAsync(trainingFilesUri, labeled); } await operation.WaitForCompletionAsync(); Assert.IsTrue(operation.HasValue); CustomFormModel model = operation.Value; Assert.IsNotNull(model.ModelId); Assert.IsNotNull(model.RequestedOn); Assert.IsNotNull(model.CompletedOn); Assert.AreEqual(CustomFormModelStatus.Ready, model.Status); Assert.IsNotNull(model.Errors); Assert.AreEqual(0, model.Errors.Count); foreach (TrainingDocumentInfo doc in model.TrainingDocuments) { Assert.IsNotNull(doc.DocumentName); Assert.IsNotNull(doc.PageCount); Assert.AreEqual(TrainingStatus.Succeeded, doc.Status); Assert.IsNotNull(doc.Errors); Assert.AreEqual(0, doc.Errors.Count); } foreach (var submodel in model.Submodels) { Assert.IsNotNull(submodel.FormType); foreach (var fields in submodel.Fields) { Assert.IsNotNull(fields.Value.Name); if (labeled) Assert.IsNotNull(fields.Value.Accuracy); else Assert.IsNotNull(fields.Value.Label); } } } [Test] public async Task StartTrainingError() { var client = CreateInstrumentedFormTrainingClient(); var containerUrl = new Uri("https://someUrl"); TrainingOperation operation = await client.StartTrainingAsync(containerUrl, useTrainingLabels: false); Assert.ThrowsAsync<RequestFailedException>(async () => await operation.WaitForCompletionAsync()); Assert.False(operation.HasValue); Assert.Throws<RequestFailedException>(() => operation.Value.GetType()); } [Test] [TestCase(true)] [TestCase(false)] public async Task TrainingOps(bool labeled) { var client = CreateInstrumentedFormTrainingClient(); var trainingFilesUri = new Uri(TestEnvironment.BlobContainerSasUrl); TrainingOperation operation; // TODO: sanitize body and enable body recording here. using (Recording.DisableRequestBodyRecording()) { operation = await client.StartTrainingAsync(trainingFilesUri, labeled); } await operation.WaitForCompletionAsync(); Assert.IsTrue(operation.HasValue); CustomFormModel trainedModel = operation.Value; CustomFormModel resultModel = await client.GetCustomModelAsync(trainedModel.ModelId); Assert.AreEqual(trainedModel.ModelId, resultModel.ModelId); Assert.AreEqual(trainedModel.RequestedOn, resultModel.RequestedOn); Assert.AreEqual(trainedModel.CompletedOn, resultModel.CompletedOn); Assert.AreEqual(CustomFormModelStatus.Ready, resultModel.Status); Assert.AreEqual(trainedModel.Status, resultModel.Status); Assert.AreEqual(trainedModel.Errors.Count, resultModel.Errors.Count); for (int i = 0; i < resultModel.TrainingDocuments.Count; i++) { var tm = trainedModel.TrainingDocuments[i]; var rm = resultModel.TrainingDocuments[i]; Assert.AreEqual(tm.DocumentName, rm.DocumentName); Assert.AreEqual(tm.PageCount, rm.PageCount); Assert.AreEqual(TrainingStatus.Succeeded, rm.Status); Assert.AreEqual(tm.Status, rm.Status); Assert.AreEqual(tm.Errors.Count, rm.Errors.Count); } for (int i = 0; i < resultModel.Submodels.Count; i++) { Assert.AreEqual(trainedModel.Submodels[i].FormType, resultModel.Submodels[i].FormType); foreach (var fields in resultModel.Submodels[i].Fields) { Assert.AreEqual(trainedModel.Submodels[i].Fields[fields.Key].Name, fields.Value.Name); if (labeled) Assert.AreEqual(trainedModel.Submodels[i].Fields[fields.Key].Accuracy, fields.Value.Accuracy); else Assert.AreEqual(trainedModel.Submodels[i].Fields[fields.Key].Label, fields.Value.Label); } } CustomFormModelInfo modelInfo = client.GetCustomModelsAsync().ToEnumerableAsync().Result.FirstOrDefault(); Assert.IsNotNull(modelInfo.ModelId); Assert.IsNotNull(modelInfo.RequestedOn); Assert.IsNotNull(modelInfo.CompletedOn); Assert.IsNotNull(modelInfo.Status); AccountProperties accountP = await client.GetAccountPropertiesAsync(); Assert.IsNotNull(accountP.CustomModelCount); Assert.IsNotNull(accountP.CustomModelLimit); await client.DeleteModelAsync(trainedModel.ModelId); Assert.ThrowsAsync<RequestFailedException>(() => client.GetCustomModelAsync(trainedModel.ModelId)); } [Test] [Ignore("Tracked by issue: https://github.com/Azure/azure-sdk-for-net/issues/12193")] public async Task CopyModel() { var sourceClient = CreateInstrumentedFormTrainingClient(); var targetClient = CreateInstrumentedFormTrainingClient(); var resourceID = TestEnvironment.TargetResourceId; var region = TestEnvironment.TargetResourceRegion; await using var trainedModel = await CreateDisposableTrainedModelAsync(useTrainingLabels: true); CopyAuthorization targetAuth = await targetClient.GetCopyAuthorizationAsync(resourceID, region); CopyModelOperation operation; // TODO: sanitize body and enable body recording here. using (Recording.DisableRequestBodyRecording()) { operation = await sourceClient.StartCopyModelAsync(trainedModel.ModelId, targetAuth); } await operation.WaitForCompletionAsync(); Assert.IsTrue(operation.HasValue); CustomFormModelInfo modelCopied = operation.Value; Assert.IsNotNull(modelCopied.CompletedOn); Assert.IsNotNull(modelCopied.RequestedOn); Assert.AreEqual(targetAuth.ModelId, modelCopied.ModelId); Assert.AreNotEqual(trainedModel.ModelId, modelCopied.ModelId); } [Test] [Ignore("Tracked by issue: https://github.com/Azure/azure-sdk-for-net/issues/12193")] public async Task CopyModelError() { var sourceClient = CreateInstrumentedFormTrainingClient(); var targetClient = CreateInstrumentedFormTrainingClient(); var resourceID = TestEnvironment.TargetResourceId; var region = TestEnvironment.TargetResourceRegion; CopyAuthorization targetAuth = await targetClient.GetCopyAuthorizationAsync(resourceID, region); Assert.ThrowsAsync<RequestFailedException>(async () => await sourceClient.StartCopyModelAsync("00000000-0000-0000-0000-000000000000", targetAuth)); } [Test] [Ignore("Tracked by issue: https://github.com/Azure/azure-sdk-for-net/issues/12193")] public async Task GetCopyAuthorization() { var targetClient = CreateInstrumentedFormTrainingClient(); var resourceID = TestEnvironment.TargetResourceId; var region = TestEnvironment.TargetResourceRegion; CopyAuthorization targetAuth = await targetClient.GetCopyAuthorizationAsync(resourceID, region); Assert.IsNotNull(targetAuth.ModelId); Assert.IsNotNull(targetAuth.AccessToken); Assert.IsNotNull(targetAuth.ExpiresOn); Assert.AreEqual(resourceID, targetAuth.ResourceId); Assert.AreEqual(region, targetAuth.Region); } [Test] [Ignore("Tracked by issue: https://github.com/Azure/azure-sdk-for-net/issues/12193")] public async Task SerializeDeserializeCopyAuthorizationAsync() { var targetClient = CreateInstrumentedFormTrainingClient(); var resourceID = TestEnvironment.TargetResourceId; var region = TestEnvironment.TargetResourceRegion; CopyAuthorization targetAuth = await targetClient.GetCopyAuthorizationAsync(resourceID, region); string jsonTargetAuth = targetAuth.ToJson(); CopyAuthorization targetAuthFromJson = CopyAuthorization.FromJson(jsonTargetAuth); Assert.AreEqual(targetAuth.ModelId, targetAuthFromJson.ModelId); Assert.AreEqual(targetAuth.ExpiresOn, targetAuthFromJson.ExpiresOn); Assert.AreEqual(targetAuth.AccessToken, targetAuthFromJson.AccessToken); Assert.AreEqual(targetAuth.ResourceId, targetAuthFromJson.ResourceId); Assert.AreEqual(targetAuth.Region, targetAuthFromJson.Region); } } }
42.341818
159
0.644023
[ "MIT" ]
LeighS/azure-sdk-for-net
sdk/formrecognizer/Azure.AI.FormRecognizer/tests/FormTrainingClient/FormTrainingClientLiveTests.cs
11,646
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Diagnostics; using Tools; using Xunit; namespace System.Numerics.Tests { public class op_multiplyTest { private static int s_samples = 10; private static Random s_random = new Random(100); [Fact] public static void RunMultiplyPositive() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; // Multiply Method - Two Large BigIntegers for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random); tempByteArray2 = GetRandomByteArray(s_random); VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*"); } // Multiply Method - Two Small BigIntegers for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random, 2); tempByteArray2 = GetRandomByteArray(s_random, 2); VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*"); } // Multiply Method - One large and one small BigIntegers for (int i = 0; i < s_samples; i++) { try { tempByteArray1 = GetRandomByteArray(s_random); tempByteArray2 = GetRandomByteArray(s_random, 2); VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*"); tempByteArray1 = GetRandomByteArray(s_random, 2); tempByteArray2 = GetRandomByteArray(s_random); VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*"); } catch (IndexOutOfRangeException) { // TODO: Refactor this Console.WriteLine("Array1: " + Print(tempByteArray1)); Console.WriteLine("Array2: " + Print(tempByteArray2)); throw; } } } [Fact] public static void RunMultiplyPositiveWith0() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; // Multiply Method - One large BigIntegers and zero for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random); tempByteArray2 = new byte[] { 0 }; VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*"); tempByteArray1 = new byte[] { 0 }; tempByteArray2 = GetRandomByteArray(s_random); VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*"); } // Multiply Method - One small BigIntegers and zero for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random, 2); tempByteArray2 = new byte[] { 0 }; VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*"); tempByteArray1 = new byte[] { 0 }; tempByteArray2 = GetRandomByteArray(s_random, 2); VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*"); } } [Fact] public static void RunMultiplyAxiomXmult1() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; // Axiom: X*1 = X VerifyIdentityString(Int32.MaxValue + " " + BigInteger.One + " b*", Int32.MaxValue.ToString()); VerifyIdentityString(Int64.MaxValue + " " + BigInteger.One + " b*", Int64.MaxValue.ToString()); for (int i = 0; i < s_samples; i++) { String randBigInt = Print(GetRandomByteArray(s_random)); VerifyIdentityString(randBigInt + BigInteger.One + " b*", randBigInt + "u+"); } } [Fact] public static void RunMultiplyAxiomXmult0() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; // Axiom: X*0 = 0 VerifyIdentityString(Int32.MaxValue + " " + BigInteger.Zero + " b*", BigInteger.Zero.ToString()); VerifyIdentityString(Int64.MaxValue + " " + BigInteger.Zero + " b*", BigInteger.Zero.ToString()); for (int i = 0; i < s_samples; i++) { String randBigInt = Print(GetRandomByteArray(s_random)); VerifyIdentityString(randBigInt + BigInteger.Zero + " b*", BigInteger.Zero.ToString()); } } [Fact] public static void RunMultiplyAxiomComm() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; // Check interesting cases for boundary conditions // You'll either be shifting a 0 or 1 across the boundary // 32 bit boundary n2=0 VerifyMultiplyString(Math.Pow(2, 32) + " 2 b*"); // 32 bit boundary n1=0 n2=1 VerifyMultiplyString(Math.Pow(2, 33) + " 2 b*"); } [Fact] public static void RunMultiplyBoundary() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; // Check interesting cases for boundary conditions // You'll either be shifting a 0 or 1 across the boundary // 32 bit boundary n2=0 VerifyMultiplyString(Math.Pow(2, 32) + " 2 b*"); // 32 bit boundary n1=0 n2=1 VerifyMultiplyString(Math.Pow(2, 33) + " 2 b*"); } [Fact] public static void RunMultiplyTests() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; // Multiply Method - Two Large BigIntegers for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random); tempByteArray2 = GetRandomByteArray(s_random); VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*"); } // Multiply Method - Two Small BigIntegers for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random, 2); tempByteArray2 = GetRandomByteArray(s_random, 2); VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*"); } // Multiply Method - One large and one small BigIntegers for (int i = 0; i < s_samples; i++) { try { tempByteArray1 = GetRandomByteArray(s_random); tempByteArray2 = GetRandomByteArray(s_random, 2); VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*"); tempByteArray1 = GetRandomByteArray(s_random, 2); tempByteArray2 = GetRandomByteArray(s_random); VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*"); } catch (IndexOutOfRangeException) { // TODO: Refactor this Console.WriteLine("Array1: " + Print(tempByteArray1)); Console.WriteLine("Array2: " + Print(tempByteArray2)); throw; } } // Multiply Method - One large BigIntegers and zero for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random); tempByteArray2 = new byte[] { 0 }; VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*"); tempByteArray1 = new byte[] { 0 }; tempByteArray2 = GetRandomByteArray(s_random); VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*"); } // Multiply Method - One small BigIntegers and zero for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random, 2); tempByteArray2 = new byte[] { 0 }; VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*"); tempByteArray1 = new byte[] { 0 }; tempByteArray2 = GetRandomByteArray(s_random, 2); VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*"); } // Axiom: X*1 = X VerifyIdentityString(Int32.MaxValue + " " + BigInteger.One + " b*", Int32.MaxValue.ToString()); VerifyIdentityString(Int64.MaxValue + " " + BigInteger.One + " b*", Int64.MaxValue.ToString()); for (int i = 0; i < s_samples; i++) { String randBigInt = Print(GetRandomByteArray(s_random)); VerifyIdentityString(randBigInt + BigInteger.One + " b*", randBigInt + "u+"); } // Axiom: X*0 = 0 VerifyIdentityString(Int32.MaxValue + " " + BigInteger.Zero + " b*", BigInteger.Zero.ToString()); VerifyIdentityString(Int64.MaxValue + " " + BigInteger.Zero + " b*", BigInteger.Zero.ToString()); for (int i = 0; i < s_samples; i++) { String randBigInt = Print(GetRandomByteArray(s_random)); VerifyIdentityString(randBigInt + BigInteger.Zero + " b*", BigInteger.Zero.ToString()); } // Axiom: a*b = b*a VerifyIdentityString(Int32.MaxValue + " " + Int64.MaxValue + " b*", Int64.MaxValue + " " + Int32.MaxValue + " b*"); for (int i = 0; i < s_samples; i++) { String randBigInt1 = Print(GetRandomByteArray(s_random)); String randBigInt2 = Print(GetRandomByteArray(s_random)); VerifyIdentityString(randBigInt1 + randBigInt2 + "b*", randBigInt2 + randBigInt1 + "b*"); } // Check interesting cases for boundary conditions // You'll either be shifting a 0 or 1 across the boundary // 32 bit boundary n2=0 VerifyMultiplyString(Math.Pow(2, 32) + " 2 b*"); // 32 bit boundary n1=0 n2=1 VerifyMultiplyString(Math.Pow(2, 33) + " 2 b*"); } private static void VerifyMultiplyString(string opstring) { StackCalc sc = new StackCalc(opstring); while (sc.DoNextOperation()) { Assert.Equal(sc.snCalc.Peek().ToString(), sc.myCalc.Peek().ToString()); } } private static void VerifyIdentityString(string opstring1, string opstring2) { StackCalc sc1 = new StackCalc(opstring1); while (sc1.DoNextOperation()) { //Run the full calculation sc1.DoNextOperation(); } StackCalc sc2 = new StackCalc(opstring2); while (sc2.DoNextOperation()) { //Run the full calculation sc2.DoNextOperation(); } Assert.Equal(sc1.snCalc.Peek().ToString(), sc2.snCalc.Peek().ToString()); } private static byte[] GetRandomByteArray(Random random) { return GetRandomByteArray(random, random.Next(0, 100)); } private static byte[] GetRandomByteArray(Random random, int size) { return MyBigIntImp.GetRandomByteArray(random, size); } private static String Print(byte[] bytes) { return MyBigIntImp.Print(bytes); } } }
39.456026
127
0.534962
[ "MIT" ]
ProgramFOX/corefx
src/System.Runtime.Numerics/tests/BigInteger/op_multiply.cs
12,113
C#
namespace KimaiDotNet.Reporting.ODataService { public static class Constants { public static class HttpClients{ public const string Kimai = "Kimai"; } } }
21.666667
48
0.625641
[ "MIT" ]
KimaiDotNet/KimaiDotNet.oDataReporting
src/KimaiDotNet.Reporting.ODataService/Constants.cs
197
C#
using System; using Microsoft.EntityFrameworkCore.Migrations; namespace TimeMachine.Data.Migrations { public partial class UpdateUsersTable : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AddColumn<DateTime>( name: "CreateProfileOn", table: "ReaderProfiles", nullable: false, defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified)); migrationBuilder.AddColumn<DateTime>( name: "CreateProfileOn", table: "AspNetUsers", nullable: false, defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified)); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropColumn( name: "CreateProfileOn", table: "ReaderProfiles"); migrationBuilder.DropColumn( name: "CreateProfileOn", table: "AspNetUsers"); } } }
31.8
91
0.574124
[ "MIT" ]
MilenaPetkanova/time-machine-app
src/Data/TimeMachine.Data/Migrations/20190101193724_UpdateUsersTable.cs
1,115
C#
using System.Collections.Generic; using System.IO; using TR2RandomizerCore.Helpers; using TRGE.Core; using TRModelTransporter.Utilities; namespace TR2RandomizerCore.Processors { internal class TextureDeduplicator : LevelProcessor { public void Deduplicate() { List<DeduplicationProcessor> processors = new List<DeduplicationProcessor> { new DeduplicationProcessor(this) }; int levelSplit = (int)(Levels.Count / _maxThreads); bool beginProcessing = true; foreach (TR23ScriptedLevel lvl in Levels) { if (processors[processors.Count - 1].LevelCount == levelSplit) { // Kick start the last one processors[processors.Count - 1].Start(); processors.Add(new DeduplicationProcessor(this)); } processors[processors.Count - 1].AddLevel(LoadCombinedLevel(lvl)); if (!TriggerProgress()) { beginProcessing = false; break; } } if (beginProcessing) { foreach (DeduplicationProcessor processor in processors) { processor.Start(); } foreach (DeduplicationProcessor processor in processors) { processor.Join(); } } if (_processingException != null) { _processingException.Throw(); } } internal class DeduplicationProcessor : AbstractProcessorThread<TextureDeduplicator> { private readonly List<TR2CombinedLevel> _levels; private readonly TRLevelTextureDeduplicator _deduplicator; internal override int LevelCount => _levels.Count; internal DeduplicationProcessor(TextureDeduplicator outer) :base(outer) { _levels = new List<TR2CombinedLevel>(); _deduplicator = new TRLevelTextureDeduplicator(); } internal void AddLevel(TR2CombinedLevel level) { _levels.Add(level); } protected override void ProcessImpl() { foreach (TR2CombinedLevel level in _levels) { string dedupPath = @"Resources\Textures\Deduplication\" + level.JsonID + "-TextureRemap.json"; if (File.Exists(dedupPath)) { _deduplicator.Level = level.Data; _deduplicator.Deduplicate(dedupPath); _outer.SaveLevel(level); } if (!_outer.TriggerProgress()) { break; } } } } } }
31.765957
124
0.507368
[ "MIT" ]
Anopob/TR2-Rando
TR2RandomizerCore/Processors/TextureDeduplicator.cs
2,988
C#
// ----------------------------------------------------------------------- // <copyright file="Program.cs" company="Asynkron HB"> // Copyright (C) 2015-2018 Asynkron HB All rights reserved // </copyright> // ----------------------------------------------------------------------- using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Proto; class Program { static void Main(string[] args) { var context = new RootContext(); Log.SetLoggerFactory(new LoggerFactory() .AddConsole(LogLevel.Debug)); var props = Props.FromProducer(() => new ParentActor()).WithChildSupervisorStrategy(new OneForOneStrategy(Decider.Decide, 1, null)); var actor = context.Spawn(props); context.Send(actor,new Hello { Who = "Alex" }); context.Send(actor,new Recoverable()); context.Send(actor,new Fatal()); //why wait? //Stop is a system message and is not processed through the user message mailbox //thus, it will be handled _before_ any user message //we only do this to show the correct order of events in the console Thread.Sleep(TimeSpan.FromSeconds(1)); actor.Stop(); Console.ReadLine(); } internal class Decider { public static SupervisorDirective Decide(PID pid, Exception reason) { switch (reason) { case RecoverableException _: return SupervisorDirective.Restart; case FatalException _: return SupervisorDirective.Stop; default: return SupervisorDirective.Escalate; } } } internal class ParentActor : IActor { public Task ReceiveAsync(IContext context) { PID child; if (context.Children == null || context.Children.Count == 0) { var props = Props.FromProducer(() => new ChildActor()); child = context.Spawn(props); } else { child = context.Children.First(); } switch (context.Message) { case Hello _: case Recoverable _: case Fatal _: context.Forward(child); break; case Terminated r: Console.WriteLine("Watched actor was Terminated, {0}", r.Who); break; } return Actor.Done; } } internal class ChildActor : IActor { private ILogger logger = Log.CreateLogger<ChildActor>(); public Task ReceiveAsync(IContext context) { switch (context.Message) { case Hello r: logger.LogDebug($"Hello {r.Who}"); break; case Recoverable _: throw new RecoverableException(); case Fatal _: throw new FatalException(); case Started _: logger.LogDebug("Started, initialize actor here"); break; case Stopping _: logger.LogDebug("Stopping, actor is about shut down"); break; case Stopped _: logger.LogDebug("Stopped, actor and it's children are stopped"); break; case Restarting _: logger.LogDebug("Restarting, actor is about restart"); break; } return Actor.Done; } } internal class Hello { public string Who; } internal class RecoverableException : Exception { } internal class FatalException : Exception { } internal class Fatal { } internal class Recoverable { } }
31.147287
140
0.502738
[ "Apache-2.0" ]
kenavn/protoactor-dotnet
examples/Supervision/Program.cs
4,020
C#
using System; using System.Collections.Generic; using System.Linq; using UniGLTF; using UnityEngine; namespace UniVRM10 { [Serializable] public class VRM10ObjectMeta { [SerializeField] public string ExporterVersion; #region Info [SerializeField] public string Name; [SerializeField] public string Version; [SerializeField] public string CopyrightInformation; [SerializeField] public List<string> Authors = new List<string>(); [SerializeField] public string ContactInformation; [SerializeField] public List<string> References = new List<string>(); [SerializeField] public Texture2D Thumbnail; #endregion #region AvatarPermission [SerializeField, Tooltip("A person who can perform with this avatar")] public UniGLTF.Extensions.VRMC_vrm.AvatarPermissionType AllowedUser; [SerializeField, Tooltip("Violent acts using this avatar")] public bool ViolentUsage; [SerializeField, Tooltip("Sexuality acts using this avatar")] public bool SexualUsage; [SerializeField, Tooltip("For commercial use")] public UniGLTF.Extensions.VRMC_vrm.CommercialUsageType CommercialUsage; [SerializeField] public bool GameUsage; [SerializeField] public bool PoliticalOrReligiousUsage; [SerializeField, Tooltip("Other License Url")] public string OtherPermissionUrl; #endregion #region Distribution License [SerializeField] public UniGLTF.Extensions.VRMC_vrm.CreditNotationType CreditNotation; [SerializeField] public bool Redistribution; [SerializeField] public UniGLTF.Extensions.VRMC_vrm.ModificationType ModificationLicense; [SerializeField] public string OtherLicenseUrl; #endregion public IEnumerable<Validation> Validate(GameObject _) { if (string.IsNullOrEmpty(Name)) { yield return Validation.Error("Require Name. "); } if (Authors == null || Authors.Count == 0) { yield return Validation.Error("Require at leaset one Author."); } if (Authors.All(x => string.IsNullOrWhiteSpace(x))) { yield return Validation.Error("All Authors is whitespace"); } } public void CopyTo(VRM10ObjectMeta dst) { dst.ExporterVersion = ExporterVersion; dst.Name = Name; dst.Version = Version; dst.CopyrightInformation = CopyrightInformation; if (Authors != null) { dst.Authors = Authors.Select(x => x).ToList(); } else { dst.Authors = new List<string>(); } dst.ContactInformation = ContactInformation; dst.References = References; dst.Thumbnail = Thumbnail; dst.AllowedUser = AllowedUser; dst.ViolentUsage = ViolentUsage; dst.SexualUsage = SexualUsage; dst.CommercialUsage = CommercialUsage; dst.GameUsage = GameUsage; dst.PoliticalOrReligiousUsage = PoliticalOrReligiousUsage; dst.OtherPermissionUrl = OtherPermissionUrl; dst.CreditNotation = CreditNotation; dst.Redistribution = Redistribution; dst.ModificationLicense = ModificationLicense; dst.OtherLicenseUrl = OtherLicenseUrl; } } }
29.304
80
0.606061
[ "MIT" ]
Cringeyzz/UniVRM
Assets/VRM10/Runtime/Components/VRM10Object/VRM10ObjectMeta.cs
3,665
C#
using System; using System.Buffers; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace NetFabric.Hyperlinq { public static partial class ValueReadOnlyCollectionExtensions { [GeneratorMapping("TSelector", "NetFabric.Hyperlinq.FunctionWrapper<TSource, int, TResult>")] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static SelectAtEnumerable<TEnumerable, TEnumerator, TSource, TResult, FunctionWrapper<TSource, int, TResult>> Select<TEnumerable, TEnumerator, TSource, TResult>(this TEnumerable source, Func<TSource, int, TResult> selector) where TEnumerable : IValueReadOnlyCollection<TSource, TEnumerator> where TEnumerator : struct, IEnumerator<TSource> => SelectAt<TEnumerable, TEnumerator, TSource, TResult, FunctionWrapper<TSource, int, TResult>>(source, new FunctionWrapper<TSource, int, TResult>(selector)); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static SelectAtEnumerable<TEnumerable, TEnumerator, TSource, TResult, TSelector> SelectAt<TEnumerable, TEnumerator, TSource, TResult, TSelector>(this TEnumerable source, TSelector selector = default) where TEnumerable : IValueReadOnlyCollection<TSource, TEnumerator> where TEnumerator : struct, IEnumerator<TSource> where TSelector : struct, IFunction<TSource, int, TResult> => new(in source, selector); [GeneratorMapping("TSource", "TResult")] [StructLayout(LayoutKind.Auto)] public partial struct SelectAtEnumerable<TEnumerable, TEnumerator, TSource, TResult, TSelector> : IValueReadOnlyCollection<TResult, SelectAtEnumerable<TEnumerable, TEnumerator, TSource, TResult, TSelector>.Enumerator> , ICollection<TResult> where TEnumerable : IValueReadOnlyCollection<TSource, TEnumerator> where TEnumerator : struct, IEnumerator<TSource> where TSelector : struct, IFunction<TSource, int, TResult> { internal readonly TEnumerable source; internal TSelector selector; internal SelectAtEnumerable(in TEnumerable source, TSelector selector) => (this.source, this.selector) = (source, selector); public readonly int Count => source.Count; [MethodImpl(MethodImplOptions.AggressiveInlining)] public readonly Enumerator GetEnumerator() => new(in this); readonly IEnumerator<TResult> IEnumerable<TResult>.GetEnumerator() // ReSharper disable once HeapView.BoxingAllocation => new Enumerator(in this); readonly IEnumerator IEnumerable.GetEnumerator() // ReSharper disable once HeapView.BoxingAllocation => new Enumerator(in this); bool ICollection<TResult>.IsReadOnly => true; public void CopyTo(Span<TResult> span) { if (Count is 0) return; if (span.Length < Count) Throw.ArgumentException(Resource.DestinationNotLongEnough, nameof(span)); checked { using var enumerator = source.GetEnumerator(); for (var index = 0; enumerator.MoveNext(); index++) span[index] = selector.Invoke(enumerator.Current, index); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void CopyTo(TResult[] array, int arrayIndex) => CopyTo(array.AsSpan().Slice(arrayIndex)); public bool Contains(TResult item) => ContainsAt<TEnumerable, TEnumerator, TSource, TResult, TSelector>(source, item, default, selector); [ExcludeFromCodeCoverage] void ICollection<TResult>.Add(TResult item) => Throw.NotSupportedException(); [ExcludeFromCodeCoverage] void ICollection<TResult>.Clear() => Throw.NotSupportedException(); [ExcludeFromCodeCoverage] bool ICollection<TResult>.Remove(TResult item) => Throw.NotSupportedException<bool>(); [StructLayout(LayoutKind.Auto)] public struct Enumerator : IEnumerator<TResult> { [SuppressMessage("Style", "IDE0044:Add readonly modifier")] TEnumerator enumerator; // do not make readonly TSelector selector; int index; internal Enumerator(in SelectAtEnumerable<TEnumerable, TEnumerator, TSource, TResult, TSelector> enumerable) { enumerator = enumerable.source.GetEnumerator(); selector = enumerable.selector; index = -1; } public TResult Current { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => selector.Invoke(enumerator.Current, index); } object? IEnumerator.Current // ReSharper disable once HeapView.PossibleBoxingAllocation => selector.Invoke(enumerator.Current, index); [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool MoveNext() { if (enumerator.MoveNext()) { checked { index++; } return true; } return false; } [ExcludeFromCodeCoverage] [DoesNotReturn] public readonly void Reset() => Throw.NotSupportedException(); public readonly void Dispose() => enumerator.Dispose(); } #region Aggregation #endregion #region Quantifier [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Any() => source.Count is not 0; #endregion #region Filtering #endregion #region Projection [MethodImpl(MethodImplOptions.AggressiveInlining)] public SelectAtEnumerable<TEnumerable, TEnumerator, TSource, TResult2, SelectorAtSelectorCombination<TSelector, FunctionWrapper<TResult, TResult2>, TSource, TResult, TResult2>> Select<TResult2>(Func<TResult, TResult2> selector) => Select<TResult2, FunctionWrapper<TResult, TResult2>>(new FunctionWrapper<TResult, TResult2>(selector)); [MethodImpl(MethodImplOptions.AggressiveInlining)] public SelectAtEnumerable<TEnumerable, TEnumerator, TSource, TResult2, SelectorAtSelectorCombination<TSelector, TSelector2, TSource, TResult, TResult2>> Select<TResult2, TSelector2>(TSelector2 selector = default) where TSelector2 : struct, IFunction<TResult, TResult2> => ValueReadOnlyCollectionExtensions.SelectAt<TEnumerable, TEnumerator, TSource, TResult2, SelectorAtSelectorCombination<TSelector, TSelector2, TSource, TResult, TResult2>>(source, new SelectorAtSelectorCombination<TSelector, TSelector2, TSource, TResult, TResult2>(this.selector, selector)); [MethodImpl(MethodImplOptions.AggressiveInlining)] public SelectAtEnumerable<TEnumerable, TEnumerator, TSource, TResult2, SelectorAtSelectorAtCombination<TSelector, FunctionWrapper<TResult, int, TResult2>, TSource, TResult, TResult2>> Select<TResult2>(Func<TResult, int, TResult2> selector) => SelectAt<TResult2, FunctionWrapper<TResult, int, TResult2>>(new FunctionWrapper<TResult, int, TResult2>(selector)); [MethodImpl(MethodImplOptions.AggressiveInlining)] public SelectAtEnumerable<TEnumerable, TEnumerator, TSource, TResult2, SelectorAtSelectorAtCombination<TSelector, TSelector2, TSource, TResult, TResult2>> SelectAt<TResult2, TSelector2>(TSelector2 selector = default) where TSelector2 : struct, IFunction<TResult, int, TResult2> => ValueReadOnlyCollectionExtensions.SelectAt<TEnumerable, TEnumerator, TSource, TResult2, SelectorAtSelectorAtCombination<TSelector, TSelector2, TSource, TResult, TResult2>>(source, new SelectorAtSelectorAtCombination<TSelector, TSelector2, TSource, TResult, TResult2>(this.selector, selector)); [MethodImpl(MethodImplOptions.AggressiveInlining)] public readonly ValueEnumerableExtensions.SelectManyEnumerable<SelectAtEnumerable<TEnumerable, TEnumerator, TSource, TResult, TSelector>, Enumerator, TResult, TSubEnumerable, TSubEnumerator, TResult2, FunctionWrapper<TResult, TSubEnumerable>> SelectMany<TSubEnumerable, TSubEnumerator, TResult2>(Func<TResult, TSubEnumerable> selector) where TSubEnumerable : IValueEnumerable<TResult2, TSubEnumerator> where TSubEnumerator : struct, IEnumerator<TResult2> => this.SelectMany<SelectAtEnumerable<TEnumerable, TEnumerator, TSource, TResult, TSelector>, Enumerator, TResult, TSubEnumerable, TSubEnumerator, TResult2>(selector); [MethodImpl(MethodImplOptions.AggressiveInlining)] public readonly ValueEnumerableExtensions.SelectManyEnumerable<SelectAtEnumerable<TEnumerable, TEnumerator, TSource, TResult, TSelector>, Enumerator, TResult, TSubEnumerable, TSubEnumerator, TResult2, TSelector2> SelectMany<TSubEnumerable, TSubEnumerator, TResult2, TSelector2>(TSelector2 selector = default) where TSubEnumerable : IValueEnumerable<TResult2, TSubEnumerator> where TSubEnumerator : struct, IEnumerator<TResult2> where TSelector2 : struct, IFunction<TResult, TSubEnumerable> => this.SelectMany<SelectAtEnumerable<TEnumerable, TEnumerator, TSource, TResult, TSelector>, Enumerator, TResult, TSubEnumerable, TSubEnumerator, TResult2, TSelector2>(selector); #endregion #region Element [MethodImpl(MethodImplOptions.AggressiveInlining)] public Option<TResult> ElementAt(int index) => ElementAtAt<TEnumerable, TEnumerator, TSource, TResult, TSelector>(source, index, selector); [MethodImpl(MethodImplOptions.AggressiveInlining)] public Option<TResult> First() => FirstAt<TEnumerable, TEnumerator, TSource, TResult, TSelector>(source, selector); [MethodImpl(MethodImplOptions.AggressiveInlining)] public Option<TResult> Single() => SingleAt<TEnumerable, TEnumerator, TSource, TResult, TSelector>(source, selector); #endregion #region Conversion [MethodImpl(MethodImplOptions.AggressiveInlining)] public TResult[] ToArray() => ToArrayAt<TEnumerable, TEnumerator, TSource, TResult, TSelector>(source, selector); [MethodImpl(MethodImplOptions.AggressiveInlining)] public ValueMemoryOwner<TResult> ToArray(ArrayPool<TResult> pool, bool clearOnDispose = default) => ToArrayAt<TEnumerable, TEnumerator, TSource, TResult, TSelector>(source, pool, clearOnDispose, selector); [MethodImpl(MethodImplOptions.AggressiveInlining)] public List<TResult> ToList() => ToListAt<TEnumerable, TEnumerator, TSource, TResult, TSelector>(source, selector); #endregion } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int Count<TEnumerable, TEnumerator, TSource, TResult, TSelector>(this in SelectAtEnumerable<TEnumerable, TEnumerator, TSource, TResult, TSelector> source) where TEnumerable : IValueReadOnlyCollection<TSource, TEnumerator> where TEnumerator : struct, IEnumerator<TSource> where TSelector : struct, IFunction<TSource, int, TResult> => source.Count; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int Sum<TEnumerable, TEnumerator, TSource, TSelector>(this SelectAtEnumerable<TEnumerable, TEnumerator, TSource, int, TSelector> source) where TEnumerable : IValueReadOnlyCollection<TSource, TEnumerator> where TEnumerator : struct, IEnumerator<TSource> where TSelector : struct, IFunction<TSource, int, int> => ValueReadOnlyCollectionExtensions.SumAt<TEnumerable, TEnumerator, TSource, int, int, TSelector>(source.source, source.selector); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int Sum<TEnumerable, TEnumerator, TSource, TSelector>(this SelectAtEnumerable<TEnumerable, TEnumerator, TSource, int?, TSelector> source) where TEnumerable : IValueReadOnlyCollection<TSource, TEnumerator> where TEnumerator : struct, IEnumerator<TSource> where TSelector : struct, IFunction<TSource, int, int?> => ValueReadOnlyCollectionExtensions.SumAt<TEnumerable, TEnumerator, TSource, int?, int, TSelector>(source.source, source.selector); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static long Sum<TEnumerable, TEnumerator, TSource, TSelector>(this SelectAtEnumerable<TEnumerable, TEnumerator, TSource, long, TSelector> source) where TEnumerable : IValueReadOnlyCollection<TSource, TEnumerator> where TEnumerator : struct, IEnumerator<TSource> where TSelector : struct, IFunction<TSource, int, long> => ValueReadOnlyCollectionExtensions.SumAt<TEnumerable, TEnumerator, TSource, long, long, TSelector>(source.source, source.selector); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static long Sum<TEnumerable, TEnumerator, TSource, TSelector>(this SelectAtEnumerable<TEnumerable, TEnumerator, TSource, long?, TSelector> source) where TEnumerable : IValueReadOnlyCollection<TSource, TEnumerator> where TEnumerator : struct, IEnumerator<TSource> where TSelector : struct, IFunction<TSource, int, long?> => ValueReadOnlyCollectionExtensions.SumAt<TEnumerable, TEnumerator, TSource, long?, long, TSelector>(source.source, source.selector); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Sum<TEnumerable, TEnumerator, TSource, TSelector>(this SelectAtEnumerable<TEnumerable, TEnumerator, TSource, float, TSelector> source) where TEnumerable : IValueReadOnlyCollection<TSource, TEnumerator> where TEnumerator : struct, IEnumerator<TSource> where TSelector : struct, IFunction<TSource, int, float> => ValueReadOnlyCollectionExtensions.SumAt<TEnumerable, TEnumerator, TSource, float, float, TSelector>(source.source, source.selector); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Sum<TEnumerable, TEnumerator, TSource, TSelector>(this SelectAtEnumerable<TEnumerable, TEnumerator, TSource, float?, TSelector> source) where TEnumerable : IValueReadOnlyCollection<TSource, TEnumerator> where TEnumerator : struct, IEnumerator<TSource> where TSelector : struct, IFunction<TSource, int, float?> => ValueReadOnlyCollectionExtensions.SumAt<TEnumerable, TEnumerator, TSource, float?, float, TSelector>(source.source, source.selector); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static double Sum<TEnumerable, TEnumerator, TSource, TSelector>(this SelectAtEnumerable<TEnumerable, TEnumerator, TSource, double, TSelector> source) where TEnumerable : IValueReadOnlyCollection<TSource, TEnumerator> where TEnumerator : struct, IEnumerator<TSource> where TSelector : struct, IFunction<TSource, int, double> => ValueReadOnlyCollectionExtensions.SumAt<TEnumerable, TEnumerator, TSource, double, double, TSelector>(source.source, source.selector); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static double Sum<TEnumerable, TEnumerator, TSource, TSelector>(this SelectAtEnumerable<TEnumerable, TEnumerator, TSource, double?, TSelector> source) where TEnumerable : IValueReadOnlyCollection<TSource, TEnumerator> where TEnumerator : struct, IEnumerator<TSource> where TSelector : struct, IFunction<TSource, int, double?> => ValueReadOnlyCollectionExtensions.SumAt<TEnumerable, TEnumerator, TSource, double?, double, TSelector>(source.source, source.selector); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static decimal Sum<TEnumerable, TEnumerator, TSource, TSelector>(this SelectAtEnumerable<TEnumerable, TEnumerator, TSource, decimal, TSelector> source) where TEnumerable : IValueReadOnlyCollection<TSource, TEnumerator> where TEnumerator : struct, IEnumerator<TSource> where TSelector : struct, IFunction<TSource, int, decimal> => ValueReadOnlyCollectionExtensions.SumAt<TEnumerable, TEnumerator, TSource, decimal, decimal, TSelector>(source.source, source.selector); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static decimal Sum<TEnumerable, TEnumerator, TSource, TSelector>(this SelectAtEnumerable<TEnumerable, TEnumerator, TSource, decimal?, TSelector> source) where TEnumerable : IValueReadOnlyCollection<TSource, TEnumerator> where TEnumerator : struct, IEnumerator<TSource> where TSelector : struct, IFunction<TSource, int, decimal?> => ValueReadOnlyCollectionExtensions.SumAt<TEnumerable, TEnumerator, TSource, decimal?, decimal, TSelector>(source.source, source.selector); } }
61.528814
347
0.677373
[ "MIT" ]
Ashrafnet/NetFabric.Hyperlinq
NetFabric.Hyperlinq/Projection/Select/SelectAt/SelectAt.ValueReadOnlyCollection.cs
18,151
C#
// // Copyright (C) 2010 Novell Inc. http://novell.com // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Windows.Markup; using System.Xaml; using System.Xaml.Schema; using System.Xml; using NUnit.Framework; using CategoryAttribute = NUnit.Framework.CategoryAttribute; namespace MonoTests.System.Xaml { [TestFixture] public class XamlXmlReaderTest : XamlReaderTestBase { // read test XamlReader GetReader (string filename) { return new XamlXmlReader (XmlReader.Create (Path.Combine ("Test/XmlFiles", filename), new XmlReaderSettings () { CloseInput =true })); } void ReadTest (string filename) { var r = GetReader (filename); while (!r.IsEof) r.Read (); } [Test] public void SchemaContext () { Assert.AreNotEqual (XamlLanguage.Type.SchemaContext, new XamlXmlReader (XmlReader.Create (new StringReader ("<root/>"))).SchemaContext, "#1"); } [Test] public void Read_Int32 () { ReadTest ("Int32.xml"); } [Test] public void Read_DateTime () { ReadTest ("DateTime.xml"); } [Test] public void Read_TimeSpan () { ReadTest ("TimeSpan.xml"); } [Test] public void Read_ArrayInt32 () { ReadTest ("Array_Int32.xml"); } [Test] public void Read_DictionaryInt32String () { ReadTest ("Dictionary_Int32_String.xml"); } [Test] public void Read_DictionaryStringType () { ReadTest ("Dictionary_String_Type.xml"); } [Test] public void Read_SilverlightApp1 () { ReadTest ("SilverlightApp1.xaml"); } [Test] public void Read_Guid () { ReadTest ("Guid.xml"); } [Test] public void Read_GuidFactoryMethod () { ReadTest ("GuidFactoryMethod.xml"); } [Test] public void ReadInt32Details () { var r = GetReader ("Int32.xml"); Assert.IsTrue (r.Read (), "ns#1"); Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "ns#2"); Assert.AreEqual (XamlLanguage.Xaml2006Namespace, r.Namespace.Namespace, "ns#3"); Assert.IsTrue (r.Read (), "so#1"); Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "so#2"); Assert.AreEqual (XamlLanguage.Int32, r.Type, "so#3"); ReadBase (r); Assert.IsTrue (r.Read (), "sinit#1"); Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "sinit#2"); Assert.AreEqual (XamlLanguage.Initialization, r.Member, "sinit#3"); Assert.IsTrue (r.Read (), "vinit#1"); Assert.AreEqual (XamlNodeType.Value, r.NodeType, "vinit#2"); Assert.AreEqual ("5", r.Value, "vinit#3"); // string Assert.IsTrue (r.Read (), "einit#1"); Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "einit#2"); Assert.IsTrue (r.Read (), "eo#1"); Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "eo#2"); Assert.IsFalse (r.Read (), "end"); } [Test] public void ReadDateTimeDetails () { var r = GetReader ("DateTime.xml"); Assert.IsTrue (r.Read (), "ns#1"); Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "ns#2"); Assert.AreEqual ("clr-namespace:System;assembly=mscorlib", r.Namespace.Namespace, "ns#3"); Assert.IsTrue (r.Read (), "so#1"); Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "so#2"); Assert.AreEqual (r.SchemaContext.GetXamlType (typeof (DateTime)), r.Type, "so#3"); ReadBase (r); Assert.IsTrue (r.Read (), "sinit#1"); Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "sinit#2"); Assert.AreEqual (XamlLanguage.Initialization, r.Member, "sinit#3"); Assert.IsTrue (r.Read (), "vinit#1"); Assert.AreEqual (XamlNodeType.Value, r.NodeType, "vinit#2"); Assert.AreEqual ("2010-04-14", r.Value, "vinit#3"); // string Assert.IsTrue (r.Read (), "einit#1"); Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "einit#2"); Assert.IsTrue (r.Read (), "eo#1"); Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "eo#2"); Assert.IsFalse (r.Read (), "end"); } [Test] public void ReadGuidFactoryMethodDetails () { var r = GetReader ("GuidFactoryMethod.xml"); Assert.IsTrue (r.Read (), "ns#1"); Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "ns#2"); Assert.AreEqual ("clr-namespace:System;assembly=mscorlib", r.Namespace.Namespace, "ns#3"); Assert.AreEqual (String.Empty, r.Namespace.Prefix, "ns#4"); Assert.IsTrue (r.Read (), "ns2#1"); Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "ns2#2"); Assert.AreEqual (XamlLanguage.Xaml2006Namespace, r.Namespace.Namespace, "ns2#3"); Assert.AreEqual ("x", r.Namespace.Prefix, "ns2#4"); Assert.IsTrue (r.Read (), "so#1"); Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "so#2"); var xt = r.SchemaContext.GetXamlType (typeof (Guid)); Assert.AreEqual (xt, r.Type, "so#3"); ReadBase (r); Assert.IsTrue (r.Read (), "sfactory#1"); Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "sfactory#2"); Assert.AreEqual (XamlLanguage.FactoryMethod, r.Member, "sfactory#3"); Assert.IsTrue (r.Read (), "vfactory#1"); Assert.AreEqual (XamlNodeType.Value, r.NodeType, "vfactory#2"); Assert.AreEqual ("Parse", r.Value, "vfactory#3"); // string Assert.IsTrue (r.Read (), "efactory#1"); Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "efactory#2"); Assert.IsTrue (r.Read (), "sarg#1"); Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "sarg#2"); Assert.AreEqual (XamlLanguage.Arguments, r.Member, "sarg#3"); Assert.IsTrue (r.Read (), "sarg1#1"); Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "sarg1#2"); Assert.AreEqual (XamlLanguage.String, r.Type, "sarg1#3"); Assert.IsTrue (r.Read (), "sInit#1"); Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "sInit#2"); Assert.AreEqual (XamlLanguage.Initialization, r.Member, "sInit#3"); Assert.IsTrue (r.Read (), "varg1#1"); Assert.AreEqual (XamlNodeType.Value, r.NodeType, "varg1#2"); Assert.AreEqual ("9c3345ec-8922-4662-8e8d-a4e41f47cf09", r.Value, "varg1#3"); Assert.IsTrue (r.Read (), "eInit#1"); Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "eInit#2"); Assert.IsTrue (r.Read (), "earg1#1"); Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "earg1#2"); Assert.IsTrue (r.Read (), "earg#1"); Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "earg#2"); Assert.IsTrue (r.Read (), "eo#1"); Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "eo#2"); Assert.IsFalse (r.Read (), "end"); } [Test] public void ReadEventStore () { var r = GetReader ("EventStore2.xml"); var xt = r.SchemaContext.GetXamlType (typeof (EventStore)); var xm = xt.GetMember ("Event1"); Assert.IsNotNull (xt, "premise#1"); Assert.IsNotNull (xm, "premise#2"); Assert.IsTrue (xm.IsEvent, "premise#3"); while (true) { r.Read (); if (r.Member != null && r.Member.IsEvent) break; if (r.IsEof) Assert.Fail ("Items did not appear"); } Assert.AreEqual (xm, r.Member, "#x1"); Assert.AreEqual ("Event1", r.Member.Name, "#x2"); Assert.IsTrue (r.Read (), "#x11"); Assert.AreEqual (XamlNodeType.Value, r.NodeType, "#x12"); Assert.AreEqual ("Method1", r.Value, "#x13"); Assert.IsTrue (r.Read (), "#x21"); Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "#x22"); xm = xt.GetMember ("Event2"); Assert.IsTrue (r.Read (), "#x31"); Assert.AreEqual (xm, r.Member, "#x32"); Assert.AreEqual ("Event2", r.Member.Name, "#x33"); Assert.IsTrue (r.Read (), "#x41"); Assert.AreEqual (XamlNodeType.Value, r.NodeType, "#x42"); Assert.AreEqual ("Method2", r.Value, "#x43"); Assert.IsTrue (r.Read (), "#x51"); Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "#x52"); Assert.IsTrue (r.Read (), "#x61"); Assert.AreEqual ("Event1", r.Member.Name, "#x62"); Assert.IsTrue (r.Read (), "#x71"); Assert.AreEqual (XamlNodeType.Value, r.NodeType, "#x72"); Assert.AreEqual ("Method3", r.Value, "#x73"); // nonexistent, but no need to raise an error. Assert.IsTrue (r.Read (), "#x81"); Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "#x82"); while (!r.IsEof) r.Read (); r.Close (); } // common XamlReader tests. [Test] public void Read_String () { var r = GetReader ("String.xml"); Read_String (r); } [Test] public void WriteNullMemberAsObject () { var r = GetReader ("TestClass4.xml"); WriteNullMemberAsObject (r, null); } [Test] public void StaticMember () { var r = GetReader ("TestClass5.xml"); StaticMember (r); } [Test] public void Skip () { var r = GetReader ("String.xml"); Skip (r); } [Test] public void Skip2 () { var r = GetReader ("String.xml"); Skip2 (r); } [Test] public void Read_XmlDocument () { var doc = new XmlDocument (); doc.LoadXml ("<root xmlns='urn:foo'><elem attr='val' /></root>"); // note that corresponding XamlXmlWriter is untested yet. var r = GetReader ("XmlDocument.xml"); Read_XmlDocument (r); } [Test] public void Read_NonPrimitive () { var r = GetReader ("NonPrimitive.xml"); Read_NonPrimitive (r); } [Test] public void Read_TypeExtension () { var r = GetReader ("Type.xml"); Read_TypeOrTypeExtension (r, null, XamlLanguage.Type.GetMember ("Type")); } [Test] public void Read_Type2 () { var r = GetReader ("Type2.xml"); Read_TypeOrTypeExtension2 (r, null, XamlLanguage.Type.GetMember ("Type")); } [Test] public void Read_Reference () { var r = GetReader ("Reference.xml"); Read_Reference (r); } [Test] public void Read_Null () { var r = GetReader ("NullExtension.xml"); Read_NullOrNullExtension (r, null); } [Test] public void Read_StaticExtension () { var r = GetReader ("StaticExtension.xml"); Read_StaticExtension (r, XamlLanguage.Static.GetMember ("Member")); } [Test] public void Read_ListInt32 () { var r = GetReader ("List_Int32.xml"); Read_ListInt32 (r, null, new int [] {5, -3, int.MaxValue, 0}.ToList ()); } [Test] public void Read_ListInt32_2 () { var r = GetReader ("List_Int32_2.xml"); Read_ListInt32 (r, null, new int [0].ToList ()); } [Test] public void Read_ListType () { var r = GetReader ("List_Type.xml"); Read_ListType (r, false); } [Test] public void Read_ListArray () { var r = GetReader ("List_Array.xml"); Read_ListArray (r); } [Test] public void Read_ArrayList () { var r = GetReader ("ArrayList.xml"); Read_ArrayList (r); } [Test] public void Read_Array () { var r = GetReader ("ArrayExtension.xml"); Read_ArrayOrArrayExtensionOrMyArrayExtension (r, null, typeof (ArrayExtension)); } [Test] public void Read_MyArrayExtension () { var r = GetReader ("MyArrayExtension.xml"); Read_ArrayOrArrayExtensionOrMyArrayExtension (r, null, typeof (MyArrayExtension)); } [Test] public void Read_ArrayExtension2 () { var r = GetReader ("ArrayExtension2.xml"); Read_ArrayExtension2 (r); } [Test] public void Read_CustomMarkupExtension () { var r = GetReader ("MyExtension.xml"); Read_CustomMarkupExtension (r); } [Test] public void Read_CustomMarkupExtension2 () { var r = GetReader ("MyExtension2.xml"); Read_CustomMarkupExtension2 (r); } [Test] public void Read_CustomMarkupExtension3 () { var r = GetReader ("MyExtension3.xml"); Read_CustomMarkupExtension3 (r); } [Test] public void Read_CustomMarkupExtension4 () { var r = GetReader ("MyExtension4.xml"); Read_CustomMarkupExtension4 (r); } [Test] public void Read_CustomMarkupExtension6 () { var r = GetReader ("MyExtension6.xml"); Read_CustomMarkupExtension6 (r); } [Test] public void Read_ArgumentAttributed () { var obj = new ArgumentAttributed ("foo", "bar"); var r = GetReader ("ArgumentAttributed.xml"); Read_ArgumentAttributed (r, obj); } [Test] public void Read_Dictionary () { var obj = new Dictionary<string,object> (); obj ["Foo"] = 5.0; obj ["Bar"] = -6.5; var r = GetReader ("Dictionary_String_Double.xml"); Read_Dictionary (r); } [Test] public void Read_Dictionary2 () { var obj = new Dictionary<string,Type> (); obj ["Foo"] = typeof (int); obj ["Bar"] = typeof (Dictionary<Type,XamlType>); var r = GetReader ("Dictionary_String_Type_2.xml"); Read_Dictionary2 (r, XamlLanguage.Type.GetMember ("Type")); } [Test] public void PositionalParameters2 () { var r = GetReader ("PositionalParametersWrapper.xml"); PositionalParameters2 (r); } [Test] public void ComplexPositionalParameters () { var r = GetReader ("ComplexPositionalParameterWrapper.xml"); ComplexPositionalParameters (r); } [Test] public void Read_ListWrapper () { var r = GetReader ("ListWrapper.xml"); Read_ListWrapper (r); } [Test] public void Read_ListWrapper2 () // read-write list member. { var r = GetReader ("ListWrapper2.xml"); Read_ListWrapper2 (r); } [Test] public void Read_ContentIncluded () { var r = GetReader ("ContentIncluded.xml"); Read_ContentIncluded (r); } [Test] public void Read_PropertyDefinition () { var r = GetReader ("PropertyDefinition.xml"); Read_PropertyDefinition (r); } [Test] public void Read_StaticExtensionWrapper () { var r = GetReader ("StaticExtensionWrapper.xml"); Read_StaticExtensionWrapper (r); } [Test] public void Read_TypeExtensionWrapper () { var r = GetReader ("TypeExtensionWrapper.xml"); Read_TypeExtensionWrapper (r); } [Test] public void Read_NamedItems () { var r = GetReader ("NamedItems.xml"); Read_NamedItems (r, false); } [Test] public void Read_NamedItems2 () { var r = GetReader ("NamedItems2.xml"); Read_NamedItems2 (r, false); } [Test] public void Read_XmlSerializableWrapper () { var r = GetReader ("XmlSerializableWrapper.xml"); Read_XmlSerializableWrapper (r, false); } [Test] public void Read_XmlSerializable () { var r = GetReader ("XmlSerializable.xml"); Read_XmlSerializable (r); } [Test] public void Read_ListXmlSerializable () { var r = GetReader ("List_XmlSerializable.xml"); Read_ListXmlSerializable (r); } [Test] public void Read_AttachedProperty () { var r = GetReader ("AttachedProperty.xml"); Read_AttachedProperty (r); } [Test] public void Read_AbstractWrapper () { var r = GetReader ("AbstractContainer.xml"); while (!r.IsEof) r.Read (); } [Test] public void Read_ReadOnlyPropertyContainer () { var r = GetReader ("ReadOnlyPropertyContainer.xml"); while (!r.IsEof) r.Read (); } [Test] public void Read_TypeConverterOnListMember () { var r = GetReader ("TypeConverterOnListMember.xml"); Read_TypeConverterOnListMember (r); } [Test] public void Read_EnumContainer () { var r = GetReader ("EnumContainer.xml"); Read_EnumContainer (r); } [Test] public void Read_CollectionContentProperty () { var r = GetReader ("CollectionContentProperty.xml"); Read_CollectionContentProperty (r, false); } [Test] public void Read_CollectionContentProperty2 () { // bug #681835 var r = GetReader ("CollectionContentProperty2.xml"); Read_CollectionContentProperty (r, true); } [Test] public void Read_CollectionContentPropertyX () { var r = GetReader ("CollectionContentPropertyX.xml"); Read_CollectionContentPropertyX (r, false); } [Test] public void Read_CollectionContentPropertyX2 () { var r = GetReader ("CollectionContentPropertyX2.xml"); Read_CollectionContentPropertyX (r, true); } [Test] public void Read_AmbientPropertyContainer () { var r = GetReader ("AmbientPropertyContainer.xml"); Read_AmbientPropertyContainer (r, false); } [Test] public void Read_AmbientPropertyContainer2 () { var r = GetReader ("AmbientPropertyContainer2.xml"); Read_AmbientPropertyContainer (r, true); } [Test] public void Read_NullableContainer () { var r = GetReader ("NullableContainer.xml"); Read_NullableContainer (r); } // It is not really a common test; it just makes use of base helper methods. [Test] public void Read_DirectListContainer () { var r = GetReader ("DirectListContainer.xml"); Read_DirectListContainer (r); } // It is not really a common test; it just makes use of base helper methods. [Test] public void Read_DirectDictionaryContainer () { var r = GetReader ("DirectDictionaryContainer.xml"); Read_DirectDictionaryContainer (r); } // It is not really a common test; it just makes use of base helper methods. [Test] public void Read_DirectDictionaryContainer2 () { var r = GetReader ("DirectDictionaryContainer2.xml"); Read_DirectDictionaryContainer2 (r); } #region non-common tests [Test] public void Bug680385 () { XamlServices.Load ("Test/XmlFiles/CurrentVersion.xaml"); } #endregion } }
25.259362
145
0.667747
[ "Apache-2.0" ]
slluis/mono
mcs/class/System.Xaml/Test/System.Xaml/XamlXmlReaderTest.cs
18,212
C#
using Jom.Blog.IRepository.Base; using Jom.Blog.IServices; using Jom.Blog.Model.Models; using Jom.Blog.Services.BASE; namespace Jom.Blog.Services { /// <summary> /// ModuleServices /// </summary> public class ModuleServices : BaseServices<Modules>, IModuleServices { IBaseRepository<Modules> _dal; public ModuleServices(IBaseRepository<Modules> dal) { this._dal = dal; base.BaseDal = dal; } } }
21.130435
72
0.621399
[ "Apache-2.0" ]
atorzhang/Jom.Blog
Jom.Blog.Services/ModuleServices.cs
486
C#
using MusicApplication.Data.MusicApplication.Data; using System; using System.Collections.Generic; using System.Data; namespace MusicApplication.Data { public class Artist // : IDataModel { public int ArtistId { get; set; } public string ArtistName { get; set; } public string Label { get; set; } public string ArtistImageUrl { get; set; } public List<Album> Albums { get; set; } public Artist() { this.Albums = new List<Album>(); } public Artist(IDataReader reader, Dictionary<int, Artist> dict) : this() { CastFromReader(reader, dict); } public void CastFromReader(IDataReader reader, Dictionary<int, Artist> dict) { this.ArtistId = Convert.ToInt32(reader["ArtistId"]); this.ArtistName = Convert.ToString(reader["ArtistName"]); this.Label = Convert.ToString(reader["Label"]); this.ArtistImageUrl = Convert.ToString(reader["ArtistImageUrl"]); if (!dict.ContainsKey(this.ArtistId)) { dict.Add(this.ArtistId, this); } var album = new Album(); album.CastFromReader(reader, dict); } } }
25.62
84
0.575332
[ "MIT" ]
jivka93/MusicApp
Back-end/MusicApplication.Data/Artist.cs
1,283
C#
/* MIT License Copyright (c) Jeff Campbell 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 CommandLine; namespace Genesis.CLI { /// <summary> /// Command-line options for manipulating or creating configs /// </summary> [Verb("config", HelpText = "Manipulates or creates a configuration file.")] internal sealed class ConfigOptions { [Option( longName:"create", SetName = "create", HelpText = "Specifies that a config file should be created and populated with all settings from " + "available plugins.")] public bool DoCreate { get; set; } [Option( longName: "output-path", SetName = "create", HelpText = "The output file path where this config should be written", Default = "new_config.json")] public string CreatePath { get; set; } [Option( "plugin-path", HelpText = "The path to the plugin folder.", Default = "Plugins")] public string PluginPath { get; set; } [Option( "verbose", HelpText = "Sets the logging to be verbose if true, errors only if false.", Default = false)] public bool IsVerbose { get; set; } [Option( "load-unsafe", HelpText = "Forces out-of-date plugins to be loaded", Default = false)] public bool DoLoadUnsafe { get; set; } } }
32.391304
102
0.728859
[ "MIT" ]
jeffcampbellmakesgames/Genesis
ExternalApp/Genesis/Options/ConfigOptions.cs
2,237
C#
using Microsoft.EntityFrameworkCore.Migrations; namespace Remotely.Server.Migrations { public partial class DeviceAgentVersion : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AddColumn<string>( name: "AgentVersion", table: "Devices", nullable: true); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropColumn( name: "AgentVersion", table: "Devices"); } } }
26.478261
71
0.587849
[ "MIT" ]
rolbre/ServiceBus
Remotely/Server/Migrations/20190705195745_Device.AgentVersion.cs
611
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 Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.Infrastructure; using Microsoft.AspNetCore.Mvc.ModelBinding; namespace Microsoft.AspNetCore.Mvc { /// <summary> /// An <see cref="ObjectResult"/> that when executed will produce a Conflict (409) response. /// </summary> [DefaultStatusCode(DefaultStatusCode)] public class ConflictObjectResult : ObjectResult { private const int DefaultStatusCode = StatusCodes.Status409Conflict; /// <summary> /// Creates a new <see cref="ConflictObjectResult"/> instance. /// </summary> /// <param name="error">Contains the errors to be returned to the client.</param> public ConflictObjectResult([ActionResultObjectValue] object? error) : base(error) { StatusCode = DefaultStatusCode; } /// <summary> /// Creates a new <see cref="ConflictObjectResult"/> instance. /// </summary> /// <param name="modelState"><see cref="ModelStateDictionary"/> containing the validation errors.</param> public ConflictObjectResult([ActionResultObjectValue] ModelStateDictionary modelState) : base(new SerializableError(modelState)) { if (modelState == null) { throw new ArgumentNullException(nameof(modelState)); } StatusCode = DefaultStatusCode; } } }
35.288889
113
0.648615
[ "MIT" ]
48355746/AspNetCore
src/Mvc/Mvc.Core/src/ConflictObjectResult.cs
1,588
C#
using System; using Microsoft.Xna.Framework.Input; using WMNW.Core.Input.Classes; namespace WMNW.Core.Input.Devices.Interfaces { #region Delegates /// <summary>Delegate used to report movement of the mouse cursor</summary> /// <param name="x">New X coordinate of the mouse cursor</param> /// <param name="y">New Y coordinate of the mouse cursor</param> public delegate void MouseMoveDelegate ( float x, float y ); /// <summary> /// Delegate used to report a press or released of one or more mouse buttons /// </summary> /// <param name="buttons">Button or buttons that have been pressed or released</param> /// <param name="x"></param> /// <param name="y"></param> public delegate void MouseButtonDelegate ( MouseButtons buttons, int x, int y ); /// <summary>Delegate used to report a rotation of the mouse wheel</summary> /// <param name="ticks">Number of ticks the mouse wheel has been rotated</param> /// <param name="x"></param> /// <param name="y"></param> public delegate void MouseWheelDelegate ( float ticks, int x, int y ); #endregion /// <summary>Specializd input devices for mouse-like controllers</summary> public interface IMouse : IInputDevice { #region Delegates /// <summary>Fired when the mouse has been moved</summary> event MouseMoveDelegate MouseMoved; /// <summary>Fired when one or more mouse buttons have been pressed</summary> event MouseButtonDelegate MouseButtonPressed; /// <summary>Fired when one or more mouse buttons have been released</summary> event MouseButtonDelegate MouseButtonReleased; /// <summary>Fired when the mouse wheel has been rotated</summary> event MouseWheelDelegate MouseWheelRotated; /// <summary> /// Fired when one or more mouse buttons have been clicked /// </summary> event MouseButtonDelegate MouseButtonClicked; #endregion #region Other Methds /// <summary> /// Retrieves the State of our Mouse /// </summary> /// <returns></returns> MouseState GetState(); /// <summary>Moves the mouse cursor to the specified location</summary> /// <param name="x">New X coordinate of the mouse cursor</param> /// <param name="y">New Y coordinate of the mouse cursor</param> void MoveTo( float x, float y ); #endregion } }
34.333333
90
0.651294
[ "MIT" ]
MuteLovestone/WM_NewWorld
Code/WM New World/Whore Master New World/Core/WMNW.Core/Input/Devices/Interfaces/IMouse.cs
2,474
C#
// This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "Acceptable legacy name", Scope = "type", Target = "~T:AnalysisManagerDtaRefineryPlugIn.AnalysisToolRunnerDtaRefinery")] [assembly: SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "Acceptable legacy name", Scope = "type", Target = "~T:AnalysisManagerDtaRefineryPlugIn.DeconMSnLogFileValidator")] [assembly: SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "Acceptable legacy name", Scope = "type", Target = "~T:AnalysisManagerDtaRefineryPlugIn.DtaRefLogMassErrorExtractor")] [assembly: SuppressMessage("Usage", "RCS1146:Use conditional access.", Justification = "Leave as-is for readability", Scope = "member", Target = "~M:AnalysisManagerDtaRefineryPlugIn.AnalysisToolRunnerDtaRefinery.IsXTandemFinished~System.Boolean")] [assembly: SuppressMessage("Usage", "RCS1146:Use conditional access.", Justification = "Leave as-is for readability", Scope = "member", Target = "~M:AnalysisManagerDtaRefineryPlugIn.AnalysisToolRunnerDtaRefinery.ValidateDTARefineryLogFile~System.Boolean")]
107.076923
257
0.788793
[ "BSD-2-Clause" ]
PNNL-Comp-Mass-Spec/DMS-Analysis-Manager
Plugins/AM_DtaRefinery_PlugIn/GlobalSuppressions.cs
1,394
C#
using System; using NQuery.Syntax; namespace NQuery { public abstract class SyntaxVisitor { protected void Dispatch(SyntaxNode node) { if (node == null) throw new ArgumentNullException(nameof(node)); switch (node.Kind) { case SyntaxKind.CompilationUnit: VisitCompilationUnit((CompilationUnitSyntax)node); break; case SyntaxKind.SkippedTokensTrivia: VisitSkippedTokensTrivia((SkippedTokensTriviaSyntax)node); break; case SyntaxKind.ComplementExpression: case SyntaxKind.IdentityExpression: case SyntaxKind.NegationExpression: case SyntaxKind.LogicalNotExpression: VisitUnaryExpression((UnaryExpressionSyntax)node); break; case SyntaxKind.BitwiseAndExpression: case SyntaxKind.BitwiseOrExpression: case SyntaxKind.ExclusiveOrExpression: case SyntaxKind.AddExpression: case SyntaxKind.SubExpression: case SyntaxKind.MultiplyExpression: case SyntaxKind.DivideExpression: case SyntaxKind.ModuloExpression: case SyntaxKind.PowerExpression: case SyntaxKind.EqualExpression: case SyntaxKind.NotEqualExpression: case SyntaxKind.LessExpression: case SyntaxKind.LessOrEqualExpression: case SyntaxKind.GreaterExpression: case SyntaxKind.GreaterOrEqualExpression: case SyntaxKind.NotLessExpression: case SyntaxKind.NotGreaterExpression: case SyntaxKind.LeftShiftExpression: case SyntaxKind.RightShiftExpression: case SyntaxKind.LogicalAndExpression: case SyntaxKind.LogicalOrExpression: VisitBinaryExpression((BinaryExpressionSyntax)node); break; case SyntaxKind.LikeExpression: VisitLikeExpression((LikeExpressionSyntax)node); break; case SyntaxKind.SoundsLikeExpression: VisitSoundsLikeExpression((SoundsLikeExpressionSyntax)node); break; case SyntaxKind.SimilarToExpression: VisitSimilarToExpression((SimilarToExpressionSyntax)node); break; case SyntaxKind.ParenthesizedExpression: VisitParenthesizedExpression((ParenthesizedExpressionSyntax)node); break; case SyntaxKind.BetweenExpression: VisitBetweenExpression((BetweenExpressionSyntax)node); break; case SyntaxKind.IsNullExpression: VisitIsNullExpression((IsNullExpressionSyntax)node); break; case SyntaxKind.CastExpression: VisitCastExpression((CastExpressionSyntax)node); break; case SyntaxKind.CaseExpression: VisitCaseExpression((CaseExpressionSyntax)node); break; case SyntaxKind.CaseLabel: VisitCaseLabel((CaseLabelSyntax)node); break; case SyntaxKind.CoalesceExpression: VisitCoalesceExpression((CoalesceExpressionSyntax)node); break; case SyntaxKind.NullIfExpression: VisitNullIfExpression((NullIfExpressionSyntax)node); break; case SyntaxKind.InExpression: VisitInExpression((InExpressionSyntax)node); break; case SyntaxKind.LiteralExpression: VisitLiteralExpression((LiteralExpressionSyntax)node); break; case SyntaxKind.VariableExpression: VisitParameterExpression((VariableExpressionSyntax)node); break; case SyntaxKind.NameExpression: VisitNameExpression((NameExpressionSyntax)node); break; case SyntaxKind.PropertyAccessExpression: VisitPropertyAccessExpression((PropertyAccessExpressionSyntax)node); break; case SyntaxKind.CountAllExpression: VisitCountAllExpression((CountAllExpressionSyntax)node); break; case SyntaxKind.FunctionInvocationExpression: VisitFunctionInvocationExpression((FunctionInvocationExpressionSyntax)node); break; case SyntaxKind.MethodInvocationExpression: VisitMethodInvocationExpression((MethodInvocationExpressionSyntax)node); break; case SyntaxKind.ArgumentList: VisitArgumentList((ArgumentListSyntax)node); break; case SyntaxKind.SingleRowSubselect: VisitSingleRowSubselect((SingleRowSubselectSyntax)node); break; case SyntaxKind.ExistsSubselect: VisitExistsSubselect((ExistsSubselectSyntax)node); break; case SyntaxKind.AllAnySubselect: VisitAllAnySubselect((AllAnySubselectSyntax)node); break; case SyntaxKind.ParenthesizedTableReference: VisitParenthesizedTableReference((ParenthesizedTableReferenceSyntax)node); break; case SyntaxKind.NamedTableReference: VisitNamedTableReference((NamedTableReferenceSyntax)node); break; case SyntaxKind.CrossJoinedTableReference: VisitCrossJoinedTableReference((CrossJoinedTableReferenceSyntax)node); break; case SyntaxKind.InnerJoinedTableReference: VisitInnerJoinedTableReference((InnerJoinedTableReferenceSyntax)node); break; case SyntaxKind.OuterJoinedTableReference: VisitOuterJoinedTableReference((OuterJoinedTableReferenceSyntax)node); break; case SyntaxKind.DerivedTableReference: VisitDerivedTableReference((DerivedTableReferenceSyntax)node); break; case SyntaxKind.ExceptQuery: VisitExceptQuery((ExceptQuerySyntax)node); break; case SyntaxKind.UnionQuery: VisitUnionQuery((UnionQuerySyntax)node); break; case SyntaxKind.IntersectQuery: VisitIntersectQuery((IntersectQuerySyntax)node); break; case SyntaxKind.OrderedQuery: VisitOrderedQuery((OrderedQuerySyntax)node); break; case SyntaxKind.OrderByColumn: VisitOrderByColumn((OrderByColumnSyntax)node); break; case SyntaxKind.ParenthesizedQuery: VisitParenthesizedQuery((ParenthesizedQuerySyntax)node); break; case SyntaxKind.CommonTableExpressionQuery: VisitCommonTableExpressionQuery((CommonTableExpressionQuerySyntax)node); break; case SyntaxKind.CommonTableExpression: VisitCommonTableExpression((CommonTableExpressionSyntax)node); break; case SyntaxKind.CommonTableExpressionColumnName: VisitCommonTableExpressionColumnName((CommonTableExpressionColumnNameSyntax)node); break; case SyntaxKind.CommonTableExpressionColumnNameList: VisitCommonTableExpressionColumnNameList((CommonTableExpressionColumnNameListSyntax)node); break; case SyntaxKind.SelectQuery: VisitSelectQuery((SelectQuerySyntax)node); break; case SyntaxKind.TopClause: VisitTopClause((TopClauseSyntax)node); break; case SyntaxKind.WildcardSelectColumn: VisitWildcardSelectColumn((WildcardSelectColumnSyntax)node); break; case SyntaxKind.ExpressionSelectColumn: VisitExpressionSelectColumn((ExpressionSelectColumnSyntax)node); break; case SyntaxKind.SelectClause: VisitSelectClause((SelectClauseSyntax)node); break; case SyntaxKind.FromClause: VisitFromClause((FromClauseSyntax)node); break; case SyntaxKind.WhereClause: VisitWhereClause((WhereClauseSyntax)node); break; case SyntaxKind.GroupByClause: VisitGroupByClause((GroupByClauseSyntax)node); break; case SyntaxKind.GroupByColumn: VisitGroupByColumn((GroupByColumnSyntax)node); break; case SyntaxKind.HavingClause: VisitHavingClause((HavingClauseSyntax)node); break; case SyntaxKind.Alias: VisitAlias((AliasSyntax)node); break; default: throw ExceptionBuilder.UnexpectedValue(node.Kind); } } public virtual void DefaultVisit(SyntaxNode node) { } public virtual void VisitAlias(AliasSyntax node) { DefaultVisit(node); } public virtual void VisitArgumentList(ArgumentListSyntax node) { DefaultVisit(node); } public virtual void VisitCaseLabel(CaseLabelSyntax node) { DefaultVisit(node); } public virtual void VisitCommonTableExpressionColumnNameList(CommonTableExpressionColumnNameListSyntax node) { DefaultVisit(node); } public virtual void VisitCommonTableExpressionColumnName(CommonTableExpressionColumnNameSyntax node) { DefaultVisit(node); } public virtual void VisitCommonTableExpression(CommonTableExpressionSyntax node) { DefaultVisit(node); } public virtual void VisitCompilationUnit(CompilationUnitSyntax node) { DefaultVisit(node); } public virtual void VisitBetweenExpression(BetweenExpressionSyntax node) { DefaultVisit(node); } public virtual void VisitBinaryExpression(BinaryExpressionSyntax node) { DefaultVisit(node); } public virtual void VisitCaseExpression(CaseExpressionSyntax node) { DefaultVisit(node); } public virtual void VisitCastExpression(CastExpressionSyntax node) { DefaultVisit(node); } public virtual void VisitCoalesceExpression(CoalesceExpressionSyntax node) { DefaultVisit(node); } public virtual void VisitCountAllExpression(CountAllExpressionSyntax node) { DefaultVisit(node); } public virtual void VisitFunctionInvocationExpression(FunctionInvocationExpressionSyntax node) { DefaultVisit(node); } public virtual void VisitInExpression(InExpressionSyntax node) { DefaultVisit(node); } public virtual void VisitIsNullExpression(IsNullExpressionSyntax node) { DefaultVisit(node); } public virtual void VisitLikeExpression(LikeExpressionSyntax node) { DefaultVisit(node); } public virtual void VisitLiteralExpression(LiteralExpressionSyntax node) { DefaultVisit(node); } public virtual void VisitMethodInvocationExpression(MethodInvocationExpressionSyntax node) { DefaultVisit(node); } public virtual void VisitNameExpression(NameExpressionSyntax node) { DefaultVisit(node); } public virtual void VisitNullIfExpression(NullIfExpressionSyntax node) { DefaultVisit(node); } public virtual void VisitParameterExpression(VariableExpressionSyntax node) { DefaultVisit(node); } public virtual void VisitParenthesizedExpression(ParenthesizedExpressionSyntax node) { DefaultVisit(node); } public virtual void VisitPropertyAccessExpression(PropertyAccessExpressionSyntax node) { DefaultVisit(node); } public virtual void VisitSimilarToExpression(SimilarToExpressionSyntax node) { DefaultVisit(node); } public virtual void VisitSoundsLikeExpression(SoundsLikeExpressionSyntax node) { DefaultVisit(node); } public virtual void VisitAllAnySubselect(AllAnySubselectSyntax node) { DefaultVisit(node); } public virtual void VisitExistsSubselect(ExistsSubselectSyntax node) { DefaultVisit(node); } public virtual void VisitSingleRowSubselect(SingleRowSubselectSyntax node) { DefaultVisit(node); } public virtual void VisitSkippedTokensTrivia(SkippedTokensTriviaSyntax node) { DefaultVisit(node); } public virtual void VisitUnaryExpression(UnaryExpressionSyntax node) { DefaultVisit(node); } public virtual void VisitSelectClause(SelectClauseSyntax node) { DefaultVisit(node); } public virtual void VisitFromClause(FromClauseSyntax node) { DefaultVisit(node); } public virtual void VisitGroupByClause(GroupByClauseSyntax node) { DefaultVisit(node); } public virtual void VisitGroupByColumn(GroupByColumnSyntax node) { DefaultVisit(node); } public virtual void VisitHavingClause(HavingClauseSyntax node) { DefaultVisit(node); } public virtual void VisitOrderByColumn(OrderByColumnSyntax node) { DefaultVisit(node); } public virtual void VisitCommonTableExpressionQuery(CommonTableExpressionQuerySyntax node) { DefaultVisit(node); } public virtual void VisitExceptQuery(ExceptQuerySyntax node) { DefaultVisit(node); } public virtual void VisitIntersectQuery(IntersectQuerySyntax node) { DefaultVisit(node); } public virtual void VisitOrderedQuery(OrderedQuerySyntax node) { DefaultVisit(node); } public virtual void VisitParenthesizedQuery(ParenthesizedQuerySyntax node) { DefaultVisit(node); } public virtual void VisitSelectQuery(SelectQuerySyntax node) { DefaultVisit(node); } public virtual void VisitUnionQuery(UnionQuerySyntax node) { DefaultVisit(node); } public virtual void VisitExpressionSelectColumn(ExpressionSelectColumnSyntax node) { DefaultVisit(node); } public virtual void VisitWildcardSelectColumn(WildcardSelectColumnSyntax node) { DefaultVisit(node); } public virtual void VisitDerivedTableReference(DerivedTableReferenceSyntax node) { DefaultVisit(node); } public virtual void VisitCrossJoinedTableReference(CrossJoinedTableReferenceSyntax node) { DefaultVisit(node); } public virtual void VisitInnerJoinedTableReference(InnerJoinedTableReferenceSyntax node) { DefaultVisit(node); } public virtual void VisitOuterJoinedTableReference(OuterJoinedTableReferenceSyntax node) { DefaultVisit(node); } public virtual void VisitNamedTableReference(NamedTableReferenceSyntax node) { DefaultVisit(node); } public virtual void VisitParenthesizedTableReference(ParenthesizedTableReferenceSyntax node) { DefaultVisit(node); } public virtual void VisitTopClause(TopClauseSyntax node) { DefaultVisit(node); } public virtual void VisitWhereClause(WhereClauseSyntax node) { DefaultVisit(node); } } }
32.466292
116
0.5828
[ "MIT" ]
dallmair/nquery-vnext
src/NQuery/SyntaxVisitor.cs
17,337
C#
using System.ComponentModel; using System.IO.Abstractions; using System.Text; using BenchmarkMockNet.Benchmarks; namespace BenchmarkMockNet; public class Report { private readonly StringBuilder _output; private readonly IFileSystem _fs; public Report(IFileSystem fs) { _fs = fs; _output = new StringBuilder(); } public async Task Save() { _output.AppendLine("# BenchmarkMockNet Results"); _output.AppendLine(); _output.AppendLine($"## Official Run: {DateTime.Today:d}"); _output.AppendLine(); ListFrameworks(); _output.AppendLine(); await OutputResults(); await _fs.File.WriteAllTextAsync("Results.md", _output.ToString()); } private async Task OutputResults() { foreach (var benchmark in All.Benchmarks) { _output.AppendLine($"### {benchmark.Name}"); _output.AppendLine(); var description = benchmark.CustomAttributes.First(a => a.AttributeType == typeof(DescriptionAttribute)); _output.AppendLine(description.ConstructorArguments.First().Value?.ToString()); var file = Path.Combine("BenchmarkDotNet.Artifacts", "results", $"{benchmark.FullName}-report-github.md"); var content = await _fs.File.ReadAllTextAsync(file); var table = content.Split("```").Last().Replace(content, "") .Replace(" ns", "\u202Fns") .Replace(" B", "\u202FB"); _output.AppendLine(table); } } private void ListFrameworks() { _output.AppendLine("| Framework | Version |"); _output.AppendLine("|-----------|---------|"); foreach (var framework in All.Frameworks) { _output.AppendLine($"| {framework.Name} | {framework.Version} |"); } } }
25.492063
109
0.697385
[ "MIT" ]
ScriptBox99/BenchmarkMockNet
BenchmarkMockNet/Report.cs
1,606
C#
using System.Runtime.Serialization; using Elasticsearch.Net; namespace Nest { [JsonFormatter(typeof(ReindexRoutingFormatter))] public class ReindexRouting { public static ReindexRouting Discard = new ReindexRouting("discard", true); public static ReindexRouting Keep = new ReindexRouting("keep", true); private readonly string _newRoutingValue; /// <summary> /// Use ReindexRouting.Keep or ReindexRouting.Discard if you want to sent "keep" or "discard", this /// constructor always sends newRoutingValue prefixed with '=' /// </summary> public ReindexRouting(string newRoutingValue) : this(newRoutingValue, false) { } private ReindexRouting(string newRoutingValue, bool noPrefix) { var routing = newRoutingValue.TrimStart('='); var prefix = noPrefix ? "" : "="; _newRoutingValue = $"{prefix}{routing}"; } public static implicit operator ReindexRouting(string routing) => new ReindexRouting(routing); public override string ToString() => _newRoutingValue; } }
32.354839
101
0.743769
[ "Apache-2.0" ]
591094733/elasticsearch-net
src/Nest/Document/Multiple/ReindexOnServer/ReindexRouting.cs
1,003
C#
//------------------------------------------------------------------------------ // <auto-generated> // このコードはツールによって生成されました。 // ランタイム バージョン:4.0.30319.34209 // // このファイルへの変更は、以下の状況下で不正な動作の原因になったり、 // コードが再生成されるときに損失したりします。 // </auto-generated> //------------------------------------------------------------------------------ namespace MsgPack.Serialization.GeneratedSerializers.ArrayBased { [System.CodeDom.Compiler.GeneratedCodeAttribute("MsgPack.Serialization.CodeDomSerializers.CodeDomSerializerBuilder", "0.6.0.0")] [System.Diagnostics.DebuggerNonUserCodeAttribute()] public class MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictObjectKeyAndStaticItemReadWriteFieldSerializer : MsgPack.Serialization.MessagePackSerializer<MsgPack.Serialization.PolymorphicMemberTypeKnownType_Dict_DictObjectKeyAndStaticItemReadWriteField> { private MsgPack.Serialization.MessagePackSerializer<System.Collections.Generic.IDictionary<object, string>> _serializer0; public MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictObjectKeyAndStaticItemReadWriteFieldSerializer(MsgPack.Serialization.SerializationContext context) : base(context) { MsgPack.Serialization.PolymorphismSchema schema0 = default(MsgPack.Serialization.PolymorphismSchema); MsgPack.Serialization.PolymorphismSchema keysSchema0 = default(MsgPack.Serialization.PolymorphismSchema); System.Collections.Generic.Dictionary<string, System.Type> keysSchemaTypeMap0 = default(System.Collections.Generic.Dictionary<string, System.Type>); keysSchemaTypeMap0 = new System.Collections.Generic.Dictionary<string, System.Type>(2); keysSchemaTypeMap0.Add("1", typeof(MsgPack.Serialization.DirectoryEntry)); keysSchemaTypeMap0.Add("0", typeof(MsgPack.Serialization.FileEntry)); keysSchema0 = MsgPack.Serialization.PolymorphismSchema.ForPolymorphicObject(typeof(object), keysSchemaTypeMap0); schema0 = MsgPack.Serialization.PolymorphismSchema.ForContextSpecifiedDictionary(typeof(System.Collections.Generic.IDictionary<object, string>), keysSchema0, null); this._serializer0 = context.GetSerializer<System.Collections.Generic.IDictionary<object, string>>(schema0); } protected internal override void PackToCore(MsgPack.Packer packer, MsgPack.Serialization.PolymorphicMemberTypeKnownType_Dict_DictObjectKeyAndStaticItemReadWriteField objectTree) { packer.PackArrayHeader(1); this._serializer0.PackTo(packer, objectTree.DictObjectKeyAndStaticItem); } protected internal override MsgPack.Serialization.PolymorphicMemberTypeKnownType_Dict_DictObjectKeyAndStaticItemReadWriteField UnpackFromCore(MsgPack.Unpacker unpacker) { MsgPack.Serialization.PolymorphicMemberTypeKnownType_Dict_DictObjectKeyAndStaticItemReadWriteField result = default(MsgPack.Serialization.PolymorphicMemberTypeKnownType_Dict_DictObjectKeyAndStaticItemReadWriteField); result = new MsgPack.Serialization.PolymorphicMemberTypeKnownType_Dict_DictObjectKeyAndStaticItemReadWriteField(); if (unpacker.IsArrayHeader) { int unpacked = default(int); int itemsCount = default(int); itemsCount = MsgPack.Serialization.UnpackHelpers.GetItemsCount(unpacker); System.Collections.Generic.IDictionary<object, string> nullable = default(System.Collections.Generic.IDictionary<object, string>); if ((unpacked < itemsCount)) { if ((unpacker.Read() == false)) { throw MsgPack.Serialization.SerializationExceptions.NewMissingItem(0); } if (((unpacker.IsArrayHeader == false) && (unpacker.IsMapHeader == false))) { nullable = this._serializer0.UnpackFrom(unpacker); } else { MsgPack.Unpacker disposable = default(MsgPack.Unpacker); disposable = unpacker.ReadSubtree(); try { nullable = this._serializer0.UnpackFrom(disposable); } finally { if (((disposable == null) == false)) { disposable.Dispose(); } } } } if (((nullable == null) == false)) { result.DictObjectKeyAndStaticItem = nullable; } unpacked = (unpacked + 1); } else { int itemsCount0 = default(int); itemsCount0 = MsgPack.Serialization.UnpackHelpers.GetItemsCount(unpacker); for (int i = 0; (i < itemsCount0); i = (i + 1)) { string key = default(string); string nullable0 = default(string); nullable0 = MsgPack.Serialization.UnpackHelpers.UnpackStringValue(unpacker, typeof(MsgPack.Serialization.PolymorphicMemberTypeKnownType_Dict_DictObjectKeyAndStaticItemReadWriteField), "MemberName"); if (((nullable0 == null) == false)) { key = nullable0; } else { throw MsgPack.Serialization.SerializationExceptions.NewNullIsProhibited("MemberName"); } if ((key == "DictObjectKeyAndStaticItem")) { System.Collections.Generic.IDictionary<object, string> nullable1 = default(System.Collections.Generic.IDictionary<object, string>); if ((unpacker.Read() == false)) { throw MsgPack.Serialization.SerializationExceptions.NewMissingItem(i); } if (((unpacker.IsArrayHeader == false) && (unpacker.IsMapHeader == false))) { nullable1 = this._serializer0.UnpackFrom(unpacker); } else { MsgPack.Unpacker disposable0 = default(MsgPack.Unpacker); disposable0 = unpacker.ReadSubtree(); try { nullable1 = this._serializer0.UnpackFrom(disposable0); } finally { if (((disposable0 == null) == false)) { disposable0.Dispose(); } } } if (((nullable1 == null) == false)) { result.DictObjectKeyAndStaticItem = nullable1; } } else { unpacker.Skip(); } } } return result; } private static T @__Conditional<T>(bool condition, T whenTrue, T whenFalse) { if (condition) { return whenTrue; } else { return whenFalse; } } } }
57.044776
273
0.55573
[ "Apache-2.0" ]
sosan/msgpack-cli
test/MsgPack.UnitTest/gen/array/MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictObjectKeyAndStaticItemReadWriteFieldSerializer.cs
7,818
C#
/* * 金庸群侠传3D重制版 * https://github.com/jynew/jynew * * 这是本开源项目文件头,所有代码均使用MIT协议。 * 但游戏内资源和第三方插件、dll等请仔细阅读LICENSE相关授权协议文档。 * * 金庸老先生千古! */ using System.Collections; using System.Collections.Generic; using UnityEngine; public struct PropertyItem { public int ID; public string Name; public string PropertyName; public int DefaulMax;//初始化的时候的最大值 public int DefaulMin;//初始化的时候的最小值 public PropertyItem(int ID, string PropertyName, string Name, int DefaulMax, int DefaulMin) { this.ID = ID; this.Name = Name; this.PropertyName = PropertyName; this.DefaulMax = DefaulMax; this.DefaulMin = DefaulMin; } } public class ColorStringDefine { public const string Red = "#EE2616"; public const string Yellow = "#EFCB28"; public const string Default="white"; public const string Mp_type1="orange"; public const string Mp_type0="#A564DB"; public const string Hp_posion="green"; public const string Hp_hurt_light="#FD726F"; public const string Hp_hurt_heavy="#F8413E"; public static Color main_menu_selected = new Color(238/255.0f,39/255.0f,24/255.0f,1.0f); public static Color main_menu_normal = new Color(125/255.0f,9/255.0f,0.0f,1.0f); public static Color save_selected = new Color(164/255.0f,164/255.0f,164/255.0f,1.0f); public static Color save_normal = new Color(1.0f,1.0f,1.0f); public static Color system_item_selected = new Color(1.0f,223/255.0f,181/255.0f); public static Color system_item_normal = new Color(1.0f,150/255.0f,16/255.0f,1.0f); } public class GameConst { public const string DefaultMainMenuScene = "0_GameStart"; public const float MapSpeed = 5; public const float MapAngularSpeed = 360; public const float MapAcceleration = 15; public const bool SEMI_REAL = false;//游戏是否是半即时制 public const int ACTION_SP = 1000;//半即时制的情况下 行动一次的花费 public const int MAX_ROLE_LEVEL = 30; public const int MAX_EXP = 9999999; //JYX2最大体力上限 public const int MAX_ROLE_TILI = 100; public const int MAX_POISON = 100; public const int MAX_USE_POISON = 100; public const int MAX_HEAL = 100; public const int MAX_DEPOISON = 100; public const int MAX_ANTIPOISON = 100; public const int MAX_HURT = 100; public const int GAME_START_MUSIC_ID = 16; /// <summary> /// 最大角色的武器熟练度 /// </summary> public const int MAX_ROLE_WEAPON_ATTR = 100; public const int MAX_ROLE_HP = 999; public const int MAX_ROLE_MP = 999; public const int MAX_ROLE_ATTACK = 100; public const int MAX_ROLE_DEFENCE = 100; public const int MAX_ROLE_QINGGONG = 100; public const int MAX_ROLE_ATK_POISON = 100; public const int MAX_ROLE_SHENGWANG = 200; public const int MAX_ROLE_PINDE = 100; public const int MAX_ROLE_ZIZHI = 100; /// <summary> /// 最大技能等级,每1级是100,最大10级所以是1000 /// </summary> public const int MAX_SKILL_LEVEL = 100 * (MAX_WUGONG_LEVEL - 1); /// <summary> /// 最大技能等级 /// </summary> public const int MAX_WUGONG_LEVEL = 10; /// <summary> /// 角色的最大武功学习数量 /// </summary> public const int MAX_ROLE_WUGONG_COUNT = 10; //银两ID public const int MONEY_ID = 174; //最大队伍人数 public const int MAX_TEAMCOUNT = 6; //最大技能数量 public const int MAX_SKILL_COUNT = 10; //最大资质 public const int MAX_ZIZHI = 100; //最大属性 public const int MAX_ROLE_ATTRITE = 100; //最大生命和内力 public const int MAX_HPMP = 999; //最大战斗上场人数 public const int MAX_BATTLE_TEAMMATE_COUNT = 6; //对话框最大可以显示字符 public const int MAX_CHAT_CHART_NUM=156; //战斗胜利结果最大显示行数 public const int MAX_BATTLE_RESULT_LINE_NUM=7; //世界地图ID public const int WORLD_MAP_ID = 1000; public static readonly int[] _levelUpExpList = new int[] { 50, 100, 150, 200, 250, 300, 350, 400, 450, 500, 1100, 1200, 1300, 1400, 1500, 1600, 1700, 1800, 2400, 1500, 3150, 3300, 3450, 3650, 3700, 3900, 4050, 4200, 4350, 4500, 4600, 4800, 5000, 5100, 5200, 5300, 5500, 5600, 5800, 6000, 6200, 6400, 6600, 6800, 7000, 7200, 7400, 7600, 7800, 8000, 8200, 8400, 8600, 8800, 9200, 9600, 10000, 20000, 30000 }; public const string UI_PREFAB_PATH = "Assets/Prefabs/Jyx2UI/{0}.prefab"; public static Dictionary<string, PropertyItem> ProItemDic = new Dictionary<string, PropertyItem>() { ["0"] = new PropertyItem(0, "MpType", "内力性质", 2, 0), ["1"] = new PropertyItem(1, "MaxMp", "内力",40,30),//创角用到 特殊 ["2"] = new PropertyItem(2, "Attack", "武力",30,20),//创角用到 特殊 ["3"] = new PropertyItem(3, "Qinggong", "轻功", 30, 20), ["4"] = new PropertyItem(4, "Defence", "防御", 30, 20), ["5"] = new PropertyItem(5, "MaxHp", "生命",50,30),//创角用到 特殊 ["6"] = new PropertyItem(6, "Heal", "医疗", 30, 20), ["7"] = new PropertyItem(7, "UsePoison", "使毒", 30, 20), ["8"] = new PropertyItem(8, "DePoison", "解毒", 30, 20), ["9"] = new PropertyItem(9, "Quanzhang", "拳掌", 30, 20), ["10"] = new PropertyItem(10, "Yujian", "剑术", 30, 20), ["11"] = new PropertyItem(11, "Shuadao", "刀术", 30, 20), ["12"] = new PropertyItem(12, "Anqi", "暗器", 30, 20), ["13"] = new PropertyItem(13, "Hp", "生命", 30, 20), ["14"] = new PropertyItem(14, "Tili", "体力", 30, 20), ["15"] = new PropertyItem(15, "Mp", "内力", 40, 30), ["16"] = new PropertyItem(16, "MaxHp", "最大生命", 50, 30), ["17"] = new PropertyItem(17, "MaxMp", "最大内力", 40, 30), ["18"] = new PropertyItem(18, "Attack", "攻击力", 30, 20), ["19"] = new PropertyItem(19, "AntiPoison", "抗毒", 30, 20), ["20"] = new PropertyItem(20, "Qimen", "奇门", 30, 20), ["21"] = new PropertyItem(21, "Wuxuechangshi", "武学常识", 30, 20), ["22"] = new PropertyItem(22, "Pinde", "品德", 30, 20), ["23"] = new PropertyItem(23, "AttackPoison", "功夫带毒", 30, 20), ["24"] = new PropertyItem(24, "Zuoyouhubo", "左右互搏", 30, 20), ["25"] = new PropertyItem(25, "IQ", "资质", 100, 30), ["26"] = new PropertyItem(26, "Poison", "中毒", 30, 20), }; //存档的数量 public const int SAVE_COUNT = 3; public static string GetUPNumber(int index) { switch (index) { case 1: return "一"; case 2: return "二"; case 3: return "三"; default: return ""; } } }
33.567708
410
0.616757
[ "MIT" ]
ning99999/jynew
jyx2/Assets/Scripts/GameConst.cs
7,077
C#
using System; namespace Mediator { internal class Colleague2 : Colleague { public Colleague2(IMediator mediator) : base(mediator) { } public override void HandleNotification(string message) { Console.WriteLine($"{nameof(Colleague2)} received: {message} (from c1)"); } } }
21.625
85
0.598266
[ "MIT" ]
daviur/DesignPatterns
Mediator/Colleague2.cs
348
C#
using Foundation; using UIKit; namespace WaterAddition.iOS { [Register("AppDelegate")] public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate { public override bool FinishedLaunching(UIApplication app, NSDictionary options) { global::Xamarin.Forms.Forms.Init(); LoadApplication(new App()); return base.FinishedLaunching(app, options); } } }
24.210526
98
0.665217
[ "MIT" ]
Porodin/WaterAddition
WaterAddition.iOS/AppDelegate.cs
460
C#
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.Network.Models { using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; /// <summary> /// Collection of SecurityProviders. /// </summary> public partial class VirtualWanSecurityProviders { /// <summary> /// Initializes a new instance of the VirtualWanSecurityProviders /// class. /// </summary> public VirtualWanSecurityProviders() { CustomInit(); } /// <summary> /// Initializes a new instance of the VirtualWanSecurityProviders /// class. /// </summary> /// <param name="supportedProviders">List of VirtualWAN security /// providers.</param> public VirtualWanSecurityProviders(IList<VirtualWanSecurityProvider> supportedProviders = default(IList<VirtualWanSecurityProvider>)) { SupportedProviders = supportedProviders; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets list of VirtualWAN security providers. /// </summary> [JsonProperty(PropertyName = "supportedProviders")] public IList<VirtualWanSecurityProvider> SupportedProviders { get; set; } } }
31.736842
141
0.645108
[ "MIT" ]
0rland0Wats0n/azure-sdk-for-net
sdk/network/Microsoft.Azure.Management.Network/src/Generated/Models/VirtualWanSecurityProviders.cs
1,809
C#
using System; using System.Linq; using LinqToDB; using NUnit.Framework; namespace Tests.Linq { using Model; [TestFixture] public class ElementOperationTests : TestBase { [Test, DataContextSource] public void First(string context) { using (var db = GetDataContext(context)) Assert.AreEqual( Parent.OrderByDescending(p => p.ParentID).First().ParentID, db.Parent.OrderByDescending(p => p.ParentID).First().ParentID); } [Test, DataContextSource] public void FirstWhere(string context) { using (var db = GetDataContext(context)) Assert.AreEqual(2, db.Parent.First(p => p.ParentID == 2).ParentID); } [Test, DataContextSource] public void FirstOrDefault(string context) { using (var db = GetDataContext(context)) Assert.IsNull((from p in db.Parent where p.ParentID == 100 select p).FirstOrDefault()); } [Test, DataContextSource] public void FirstOrDefaultWhere(string context) { using (var db = GetDataContext(context)) Assert.AreEqual(2, db.Parent.FirstOrDefault(p => p.ParentID == 2).ParentID); } [Test, DataContextSource] public void Single(string context) { using (var db = GetDataContext(context)) Assert.AreEqual(1, db.Parent.Where(p => p.ParentID == 1).Single().ParentID); } [Test, DataContextSource] public void SingleWhere(string context) { using (var db = GetDataContext(context)) Assert.AreEqual(2, db.Parent.Single(p => p.ParentID == 2).ParentID); } [Test, DataContextSource] public void SingleOrDefault(string context) { using (var db = GetDataContext(context)) Assert.IsNull((from p in db.Parent where p.ParentID == 100 select p).SingleOrDefault()); } [Test, DataContextSource] public void SingleOrDefaultWhere(string context) { using (var db = GetDataContext(context)) Assert.AreEqual(2, db.Parent.SingleOrDefault(p => p.ParentID == 2).ParentID); } [Test, DataContextSource] public void FirstOrDefaultScalar(string context) { using (var db = GetDataContext(context)) Assert.AreEqual( Parent.OrderBy(p => p.ParentID).FirstOrDefault().ParentID, db.Parent.OrderBy(p => p.ParentID).FirstOrDefault().ParentID); } [Test, DataContextSource(ProviderName.Informix, ProviderName.Sybase, ProviderName.SapHana)] public void NestedFirstOrDefaultScalar1(string context) { using (var db = GetDataContext(context)) AreEqual( from p in Parent select Child.FirstOrDefault().ChildID, from p in db.Parent select db.Child.FirstOrDefault().ChildID); } [Test, DataContextSource(ProviderName.Informix, ProviderName.OracleNative, ProviderName.OracleManaged, ProviderName.Sybase, ProviderName.SapHana)] public void NestedFirstOrDefaultScalar2(string context) { using (var db = GetDataContext(context)) AreEqual( from p in Parent select new { p.ParentID, MaxChild = Child .Where(c => c.Parent == p) .OrderByDescending(c => c.ChildID * c.ParentID) .FirstOrDefault() == null ? 0 : Child .Where(c => c.Parent == p) .OrderByDescending(c => c.ChildID * c.ParentID) .FirstOrDefault() .ChildID }, from p in db.Parent select new { p.ParentID, MaxChild = db.Child .Where(c => c.Parent == p) .OrderByDescending(c => c.ChildID * c.ParentID) .FirstOrDefault() .ChildID }); } [Test, DataContextSource] public void NestedFirstOrDefault1(string context) { LinqToDB.Common.Configuration.Linq.AllowMultipleQuery = true; using (var db = GetDataContext(context)) AreEqual( from p in Parent select Child.FirstOrDefault(), from p in db.Parent select db.Child.FirstOrDefault()); LinqToDB.Common.Configuration.Linq.AllowMultipleQuery = false; } [Test, DataContextSource] public void NestedFirstOrDefault2(string context) { LinqToDB.Common.Configuration.Linq.AllowMultipleQuery = true; using (var db = GetDataContext(context)) AreEqual( from p in Parent select p.Children.FirstOrDefault(), from p in db.Parent select p.Children.FirstOrDefault()); LinqToDB.Common.Configuration.Linq.AllowMultipleQuery = false; } [Test, DataContextSource(ProviderName.Informix, ProviderName.Firebird, ProviderName.SapHana)] public void NestedFirstOrDefault3(string context) { using (var db = GetDataContext(context)) AreEqual( from p in Parent select p.Children.Select(c => c.ParentID).Distinct().FirstOrDefault(), from p in db.Parent select p.Children.Select(c => c.ParentID).Distinct().FirstOrDefault()); } [Test, DataContextSource(ProviderName.Informix, ProviderName.Firebird, ProviderName.PostgreSQL)] public void NestedFirstOrDefault4(string context) { LinqToDB.Common.Configuration.Linq.AllowMultipleQuery = true; using (var db = GetDataContext(context)) AreEqual( from p in Parent select p.Children.Where(c => c.ParentID > 0).Distinct().FirstOrDefault(), from p in db.Parent select p.Children.Where(c => c.ParentID > 0).Distinct().FirstOrDefault()); LinqToDB.Common.Configuration.Linq.AllowMultipleQuery = false; } [Test, DataContextSource] public void NestedFirstOrDefault5(string context) { LinqToDB.Common.Configuration.Linq.AllowMultipleQuery = true; using (var db = GetDataContext(context)) AreEqual( from p in GrandChild select p.Child.Parent.Children.FirstOrDefault(), from p in db.GrandChild select p.Child.Parent.Children.FirstOrDefault()); LinqToDB.Common.Configuration.Linq.AllowMultipleQuery = false; } [Test, DataContextSource] public void NestedSingleOrDefault1(string context) { using (var db = GetDataContext(context)) AreEqual( from p in Parent select p.Children.Select(c => c.ParentID).Distinct().SingleOrDefault(), from p in db.Parent select p.Children.Select(c => c.ParentID).Distinct().SingleOrDefault()); } [Test, NorthwindDataContext] public void FirstOrDefaultEntitySet(string context) { using (var db = new NorthwindDB()) { AreEqual( Customer.Select(c => c.Orders.FirstOrDefault()), db.Customer.Select(c => c.Orders.FirstOrDefault())); } } [Test, NorthwindDataContext] public void NestedSingleOrDefaultTest(string context) { using (var db = new NorthwindDB()) { AreEqual( Customer.Select(c => c.Orders.Take(1).SingleOrDefault()), db.Customer.Select(c => c.Orders.Take(1).SingleOrDefault())); } } [Test, NorthwindDataContext] public void MultipleQuery(string context) { using (var db = new NorthwindDB()) { var q = from p in db.Product select db.Category.Select(zrp => zrp.CategoryName).FirstOrDefault(); q.ToList(); } } } }
30.591304
149
0.669557
[ "MIT" ]
codefox42/linq2db
Tests/Linq/Linq/ElementOperationTests.cs
7,038
C#
using System; using UnityEngine; namespace Assets.Scripts.Common { public class MonoSingleton<T> : MonoBehaviour where T : Component { private static T InnerInstance; private static bool bIsDestroyed; private static readonly string RootObjectName = "RootObj"; public static T GetInstance() { Debug.Log ("[MonoSingleton]GetInstance ..."); if (InnerInstance == null && !bIsDestroyed) { Type theType = typeof(T); InnerInstance = (T)FindObjectOfType(theType); if (InnerInstance == null) { var go = new GameObject(typeof(T).Name); go.AddComponent<T>(); GameObject bootObj = GameObject.Find(RootObjectName); if (bootObj != null) { go.transform.parent = bootObj.transform; } } } return InnerInstance; } public static T instance { get { return GetInstance(); } } public static void DestroyInstance() { if (InnerInstance != null) { Destroy(InnerInstance.gameObject); } bIsDestroyed = true; InnerInstance = null; } protected virtual void Awake() { if (InnerInstance != null && InnerInstance.gameObject != gameObject) { if (Application.isPlaying) { Destroy(gameObject); } else { DestroyImmediate(gameObject); } } else if (InnerInstance == null) { InnerInstance = GetComponent<T>(); } DontDestroyOnLoad(gameObject); Init(); } protected virtual void OnDestroy() { if (InnerInstance != null && InnerInstance.gameObject == gameObject) { InnerInstance = null; } } public virtual void DestroySelf() { InnerInstance = null; Destroy(gameObject); } public static bool HasInstance() { return InnerInstance != null; } protected virtual void Init() { } } }
24.313725
80
0.460081
[ "MIT" ]
martinkro/Unity-CheatConsole
Assets/Scripts/Common/MonoSingleton.cs
2,482
C#
using System; using DOA; namespace Cocktail { public interface IScope { State Dereference(TStateId sid); State Dereference(TStateId sid, string refType); } public abstract class StateRef { protected string m_refType; public TStateId StateId { get; private set; } protected StateRef(TStateId stateId, Type refType) :this(stateId, refType.ToString()) { } protected StateRef(TStateId stateId, string refType) { StateId = stateId; m_refType = refType; } public string GetRefType() { return m_refType; } public abstract State GetObject(IScope scope); public virtual void Sync() { throw new NotImplementedException(); } public virtual T GetField<T>(string name) { throw new NotImplementedException(); } public virtual void SetField<T>(string name, T val) { throw new NotImplementedException(); } } public abstract class DirectStateRef : StateRef { protected State m_impl; public DirectStateRef(State impl) :base(impl.StateId, impl.GetType()) { m_impl = impl; } public override State GetObject(IScope scope) { return m_impl; } } public class _LocalStateRef<T> : DirectStateRef where T : State { public _LocalStateRef(T impl) :base(impl) { } public T GetInterface() { return (T)m_impl; } public override void Sync() { } public override TField GetField<TField>(string name) { return (TField)m_impl.GetType().GetField(name).GetValue(m_impl); } public override void SetField<TField>(string name, TField val) { m_impl.GetType().GetField(name).SetValue(m_impl, val); } } //// DEPRECATED //public class _RemoteStateRef : StateRef //{ // public _RemoteStateRef(TStateId stateId, string refType) // : base(stateId, refType) // { // } // public object GetObject(Spacetime scope) // { // var state = NamingSvcClient.Instance.GetObject(StateId.ToString(), m_refType); // return state; // } // public override void Sync() // { // //TODO: send it back, with version checking and merging // } // public override T GetField<T>(string name) // { // var state = NamingSvcClient.Instance.GetObject(StateId.ToString(), m_refType); // var type = state.GetType(); // return (T)type.GetField(name).GetValue(state); // } // public override void SetField<T>(string name, T val) // { // var state = NamingSvcClient.Instance.GetObject(StateId.ToString(), m_refType); // var type = state.GetType(); // type.GetField(name).SetValue(state, val); // } //} public class ScopedStateRef : StateRef { public ScopedStateRef(TStateId stateId, string refType) :base(stateId, refType) { } public override State GetObject(IScope scope) { return scope.Dereference(StateId); } public override void Sync() { } } }
23.072581
94
0.665152
[ "MIT" ]
diclogic/cocktailvm
src/Cocktail/StateRef.cs
2,863
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 rekognition-2016-06-27.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.Rekognition.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.Rekognition.Model.Internal.MarshallTransformations { /// <summary> /// DeleteCollection Request Marshaller /// </summary> public class DeleteCollectionRequestMarshaller : IMarshaller<IRequest, DeleteCollectionRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((DeleteCollectionRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(DeleteCollectionRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.Rekognition"); string target = "RekognitionService.DeleteCollection"; request.Headers["X-Amz-Target"] = target; request.Headers["Content-Type"] = "application/x-amz-json-1.1"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2016-06-27"; request.HttpMethod = "POST"; request.ResourcePath = "/"; request.MarshallerVersion = 2; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetCollectionId()) { context.Writer.WritePropertyName("CollectionId"); context.Writer.Write(publicRequest.CollectionId); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } private static DeleteCollectionRequestMarshaller _instance = new DeleteCollectionRequestMarshaller(); internal static DeleteCollectionRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static DeleteCollectionRequestMarshaller Instance { get { return _instance; } } } }
35.380952
147
0.632571
[ "Apache-2.0" ]
PureKrome/aws-sdk-net
sdk/src/Services/Rekognition/Generated/Model/Internal/MarshallTransformations/DeleteCollectionRequestMarshaller.cs
3,715
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("Template10.Samples.ShareTargetSample")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Template10.Samples.ShareTargetSample")] [assembly: AssemblyCopyright("Copyright © 2015")] [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)]
36.3
84
0.749311
[ "Apache-2.0" ]
ArtjomP/Template10
Samples/ShareTarget/Properties/AssemblyInfo.cs
1,090
C#
/* * PagarmeCoreApi.Standard * * This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ). */ using System; using System.IO; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using PagarmeCoreApi.Standard; using PagarmeCoreApi.Standard.Utilities; namespace PagarmeCoreApi.Standard.Models { public class UpdateOrderItemRequest : BaseModel { // These fields hold the values for the public properties. private int amount; private string description; private int quantity; private string category; /// <summary> /// TODO: Write general description for this method /// </summary> [JsonProperty("amount")] public int Amount { get { return this.amount; } set { this.amount = value; onPropertyChanged("Amount"); } } /// <summary> /// TODO: Write general description for this method /// </summary> [JsonProperty("description")] public string Description { get { return this.description; } set { this.description = value; onPropertyChanged("Description"); } } /// <summary> /// TODO: Write general description for this method /// </summary> [JsonProperty("quantity")] public int Quantity { get { return this.quantity; } set { this.quantity = value; onPropertyChanged("Quantity"); } } /// <summary> /// TODO: Write general description for this method /// </summary> [JsonProperty("category")] public string Category { get { return this.category; } set { this.category = value; onPropertyChanged("Category"); } } } }
25.278351
83
0.477162
[ "MIT" ]
pagarme/pagarme-core-api-dotnet-standard
PagarmeCoreApi.Standard/Models/UpdateOrderItemRequest.cs
2,452
C#
using Piraeus.Core.Metadata; using System; using System.Management.Automation; namespace Piraeus.Module { [Cmdlet(VerbsCommon.Add, "PiraeusEventHubSubscription")] public class AddAzureEventHubSubscriptionCmdlet : Cmdlet { [Parameter(HelpMessage = "Url of the service.", Mandatory = true)] public string ServiceUrl; [Parameter(HelpMessage = "Security token used to access the REST service.", Mandatory = true)] public string SecurityToken; [Parameter(HelpMessage = "Unique URI identifier of resource to subscribe.", Mandatory = true)] public string ResourceUriString; [Parameter(HelpMessage = "Account name of EventHub, e.g, <account>.servicebus.windows.net", Mandatory = true)] public string Account; [Parameter(HelpMessage = "Name of EventHub", Mandatory = true)] public string Hub; [Parameter(HelpMessage = "Name of key used for authentication.", Mandatory = true)] public string KeyName; [Parameter(HelpMessage = "(Optional) ID of partition if you want to send message to a single partition.", Mandatory = false)] public string PartitionId; [Parameter(HelpMessage = "Token used for authentication.", Mandatory = true)] public string Key; [Parameter(HelpMessage = "Number of blob storage clients to use.", Mandatory = false)] public int NumClients; [Parameter(HelpMessage = "Description of the subscription.", Mandatory = false)] public string Description; protected override void ProcessRecord() { string uriString = String.Format("eh://{0}.servicebus.windows.net?hub={1}&keyname={2}&clients={3}", Account, Hub, KeyName, NumClients <= 0 ? 1 : NumClients); if (PartitionId != null) { uriString = String.Format("{0}&partitionid={1}", uriString, PartitionId); } SubscriptionMetadata metadata = new SubscriptionMetadata() { IsEphemeral = false, NotifyAddress = uriString, SymmetricKey = Key, Description = this.Description }; string url = String.Format("{0}/api/resource/subscribe?resourceuristring={1}", ServiceUrl, ResourceUriString); RestRequestBuilder builder = new RestRequestBuilder("POST", url, RestConstants.ContentType.Json, false, SecurityToken); RestRequest request = new RestRequest(builder); string subscriptionUriString = request.Post<SubscriptionMetadata, string>(metadata); WriteObject(subscriptionUriString); } } }
37.690141
169
0.648356
[ "MIT" ]
lulzzz/SkunkLab.Core
src/Piraeus.Module.Core/AddAzureEventHubSubscriptionCmdlet.cs
2,678
C#
using System; using System.ComponentModel; using System.Runtime.CompilerServices; namespace RockPaperScissorsGame { public class VM : INotifyPropertyChanged { private readonly Random random = new Random(); private String compWin = "0"; public String CompWin { get { return compWin; } set { compWin = value; onChange(); } } private int compWinNum = 0; private String playerWin = "0"; public String PlayerWin { get { return playerWin; } set { playerWin = value; onChange(); } } private int playerWinNum = 0; public void ResetScore() { compWinNum = 0; CompWin = compWinNum.ToString(); playerWinNum = 0; PlayerWin = playerWinNum.ToString(); Message = null; onChange(); } public int CompChoice() { int value = random.Next(0, 5); return value; } public int UserChoice(int x) { return x; } private String message; public String Message { get { return message; } set { message = value; onChange(); } } public void WinOrLose(int CompNum, int UserNum) { int diff = (CompNum - UserNum); if (diff < 0) diff += 5; if (diff == 2 | diff == 4) { Message = "Computer wins!"; compWinNum++; CompWin = compWinNum.ToString(); onChange(); } else if (diff == 1 | diff == 3) { Message = "User wins!"; playerWinNum++; PlayerWin = playerWinNum.ToString(); onChange(); } else { Message = "Computer and User tie!"; onChange(); } } public event PropertyChangedEventHandler PropertyChanged; private void onChange([CallerMemberName]string property = "") { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property)); } } }
29.1
83
0.464347
[ "MIT" ]
tongw-tw/RockPaperScissorsLizardSpock
RockPaperScissorsGame/VM-TWANG-DESKTOP.cs
2,330
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http; using System.Web.Routing; namespace WebDrh { public class WebApiApplication : System.Web.HttpApplication { protected void Application_Start() { GlobalConfiguration.Configure(WebApiConfig.Register); } } }
20.111111
65
0.698895
[ "MIT" ]
RichardC64/DemoAngularWebApi
server/WebDrh/Global.asax.cs
364
C#
using System; using System.Text.RegularExpressions; using AldursLab.WurmApi.Extensions.DotNet; using AldursLab.WurmApi.Modules.Wurm.Servers.WurmServersModel; namespace AldursLab.WurmApi.Modules.Wurm.Servers { class LogEntriesParser { /// <summary> /// Null if entry is not applicable. /// </summary> public ServerDateStamped TryParseWurmDateTime(LogEntry wurmLogEntry) { //[16:24:19] It is 09:00:48 on day of the Wurm in week 4 of the Bear's starfall in the year of 1035. if (wurmLogEntry.Content.Contains("It is", StringComparison.InvariantCulture)) { if (Regex.IsMatch( wurmLogEntry.Content, @"It is \d\d:\d\d:\d\d on .+ in week .+ in the year of \d+\.", RegexOptions.Compiled)) { var wurmDateTime = TryCreateWurmDateTimeFromLogLine(wurmLogEntry.Content); if (wurmDateTime == null) { return null; } var result = new ServerDateStamped() { WurmDateTime = wurmDateTime.Value, Stamp = wurmLogEntry.Timestamp }; return result; } } return null; } /// <summary> /// Null if entry is not applicable. /// </summary> public ServerUptimeStamped TryParseUptime(LogEntry wurmLogEntry) { if (wurmLogEntry.Content.Contains("The server has been up")) { var uptime = TryGetTimeSpanServerUpSince(wurmLogEntry.Content); if (uptime == null) { return null; } var result = new ServerUptimeStamped() { Uptime = uptime.Value, Stamp = wurmLogEntry.Timestamp }; return result; } return null; } static TimeSpan? TryGetTimeSpanServerUpSince(string logevent) { //EX: The server has been up 1 days, 14 hours and 43 minutes. Match matchdays = Regex.Match(logevent, @"(\d\d*) days", RegexOptions.Compiled); int days = ParseMatchToInt32(matchdays); Match matchhours = Regex.Match(logevent, @"(\d\d*) hours", RegexOptions.Compiled); int hours = ParseMatchToInt32(matchhours); Match matchminutes = Regex.Match(logevent, @"(\d\d*) minutes", RegexOptions.Compiled); int minutes = ParseMatchToInt32(matchminutes); Match matchseconds = Regex.Match(logevent, @"(\d\d*) seconds", RegexOptions.Compiled); int seconds = ParseMatchToInt32(matchseconds); if (!matchdays.Success && !matchhours.Success && !matchminutes.Success && !matchseconds.Success) { return null; } return new TimeSpan(days, hours, minutes, seconds); } static int ParseMatchToInt32(Match match) { if (match.Success) { return Int32.Parse(match.Groups[1].Value); } else { return 0; } } /// <summary> /// Attempt to create WurmDateTime from wurm log line, throws exception on error /// </summary> /// <exception cref="WurmApiException">Parsing failed</exception> /// <param name="logLine"></param> private WurmDateTime? TryCreateWurmDateTimeFromLogLine(string logLine) { //[16:24:19] It is 09:00:48 on day of the Wurm in week 4 of the Bear's starfall in the year of 1035. //time Match wurmTime = Regex.Match(logLine, @" \d\d:\d\d:\d\d ", RegexOptions.Compiled); if (!wurmTime.Success) { return null; } int hour = Convert.ToInt32(wurmTime.Value.Substring(1, 2)); int minute = Convert.ToInt32(wurmTime.Value.Substring(4, 2)); int second = Convert.ToInt32(wurmTime.Value.Substring(7, 2)); //day WurmDay? day = null; foreach (string name in WurmDay.AllNormalizedNames) { if (Regex.IsMatch(logLine, name, RegexOptions.Compiled | RegexOptions.IgnoreCase)) { day = new WurmDay(name); break; } } //week Match wurmWeek = Regex.Match(logLine, @"week (\d)", RegexOptions.Compiled); if (!wurmWeek.Success) { return null; } int week = Convert.ToInt32(wurmWeek.Groups[1].Value); //month(starfall) WurmStarfall? starfall = null; foreach (string name in WurmStarfall.AllNormalizedNames) { if (Regex.IsMatch(logLine, name, RegexOptions.Compiled | RegexOptions.IgnoreCase)) { starfall = new WurmStarfall(name); break; } } //year Match wurmYear = Regex.Match(logLine, @"in the year of (\d+)", RegexOptions.Compiled); if (!wurmYear.Success) { return null; } int year = Convert.ToInt32(wurmYear.Groups[1].Value); if (day == null || starfall == null) { return null; } return new WurmDateTime(year, starfall.Value, week, day.Value, hour, minute, second); } } }
37.2
112
0.511793
[ "MIT" ]
artizzan/WurmAssistant3
src/WurmApi/WurmApi/Modules/Wurm/Servers/LogEntriesParser.cs
5,766
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.Reflection; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.CompilerServices; using Internal.Runtime.Augments; namespace System { [StructLayoutAttribute(LayoutKind.Sequential)] public struct RuntimeFieldHandle : IEquatable<RuntimeFieldHandle>, ISerializable { private IntPtr _value; public IntPtr Value => _value; public override bool Equals(object? obj) { if (!(obj is RuntimeFieldHandle)) return false; return Equals((RuntimeFieldHandle)obj); } public bool Equals(RuntimeFieldHandle handle) { if (_value == handle._value) return true; if (_value == IntPtr.Zero || handle._value == IntPtr.Zero) return false; string fieldName1, fieldName2; RuntimeTypeHandle declaringType1, declaringType2; RuntimeAugments.TypeLoaderCallbacks.GetRuntimeFieldHandleComponents(this, out declaringType1, out fieldName1); RuntimeAugments.TypeLoaderCallbacks.GetRuntimeFieldHandleComponents(handle, out declaringType2, out fieldName2); return declaringType1.Equals(declaringType2) && fieldName1 == fieldName2; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int _rotl(int value, int shift) { return (int)(((uint)value << shift) | ((uint)value >> (32 - shift))); } public override int GetHashCode() { if (_value == IntPtr.Zero) return 0; string fieldName; RuntimeTypeHandle declaringType; RuntimeAugments.TypeLoaderCallbacks.GetRuntimeFieldHandleComponents(this, out declaringType, out fieldName); int hashcode = declaringType.GetHashCode(); return (hashcode + _rotl(hashcode, 13)) ^ fieldName.GetHashCode(); } public static bool operator ==(RuntimeFieldHandle left, RuntimeFieldHandle right) { return left.Equals(right); } public static bool operator !=(RuntimeFieldHandle left, RuntimeFieldHandle right) { return !left.Equals(right); } public void GetObjectData(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(); } } }
32.225
124
0.643522
[ "MIT" ]
AlexanderSemenyak/runtime
src/coreclr/nativeaot/System.Private.CoreLib/src/System/RuntimeFieldHandle.cs
2,578
C#
namespace Core4.Sagas.SimpleSaga { public class CompleteOrder { public string OrderId { get; set; } } }
18.428571
44
0.604651
[ "Apache-2.0" ]
A-Franklin/docs.particular.net
Snippets/Core/Core_4/Sagas/SimpleSaga/CompleteOrder.cs
123
C#
using System; using System.Collections.Generic; using System.Web.Routing; namespace CompositeC1Contrib.Rendering.Mvc { public class BootstrapperConfiguration : IBootstrapperConfiguration { public IEnumerable<Type> TemplateTypes { get; private set; } public Action<RouteCollection> RouteRegistrator { get; private set; } public void UseTemplates(params Type[] templateTypes) { TemplateTypes = templateTypes; } public void RegisterRoutes(Action<RouteCollection> action) { RouteRegistrator = action; } } }
27.347826
78
0.650238
[ "MIT" ]
burningice2866/CompositeC1Contrib
Rendering.Mvc/BootstrapperConfiguration.cs
631
C#
#region Copyright // // DotNetNuke® - http://www.dotnetnuke.com // Copyright (c) 2002-2018 // by DotNetNuke Corporation // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated // documentation files (the "Software"), to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and // to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions // of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED // TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF // CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #endregion #region Usings using System.Collections.Generic; using System.Linq; using DotNetNuke.Common; using DotNetNuke.Common.Utilities; using DotNetNuke.Entities.Content.Common; using DotNetNuke.Entities.Content.Data; #endregion namespace DotNetNuke.Entities.Content { /// <summary> /// ContentTypeController provides the business layer of ContentType. /// </summary> /// <remarks> /// </remarks> /// <example> /// <code lang="C#"> /// IContentTypeController typeController = new ContentTypeController(); /// ContentType contentType = (from t in typeController.GetContentTypes() /// where t.ContentType == "DesktopModule" /// select t).SingleOrDefault(); /// if(contentType == null) /// { /// contentType = new ContentType {ContentType = "DesktopModule"}; /// contentType.ContentTypeId = typeController.AddContentType(contentType); /// } /// </code> /// </example> public class ContentTypeController : IContentTypeController { private readonly IDataService _DataService; #region Constructors public ContentTypeController() : this(Util.GetDataService()) { } public ContentTypeController(IDataService dataService) { _DataService = dataService; } #endregion #region Public Methods /// <summary> /// Adds the type of the content. /// </summary> /// <param name="contentType">Type of the content.</param> /// <returns>content type id.</returns> /// <exception cref="System.ArgumentNullException">content type is null.</exception> /// <exception cref="System.ArgumentException">contentType.ContentType is empty.</exception> public int AddContentType(ContentType contentType) { //Argument Contract Requires.NotNull("contentType", contentType); Requires.PropertyNotNullOrEmpty("contentType", "ContentType", contentType.ContentType); contentType.ContentTypeId = _DataService.AddContentType(contentType); //Refresh cached collection of types ClearContentTypeCache(); return contentType.ContentTypeId; } /// <summary> /// Clears the content type cache. /// </summary> public void ClearContentTypeCache() { DataCache.RemoveCache(DataCache.ContentTypesCacheKey); } /// <summary> /// Deletes the type of the content. /// </summary> /// <param name="contentType">Type of the content.</param> /// <exception cref="System.ArgumentNullException">content type is null.</exception> /// <exception cref="System.ArgumentOutOfRangeException">content type id is less than 0.</exception> public void DeleteContentType(ContentType contentType) { //Argument Contract Requires.NotNull("contentType", contentType); Requires.PropertyNotNegative("contentType", "ContentTypeId", contentType.ContentTypeId); _DataService.DeleteContentType(contentType); //Refresh cached collection of types ClearContentTypeCache(); } /// <summary> /// Gets the content types. /// </summary> /// <returns>content type collection.</returns> public IQueryable<ContentType> GetContentTypes() { return CBO.GetCachedObject<List<ContentType>>(new CacheItemArgs(DataCache.ContentTypesCacheKey, DataCache.ContentTypesCacheTimeOut, DataCache.ContentTypesCachePriority), c => CBO.FillQueryable<ContentType>(_DataService.GetContentTypes()).ToList()).AsQueryable(); } /// <summary> /// Updates the type of the content. /// </summary> /// <param name="contentType">Type of the content.</param> /// <exception cref="System.ArgumentNullException">content type is null.</exception> /// <exception cref="System.ArgumentOutOfRangeException">content type id is less than 0.</exception> /// <exception cref="System.ArgumentException">contentType.ContentType is empty.</exception> public void UpdateContentType(ContentType contentType) { //Argument Contract Requires.NotNull("contentType", contentType); Requires.PropertyNotNegative("contentType", "ContentTypeId", contentType.ContentTypeId); Requires.PropertyNotNullOrEmpty("contentType", "ContentType", contentType.ContentType); _DataService.UpdateContentType(contentType); //Refresh cached collection of types ClearContentTypeCache(); } #endregion } }
40.620915
156
0.638777
[ "MIT" ]
Abrahamberg/Dnn.Platform
DNN Platform/Library/Entities/Content/ContentTypeController.cs
6,218
C#
using ITfoxtec.Identity.Saml2; using ITfoxtec.Identity.Saml2.MvcCore; using ITfoxtec.Identity.Saml2.Schemas; using ITfoxtec.Identity.Saml2.Schemas.Metadata; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Options; using System; using System.Collections.Generic; using System.Security.Cryptography.X509Certificates; namespace TestWebApp.Controllers { [AllowAnonymous] [Route("Metadata")] public class MetadataController : Controller { private readonly Saml2Configuration config; public MetadataController(IOptions<Saml2Configuration> configAccessor) { config = configAccessor.Value; } public IActionResult Index() { var defaultSite = new Uri($"{Request.Scheme}://{Request.Host.ToUriComponent()}/"); var entityDescriptor = new EntityDescriptor(config); entityDescriptor.ValidUntil = 365; entityDescriptor.SPSsoDescriptor = new SPSsoDescriptor { WantAssertionsSigned = true, SigningCertificates = new X509Certificate2[] { config.SigningCertificate }, //EncryptionCertificates = new X509Certificate2[] //{ // config.DecryptionCertificate //}, SingleLogoutServices = new SingleLogoutService[] { new SingleLogoutService { Binding = ProtocolBindings.HttpPost, Location = new Uri(defaultSite, "Auth/SingleLogout"), ResponseLocation = new Uri(defaultSite, "Auth/LoggedOut") } }, NameIDFormats = new Uri[] { NameIdentifierFormats.X509SubjectName }, AssertionConsumerServices = new AssertionConsumerService[] { new AssertionConsumerService { Binding = ProtocolBindings.HttpPost, Location = new Uri(defaultSite, "Auth/AssertionConsumerService") } }, AttributeConsumingServices = new AttributeConsumingService[] { new AttributeConsumingService { ServiceName = new ServiceName("Some SP", "en"), RequestedAttributes = CreateRequestedAttributes() } }, }; entityDescriptor.ContactPersons = new[] { new ContactPerson(ContactTypes.Administrative) { Company = "Some Company", GivenName = "Some Given Name", SurName = "Some Sur Name", EmailAddress = "some@some-domain.com", TelephoneNumber = "11111111", }, new ContactPerson(ContactTypes.Technical) { Company = "Some Company", GivenName = "Some tech Given Name", SurName = "Some tech Sur Name", EmailAddress = "sometech@some-domain.com", TelephoneNumber = "22222222", } }; return new Saml2Metadata(entityDescriptor).CreateMetadata().ToActionResult(); } private IEnumerable<RequestedAttribute> CreateRequestedAttributes() { yield return new RequestedAttribute("urn:oid:2.5.4.4"); yield return new RequestedAttribute("urn:oid:2.5.4.3", false); } } }
41.53012
196
0.584856
[ "BSD-3-Clause" ]
ChrisWeaver1/ITfoxtec.Identity.Saml2
test/TestWebAppCoreFramework/Controllers/MetadataController.cs
3,449
C#
// CodeContracts // // 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. // File System.ServiceModel.Security.WindowsClientCredential.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.ServiceModel.Security { sealed public partial class WindowsClientCredential { #region Methods and constructors internal WindowsClientCredential() { } #endregion #region Properties and indexers public System.Security.Principal.TokenImpersonationLevel AllowedImpersonationLevel { get { return default(System.Security.Principal.TokenImpersonationLevel); } set { } } public bool AllowNtlm { get { return default(bool); } set { } } public System.Net.NetworkCredential ClientCredential { get { Contract.Ensures(Contract.Result<System.Net.NetworkCredential>() != null); return default(System.Net.NetworkCredential); } set { } } #endregion } }
32.954023
463
0.72759
[ "MIT" ]
Acidburn0zzz/CodeContracts
Microsoft.Research/Contracts/System.ServiceModel/Sources/System.ServiceModel.Security.WindowsClientCredential.cs
2,867
C#
using PcapDotNet.Base; namespace PcapDotNet.Packets.Ethernet { /// <summary> /// Represents an Ethernet layer. /// <seealso cref="EthernetDatagram"/> /// </summary> public sealed class EthernetLayer : EthernetBaseLayer { /// <summary> /// Creates an instance with zero values. /// </summary> public EthernetLayer() { Source = MacAddress.Zero; Destination = MacAddress.Zero; } /// <summary> /// Ethernet source address. /// </summary> public MacAddress Source { get; set; } /// <summary> /// Ethernet destination address. /// </summary> public MacAddress Destination { get; set; } /// <summary> /// The number of bytes this layer will take. /// </summary> public override int Length { get { return EthernetDatagram.HeaderLengthValue; } } /// <summary> /// Writes the layer to the buffer. /// </summary> /// <param name="buffer">The buffer to write the layer to.</param> /// <param name="offset">The offset in the buffer to start writing the layer at.</param> /// <param name="payloadLength">The length of the layer's payload (the number of bytes after the layer in the packet).</param> /// <param name="previousLayer">The layer that comes before this layer. null if this is the first layer.</param> /// <param name="nextLayer">The layer that comes after this layer. null if this is the last layer.</param> public override void Write(byte[] buffer, int offset, int payloadLength, ILayer previousLayer, ILayer nextLayer) { EthernetType etherType = GetEthernetType(EtherType, nextLayer); MacAddress destination = Destination; IEthernetNextLayer ethernetNextLayer = nextLayer as IEthernetNextLayer; if (destination == MacAddress.Zero) { if (ethernetNextLayer != null && ethernetNextLayer.PreviousLayerDefaultDestination != null) destination = ethernetNextLayer.PreviousLayerDefaultDestination.Value; } EthernetDatagram.WriteHeader(buffer, offset, Source, destination, etherType); } /// <summary> /// The kind of the data link of the layer. /// Can be null if this is not the first layer in the packet. /// </summary> public override DataLinkKind? DataLink { get { return DataLinkKind.Ethernet; } } /// <summary> /// Two Ethernet layers are equal if they have the same source, destination and ethernet type. /// </summary> public bool Equals(EthernetLayer other) { return other != null && Source == other.Source && Destination == other.Destination && EtherType == other.EtherType; } /// <summary> /// Two Ethernet layers are equal if they have the same source, destination and ethernet type. /// </summary> public override bool Equals(Layer other) { return Equals(other as EthernetLayer); } /// <summary> /// Returns a hash code for the layer. /// The hash code is a XOR of the hash codes of the layer length, data link, source and destination addresses and the ethernet type. /// </summary> public override int GetHashCode() { return base.GetHashCode() ^ Sequence.GetHashCode(Source, Destination, EtherType); } /// <summary> /// Contains the source, destination and ether type. /// </summary> /// <returns></returns> public override string ToString() { return Source + " -> " + Destination + " (" + EtherType + ")"; } } }
37.113208
140
0.578292
[ "BSD-3-Clause" ]
okaywang/MyPcap
PcapDotNet/src/PcapDotNet.Packets/Ethernet/EthernetLayer.cs
3,934
C#
using NSubstitute; using Serilog.Core; using Serilog.Events; using Serilog.Sinks.Firestore.Interfaces; using Serilog.Sinks.Firestore.Models; using Serilog.Sinks.TestCorrelator; using System; using System.Collections.Generic; using System.Linq; using Xunit; namespace Serilog.Sinks.Firestore.Tests { public class FirestoreSinkTests : IDisposable { private readonly IFormatProvider _subFormatProvider; private readonly IFirestoreApiClient _subFirestoreApiClient; private readonly Logger _testLogger; private readonly ITestCorrelatorContext _testContext; public FirestoreSinkTests() { _subFormatProvider = Substitute.For<IFormatProvider>(); _subFirestoreApiClient = Substitute.For<IFirestoreApiClient>(); _testLogger = new LoggerConfiguration().WriteTo.TestCorrelator().CreateLogger(); _testContext = TestCorrelator.TestCorrelator.CreateContext(); } private FirestoreSink CreateFirestoreSink() { return new FirestoreSink(_subFormatProvider, _subFirestoreApiClient, TimeSpan.FromSeconds(1), 1); } [Fact] public void ConvertLog_WithFlatLogProperty_ReturnsDictionary() { // Arrange var config = new FirestoreConfiguration("project", "logs"); _testLogger.Error("messageTemplate"); // Act var formatted = CreateFirestoreSink().ConvertLog(GetLastLogEvent()); // Assert Assert.NotNull(formatted); } [Fact] public void ConvertLog_WithNestedLogProperty_ReturnsDictionaryContainingExpectedValue() { // Arrange var config = new FirestoreConfiguration("project", "logs"); var nestedId = Guid.NewGuid(); var nestedObject = new { Name = "test", Nested = new { Bytes = new byte[8], Output = uint.MaxValue, Nested = new { Nested = new { Id = nestedId } } } }; _testLogger.Error("Processed {@nestedObject}", nestedObject); // Act var formatted = CreateFirestoreSink().ConvertLog(GetLastLogEvent()); var propertiesDictionary = formatted["Properties"] as IDictionary<string, string>; // Assert Assert.Contains(nestedId.ToString(), propertiesDictionary["nestedObject"].ToString()); } [Fact] public void ConvertLog_WithNullLogProperty_ReturnsDictionary() { // Arrange var config = new FirestoreConfiguration("project", "logs"); _testLogger.Error("Processed {@nestedObject}", null); // Act var formatted = CreateFirestoreSink().ConvertLog(GetLastLogEvent()); // Assert Assert.NotNull(formatted); } private LogEvent GetLastLogEvent() { return TestCorrelator.TestCorrelator.GetLogEventsFromContextGuid(_testContext.Guid).First(); } public void Dispose() { _testContext.Dispose(); } } }
33.879121
165
0.638015
[ "MIT" ]
kurtmkurtm/serilog-sinks-firestore
src/Serilog.Sinks.Firestore.Tests/FirestoreSinkTests.cs
3,083
C#
using System; using System.Collections.Generic; namespace Albert.Model { class Packages { public int Count { get; set; } public List<Package> Value { get; set; } } }
15.153846
48
0.614213
[ "MIT" ]
AlbertZhaohongyong/producetool
ProduceTools/Model/Packages.cs
199
C#
namespace dnlib.DotNet { /// <summary> /// Extension methods /// </summary> public static partial class Extensions { } }
16.555556
42
0.563758
[ "MIT" ]
Dekryptor/KoiVM-Virtualization
dnlib/src/DotNet/Extensions.cs
151
C#
using System; using Microsoft.Xna.Framework; namespace Alex.API.Utils { public struct BoundingCylinder : IEquatable<BoundingCylinder> { public Vector3 Min; public Vector3 Max; public double Radius; public BoundingCylinder(Vector3 min, Vector3 max, double radius) { Min = min; Max = max; Radius = radius; } public bool Intersects(Vector3 q) { return DistancePointLine(q, Min, Max) < Radius; } public bool Intersects(BoundingBox q) { var corners = q.GetCorners(); for (int i = 0; i < corners.Length; i++) { if (Intersects(corners[i])) return true; } return false; } // http://answers.unity3d.com/questions/62644/distance-between-a-ray-and-a-point.html public static double DistancePointLine(Vector3 point, Vector3 lineStart, Vector3 lineEnd) { return (ProjectPointLine(point, lineStart, lineEnd) - point).Length(); } public static Vector3 ProjectPointLine(Vector3 point, Vector3 lineStart, Vector3 lineEnd) { var rhs = point - lineStart; var vector2 = lineEnd - lineStart; var magnitude = vector2.Length(); var lhs = vector2; if (magnitude > 1E-06f) lhs = lhs / magnitude; var num2 = Vector3.Dot(lhs, rhs); if (num2 < 0) num2 = 0; if (num2 > magnitude) num2 = magnitude; return lineStart + (lhs * num2); } public bool Equals(BoundingCylinder other) { return other.Max == this.Max && other.Min == this.Min && other.Radius == this.Radius; } } }
22.938462
91
0.663984
[ "MPL-2.0" ]
TheBlackPlague/Alex
src/Alex.API/Utils/BoundingCylinder.cs
1,493
C#
// Generated by SharpKit.QooxDoo.Generator using System; using System.Collections.Generic; using SharpKit.Html; using SharpKit.JavaScript; namespace qx.fx.effect.core { /// <summary> /// <para>Core effect &#8220;Scroll&#8221;</para> /// <para>Scrolls to specified coordinates on given element.</para> /// </summary> [JsType(JsMode.Prototype, Name = "qx.fx.effect.core.Scroll", OmitOptionalParameters = true, Export = false)] public partial class Scroll : qx.fx.Base { #region Properties /// <summary> /// <para>String indicating if the coordinates are relative or absolute.</para> /// </summary> /// <remarks> /// Possible values: "relative","absolute" /// </remarks> [JsProperty(Name = "mode", NativeField = true)] public object Mode { get; set; } /// <summary> /// <para>X coordinate the element should be scroll to.</para> /// </summary> [JsProperty(Name = "x", NativeField = true)] public double X { get; set; } /// <summary> /// <para>Y coordinate the element should be scroll to.</para> /// </summary> [JsProperty(Name = "y", NativeField = true)] public double Y { get; set; } #endregion Properties #region Methods public Scroll() { throw new NotImplementedException(); } /// <summary> /// <para>Returns the (computed) value of the property mode.</para> /// </summary> [JsMethod(Name = "getMode")] public object GetMode() { throw new NotImplementedException(); } /// <summary> /// <para>Returns the (computed) value of the property x.</para> /// </summary> [JsMethod(Name = "getX")] public double GetX() { throw new NotImplementedException(); } /// <summary> /// <para>Returns the (computed) value of the property y.</para> /// </summary> [JsMethod(Name = "getY")] public double GetY() { throw new NotImplementedException(); } /// <summary> /// <para>Calls the apply method and dispatches the change event of the property mode /// with the default value defined by the class developer. This function can /// only be called from the constructor of a class.</para> /// </summary> /// <param name="value">Initial value for property mode.</param> [JsMethod(Name = "initMode")] public void InitMode(object value) { throw new NotImplementedException(); } /// <summary> /// <para>Calls the apply method and dispatches the change event of the property x /// with the default value defined by the class developer. This function can /// only be called from the constructor of a class.</para> /// </summary> /// <param name="value">Initial value for property x.</param> [JsMethod(Name = "initX")] public void InitX(object value) { throw new NotImplementedException(); } /// <summary> /// <para>Calls the apply method and dispatches the change event of the property y /// with the default value defined by the class developer. This function can /// only be called from the constructor of a class.</para> /// </summary> /// <param name="value">Initial value for property y.</param> [JsMethod(Name = "initY")] public void InitY(object value) { throw new NotImplementedException(); } /// <summary> /// <para>Resets the user value of the property mode.</para> /// <para>The computed value falls back to the next available value e.g. appearance, init or /// inheritance value depeneding on the property configuration and value availability.</para> /// </summary> [JsMethod(Name = "resetMode")] public void ResetMode() { throw new NotImplementedException(); } /// <summary> /// <para>Resets the user value of the property x.</para> /// <para>The computed value falls back to the next available value e.g. appearance, init or /// inheritance value depeneding on the property configuration and value availability.</para> /// </summary> [JsMethod(Name = "resetX")] public void ResetX() { throw new NotImplementedException(); } /// <summary> /// <para>Resets the user value of the property y.</para> /// <para>The computed value falls back to the next available value e.g. appearance, init or /// inheritance value depeneding on the property configuration and value availability.</para> /// </summary> [JsMethod(Name = "resetY")] public void ResetY() { throw new NotImplementedException(); } /// <summary> /// <para>Sets the user value of the property mode.</para> /// </summary> /// <param name="value">New value for property mode.</param> [JsMethod(Name = "setMode")] public void SetMode(object value) { throw new NotImplementedException(); } /// <summary> /// <para>Sets the user value of the property x.</para> /// </summary> /// <param name="value">New value for property x.</param> [JsMethod(Name = "setX")] public void SetX(double value) { throw new NotImplementedException(); } /// <summary> /// <para>Sets the user value of the property y.</para> /// </summary> /// <param name="value">New value for property y.</param> [JsMethod(Name = "setY")] public void SetY(double value) { throw new NotImplementedException(); } /// <summary> /// <para>Starts the effect</para> /// </summary> /// <returns>true if the effect was successfully started</returns> [JsMethod(Name = "start")] public bool Start() { throw new NotImplementedException(); } /// <summary> /// <para>This internal function is called /// each time the effect performs an /// step of the animation.</para> /// <para>Sub classes will overwrite this to /// perform the actual changes on element /// properties.</para> /// </summary> /// <param name="position">Animation setup as Number between 0 and 1.</param> [JsMethod(Name = "update")] public void Update(double position) { throw new NotImplementedException(); } #endregion Methods } }
36.961538
109
0.674471
[ "MIT" ]
SharpKit/SharpKit-SDK
Defs/Qooxdoo/fx/effect/core/Scroll.cs
5,766
C#
using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Corporate.Chat.Application.Interfaces; using Corporate.Chat.Domain.Interfaces.Model; using Corporate.Chat.Domain.Interfaces.Repositories; using Corporate.Chat.Domain.Pagination; namespace Corporate.Chat.Application { public class AppService<T> : IAppService<T> where T : class, IEntity { private readonly IRepository<T> repository; public AppService(IRepository<T> repository) { this.repository = repository; } public async Task<T> AddAsync(T entity, CancellationToken cancellationToken = default(CancellationToken)) { return await repository.AddAsync(entity, cancellationToken); } public bool Delete(T entity) { return repository.Delete(entity); } public bool Delete(int id) { return repository.Delete(id); } public Task<IEnumerable<T>> GetAllAsync(CancellationToken cancellationToken = default(CancellationToken)) { return repository.GetAllAsync(cancellationToken); } public Task<T> GetByIdAsync(int id) { return repository.GetByIdAsync(id); } public Task<PagedResult<T>> GetPagedAsync(int page, int pageSize, CancellationToken cancellationToken = default(CancellationToken)) { return repository.GetPagedAsync(page, pageSize, cancellationToken); } public Task<int> SaveChangesAsync(CancellationToken cancellationToken = default(CancellationToken)) { return repository.SaveChangesAsync(cancellationToken); } public T Update(T entity) { return repository.Update(entity); } } }
30.898305
139
0.657707
[ "MIT" ]
viniciusduartereis/Corporate-Chat
src/backend/Corporate.Chat.Application/AppService.cs
1,823
C#
using System.Collections.Generic; using Boleto2Net.Exceptions; using System.Web.UI; using System; [assembly: WebResource("Boleto2Net.Imagens.748.jpg", "image/jpg")] namespace Boleto2Net { internal sealed class BancoSicredi : IBanco { internal static Lazy<IBanco> Instance { get; } = new Lazy<IBanco>(() => new BancoSicredi()); public Cedente Cedente { get; set; } public int Codigo { get; } = 748; public string Nome { get; } = "Sicredi"; public string Digito { get; } = "X"; public List<string> IdsRetornoCnab400RegistroDetalhe { get; } = new List<string> { "1" }; public bool RemoveAcentosArquivoRemessa { get; } = true; public void FormataCedente() { var contaBancaria = Cedente.ContaBancaria; if (!CarteiraFactory<BancoSicredi>.CarteiraEstaImplementada(contaBancaria.CarteiraComVariacaoPadrao)) throw Boleto2NetException.CarteiraNaoImplementada(contaBancaria.CarteiraComVariacaoPadrao); contaBancaria.FormatarDados("PREFERENCIALMENTE EM CANAIS ELETRÔNICOS DA SUA INSTITUIÇÃO FINANCEIRA.", "", "", 9); Cedente.CodigoFormatado = $"{contaBancaria.Agencia}.{contaBancaria.OperacaoConta}.{Cedente.Codigo}"; } public string FormataCodigoBarraCampoLivre(Boleto boleto) { var carteira = CarteiraFactory<BancoSicredi>.ObterCarteira(boleto.CarteiraComVariacao); return carteira.FormataCodigoBarraCampoLivre(boleto); } public void FormataNossoNumero(Boleto boleto) { var carteira = CarteiraFactory<BancoSicredi>.ObterCarteira(boleto.CarteiraComVariacao); carteira.FormataNossoNumero(boleto); } public string FormatarNomeArquivoRemessa(int sequencial) { var agora = DateTime.Now; var mes = agora.Month.ToString(); if (mes == "10") mes = "O"; if (mes == "11") mes = "N"; if (mes == "12") mes = "D"; var dia = agora.Day.ToString().PadLeft(2, '0'); //Caso for gerado mais de um arquivo de remessa alterar a extensão do aquivo para "RM" + o contador do numero do arquivo de remessa gerado no dia var nomeArquivoRemessa = string.Format("{0}{1}{2}.{3}", Cedente.Codigo, mes, dia, sequencial > 1 ? $"RM{sequencial}" : "REM"); return nomeArquivoRemessa; } public string GerarDetalheRemessa(TipoArquivo tipoArquivo, Boleto boleto, ref int numeroRegistro) { try { //NAO INCREMENTAR AQUI PARA NAO AFETAR A SEQUENCIA DOS REGISTROS DO LOTE CNAB240 //numeroRegistro++; string _detalhe = " "; switch (tipoArquivo) { case TipoArquivo.CNAB400: _detalhe = GerarDetalheRemessaCNAB400(boleto, ref numeroRegistro, tipoArquivo); break; case TipoArquivo.CNAB240: // Segmento P (Obrigatório) _detalhe = GerarDetalheSegmentoPRemessaCNAB240(boleto, ref numeroRegistro); // Segmento Q (Obrigatório) _detalhe += Environment.NewLine; _detalhe += GerarDetalheSegmentoQRemessaCNAB240(boleto, ref numeroRegistro); // Segmento R (Opcional) var strline = GerarDetalheSegmentoRRemessaCNAB240(boleto, ref numeroRegistro); if (!String.IsNullOrWhiteSpace(strline)) { _detalhe += Environment.NewLine; _detalhe += strline; } // Segmento S (Opcional) strline = GerarDetalheSegmentoSRemessaCNAB240(boleto, ref numeroRegistro); if (!String.IsNullOrWhiteSpace(strline)) { _detalhe += Environment.NewLine; _detalhe += strline; } break; } return _detalhe; } catch (Exception ex) { throw new Exception("Erro durante a geração do DETALHE arquivo de REMESSA.", ex); } } public string GerarDetalheRemessaCNAB400(Boleto boleto, ref int numeroRegistro, TipoArquivo tipoArquivo) { //COM A INCLUSAO DO CNAB240 DEVEMOS INCREMENTAR AQUI DENTRO numeroRegistro++; string detalhe = string.Empty; //Redireciona para o Detalhe da remessa Conforme o "Tipo de Documento" = "Tipo de Cobrança do CNAB400": // A = 'A' - SICREDI com Registro // C1 = 'C' - SICREDI sem Registro Impressão Completa pelo Sicredi // C2 = 'C' - SICREDI sem Registro Pedido de bloquetos pré-impressos if (boleto.VariacaoCarteira.Equals("A")) detalhe = GerarDetalheRemessaCNAB400_A(boleto, numeroRegistro, tipoArquivo); else if (boleto.VariacaoCarteira.Equals("C1")) detalhe = GerarDetalheRemessaCNAB400_C1(boleto, numeroRegistro, tipoArquivo); else if (boleto.VariacaoCarteira.Equals("C2")) detalhe = GerarDetalheRemessaCNAB400_C2(boleto, numeroRegistro, tipoArquivo); return detalhe; } private string GerarDetalheRemessaCNAB400_A(Boleto boleto, int numeroRegistro, TipoArquivo tipoArquivo) { try { //string NumeroDocumento = boleto.NossoNumero; TRegistroEDI reg = new TRegistroEDI(); reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0001, 001, 0, "1", ' ')); //001-001 reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0002, 001, 0, "A", ' ')); //002-002 'A' - SICREDI com Registro reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0003, 001, 0, "A", ' ')); //003-003 'A' - Simples reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0004, 001, 0, "A", ' ')); //004-004 'A' – Normal reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0005, 012, 0, string.Empty, ' ')); //005-016 reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0017, 001, 0, "A", ' ')); //017-017 Tipo de moeda: 'A' - REAL reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0018, 001, 0, "A", ' ')); //018-018 Tipo de desconto: 'A' - VALOR reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0019, 001, 0, "B", ' ')); //019-019 Tipo de juros: 'A' - VALOR / 'B' - PERCENTUAL reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0020, 028, 0, string.Empty, ' ')); //020-047 reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediNumericoSemSeparador_, 0048, 009, 0, boleto.NossoNumero, '0')); //048-056 reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0057, 006, 0, string.Empty, ' ')); //057-062 reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediDataAAAAMMDD_________, 0063, 008, 0, boleto.DataProcessamento, ' ')); //063-070 reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0071, 001, 0, string.Empty, ' ')); //071-071 reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0072, 001, 0, 'N', ' ')); //072-072 'S' - Para postar o título diretamente ao pagador / 'N' - Não Postar e remeter para o beneficiário reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0073, 001, 0, string.Empty, ' ')); //073-073 switch (boleto.Banco.Cedente.ContaBancaria.TipoImpressaoBoleto) { case TipoImpressaoBoleto.Banco: reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0074, 001, 0, 'A', ' ')); //074-074 'A' - Impressão é feita pelo Sicredi break; case TipoImpressaoBoleto.Empresa: reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0074, 001, 0, 'B', ' ')); //'B' – Impressão é feita pelo Beneficiário break; } reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediNumericoSemSeparador_, 0075, 002, 0, 0, '0')); //075-076 reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediNumericoSemSeparador_, 0077, 002, 0, 0, '0')); //077-078 reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0079, 004, 0, string.Empty, ' ')); //079-082 reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediNumericoSemSeparador_, 0083, 010, 2, boleto.ValorDesconto, '0')); //083-092 reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediNumericoSemSeparador_, 0093, 004, 2, boleto.PercentualMulta, '0')); //093-096 reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0097, 012, 0, string.Empty, ' ')); //097-108 reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0109, 002, 0, "01", ' ')); //109-110 01 - Cadastro de título; reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0111, 010, 0, boleto.NumeroDocumento, ' ')); //111-120 reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediDataDDMMAA___________, 0121, 006, 0, boleto.DataVencimento, ' ')); //121-126 reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediNumericoSemSeparador_, 0127, 013, 2, boleto.ValorTitulo, '0')); //127-139 reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0140, 009, 0, string.Empty, ' ')); //140-148 reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0149, 001, 0, EspecieDocumentoSicredi(boleto.EspecieDocumento), ' ')); //149-149 reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0150, 001, 0, boleto.Aceite, ' ')); //150-150 reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediDataDDMMAA___________, 0151, 006, 0, boleto.DataProcessamento, ' ')); //151-156 //Instruções de protesto string vInstrucao1 = ""; string vInstrucao2 = ""; switch (boleto.CodigoProtesto) { case TipoCodigoProtesto.NaoProtestar: vInstrucao1 = "00"; vInstrucao2 = "0"; break; case TipoCodigoProtesto.ProtestarDiasCorridos: vInstrucao1 = "06"; vInstrucao2 = boleto.DiasProtesto.ToString(); break; } reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0157, 002, 0, vInstrucao1, '0')); //157-158 reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0159, 002, 0, vInstrucao2, '0')); //159-160 reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediNumericoSemSeparador_, 0161, 013, 2, boleto.PercentualJurosDia, '0')); //161-173 //DataDesconto string vDataDesconto = "000000"; if (!boleto.DataDesconto.Equals(DateTime.MinValue)) vDataDesconto = boleto.DataDesconto.ToString("ddMMyy"); reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0174, 006, 0, vDataDesconto, '0')); //174-179 reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediNumericoSemSeparador_, 0180, 013, 2, boleto.ValorDesconto, '0')); //180-192 reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediNumericoSemSeparador_, 0193, 013, 0, 0, '0')); //193-205 reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediNumericoSemSeparador_, 0206, 013, 2, boleto.ValorAbatimento, '0')); //206-218 //Regra Tipo de Inscrição Sacado string vCpfCnpjSac = "0"; if (boleto.Sacado.CPFCNPJ.Length.Equals(11)) vCpfCnpjSac = "1"; else if (boleto.Sacado.CPFCNPJ.Length.Equals(14)) vCpfCnpjSac = "2"; reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediNumericoSemSeparador_, 0219, 001, 0, vCpfCnpjSac, '0')); //219-219 reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0220, 001, 0, "0", '0')); //220-220 reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediNumericoSemSeparador_, 0221, 014, 0, boleto.Sacado.CPFCNPJ, '0')); //221-234 reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0235, 040, 0, boleto.Sacado.Nome.ToUpper(), ' ')); //235-274 reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0275, 040, 0, boleto.Sacado.Endereco.LogradouroEndereco.ToUpper(), ' ')); //275-314 reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediNumericoSemSeparador_, 0315, 005, 0, 0, '0')); //315-319 reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediNumericoSemSeparador_, 0320, 006, 0, 0, '0')); //320-325 reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediNumericoSemSeparador_, 0326, 001, 0, string.Empty, ' ')); //326-326 reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediNumericoSemSeparador_, 0327, 008, 0, boleto.Sacado.Endereco.CEP, '0')); //327-334 reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediNumericoSemSeparador_, 0335, 005, 1, 0, '0')); //335-339 reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0340, 014, 0, string.Empty, ' ')); //340-353 reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0354, 041, 0, string.Empty, ' ')); //354-394 reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediNumericoSemSeparador_, 0395, 006, 0, numeroRegistro, '0')); //395-400 reg.CodificarLinha(); string _detalhe = Utils.SubstituiCaracteresEspeciais(reg.LinhaRegistro); return _detalhe; } catch (Exception ex) { throw new Exception("Erro ao gerar DETALHE do arquivo CNAB400.", ex); } } private string EspecieDocumentoSicredi(TipoEspecieDocumento EspecieDocumento) { switch (EspecieDocumento) { case TipoEspecieDocumento.DM: case TipoEspecieDocumento.DMI: return "A"; case TipoEspecieDocumento.DR: return "B"; case TipoEspecieDocumento.NP: return "C"; case TipoEspecieDocumento.NPR: return "D"; case TipoEspecieDocumento.NS: return "E"; case TipoEspecieDocumento.RC: return "G"; case TipoEspecieDocumento.LC: return "H"; case TipoEspecieDocumento.DSI: return "J"; case TipoEspecieDocumento.OU: return "K"; } return string.Empty; } private string GerarDetalheRemessaCNAB400_C1(Boleto boleto, int numeroRegistro, TipoArquivo tipoArquivo) { throw new NotImplementedException("Função não implementada."); } private string GerarDetalheRemessaCNAB400_C2(Boleto boleto, int numeroRegistro, TipoArquivo tipoArquivo) { throw new NotImplementedException("Função não implementada."); } public string GerarHeaderRemessa(TipoArquivo tipoArquivo, int numeroArquivoRemessa, ref int numeroRegistro) { try { //NAO INCREMENTAR AQUI PARA NAO AFETAR A SEQUENCIA DOS REGISTROS DO LOTE CNAB240 //numeroRegistro++; string _header = " "; switch (tipoArquivo) { case TipoArquivo.CNAB400: _header = GerarHeaderRemessaCNAB400(numeroArquivoRemessa, ref numeroRegistro); break; case TipoArquivo.CNAB240: _header = GerarHeaderRemessaCNAB240(numeroArquivoRemessa, ref numeroRegistro); _header += Environment.NewLine; _header += GerarHeaderLoteRemessaCNAB240(numeroArquivoRemessa, ref numeroRegistro); break; default: throw new Exception("Scired - Header - Tipo de arquivo inexistente."); } return _header; } catch (Exception ex) { throw new Exception("Erro durante a geração do HEADER do arquivo de REMESSA.", ex); } } private string GerarHeaderRemessaCNAB400(int numeroArquivoRemessa, ref int numeroRegistroGeral) { try { //COM A INCLUSAO DO CNAB240 DEVEMOS INCREMENTAR AQUI DENTRO numeroRegistroGeral++; TRegistroEDI reg = new TRegistroEDI(); reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0001, 001, 0, "0", ' ')); //001-001 reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0002, 001, 0, "1", ' ')); //002-002 reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0003, 007, 0, "REMESSA", ' ')); //003-009 reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0010, 002, 0, "01", ' ')); //010-011 reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0012, 015, 0, "COBRANCA", ' ')); //012-026 reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0027, 005, 0, Cedente.Codigo, ' ')); //027-031 reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0032, 014, 0, Cedente.CPFCNPJ, ' ')); //032-045 reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0046, 031, 0, "", ' ')); //046-076 reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0077, 003, 0, "748", ' ')); //077-079 reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0080, 015, 0, "SICREDI", ' ')); //080-094 reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediDataAAAAMMDD_________, 0095, 008, 0, DateTime.Now, ' ')); //095-102 reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0103, 008, 0, "", ' ')); //103-110 reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediNumericoSemSeparador_, 0111, 007, 0, numeroArquivoRemessa.ToString(), '0')); //111-117 reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0118, 273, 0, "", ' ')); //118-390 reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0391, 004, 0, "2.00", ' ')); //391-394 reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediNumericoSemSeparador_, 0395, 006, 0, numeroRegistroGeral, '0')); //395-400 reg.CodificarLinha(); string vLinha = reg.LinhaRegistro; string _header = Utils.SubstituiCaracteresEspeciais(vLinha); return _header; } catch (Exception ex) { throw new Exception("Erro ao gerar HEADER do arquivo de remessa do CNAB400.", ex); } } public string GerarTrailerRemessa(TipoArquivo tipoArquivo, int numeroArquivoRemessa, ref int numeroRegistroGeral, decimal valorBoletoGeral, int numeroRegistroCobrancaSimples, decimal valorCobrancaSimples, int numeroRegistroCobrancaVinculada, decimal valorCobrancaVinculada, int numeroRegistroCobrancaCaucionada, decimal valorCobrancaCaucionada, int numeroRegistroCobrancaDescontada, decimal valorCobrancaDescontada) { try { //NAO INCREMENTAR AQUI PARA NAO AFETAR A SEQUENCIA DOS REGISTROS DO LOTE CNAB240 //numeroRegistroGeral++; string trailer = " "; switch (tipoArquivo) { case TipoArquivo.CNAB400: trailer = GerarTrailerRemessa400(ref numeroRegistroGeral); break; case TipoArquivo.CNAB240: // Trailler do Lote trailer = GerarTrailerLoteRemessaCNAC240(ref numeroRegistroGeral, numeroRegistroCobrancaSimples, valorCobrancaSimples, numeroRegistroCobrancaCaucionada, valorCobrancaCaucionada, numeroRegistroCobrancaDescontada, valorCobrancaDescontada); // Trailler do Arquivo trailer += Environment.NewLine; trailer += GerarTrailerRemessaCNAB240(ref numeroRegistroGeral); break; } return trailer; } catch (Exception ex) { throw new Exception("", ex); } } private string GerarTrailerRemessa400(ref int numeroRegistroGeral) { try { //COM A INCLUSAO DO CNAB240 DEVEMOS INCREMENTAR AQUI DENTRO numeroRegistroGeral++; TRegistroEDI reg = new TRegistroEDI(); reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0001, 001, 0, "9", ' ')); //001-001 reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0002, 001, 0, "1", ' ')); //002-002 reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0003, 003, 0, "748", ' ')); //003-006 reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0006, 005, 0, Cedente.Codigo, ' ')); //006-010 reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0011, 384, 0, string.Empty, ' ')); //011-394 reg.CamposEDI.Add(new TCampoRegistroEDI(TTiposDadoEDI.ediNumericoSemSeparador_, 0395, 006, 0, numeroRegistroGeral, '0')); //395-400 reg.CodificarLinha(); string vLinha = reg.LinhaRegistro; string _trailer = Utils.SubstituiCaracteresEspeciais(vLinha); return _trailer; } catch (Exception ex) { throw new Exception("Erro durante a geração do registro TRAILER do arquivo de REMESSA.", ex); } } public void LerDetalheRetornoCNAB400Segmento1(ref Boleto boleto, string registro) { try { // Identificação do Título no Banco boleto.NossoNumero = registro.Substring(47, 8); boleto.NossoNumeroDV = registro.Substring(55, 1); boleto.NossoNumeroFormatado = string.Format("{0}/{1}-{2}", boleto.NossoNumero.Substring(0, 2), boleto.NossoNumero.Substring(2, 6), boleto.NossoNumeroDV); // Identificação de Ocorrência boleto.CodigoOcorrencia = registro.Substring(108, 2); boleto.DescricaoOcorrencia = DescricaoOcorrenciaCnab400(boleto.CodigoOcorrencia); // Data Ocorrência no Banco boleto.DataProcessamento = Utils.ToDateTime(Utils.ToInt32(registro.Substring(110, 6)).ToString("##-##-##")); // Número do Documento boleto.NumeroDocumento = registro.Substring(116, 10).Trim(); // Seu número - Seu número enviado na Remessa boleto.NumeroControleParticipante = registro.Substring(116, 10).Trim(); //Data Vencimento do Título boleto.DataVencimento = Utils.ToDateTime(Utils.ToInt32(registro.Substring(146, 6)).ToString("##-##-##")); //Valores do Título boleto.ValorTitulo = Convert.ToDecimal(registro.Substring(152, 13)) / 100; boleto.ValorAbatimento = Convert.ToDecimal(registro.Substring(227, 13)) / 100; boleto.ValorDesconto = Convert.ToDecimal(registro.Substring(240, 13)) / 100; boleto.ValorPago = Convert.ToDecimal(registro.Substring(253, 13)) / 100; boleto.ValorJurosDia = Convert.ToDecimal(registro.Substring(266, 13)) / 100; boleto.ValorOutrosCreditos = Convert.ToDecimal(registro.Substring(279, 13)) / 100; boleto.ValorPago += boleto.ValorJurosDia; // Data do Crédito boleto.DataCredito = Utils.ToDateTime(Utils.ToInt32(registro.Substring(328, 8)).ToString("####-##-##")); // Identificação de Ocorrência - Código Auxiliar boleto.CodigoOcorrenciaAuxiliar = registro.Substring(381, 10); // Registro Retorno boleto.RegistroArquivoRetorno = boleto.RegistroArquivoRetorno + registro + Environment.NewLine; } catch (Exception ex) { throw new Exception("Erro ao ler detalhe do arquivo de RETORNO / CNAB 400.", ex); } } private string DescricaoOcorrenciaCnab400(string codigo) { switch (codigo) { case "02": return "Confirmação de entrada"; case "03": return "Entrada rejeitada"; case "04": return "Baixa de título liquidado por edital"; case "06": return "Liquidação normal"; case "07": return "Liquidação parcial"; case "08": return "Baixa por pagamento, liquidação pelo saldo"; case "09": return "Devolução automática"; case "10": return "Baixado conforme instruções"; case "11": return "Arquivo levantamento"; case "12": return "Concessão de abatimento"; case "13": return "Cancelamento de abatimento"; case "14": return "Vencimento alterado"; case "15": return "Pagamento em cartório"; case "16": return "Alteração de dados"; case "18": return "Alteração de instruções"; case "19": return "Confirmação de instrução protesto"; case "20": return "Confirmação de instrução para sustar protesto"; case "21": return "Aguardando autorização para protesto por edital"; case "22": return "Protesto sustado por alteração de vencimento e prazo de cartório"; case "23": return "Confirmação da entrada em cartório"; case "25": return "Devolução, liquidado anteriormente"; case "26": return "Devolvido pelo cartório – erro de informação"; case "30": return "Cobrança a creditar (liquidação em trânsito)"; case "31": return "Título em trânsito pago em cartório"; case "32": return "Reembolso e transferência Desconto e Vendor ou carteira em garantia"; case "33": return "Reembolso e devolução Desconto e Vendor"; case "34": return "Reembolso não efetuado por falta de saldo"; case "40": return "Baixa de títulos protestados"; case "41": return "Despesa de aponte"; case "42": return "Alteração de título"; case "43": return "Relação de títulos"; case "44": return "Manutenção mensal"; case "45": return "Sustação de cartório e envio de título a cartório"; case "46": return "Fornecimento de formulário pré-impresso"; case "47": return "Confirmação de entrada – Pagador DDA"; case "68": return "Acerto dos dados do rateio de crédito"; case "69": return "Cancelamento dos dados do rateio"; default: return ""; } } public void LerDetalheRetornoCNAB400Segmento7(ref Boleto boleto, string registro) { throw new NotImplementedException(); } public void LerHeaderRetornoCNAB400(ArquivoRetorno arquivoRetorno, string registro) { try { if (registro.Substring(0, 9) != "02RETORNO") throw new Exception("O arquivo não é do tipo \"02RETORNO\""); var dataStr = Utils.ToInt32(registro.Substring(94, 8)).ToString("####-##-##").Split('-'); var ano = Utils.ToInt32(dataStr[0]); var mes = Utils.ToInt32(dataStr[1]); var dia = Utils.ToInt32(dataStr[2]); //095 a 102 008 Data de gravação do arquivo AAAAMMDD arquivoRetorno.DataGeracao = new DateTime(ano, mes, dia); } catch (Exception ex) { throw new Exception("Erro ao ler HEADER do arquivo de RETORNO / CNAB 400.", ex); } } public void LerTrailerRetornoCNAB400(string registro) { } #region CNAB240 REMESSA private string GerarHeaderRemessaCNAB240(int numeroArquivoRemessa, ref int numeroRegistroGeral) { try { var reg = new TRegistroEDI(); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0001, 003, 0, "748", '0'); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0004, 004, 0, "0000", '0'); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0008, 001, 0, "0", '0'); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0009, 009, 0, String.Empty, ' '); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0018, 001, 0, Cedente.TipoCPFCNPJ("0"), '0'); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0019, 014, 0, Cedente.CPFCNPJ, '0'); //reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0033, 020, 0, Cedente.Codigo, '0'); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0033, 020, 0, String.Empty, ' '); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0053, 005, 0, Cedente.ContaBancaria.Agencia, '0'); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0058, 001, 0, String.Empty, ' '); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0059, 012, 0, Cedente.ContaBancaria.Conta, '0'); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0071, 001, 0, Cedente.ContaBancaria.DigitoConta, '0'); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0072, 001, 0, String.Empty, ' '); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0073, 030, 0, Cedente.Nome, ' '); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0103, 030, 0, "SICREDI", ' '); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0133, 010, 0, String.Empty, ' '); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0143, 001, 0, "1", '0'); var dt = DateTime.Now; reg.Adicionar(TTiposDadoEDI.ediDataDDMMAAAA_________, 0144, 008, 0, dt, ' '); reg.Adicionar(TTiposDadoEDI.ediHoraHHMMSS___________, 0152, 006, 0, dt, ' '); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0158, 006, 0, numeroArquivoRemessa, '0'); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0164, 003, 0, "081", '0'); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0167, 005, 0, "01600", '0'); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0172, 020, 0, String.Empty, ' '); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0192, 020, 0, String.Empty, ' '); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0212, 029, 0, String.Empty, ' '); reg.CodificarLinha(); return reg.LinhaRegistro; } catch (Exception ex) { throw new Exception("Erro ao gerar HEADER do arquivo de remessa do CNAB240.", ex); } } private string GerarHeaderLoteRemessaCNAB240(int numeroArquivoRemessa, ref int numeroRegistroGeral) { try { var reg = new TRegistroEDI(); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0001, 003, 0, "748", '0'); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0004, 004, 0, "0001", '0'); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0008, 001, 0, "1", '0'); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0009, 001, 0, "R", ' '); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0010, 002, 0, "01", '0'); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0012, 002, 0, String.Empty, ' '); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0014, 003, 0, "040", '0'); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0017, 001, 0, String.Empty, ' '); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0018, 001, 0, Cedente.TipoCPFCNPJ("0"), '0'); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0019, 015, 0, Cedente.CPFCNPJ, '0'); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0034, 020, 0, String.Empty, ' '); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0054, 005, 0, Cedente.ContaBancaria.Agencia, '0'); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0059, 001, 0, String.Empty, ' '); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0060, 012, 0, Cedente.ContaBancaria.Conta, '0'); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0072, 001, 0, Cedente.ContaBancaria.DigitoConta, '0'); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0073, 001, 0, String.Empty, ' '); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0074, 030, 0, Cedente.Nome, ' '); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0104, 040, 0, String.Empty, ' '); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0144, 040, 0, String.Empty, ' '); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0184, 008, 0, numeroArquivoRemessa, '0'); reg.Adicionar(TTiposDadoEDI.ediDataDDMMAAAA_________, 0192, 008, 0, DateTime.Now, ' '); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0200, 008, 0, 0, '0'); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0208, 033, 0, String.Empty, ' '); reg.CodificarLinha(); return reg.LinhaRegistro; } catch (Exception ex) { throw new Exception("Erro ao gerar HEADER do lote no arquivo de remessa do CNAB240.", ex); } } private string GerarDetalheSegmentoPRemessaCNAB240(Boleto boleto, ref int numeroRegistroGeral) { try { numeroRegistroGeral++; var reg = new TRegistroEDI(); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0001, 003, 0, "748", '0'); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0004, 004, 0, "0001", '0'); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0008, 001, 0, "3", '0'); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0009, 005, 0, numeroRegistroGeral, '0'); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0014, 001, 0, "P", '0'); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0015, 001, 0, String.Empty, ' '); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0016, 002, 0, boleto.CodigoOcorrencia, ' '); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0018, 005, 0, boleto.Banco.Cedente.ContaBancaria.Agencia, '0'); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0023, 001, 0, String.Empty, ' '); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0024, 012, 0, boleto.Banco.Cedente.ContaBancaria.Conta, '0'); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0036, 001, 0, boleto.Banco.Cedente.ContaBancaria.DigitoConta, ' '); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0037, 001, 0, String.Empty, ' '); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0038, 020, 0, boleto.NossoNumero, ' '); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0058, 001, 0, "1", ' '); var comRegistro = boleto.Banco.Cedente.ContaBancaria.TipoFormaCadastramento == TipoFormaCadastramento.ComRegistro; reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 059, 001, 0, comRegistro ? "1" : "2", '0'); var docTradicional = boleto.Banco.Cedente.ContaBancaria.TipoDocumento == TipoDocumento.Tradicional; reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0060, 001, 0, docTradicional ? "1" : "2", ' '); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0061, 001, 0, "2", ' '); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0062, 001, 0, "2", ' '); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0063, 015, 0, boleto.NumeroDocumento, ' '); reg.Adicionar(TTiposDadoEDI.ediDataDDMMAAAA_________, 0078, 008, 0, boleto.DataVencimento, ' '); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0086, 015, 2, boleto.ValorTitulo, '0'); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0101, 005, 0, "0", '0'); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0106, 001, 0, String.Empty, ' '); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0107, 002, 0, (int)boleto.EspecieDocumento, '0'); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0109, 001, 0, boleto.Aceite, ' '); reg.Adicionar(TTiposDadoEDI.ediDataDDMMAAAA_________, 0110, 008, 0, boleto.DataEmissao, '0'); if (boleto.ValorJurosDia == 0) { // Sem Juros Mora reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0118, 001, 2, "3", '0'); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0119, 008, 0, "0", '0'); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0127, 015, 2, 0, '0'); } else { // Com Juros Mora ($) reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0118, 001, 2, "1", '0'); reg.Adicionar(TTiposDadoEDI.ediDataDDMMAAAA_________, 0119, 008, 0, boleto.DataJuros, '0'); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0127, 015, 2, boleto.ValorJurosDia, '0'); } if (boleto.ValorDesconto == 0) { // Sem Desconto reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0142, 001, 0, "0", '0'); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0143, 008, 0, "0", '0'); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0151, 015, 2, "0", '0'); } else { // Com Desconto reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0142, 001, 0, "1", '0'); reg.Adicionar(TTiposDadoEDI.ediDataDDMMAAAA_________, 0143, 008, 0, boleto.DataDesconto, '0'); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0151, 015, 2, boleto.ValorDesconto, '0'); } reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0166, 015, 2, boleto.ValorIOF, '0'); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0181, 015, 2, boleto.ValorAbatimento, '0'); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0196, 025, 0, String.Empty, ' '); switch (boleto.CodigoProtesto) { case TipoCodigoProtesto.ProtestarDiasCorridos: reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0221, 001, 0, 1, '0'); break; //case TipoCodigoProtesto.NaoProtestar: // reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0221, 001, 0, 3, '0'); // break; case TipoCodigoProtesto.NegativacaoSemProtesto: reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0221, 001, 0, 8, '0'); break; case TipoCodigoProtesto.CancelamentoProtestoAutomatico: reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0221, 001, 0, 9, '0'); break; default: //NAO PROTESTAR reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0221, 001, 0, 3, '0'); break; } reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0222, 002, 0, boleto.DiasProtesto, '0'); //A DOCUMENTACAO MANDA UTILIZAR SEMPRE O VALOR 1 - BAIXAR/DEVOLVER reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0224, 001, 0, 1, '0'); //A DOCUMENTACAO MANDA UTILIZAR SEMPRE O VALOR '060' - 60 DIAS reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0225, 003, 0, "060", '0'); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0228, 002, 0, "09", '0'); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0230, 010, 0, 0, '0'); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0240, 001, 0, String.Empty, ' '); reg.CodificarLinha(); var vLinha = reg.LinhaRegistro; return vLinha; } catch (Exception ex) { throw new Exception("Erro ao gerar DETALHE do Segmento P no arquivo de remessa do CNAB240.", ex); } } private string GerarDetalheSegmentoQRemessaCNAB240(Boleto boleto, ref int numeroRegistroGeral) { try { numeroRegistroGeral++; var reg = new TRegistroEDI(); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0001, 003, 0, "748", '0'); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0004, 004, 0, "0001", '0'); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0008, 001, 0, "3", '0'); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0009, 005, 0, numeroRegistroGeral, '0'); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0014, 001, 0, "Q", '0'); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0015, 001, 0, String.Empty, ' '); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0016, 002, 0, boleto.CodigoOcorrencia, '0'); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0018, 001, 0, boleto.Sacado.TipoCPFCNPJ("0"), '0'); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0019, 015, 0, boleto.Sacado.CPFCNPJ, '0'); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0034, 040, 0, boleto.Sacado.Nome, ' '); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0074, 040, 0, boleto.Sacado.Endereco.FormataLogradouro(40), ' '); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0114, 015, 0, boleto.Sacado.Endereco.Bairro, ' '); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0129, 008, 0, boleto.Sacado.Endereco.CEP.Replace("-", ""), ' '); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0137, 015, 0, boleto.Sacado.Endereco.Cidade, ' '); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0152, 002, 0, boleto.Sacado.Endereco.UF, ' '); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0154, 001, 0, boleto.Avalista.TipoCPFCNPJ("0"), '0'); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0155, 015, 0, boleto.Avalista.CPFCNPJ, '0'); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0170, 040, 0, boleto.Avalista.Nome, ' '); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0210, 003, 0, "0", '0'); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0213, 020, 0, String.Empty, ' '); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0233, 008, 0, String.Empty, ' '); reg.CodificarLinha(); var vLinha = reg.LinhaRegistro; return vLinha; } catch (Exception ex) { throw new Exception("Erro ao gerar DETALHE do Segmento Q no arquivo de remessa do CNAB240.", ex); } } private string GerarDetalheSegmentoRRemessaCNAB240(Boleto boleto, ref int numeroRegistroGeral) { try { //string codMulta; //if (boleto.ValorMulta > 0) // codMulta = "1"; //else // codMulta = "0"; var msg = boleto.MensagemArquivoRemessa.PadRight(500, ' '); var msg3 = msg.Substring(00, 40).FitStringLength(40, ' '); var msg4 = msg.Substring(40, 40).FitStringLength(40, ' '); if ((boleto.PercentualMulta == 0) & String.IsNullOrWhiteSpace(msg3) & String.IsNullOrWhiteSpace(msg4)) return ""; numeroRegistroGeral++; var reg = new TRegistroEDI(); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0001, 003, 0, "748", '0'); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0004, 004, 0, "0001", '0'); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0008, 001, 0, "3", '0'); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0009, 005, 0, numeroRegistroGeral, '0'); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0014, 001, 0, "R", '0'); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0015, 001, 0, String.Empty, ' '); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0016, 002, 0, boleto.CodigoOcorrencia, '0'); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0018, 001, 0, "0", '0'); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0019, 008, 0, "0", '0'); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0027, 015, 0, "0", '0'); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0042, 001, 0, "0", '0'); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0043, 008, 0, "0", '0'); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0051, 015, 0, "0", '0'); //NA DOCUMENTACAO APENAS É PREVISTO O CÓDIGO DE MULTA 2 - PERCENTUAL reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0066, 001, 0, "2", '0'); if (boleto.PercentualMulta > 0) { reg.Adicionar(TTiposDadoEDI.ediDataDDMMAAAA_________, 0067, 008, 0, boleto.DataMulta, '0'); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0075, 015, 2, boleto.PercentualMulta, '0'); } else { reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0067, 008, 0, 0, '0'); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0075, 015, 0, 0, '0'); } reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0090, 010, 0, String.Empty, ' '); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0100, 040, 0, msg3, ' '); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0140, 040, 0, msg4, ' '); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0180, 020, 0, String.Empty, ' '); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0200, 008, 0, 0, '0'); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0208, 003, 0, 0, '0'); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0211, 005, 0, 0, '0'); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0216, 001, 0, String.Empty, ' '); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0217, 012, 0, 0, '0'); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0229, 001, 0, String.Empty, ' '); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0230, 001, 0, String.Empty, ' '); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0231, 001, 0, 0, '0'); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0232, 009, 0, String.Empty, ' '); reg.CodificarLinha(); var vLinha = reg.LinhaRegistro; return vLinha; } catch (Exception ex) { throw new Exception("Erro ao gerar DETALHE do Segmento R no arquivo de remessa do CNAB240.", ex); } } private string GerarDetalheSegmentoSRemessaCNAB240(Boleto boleto, ref int numeroRegistroGeral) { try { var informativo = boleto.MensagemArquivoRemessa.PadRight(500, ' ').Substring(80, 200); if (String.IsNullOrWhiteSpace(informativo)) return ""; numeroRegistroGeral++; var reg = new TRegistroEDI(); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0001, 003, 0, "748", '0'); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0004, 004, 0, "0001", '0'); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0008, 001, 0, "3", '0'); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0009, 005, 0, numeroRegistroGeral, '0'); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0014, 001, 0, "S", '0'); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0015, 001, 0, String.Empty, ' '); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0016, 002, 0, boleto.CodigoOcorrencia, '0'); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0018, 001, 0, "3", '0'); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0019, 120, 0, informativo, ' '); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0139, 040, 0, String.Empty, ' '); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0179, 040, 0, String.Empty, ' '); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0219, 022, 0, String.Empty, ' '); reg.CodificarLinha(); return reg.LinhaRegistro; } catch (Exception ex) { throw new Exception("Erro ao gerar DETALHE do Segmento S no arquivo de remessa do CNAB240.", ex); } } private string GerarTrailerLoteRemessaCNAC240(ref int numeroRegistroGeral, int numeroRegistroCobrancaSimples, decimal valorCobrancaSimples, int numeroRegistroCobrancaCaucionada, decimal valorCobrancaCaucionada, int numeroRegistroCobrancaDescontada, decimal valorCobrancaDescontada) { try { // O número de registros no lote é igual ao número de registros gerados + 2 (header e trailler do lote) var numeroRegistrosNoLote = numeroRegistroGeral + 2; var reg = new TRegistroEDI(); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0001, 003, 0, "748", '0'); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0004, 004, 0, "0001", '0'); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0008, 001, 0, "5", '0'); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0009, 009, 0, String.Empty, ' '); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0018, 006, 0, numeroRegistrosNoLote, '0'); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0024, 006, 0, "0", '0'); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0030, 017, 0, "0", '0'); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0047, 006, 0, "0", '0'); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0053, 017, 0, "0", '0'); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0070, 006, 0, "0", '0'); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0076, 017, 0, "0", '0'); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0093, 006, 0, "0", '0'); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0099, 017, 0, "0", '0'); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0116, 008, 0, String.Empty, ' '); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0124, 117, 0, String.Empty, ' '); reg.CodificarLinha(); return reg.LinhaRegistro; } catch (Exception ex) { throw new Exception("Erro ao gerar HEADER do lote no arquivo de remessa do CNAB400.", ex); } } private string GerarTrailerRemessaCNAB240(ref int numeroRegistroGeral) { try { // O número de registros no arquivo é igual ao número de registros gerados + 4 (header e trailler do lote / header e trailler do arquivo) var numeroRegistrosNoArquivo = numeroRegistroGeral + 4; var reg = new TRegistroEDI(); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0001, 003, 0, "748", '0'); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0004, 004, 0, "9999", '0'); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0008, 001, 0, "9", '0'); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0009, 009, 0, String.Empty, ' '); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0018, 006, 0, "1", '0'); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0024, 006, 0, numeroRegistrosNoArquivo, '0'); reg.Adicionar(TTiposDadoEDI.ediNumericoSemSeparador_, 0030, 006, 0, 0, '0'); reg.Adicionar(TTiposDadoEDI.ediAlphaAliEsquerda_____, 0036, 205, 0, String.Empty, ' '); reg.CodificarLinha(); return reg.LinhaRegistro; } catch (Exception ex) { throw new Exception("Erro ao gerar HEADER do arquivo de remessa do CNAB400.", ex); } } #endregion #region CNAB240 RETORNO public void LerHeaderRetornoCNAB240(ArquivoRetorno arquivoRetorno, string registro) { arquivoRetorno.Banco.Cedente = new Cedente(); arquivoRetorno.Banco.Cedente.CPFCNPJ = registro.Substring(17, 1) == "1" ? registro.Substring(21, 11) : registro.Substring(18, 14); //Código do convêncio no banco - segundo o manual este campo estará vazio('Brancos') //arquivoRetorno.Banco.Cedente.Codigo = registro.Substring(32, 20); //Conta corrente do Beneficiário - o suporte sicredi disse na época que o código do convêncio é sempre igual ao código da conta corrente //arquivoRetorno.Banco.Cedente.Codigo = registro.Substring(58, 12); arquivoRetorno.Banco.Cedente.Nome = registro.Substring(72, 30).Trim(); arquivoRetorno.Banco.Cedente.ContaBancaria = new ContaBancaria(); arquivoRetorno.Banco.Cedente.ContaBancaria.Agencia = registro.Substring(52, 5); arquivoRetorno.Banco.Cedente.ContaBancaria.Conta = registro.Substring(58, 12); arquivoRetorno.Banco.Cedente.ContaBancaria.DigitoConta = registro.Substring(70, 1); arquivoRetorno.DataGeracao = Utils.ToDateTime(Utils.ToInt32(registro.Substring(143, 8)).ToString("##-##-####")); arquivoRetorno.NumeroSequencial = Utils.ToInt32(registro.Substring(157, 6)); } public void LerDetalheRetornoCNAB240SegmentoT(ref Boleto boleto, string registro) { try { //Identificação do título na Empresa boleto.NumeroControleParticipante = registro.Substring(105, 25); //Código da carteira boleto.Carteira = registro.Substring(57, 1); switch (boleto.Carteira) { case "2": boleto.TipoCarteira = TipoCarteira.CarteiraCobrancaVinculada; break; case "3": boleto.TipoCarteira = TipoCarteira.CarteiraCobrancaCaucionada; break; case "4": boleto.TipoCarteira = TipoCarteira.CarteiraCobrancaDescontada; break; default: boleto.TipoCarteira = TipoCarteira.CarteiraCobrancaSimples; break; } //Identificação do título boleto.NossoNumero = registro.Substring(37, 8); boleto.NossoNumeroDV = registro.Substring(45, 1); boleto.NossoNumeroFormatado = String.Format("{0}/{1}-{2}", boleto.NossoNumero.Substring(0, 2), boleto.NossoNumero.Substring(2, 6), boleto.NossoNumeroDV); //Código de movimento retorno boleto.CodigoOcorrencia = registro.Substring(15, 2); boleto.DescricaoOcorrencia = Cnab.OcorrenciaCnab240(boleto.CodigoOcorrencia); boleto.CodigoOcorrenciaAuxiliar = registro.Substring(213, 10); //Nº do documento de cobrança boleto.NumeroDocumento = registro.Substring(58, 15); boleto.EspecieDocumento = TipoEspecieDocumento.NaoDefinido; //Valor nominal do título boleto.ValorTitulo = Convert.ToDecimal(registro.Substring(81, 15)) / 100; //Data do vencimento do título boleto.DataVencimento = Utils.ToDateTime(Utils.ToInt32(registro.Substring(73, 8)).ToString("##-##-####")); //Nº do Banco Cobrador / Recebedor boleto.BancoCobradorRecebedor = registro.Substring(96, 3); //100 – 104 Cooperativa/agência cobradora/recebedora //105 – 105 Dígito verificador da cooperativa/agência boleto.AgenciaCobradoraRecebedora = registro.Substring(99, 6); //Pagador - Número de inscrição boleto.Sacado = new Sacado(); boleto.Sacado.CPFCNPJ = registro.Substring(134, 14); //Pagador - Nome boleto.Sacado.Nome = registro.Substring(148, 40); //Valor da tarifa/custas boleto.ValorTarifas = Convert.ToDecimal(registro.Substring(198, 15)) / 100; // Registro Retorno boleto.RegistroArquivoRetorno = boleto.RegistroArquivoRetorno + registro + Environment.NewLine; } catch (Exception ex) { throw new Exception("Erro ao ler detalhe do arquivo de RETORNO / CNAB 240 / T.", ex); } } public void LerDetalheRetornoCNAB240SegmentoU(ref Boleto boleto, string registro) { try { //Juros/multa/encargos boleto.ValorJurosDia = Convert.ToDecimal(registro.Substring(17, 15)) / 100; //Valor do desconto concedido boleto.ValorDesconto = Convert.ToDecimal(registro.Substring(32, 15)) / 100; //Valor do abat. concedido/cancel. boleto.ValorAbatimento = Convert.ToDecimal(registro.Substring(47, 15)) / 100; //Valor do IOF recolhido boleto.ValorIOF = Convert.ToDecimal(registro.Substring(62, 15)) / 100; //Valor pago pelo pagador boleto.ValorPago = Convert.ToDecimal(registro.Substring(77, 15)) / 100; //Valor liquido a ser creditado boleto.ValorPagoCredito = Convert.ToDecimal(registro.Substring(92, 15)) / 100; //Valor de outras despesas boleto.ValorOutrasDespesas = Convert.ToDecimal(registro.Substring(107, 15)) / 100; //Valor de outros créditos boleto.ValorOutrosCreditos = Convert.ToDecimal(registro.Substring(122, 15)) / 100; //Data da ocorrência boleto.DataProcessamento = Utils.ToDateTime(Utils.ToInt32(registro.Substring(137, 8)).ToString("##-##-####")); //Data da efetivação do crédito boleto.DataCredito = Utils.ToDateTime(Utils.ToInt32(registro.Substring(145, 8)).ToString("##-##-####")); //Registro Retorno boleto.RegistroArquivoRetorno = boleto.RegistroArquivoRetorno + registro + Environment.NewLine; } catch (Exception ex) { throw new Exception("Erro ao ler detalhe do arquivo de RETORNO / CNAB 240 / U.", ex); } } #endregion public void ValidaBoleto(Boleto boleto) { switch (boleto.EspecieDocumento) { case TipoEspecieDocumento.DMI: case TipoEspecieDocumento.DR: case TipoEspecieDocumento.NP: case TipoEspecieDocumento.NPR: case TipoEspecieDocumento.NS: case TipoEspecieDocumento.RC: case TipoEspecieDocumento.LC: case TipoEspecieDocumento.ND: case TipoEspecieDocumento.DSI: case TipoEspecieDocumento.OU: break; //TIPOS POSSÍVEIS DE ACORDO COM A DOCUMENTAÇÃO DO SICREDI default: throw new Exception($"Especie de documento: {boleto.EspecieDocumento} inválida para o banco {Nome}."); } if (boleto.Sacado.Endereco == null) { throw new Exception("O endereço do sacado não foi informado."); } if (string.IsNullOrEmpty(boleto.Sacado.Endereco.LogradouroEndereco)) { throw new Exception("O logradouro do sacado não foi informado."); } if (string.IsNullOrEmpty(boleto.Sacado.Endereco.LogradouroNumero)) { throw new Exception("O número do logradouro do sacado não foi informado."); } if (string.IsNullOrEmpty(boleto.Sacado.Endereco.Bairro)) { throw new Exception("O bairro do sacado não foi informado."); } if (string.IsNullOrEmpty(boleto.Sacado.Endereco.UF)) { throw new Exception("A UF do sacado não foi informada."); } if (string.IsNullOrEmpty(boleto.Sacado.Endereco.Cidade)) { throw new Exception("A cidade do sacado não foi informada."); } if (string.IsNullOrEmpty(boleto.Sacado.Endereco.CEP)) { throw new Exception("O CEP do sacado não foi informado."); } } } }
59.220601
423
0.570892
[ "Apache-2.0" ]
BoletoNet/boleto2net
Boleto2.Net/Banco/BancoSicredi.cs
69,188
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.Gcp.Compute.Outputs { [OutputType] public sealed class RegionUrlMapTest { /// <summary> /// Description of this test case. /// </summary> public readonly string? Description; /// <summary> /// Host portion of the URL. /// </summary> public readonly string Host; /// <summary> /// Path portion of the URL. /// </summary> public readonly string Path; /// <summary> /// A reference to expected RegionBackendService resource the given URL should be mapped to. /// </summary> public readonly string Service; [OutputConstructor] private RegionUrlMapTest( string? description, string host, string path, string service) { Description = description; Host = host; Path = path; Service = service; } } }
26.02
100
0.579554
[ "ECL-2.0", "Apache-2.0" ]
dimpu47/pulumi-gcp
sdk/dotnet/Compute/Outputs/RegionUrlMapTest.cs
1,301
C#