content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Allgemeine Informationen über eine Assembly werden über die folgenden // Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern, // die einer Assembly zugeordnet sind. [assembly: AssemblyTitle("ConsoleApp1")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ConsoleApp1")] [assembly: AssemblyCopyright("Copyright © 2021")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Durch Festlegen von ComVisible auf FALSE werden die Typen in dieser Assembly // für COM-Komponenten unsichtbar. Wenn Sie auf einen Typ in dieser Assembly von // COM aus zugreifen müssen, sollten Sie das ComVisible-Attribut für diesen Typ auf "True" festlegen. [assembly: ComVisible(false)] // Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird [assembly: Guid("31cbba5d-5535-41ef-aaa9-161dce03103f")] // Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten: // // Hauptversion // Nebenversion // Buildnummer // Revision // // Sie können alle Werte angeben oder Standardwerte für die Build- und Revisionsnummern verwenden, // indem Sie "*" wie unten gezeigt eingeben: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
40.702703
106
0.764276
[ "MIT" ]
timwurbs/HSP-Gruppe-F
ConsoleApp1/Properties/AssemblyInfo.cs
1,521
C#
using FlyingRat.Captcha; using FlyingRat.Captcha.Configuration; using FlyingRat.Captcha.Context; using FlyingRat.Captcha.Extensions; using FlyingRat.Captcha.Interface; using FlyingRat.Captcha.Validator; using FlyingRat.Captcha.ViewModel; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Caching.Memory; using SixLabors.ImageSharp; using System; using System.IO; using System.Threading.Tasks; namespace Captcha.Controllers { public class ImageController : Controller { private readonly IImageProvider _imageProvider; private readonly ImageDriver _imageHandler; private readonly IMemoryCache _memoryCache; private readonly ICaptchaManager _captchaManager; private static readonly string cacheKey = "image_catpture"; public ImageController(ImageDriver handler, IImageProvider imageFileProvider, ICaptchaManager captchaManager, IMemoryCache cache) { _imageHandler = handler; _imageProvider = imageFileProvider; _memoryCache = cache; _captchaManager = captchaManager; } public IActionResult Index() { return View(); } public async ValueTask<IActionResult> RandImage(string type= "SliderCatpcha", int? row = 2, int? col = 13) { var captcha =await _captchaManager.Captcha(type, new BaseCaptchaOptions() { Col=col.Value,Row=row.Value,Validate_Max=2}); var model = captcha.ToViewModel(Url.Action("Validate"),hasBackground:true); //model.BgGap = Url.Action("SliderBackground"); //model.Full = Url.Action("Background"); //model.Gap = Url.Action("Slider"); _memoryCache.Set(cacheKey + model.Tk, captcha.ToCacheModel(), DateTimeOffset.Now.AddMinutes(5)); return Json(model); } public IActionResult Background(string tk) { var data = _memoryCache.Get<CaptchaCacheModel>(cacheKey + tk); if (data == null) return File(new byte[1], "image/jpeg"); using MemoryStream ms = new MemoryStream(); data.Backgorund.SaveAsJpeg(ms); return File(ms.ToArray(), "image/jpeg"); } public IActionResult SliderBackground(string tk) { var data = _memoryCache.Get<CaptchaCacheModel>(cacheKey + tk); if (data == null) return File(new byte[1], "image/jpeg"); using MemoryStream ms = new MemoryStream(); data.GapBackground.SaveAsJpeg(ms); return File(ms.ToArray(), "image/jpeg"); } public IActionResult Slider(string tk) { var data = _memoryCache.Get<CaptchaCacheModel>(cacheKey + tk); if (data == null) return File(new byte[1], "image/png"); using MemoryStream ms = new MemoryStream(); data.Gap.SaveAsPng(ms); return File(ms.ToArray(), "image/png"); } public async ValueTask<IActionResult> Validate([FromBody]CaptchaVerifyModel model) { if (model == null) return Json(ValidateResult.Failed); var data = _memoryCache.Get<CaptchaCacheModel>(cacheKey + model.TK); if (data == null) return Json(ValidateResult.Failed); var context = new CaptchaValidateContext(new ValidateModel(data.Points), model.ToValidateModel(),data.Validate); data.Validate =await _captchaManager.Validate(data.Name, context,data.Options); return Json(data.Validate?.ToViewModel()); } } }
41.72093
133
0.643255
[ "MIT" ]
cqkisyouq/FlyingRat.Captcha
test/captcha/Controllers/ImageController.cs
3,590
C#
// Copyright M. Griffie <nexus@nexussays.com> // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. using System; using nexus.core; using NUnit.Framework; // ReSharper disable InvokeAsExtensionMethod namespace nexus.core_test { [TestFixture] internal partial class BytesTest { [TestCase( ByteOrder.LittleEndian, 0, ExpectedResult = new Byte[] {0, 0} )] [TestCase( ByteOrder.LittleEndian, 256, ExpectedResult = new Byte[] {0, 1} )] [TestCase( ByteOrder.LittleEndian, 1, ExpectedResult = new Byte[] {1, 0} )] [TestCase( ByteOrder.LittleEndian, Int16.MinValue, ExpectedResult = new Byte[] {0, 128} )] [TestCase( ByteOrder.LittleEndian, 128, ExpectedResult = new Byte[] {128, 0} )] [TestCase( ByteOrder.LittleEndian, -256, ExpectedResult = new Byte[] {0, 255} )] [TestCase( ByteOrder.LittleEndian, 255, ExpectedResult = new Byte[] {255, 0} )] [TestCase( ByteOrder.LittleEndian, Int16.MaxValue, ExpectedResult = new Byte[] {255, 127} )] [TestCase( ByteOrder.LittleEndian, Int16.MinValue + 255, ExpectedResult = new Byte[] {255, 128} )] [TestCase( ByteOrder.LittleEndian, -1, ExpectedResult = new Byte[] {255, 255} )] [TestCase( ByteOrder.BigEndian, 0, ExpectedResult = new Byte[] {0, 0} )] [TestCase( ByteOrder.BigEndian, 1, ExpectedResult = new Byte[] {0, 1} )] [TestCase( ByteOrder.BigEndian, 256, ExpectedResult = new Byte[] {1, 0} )] [TestCase( ByteOrder.BigEndian, 128, ExpectedResult = new Byte[] {0, 128} )] [TestCase( ByteOrder.BigEndian, Int16.MinValue, ExpectedResult = new Byte[] {128, 0} )] [TestCase( ByteOrder.BigEndian, 255, ExpectedResult = new Byte[] {0, 255} )] [TestCase( ByteOrder.BigEndian, -256, ExpectedResult = new Byte[] {255, 0} )] [TestCase( ByteOrder.BigEndian, Int16.MaxValue, ExpectedResult = new Byte[] {127, 255} )] [TestCase( ByteOrder.BigEndian, Int16.MinValue + 255, ExpectedResult = new Byte[] {128, 255} )] [TestCase( ByteOrder.BigEndian, -1, ExpectedResult = new Byte[] {255, 255} )] [TestCase( ByteOrder.BigEndian, 0, ExpectedResult = new Byte[] {0, 0} )] public Byte[] to_bytes_correctly_converts_int16( ByteOrder order, Int16 value ) { return Bytes.ToBytes( value, order ); } [TestCase( ByteOrder.LittleEndian, new Byte[] {0, 0, 0, 0}, 0 )] [TestCase( ByteOrder.LittleEndian, new Byte[] {0, 1, 0, 0}, 256 )] [TestCase( ByteOrder.LittleEndian, new Byte[] {1, 0, 0, 0}, 1 )] [TestCase( ByteOrder.LittleEndian, new Byte[] {0, 0, 0, 128}, Int32.MinValue )] [TestCase( ByteOrder.LittleEndian, new Byte[] {128, 0, 0, 0}, 128 )] [TestCase( ByteOrder.LittleEndian, new Byte[] {255, 0, 0, 0}, 255 )] [TestCase( ByteOrder.LittleEndian, new Byte[] {255, 255, 255, 127}, Int32.MaxValue )] [TestCase( ByteOrder.LittleEndian, new Byte[] {255, 0, 0, 128}, Int32.MinValue + 255 )] [TestCase( ByteOrder.LittleEndian, new Byte[] {255, 255, 255, 255}, -1 )] [TestCase( ByteOrder.BigEndian, new Byte[] {0, 0, 0, 0}, 0 )] [TestCase( ByteOrder.BigEndian, new Byte[] {0, 0, 0, 1}, 1 )] [TestCase( ByteOrder.BigEndian, new Byte[] {0, 0, 1, 0}, 256 )] [TestCase( ByteOrder.BigEndian, new Byte[] {0, 0, 0, 128}, 128 )] [TestCase( ByteOrder.BigEndian, new Byte[] {128, 0, 0, 0}, Int32.MinValue )] [TestCase( ByteOrder.BigEndian, new Byte[] {128, 0, 0, 1}, Int32.MinValue + 1 )] [TestCase( ByteOrder.BigEndian, new Byte[] {192, 0, 0, 0}, Int32.MinValue / 2 )] [TestCase( ByteOrder.BigEndian, new Byte[] {0, 0, 0, 255}, 255 )] [TestCase( ByteOrder.BigEndian, new Byte[] {127, 255, 255, 255}, Int32.MaxValue )] [TestCase( ByteOrder.BigEndian, new Byte[] {128, 0, 0, 255}, Int32.MinValue + 255 )] [TestCase( ByteOrder.BigEndian, new Byte[] {255, 255, 255, 255}, -1 )] public void to_bytes_correctly_converts_int32( ByteOrder order, Byte[] result, Int32 value ) { Assert.That( Bytes.ToBytes( value, order ), Is.EqualTo( result ) ); } [TestCase( ByteOrder.LittleEndian, new Byte[] {0, 0, 0, 0, 0, 0, 0, 0}, 0 )] [TestCase( ByteOrder.LittleEndian, new Byte[] {0, 1, 0, 0, 0, 0, 0, 0}, 256 )] [TestCase( ByteOrder.LittleEndian, new Byte[] {1, 0, 0, 0, 0, 0, 0, 0}, 1 )] [TestCase( ByteOrder.LittleEndian, new Byte[] {0, 0, 0, 0, 0, 0, 0, 128}, Int64.MinValue )] [TestCase( ByteOrder.LittleEndian, new Byte[] {128, 0, 0, 0, 0, 0, 0, 0}, 128 )] [TestCase( ByteOrder.LittleEndian, new Byte[] {255, 0, 0, 0, 0, 0, 0, 0}, 255 )] [TestCase( ByteOrder.LittleEndian, new Byte[] {255, 255, 255, 255, 255, 255, 255, 127}, Int64.MaxValue )] [TestCase( ByteOrder.LittleEndian, new Byte[] {255, 0, 0, 0, 0, 0, 0, 128}, Int64.MinValue + 255 )] [TestCase( ByteOrder.LittleEndian, new Byte[] {255, 255, 255, 255, 255, 255, 255, 255}, -1 )] [TestCase( ByteOrder.LittleEndian, new Byte[] {0x00, 0x00, 0x9C, 0x58, 0x4C, 0x49, 0x1F, 0xF2}, -1000000000000000000 )] [TestCase( ByteOrder.BigEndian, new Byte[] {0, 0, 0, 0, 0, 0, 0, 0}, 0 )] [TestCase( ByteOrder.BigEndian, new Byte[] {0, 0, 0, 0, 0, 0, 0, 1}, 1 )] [TestCase( ByteOrder.BigEndian, new Byte[] {0, 0, 0, 0, 0, 0, 1, 0}, 256 )] [TestCase( ByteOrder.BigEndian, new Byte[] {0, 0, 0, 0, 0, 0, 0, 128}, 128 )] [TestCase( ByteOrder.BigEndian, new Byte[] {128, 0, 0, 0, 0, 0, 0, 0}, Int64.MinValue )] [TestCase( ByteOrder.BigEndian, new Byte[] {128, 0, 0, 0, 0, 0, 0, 1}, Int64.MinValue + 1 )] [TestCase( ByteOrder.BigEndian, new Byte[] {192, 0, 0, 0, 0, 0, 0, 0}, Int64.MinValue / 2 )] [TestCase( ByteOrder.BigEndian, new Byte[] {0, 0, 0, 0, 0, 0, 0, 255}, 255 )] [TestCase( ByteOrder.BigEndian, new Byte[] {127, 255, 255, 255, 255, 255, 255, 255}, Int64.MaxValue )] [TestCase( ByteOrder.BigEndian, new Byte[] {128, 0, 0, 0, 0, 0, 0, 255}, Int64.MinValue + 255 )] [TestCase( ByteOrder.BigEndian, new Byte[] {255, 255, 255, 255, 255, 255, 255, 255}, -1 )] public void to_bytes_correctly_converts_int64( ByteOrder order, Byte[] result, Int64 value ) { Assert.That( Bytes.ToBytes( value, order ), Is.EqualTo( result ) ); } [TestCase( ByteOrder.LittleEndian, new Byte[] {0, 0}, UInt16.MinValue )] [TestCase( ByteOrder.LittleEndian, new Byte[] {0, 1}, 256 )] [TestCase( ByteOrder.LittleEndian, new Byte[] {1, 0}, 1 )] [TestCase( ByteOrder.LittleEndian, new Byte[] {128, 0}, 128 )] [TestCase( ByteOrder.LittleEndian, new Byte[] {255, 0}, 255 )] [TestCase( ByteOrder.LittleEndian, new Byte[] {255, 255}, UInt16.MaxValue )] [TestCase( ByteOrder.BigEndian, new Byte[] {0, 0}, UInt16.MinValue )] [TestCase( ByteOrder.BigEndian, new Byte[] {0, 1}, 1 )] [TestCase( ByteOrder.BigEndian, new Byte[] {1, 0}, 256 )] [TestCase( ByteOrder.BigEndian, new Byte[] {0, 128}, 128 )] [TestCase( ByteOrder.BigEndian, new Byte[] {0, 255}, 255 )] [TestCase( ByteOrder.BigEndian, new Byte[] {255, 255}, UInt16.MaxValue )] [TestCase( ByteOrder.BigEndian, new Byte[] {0, 0}, 0 )] public void to_bytes_correctly_converts_uint16( ByteOrder order, Byte[] result, Int32 value ) { Assert.That( Bytes.ToBytes( (UInt16)value, order ), Is.EqualTo( result ) ); } [TestCase( ByteOrder.LittleEndian, new Byte[] {0, 0, 0, 0}, UInt32.MinValue )] [TestCase( ByteOrder.LittleEndian, new Byte[] {0, 1, 0, 0}, (UInt32)256 )] [TestCase( ByteOrder.LittleEndian, new Byte[] {1, 0, 0, 0}, (UInt32)1 )] [TestCase( ByteOrder.LittleEndian, new Byte[] {128, 0, 0, 0}, (UInt32)128 )] [TestCase( ByteOrder.LittleEndian, new Byte[] {255, 0, 0, 0}, (UInt32)255 )] [TestCase( ByteOrder.LittleEndian, new Byte[] {255, 255, 255, 255}, UInt32.MaxValue )] [TestCase( ByteOrder.BigEndian, new Byte[] {0, 0, 0, 0}, UInt32.MinValue )] [TestCase( ByteOrder.BigEndian, new Byte[] {0, 0, 0, 1}, (UInt32)1 )] [TestCase( ByteOrder.BigEndian, new Byte[] {0, 0, 1, 0}, (UInt32)256 )] [TestCase( ByteOrder.BigEndian, new Byte[] {0, 0, 0, 128}, (UInt32)128 )] [TestCase( ByteOrder.BigEndian, new Byte[] {0, 0, 0, 255}, (UInt32)255 )] [TestCase( ByteOrder.BigEndian, new Byte[] {255, 255, 255, 255}, UInt32.MaxValue )] public void to_bytes_correctly_converts_uint32( ByteOrder order, Byte[] result, UInt32 value ) { Assert.That( Bytes.ToBytes( value, order ), Is.EqualTo( result ) ); } [TestCase( ByteOrder.LittleEndian, UInt64.MinValue, ExpectedResult = new Byte[] {0, 0, 0, 0, 0, 0, 0, 0} )] [TestCase( ByteOrder.LittleEndian, (UInt64)256, ExpectedResult = new Byte[] {0, 1, 0, 0, 0, 0, 0, 0} )] [TestCase( ByteOrder.LittleEndian, (UInt64)1, ExpectedResult = new Byte[] {1, 0, 0, 0, 0, 0, 0, 0} )] [TestCase( ByteOrder.LittleEndian, (UInt64)128, ExpectedResult = new Byte[] {128, 0, 0, 0, 0, 0, 0, 0} )] [TestCase( ByteOrder.LittleEndian, (UInt64)255, ExpectedResult = new Byte[] {255, 0, 0, 0, 0, 0, 0, 0} )] [TestCase( ByteOrder.LittleEndian, UInt64.MaxValue, ExpectedResult = new Byte[] {255, 255, 255, 255, 255, 255, 255, 255} )] [TestCase( ByteOrder.LittleEndian, 17446744073709551616, ExpectedResult = new Byte[] {0x00, 0x00, 0x9C, 0x58, 0x4C, 0x49, 0x1F, 0xF2} )] [TestCase( ByteOrder.BigEndian, UInt64.MinValue, ExpectedResult = new Byte[] {0, 0, 0, 0, 0, 0, 0, 0} )] [TestCase( ByteOrder.BigEndian, (UInt64)1, ExpectedResult = new Byte[] {0, 0, 0, 0, 0, 0, 0, 1} )] [TestCase( ByteOrder.BigEndian, (UInt64)256, ExpectedResult = new Byte[] {0, 0, 0, 0, 0, 0, 1, 0} )] [TestCase( ByteOrder.BigEndian, (UInt64)128, ExpectedResult = new Byte[] {0, 0, 0, 0, 0, 0, 0, 128} )] [TestCase( ByteOrder.BigEndian, (UInt64)255, ExpectedResult = new Byte[] {0, 0, 0, 0, 0, 0, 0, 255} )] [TestCase( ByteOrder.BigEndian, UInt64.MaxValue, ExpectedResult = new Byte[] {255, 255, 255, 255, 255, 255, 255, 255} )] [TestCase( ByteOrder.BigEndian, 17446744073709551616, ExpectedResult = new Byte[] {0xF2, 0x1F, 0x49, 0x4C, 0x58, 0x9C, 0x00, 0x00} )] public Byte[] to_bytes_correctly_converts_uint64( ByteOrder order, UInt64 value ) { return Bytes.ToBytes( value, order ); } /* // TODO: Fix [Ignore( "Test incomplete" )] public void to_bytes_correctly_converts_float32( ByteOrder order, Byte[] result, Single value ) { Assert.That( Bytes.ToBytes( value, order ), Is.EqualTo( result ) ); } [Ignore("Test incomplete")] [TestCase(ByteOrder.LittleEndian, Double.MinValue, ExpectedResult = new Byte[] { 0, 0, 0, 0, 0, 0, 0, 0 })] [TestCase(ByteOrder.LittleEndian, (Double)256, ExpectedResult = new Byte[] { 0, 1, 0, 0, 0, 0, 0, 0 })] [TestCase(ByteOrder.LittleEndian, (Double)1, ExpectedResult = new Byte[] { 1, 0, 0, 0, 0, 0, 0, 0 })] [TestCase(ByteOrder.LittleEndian, (Double)128, ExpectedResult = new Byte[] { 128, 0, 0, 0, 0, 0, 0, 0 })] [TestCase(ByteOrder.LittleEndian, (Double)255, ExpectedResult = new Byte[] { 255, 0, 0, 0, 0, 0, 0, 0 })] [TestCase( ByteOrder.LittleEndian, Double.MaxValue, ExpectedResult = new Byte[] { 255, 255, 255, 255, 255, 255, 255, 255 })] [TestCase( ByteOrder.LittleEndian, 17446744073709551616, ExpectedResult = new Byte[] { 0x00, 0x00, 0x9C, 0x58, 0x4C, 0x49, 0x1F, 0xF2 })] [TestCase(ByteOrder.BigEndian, Double.MinValue, ExpectedResult = new Byte[] { 0, 0, 0, 0, 0, 0, 0, 0 })] [TestCase(ByteOrder.BigEndian, (Double)1, ExpectedResult = new Byte[] { 0, 0, 0, 0, 0, 0, 0, 1 })] [TestCase(ByteOrder.BigEndian, (Double)256, ExpectedResult = new Byte[] { 0, 0, 0, 0, 0, 0, 1, 0 })] [TestCase(ByteOrder.BigEndian, (Double)128, ExpectedResult = new Byte[] { 0, 0, 0, 0, 0, 0, 0, 128 })] [TestCase(ByteOrder.BigEndian, (Double)255, ExpectedResult = new Byte[] { 0, 0, 0, 0, 0, 0, 0, 255 })] [TestCase( ByteOrder.BigEndian, Double.MaxValue, ExpectedResult = new Byte[] { 255, 255, 255, 255, 255, 255, 255, 255 })] [TestCase( ByteOrder.BigEndian, 17446744073709551616, ExpectedResult = new Byte[] { 0xF2, 0x1F, 0x49, 0x4C, 0x58, 0x9C, 0x00, 0x00 })] public Byte[] to_bytes_correctly_converts_float64( ByteOrder order, Double value ) { return Bytes.ToBytes( value, order ); } */ // ReSharper disable NUnit.MethodWithParametersAndTestAttribute [Test] public void to_bytes_to_int16_equals_original_int16( [Random( Int16.MinValue, Int16.MaxValue, 10 )] Int16 value, [Values( ByteOrder.BigEndian, ByteOrder.LittleEndian )] ByteOrder endianness ) { Assert.That( Bytes.ToInt16( Bytes.ToBytes( value, endianness ), 0, endianness ), Is.EqualTo( value ) ); } [Test] public void to_bytes_to_int32_equals_original_int32( [Random( Int32.MinValue, Int32.MaxValue, 10 )] Int32 value, [Values( ByteOrder.BigEndian, ByteOrder.LittleEndian )] ByteOrder endianness ) { Assert.That( Bytes.ToInt32( Bytes.ToBytes( value, endianness ), 0, endianness ), Is.EqualTo( value ) ); } [Test] public void to_bytes_to_int64_equals_original_int64( [Random( Int64.MinValue, Int64.MaxValue, 10 )] Int64 value, [Values( ByteOrder.BigEndian, ByteOrder.LittleEndian )] ByteOrder endianness ) { Assert.That( Bytes.ToInt64( Bytes.ToBytes( value, endianness ), 0, endianness ), Is.EqualTo( value ) ); } [Test] public void to_bytes_to_uint16_equals_original_uint16( [Random( UInt16.MinValue, UInt16.MaxValue, 10 )] UInt16 value, [Values( ByteOrder.BigEndian, ByteOrder.LittleEndian )] ByteOrder endianness ) { Assert.That( Bytes.ToUInt16( Bytes.ToBytes( value, endianness ), 0, endianness ), Is.EqualTo( value ) ); } [Test] public void to_bytes_to_uint32_equals_original_uint32( [Random( UInt32.MinValue, UInt32.MaxValue, 10 )] UInt32 value, [Values( ByteOrder.BigEndian, ByteOrder.LittleEndian )] ByteOrder endianness ) { Assert.That( Bytes.ToUInt32( Bytes.ToBytes( value, endianness ), 0, endianness ), Is.EqualTo( value ) ); } [Test] public void to_bytes_to_uint64_equals_original_uint64( [Random( UInt64.MinValue, UInt64.MaxValue, 10 )] UInt64 value, [Values( ByteOrder.BigEndian, ByteOrder.LittleEndian )] ByteOrder endianness ) { Assert.That( Bytes.ToUInt64( Bytes.ToBytes( value, endianness ), 0, endianness ), Is.EqualTo( value ) ); } /* [Test] public void to_bytes_to_float32_equals_original_float32( [Random( Single.MinValue, Single.MaxValue, 10 )] Single value, [Values( ByteOrder.BigEndian, ByteOrder.LittleEndian )] ByteOrder endianness ) { Assert.That( Bytes.ToFloat32( Bytes.ToBytes( value, endianness ), 0, endianness ), Is.EqualTo( value ) ); } [Test] public void to_bytes_to_float64_equals_original_float64( [Random( Double.MinValue, Double.MaxValue, 10 )] Double value, [Values( ByteOrder.BigEndian, ByteOrder.LittleEndian )] ByteOrder endianness ) { Assert.That( Bytes.ToFloat64( Bytes.ToBytes( value, endianness ), 0, endianness ), Is.EqualTo( value ) ); } */ // ReSharper restore NUnit.MethodWithParametersAndTestAttribute } }
59.455882
118
0.613282
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
nexussays/core
test/nexus.core_test/Bytes.ToBytes.Test.cs
16,174
C#
public class Map { public int Rows; public int Cols; public byte[,] Data; public int Lives; public int SprayUses; public int AccelerationCD; public bool passThroughtVirus; }
18.454545
34
0.669951
[ "MIT" ]
Zargith/Keimyung_Game_Project_2_Spring2021
Assets/Scripts/Levels/Mysophobia/Map/Map.cs
203
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/sapi.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace TerraFX.Interop.Windows; /// <include file='ISpXMLRecoResult.xml' path='doc/member[@name="ISpXMLRecoResult"]/*' /> [Guid("AE39362B-45A8-4074-9B9E-CCF49AA2D0B6")] [NativeTypeName("struct ISpXMLRecoResult : ISpRecoResult")] [NativeInheritance("ISpRecoResult")] public unsafe partial struct ISpXMLRecoResult : ISpXMLRecoResult.Interface { public void** lpVtbl; /// <inheritdoc cref="IUnknown.QueryInterface" /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(0)] public HRESULT QueryInterface([NativeTypeName("const IID &")] Guid* riid, void** ppvObject) { return ((delegate* unmanaged<ISpXMLRecoResult*, Guid*, void**, int>)(lpVtbl[0]))((ISpXMLRecoResult*)Unsafe.AsPointer(ref this), riid, ppvObject); } /// <inheritdoc cref="IUnknown.AddRef" /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(1)] [return: NativeTypeName("ULONG")] public uint AddRef() { return ((delegate* unmanaged<ISpXMLRecoResult*, uint>)(lpVtbl[1]))((ISpXMLRecoResult*)Unsafe.AsPointer(ref this)); } /// <inheritdoc cref="IUnknown.Release" /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(2)] [return: NativeTypeName("ULONG")] public uint Release() { return ((delegate* unmanaged<ISpXMLRecoResult*, uint>)(lpVtbl[2]))((ISpXMLRecoResult*)Unsafe.AsPointer(ref this)); } /// <inheritdoc cref="ISpPhrase.GetPhrase" /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(3)] public HRESULT GetPhrase(SPPHRASE** ppCoMemPhrase) { return ((delegate* unmanaged<ISpXMLRecoResult*, SPPHRASE**, int>)(lpVtbl[3]))((ISpXMLRecoResult*)Unsafe.AsPointer(ref this), ppCoMemPhrase); } /// <inheritdoc cref="ISpPhrase.GetSerializedPhrase" /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(4)] public HRESULT GetSerializedPhrase(SPSERIALIZEDPHRASE** ppCoMemPhrase) { return ((delegate* unmanaged<ISpXMLRecoResult*, SPSERIALIZEDPHRASE**, int>)(lpVtbl[4]))((ISpXMLRecoResult*)Unsafe.AsPointer(ref this), ppCoMemPhrase); } /// <inheritdoc cref="ISpPhrase.GetText" /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(5)] public HRESULT GetText([NativeTypeName("ULONG")] uint ulStart, [NativeTypeName("ULONG")] uint ulCount, BOOL fUseTextReplacements, [NativeTypeName("LPWSTR *")] ushort** ppszCoMemText, byte* pbDisplayAttributes) { return ((delegate* unmanaged<ISpXMLRecoResult*, uint, uint, BOOL, ushort**, byte*, int>)(lpVtbl[5]))((ISpXMLRecoResult*)Unsafe.AsPointer(ref this), ulStart, ulCount, fUseTextReplacements, ppszCoMemText, pbDisplayAttributes); } /// <inheritdoc cref="ISpPhrase.Discard" /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(6)] public HRESULT Discard([NativeTypeName("DWORD")] uint dwValueTypes) { return ((delegate* unmanaged<ISpXMLRecoResult*, uint, int>)(lpVtbl[6]))((ISpXMLRecoResult*)Unsafe.AsPointer(ref this), dwValueTypes); } /// <inheritdoc cref="ISpRecoResult.GetResultTimes" /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(7)] public HRESULT GetResultTimes(SPRECORESULTTIMES* pTimes) { return ((delegate* unmanaged<ISpXMLRecoResult*, SPRECORESULTTIMES*, int>)(lpVtbl[7]))((ISpXMLRecoResult*)Unsafe.AsPointer(ref this), pTimes); } /// <inheritdoc cref="ISpRecoResult.GetAlternates" /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(8)] public HRESULT GetAlternates([NativeTypeName("ULONG")] uint ulStartElement, [NativeTypeName("ULONG")] uint cElements, [NativeTypeName("ULONG")] uint ulRequestCount, ISpPhraseAlt** ppPhrases, [NativeTypeName("ULONG *")] uint* pcPhrasesReturned) { return ((delegate* unmanaged<ISpXMLRecoResult*, uint, uint, uint, ISpPhraseAlt**, uint*, int>)(lpVtbl[8]))((ISpXMLRecoResult*)Unsafe.AsPointer(ref this), ulStartElement, cElements, ulRequestCount, ppPhrases, pcPhrasesReturned); } /// <inheritdoc cref="ISpRecoResult.GetAudio" /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(9)] public HRESULT GetAudio([NativeTypeName("ULONG")] uint ulStartElement, [NativeTypeName("ULONG")] uint cElements, ISpStreamFormat** ppStream) { return ((delegate* unmanaged<ISpXMLRecoResult*, uint, uint, ISpStreamFormat**, int>)(lpVtbl[9]))((ISpXMLRecoResult*)Unsafe.AsPointer(ref this), ulStartElement, cElements, ppStream); } /// <inheritdoc cref="ISpRecoResult.SpeakAudio" /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(10)] public HRESULT SpeakAudio([NativeTypeName("ULONG")] uint ulStartElement, [NativeTypeName("ULONG")] uint cElements, [NativeTypeName("DWORD")] uint dwFlags, [NativeTypeName("ULONG *")] uint* pulStreamNumber) { return ((delegate* unmanaged<ISpXMLRecoResult*, uint, uint, uint, uint*, int>)(lpVtbl[10]))((ISpXMLRecoResult*)Unsafe.AsPointer(ref this), ulStartElement, cElements, dwFlags, pulStreamNumber); } /// <inheritdoc cref="ISpRecoResult.Serialize" /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(11)] public HRESULT Serialize(SPSERIALIZEDRESULT** ppCoMemSerializedResult) { return ((delegate* unmanaged<ISpXMLRecoResult*, SPSERIALIZEDRESULT**, int>)(lpVtbl[11]))((ISpXMLRecoResult*)Unsafe.AsPointer(ref this), ppCoMemSerializedResult); } /// <inheritdoc cref="ISpRecoResult.ScaleAudio" /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(12)] public HRESULT ScaleAudio([NativeTypeName("const GUID *")] Guid* pAudioFormatId, [NativeTypeName("const WAVEFORMATEX *")] WAVEFORMATEX* pWaveFormatEx) { return ((delegate* unmanaged<ISpXMLRecoResult*, Guid*, WAVEFORMATEX*, int>)(lpVtbl[12]))((ISpXMLRecoResult*)Unsafe.AsPointer(ref this), pAudioFormatId, pWaveFormatEx); } /// <inheritdoc cref="ISpRecoResult.GetRecoContext" /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(13)] public HRESULT GetRecoContext(ISpRecoContext** ppRecoContext) { return ((delegate* unmanaged<ISpXMLRecoResult*, ISpRecoContext**, int>)(lpVtbl[13]))((ISpXMLRecoResult*)Unsafe.AsPointer(ref this), ppRecoContext); } /// <include file='ISpXMLRecoResult.xml' path='doc/member[@name="ISpXMLRecoResult.GetXMLResult"]/*' /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(14)] public HRESULT GetXMLResult([NativeTypeName("LPWSTR *")] ushort** ppszCoMemXMLResult, SPXMLRESULTOPTIONS Options) { return ((delegate* unmanaged<ISpXMLRecoResult*, ushort**, SPXMLRESULTOPTIONS, int>)(lpVtbl[14]))((ISpXMLRecoResult*)Unsafe.AsPointer(ref this), ppszCoMemXMLResult, Options); } /// <include file='ISpXMLRecoResult.xml' path='doc/member[@name="ISpXMLRecoResult.GetXMLErrorInfo"]/*' /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(15)] public HRESULT GetXMLErrorInfo(SPSEMANTICERRORINFO* pSemanticErrorInfo) { return ((delegate* unmanaged<ISpXMLRecoResult*, SPSEMANTICERRORINFO*, int>)(lpVtbl[15]))((ISpXMLRecoResult*)Unsafe.AsPointer(ref this), pSemanticErrorInfo); } public interface Interface : ISpRecoResult.Interface { [VtblIndex(14)] HRESULT GetXMLResult([NativeTypeName("LPWSTR *")] ushort** ppszCoMemXMLResult, SPXMLRESULTOPTIONS Options); [VtblIndex(15)] HRESULT GetXMLErrorInfo(SPSEMANTICERRORINFO* pSemanticErrorInfo); } public partial struct Vtbl<TSelf> where TSelf : unmanaged, Interface { [NativeTypeName("HRESULT (const IID &, void **) __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, Guid*, void**, int> QueryInterface; [NativeTypeName("ULONG () __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, uint> AddRef; [NativeTypeName("ULONG () __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, uint> Release; [NativeTypeName("HRESULT (SPPHRASE **) __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, SPPHRASE**, int> GetPhrase; [NativeTypeName("HRESULT (SPSERIALIZEDPHRASE **) __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, SPSERIALIZEDPHRASE**, int> GetSerializedPhrase; [NativeTypeName("HRESULT (ULONG, ULONG, BOOL, LPWSTR *, BYTE *) __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, uint, uint, BOOL, ushort**, byte*, int> GetText; [NativeTypeName("HRESULT (DWORD) __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, uint, int> Discard; [NativeTypeName("HRESULT (SPRECORESULTTIMES *) __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, SPRECORESULTTIMES*, int> GetResultTimes; [NativeTypeName("HRESULT (ULONG, ULONG, ULONG, ISpPhraseAlt **, ULONG *) __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, uint, uint, uint, ISpPhraseAlt**, uint*, int> GetAlternates; [NativeTypeName("HRESULT (ULONG, ULONG, ISpStreamFormat **) __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, uint, uint, ISpStreamFormat**, int> GetAudio; [NativeTypeName("HRESULT (ULONG, ULONG, DWORD, ULONG *) __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, uint, uint, uint, uint*, int> SpeakAudio; [NativeTypeName("HRESULT (SPSERIALIZEDRESULT **) __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, SPSERIALIZEDRESULT**, int> Serialize; [NativeTypeName("HRESULT (const GUID *, const WAVEFORMATEX *) __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, Guid*, WAVEFORMATEX*, int> ScaleAudio; [NativeTypeName("HRESULT (ISpRecoContext **) __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, ISpRecoContext**, int> GetRecoContext; [NativeTypeName("HRESULT (LPWSTR *, SPXMLRESULTOPTIONS) __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, ushort**, SPXMLRESULTOPTIONS, int> GetXMLResult; [NativeTypeName("HRESULT (SPSEMANTICERRORINFO *) __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, SPSEMANTICERRORINFO*, int> GetXMLErrorInfo; } }
50.64455
247
0.711679
[ "MIT" ]
IngmarBitter/terrafx.interop.windows
sources/Interop/Windows/Windows/um/sapi/ISpXMLRecoResult.cs
10,688
C#
using System; using Microsoft.EntityFrameworkCore.Migrations; namespace backend.v2.Migrations { public partial class RenamedColumn : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "FK_Books_Collections_CollectionId", table: "Books"); migrationBuilder.DropIndex( name: "IX_Books_CollectionId", table: "Books"); migrationBuilder.DropColumn( name: "CollectionId", table: "Books"); migrationBuilder.AddColumn<Guid>( name: "CollectionGuid", table: "Books", nullable: true); migrationBuilder.CreateIndex( name: "IX_Books_CollectionGuid", table: "Books", column: "CollectionGuid"); migrationBuilder.AddForeignKey( name: "FK_Books_Collections_CollectionGuid", table: "Books", column: "CollectionGuid", principalTable: "Collections", principalColumn: "Guid", onDelete: ReferentialAction.Restrict); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "FK_Books_Collections_CollectionGuid", table: "Books"); migrationBuilder.DropIndex( name: "IX_Books_CollectionGuid", table: "Books"); migrationBuilder.DropColumn( name: "CollectionGuid", table: "Books"); migrationBuilder.AddColumn<Guid>( name: "CollectionId", table: "Books", type: "uuid", nullable: true); migrationBuilder.CreateIndex( name: "IX_Books_CollectionId", table: "Books", column: "CollectionId"); migrationBuilder.AddForeignKey( name: "FK_Books_Collections_CollectionId", table: "Books", column: "CollectionId", principalTable: "Collections", principalColumn: "Guid", onDelete: ReferentialAction.Restrict); } } }
31.552632
71
0.530442
[ "MIT" ]
afferenslucem/bookolog
backend.v2/backend.v2/Migrations/20210114044059_RenamedColumn.cs
2,400
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Resources; // 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("ParsePhonePushSample")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ParsePhonePushSample")] [assembly: AssemblyCopyright("Copyright © 2013")] [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("2ad61a5a-9403-4a7e-96b3-1098b91559bc")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: NeutralResourcesLanguageAttribute("en-US")]
39.184211
85
0.736736
[ "CC0-1.0" ]
ForkedProjects/PushTutorial
WindowsPhone/ParsePhonePushSample/Properties/AssemblyInfo.cs
1,492
C#
using template.compiler; namespace latex.compiler { class Program { static void Main(string[] args) { string templateDir = @"D:\Code\latex-template-compiler\example\template"; string rootFile = @"template.tex"; string outputDir = @"D:\Code\latex-template-compiler\example\output"; string dataPath = @"D:\Code\latex-template-compiler\example\data.json"; TemplateCompiler compiler = new TemplateCompiler(templateDir, rootFile, dataPath, cleanUpAuxiliary: true, cleanUpTemplate: true, cleanUpSyncTex: true); compiler.Compile(outputDir); } } }
36.111111
163
0.649231
[ "MIT" ]
helgihalldorsson/latex-template-compiler
src/latex.compiler/Program.cs
652
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class FripperController : MonoBehaviour { private HingeJoint myHingeJoint; private float defaultAngle = 20; private float flickAngle = -20; // Start is called before the first frame update void Start() { this.myHingeJoint = GetComponent<HingeJoint>(); SetAngle(this.defaultAngle); } // Update is called once per frame void Update() { if(Input.GetKeyDown(KeyCode.LeftArrow) && tag == "LeftFripperTag") { SetAngle(this.flickAngle); } if (Input.GetKeyDown(KeyCode.RightArrow) && tag == "RightFripperTag") { SetAngle(this.flickAngle); } if (Input.GetKeyUp(KeyCode.LeftArrow) && tag == "LeftFripperTag") { SetAngle(this.defaultAngle); } if (Input.GetKeyUp(KeyCode.RightArrow) && tag == "RightFripperTag") { SetAngle(this.defaultAngle); } } public void SetAngle(float angle) { JointSpring jointSpr = this.myHingeJoint.spring; jointSpr.targetPosition = angle; this.myHingeJoint.spring = jointSpr; } }
22.392857
77
0.598086
[ "MIT" ]
Okashiou/202006pinpon
pinpon/pinpon/Assets/Script/FripperController.cs
1,256
C#
#pragma warning disable 1591 //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ [assembly: global::Android.Runtime.ResourceDesignerAttribute("Xenko.Input.Tests.Resource", IsApplication=true)] namespace Xenko.Input.Tests { [System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Android.Build.Tasks", "1.0.0.0")] public partial class Resource { static Resource() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } public static void UpdateIdValues() { global::Xenko.Resource.Id.EditTextLayout = global::Xenko.Input.Tests.Resource.Id.EditTextLayout; global::Xenko.Resource.Id.GameMainLayout = global::Xenko.Input.Tests.Resource.Id.GameMainLayout; global::Xenko.Resource.Id.GameViewLayout = global::Xenko.Input.Tests.Resource.Id.GameViewLayout; global::Xenko.Resource.Layout.Game = global::Xenko.Input.Tests.Resource.Layout.Game; global::Xamarin.Android.NUnitLite.Resource.Id.OptionHostName = global::Xenko.Input.Tests.Resource.Id.OptionHostName; global::Xamarin.Android.NUnitLite.Resource.Id.OptionPort = global::Xenko.Input.Tests.Resource.Id.OptionPort; global::Xamarin.Android.NUnitLite.Resource.Id.OptionRemoteServer = global::Xenko.Input.Tests.Resource.Id.OptionRemoteServer; global::Xamarin.Android.NUnitLite.Resource.Id.OptionsButton = global::Xenko.Input.Tests.Resource.Id.OptionsButton; global::Xamarin.Android.NUnitLite.Resource.Id.ResultFullName = global::Xenko.Input.Tests.Resource.Id.ResultFullName; global::Xamarin.Android.NUnitLite.Resource.Id.ResultMessage = global::Xenko.Input.Tests.Resource.Id.ResultMessage; global::Xamarin.Android.NUnitLite.Resource.Id.ResultResultState = global::Xenko.Input.Tests.Resource.Id.ResultResultState; global::Xamarin.Android.NUnitLite.Resource.Id.ResultRunSingleMethodTest = global::Xenko.Input.Tests.Resource.Id.ResultRunSingleMethodTest; global::Xamarin.Android.NUnitLite.Resource.Id.ResultStackTrace = global::Xenko.Input.Tests.Resource.Id.ResultStackTrace; global::Xamarin.Android.NUnitLite.Resource.Id.ResultsFailed = global::Xenko.Input.Tests.Resource.Id.ResultsFailed; global::Xamarin.Android.NUnitLite.Resource.Id.ResultsId = global::Xenko.Input.Tests.Resource.Id.ResultsId; global::Xamarin.Android.NUnitLite.Resource.Id.ResultsIgnored = global::Xenko.Input.Tests.Resource.Id.ResultsIgnored; global::Xamarin.Android.NUnitLite.Resource.Id.ResultsInconclusive = global::Xenko.Input.Tests.Resource.Id.ResultsInconclusive; global::Xamarin.Android.NUnitLite.Resource.Id.ResultsMessage = global::Xenko.Input.Tests.Resource.Id.ResultsMessage; global::Xamarin.Android.NUnitLite.Resource.Id.ResultsPassed = global::Xenko.Input.Tests.Resource.Id.ResultsPassed; global::Xamarin.Android.NUnitLite.Resource.Id.ResultsResult = global::Xenko.Input.Tests.Resource.Id.ResultsResult; global::Xamarin.Android.NUnitLite.Resource.Id.RunTestsButton = global::Xenko.Input.Tests.Resource.Id.RunTestsButton; global::Xamarin.Android.NUnitLite.Resource.Id.TestSuiteListView = global::Xenko.Input.Tests.Resource.Id.TestSuiteListView; global::Xamarin.Android.NUnitLite.Resource.Layout.options = global::Xenko.Input.Tests.Resource.Layout.options; global::Xamarin.Android.NUnitLite.Resource.Layout.results = global::Xenko.Input.Tests.Resource.Layout.results; global::Xamarin.Android.NUnitLite.Resource.Layout.test_result = global::Xenko.Input.Tests.Resource.Layout.test_result; global::Xamarin.Android.NUnitLite.Resource.Layout.test_suite = global::Xenko.Input.Tests.Resource.Layout.test_suite; } public partial class Attribute { static Attribute() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private Attribute() { } } public partial class Drawable { // aapt resource value: 0x7f020000 public const int dialog_disclosure = 2130837504; // aapt resource value: 0x7f020001 public const int dialog_expander_ic_minimized = 2130837505; // aapt resource value: 0x7f020002 public const int Icon = 2130837506; static Drawable() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private Drawable() { } } public partial class Id { // aapt resource value: 0x7f04000f public const int EditTextLayout = 2130968591; // aapt resource value: 0x7f04000d public const int GameMainLayout = 2130968589; // aapt resource value: 0x7f04000e public const int GameViewLayout = 2130968590; // aapt resource value: 0x7f040011 public const int OptionHostName = 2130968593; // aapt resource value: 0x7f040012 public const int OptionPort = 2130968594; // aapt resource value: 0x7f040010 public const int OptionRemoteServer = 2130968592; // aapt resource value: 0x7f040020 public const int OptionsButton = 2130968608; // aapt resource value: 0x7f04001b public const int ResultFullName = 2130968603; // aapt resource value: 0x7f04001d public const int ResultMessage = 2130968605; // aapt resource value: 0x7f04001c public const int ResultResultState = 2130968604; // aapt resource value: 0x7f04001a public const int ResultRunSingleMethodTest = 2130968602; // aapt resource value: 0x7f04001e public const int ResultStackTrace = 2130968606; // aapt resource value: 0x7f040016 public const int ResultsFailed = 2130968598; // aapt resource value: 0x7f040013 public const int ResultsId = 2130968595; // aapt resource value: 0x7f040017 public const int ResultsIgnored = 2130968599; // aapt resource value: 0x7f040018 public const int ResultsInconclusive = 2130968600; // aapt resource value: 0x7f040019 public const int ResultsMessage = 2130968601; // aapt resource value: 0x7f040015 public const int ResultsPassed = 2130968597; // aapt resource value: 0x7f040014 public const int ResultsResult = 2130968596; // aapt resource value: 0x7f04001f public const int RunTestsButton = 2130968607; // aapt resource value: 0x7f040021 public const int TestSuiteListView = 2130968609; // aapt resource value: 0x7f040002 public const int dialog_BoolField = 2130968578; // aapt resource value: 0x7f040003 public const int dialog_Button = 2130968579; // aapt resource value: 0x7f040009 public const int dialog_DisclosureField = 2130968585; // aapt resource value: 0x7f040005 public const int dialog_ImageLeft = 2130968581; // aapt resource value: 0x7f040007 public const int dialog_ImageRight = 2130968583; // aapt resource value: 0x7f040000 public const int dialog_LabelField = 2130968576; // aapt resource value: 0x7f040001 public const int dialog_LabelSubtextField = 2130968577; // aapt resource value: 0x7f040008 public const int dialog_Panel = 2130968584; // aapt resource value: 0x7f04000a public const int dialog_RadioButtonList = 2130968586; // aapt resource value: 0x7f040006 public const int dialog_SliderField = 2130968582; // aapt resource value: 0x7f04000b public const int dialog_Spinner = 2130968587; // aapt resource value: 0x7f040004 public const int dialog_ValueField = 2130968580; // aapt resource value: 0x7f04000c public const int iFormFieldValue = 2130968588; static Id() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private Id() { } } public partial class Layout { // aapt resource value: 0x7f030000 public const int dialog_achievements = 2130903040; // aapt resource value: 0x7f030001 public const int dialog_boolfieldleft = 2130903041; // aapt resource value: 0x7f030002 public const int dialog_boolfieldright = 2130903042; // aapt resource value: 0x7f030003 public const int dialog_boolfieldsubleft = 2130903043; // aapt resource value: 0x7f030004 public const int dialog_boolfieldsubright = 2130903044; // aapt resource value: 0x7f030005 public const int dialog_button = 2130903045; // aapt resource value: 0x7f030006 public const int dialog_datefield = 2130903046; // aapt resource value: 0x7f030007 public const int dialog_fieldsetlabel = 2130903047; // aapt resource value: 0x7f030008 public const int dialog_floatimage = 2130903048; // aapt resource value: 0x7f030009 public const int dialog_labelfieldbelow = 2130903049; // aapt resource value: 0x7f03000a public const int dialog_labelfieldright = 2130903050; // aapt resource value: 0x7f03000b public const int dialog_onofffieldright = 2130903051; // aapt resource value: 0x7f03000c public const int dialog_panel = 2130903052; // aapt resource value: 0x7f03000d public const int dialog_root = 2130903053; // aapt resource value: 0x7f03000e public const int dialog_selectlist = 2130903054; // aapt resource value: 0x7f03000f public const int dialog_selectlistfield = 2130903055; // aapt resource value: 0x7f030010 public const int dialog_textarea = 2130903056; // aapt resource value: 0x7f030011 public const int dialog_textfieldbelow = 2130903057; // aapt resource value: 0x7f030012 public const int dialog_textfieldright = 2130903058; // aapt resource value: 0x7f030013 public const int Game = 2130903059; // aapt resource value: 0x7f030014 public const int options = 2130903060; // aapt resource value: 0x7f030015 public const int results = 2130903061; // aapt resource value: 0x7f030016 public const int test_result = 2130903062; // aapt resource value: 0x7f030017 public const int test_suite = 2130903063; static Layout() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private Layout() { } } } } #pragma warning restore 1591
34.989796
141
0.727715
[ "MIT" ]
Aminator/xenko
sources/engine/Xenko.Input.Tests/Resources/Resource.Designer.cs
10,287
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; namespace ClipIt.Controls { public class Range { public double RangeValue { get; set; } public Thickness RangeMargin { get { if (RangeValue.ToString().Length == 1) { return new Thickness(-1, 0, -1, 0); } else if (RangeValue.ToString().Length == 2) { return new Thickness(-5, 0, -5, 0); } else if (RangeValue.ToString().Length == 3) { return new Thickness(-7, 0, -7, 0); } else if (RangeValue.ToString().Length == 4) { return new Thickness(-9, 0, -9, 0); } else return new Thickness(-1, 0, -1, 0); } } } }
28.612903
63
0.499436
[ "MIT" ]
agillgilla/clipit
ClipIt/ClipIt/Controls/Range.cs
889
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ public partial class CMSModules_OnlineMarketing_Pages_Content_ABTesting_ABTest_Tab_General { /// <summary> /// ucDisabledModule control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::CMSAdminControls_Basic_DisabledModuleInfo ucDisabledModule; /// <summary> /// plcMess control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::CMS.Base.Web.UI.MessagesPlaceHolder plcMess; /// <summary> /// editElem control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::CMSModules_OnlineMarketing_Controls_UI_AbTest_Edit editElem; }
33.756098
93
0.567197
[ "MIT" ]
CMeeg/kentico-contrib
src/CMS/CMSModules/OnlineMarketing/Pages/Content/ABTesting/ABTest/Tab_General.aspx.designer.cs
1,386
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Data; using System.Windows.Input; using Autodesk.Revit.DB; using Autodesk.Revit.UI; using dosymep.WPF.Commands; using dosymep.WPF.ViewModels; using RevitLintelPlacement.Comparers; using RevitLintelPlacement.Models; namespace RevitLintelPlacement.ViewModels { internal class LintelCollectionViewModel : BaseViewModel { private readonly RevitRepository _revitRepository; private readonly ElementInfosViewModel _elementInfos; private ElementInWallKind _selectedElementKind; private ViewOrientation3D _orientation; //вряд ли здесь нужно хранить private ObservableCollection<LintelInfoViewModel> _lintelInfos; private SampleMode selectedSampleMode; private int countLintelInView; public LintelCollectionViewModel(RevitRepository revitRepository, ElementInfosViewModel elementInfos) { this._revitRepository = revitRepository; this._elementInfos = elementInfos; var config = revitRepository.LintelsConfig.GetSettings(_revitRepository.GetDocumentName()); if(config != null) { SelectedSampleMode = config.SelectedModeNavigator; } InitializeLintels(SelectedSampleMode); LintelsViewSource = new CollectionViewSource { Source = LintelInfos }; LintelsViewSource.GroupDescriptions.Add(new PropertyGroupDescription(nameof(LintelInfoViewModel.Level))); LintelsViewSource.Filter += ElementInWallKindFilter; SelectAndShowElementCommand = new RelayCommand(async p => await SelectElement(p)); SelectNextCommand = new RelayCommand(async p => await SelectNext(p)); SelectPreviousCommand = new RelayCommand(async p => await SelectPrevious(p)); SelectionElementKindChangedCommand = new RelayCommand(SelectionElementKindChanged, p => true); SampleModeChangedCommand = new RelayCommand(SampleModeChanged, p => true); CloseCommand = new RelayCommand(Close, p => true); CountLintelInView = LintelsViewSource.View.Cast<LintelInfoViewModel>().Count(); } public int CountLintelInView { get => countLintelInView; set => this.RaiseAndSetIfChanged(ref countLintelInView, value); } public ElementInWallKind SelectedElementKind { get => _selectedElementKind; set => this.RaiseAndSetIfChanged(ref _selectedElementKind, value); } public SampleMode SelectedSampleMode { get => selectedSampleMode; set => this.RaiseAndSetIfChanged(ref selectedSampleMode, value); } public ICommand SelectionElementKindChangedCommand { get; } public ICommand SelectAndShowElementCommand { get; } public ICommand SelectNextCommand { get; } public ICommand SelectPreviousCommand { get; } public ICommand SampleModeChangedCommand { get; set; } public ICommand CloseCommand { get; set; } public CollectionViewSource LintelsViewSource { get; set; } public ObservableCollection<LintelInfoViewModel> LintelInfos { get => _lintelInfos; set => this.RaiseAndSetIfChanged(ref _lintelInfos, value); } private void ElementInWallKindFilter(object sender, FilterEventArgs e) { if(e.Item is LintelInfoViewModel lintel) { e.Accepted = SelectedElementKind == ElementInWallKind.All ? true : lintel.ElementInWallKind == SelectedElementKind; } } private async Task SelectElement(object p) { if(!(p is ElementId id) || p == null) { return; } _revitRepository.SetActiveView(); if(_orientation == null) { _orientation = _revitRepository.GetOrientation3D(); } await _revitRepository.SelectAndShowElement(id, _orientation); } private async Task SelectNext(object p) { LintelsViewSource.View.MoveCurrentToNext(); if(LintelsViewSource.View.IsCurrentAfterLast) { LintelsViewSource.View.MoveCurrentToPrevious(); } else { var lintelInfo = LintelsViewSource.View.CurrentItem; if(lintelInfo is LintelInfoViewModel lintel) { await SelectElement(lintel.LintelId); } } } private async Task SelectPrevious(object p) { LintelsViewSource.View.MoveCurrentToPrevious(); if(LintelsViewSource.View.IsCurrentBeforeFirst) { LintelsViewSource.View.MoveCurrentToNext(); } else { var lintelInfo = LintelsViewSource.View.CurrentItem; if(lintelInfo is LintelInfoViewModel lintel) { await SelectElement(lintel.LintelId); } } } private void SelectionElementKindChanged(object p) { LintelsViewSource.View.Refresh(); CountLintelInView = LintelsViewSource.View.Cast<LintelInfoViewModel>().Count(); } //сопоставляются перемычки в группе + перемычки, закрепленные с элементом private void InitializeLintels(SampleMode sampleMode) { LintelInfos = new ObservableCollection<LintelInfoViewModel>(); var lintels = _revitRepository.GetLintels(sampleMode); var correlator = new LintelElementCorrelator(_revitRepository, _elementInfos); var lintelInfos = lintels .Select(l => new LintelInfoViewModel(_revitRepository, l, correlator.Correlate(l))) .OrderBy(l => l.Level, new AlphanumericComparer()); foreach(var lintelInfo in lintelInfos) { LintelInfos.Add(lintelInfo); } } private void SampleModeChanged(object p) { InitializeLintels(SelectedSampleMode); LintelsViewSource.Source = LintelInfos; LintelsViewSource.View.Refresh(); CountLintelInView = LintelsViewSource.View.Cast<LintelInfoViewModel>().Count(); } private void Close(object p) { LintelsSettings settings; if(_revitRepository.LintelsConfig.GetSettings(_revitRepository.GetDocumentName()) == null) { settings = _revitRepository.LintelsConfig.AddSettings(_revitRepository.GetDocumentName()); } else { settings = _revitRepository.LintelsConfig.GetSettings(_revitRepository.GetDocumentName()); } settings.SelectedModeNavigator = SelectedSampleMode; _revitRepository.LintelsConfig.SaveProjectConfig(); } } internal enum SampleMode { [Description("Выборка по всем элементам")] AllElements, [Description("Выборка по выделенным элементам")] SelectedElements, [Description("Выборка по текущему виду")] CurrentView } }
42.235294
131
0.659889
[ "MIT" ]
dosymep/RevitPlugins
RevitLintelPlacement/ViewModels/LintelViewModels/LintelCollectionViewModel.cs
7,337
C#
namespace VehicleCostsMonitor.Web.Areas.Vehicle.Models { using Common.AutoMapping.Interfaces; using Microsoft.AspNetCore.Mvc.Rendering; using Services.Models.Vehicle; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using static VehicleCostsMonitor.Models.Common.ModelConstants; public class VehicleUpdateViewModel : IAutoMapWith<VehicleUpdateServiceModel> { [Required] public int Id { get; set; } [Required] public string UserId { get; set; } [Required] [Display(Name = "Make")] public int ManufacturerId { get; set; } public IEnumerable<SelectListItem> AllManufacturers { get; set; } [Required] [Display(Name = "Model")] public string ModelName { get; set; } public IEnumerable<SelectListItem> AllModels { get; set; } [Display(Name = "Exact model name")] public string ExactModelname { get; set; } [Required] [Display(Name = "Year")] public int YearOfManufacture { get; set; } public IEnumerable<SelectListItem> AvailableYears { get; set; } [Required] [Range(EngineHorsePowerMinValue, EngineHorsePowerMaxValue)] [Display(Name = "Engine horse power")] public int EngineHorsePower { get; set; } [Required] [Display(Name = "Vehicle type")] public int VehicleTypeId { get; set; } public IEnumerable<SelectListItem> AllVehicleTypes { get; set; } [Required] [Display(Name = "Fuel type")] public int FuelTypeId { get; set; } public IEnumerable<SelectListItem> AllFuelTypes { get; set; } [Required] [Display(Name = "Gearing type")] public int GearingTypeId { get; set; } public IEnumerable<SelectListItem> AllGearingTypes { get; set; } } }
29.984127
81
0.635257
[ "MIT" ]
msotiroff/Asp.Net-Core-Projects
source/VehicleCostsMonitor.Web/Areas/Vehicle/Models/Vehicle/VehicleUpdateViewModel.cs
1,891
C#
#region Copyright // Copyright Hitachi Consulting // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using System.Collections; using System.Collections.Generic; using Microsoft.WindowsAzure.Storage.Auth; using Xigadee; namespace Test.Xigadee { public class PersistenceMondayMorningBluesBlob: PersistenceMessageHandlerAzureBlobStorageBase<Guid, MondayMorningBlues> { public PersistenceMondayMorningBluesBlob(StorageCredentials credentials , VersionPolicy<MondayMorningBlues> versionPolicy = null , ICacheManager<Guid, MondayMorningBlues> cacheManager = null , IServiceHandlerEncryption encryption = null) : base(credentials, (k) => k.Id, (s) => new Guid(s), keySerializer: (g) => g.ToString("N").ToUpperInvariant(), cacheManager: cacheManager , versionPolicy: versionPolicy , referenceMaker: MondayMorningBluesHelper.ToReferences , encryption: encryption ) { } } }
36.571429
149
0.717448
[ "Apache-2.0" ]
xigadee/Microservice
Src/Test/Test.Xigadee.Shared/Persistence/MondayMorningBlues/PersistenceMondayMorningBluesBlob.cs
1,538
C#
#region Header /** * IJsonWrapper.cs * Interface that represents a type capable of handling all kinds of JSON * data. This is mainly used when mapping objects through JsonMapper, and * it's implemented by JsonData. * * The authors disclaim copyright to this source code. For more details, see * the COPYING file included with this distribution. **/ #endregion using System.Collections; using System.Collections.Specialized; namespace LitJson { public enum JsonType { None, Object, Array, String, Int, Long, Double, Boolean } public interface IOrderedDictionary : IDictionary { new IDictionaryEnumerator GetEnumerator(); void Insert(int index, object key, object value); void RemoveAt(int index); object this[int index] { get; set; } } public interface IJsonWrapper : IList, IOrderedDictionary { bool IsArray { get; } bool IsBoolean { get; } bool IsDouble { get; } bool IsInt { get; } bool IsLong { get; } bool IsObject { get; } bool IsString { get; } bool GetBoolean (); double GetDouble (); int GetInt (); JsonType GetJsonType (); long GetLong (); string GetString (); void SetBoolean (bool val); void SetDouble (double val); void SetInt (int val); void SetJsonType (JsonType type); void SetLong (long val); void SetString (string val); string ToJson (); void ToJson (JsonWriter writer); } }
24
77
0.545045
[ "Apache-2.0" ]
Cl0udG0d/Asteroid
Assets/Import/Best HTTP (Pro)/Examples/LitJson/IJsonWrapper.cs
1,776
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Cardozo_Claudia_Clima { public class main { public double temp { get; set; } public double temp_min { get; set; } public double temp_max { get; set; } public double humidity { get; set; } } // fin clase public class InfoPronostico { public city city { get; set; } public List<list> list { get; set; } } // fin clase public class weather { public string main { get; set; } public string description { get; set; } }// fin clase public class list { public double dt { get; set; } public double pressure { get; set; } public double speed { get; set; } public main main { get; set; } public List<weather> weather { get; set; } } //fin clase public class city { }//fin clase }
21.040816
53
0.549952
[ "Unlicense" ]
DarkRyo/TP3erParcialCSharpAvanzado
Cardozo_Claudia_Clima/InfoPronostico.cs
1,033
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Commons.Music.Midi.Wpf.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.7.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
39.888889
151
0.583101
[ "MIT" ]
jaladaGmbH/managed-midi
Commons.Music.Midi.Wpf/Properties/Settings.Designer.cs
1,079
C#
using System; [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] public class DevExtMethodsAttribute : Attribute { public string BaseMethodName { get; private set; } public DevExtMethodsAttribute(string baseMethodName) { BaseMethodName = baseMethodName; } }
26.333333
82
0.743671
[ "MIT" ]
insthync/unity-dev-extension
Scripts/DevExtMethodsAttribute.cs
318
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ww { class ArrayForDraw { private int width, height; private int[,] Painting; private int seed; public ArrayForDraw(int width, int height,int seed) { this.width = width; this.height = height; this.seed = seed; Painting = new int[height, width]; } //private int DegreeToPosition(int degree) //{ // return (int)(width / 2f + width / 360f * degree); //} //private int tempStart; //private int tempEnd; //private int degree = 0; //public void MoveRight() //{ // int start = DegreeToPosition(-100); // int end = DegreeToPosition(100); // degree++; // if (degree > end) // { // degree = 0; // } // for (int i = 0; i != height; i++) // { // for (int j = 0 ; j != barWidth; j++) // { // Painting[i, j + start + degree] = 0; // } // } //} public int[,] GiveValueForRandow() { Random rd = new Random(seed); for (int i = 0; i != height; i++) { for (int j = 0; j != width; j++) { int value = rd.Next(0,100); if (value < 40) { Painting[i, j] = 1; } else { Painting[i, j] = 0; } } } return Painting; } } }
20.405941
63
0.340126
[ "MIT" ]
Taaccoo-beta/Flight-Simulator-In-Drosophila
FlightSimulatorNewForOpenLoop/FlightSimulator/ArrayForDraw.cs
2,063
C#
using System; using System.Linq; using System.Collections.Generic; using System.Data; using Norm; using Npgsql; using NpgsqlTypes; namespace PgRoutiner { public static partial class DataAccess { public static IEnumerable<string> GetTablesThatDontExist(this NpgsqlConnection connection, IEnumerable<string> tableNames) { return connection.Read<string>(@$" select n from unnest(@tables) n left outer join information_schema.tables t on t.table_name = n or '""' || t.table_name || '""' = n or t.table_schema || '.' || t.table_name = n or t.table_schema || '.' || '""' || t.table_name || '""' = n where t.table_name is null ", ("tables", tableNames, NpgsqlDbType.Varchar | NpgsqlDbType.Array)); } } }
28.323529
130
0.530633
[ "MIT" ]
vb-consulting/PgRoutiner
PgRoutiner/DataAccess/GetTablesThatDontExist.cs
965
C#
using System; using System.Web.UI; using BBX.Common; using BBX.Entity; using BBX.Forum; namespace BBX.Web.Admin { public class global_refreshallcache : Page { private void Page_Load(object sender, EventArgs e) { if (!this.Page.IsPostBack) { int @int = DNTRequest.GetInt("opnumber", 0); int num = -1; switch (@int) { case 1: //Caches.ReSetAdminGroupList(); num = 2; break; case 2: //Caches.ReSetUserGroupList(); num = 3; break; case 3: Caches.ReSetModeratorList(); num = 4; break; case 4: Caches.ReSetAnnouncementList(); Caches.ReSetSimplifiedAnnouncementList(); num = 5; break; case 5: Caches.ReSetSimplifiedAnnouncementList(); num = 6; break; case 6: Caches.ReSetForumListBoxOptions(); num = 7; break; case 7: Caches.ReSetSmiliesList(); num = 8; break; case 8: Caches.ReSetIconsList(); num = 9; break; case 9: Caches.ReSetCustomEditButtonList(); num = 10; break; case 10: num = 11; break; case 11: Caches.ReSetScoreset(); num = 12; break; case 12: Caches.ReSetSiteUrls(); num = 13; break; case 13: Caches.ReSetStatistics(); num = 14; break; case 14: Caches.ReSetAttachmentTypeArray(); num = 15; break; case 15: Caches.ReSetTemplateListBoxOptionsCache(); num = 16; break; case 16: //Caches.ReSetOnlineGroupIconList(); num = 17; break; case 17: Caches.ReSetForumLinkList(); num = 18; break; case 18: Caches.ReSetBanWordList(); num = 19; break; case 19: Caches.ReSetForumList(); num = 20; break; case 20: Caches.ReSetOnlineUserTable(); num = 21; break; case 21: Caches.ReSetRss(); num = 22; break; case 22: Caches.ReSetRssXml(); num = 23; break; case 23: Caches.ReSetValidTemplateIDList(); num = 24; break; case 24: Caches.ReSetValidScoreName(); num = 25; break; case 25: //Caches.ReSetMedalsList(); num = 26; break; case 26: Caches.ReSetDBlinkAndTablePrefix(); num = 27; break; case 27: //Caches.ReSetAllPostTableName(); num = 28; break; case 28: //Caches.ReSetLastPostTableName(); num = 29; break; case 29: Caches.ReSetAdsList(); num = 30; break; case 30: Caches.ReSetStatisticsSearchtime(); num = 31; break; case 31: Caches.ReSetStatisticsSearchcount(); num = 32; break; case 32: Caches.ReSetCommonAvatarList(); num = 33; break; case 33: Caches.ReSetJammer(); num = 34; break; case 34: Caches.ReSetMagicList(); num = 35; break; case 35: Caches.ReSetScorePaySet(); num = 36; break; case 36: //Caches.ReSetPostTableInfo(); num = 37; break; case 37: Caches.ReSetDigestTopicList(16); num = 38; break; case 38: Caches.ReSetHotTopicList(16, 30); num = 39; break; case 39: Caches.ReSetRecentTopicList(16); num = 40; break; case 40: Caches.EditDntConfig(); num = 41; break; case 41: Online.ResetOnlineList(); num = 42; break; case 42: Caches.ReSetNavPopupMenu(); num = -1; break; } base.Response.Write(num); base.Response.ExpiresAbsolute = DateTime.Now.AddSeconds(-1.0); base.Response.Expires = -1; base.Response.End(); } } } }
35.214286
78
0.29687
[ "MIT" ]
NewLifeX/BBX
BBX.Web.Admin/global_refreshallcache.cs
6,902
C#
using MediatR; namespace ELearning.Application.Exercises.Commands.UpdateExercise { public class UpdateExerciseCommand : IRequest { public int Id { get; set; } public string Title { get; set; } } }
20.636364
65
0.669604
[ "MIT" ]
MKafar/ELearning
ELearning.Application/Exercises/Commands/UpdateExercise/UpdateExerciseCommand.cs
229
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Anf.Platform.Test { [TestClass] public class StoreFetchSettingsTest { [TestMethod] public void NoCache_MustTagNoCahce() { var s = StoreFetchSettings.NoCache; Assert.IsTrue(s.ForceNoCache); } [TestMethod] public void DefaultCache() { var s = StoreFetchSettings.DefaultCache; Assert.IsFalse(s.ForceNoCache); Assert.AreEqual(StoreFetchSettings.DefaultExpiresTime, s.ExpiresTime); Assert.IsTrue(s.DisposeStream); } [TestMethod] public void InitWithArgs_PropertyMustEqualInput() { var t = TimeSpan.FromSeconds(10); var s = new StoreFetchSettings(true, t); Assert.IsTrue(s.ForceNoCache); Assert.AreEqual(t, s.ExpiresTime); } [TestMethod] public void Clone_AllPropertyMustEqual() { var a = new StoreFetchSettings(true, TimeSpan.FromSeconds(10)) { DisposeStream = true }; var b = a.Clone(); Assert.AreEqual(a.DisposeStream, b.DisposeStream); Assert.AreEqual(a.ExpiresTime, b.ExpiresTime); Assert.AreEqual(a.ForceNoCache, b.ForceNoCache); } } }
31.638298
101
0.597176
[ "BSD-3-Clause" ]
Cricle/Anf
test/Anf.Platform.Test/StoreFetchSettingsTest.cs
1,489
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: IEntityRequestBuilder.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; /// <summary> /// The interface IPolicyRootRequestBuilder. /// </summary> public partial interface IPolicyRootRequestBuilder : IBaseRequestBuilder { /// <summary> /// Builds the request. /// </summary> /// <returns>The built request.</returns> IPolicyRootRequest Request(); /// <summary> /// Builds the request. /// </summary> /// <param name="options">The query and header options for the request.</param> /// <returns>The built request.</returns> IPolicyRootRequest Request(IEnumerable<Option> options); /// <summary> /// Gets the request builder for AuthenticationMethodsPolicy. /// </summary> /// <returns>The <see cref="IAuthenticationMethodsPolicyRequestBuilder"/>.</returns> IAuthenticationMethodsPolicyRequestBuilder AuthenticationMethodsPolicy { get; } /// <summary> /// Gets the request builder for AuthenticationFlowsPolicy. /// </summary> /// <returns>The <see cref="IAuthenticationFlowsPolicyRequestBuilder"/>.</returns> IAuthenticationFlowsPolicyRequestBuilder AuthenticationFlowsPolicy { get; } /// <summary> /// Gets the request builder for B2cAuthenticationMethodsPolicy. /// </summary> /// <returns>The <see cref="IB2cAuthenticationMethodsPolicyRequestBuilder"/>.</returns> IB2cAuthenticationMethodsPolicyRequestBuilder B2cAuthenticationMethodsPolicy { get; } /// <summary> /// Gets the request builder for ActivityBasedTimeoutPolicies. /// </summary> /// <returns>The <see cref="IPolicyRootActivityBasedTimeoutPoliciesCollectionRequestBuilder"/>.</returns> IPolicyRootActivityBasedTimeoutPoliciesCollectionRequestBuilder ActivityBasedTimeoutPolicies { get; } /// <summary> /// Gets the request builder for AppManagementPolicies. /// </summary> /// <returns>The <see cref="IPolicyRootAppManagementPoliciesCollectionRequestBuilder"/>.</returns> IPolicyRootAppManagementPoliciesCollectionRequestBuilder AppManagementPolicies { get; } /// <summary> /// Gets the request builder for AuthorizationPolicy. /// </summary> /// <returns>The <see cref="IPolicyRootAuthorizationPolicyCollectionRequestBuilder"/>.</returns> IPolicyRootAuthorizationPolicyCollectionRequestBuilder AuthorizationPolicy { get; } /// <summary> /// Gets the request builder for ClaimsMappingPolicies. /// </summary> /// <returns>The <see cref="IPolicyRootClaimsMappingPoliciesCollectionRequestBuilder"/>.</returns> IPolicyRootClaimsMappingPoliciesCollectionRequestBuilder ClaimsMappingPolicies { get; } /// <summary> /// Gets the request builder for DefaultAppManagementPolicy. /// </summary> /// <returns>The <see cref="ITenantAppManagementPolicyRequestBuilder"/>.</returns> ITenantAppManagementPolicyRequestBuilder DefaultAppManagementPolicy { get; } /// <summary> /// Gets the request builder for HomeRealmDiscoveryPolicies. /// </summary> /// <returns>The <see cref="IPolicyRootHomeRealmDiscoveryPoliciesCollectionRequestBuilder"/>.</returns> IPolicyRootHomeRealmDiscoveryPoliciesCollectionRequestBuilder HomeRealmDiscoveryPolicies { get; } /// <summary> /// Gets the request builder for PermissionGrantPolicies. /// </summary> /// <returns>The <see cref="IPolicyRootPermissionGrantPoliciesCollectionRequestBuilder"/>.</returns> IPolicyRootPermissionGrantPoliciesCollectionRequestBuilder PermissionGrantPolicies { get; } /// <summary> /// Gets the request builder for ServicePrincipalCreationPolicies. /// </summary> /// <returns>The <see cref="IPolicyRootServicePrincipalCreationPoliciesCollectionRequestBuilder"/>.</returns> IPolicyRootServicePrincipalCreationPoliciesCollectionRequestBuilder ServicePrincipalCreationPolicies { get; } /// <summary> /// Gets the request builder for TokenIssuancePolicies. /// </summary> /// <returns>The <see cref="IPolicyRootTokenIssuancePoliciesCollectionRequestBuilder"/>.</returns> IPolicyRootTokenIssuancePoliciesCollectionRequestBuilder TokenIssuancePolicies { get; } /// <summary> /// Gets the request builder for TokenLifetimePolicies. /// </summary> /// <returns>The <see cref="IPolicyRootTokenLifetimePoliciesCollectionRequestBuilder"/>.</returns> IPolicyRootTokenLifetimePoliciesCollectionRequestBuilder TokenLifetimePolicies { get; } /// <summary> /// Gets the request builder for FeatureRolloutPolicies. /// </summary> /// <returns>The <see cref="IPolicyRootFeatureRolloutPoliciesCollectionRequestBuilder"/>.</returns> IPolicyRootFeatureRolloutPoliciesCollectionRequestBuilder FeatureRolloutPolicies { get; } /// <summary> /// Gets the request builder for AccessReviewPolicy. /// </summary> /// <returns>The <see cref="IAccessReviewPolicyRequestBuilder"/>.</returns> IAccessReviewPolicyRequestBuilder AccessReviewPolicy { get; } /// <summary> /// Gets the request builder for AdminConsentRequestPolicy. /// </summary> /// <returns>The <see cref="IAdminConsentRequestPolicyRequestBuilder"/>.</returns> IAdminConsentRequestPolicyRequestBuilder AdminConsentRequestPolicy { get; } /// <summary> /// Gets the request builder for DirectoryRoleAccessReviewPolicy. /// </summary> /// <returns>The <see cref="IDirectoryRoleAccessReviewPolicyRequestBuilder"/>.</returns> IDirectoryRoleAccessReviewPolicyRequestBuilder DirectoryRoleAccessReviewPolicy { get; } /// <summary> /// Gets the request builder for ConditionalAccessPolicies. /// </summary> /// <returns>The <see cref="IPolicyRootConditionalAccessPoliciesCollectionRequestBuilder"/>.</returns> IPolicyRootConditionalAccessPoliciesCollectionRequestBuilder ConditionalAccessPolicies { get; } /// <summary> /// Gets the request builder for IdentitySecurityDefaultsEnforcementPolicy. /// </summary> /// <returns>The <see cref="IIdentitySecurityDefaultsEnforcementPolicyRequestBuilder"/>.</returns> IIdentitySecurityDefaultsEnforcementPolicyRequestBuilder IdentitySecurityDefaultsEnforcementPolicy { get; } /// <summary> /// Gets the request builder for MobileAppManagementPolicies. /// </summary> /// <returns>The <see cref="IPolicyRootMobileAppManagementPoliciesCollectionRequestBuilder"/>.</returns> IPolicyRootMobileAppManagementPoliciesCollectionRequestBuilder MobileAppManagementPolicies { get; } /// <summary> /// Gets the request builder for MobileDeviceManagementPolicies. /// </summary> /// <returns>The <see cref="IPolicyRootMobileDeviceManagementPoliciesCollectionRequestBuilder"/>.</returns> IPolicyRootMobileDeviceManagementPoliciesCollectionRequestBuilder MobileDeviceManagementPolicies { get; } /// <summary> /// Gets the request builder for RoleManagementPolicies. /// </summary> /// <returns>The <see cref="IPolicyRootRoleManagementPoliciesCollectionRequestBuilder"/>.</returns> IPolicyRootRoleManagementPoliciesCollectionRequestBuilder RoleManagementPolicies { get; } /// <summary> /// Gets the request builder for RoleManagementPolicyAssignments. /// </summary> /// <returns>The <see cref="IPolicyRootRoleManagementPolicyAssignmentsCollectionRequestBuilder"/>.</returns> IPolicyRootRoleManagementPolicyAssignmentsCollectionRequestBuilder RoleManagementPolicyAssignments { get; } } }
48.988506
153
0.683599
[ "MIT" ]
microsoftgraph/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Generated/requests/IPolicyRootRequestBuilder.cs
8,524
C#
using Core.DataAccess.EntityFramework; using DataAccess.Abstract; using Entities.Concrete; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DataAccess.Concrete.EntityFramework { public class EfCarImageDal:EfEntityRepositoryBase<CarImage,ECommerceContext>,ICarImageDal { } }
22.8125
93
0.813699
[ "MIT" ]
baristutakli/ReCapProject
DataAccess/Concrete/EntityFramework/EfCarImageDal.cs
367
C#
using CSharpFunctionalExtensions; using DeUrgenta.Admin.Api.Models; using DeUrgenta.Common.Models.Events; using DeUrgenta.Common.Validation; using MediatR; namespace DeUrgenta.Admin.Api.Commands { public class CreateEvent : IRequest<Result<EventResponseModel, ValidationResult>> { public EventRequest Event { get; } public CreateEvent(EventRequest eventRequest) { Event = eventRequest; } } }
23.736842
85
0.711752
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
Alexei000/de-urgenta-backend
Src/DeUrgenta.Admin.Api/Commands/CreateEvent.cs
453
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Hatfield.EnviroData.Core { using System; using System.Collections.Generic; public partial class SpatialReferenceExternalIdentifier { public int BridgeID { get; set; } public int SpatialReferenceID { get; set; } public int ExternalIdentifierSystemID { get; set; } public string SpatialReferenceExternalIdentifier1 { get; set; } public string SpatialReferenceExternalIdentifierURI { get; set; } public virtual ExternalIdentifierSystem ExternalIdentifierSystem { get; set; } public virtual SpatialReference SpatialReference { get; set; } } }
40.185185
87
0.58341
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
HatfieldConsultants/Hatfield.EnviroData.Core
Source/Hatfield.EnviroData.Core/SpatialReferenceExternalIdentifier.cs
1,085
C#
// This software is part of the Autofac IoC container // Copyright © 2013 Autofac Contributors // http://autofac.org // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. using System; using System.Linq; using Autofac.Integration.SignalR; using Microsoft.AspNet.SignalR; using Microsoft.AspNet.SignalR.Messaging; using Moq; using NUnit.Framework; namespace Autofac.Tests.Integration.SignalR { [TestFixture] public class AutofacDependencyResolverFixture { [Test] public void CurrentPropertyExposesTheCorrectResolver() { var container = new ContainerBuilder().Build(); var resolver = new AutofacDependencyResolver(container); GlobalHost.DependencyResolver = resolver; Assert.That(AutofacDependencyResolver.Current, Is.EqualTo(GlobalHost.DependencyResolver)); } [Test] public void NullLifetimeScopeThrowsException() { var exception = Assert.Throws<ArgumentNullException>( () => new AutofacDependencyResolver(null)); Assert.That(exception.ParamName, Is.EqualTo("lifetimeScope")); } [Test] public void ProvidedLifetimeScopeExposed() { var container = new ContainerBuilder().Build(); var dependencyResolver = new AutofacDependencyResolver(container); Assert.That(dependencyResolver.LifetimeScope, Is.EqualTo(container)); } [Test] public void GetServiceReturnsNullForUnregisteredService() { var container = new ContainerBuilder().Build(); var resolver = new AutofacDependencyResolver(container); var service = resolver.GetService(typeof(object)); Assert.That(service, Is.Null); } [Test] public void GetServiceReturnsRegisteredService() { var builder = new ContainerBuilder(); builder.Register(c => new object()); var container = builder.Build(); var resolver = new AutofacDependencyResolver(container); var service = resolver.GetService(typeof(object)); Assert.That(service, Is.Not.Null); } [Test] public void GetServicesReturnsNullForUnregisteredService() { var container = new ContainerBuilder().Build(); var resolver = new AutofacDependencyResolver(container); var services = resolver.GetServices(typeof(object)); Assert.That(services, Is.EqualTo(null)); } [Test] public void GetServicesReturnsRegisteredService() { var builder = new ContainerBuilder(); builder.Register(c => new object()); var container = builder.Build(); var resolver = new AutofacDependencyResolver(container); var services = resolver.GetServices(typeof(object)); Assert.That(services.Count(), Is.EqualTo(1)); } [Test] public void CanResolveDefaultServices() { var container = new ContainerBuilder().Build(); var resolver = new AutofacDependencyResolver(container); var service = resolver.GetService(typeof(IMessageBus)); Assert.That(service, Is.InstanceOf<IMessageBus>()); } [Test] public void CanOverrideDefaultServices() { var builder = new ContainerBuilder(); var messageBus = new Mock<IMessageBus>().Object; builder.RegisterInstance(messageBus); var resolver = new AutofacDependencyResolver(builder.Build()); var service = resolver.GetService(typeof(IMessageBus)); Assert.That(service, Is.SameAs(messageBus)); } } }
35.5
103
0.636016
[ "MIT" ]
OrchardCMS/Autofac
Core/Tests/Autofac.Tests.Integration.SignalR/AutofacDependencyResolverFixture.cs
4,973
C#
using System.Collections; using System.Collections.Generic; using Unity.Collections; using Unity.Jobs; using UnityEngine; public class Boid : MonoBehaviour { BoidSettings settings; // State [HideInInspector] public Vector3 position; [HideInInspector] public Vector3 forward; Vector3 velocity; public enum CheckState { NeedUpdate, Updated } public CheckState checkState = CheckState.NeedUpdate; Vector3 accelerate; // To update: Vector3 acceleration; [HideInInspector] public Vector3 avgFlockHeading; [HideInInspector] public Vector3 avgAvoidanceHeading; [HideInInspector] public Vector3 centreOfFlockmates; [HideInInspector] public int numPerceivedFlockmates; // Cached Material material; Transform cachedTransform; Transform target; static int batchSize = 100; void Awake() { material = transform.GetComponentInChildren<MeshRenderer>().material; cachedTransform = transform; } public void Initialize(BoidSettings settings, Transform target) { this.target = target; this.settings = settings; position = cachedTransform.position; forward = cachedTransform.forward; float startSpeed = (settings.minSpeed + settings.maxSpeed) / 2; velocity = transform.forward * startSpeed; } public void SetColour(Color col) { if (material != null) { material.color = col; } } public void UpdateBoid() { Vector3 acceleration = Vector3.zero; if (target != null) { Vector3 offsetToTarget = (target.position - position); acceleration = SteerTowards(offsetToTarget) * settings.targetWeight; } if (numPerceivedFlockmates != 0) { centreOfFlockmates /= numPerceivedFlockmates; Vector3 offsetToFlockmatesCentre = (centreOfFlockmates - position); var alignmentForce = SteerTowards(avgFlockHeading) * settings.alignWeight; var cohesionForce = SteerTowards(offsetToFlockmatesCentre) * settings.cohesionWeight; var seperationForce = SteerTowards(avgAvoidanceHeading) * settings.seperateWeight; acceleration += alignmentForce; acceleration += cohesionForce; acceleration += seperationForce; } if (IsHeadingForCollision()) { Vector3 collisionAvoidDir = ObstacleRaysJob(); // Vector3 collisionAvoidDir = ObstacleRays (); Vector3 collisionAvoidForce = SteerTowards(collisionAvoidDir) * settings.avoidCollisionWeight; acceleration += collisionAvoidForce; } velocity += acceleration * Time.deltaTime; float speed = velocity.magnitude; Vector3 dir = velocity / speed; speed = Mathf.Clamp(speed, settings.minSpeed, settings.maxSpeed); velocity = dir * speed; cachedTransform.position += velocity * Time.deltaTime; cachedTransform.forward = dir; position = cachedTransform.position; forward = dir; } public static int FirstCheck(Boid[] boids){ int count = boids.Length; var results = new NativeArray<RaycastHit>(count, Allocator.TempJob); var commands = new NativeArray<SpherecastCommand>(count, Allocator.TempJob); for(int i = 0; i < boids.Length; i++){ commands[i] = new SpherecastCommand( boids[i].position, boids[i].settings.boundsRadius, boids[i].forward, boids[i].settings.collisionAvoidDst, boids[i].settings.obstacleMask ); } JobHandle handle = SpherecastCommand.ScheduleBatch(commands, results, batchSize, default(JobHandle)); // Wait for the batch processing job to complete handle.Complete(); // Copy the result. If batchedHit.collider is null there was no hit for (int i = 0; i < boids.Length; i++) { if (results[i].collider == null) { boids[i].checkState = CheckState.Updated; boids[i].accelerate = Vector3.zero; count--; } else { boids[i].checkState = CheckState.NeedUpdate; } } // Dispose the buffers results.Dispose(); commands.Dispose(); return count; } public static void avoidProcess(Boid[] boids) { int count = FirstCheck(boids); int index = 0; int[] map = new int[count]; while(count > 0 && index < BoidHelper.directions.Length){ Vector3 rayDirection = BoidHelper.directions[index]; var results = new NativeArray<RaycastHit>(count, Allocator.TempJob); var commands = new NativeArray<SpherecastCommand>(count, Allocator.TempJob); int cmdId = 0; for (int i = 0; i < boids.Length; i++) { if(boids[i].checkState == CheckState.Updated){ continue; } Vector3 dir = boids[i].cachedTransform.TransformDirection(rayDirection); map[cmdId] = i; commands[cmdId] = new SpherecastCommand( boids[i].position, boids[i].settings.boundsRadius, dir, boids[i].settings.collisionAvoidDst, boids[i].settings.obstacleMask ); cmdId++; } // Schedule the batch of raycasts JobHandle handle = SpherecastCommand.ScheduleBatch(commands, results, batchSize, default(JobHandle)); // Wait for the batch processing job to complete handle.Complete(); int currentCount = count; // Copy the result. If batchedHit.collider is null there was no hit for (int i = 0; i < currentCount; i++) { int mapId = map[i]; if (results[i].collider == null) { boids[mapId].checkState = CheckState.Updated; boids[mapId].accelerate = boids[mapId].cachedTransform.TransformDirection(rayDirection); count--; break; } } // Dispose the buffers results.Dispose(); commands.Dispose(); index++; } } public static void updateBoids(Boid[] boids) { avoidProcess(boids); for (int i = 0; i < boids.Length; i++) { var boid = boids[i]; Vector3 acceleration = Vector3.zero; if (boid.target != null) { Vector3 offsetToTarget = (boid.target.position - boid.position); acceleration = boid.SteerTowards(offsetToTarget) * boid.settings.targetWeight; } if (boid.numPerceivedFlockmates != 0) { boid.centreOfFlockmates /= boid.numPerceivedFlockmates; Vector3 offsetToFlockmatesCentre = (boid.centreOfFlockmates - boid.position); var alignmentForce = boid.SteerTowards(boid.avgFlockHeading) * boid.settings.alignWeight; var cohesionForce = boid.SteerTowards(offsetToFlockmatesCentre) * boid.settings.cohesionWeight; var seperationForce = boid.SteerTowards(boid.avgAvoidanceHeading) * boid.settings.seperateWeight; acceleration += alignmentForce; acceleration += cohesionForce; acceleration += seperationForce; } if(boid.accelerate.magnitude > 0){ acceleration += boid.SteerTowards(boid.accelerate) * boid.settings.avoidCollisionWeight; } // Debug.Log(boid.accelerate); boid.velocity += acceleration * Time.deltaTime; float speed = boid.velocity.magnitude; Vector3 dir = boid.velocity / speed; speed = Mathf.Clamp(speed, boid.settings.minSpeed, boid.settings.maxSpeed); boid.velocity = dir * speed; boid.cachedTransform.position += boid.velocity * Time.deltaTime; boid.cachedTransform.forward = dir; boid.position = boid.cachedTransform.position; boid.forward = dir; } } bool IsHeadingForCollision() { RaycastHit hit; if (Physics.SphereCast(position, settings.boundsRadius, forward, out hit, settings.collisionAvoidDst, settings.obstacleMask)) { return true; } else { } return false; } Vector3 ObstacleRays () { Vector3[] rayDirections = BoidHelper.directions; for (int i = 0; i < rayDirections.Length; i++) { Vector3 dir = cachedTransform.TransformDirection (rayDirections[i]); Ray ray = new Ray (position, dir); if (!Physics.SphereCast (ray, settings.boundsRadius, settings.collisionAvoidDst, settings.obstacleMask)) { return dir; } } return forward; } private Vector3 ObstacleRaysJob() { Vector3[] rayDirections = BoidHelper.directions; int count = rayDirections.Length; // count = 1; // Perform a single raycast using RaycastCommand and wait for it to complete // Setup the command and result buffers var results = new NativeArray<RaycastHit>(count, Allocator.TempJob); // var commands = new NativeArray<RaycastCommand>(count, Allocator.TempJob); var commands = new NativeArray<SpherecastCommand>(count, Allocator.TempJob); // Set the data of the first command Vector3 origin = position; for (int i = 0; i < count; i++) { Vector3 dir = cachedTransform.TransformDirection(rayDirections[i]); Vector3 direction = dir; commands[i] = new SpherecastCommand(origin, settings.boundsRadius, direction, settings.collisionAvoidDst, settings.obstacleMask); } // Schedule the batch of raycasts JobHandle handle = SpherecastCommand.ScheduleBatch(commands, results, batchSize, default(JobHandle)); // Wait for the batch processing job to complete handle.Complete(); Vector3 result = forward; // Copy the result. If batchedHit.collider is null there was no hit for (int i = 0; i < count; i++) { if (results[i].collider == null) { result = cachedTransform.TransformDirection(rayDirections[i]); break; } } // Dispose the buffers results.Dispose(); commands.Dispose(); return result; } Vector3 SteerTowards(Vector3 vector) { Vector3 v = vector.normalized * settings.maxSpeed - velocity; return Vector3.ClampMagnitude (v, settings.maxSteerForce); } }
33.170659
141
0.590487
[ "MIT" ]
SiyaoHuang/Boids
Assets/Scripts/Boid.cs
11,081
C#
using System; using System.Diagnostics; using Serilog.Core; using Serilog.Events; using Xunit.Abstractions; namespace Milou.Deployer.Tests.Integration { public class TestSink : ILogEventSink { private readonly IFormatProvider _formatProvider; private readonly ITestOutputHelper _helper; public TestSink(IFormatProvider formatProvider, ITestOutputHelper helper) { _formatProvider = formatProvider; _helper = helper; } public void Emit(LogEvent logEvent) { string message = logEvent.RenderMessage(_formatProvider); string actualMessage = message ?? logEvent.MessageTemplate.Render(logEvent.Properties); string line = $"[{logEvent.Level}] {actualMessage}"; Debug.WriteLine(line); _helper.WriteLine(line); if (logEvent.Exception != null) { string format = logEvent.Exception.ToString(); _helper.WriteLine(format); Debug.WriteLine(format); } } } }
28.051282
99
0.620658
[ "MIT" ]
bjorkblom/milou.deployer
src/Milou.Deployer.Tests.Integration/TestSink.cs
1,096
C#
// Copyright (c) 2020, UW Medicine Research IT, University of Washington // Developed by Nic Dobbins and Cliff Spital, CRIO Sean Mooney // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. using System; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Model.Authorization; using System.Text.RegularExpressions; namespace Model.Notification { public class NotificationManager { readonly Regex HTML_TAGS = new Regex("<(?:[^><\"\']*?(?:([\"\']).*?\\1)?[^><\'\"]*?)+(?:>|$)"); public interface INotificationService { Task<bool> NotifyAsync(string subject, string content, ContentType contentType); } public enum ContentType { Html = 1, PlainText = 2 } readonly INotificationService svc; readonly IUserContext user; readonly ILogger<NotificationManager> log; public NotificationManager(INotificationService service, ILogger<NotificationManager> log, IUserContext user) { svc = service; this.log = log; this.user = user; } public async Task<bool> SendUserInquiry(UserInquiry inquiry) { log.LogInformation("Sending user inquiry. Inquiry:{@Inquiry}", inquiry); // Strip any possible HTML from malicious users and // replace newlines with HTML line breaks var text = HTML_TAGS.Replace(inquiry.Text, "").Replace("\n", "</br>"); var typeText = inquiry.Type == UserInquiry.UserInquiryType.DataRequest ? "Data Request" : inquiry.Type == UserInquiry.UserInquiryType.HelpMakingQuery ? "Help in making query" : "Other"; var subject = @"Leaf User Question Received"; var body = $@" <html> <head> <meta http-equiv='Content-Type' content='text/html; charset=utf-8'> </head> <body style='font-family:arial,helvetica;font-size:10pt;'> [This message was automatically generated by Leaf] </br> </br> This email is to notify you that user <b>{user.Identity}</b> ({inquiry.EmailAddress}) has asked the following question: </br> </br> <span><b>Request Type</b>: {typeText}</span></br> </br> <span>""{text}""</span> </body> </html>"; await svc.NotifyAsync(subject, body, ContentType.Html); return true; } } }
39.616438
150
0.548409
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
BayesianGraph/leaf
src/server/Model/Notification/NotificationManager.cs
2,894
C#
using System.Collections.Generic; using System.ComponentModel; using PropertyChanged; public abstract class ObservableTestObject : INotifyPropertyChanged { [DoNotNotify] public IList<string> PropertyChangedCalls { get; } = new List<string>(); public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged(string propertyName) { PropertyChangedCalls.Add(propertyName); PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } }
29.333333
82
0.768939
[ "MIT" ]
Dresel/PropertyChanged
TestAssemblies/AssemblyToProcess/WithInitializedProperties/ObservableTestObject.cs
530
C#
using System.Threading.Tasks; using BoutiqueCommon.Models.Domain.Interfaces.Identities; using ResultFunctional.Models.Interfaces.Results; namespace BoutiqueXamarinCommon.Infrastructure.Interfaces.Authorize { /// <summary> /// Сервис авторизации и сохранения логина /// </summary> public interface ILoginService { /// <summary> /// Авторизоваться через токен JWT /// </summary> Task<IResultError> Login(IAuthorizeDomain authorize); } }
28.941176
67
0.703252
[ "MIT" ]
rubilnik4/VeraBoutique
BoutiqueXamarinCommon/Infrastructure/Interfaces/Authorize/ILoginService.cs
552
C#
using System; using System.Collections.Generic; using System.Text; namespace ProductManagement.Core.CrossCuttingConcerns.Caching { public interface ICacheService { T Get<T>(string key); object Get(string key); void Add(string key, object data, int duration); bool IsAdd(string key); void Remove(string key); void RemoveByPattern(string pattern); } }
16.814815
61
0.612335
[ "MIT" ]
mustafafindik/ProductManagement
ProductManagement.Core/CrossCuttingConcerns/Caching/ICacheService.cs
456
C#
using System.Web.Mvc; using Ignition.Core.Mvc; namespace Ignition.Sc.Components.News { public class NewsController : IgnitionController { public ActionResult NewsGrid() => View<NewsGridViewModel>(); public ActionResult FeaturedNews() => View<FeaturedNewsAgent, FeaturedNewsViewModel>(); public ActionResult LatestNews() => View<LatestNewsAgent, LatestNewsViewModel>(); } }
29.428571
95
0.723301
[ "MIT" ]
Ali-Nasir-01/SitecoreIgnition
Ignition.Sc/Components/News/NewsController.cs
414
C#
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.ServiceModel.Channels { using System; using System.ServiceModel.Channels; using System.Xml; [Serializable] public class RedirectionLocation { // For Serialization private RedirectionLocation() { } public RedirectionLocation(Uri address) { if (address == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("address"); } if (!address.IsAbsoluteUri) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("address", SR.GetString(SR.UriMustBeAbsolute)); } //Xml schema anyUri can be either relative or absolute... this.Address = address; } public Uri Address { get; private set; } } }
28.5
124
0.531189
[ "Apache-2.0" ]
295007712/295007712.github.io
sourceCode/dotNet4.6/ndp/cdf/src/WCF/ServiceModel/System/ServiceModel/Channels/RedirectionLocation.cs
1,026
C#
using System.Windows; using System.Windows.Input; using MahApps.Metro.Controls; namespace Forge.Forms.Controls { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class DialogWindow : MetroWindow { public DialogWindow(object model, object context, WindowOptions options) { DataContext = options; InitializeComponent(); Loaded += (sender, e) => { MoveFocus(new TraversalRequest(FocusNavigationDirection.Next)); }; Form.Environment.Add(options.EnvironmentFlags); Form.Context = context; Form.Model = model; } private void CloseDialogCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e) { DialogResult = e.Parameter as bool?; Close(); } private void CloseDialogCommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = true; } } }
23.026316
95
0.726857
[ "MIT" ]
BenjaminSieg/Forge.Forms
Forge.Forms/src/Forge.Forms/Controls/DialogWindow.xaml.cs
877
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Agent.ViewModel.Util { class BatchedObservableCollection<T> : ObservableCollection<T> { public void AddRange(IEnumerable<T> seq) => InsertRange(seq, -1); public void InsertRange(IEnumerable<T> seq, int index) { if (seq == null) throw new ArgumentNullException(nameof(seq)); CheckReentrancy(); var items = Items; var newItems = seq.ToList(); if (newItems.Count == 0) return; if (index == -1) index = Count; var curr = index; foreach (var el in newItems) items.Insert(curr++, el); OnPropertyChanged(new PropertyChangedEventArgs(CountString)); OnPropertyChanged(new PropertyChangedEventArgs(IndexerName)); OnCollectionChanged( new NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction.Add, newItems, index)); } public void RemoveAll(IEnumerable<T> seq) { if (seq == null) throw new ArgumentNullException(nameof(seq)); CheckReentrancy(); var items = Items; var removedItems = new List<T>(); foreach (var el in seq) { int index = items.IndexOf(el); if (index < 0) continue; removedItems.Add(el); items.RemoveAt(index); } if (removedItems.Count == 0) return; OnPropertyChanged(new PropertyChangedEventArgs(CountString)); OnPropertyChanged(new PropertyChangedEventArgs(IndexerName)); OnCollectionChanged( new NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction.Remove, removedItems)); } public void ReplaceRange(List<T> remSeq, IEnumerable<T> addSeq) { if (remSeq == null) throw new ArgumentNullException(nameof(remSeq)); if (addSeq == null) throw new ArgumentNullException(nameof(addSeq)); CheckReentrancy(); int idxToAdd = -1; var items = Items; var removedItems = new List<T>(); foreach (var el in remSeq) { int index = items.IndexOf(el); if (index < 0) continue; if (idxToAdd < 0) idxToAdd = index; removedItems.Add(el); items.RemoveAt(index); } if (idxToAdd < 0) idxToAdd = Count; var indexSave = idxToAdd; var newItems = addSeq.ToList(); foreach (var el in newItems) items.Insert(idxToAdd++, el); if (removedItems.Count == 0 && newItems.Count == 0) return; if (removedItems.Count != newItems.Count) OnPropertyChanged(new PropertyChangedEventArgs(CountString)); OnPropertyChanged(new PropertyChangedEventArgs(IndexerName)); OnCollectionChanged( new NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction.Replace, newItems, removedItems, indexSave)); } public void MoveRange(List<T> itemsToMove, int newIndex) { if (itemsToMove == null) throw new ArgumentNullException(nameof(itemsToMove)); CheckReentrancy(); var items = Items; var temporaryItems = new List<T>(); foreach (var el in itemsToMove) { int index = items.IndexOf(el); if (index < 0) continue; temporaryItems.Add(el); items.RemoveAt(index); } if (temporaryItems.Count == 0) return; if (newIndex == -1) newIndex = Count; var currentIndex = newIndex; foreach (var el in temporaryItems) items.Insert(currentIndex++, el); OnPropertyChanged(new PropertyChangedEventArgs(IndexerName)); OnCollectionChanged( new NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction.Move, temporaryItems, newIndex)); } public void Reset(IEnumerable<T> seq) { if (seq == null) throw new ArgumentNullException(nameof(seq)); CheckReentrancy(); var items = Items; var oldCount = items.Count; items.Clear(); foreach (var el in seq) items.Add(el); if (oldCount != items.Count) OnPropertyChanged(new PropertyChangedEventArgs(CountString)); OnPropertyChanged(new PropertyChangedEventArgs(IndexerName)); OnCollectionChanged( new NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction.Reset)); } // это грязный хак, который подсмотрен здесь: // http://geekswithblogs.net/NewThingsILearned/archive/2008/01/16/listcollectionviewcollectionview-doesnt-support-notifycollectionchanged-with-multiple-items.aspx // он обходит проблему с контролом CollectionView, который не умеет обрабатывать // неодноэлементные изменения public override event NotifyCollectionChangedEventHandler CollectionChanged; protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e) { var handlers = CollectionChanged; if (handlers != null) { using (BlockReentrancy()) { foreach (NotifyCollectionChangedEventHandler handler in handlers.GetInvocationList()) { if (handler.Target is System.Windows.Data.CollectionView cv) cv.Refresh(); else handler(this, e); } } } } private const string CountString = "Count"; private const string IndexerName = "Item[]"; } }
36.234973
170
0.541246
[ "MIT" ]
arrer/WarframeAgent
Agent/Agent/ViewModel/Util/BatchedObservableCollection.cs
6,746
C#
using System.Collections.Generic; using UnityEngine; using System.Text; #if UNITY_EDITOR using UnityEditor; #endif namespace Kayac { public class ObjFileWriter { public static string ToText(Mesh mesh, int subMeshIndex) { var sb = new StringBuilder(); var uv = mesh.uv; bool hasUv = (uv != null) && (uv.Length == mesh.vertexCount); ToTextVertices(sb, mesh.vertices, uv, mesh.normals); ToTextFaces(sb, mesh.GetIndices(subMeshIndex), hasUv, subMeshIndex.ToString(), vertexIndexOffset: 1); // objは1から return sb.ToString(); } // サブメッシュ結合書き出し public static string ToText(Mesh mesh) { var sb = new StringBuilder(); var uv = mesh.uv; bool hasUv = (uv != null) && (uv.Length == mesh.vertexCount); ToTextVertices(sb, mesh.vertices, uv, mesh.normals); for (int i = 0; i < mesh.subMeshCount; i++) { ToTextFaces(sb, mesh.GetIndices(i), hasUv, i.ToString(), vertexIndexOffset: 1); // objは1から } return sb.ToString(); } public static string ToText( IList<Vector3> positions, IList<Vector2> uvs, IList<Vector3> normals, IList<int> indices) { var sb = new StringBuilder(); bool hasUv = (uvs != null) && (uvs.Count == positions.Count); ToTextVertices(sb, positions, uvs, normals); ToTextFaces(sb, indices, hasUv, "unnamed", vertexIndexOffset: 1); // objは1から return sb.ToString(); } #if UNITY_EDITOR [MenuItem("GameObject/Save .obj recursive", false, 20)] public static void SaveObjRecursive() { var selected = Selection.activeObject; var gameObject = selected as GameObject; Write("Assets", gameObject, importImmediately: true); } [MenuItem("GameObject/Save .obj recursive", true)] public static bool ValidateSaveObjRecursive() { var ret = false; var active = Selection.activeObject; if (active != null) { ret = (active.GetType() == typeof(GameObject)); } return ret; } [MenuItem("Assets/Save .obj")] public static void Save() { var selected = Selection.activeObject; var mesh = selected as Mesh; if (mesh == null) { Debug.LogError("selected object is not mesh. type=" + selected.GetType().Name); return; } var originalPath = AssetDatabase.GetAssetPath(mesh); var dir = System.IO.Path.GetDirectoryName(originalPath); Write(dir, mesh, importImmediately: true); } [MenuItem("Assets/Save .obj", true)] public static bool ValidateSave() { var ret = false; var active = Selection.activeObject; if (active != null) { ret = (active.GetType() == typeof(Mesh)); } return ret; } [MenuItem("CONTEXT/MeshFilter/Save .obj")] public static void SaveObjFromInspector(MenuCommand menuCommand) { var meshFilter = menuCommand.context as MeshFilter; if (meshFilter != null) { var mesh = meshFilter.sharedMesh; if (mesh != null) { Write("Assets", mesh, importImmediately: true); } } } public static bool Write( string directory, Mesh mesh, bool importImmediately = false) { Debug.Assert(mesh != null); var name = mesh.name; if (string.IsNullOrEmpty(name)) { name = "unnamed.obj"; } else { name += ".obj"; } var path = System.IO.Path.Combine(directory, name); var text = ToText(mesh); return Write(path, text, importImmediately); } public static bool Write( string directory, Mesh mesh, int subMeshIndex, bool importImmediately = false) { Debug.Assert(mesh != null); var name = mesh.name; if (string.IsNullOrEmpty(name)) { name = "unnamed"; } name += "_" + subMeshIndex + ".obj"; var path = System.IO.Path.Combine(directory, name); var text = ToText(mesh); return Write(path, text, importImmediately); } public static bool Write( string directory, GameObject gameObject, bool importImmediately = false) { Debug.Assert(gameObject != null); var items = new List<MergedItem>(); if (gameObject != null) { CollectMeshesRecursive(items, gameObject, Matrix4x4.identity); } var name = gameObject.name; if (string.IsNullOrEmpty(name)) { name = "unnamed"; } name += ".obj"; var path = System.IO.Path.Combine(directory, name); var text = ToText(items); return Write(path, text, importImmediately); } public static bool Write( string path, IList<Vector3> positions, IList<Vector2> uvs, IList<Vector3> normals, IList<int> indices, bool importImmediately = false) { var text = ToText(positions, uvs, normals, indices); return Write(path, text, importImmediately); } // おまけ。 TODO: Objと何の関係もないので、別ファイルが望ましい。 [MenuItem("CONTEXT/MeshFilter/Save .asset")] public static void SaveAssetFromInspector(MenuCommand menuCommand) { var meshFilter = menuCommand.context as MeshFilter; if (meshFilter != null) { var mesh = meshFilter.sharedMesh; if (mesh != null) { var path = string.Format("Assets/{0}.asset", mesh.name); AssetDatabase.CreateAsset(mesh, path); AssetDatabase.SaveAssets(); // これがないと中身が空になる仕様らしい } } } // non-public ------------------ struct MergedItem { public Mesh mesh; public Matrix4x4 matrix; } static void ToTextVertices( StringBuilder sb, IList<Vector3> positions, IList<Vector2> uvs, IList<Vector3> normals) { Debug.Assert(positions != null); sb.AppendFormat("Generated by Kayac.ObjFileWriter. {0} vertices\n", positions.Count); sb.AppendLine("# positions"); foreach (var item in positions) { sb.AppendFormat("v {0} {1} {2}\n", item.x.ToString("F8"), //精度指定しないとfloat精度の全体を吐かないので劣化してしまう。10進8桁必要 item.y.ToString("F8"), item.z.ToString("F8")); } bool hasUv = (uvs != null) && (uvs.Count > 0); if (hasUv) { Debug.Assert(uvs.Count == positions.Count); sb.AppendLine("\n# texcoords"); foreach (var item in uvs) { sb.AppendFormat("vt {0} {1}\n", item.x.ToString("F8"), item.y.ToString("F8")); } } Debug.Assert(normals != null); sb.AppendLine("\n# normals"); foreach (var item in normals) { sb.AppendFormat("vn {0} {1} {2}\n", item.x.ToString("F8"), item.y.ToString("F8"), item.z.ToString("F8")); } } static void ToTextFaces( StringBuilder sb, IList<int> indices, bool hasUv, string materialName, int vertexIndexOffset) { Debug.Assert(indices != null); Debug.Assert((indices.Count % 3) == 0); sb.AppendLine("\nusemtl " + materialName); sb.AppendLine("# triangle faces"); for (var i = 0; i < indices.Count; i += 3) { var i0 = indices[i + 0] + vertexIndexOffset; // 1 based index. var i1 = indices[i + 1] + vertexIndexOffset; var i2 = indices[i + 2] + vertexIndexOffset; if (hasUv) { sb.AppendFormat("f {0}/{0}/{0} {1}/{1}/{1} {2}/{2}/{2}\n", i0, i1, i2); } else { sb.AppendFormat("f {0}//{0} {1}//{1} {2}//{2}\n", i0, i1, i2); } } } static void CollectMeshesRecursive(List<MergedItem> items, GameObject gameObject, Matrix4x4 matrix) { var transform = gameObject.transform; var localMatrix = Matrix4x4.TRS( transform.localPosition, transform.localRotation, transform.localScale); matrix = matrix * localMatrix; var meshFilter = gameObject.GetComponent<MeshFilter>(); if (meshFilter != null) { MergedItem item; item.mesh = meshFilter.sharedMesh; item.matrix = matrix; items.Add(item); } for (int i = 0; i < transform.childCount; i++) { CollectMeshesRecursive(items, transform.GetChild(i).gameObject, matrix); } } static bool Write(string path, string objFileText, bool importImmediately) { bool ret = false; try { System.IO.File.WriteAllText(path, objFileText); if (importImmediately) { UnityEditor.AssetDatabase.ImportAsset(path, UnityEditor.ImportAssetOptions.Default); } ret = true; } catch (System.Exception e) { Debug.LogException(e); } return ret; } // メッシュマージしつつ書き出し static string ToText(IList<MergedItem> items) { var sb = new StringBuilder(); // まず全メッシュ全頂点結合。オフセットテーブル生成 var vertices = new List<Vector3>(); var uvs = new List<Vector2>(); var normals = new List<Vector3>(); var vertexIndexOffsets = new int[items.Count + 1]; // 特別処理を避けるために+1 vertexIndexOffsets[0] = 1; // objは1から var hasUv = true; for (int i = 0; i < items.Count; i++) { TransformVertices(vertices, normals, items[i]); var mesh = items[i].mesh; var meshUv = mesh.uv; if ((meshUv == null) || (meshUv.Length < mesh.vertexCount)) { hasUv = false; uvs = null; } if (hasUv) { uvs.AddRange(meshUv); } vertexIndexOffsets[i + 1] = vertexIndexOffsets[i] + mesh.vertexCount; } ToTextVertices(sb, vertices, uvs, normals); for (int meshIndex = 0; meshIndex < items.Count; meshIndex++) { var item = items[meshIndex]; var mesh = item.mesh; var meshName = mesh.name; if (string.IsNullOrEmpty(meshName)) { meshName = meshIndex.ToString() + "_"; } for (int subMeshIndex = 0; subMeshIndex < mesh.subMeshCount; subMeshIndex++) { ToTextFaces( sb, mesh.GetIndices(subMeshIndex), hasUv, meshName + subMeshIndex.ToString(), vertexIndexOffsets[meshIndex]); } } return sb.ToString(); } static void TransformVertices(List<Vector3> verticesOut, List<Vector3> normalsOut, MergedItem item) { var mesh = item.mesh; var vertexCount = mesh.vertexCount; var vertices = mesh.vertices; var normals = mesh.normals; var matrix = item.matrix; for (int i = 0; i < vertexCount; i++) { var v = matrix.MultiplyPoint3x4(vertices[i]); var n = matrix.MultiplyVector(normals[i]); verticesOut.Add(v); normalsOut.Add(n); } } #endif } }
26.245524
116
0.613331
[ "MIT" ]
hiryma/UnitySamples
MeshDestruction/Assets/Kayac/Graphics/ObjFileWriter.cs
10,562
C#
/* * Copyright 2013-2018 Guardtime, Inc. * * This file is part of the Guardtime client SDK. * * 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, CONDITIONS, OR OTHER LICENSES OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * "Guardtime" and "KSI" are trademarks or registered trademarks of * Guardtime, Inc., and no license to trademarks is granted; Guardtime * reserves and retains all trademark rights. */ using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Threading; using Guardtime.KSI.Exceptions; using Guardtime.KSI.Hashing; using Guardtime.KSI.Parser; using Guardtime.KSI.Service; using Guardtime.KSI.Service.HighAvailability; using Guardtime.KSI.Signature; using Guardtime.KSI.Test.Properties; using Guardtime.KSI.Utils; using NUnit.Framework; namespace Guardtime.KSI.Test.Service.HighAvailability { [TestFixture] public class HAAggregatorConfigStaticTests : StaticServiceTestsBase { [Test] public void HAAggregatorConfigRequestWithSingleServiceTest() { // Test getting aggregator configuration with single sub-service IKsiService haService = GetHAService( new List<PduPayload>() { GetAggregatorConfigResponsePayload(1, 2, 100, 4, new List<string>() { "uri-1" }) }); haService.GetAggregatorConfig(); AggregatorConfig config = haService.GetAggregatorConfig(); Assert.AreEqual(1, config.MaxLevel, "Unexpected max level value"); Assert.AreEqual(2, config.AggregationAlgorithm, "Unexpected algorithm value"); Assert.AreEqual(100, config.AggregationPeriod, "Unexpected aggregation period value"); Assert.AreEqual(4, config.MaxRequests, "Unexpected max requests value"); Assert.AreEqual(1, config.ParentsUris.Count, "Unexpected parent uri count"); Assert.AreEqual("uri-1", config.ParentsUris[0], "Unexpected parent uri value at position 0"); } [Test] public void HAAggregatorConfigRequestTest() { // Test getting aggregator configuration with 1 successful and 2 unsuccessful sub-service responses IKsiService haService = new HAKsiService( new List<IKsiService>() { GetStaticKsiService(File.ReadAllBytes(Path.Combine(TestSetup.LocalPath, Resources.KsiService_AggregationResponsePdu_RequestId_1584727637)), 1584727638), GetStaticKsiService(File.ReadAllBytes(Path.Combine(TestSetup.LocalPath, Resources.KsiService_AggregatorConfigResponsePdu)), 1584727637), GetStaticKsiService(File.ReadAllBytes(Path.Combine(TestSetup.LocalPath, Resources.KsiService_AggregationResponsePdu_RequestId_1584727637)), 1584727637) }, null, null); AggregatorConfig config = haService.GetAggregatorConfig(); Assert.AreEqual(17, config.MaxLevel, "Unexpected max level value"); Assert.AreEqual(1, config.AggregationAlgorithm, "Unexpected algorithm value"); Assert.AreEqual(400, config.AggregationPeriod, "Unexpected aggregation period value"); Assert.AreEqual(1024, config.MaxRequests, "Unexpected max requests value"); Assert.AreEqual(0, config.ParentsUris.Count, "Unexpected parent uri count"); } [Test] public void HAAggregatorConfigRequestUsingEventHandlerTest() { // Test getting aggregator configuration with 1 successful and 2 unsuccessful sub-service responses. // Get response using AggregatorConfigChanged event handler IKsiService haService = new HAKsiService( new List<IKsiService>() { GetStaticKsiService(File.ReadAllBytes(Path.Combine(TestSetup.LocalPath, Resources.KsiService_AggregationResponsePdu_RequestId_1584727637)), 1584727638), GetStaticKsiService(File.ReadAllBytes(Path.Combine(TestSetup.LocalPath, Resources.KsiService_AggregatorConfigResponsePdu)), 1584727637), GetStaticKsiService(File.ReadAllBytes(Path.Combine(TestSetup.LocalPath, Resources.KsiService_AggregationResponsePdu_RequestId_1584727637)), 1584727637) }, null, null); ManualResetEvent waitHandle = new ManualResetEvent(false); AggregatorConfig aggregatorConfig = null; haService.AggregatorConfigChanged += delegate(object sender, AggregatorConfigChangedEventArgs e) { aggregatorConfig = e.AggregatorConfig; waitHandle.Set(); }; haService.GetAggregatorConfig(); waitHandle.WaitOne(1000); Assert.IsNotNull(aggregatorConfig, "Could not get aggregator config using event handler."); Assert.AreEqual(17, aggregatorConfig.MaxLevel, "Unexpected max level value"); Assert.AreEqual(1, aggregatorConfig.AggregationAlgorithm, "Unexpected algorithm value"); Assert.AreEqual(400, aggregatorConfig.AggregationPeriod, "Unexpected aggregation period value"); Assert.AreEqual(1024, aggregatorConfig.MaxRequests, "Unexpected max requests value"); Assert.AreEqual(0, aggregatorConfig.ParentsUris.Count, "Unexpected parent uri count"); } [Test] public void HAAggregatorConfigRequestFailSTest() { // Test getting aggregator configuration with all 3 sub-services responses failing IKsiService haService = new HAKsiService( new List<IKsiService>() { GetStaticKsiService(File.ReadAllBytes(Path.Combine(TestSetup.LocalPath, Resources.KsiService_AggregationResponsePdu_RequestId_1584727637)), 1), GetStaticKsiService(File.ReadAllBytes(Path.Combine(TestSetup.LocalPath, Resources.KsiService_AggregationResponsePdu_RequestId_1584727637)), 2), GetStaticKsiService(File.ReadAllBytes(Path.Combine(TestSetup.LocalPath, Resources.KsiService_AggregationResponsePdu_RequestId_1584727637)), 3) }, null, null); HAKsiServiceException ex = Assert.Throws<HAKsiServiceException>(delegate { haService.GetAggregatorConfig(); }); Assert.That(ex.Message.StartsWith("Could not get aggregator configuration"), "Unexpected exception message: " + ex.Message); } [Test] public void HAGetConfigSingleResultAllNullsTest() { // Test getting aggregator configuration with 1 successful sub-service response // All the values are empty IKsiService haService = GetHAService( new List<PduPayload>() { GetAggregatorConfigResponsePayload(null, null, null, null, null), }); AggregatorConfig config = haService.GetAggregatorConfig(); Assert.IsNull(config.MaxLevel, "Unexpected max level value"); Assert.IsNull(config.AggregationAlgorithm, "Unexpected algorithm value"); Assert.IsNull(config.AggregationPeriod, "Unexpected aggregation period value"); Assert.IsNull(config.MaxRequests, "Unexpected max requests value"); Assert.AreEqual(0, config.ParentsUris.Count, "Unexpected parent uri list"); } [Test] public void HAGetConfigTwoResultsTest1() { // Test getting aggregator configuration with 2 successful sub-service responses IKsiService haService = GetHAService( new List<PduPayload>() { GetAggregatorConfigResponsePayload(1, 2, 100, 4, null), }, new List<PduPayload>() { GetAggregatorConfigResponsePayload(2, null, 200, 5, new List<string>() { "uri-2" }) }); AggregatorConfig config = haService.GetAggregatorConfig(); Assert.AreEqual(2, config.MaxLevel, "Unexpected max level value"); Assert.AreEqual(2, config.AggregationAlgorithm, "Unexpected algorithm value"); Assert.AreEqual(100, config.AggregationPeriod, "Unexpected aggregation period value"); Assert.AreEqual(5, config.MaxRequests, "Unexpected max requests value"); Assert.AreEqual(1, config.ParentsUris.Count, "Unexpected parent uri count"); Assert.AreEqual("uri-2", config.ParentsUris[0], "Unexpected parent uri value at position 0"); } [Test] public void HAGetConfigTwoResultsTest2() { // Test getting aggregator configuration with 2 successful sub-service responses IKsiService haService = GetHAService( new List<PduPayload>() { GetAggregatorConfigResponsePayload(2, 3, 200, 5, new List<string>() { "uri-1" }), }, new List<PduPayload>() { GetAggregatorConfigResponsePayload(1, 2, 100, 4, new List<string>() { "uri-2" }) }); AggregatorConfig config = haService.GetAggregatorConfig(); Assert.AreEqual(2, config.MaxLevel, "Unexpected max level value"); Assert.IsTrue(config.AggregationAlgorithm == 3 || config.AggregationAlgorithm == 2, "Unexpected algorithm value"); Assert.AreEqual(100, config.AggregationPeriod, "Unexpected aggregation period value"); Assert.AreEqual(5, config.MaxRequests, "Unexpected max requests value"); Assert.AreEqual(1, config.ParentsUris.Count, "Unexpected parent uri count"); Assert.IsTrue(config.ParentsUris[0] == "uri-1" || config.ParentsUris[0] == "uri-2", "Unexpected parent uri value at position 0"); } [Test] public void HAGetConfigTwoResultsTest3() { // Test getting aggregator configuration with 2 successful sub-service responses IKsiService haService = GetHAService( new List<PduPayload>() { GetAggregatorConfigResponsePayload(null, null, null, null, null), }, new List<PduPayload>() { GetAggregatorConfigResponsePayload(1, 2, 100, 4, new List<string>() { "uri-2" }) }); AggregatorConfig config = haService.GetAggregatorConfig(); Assert.AreEqual(1, config.MaxLevel, "Unexpected max level value"); Assert.AreEqual(2, config.AggregationAlgorithm, "Unexpected algorithm value"); Assert.AreEqual(100, config.AggregationPeriod, "Unexpected aggregation period value"); Assert.AreEqual(4, config.MaxRequests, "Unexpected max requests value"); Assert.AreEqual(1, config.ParentsUris.Count, "Unexpected parent uri count"); Assert.AreEqual("uri-2", config.ParentsUris[0], "Unexpected parent uri value at position 0"); } [Test] public void HAGetConfigTwoResultsTest4() { // Test getting aggregator configuration with 2 successful sub-service responses IKsiService haService = GetHAService( new List<PduPayload>() { GetAggregatorConfigResponsePayload(1, 2, 100, 4, new List<string>() { "uri-1" }), }, new List<PduPayload>() { GetAggregatorConfigResponsePayload(null, null, null, null, null) }); AggregatorConfig config = haService.GetAggregatorConfig(); Assert.AreEqual(1, config.MaxLevel, "Unexpected max level value"); Assert.AreEqual(2, config.AggregationAlgorithm, "Unexpected algorithm value"); Assert.AreEqual(100, config.AggregationPeriod, "Unexpected aggregation period value"); Assert.AreEqual(4, config.MaxRequests, "Unexpected max requests value"); Assert.AreEqual(1, config.ParentsUris.Count, "Unexpected parent uri count"); Assert.AreEqual("uri-1", config.ParentsUris[0], "Unexpected parent uri value at position 0"); } [Test] public void HAGetConfigResultsOutOfLimitTest() { // Test getting aggregator configuration with 2 successful sub-service responses // Some values are out of bounds IKsiService haService = GetHAService( new List<PduPayload>() { GetAggregatorConfigResponsePayload(1, 2, 99, 4, new List<string>() { "uri-1" }) }, new List<PduPayload>() { GetAggregatorConfigResponsePayload(21, null, 20001, 16001, null) }); AggregatorConfig config = haService.GetAggregatorConfig(); Assert.AreEqual(1, config.MaxLevel, "Unexpected max level value"); Assert.AreEqual(2, config.AggregationAlgorithm, "Unexpected algorithm value"); Assert.IsNull(config.AggregationPeriod, "Unexpected aggregation period value"); Assert.AreEqual(4, config.MaxRequests, "Unexpected max requests value"); Assert.AreEqual(1, config.ParentsUris.Count, "Unexpected parent uri count"); Assert.AreEqual("uri-1", config.ParentsUris[0], "Unexpected parent uri value at position 0"); } [Test] public void HAGetConfigResultsAndRemoveAllTest() { // A configuration request with 2 successful sub-requests is made. // Then a new configuration request is made with 2 unsuccessful sub-requests. // Both configuration are removed from cache. // AggregationConfigChanged event handler should get result containing an exception. HAKsiService haService = GetHAService( new List<PduPayload>() { GetAggregatorConfigResponsePayload(1, 1, 100, 4, new List<string>() { "uri-1" }) }, new List<PduPayload>() { GetAggregatorConfigResponsePayload(1, 2, 100, 4, new List<string>() { "uri-2" }) }); haService.GetAggregatorConfig(); // change first service response so that request fails ((TestKsiService)haService.SigningServices[0]).SigningServiceProtocol.RequestResult = File.ReadAllBytes(Path.Combine(TestSetup.LocalPath, Resources.KsiService_AggregationResponsePdu_RequestId_1584727637)); // change second service response so that request fails ((TestKsiService)haService.SigningServices[1]).SigningServiceProtocol.RequestResult = File.ReadAllBytes(Path.Combine(TestSetup.LocalPath, Resources.KsiService_AggregationResponsePdu_RequestId_1584727637)); AggregatorConfigChangedEventArgs args = null; ManualResetEvent waitHandle = new ManualResetEvent(false); haService.AggregatorConfigChanged += delegate(object sender, AggregatorConfigChangedEventArgs e) { args = e; waitHandle.Set(); }; HAKsiServiceException ex = Assert.Throws<HAKsiServiceException>(delegate { haService.GetAggregatorConfig(); }); Assert.That(ex.Message.StartsWith("Could not get aggregator configuration"), "Unexpected exception message: " + ex.Message); waitHandle.WaitOne(1000); Assert.IsNotNull(args, "AggregatorConfigChangedEventArgs cannot be null."); Assert.IsNull(args.AggregatorConfig, "AggregatorConfigChangedEventArgs.AggregatorConfig cannot have value."); Assert.IsNotNull(args.Exception, "AggregatorConfigChangedEventArgs.Exception cannot be null."); Assert.AreEqual(haService, args.KsiService, "Unexpected AggregatorConfigChangedEventArgs.KsiService"); Assert.That(args.Exception.Message.StartsWith("Could not get aggregator configuration"), "Unexpected exception message: " + args.Exception.Message); } [Test] public void HAGetConfigResultsAndRemoveOneTest() { // A configuration request with 2 successful sub-requests is made. // Then a new configuration request is made with 1 successful and 1 unsuccessful sub-requests. // Unsuccessful service config should be removed from cache and merged config should be recalculated HAKsiService haService = GetHAService( new List<PduPayload>() { GetAggregatorConfigResponsePayload(2, 1, 100, 4, new List<string>() { "uri-1" }) }, new List<PduPayload>() { GetAggregatorConfigResponsePayload(1, 2, 100, 4, new List<string>() { "uri-2" }) }); ManualResetEvent waitHandle = new ManualResetEvent(false); haService.AggregatorConfigChanged += delegate { }; AggregatorConfig resultConf = haService.GetAggregatorConfig(); waitHandle.WaitOne(1000); Assert.AreEqual(2, resultConf.MaxLevel, "Unexpected max level value"); Assert.AreEqual(100, resultConf.AggregationPeriod, "Unexpected aggregation period value"); Assert.AreEqual(4, resultConf.MaxRequests, "Unexpected max requests value"); Assert.AreEqual(1, resultConf.ParentsUris.Count, "Unexpected parent uri count"); // change first service response so that request fails ((TestKsiService)haService.SigningServices[0]).SigningServiceProtocol.RequestResult = File.ReadAllBytes(Path.Combine(TestSetup.LocalPath, Resources.KsiService_AggregationResponsePdu_RequestId_1584727637)); // change second service response so that a valid configuration is returned TestKsiService newService = (TestKsiService)GetService(new List<PduPayload>() { GetAggregationResponsePayload(Resources.KsiService_AggregationResponsePdu_RequestId_1584727638), GetAggregatorConfigResponsePayload(2, 3, 400, 3, new List<string>() { "uri-2-changed" }) }); ((TestKsiService)haService.SigningServices[1]).SigningServiceProtocol.RequestResult = newService.SigningServiceProtocol.RequestResult; AggregatorConfigChangedEventArgs args = null; waitHandle = new ManualResetEvent(false); haService.AggregatorConfigChanged += delegate(object sender, AggregatorConfigChangedEventArgs e) { args = e; }; resultConf = haService.GetAggregatorConfig(); Assert.AreEqual(2, resultConf.MaxLevel, "Unexpected max level value"); Assert.AreEqual(3, resultConf.AggregationAlgorithm, "Unexpected algorithm value"); Assert.AreEqual(400, resultConf.AggregationPeriod, "Unexpected aggregation period value"); Assert.AreEqual(3, resultConf.MaxRequests, "Unexpected max requests value"); Assert.AreEqual(1, resultConf.ParentsUris.Count, "Unexpected parent uri count"); Assert.AreEqual("uri-2-changed", resultConf.ParentsUris[0], "Unexpected parent uri value at position 0"); waitHandle.WaitOne(1000); Assert.IsNotNull(args, "AggregatorConfigChangedEventArgs cannot be null."); Assert.AreEqual(resultConf, args.AggregatorConfig, "Unexpected AggregatorConfigChangedEventArgs.AggregatorConfig."); Assert.IsNull(args.Exception, "AggregatorConfigChangedEventArgs.Exception cannot have value."); Assert.AreEqual(haService, args.KsiService, "Unexpected AggregatorConfigChangedEventArgs.KsiService"); } [Test] public void HAGetConfigResultsWithSignRequestTest() { // Test getting aggregator configurations via AggregatorConfigChanged event handler when using Sign method. // Testing getting different configurations in a sequence HAKsiService haService = GetHAService( new List<PduPayload>() { GetAggregationResponsePayload(Resources.KsiService_AggregationResponsePdu_RequestId_1584727637), GetAggregatorConfigResponsePayload(1, 1, 200, 4, new List<string>() { "uri-1" }) }, new List<PduPayload>() { GetAggregationResponsePayload(Resources.KsiService_AggregationResponsePdu_RequestId_1584727638), GetAggregatorConfigResponsePayload(1, 1, 200, 4, new List<string>() { "uri-2" }) }); TestKsiService secondService = (TestKsiService)haService.SigningServices[1]; secondService.RequestId = 1584727638; AggregatorConfig resultConf = null; int changeCount = 0; ManualResetEvent waitHandle = new ManualResetEvent(false); haService.AggregatorConfigChanged += delegate(object sender, AggregatorConfigChangedEventArgs e) { resultConf = e.AggregatorConfig; changeCount++; if (changeCount == 2) { waitHandle.Set(); } }; DataHash inputHash = new DataHash(Base16.Decode("019f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08")); IKsiSignature signature = haService.Sign(inputHash); Assert.AreEqual(inputHash, signature.InputHash, "Unexpected signature input hash."); waitHandle.WaitOne(1000); Assert.IsNotNull(resultConf, "Could not get aggregator config using event handler."); Assert.AreEqual(1, resultConf.MaxLevel, "Unexpected max level value"); Assert.IsTrue(resultConf.AggregationAlgorithm == 1 || resultConf.AggregationAlgorithm == 2, "Unexpected algorithm value"); Assert.AreEqual(200, resultConf.AggregationPeriod, "Unexpected aggregation period value"); Assert.AreEqual(4, resultConf.MaxRequests, "Unexpected max requests value"); Assert.AreEqual(1, resultConf.ParentsUris.Count, "Unexpected parent uri count"); Assert.IsTrue(resultConf.ParentsUris[0] == "uri-1" || resultConf.ParentsUris[0] == "uri-2", "Unexpected parent uri value at position 0"); // changing aggregation algorithm or parent uri should not change merged config TestKsiService newService = (TestKsiService)GetService(new List<PduPayload>() { GetAggregationResponsePayload(Resources.KsiService_AggregationResponsePdu_RequestId_1584727638), GetAggregatorConfigResponsePayload(1, 3, 200, 4, new List<string>() { "uri-2-changed" }) }); secondService.SigningServiceProtocol.RequestResult = newService.SigningServiceProtocol.RequestResult; resultConf = null; changeCount = 0; haService.Sign(inputHash); Thread.Sleep(1000); Assert.IsNull(resultConf, "Aggregator config should have not changed (2nd request)"); Assert.AreEqual(0, changeCount, "Unexpected change count."); // changing max level should change merged config newService = (TestKsiService)GetService(new List<PduPayload>() { GetAggregationResponsePayload(Resources.KsiService_AggregationResponsePdu_RequestId_1584727638), GetAggregatorConfigResponsePayload(2, 2, 200, 4, new List<string>() { "uri-2", "uri-3" }) }); secondService.SigningServiceProtocol.RequestResult = newService.SigningServiceProtocol.RequestResult; waitHandle.Reset(); resultConf = null; changeCount = 0; haService.Sign(inputHash); waitHandle.WaitOne(1000); Assert.IsNotNull(resultConf, "Could not get aggregator config using event handler (after 3rd sign request)."); Assert.AreEqual(2, resultConf.MaxLevel, "Unexpected max level value (after 3rd sign request)"); Assert.IsTrue(resultConf.AggregationAlgorithm == 1 || resultConf.AggregationAlgorithm == 2, "Unexpected algorithm value (after 3rd sign request)"); Assert.AreEqual(200, resultConf.AggregationPeriod, "Unexpected aggregation period value (after 3rd sign request)"); Assert.AreEqual(4, resultConf.MaxRequests, "Unexpected max requests value (after 3rd sign request)"); Assert.AreEqual(1, resultConf.ParentsUris.Count, "Unexpected parent uri count (after 3rd sign request)"); Assert.IsTrue(resultConf.ParentsUris[0] == "uri-1" || resultConf.ParentsUris[0] == "uri-2", "Unexpected parent uri value at position 0 (after 3rd sign request)"); // changing aggegation period should change merged config newService = (TestKsiService)GetService(new List<PduPayload>() { GetAggregationResponsePayload(Resources.KsiService_AggregationResponsePdu_RequestId_1584727638), GetAggregatorConfigResponsePayload(2, 2, 100, 4, new List<string>() { "uri-2", "uri-3" }) }); secondService.SigningServiceProtocol.RequestResult = newService.SigningServiceProtocol.RequestResult; waitHandle.Reset(); resultConf = null; changeCount = 0; haService.Sign(inputHash); waitHandle.WaitOne(1000); Assert.IsNotNull(resultConf, "Could not get aggregator config using event handler (after 4th sign request)."); Assert.AreEqual(2, resultConf.MaxLevel, "Unexpected max level value (after 4th sign request)"); Assert.IsTrue(resultConf.AggregationAlgorithm == 1 || resultConf.AggregationAlgorithm == 2, "Unexpected algorithm value (after 4th sign request)"); Assert.AreEqual(100, resultConf.AggregationPeriod, "Unexpected aggregation period value (after 4th sign request)"); Assert.AreEqual(4, resultConf.MaxRequests, "Unexpected max requests value (after 4th sign request)"); Assert.AreEqual(1, resultConf.ParentsUris.Count, "Unexpected parent uri count (after 4th sign request)"); Assert.IsTrue(resultConf.ParentsUris[0] == "uri-1" || resultConf.ParentsUris[0] == "uri-2", "Unexpected parent uri value at position 0 (after 4th sign request)"); // changing max requests should change merged config newService = (TestKsiService)GetService(new List<PduPayload>() { GetAggregationResponsePayload(Resources.KsiService_AggregationResponsePdu_RequestId_1584727638), GetAggregatorConfigResponsePayload(2, 2, 200, 5, new List<string>() { "uri-2", "uri-3" }) }); secondService.SigningServiceProtocol.RequestResult = newService.SigningServiceProtocol.RequestResult; waitHandle.Reset(); resultConf = null; changeCount = 0; haService.Sign(inputHash); waitHandle.WaitOne(1000); Assert.IsNotNull(resultConf, "Could not get aggregator config using event handler (after 5th sign request)."); Assert.AreEqual(2, resultConf.MaxLevel, "Unexpected max level value (after 5th sign request)"); Assert.IsTrue(resultConf.AggregationAlgorithm == 1 || resultConf.AggregationAlgorithm == 2, "Unexpected algorithm value (after 5th sign request)"); Assert.AreEqual(200, resultConf.AggregationPeriod, "Unexpected aggregation period value (after 5th sign request)"); Assert.AreEqual(5, resultConf.MaxRequests, "Unexpected max requests value (after 5th sign request)"); Assert.AreEqual(1, resultConf.ParentsUris.Count, "Unexpected parent uri count (after 5th sign request)"); Assert.IsTrue(resultConf.ParentsUris[0] == "uri-1" || resultConf.ParentsUris[0] == "uri-2", "Unexpected parent uri value at position 0 (after 5th sign request)"); // signing again should not change merged config waitHandle.Reset(); resultConf = null; changeCount = 0; haService.Sign(inputHash); waitHandle.WaitOne(1000); Assert.IsNull(resultConf, "Aggregator config should have not changed (after 6th sign request"); Assert.AreEqual(0, changeCount, "Unexpected change count."); } /// <summary> /// Test HA get aggregator config request timeout. /// </summary> [Test] public void HAGetAggregatorConfigTimeoutTest() { TestKsiServiceProtocol protocol = new TestKsiServiceProtocol { RequestResult = GetAggregatorConfigResponsePayload(1, 2, 100, 4, null).Encode(), DelayMilliseconds = 3000 }; IKsiService haService = new HAKsiService( new List<IKsiService>() { GetStaticKsiService(protocol), }, null, null, 1000); HAKsiServiceException ex = Assert.Throws<HAKsiServiceException>(delegate { haService.GetAggregatorConfig(); }); Assert.That(ex.Message.StartsWith("HA service request timed out"), "Unexpected exception message: " + ex.Message); } private static HAKsiService GetHAService(params List<PduPayload>[] subServiceResults) { return new HAKsiService(subServiceResults.Select(payloads => GetService(payloads)).ToList(), null, null); } private static IKsiService GetService(List<PduPayload> payloads, ulong requestId = 1584727637) { List<ITlvTag> childTags = new List<ITlvTag> { new PduHeader(Settings.Default.HttpSigningServiceUser) }; childTags.AddRange(payloads); childTags.Add(new ImprintTag(Constants.Pdu.MacTagType, false, false, new DataHash(HashAlgorithm.Sha2256, new byte[32]))); AggregationResponsePdu pdu = TestUtil.GetCompositeTag<AggregationResponsePdu>(Constants.AggregationResponsePdu.TagType, childTags.ToArray()); MethodInfo m = pdu.GetType().GetMethod("SetMacValue", BindingFlags.Instance | BindingFlags.NonPublic); m.Invoke(pdu, new object[] { HashAlgorithm.Sha2256, Util.EncodeNullTerminatedUtf8String(TestConstants.ServicePass) }); MemoryStream stream = new MemoryStream(); using (TlvWriter writer = new TlvWriter(stream)) { writer.WriteTag(pdu); } return GetStaticKsiService(stream.ToArray(), requestId); } private static AggregationResponsePayload GetAggregationResponsePayload(string path) { byte[] bytes = File.ReadAllBytes(Path.Combine(TestSetup.LocalPath, path)); using (TlvReader reader = new TlvReader(new MemoryStream(bytes))) { AggregationResponsePdu pdu = new AggregationResponsePdu(reader.ReadTag()); return pdu.Payloads[0] as AggregationResponsePayload; } } private static AggregatorConfigResponsePayload GetAggregatorConfigResponsePayload(ulong? maxLevel, ulong? aggregationAlgorithm, ulong? aggregationPeriod, ulong? maxRequests, IList<string> parentsUris) { List<ITlvTag> tlvTags = new List<ITlvTag>(); if (maxLevel.HasValue) { tlvTags.Add(new IntegerTag(Constants.AggregatorConfigResponsePayload.MaxLevelTagType, false, false, maxLevel.Value)); } if (aggregationAlgorithm.HasValue) { tlvTags.Add(new IntegerTag(Constants.AggregatorConfigResponsePayload.AggregationAlgorithmTagType, false, false, aggregationAlgorithm.Value)); } if (aggregationPeriod.HasValue) { tlvTags.Add(new IntegerTag(Constants.AggregatorConfigResponsePayload.AggregationPeriodTagType, false, false, aggregationPeriod.Value)); } if (maxRequests.HasValue) { tlvTags.Add(new IntegerTag(Constants.AggregatorConfigResponsePayload.MaxRequestsTagType, false, false, maxRequests.Value)); } if (parentsUris != null) { tlvTags.AddRange(parentsUris.Select(uri => new StringTag(Constants.AggregatorConfigResponsePayload.ParentUriTagType, false, false, uri))); } AggregatorConfigResponsePayload payload = TestUtil.GetCompositeTag<AggregatorConfigResponsePayload>(Constants.AggregatorConfigResponsePayload.TagType, tlvTags.ToArray()); return payload; } } }
51.609756
176
0.64225
[ "Apache-2.0" ]
GuardTime/ksi-net-sdk
ksi-net-api-test/Service/HighAvailability/HAAggregatorConfigStaticTests.cs
33,858
C#
using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; namespace AspNetCore.Data.Migrations { [DbContext(typeof(ApplicationDbContext))] partial class ApplicationDbContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { modelBuilder .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn) .HasAnnotation("ProductVersion", "1.1.0-rtm-22752"); modelBuilder.Entity("ApsNetCore.Data.Article", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Text") .HasMaxLength(4000); b.Property<string>("Title") .IsRequired() .HasMaxLength(250); b.HasKey("Id"); b.ToTable("Articles"); }); modelBuilder.Entity("ApsNetCore.Models.ApplicationUser", b => { b.Property<string>("Id") .ValueGeneratedOnAdd(); b.Property<int>("AccessFailedCount"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Email") .HasMaxLength(256); b.Property<bool>("EmailConfirmed"); b.Property<bool>("LockoutEnabled"); b.Property<DateTimeOffset?>("LockoutEnd"); b.Property<string>("NormalizedEmail") .HasMaxLength(256); b.Property<string>("NormalizedUserName") .HasMaxLength(256); b.Property<string>("PasswordHash"); b.Property<string>("PhoneNumber"); b.Property<bool>("PhoneNumberConfirmed"); b.Property<string>("SecurityStamp"); b.Property<bool>("TwoFactorEnabled"); b.Property<string>("UserName") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasName("EmailIndex"); b.HasIndex("NormalizedUserName") .IsUnique() .HasName("UserNameIndex"); b.ToTable("AspNetUsers"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole", b => { b.Property<string>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Name") .HasMaxLength(256); b.Property<string>("NormalizedName") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedName") .IsUnique() .HasName("RoleNameIndex"); b.ToTable("AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("RoleId") .IsRequired(); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("UserId") .IsRequired(); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider"); b.Property<string>("ProviderKey"); b.Property<string>("ProviderDisplayName"); b.Property<string>("UserId") .IsRequired(); b.HasKey("LoginProvider", "ProviderKey"); b.HasIndex("UserId"); b.ToTable("AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b => { b.Property<string>("UserId"); b.Property<string>("RoleId"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.ToTable("AspNetUserRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserToken<string>", b => { b.Property<string>("UserId"); b.Property<string>("LoginProvider"); b.Property<string>("Name"); b.Property<string>("Value"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AspNetUserTokens"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole") .WithMany("Claims") .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b => { b.HasOne("ApsNetCore.Models.ApplicationUser") .WithMany("Claims") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b => { b.HasOne("ApsNetCore.Models.ApplicationUser") .WithMany("Logins") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole") .WithMany("Users") .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("ApsNetCore.Models.ApplicationUser") .WithMany("Roles") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); } } }
33.93913
115
0.476685
[ "MIT" ]
SokolovArtur/AspNetCore
AspNetCore/Data/Migrations/ApplicationDbContextModelSnapshot.cs
7,808
C#
// Copyright (c) Six Labors and contributors. // Licensed under the Apache License, Version 2.0. using System; using System.Buffers; using System.Buffers.Binary; using System.IO; using System.Numerics; using System.Runtime.CompilerServices; using SixLabors.ImageSharp.Common.Helpers; using SixLabors.ImageSharp.Memory; using SixLabors.ImageSharp.MetaData; using SixLabors.ImageSharp.PixelFormats; using SixLabors.Memory; namespace SixLabors.ImageSharp.Formats.Bmp { /// <summary> /// Performs the bitmap decoding operation. /// </summary> /// <remarks> /// A useful decoding source example can be found at <see href="https://dxr.mozilla.org/mozilla-central/source/image/decoders/nsBMPDecoder.cpp"/> /// </remarks> internal sealed class BmpDecoderCore { /// <summary> /// The default mask for the red part of the color for 16 bit rgb bitmaps. /// </summary> private const int DefaultRgb16RMask = 0x7C00; /// <summary> /// The default mask for the green part of the color for 16 bit rgb bitmaps. /// </summary> private const int DefaultRgb16GMask = 0x3E0; /// <summary> /// The default mask for the blue part of the color for 16 bit rgb bitmaps. /// </summary> private const int DefaultRgb16BMask = 0x1F; /// <summary> /// RLE8 flag value that indicates following byte has special meaning. /// </summary> private const int RleCommand = 0x00; /// <summary> /// RLE8 flag value marking end of a scan line. /// </summary> private const int RleEndOfLine = 0x00; /// <summary> /// RLE8 flag value marking end of bitmap data. /// </summary> private const int RleEndOfBitmap = 0x01; /// <summary> /// RLE8 flag value marking the start of [x,y] offset instruction. /// </summary> private const int RleDelta = 0x02; /// <summary> /// The stream to decode from. /// </summary> private Stream stream; /// <summary> /// The metadata. /// </summary> private ImageMetaData metaData; /// <summary> /// The bmp specific metadata. /// </summary> private BmpMetaData bmpMetaData; /// <summary> /// The file header containing general information. /// TODO: Why is this not used? We advance the stream but do not use the values parsed. /// </summary> private BmpFileHeader fileHeader; /// <summary> /// The info header containing detailed information about the bitmap. /// </summary> private BmpInfoHeader infoHeader; private readonly Configuration configuration; private readonly MemoryAllocator memoryAllocator; /// <summary> /// Initializes a new instance of the <see cref="BmpDecoderCore"/> class. /// </summary> /// <param name="configuration">The configuration.</param> /// <param name="options">The options.</param> public BmpDecoderCore(Configuration configuration, IBmpDecoderOptions options) { this.configuration = configuration; this.memoryAllocator = configuration.MemoryAllocator; } /// <summary> /// Decodes the image from the specified this._stream and sets /// the data to image. /// </summary> /// <typeparam name="TPixel">The pixel format.</typeparam> /// <param name="stream">The stream, where the image should be /// decoded from. Cannot be null (Nothing in Visual Basic).</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="stream"/> is null.</para> /// </exception> /// <returns>The decoded image.</returns> public Image<TPixel> Decode<TPixel>(Stream stream) where TPixel : struct, IPixel<TPixel> { try { int bytesPerColorMapEntry = this.ReadImageHeaders(stream, out bool inverted, out byte[] palette); var image = new Image<TPixel>(this.configuration, this.infoHeader.Width, this.infoHeader.Height, this.metaData); Buffer2D<TPixel> pixels = image.GetRootFramePixelBuffer(); switch (this.infoHeader.Compression) { case BmpCompression.RGB: if (this.infoHeader.BitsPerPixel == 32) { if (this.bmpMetaData.InfoHeaderType == BmpInfoHeaderType.WinVersion3) { this.ReadRgb32Slow(pixels, this.infoHeader.Width, this.infoHeader.Height, inverted); } else { this.ReadRgb32Fast(pixels, this.infoHeader.Width, this.infoHeader.Height, inverted); } } else if (this.infoHeader.BitsPerPixel == 24) { this.ReadRgb24(pixels, this.infoHeader.Width, this.infoHeader.Height, inverted); } else if (this.infoHeader.BitsPerPixel == 16) { this.ReadRgb16(pixels, this.infoHeader.Width, this.infoHeader.Height, inverted); } else if (this.infoHeader.BitsPerPixel <= 8) { this.ReadRgbPalette( pixels, palette, this.infoHeader.Width, this.infoHeader.Height, this.infoHeader.BitsPerPixel, bytesPerColorMapEntry, inverted); } break; case BmpCompression.RLE8: case BmpCompression.RLE4: this.ReadRle(this.infoHeader.Compression, pixels, palette, this.infoHeader.Width, this.infoHeader.Height, inverted); break; case BmpCompression.BitFields: this.ReadBitFields(pixels, inverted); break; default: BmpThrowHelper.ThrowNotSupportedException("Does not support this kind of bitmap files."); break; } return image; } catch (IndexOutOfRangeException e) { throw new ImageFormatException("Bitmap does not have a valid format.", e); } } /// <summary> /// Reads the raw image information from the specified stream. /// </summary> /// <param name="stream">The <see cref="Stream"/> containing image data.</param> public IImageInfo Identify(Stream stream) { this.ReadImageHeaders(stream, out _, out _); return new ImageInfo(new PixelTypeInfo(this.infoHeader.BitsPerPixel), this.infoHeader.Width, this.infoHeader.Height, this.metaData); } /// <summary> /// Returns the y- value based on the given height. /// </summary> /// <param name="y">The y- value representing the current row.</param> /// <param name="height">The height of the bitmap.</param> /// <param name="inverted">Whether the bitmap is inverted.</param> /// <returns>The <see cref="int"/> representing the inverted value.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int Invert(int y, int height, bool inverted) => (!inverted) ? height - y - 1 : y; /// <summary> /// Calculates the amount of bytes to pad a row. /// </summary> /// <param name="width">The image width.</param> /// <param name="componentCount">The pixel component count.</param> /// <returns> /// The <see cref="int"/>. /// </returns> private static int CalculatePadding(int width, int componentCount) { int padding = (width * componentCount) % 4; if (padding != 0) { padding = 4 - padding; } return padding; } /// <summary> /// Decodes a bitmap containing BITFIELDS Compression type. For each color channel, there will be bitmask /// which will be used to determine which bits belong to that channel. /// </summary> /// <typeparam name="TPixel">The pixel format.</typeparam> /// <param name="pixels">The output pixel buffer containing the decoded image.</param> /// <param name="inverted">Whether the bitmap is inverted.</param> private void ReadBitFields<TPixel>(Buffer2D<TPixel> pixels, bool inverted) where TPixel : struct, IPixel<TPixel> { if (this.infoHeader.BitsPerPixel == 16) { this.ReadRgb16( pixels, this.infoHeader.Width, this.infoHeader.Height, inverted, this.infoHeader.RedMask, this.infoHeader.GreenMask, this.infoHeader.BlueMask); } else { this.ReadRgb32BitFields( pixels, this.infoHeader.Width, this.infoHeader.Height, inverted, this.infoHeader.RedMask, this.infoHeader.GreenMask, this.infoHeader.BlueMask, this.infoHeader.AlphaMask); } } /// <summary> /// Looks up color values and builds the image from de-compressed RLE8 or RLE4 data. /// Compressed RLE8 stream is uncompressed by <see cref="UncompressRle8(int, Span{byte})"/> /// Compressed RLE4 stream is uncompressed by <see cref="UncompressRle4(int, Span{byte})"/> /// </summary> /// <typeparam name="TPixel">The pixel format.</typeparam> /// <param name="compression">The compression type. Either RLE4 or RLE8.</param> /// <param name="pixels">The <see cref="Buffer2D{TPixel}"/> to assign the palette to.</param> /// <param name="colors">The <see cref="T:byte[]"/> containing the colors.</param> /// <param name="width">The width of the bitmap.</param> /// <param name="height">The height of the bitmap.</param> /// <param name="inverted">Whether the bitmap is inverted.</param> private void ReadRle<TPixel>(BmpCompression compression, Buffer2D<TPixel> pixels, byte[] colors, int width, int height, bool inverted) where TPixel : struct, IPixel<TPixel> { TPixel color = default; using (Buffer2D<byte> buffer = this.memoryAllocator.Allocate2D<byte>(width, height, AllocationOptions.Clean)) { if (compression == BmpCompression.RLE8) { this.UncompressRle8(width, buffer.GetSpan()); } else { this.UncompressRle4(width, buffer.GetSpan()); } for (int y = 0; y < height; y++) { int newY = Invert(y, height, inverted); Span<byte> bufferRow = buffer.GetRowSpan(y); Span<TPixel> pixelRow = pixels.GetRowSpan(newY); for (int x = 0; x < width; x++) { color.FromBgr24(Unsafe.As<byte, Bgr24>(ref colors[bufferRow[x] * 4])); pixelRow[x] = color; } } } } /// <summary> /// Produce uncompressed bitmap data from a RLE4 stream. /// </summary> /// <remarks> /// RLE4 is a 2-byte run-length encoding. /// <br/>If first byte is 0, the second byte may have special meaning. /// <br/>Otherwise, the first byte is the length of the run and second byte contains two color indexes. /// </remarks> /// <param name="w">The width of the bitmap.</param> /// <param name="buffer">Buffer for uncompressed data.</param> private void UncompressRle4(int w, Span<byte> buffer) { #if NETCOREAPP2_1 Span<byte> cmd = stackalloc byte[2]; #else byte[] cmd = new byte[2]; #endif int count = 0; while (count < buffer.Length) { if (this.stream.Read(cmd, 0, cmd.Length) != 2) { BmpThrowHelper.ThrowImageFormatException("Failed to read 2 bytes from the stream while uncompressing RLE4 bitmap."); } if (cmd[0] == RleCommand) { switch (cmd[1]) { case RleEndOfBitmap: return; case RleEndOfLine: int extra = count % w; if (extra > 0) { count += w - extra; } break; case RleDelta: int dx = this.stream.ReadByte(); int dy = this.stream.ReadByte(); count += (w * dy) + dx; break; default: // If the second byte > 2, we are in 'absolute mode'. // The second byte contains the number of color indexes that follow. int max = cmd[1]; int bytesToRead = (max + 1) / 2; byte[] run = new byte[bytesToRead]; this.stream.Read(run, 0, run.Length); int idx = 0; for (int i = 0; i < max; i++) { byte twoPixels = run[idx]; if (i % 2 == 0) { byte leftPixel = (byte)((twoPixels >> 4) & 0xF); buffer[count++] = leftPixel; } else { byte rightPixel = (byte)(twoPixels & 0xF); buffer[count++] = rightPixel; idx++; } } // Absolute mode data is aligned to two-byte word-boundary int padding = bytesToRead & 1; this.stream.Skip(padding); break; } } else { int max = cmd[0]; // The second byte contains two color indexes, one in its high-order 4 bits and one in its low-order 4 bits. byte twoPixels = cmd[1]; byte rightPixel = (byte)(twoPixels & 0xF); byte leftPixel = (byte)((twoPixels >> 4) & 0xF); for (int idx = 0; idx < max; idx++) { if (idx % 2 == 0) { buffer[count] = leftPixel; } else { buffer[count] = rightPixel; } count++; } } } } /// <summary> /// Produce uncompressed bitmap data from a RLE8 stream. /// </summary> /// <remarks> /// RLE8 is a 2-byte run-length encoding. /// <br/>If first byte is 0, the second byte may have special meaning. /// <br/>Otherwise, the first byte is the length of the run and second byte is the color for the run. /// </remarks> /// <param name="w">The width of the bitmap.</param> /// <param name="buffer">Buffer for uncompressed data.</param> private void UncompressRle8(int w, Span<byte> buffer) { #if NETCOREAPP2_1 Span<byte> cmd = stackalloc byte[2]; #else byte[] cmd = new byte[2]; #endif int count = 0; while (count < buffer.Length) { if (this.stream.Read(cmd, 0, cmd.Length) != 2) { BmpThrowHelper.ThrowImageFormatException("Failed to read 2 bytes from stream while uncompressing RLE8 bitmap."); } if (cmd[0] == RleCommand) { switch (cmd[1]) { case RleEndOfBitmap: return; case RleEndOfLine: int extra = count % w; if (extra > 0) { count += w - extra; } break; case RleDelta: int dx = this.stream.ReadByte(); int dy = this.stream.ReadByte(); count += (w * dy) + dx; break; default: // If the second byte > 2, we are in 'absolute mode' // Take this number of bytes from the stream as uncompressed data int length = cmd[1]; byte[] run = new byte[length]; this.stream.Read(run, 0, run.Length); run.AsSpan().CopyTo(buffer.Slice(count)); count += run.Length; // Absolute mode data is aligned to two-byte word-boundary int padding = length & 1; this.stream.Skip(padding); break; } } else { int max = count + cmd[0]; // as we start at the current count in the following loop, max is count + cmd[0] byte cmd1 = cmd[1]; // store the value to avoid the repeated indexer access inside the loop for (; count < max; count++) { buffer[count] = cmd1; } } } } /// <summary> /// Reads the color palette from the stream. /// </summary> /// <typeparam name="TPixel">The pixel format.</typeparam> /// <param name="pixels">The <see cref="Buffer2D{TPixel}"/> to assign the palette to.</param> /// <param name="colors">The <see cref="T:byte[]"/> containing the colors.</param> /// <param name="width">The width of the bitmap.</param> /// <param name="height">The height of the bitmap.</param> /// <param name="bitsPerPixel">The number of bits per pixel.</param> /// <param name="bytesPerColorMapEntry">Usually 4 bytes, but in case of Windows 2.x bitmaps or OS/2 1.x bitmaps /// the bytes per color palette entry's can be 3 bytes instead of 4.</param> /// <param name="inverted">Whether the bitmap is inverted.</param> private void ReadRgbPalette<TPixel>(Buffer2D<TPixel> pixels, byte[] colors, int width, int height, int bitsPerPixel, int bytesPerColorMapEntry, bool inverted) where TPixel : struct, IPixel<TPixel> { // Pixels per byte (bits per pixel) int ppb = 8 / bitsPerPixel; int arrayWidth = (width + ppb - 1) / ppb; // Bit mask int mask = 0xFF >> (8 - bitsPerPixel); // Rows are aligned on 4 byte boundaries int padding = arrayWidth % 4; if (padding != 0) { padding = 4 - padding; } using (IManagedByteBuffer row = this.memoryAllocator.AllocateManagedByteBuffer(arrayWidth + padding, AllocationOptions.Clean)) { TPixel color = default; Span<byte> rowSpan = row.GetSpan(); for (int y = 0; y < height; y++) { int newY = Invert(y, height, inverted); this.stream.Read(row.Array, 0, row.Length()); int offset = 0; Span<TPixel> pixelRow = pixels.GetRowSpan(newY); for (int x = 0; x < arrayWidth; x++) { int colOffset = x * ppb; for (int shift = 0, newX = colOffset; shift < ppb && newX < width; shift++, newX++) { int colorIndex = ((rowSpan[offset] >> (8 - bitsPerPixel - (shift * bitsPerPixel))) & mask) * bytesPerColorMapEntry; color.FromBgr24(Unsafe.As<byte, Bgr24>(ref colors[colorIndex])); pixelRow[newX] = color; } offset++; } } } } /// <summary> /// Reads the 16 bit color palette from the stream. /// </summary> /// <typeparam name="TPixel">The pixel format.</typeparam> /// <param name="pixels">The <see cref="Buffer2D{TPixel}"/> to assign the palette to.</param> /// <param name="width">The width of the bitmap.</param> /// <param name="height">The height of the bitmap.</param> /// <param name="inverted">Whether the bitmap is inverted.</param> /// <param name="redMask">The bitmask for the red channel.</param> /// <param name="greenMask">The bitmask for the green channel.</param> /// <param name="blueMask">The bitmask for the blue channel.</param> private void ReadRgb16<TPixel>(Buffer2D<TPixel> pixels, int width, int height, bool inverted, int redMask = DefaultRgb16RMask, int greenMask = DefaultRgb16GMask, int blueMask = DefaultRgb16BMask) where TPixel : struct, IPixel<TPixel> { int padding = CalculatePadding(width, 2); int stride = (width * 2) + padding; TPixel color = default; int rightShiftRedMask = CalculateRightShift((uint)redMask); int rightShiftGreenMask = CalculateRightShift((uint)greenMask); int rightShiftBlueMask = CalculateRightShift((uint)blueMask); // Each color channel contains either 5 or 6 Bits values. int redMaskBits = CountBits((uint)redMask); int greenMaskBits = CountBits((uint)greenMask); int blueMaskBits = CountBits((uint)blueMask); using (IManagedByteBuffer buffer = this.memoryAllocator.AllocateManagedByteBuffer(stride)) { for (int y = 0; y < height; y++) { this.stream.Read(buffer.Array, 0, stride); int newY = Invert(y, height, inverted); Span<TPixel> pixelRow = pixels.GetRowSpan(newY); int offset = 0; for (int x = 0; x < width; x++) { short temp = BitConverter.ToInt16(buffer.Array, offset); // Rescale values, so the values range from 0 to 255. int r = (redMaskBits == 5) ? GetBytesFrom5BitValue((temp & redMask) >> rightShiftRedMask) : GetBytesFrom6BitValue((temp & redMask) >> rightShiftRedMask); int g = (greenMaskBits == 5) ? GetBytesFrom5BitValue((temp & greenMask) >> rightShiftGreenMask) : GetBytesFrom6BitValue((temp & greenMask) >> rightShiftGreenMask); int b = (blueMaskBits == 5) ? GetBytesFrom5BitValue((temp & blueMask) >> rightShiftBlueMask) : GetBytesFrom6BitValue((temp & blueMask) >> rightShiftBlueMask); var rgb = new Rgb24((byte)r, (byte)g, (byte)b); color.FromRgb24(rgb); pixelRow[x] = color; offset += 2; } } } } /// <summary> /// Performs final shifting from a 5bit value to an 8bit one. /// </summary> /// <param name="value">The masked and shifted value.</param> /// <returns>The <see cref="byte"/></returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] private static byte GetBytesFrom5BitValue(int value) => (byte)((value << 3) | (value >> 2)); /// <summary> /// Performs final shifting from a 6bit value to an 8bit one. /// </summary> /// <param name="value">The masked and shifted value.</param> /// <returns>The <see cref="byte"/></returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] private static byte GetBytesFrom6BitValue(int value) => (byte)((value << 2) | (value >> 4)); /// <summary> /// Reads the 24 bit color palette from the stream. /// </summary> /// <typeparam name="TPixel">The pixel format.</typeparam> /// <param name="pixels">The <see cref="Buffer2D{TPixel}"/> to assign the palette to.</param> /// <param name="width">The width of the bitmap.</param> /// <param name="height">The height of the bitmap.</param> /// <param name="inverted">Whether the bitmap is inverted.</param> private void ReadRgb24<TPixel>(Buffer2D<TPixel> pixels, int width, int height, bool inverted) where TPixel : struct, IPixel<TPixel> { int padding = CalculatePadding(width, 3); using (IManagedByteBuffer row = this.memoryAllocator.AllocatePaddedPixelRowBuffer(width, 3, padding)) { for (int y = 0; y < height; y++) { this.stream.Read(row); int newY = Invert(y, height, inverted); Span<TPixel> pixelSpan = pixels.GetRowSpan(newY); PixelOperations<TPixel>.Instance.FromBgr24Bytes( this.configuration, row.GetSpan(), pixelSpan, width); } } } /// <summary> /// Reads the 32 bit color palette from the stream. /// </summary> /// <typeparam name="TPixel">The pixel format.</typeparam> /// <param name="pixels">The <see cref="Buffer2D{TPixel}"/> to assign the palette to.</param> /// <param name="width">The width of the bitmap.</param> /// <param name="height">The height of the bitmap.</param> /// <param name="inverted">Whether the bitmap is inverted.</param> private void ReadRgb32Fast<TPixel>(Buffer2D<TPixel> pixels, int width, int height, bool inverted) where TPixel : struct, IPixel<TPixel> { int padding = CalculatePadding(width, 4); using (IManagedByteBuffer row = this.memoryAllocator.AllocatePaddedPixelRowBuffer(width, 4, padding)) { for (int y = 0; y < height; y++) { this.stream.Read(row); int newY = Invert(y, height, inverted); Span<TPixel> pixelSpan = pixels.GetRowSpan(newY); PixelOperations<TPixel>.Instance.FromBgra32Bytes( this.configuration, row.GetSpan(), pixelSpan, width); } } } /// <summary> /// Reads the 32 bit color palette from the stream, checking the alpha component of each pixel. /// This is a special case only used for 32bpp WinBMPv3 files, which could be in either BGR0 or BGRA format. /// </summary> /// <typeparam name="TPixel">The pixel format.</typeparam> /// <param name="pixels">The <see cref="Buffer2D{TPixel}"/> to assign the palette to.</param> /// <param name="width">The width of the bitmap.</param> /// <param name="height">The height of the bitmap.</param> /// <param name="inverted">Whether the bitmap is inverted.</param> private void ReadRgb32Slow<TPixel>(Buffer2D<TPixel> pixels, int width, int height, bool inverted) where TPixel : struct, IPixel<TPixel> { int padding = CalculatePadding(width, 4); using (IManagedByteBuffer row = this.memoryAllocator.AllocatePaddedPixelRowBuffer(width, 4, padding)) using (IMemoryOwner<Bgra32> bgraRow = this.memoryAllocator.Allocate<Bgra32>(width)) { Span<Bgra32> bgraRowSpan = bgraRow.GetSpan(); long currentPosition = this.stream.Position; bool hasAlpha = false; // Loop though the rows checking each pixel. We start by assuming it's // an BGR0 image. If we hit a non-zero alpha value, then we know it's // actually a BGRA image, and change tactics accordingly. for (int y = 0; y < height; y++) { this.stream.Read(row); PixelOperations<Bgra32>.Instance.FromBgra32Bytes( this.configuration, row.GetSpan(), bgraRowSpan, width); // Check each pixel in the row to see if it has an alpha value. for (int x = 0; x < width; x++) { Bgra32 bgra = bgraRowSpan[x]; if (bgra.A > 0) { hasAlpha = true; break; } } if (hasAlpha) { break; } } // Reset our stream for a second pass. this.stream.Position = currentPosition; // Process the pixels in bulk taking the raw alpha component value. if (hasAlpha) { for (int y = 0; y < height; y++) { this.stream.Read(row); int newY = Invert(y, height, inverted); Span<TPixel> pixelSpan = pixels.GetRowSpan(newY); PixelOperations<TPixel>.Instance.FromBgra32Bytes( this.configuration, row.GetSpan(), pixelSpan, width); } return; } // Slow path. We need to set each alpha component value to fully opaque. for (int y = 0; y < height; y++) { this.stream.Read(row); PixelOperations<Bgra32>.Instance.FromBgra32Bytes( this.configuration, row.GetSpan(), bgraRowSpan, width); int newY = Invert(y, height, inverted); Span<TPixel> pixelSpan = pixels.GetRowSpan(newY); for (int x = 0; x < width; x++) { Bgra32 bgra = bgraRowSpan[x]; bgra.A = byte.MaxValue; ref TPixel pixel = ref pixelSpan[x]; pixel.FromBgra32(bgra); } } } } /// <summary> /// Decode an 32 Bit Bitmap containing a bitmask for each color channel. /// </summary> /// <typeparam name="TPixel">The pixel format.</typeparam> /// <param name="pixels">The output pixel buffer containing the decoded image.</param> /// <param name="width">The width of the image.</param> /// <param name="height">The height of the image.</param> /// <param name="inverted">Whether the bitmap is inverted.</param> /// <param name="redMask">The bitmask for the red channel.</param> /// <param name="greenMask">The bitmask for the green channel.</param> /// <param name="blueMask">The bitmask for the blue channel.</param> /// <param name="alphaMask">The bitmask for the alpha channel.</param> private void ReadRgb32BitFields<TPixel>(Buffer2D<TPixel> pixels, int width, int height, bool inverted, int redMask, int greenMask, int blueMask, int alphaMask) where TPixel : struct, IPixel<TPixel> { TPixel color = default; int padding = CalculatePadding(width, 4); int stride = (width * 4) + padding; int rightShiftRedMask = CalculateRightShift((uint)redMask); int rightShiftGreenMask = CalculateRightShift((uint)greenMask); int rightShiftBlueMask = CalculateRightShift((uint)blueMask); int rightShiftAlphaMask = CalculateRightShift((uint)alphaMask); int bitsRedMask = CountBits((uint)redMask); int bitsGreenMask = CountBits((uint)greenMask); int bitsBlueMask = CountBits((uint)blueMask); int bitsAlphaMask = CountBits((uint)alphaMask); float invMaxValueRed = 1.0f / (0xFFFFFFFF >> (32 - bitsRedMask)); float invMaxValueGreen = 1.0f / (0xFFFFFFFF >> (32 - bitsGreenMask)); float invMaxValueBlue = 1.0f / (0xFFFFFFFF >> (32 - bitsBlueMask)); uint maxValueAlpha = 0xFFFFFFFF >> (32 - bitsAlphaMask); float invMaxValueAlpha = 1.0f / maxValueAlpha; bool unusualBitMask = false; if (bitsRedMask > 8 || bitsGreenMask > 8 || bitsBlueMask > 8 || invMaxValueAlpha > 8) { unusualBitMask = true; } using (IManagedByteBuffer buffer = this.memoryAllocator.AllocateManagedByteBuffer(stride)) { for (int y = 0; y < height; y++) { this.stream.Read(buffer.Array, 0, stride); int newY = Invert(y, height, inverted); Span<TPixel> pixelRow = pixels.GetRowSpan(newY); int offset = 0; for (int x = 0; x < width; x++) { uint temp = BitConverter.ToUInt32(buffer.Array, offset); if (unusualBitMask) { uint r = (uint)(temp & redMask) >> rightShiftRedMask; uint g = (uint)(temp & greenMask) >> rightShiftGreenMask; uint b = (uint)(temp & blueMask) >> rightShiftBlueMask; float alpha = alphaMask != 0 ? invMaxValueAlpha * ((uint)(temp & alphaMask) >> rightShiftAlphaMask) : 1.0f; var vector4 = new Vector4( r * invMaxValueRed, g * invMaxValueGreen, b * invMaxValueBlue, alpha); color.FromVector4(vector4); } else { byte r = (byte)((temp & redMask) >> rightShiftRedMask); byte g = (byte)((temp & greenMask) >> rightShiftGreenMask); byte b = (byte)((temp & blueMask) >> rightShiftBlueMask); byte a = alphaMask != 0 ? (byte)((temp & alphaMask) >> rightShiftAlphaMask) : (byte)255; color.FromRgba32(new Rgba32(r, g, b, a)); } pixelRow[x] = color; offset += 4; } } } } /// <summary> /// Calculates the necessary right shifts for a given color bitmask (the 0 bits to the right). /// </summary> /// <param name="n">The color bit mask.</param> /// <returns>Number of bits to shift right.</returns> private static int CalculateRightShift(uint n) { int count = 0; while (n > 0) { if ((1 & n) == 0) { count++; } else { break; } n >>= 1; } return count; } /// <summary> /// Counts none zero bits. /// </summary> /// <param name="n">A color mask.</param> /// <returns>The none zero bits.</returns> private static int CountBits(uint n) { int count = 0; while (n != 0) { count++; n &= n - 1; } return count; } /// <summary> /// Reads the <see cref="BmpInfoHeader"/> from the stream. /// </summary> private void ReadInfoHeader() { #if NETCOREAPP2_1 Span<byte> buffer = stackalloc byte[BmpInfoHeader.MaxHeaderSize]; #else byte[] buffer = new byte[BmpInfoHeader.MaxHeaderSize]; #endif this.stream.Read(buffer, 0, BmpInfoHeader.HeaderSizeSize); // read the header size int headerSize = BinaryPrimitives.ReadInt32LittleEndian(buffer); if (headerSize < BmpInfoHeader.CoreSize) { BmpThrowHelper.ThrowNotSupportedException($"ImageSharp does not support this BMP file. HeaderSize is '{headerSize}'."); } int skipAmount = 0; if (headerSize > BmpInfoHeader.MaxHeaderSize) { skipAmount = headerSize - BmpInfoHeader.MaxHeaderSize; headerSize = BmpInfoHeader.MaxHeaderSize; } // read the rest of the header this.stream.Read(buffer, BmpInfoHeader.HeaderSizeSize, headerSize - BmpInfoHeader.HeaderSizeSize); BmpInfoHeaderType infoHeaderType = BmpInfoHeaderType.WinVersion2; if (headerSize == BmpInfoHeader.CoreSize) { // 12 bytes infoHeaderType = BmpInfoHeaderType.WinVersion2; this.infoHeader = BmpInfoHeader.ParseCore(buffer); } else if (headerSize == BmpInfoHeader.Os22ShortSize) { // 16 bytes infoHeaderType = BmpInfoHeaderType.Os2Version2Short; this.infoHeader = BmpInfoHeader.ParseOs22Short(buffer); } else if (headerSize == BmpInfoHeader.SizeV3) { // == 40 bytes infoHeaderType = BmpInfoHeaderType.WinVersion3; this.infoHeader = BmpInfoHeader.ParseV3(buffer); // if the info header is BMP version 3 and the compression type is BITFIELDS, // color masks for each color channel follow the info header. if (this.infoHeader.Compression == BmpCompression.BitFields) { byte[] bitfieldsBuffer = new byte[12]; this.stream.Read(bitfieldsBuffer, 0, 12); Span<byte> data = bitfieldsBuffer.AsSpan<byte>(); this.infoHeader.RedMask = BinaryPrimitives.ReadInt32LittleEndian(data.Slice(0, 4)); this.infoHeader.GreenMask = BinaryPrimitives.ReadInt32LittleEndian(data.Slice(4, 4)); this.infoHeader.BlueMask = BinaryPrimitives.ReadInt32LittleEndian(data.Slice(8, 4)); } } else if (headerSize == BmpInfoHeader.AdobeV3Size) { // == 52 bytes infoHeaderType = BmpInfoHeaderType.AdobeVersion3; this.infoHeader = BmpInfoHeader.ParseAdobeV3(buffer, withAlpha: false); } else if (headerSize == BmpInfoHeader.AdobeV3WithAlphaSize) { // == 56 bytes infoHeaderType = BmpInfoHeaderType.AdobeVersion3WithAlpha; this.infoHeader = BmpInfoHeader.ParseAdobeV3(buffer, withAlpha: true); } else if (headerSize == BmpInfoHeader.Os2v2Size) { // == 64 bytes infoHeaderType = BmpInfoHeaderType.Os2Version2; this.infoHeader = BmpInfoHeader.ParseOs2Version2(buffer); } else if (headerSize >= BmpInfoHeader.SizeV4) { // >= 108 bytes infoHeaderType = headerSize == BmpInfoHeader.SizeV4 ? BmpInfoHeaderType.WinVersion4 : BmpInfoHeaderType.WinVersion5; this.infoHeader = BmpInfoHeader.ParseV4(buffer); } else { BmpThrowHelper.ThrowNotSupportedException($"ImageSharp does not support this BMP file. HeaderSize '{headerSize}'."); } // Resolution is stored in PPM. var meta = new ImageMetaData { ResolutionUnits = PixelResolutionUnit.PixelsPerMeter }; if (this.infoHeader.XPelsPerMeter > 0 && this.infoHeader.YPelsPerMeter > 0) { meta.HorizontalResolution = this.infoHeader.XPelsPerMeter; meta.VerticalResolution = this.infoHeader.YPelsPerMeter; } else { // Convert default metadata values to PPM. meta.HorizontalResolution = Math.Round(UnitConverter.InchToMeter(ImageMetaData.DefaultHorizontalResolution)); meta.VerticalResolution = Math.Round(UnitConverter.InchToMeter(ImageMetaData.DefaultVerticalResolution)); } this.metaData = meta; short bitsPerPixel = this.infoHeader.BitsPerPixel; this.bmpMetaData = this.metaData.GetFormatMetaData(BmpFormat.Instance); this.bmpMetaData.InfoHeaderType = infoHeaderType; // We can only encode at these bit rates so far. if (bitsPerPixel.Equals((short)BmpBitsPerPixel.Pixel24) || bitsPerPixel.Equals((short)BmpBitsPerPixel.Pixel32)) { this.bmpMetaData.BitsPerPixel = (BmpBitsPerPixel)bitsPerPixel; } // skip the remaining header because we can't read those parts this.stream.Skip(skipAmount); } /// <summary> /// Reads the <see cref="BmpFileHeader"/> from the stream. /// </summary> private void ReadFileHeader() { #if NETCOREAPP2_1 Span<byte> buffer = stackalloc byte[BmpFileHeader.Size]; #else byte[] buffer = new byte[BmpFileHeader.Size]; #endif this.stream.Read(buffer, 0, BmpFileHeader.Size); this.fileHeader = BmpFileHeader.Parse(buffer); if (this.fileHeader.Type != BmpConstants.TypeMarkers.Bitmap) { BmpThrowHelper.ThrowNotSupportedException($"ImageSharp does not support this BMP file. File header bitmap type marker '{this.fileHeader.Type}'."); } } /// <summary> /// Reads the <see cref="BmpFileHeader"/> and <see cref="BmpInfoHeader"/> from the stream and sets the corresponding fields. /// </summary> /// <returns>Bytes per color palette entry. Usually 4 bytes, but in case of Windows 2.x bitmaps or OS/2 1.x bitmaps /// the bytes per color palette entry's can be 3 bytes instead of 4.</returns> private int ReadImageHeaders(Stream stream, out bool inverted, out byte[] palette) { this.stream = stream; this.ReadFileHeader(); this.ReadInfoHeader(); // see http://www.drdobbs.com/architecture-and-design/the-bmp-file-format-part-1/184409517 // If the height is negative, then this is a Windows bitmap whose origin // is the upper-left corner and not the lower-left. The inverted flag // indicates a lower-left origin.Our code will be outputting an // upper-left origin pixel array. inverted = false; if (this.infoHeader.Height < 0) { inverted = true; this.infoHeader.Height = -this.infoHeader.Height; } int colorMapSize = -1; int bytesPerColorMapEntry = 4; if (this.infoHeader.ClrUsed == 0) { if (this.infoHeader.BitsPerPixel == 1 || this.infoHeader.BitsPerPixel == 4 || this.infoHeader.BitsPerPixel == 8) { int colorMapSizeBytes = this.fileHeader.Offset - BmpFileHeader.Size - this.infoHeader.HeaderSize; int colorCountForBitDepth = ImageMaths.GetColorCountForBitDepth(this.infoHeader.BitsPerPixel); bytesPerColorMapEntry = colorMapSizeBytes / colorCountForBitDepth; colorMapSize = colorMapSizeBytes; } } else { colorMapSize = this.infoHeader.ClrUsed * bytesPerColorMapEntry; } palette = null; if (colorMapSize > 0) { // 256 * 4 if (colorMapSize > 1024) { BmpThrowHelper.ThrowImageFormatException($"Invalid bmp colormap size '{colorMapSize}'"); } palette = new byte[colorMapSize]; this.stream.Read(palette, 0, colorMapSize); } this.infoHeader.VerifyDimensions(); int skipAmount = this.fileHeader.Offset - (int)this.stream.Position; if ((skipAmount + (int)this.stream.Position) > this.stream.Length) { BmpThrowHelper.ThrowImageFormatException($"Invalid fileheader offset found. Offset is greater than the stream length."); } if (skipAmount > 0) { this.stream.Skip(skipAmount); } return bytesPerColorMapEntry; } } }
42.126786
203
0.50479
[ "Apache-2.0" ]
SirusDoma/ImageSharp
src/ImageSharp/Formats/Bmp/BmpDecoderCore.cs
47,184
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.InteropServices; using System.Runtime.Loader; namespace Internal.Runtime.InteropServices { /// <summary> /// This class enables the .NET IJW host to load an in-memory module as a .NET assembly /// </summary> public static class InMemoryAssemblyLoader { /// <summary> /// Loads into an isolated AssemblyLoadContext an assembly that has already been loaded into memory by the OS loader as a native module. /// </summary> /// <param name="moduleHandle">The native module handle for the assembly.</param> /// <param name="assemblyPath">The path to the assembly (as a pointer to a UTF-16 C string).</param> public static unsafe void LoadInMemoryAssembly(IntPtr moduleHandle, IntPtr assemblyPath) { string? assemblyPathString = Marshal.PtrToStringUni(assemblyPath); if (assemblyPathString == null) { throw new ArgumentOutOfRangeException(nameof(assemblyPath)); } // We don't cache the ALCs here since each IJW assembly will call this method at most once // (the load process rewrites the stubs that call here to call the actual methods they're supposed to) AssemblyLoadContext context = new IsolatedComponentLoadContext(assemblyPathString); context.LoadFromInMemoryModule(moduleHandle); } } }
45.222222
144
0.684889
[ "MIT" ]
1shekhar/runtime
src/coreclr/src/System.Private.CoreLib/src/Internal/Runtime/InteropServices/InMemoryAssemblyLoader.cs
1,628
C#
using System.Linq; using FluentAssertions; using HealthChecks.Kubernetes; using HealthChecks.MongoDb; using k8s; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Options; using Xunit; namespace UnitTests.DependencyInjection.Kubernetes { public class kubernetes_registration_should { [Fact] public void add_health_check_when_properly_configured() { var services = new ServiceCollection(); services.AddHealthChecks() .AddKubernetes(setup => { setup.WithConfiguration(new KubernetesClientConfiguration() { Host = "https://localhost:443", SkipTlsVerify = true }).CheckService("DummyService", s => s.Spec.Type == "LoadBalancer"); }); var serviceProvider = services.BuildServiceProvider(); var options = serviceProvider.GetService<IOptions<HealthCheckServiceOptions>>(); var registration = options.Value.Registrations.First(); var check = registration.Factory(serviceProvider); registration.Name.Should().Be("k8s"); check.GetType().Should().Be(typeof(KubernetesHealthCheck)); } [Fact] public void add_named_health_check_when_properly_configured() { var services = new ServiceCollection(); services.AddHealthChecks() .AddKubernetes(setup => { setup.WithConfiguration(new KubernetesClientConfiguration() { Host = "https://localhost:443", SkipTlsVerify = true }).CheckService("DummyService", s => s.Spec.Type == "LoadBalancer"); }, name: "second-k8s-cluster"); var serviceProvider = services.BuildServiceProvider(); var options = serviceProvider.GetService<IOptions<HealthCheckServiceOptions>>(); var registration = options.Value.Registrations.First(); var check = registration.Factory(serviceProvider); registration.Name.Should().Be("second-k8s-cluster"); check.GetType().Should().Be(typeof(KubernetesHealthCheck)); } } }
37.904762
92
0.600084
[ "Apache-2.0" ]
Ahmad-Magdy/AspNetCore.Diagnostics.HealthChecks
test/UnitTests/DependencyInjection/Kubernetes/KubernetesUnitTests.cs
2,388
C#
// // Platform.cs // // Author: // Mikayla Hutchinson <m.j.hutchinson@gmail.com> // // Copyright (c) 2011 Xamarin Inc. (http://xamarin.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.Runtime.InteropServices; using System.IO; //from MonoDevelop.Core.Platform namespace MonoDevelop.MSBuild.Util { static class Platform { public readonly static bool IsWindows; public readonly static bool IsMac; public readonly static bool IsLinux; public static Version OSVersion { get; private set; } static Platform () { IsWindows = Path.DirectorySeparatorChar == '\\'; IsMac = !IsWindows && IsRunningOnMac (); IsLinux = !IsMac && !IsWindows; OSVersion = Environment.OSVersion.Version; } public static void Initialize () { //no-op, triggers static ctor } [DllImport ("libc")] static extern int uname (IntPtr buf); //From Managed.Windows.Forms/XplatUI static bool IsRunningOnMac () { IntPtr buf = IntPtr.Zero; try { buf = Marshal.AllocHGlobal (8192); // This is a hacktastic way of getting sysname from uname () if (uname (buf) == 0) { string os = Marshal.PtrToStringAnsi (buf); if (os == "Darwin") return true; } } catch { } finally { if (buf != IntPtr.Zero) Marshal.FreeHGlobal (buf); } return false; } } }
30.512821
80
0.705462
[ "Apache-2.0" ]
DavidKarlas/MonoDevelop.MSBuildEditor
MonoDevelop.MSBuild/Util/Platform.cs
2,382
C#
using System.Collections.Generic; namespace ChessEngine.Engine { internal static class PieceValidMoves { private static void AnalyzeMovePawn(Board board, byte dstPos, Piece pcMoving) { //Because Pawns only kill diagonaly we handle the En Passant scenario specialy if (board.EnPassantPosition > 0) { if (pcMoving.PieceColor != board.EnPassantColor) { if (board.EnPassantPosition == dstPos) { //We have an En Passant Possible pcMoving.ValidMoves.Push(dstPos); if (pcMoving.PieceColor == ChessPieceColor.White) { board.WhiteAttackBoard[dstPos] = true; } else { board.BlackAttackBoard[dstPos] = true; } } } } Piece pcAttacked = board.Squares[dstPos].Piece; //If there no piece there I can potentialy kill if (pcAttacked == null) return; //Regardless of what is there I am attacking this square if (pcMoving.PieceColor == ChessPieceColor.White) { board.WhiteAttackBoard[dstPos] = true; //if that piece is the same color if (pcAttacked.PieceColor == pcMoving.PieceColor) { pcAttacked.DefendedValue += pcMoving.PieceActionValue; return; } pcAttacked.AttackedValue += pcMoving.PieceActionValue; //If this is a king set it in check if (pcAttacked.PieceType == ChessPieceType.King) { board.BlackCheck = true; } else { //Add this as a valid move pcMoving.ValidMoves.Push(dstPos); } } else { board.BlackAttackBoard[dstPos] = true; //if that piece is the same color if (pcAttacked.PieceColor == pcMoving.PieceColor) { pcAttacked.DefendedValue += pcMoving.PieceActionValue; return; } pcAttacked.AttackedValue += pcMoving.PieceActionValue; //If this is a king set it in check if (pcAttacked.PieceType == ChessPieceType.King) { board.WhiteCheck = true; } else { //Add this as a valid move pcMoving.ValidMoves.Push(dstPos); } } return; } private static bool AnalyzeMove(Board board, byte dstPos, Piece pcMoving) { //If I am not a pawn everywhere I move I can attack if (pcMoving.PieceColor == ChessPieceColor.White) { board.WhiteAttackBoard[dstPos] = true; } else { board.BlackAttackBoard[dstPos] = true; } //If there no piece there I can potentialy kill just add the move and exit if (board.Squares[dstPos].Piece == null) { pcMoving.ValidMoves.Push(dstPos); return true; } Piece pcAttacked = board.Squares[dstPos].Piece; //if that piece is a different color if (pcAttacked.PieceColor != pcMoving.PieceColor) { pcAttacked.AttackedValue += pcMoving.PieceActionValue; //If this is a king set it in check if (pcAttacked.PieceType == ChessPieceType.King) { if (pcAttacked.PieceColor == ChessPieceColor.Black) { board.BlackCheck = true; } else { board.WhiteCheck = true; } } else { //Add this as a valid move pcMoving.ValidMoves.Push(dstPos); } //We don't continue movement past this piece return false; } //Same Color I am defending pcAttacked.DefendedValue += pcMoving.PieceActionValue; //Since this piece is of my kind I can't move there return false; } private static void CheckValidMovesPawn(List<byte> moves, Piece pcMoving, byte srcPosition, Board board, byte count) { for (byte i = 0; i < count; i++) { byte dstPos = moves[i]; //Diagonal if (dstPos%8 != srcPosition%8) { //If there is a piece there I can potentialy kill AnalyzeMovePawn(board, dstPos, pcMoving); if (pcMoving.PieceColor == ChessPieceColor.White) { board.WhiteAttackBoard[dstPos] = true; } else { board.BlackAttackBoard[dstPos] = true; } } // if there is something if front pawns can't move there else if (board.Squares[dstPos].Piece != null) { return; } //if there is nothing in front of else { pcMoving.ValidMoves.Push(dstPos); } } } private static void GenerateValidMovesKing(Piece piece, Board board, byte srcPosition) { if (piece == null) { return; } for (byte i = 0; i < MoveArrays.KingTotalMoves[srcPosition]; i++) { byte dstPos = MoveArrays.KingMoves[srcPosition].Moves[i]; if (piece.PieceColor == ChessPieceColor.White) { //I can't move where I am being attacked if (board.BlackAttackBoard[dstPos]) { board.WhiteAttackBoard[dstPos] = true; continue; } } else { if (board.WhiteAttackBoard[dstPos]) { board.BlackAttackBoard[dstPos] = true; continue; } } AnalyzeMove(board, dstPos, piece); } } private static void GenerateValidMovesKingCastle(Board board, Piece king) { //This code will add the castleling move to the pieces available moves if (king.PieceColor == ChessPieceColor.White) { if (board.Squares[63].Piece != null) { //Check if the Right Rook is still in the correct position if (board.Squares[63].Piece.PieceType == ChessPieceType.Rook) { if (board.Squares[63].Piece.PieceColor == king.PieceColor) { //Move one column to right see if its empty if (board.Squares[62].Piece == null) { if (board.Squares[61].Piece == null) { if (board.BlackAttackBoard[61] == false && board.BlackAttackBoard[62] == false) { //Ok looks like move is valid lets add it king.ValidMoves.Push(62); board.WhiteAttackBoard[62] = true; } } } } } } if (board.Squares[56].Piece != null) { //Check if the Left Rook is still in the correct position if (board.Squares[56].Piece.PieceType == ChessPieceType.Rook) { if (board.Squares[56].Piece.PieceColor == king.PieceColor) { //Move one column to right see if its empty if (board.Squares[57].Piece == null) { if (board.Squares[58].Piece == null) { if (board.Squares[59].Piece == null) { if (board.BlackAttackBoard[58] == false && board.BlackAttackBoard[59] == false) { //Ok looks like move is valid lets add it king.ValidMoves.Push(58); board.WhiteAttackBoard[58] = true; } } } } } } } } else if (king.PieceColor == ChessPieceColor.Black) { //There are two ways to castle, scenario 1: if (board.Squares[7].Piece != null) { //Check if the Right Rook is still in the correct position if (board.Squares[7].Piece.PieceType == ChessPieceType.Rook && !board.Squares[7].Piece.Moved) { if (board.Squares[7].Piece.PieceColor == king.PieceColor) { //Move one column to right see if its empty if (board.Squares[6].Piece == null) { if (board.Squares[5].Piece == null) { if (board.WhiteAttackBoard[5] == false && board.WhiteAttackBoard[6] == false) { //Ok looks like move is valid lets add it king.ValidMoves.Push(6); board.BlackAttackBoard[6] = true; } } } } } } //There are two ways to castle, scenario 2: if (board.Squares[0].Piece != null) { //Check if the Left Rook is still in the correct position if (board.Squares[0].Piece.PieceType == ChessPieceType.Rook && !board.Squares[0].Piece.Moved) { if (board.Squares[0].Piece.PieceColor == king.PieceColor) { //Move one column to right see if its empty if (board.Squares[1].Piece == null) { if (board.Squares[2].Piece == null) { if (board.Squares[3].Piece == null) { if (board.WhiteAttackBoard[2] == false && board.WhiteAttackBoard[3] == false) { //Ok looks like move is valid lets add it king.ValidMoves.Push(2); board.BlackAttackBoard[2] = true; } } } } } } } } } internal static void GenerateValidMoves(Board board) { // Reset Board board.BlackCheck = false; board.WhiteCheck = false; byte blackRooksMoved = 0; byte whiteRooksMoved = 0; //Calculate Remaining Material on Board to make the End Game Decision int remainingPieces = 0; //Generate Moves for (byte x = 0; x < 64; x++) { Square sqr = board.Squares[x]; if (sqr.Piece == null) continue; sqr.Piece.ValidMoves = new Stack<byte>(sqr.Piece.LastValidMoveCount); remainingPieces++; switch (sqr.Piece.PieceType) { case ChessPieceType.Pawn: { if (sqr.Piece.PieceColor == ChessPieceColor.White) { CheckValidMovesPawn(MoveArrays.WhitePawnMoves[x].Moves, sqr.Piece, x, board, MoveArrays.WhitePawnTotalMoves[x]); break; } if (sqr.Piece.PieceColor == ChessPieceColor.Black) { CheckValidMovesPawn(MoveArrays.BlackPawnMoves[x].Moves, sqr.Piece, x, board, MoveArrays.BlackPawnTotalMoves[x]); break; } break; } case ChessPieceType.Knight: { for (byte i = 0; i < MoveArrays.KnightTotalMoves[x]; i++) { AnalyzeMove(board, MoveArrays.KnightMoves[x].Moves[i], sqr.Piece); } break; } case ChessPieceType.Bishop: { for (byte i = 0; i < MoveArrays.BishopTotalMoves1[x]; i++) { if ( AnalyzeMove(board, MoveArrays.BishopMoves1[x].Moves[i], sqr.Piece) == false) { break; } } for (byte i = 0; i < MoveArrays.BishopTotalMoves2[x]; i++) { if ( AnalyzeMove(board, MoveArrays.BishopMoves2[x].Moves[i], sqr.Piece) == false) { break; } } for (byte i = 0; i < MoveArrays.BishopTotalMoves3[x]; i++) { if ( AnalyzeMove(board, MoveArrays.BishopMoves3[x].Moves[i], sqr.Piece) == false) { break; } } for (byte i = 0; i < MoveArrays.BishopTotalMoves4[x]; i++) { if ( AnalyzeMove(board, MoveArrays.BishopMoves4[x].Moves[i], sqr.Piece) == false) { break; } } break; } case ChessPieceType.Rook: { if (sqr.Piece.Moved) { if (sqr.Piece.PieceColor == ChessPieceColor.Black) { blackRooksMoved++; } else { whiteRooksMoved++; } } for (byte i = 0; i < MoveArrays.RookTotalMoves1[x]; i++) { if ( AnalyzeMove(board, MoveArrays.RookMoves1[x].Moves[i], sqr.Piece) == false) { break; } } for (byte i = 0; i < MoveArrays.RookTotalMoves2[x]; i++) { if ( AnalyzeMove(board, MoveArrays.RookMoves2[x].Moves[i], sqr.Piece) == false) { break; } } for (byte i = 0; i < MoveArrays.RookTotalMoves3[x]; i++) { if ( AnalyzeMove(board, MoveArrays.RookMoves3[x].Moves[i], sqr.Piece) == false) { break; } } for (byte i = 0; i < MoveArrays.RookTotalMoves4[x]; i++) { if ( AnalyzeMove(board, MoveArrays.RookMoves4[x].Moves[i], sqr.Piece) == false) { break; } } break; } case ChessPieceType.Queen: { for (byte i = 0; i < MoveArrays.QueenTotalMoves1[x]; i++) { if ( AnalyzeMove(board, MoveArrays.QueenMoves1[x].Moves[i], sqr.Piece) == false) { break; } } for (byte i = 0; i < MoveArrays.QueenTotalMoves2[x]; i++) { if ( AnalyzeMove(board, MoveArrays.QueenMoves2[x].Moves[i], sqr.Piece) == false) { break; } } for (byte i = 0; i < MoveArrays.QueenTotalMoves3[x]; i++) { if ( AnalyzeMove(board, MoveArrays.QueenMoves3[x].Moves[i], sqr.Piece) == false) { break; } } for (byte i = 0; i < MoveArrays.QueenTotalMoves4[x]; i++) { if ( AnalyzeMove(board, MoveArrays.QueenMoves4[x].Moves[i], sqr.Piece) == false) { break; } } for (byte i = 0; i < MoveArrays.QueenTotalMoves5[x]; i++) { if ( AnalyzeMove(board, MoveArrays.QueenMoves5[x].Moves[i], sqr.Piece) == false) { break; } } for (byte i = 0; i < MoveArrays.QueenTotalMoves6[x]; i++) { if ( AnalyzeMove(board, MoveArrays.QueenMoves6[x].Moves[i], sqr.Piece) == false) { break; } } for (byte i = 0; i < MoveArrays.QueenTotalMoves7[x]; i++) { if ( AnalyzeMove(board, MoveArrays.QueenMoves7[x].Moves[i], sqr.Piece) == false) { break; } } for (byte i = 0; i < MoveArrays.QueenTotalMoves8[x]; i++) { if ( AnalyzeMove(board, MoveArrays.QueenMoves8[x].Moves[i], sqr.Piece) == false) { break; } } break; } case ChessPieceType.King: { if (sqr.Piece.PieceColor == ChessPieceColor.White) { if (sqr.Piece.Moved) { board.WhiteCanCastle = false; } board.WhiteKingPosition = x; } else { if (sqr.Piece.Moved) { board.BlackCanCastle = false; } board.BlackKingPosition = x; } break; } } } if (blackRooksMoved > 1) { board.BlackCanCastle = false; } if (whiteRooksMoved > 1) { board.WhiteCanCastle = false; } if (remainingPieces < 10) { board.EndGamePhase = true; } if (board.WhoseMove == ChessPieceColor.White) { GenerateValidMovesKing(board.Squares[board.BlackKingPosition].Piece, board, board.BlackKingPosition); GenerateValidMovesKing(board.Squares[board.WhiteKingPosition].Piece, board, board.WhiteKingPosition); } else { GenerateValidMovesKing(board.Squares[board.WhiteKingPosition].Piece, board, board.WhiteKingPosition); GenerateValidMovesKing(board.Squares[board.BlackKingPosition].Piece, board, board.BlackKingPosition); } //Now that all the pieces were examined we know if the king is in check if (!board.WhiteCastled && board.WhiteCanCastle && !board.WhiteCheck) { GenerateValidMovesKingCastle(board, board.Squares[board.WhiteKingPosition].Piece); } if (!board.BlackCastled && board.BlackCanCastle && !board.BlackCheck) { GenerateValidMovesKingCastle(board, board.Squares[board.BlackKingPosition].Piece); } } } }
40.683121
113
0.334534
[ "MIT" ]
A-Abdiukov/Chess-with-AI
NewChess/ChessCoreEngine/PieceValidMoves.cs
25,549
C#
// // WinRawJoystick.cs // // Author: // Stefanos A. <stapostol@gmail.com> // // Copyright (c) 2014 Stefanos Apostolopoulos // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using OpenTK.Input.Hid; using OpenTK.Input; using OpenTK.NT.Native; using OpenTK.Mathematics; namespace OpenTK.Platform.Windows { internal class WinRawJoystick : IJoystickDriver2 { private static readonly string TypeName = typeof(WinRawJoystick).Name; private readonly DeviceCollection<Device> Devices = new DeviceCollection<Device>(); // Defines which types of HID devices we are interested in private readonly RawInputDevice[] DeviceTypes; private readonly object UpdateLock = new object(); private readonly XInputJoystick XInput = new XInputJoystick(); private HidProtocolData[] DataBuffer = new HidProtocolData[16]; private RawInput _rawData = default(RawInput); private byte[] PreparsedData = new byte[1024]; public WinRawJoystick(IntPtr window) { Debug.WriteLine("Using WinRawJoystick."); Debug.Indent(); if (window == IntPtr.Zero) throw new ArgumentNullException(nameof(window)); DeviceTypes = new[] { new RawInputDevice(HidGenericDesktopUsage.Joystick, RawInputDeviceFlags.DevNotify | RawInputDeviceFlags.InputSink, window), new RawInputDevice(HidGenericDesktopUsage.GamePad, RawInputDeviceFlags.DevNotify | RawInputDeviceFlags.InputSink, window), new RawInputDevice(HidConsumerUsage.ConsumerControl, RawInputDeviceFlags.DevNotify | RawInputDeviceFlags.InputSink, window) }; if (!User32.RawInput.RegisterRawInputDevices(DeviceTypes, (uint)DeviceTypes.Length, RawInputDevice.SizeInBytes)) { Debug.Print("[Warning] Raw input registration failed with error: {0}.", Marshal.GetLastWin32Error()); } else { Debug.Print("[WinRawJoystick] Registered for raw input"); } RefreshDevices(); Debug.Unindent(); } public JoystickState GetState(int index) { lock (UpdateLock) { if (IsValid(index)) { var dev = Devices.FromIndex(index); if (dev.IsXInput) return XInput.GetState(dev.XInputIndex); return dev.GetState(); } return new JoystickState(); } } public JoystickCapabilities GetCapabilities(int index) { lock (UpdateLock) { if (IsValid(index)) { var dev = Devices.FromIndex(index); if (dev.IsXInput) return XInput.GetCapabilities(dev.XInputIndex); return dev.GetCapabilities(); } return new JoystickCapabilities(); } } public Guid GetGuid(int index) { lock (UpdateLock) { if (IsValid(index)) { var dev = Devices.FromIndex(index); if (dev.IsXInput) return XInput.GetGuid(dev.XInputIndex); return dev.GetGuid(); } return new Guid(); } } public void RefreshDevices() { // Mark all devices as disconnected. We will check which of those // are connected below. foreach (var device in Devices) device.SetConnected(false); // Discover joystick devices var xinput_device_count = 0; foreach (var dev in WinRawInput.GetDeviceList()) { // Skip non-joystick devices if (dev.Type != RawInputDeviceType.Hid) continue; // We use the device handle as the hardware id. // This works, but the handle will change whenever the // device is unplugged/replugged. We compensate for this // by checking device GUIDs, below. // Note: we cannot use the GUID as the hardware id, // because it is costly to query (and we need to query // that every time we process a device event.) var handle = dev.Device; var is_xinput = IsXInput(handle); var guid = GetDeviceGuid(handle); var hardware_id = handle.ToInt64(); var device = Devices.FromHardwareId(hardware_id); if (device != null) { // We have already opened this device, mark it as connected device.SetConnected(true); } else { device = new Device(handle, guid, is_xinput, is_xinput ? xinput_device_count++ : 0); // This is a new device, query its capabilities and add it // to the device list if (!QueryDeviceCaps(device) && !is_xinput) continue; device.SetConnected(true); // Check if a disconnected device with identical GUID already exists. // If so, replace that device with this instance. Device match = null; foreach (var candidate in Devices) if (candidate.GetGuid() == guid && !candidate.GetCapabilities().IsConnected) match = candidate; if (match != null) Devices.Remove(match.Handle.ToInt64()); Devices.Add(hardware_id, device); Debug.Print("[{0}] Connected joystick {1} ({2})", GetType().Name, device.GetGuid(), device.GetCapabilities()); } } } public unsafe bool ProcessEvent(IntPtr raw) { // Query the size of the raw HID data buffer uint size = 0; User32.RawInput.GetRawInputData(raw, GetRawInputDataCommand.Input, IntPtr.Zero, ref size, RawInputHeader.SizeInBytes); // Retrieve the raw HID data buffer if (User32.RawInput.GetRawInputData(raw, out _rawData) > 0) { fixed (RawInput* rin = &_rawData) { var handle = rin->Header.Device; var stick = GetDevice(handle); if (stick == null) { Debug.Print("[WinRawJoystick] Unknown device {0}", handle); return false; } if (stick.IsXInput) return true; if (!GetPreparsedData(handle, ref PreparsedData)) return false; // Query current state // Allocate enough storage to hold the data of the current report var report_count = HidProtocol.MaxDataListLength(HidProtocolReportType.Input, PreparsedData); if (report_count == 0) { Debug.Print("[WinRawJoystick] HidProtocol.MaxDataListLength() failed with {0}", Marshal.GetLastWin32Error()); return false; } // Fill the data buffer if (DataBuffer.Length < report_count) Array.Resize(ref DataBuffer, report_count); UpdateAxes(rin, stick); UpdateButtons(rin, stick); return true; } } return false; } private HatPosition GetHatPosition(uint value, HidProtocolValueCaps caps) { if (value > caps.LogicalMax) { //Return zero if our value is out of bounds ==> e.g. //Thrustmaster T-Flight Hotas X returns 15 for the centered position return HatPosition.Centered; } if (caps.LogicalMax == 3) { //4-way hat switch as per the example in Appendix C //http://www.usb.org/developers/hidpage/Hut1_12v2.pdf switch (value) { case 0: return HatPosition.Left; case 1: return HatPosition.Up; case 2: return HatPosition.Right; case 3: return HatPosition.Down; } } if (caps.LogicalMax == 8) { //Hat states are represented as a plain number from 0-8 //with centered being zero //Padding should have already been stripped out, so just cast return (HatPosition)value; } if (caps.LogicalMax == 7) { //Hat states are represented as a plain number from 0-7 //with centered being 8 value++; value %= 9; return (HatPosition)value; } //The HID report length is unsupported return HatPosition.Centered; } private unsafe void UpdateAxes(RawInput* rin, Device stick) { for (var i = 0; i < stick.AxisCaps.Count; i++) { if (stick.AxisCaps[i].IsRange) { Debug.Print( "[{0}] Axis range collections not implemented. Please report your controller type at https://github.com/opentk/opentk/issues", GetType().Name); continue; } var page = stick.AxisCaps[i].UsagePage; var usage = stick.AxisCaps[i].NotRange.Usage; uint value = 0; var collection = stick.AxisCaps[i].LinkCollection; var status = HidProtocol.GetUsageValue( HidProtocolReportType.Input, page, 0, usage, ref value, PreparsedData, new IntPtr(&rin->Data.Hid.RawData), (int)rin->Data.Hid.SizeHid ); if (status != HidProtocolStatus.Success) { Debug.Print("[{0}] HidProtocol.GetScaledUsageValue() failed. Error: {1}", GetType().Name, status); continue; } if (page == HidPage.GenericDesktop && (HidGenericDesktopUsage)usage == HidGenericDesktopUsage.Hatswitch) { stick.SetHat(collection, page, usage, GetHatPosition(value, stick.AxisCaps[i])); } else if (stick.AxisCaps[i].LogicalMin > 0) { short scaled_value = (short)MathHelper.ScaleValue( (int)(value + stick.AxisCaps[i].LogicalMin), stick.AxisCaps[i].LogicalMin, stick.AxisCaps[i].LogicalMax, short.MinValue, short.MaxValue ); stick.SetAxis(collection, page, usage, scaled_value); } else { //If our stick returns a minimum value below zero, we should not add this to our value //before attempting to scale it, as this then inverts the value var scaled_value = (short)MathHelper.ScaleValue( (int)value, stick.AxisCaps[i].LogicalMin, stick.AxisCaps[i].LogicalMax, short.MinValue, short.MaxValue ); stick.SetAxis(collection, page, usage, scaled_value); } } } private unsafe void UpdateButtons(RawInput* rin, Device stick) { stick.ClearButtons(); for (var i = 0; i < stick.ButtonCaps.Count; i++) { short* usage_list = stackalloc short[64]; var usage_length = 64; var page = stick.ButtonCaps[i].UsagePage; var collection = stick.ButtonCaps[i].LinkCollection; var status = HidProtocol.GetUsages( HidProtocolReportType.Input, page, 0, usage_list, ref usage_length, PreparsedData, new IntPtr(&rin->Data.Hid.RawData), (int)rin->Data.Hid.SizeHid ); if (status != HidProtocolStatus.Success) { Debug.Print("[WinRawJoystick] HidProtocol.GetUsages() failed with {0}", Marshal.GetLastWin32Error()); continue; } for (var j = 0; j < usage_length; j++) { var usage = *(usage_list + j); stick.SetButton(collection, page, usage, true); } } } private static bool GetPreparsedData(IntPtr handle, ref byte[] preparsed_data) { // Query the size of the _HIDP_PREPARSED_DATA structure for this event. uint preparsed_size = 0; User32.RawInput.GetRawInputDeviceInfo(handle, GetRawInputDeviceInfoEnum.PreparsedData, IntPtr.Zero, ref preparsed_size); if (preparsed_size == 0) { Debug.Print("[WinRawJoystick] GetRawInputDeviceInfo(PARSEDDATA) failed with {0}", Marshal.GetLastWin32Error()); return false; } // Allocate space for _HIDP_PREPARSED_DATA. // This is an untyped blob of data. if (preparsed_data.Length < preparsed_size) Array.Resize(ref preparsed_data, (int)preparsed_size); if (User32.RawInput.GetRawInputDeviceInfo(handle, GetRawInputDeviceInfoEnum.PreparsedData, preparsed_data, ref preparsed_size) < 0) { Debug.Print("[WinRawJoystick] GetRawInputDeviceInfo(PARSEDDATA) failed with {0}", Marshal.GetLastWin32Error()); return false; } return true; } private bool QueryDeviceCaps(Device stick) { Debug.Print("[{0}] Querying joystick {1}", TypeName, stick.GetGuid()); try { Debug.Indent(); HidProtocolCaps caps; if (GetPreparsedData(stick.Handle, ref PreparsedData) && GetDeviceCaps(stick, PreparsedData, out caps)) { if (stick.AxisCaps.Count >= JoystickState.MaxAxes || stick.ButtonCaps.Count >= JoystickState.MaxButtons) { Debug.Print("Device {0} has {1} and {2} buttons. This might be a touch device - skipping.", stick.Handle, stick.AxisCaps.Count, stick.ButtonCaps.Count); return false; } for (var i = 0; i < stick.AxisCaps.Count; i++) { Debug.Print("Analyzing value collection {0} {1} {2}", i, stick.AxisCaps[i].IsRange ? "range" : "", stick.AxisCaps[i].IsAlias ? "alias" : ""); if (stick.AxisCaps[i].IsRange || stick.AxisCaps[i].IsAlias) { Debug.Print("Skipping value collection {0}", i); continue; } var page = stick.AxisCaps[i].UsagePage; var collection = stick.AxisCaps[i].LinkCollection; switch (page) { case HidPage.GenericDesktop: var gd_usage = (HidGenericDesktopUsage)stick.AxisCaps[i].NotRange.Usage; switch (gd_usage) { case HidGenericDesktopUsage.X: case HidGenericDesktopUsage.Y: case HidGenericDesktopUsage.Z: case HidGenericDesktopUsage.RotationX: case HidGenericDesktopUsage.RotationY: case HidGenericDesktopUsage.RotationZ: case HidGenericDesktopUsage.Slider: case HidGenericDesktopUsage.Dial: case HidGenericDesktopUsage.Wheel: Debug.Print("Found axis {0} ({1} / {2})", stick.GetCapabilities().AxisCount, page, (HidGenericDesktopUsage)stick.AxisCaps[i].NotRange.Usage); stick.SetAxis(collection, page, stick.AxisCaps[i].NotRange.Usage, 0); break; case HidGenericDesktopUsage.Hatswitch: Debug.Print("Found hat {0} ({1} / {2})", JoystickHat.Hat0 + stick.GetCapabilities().HatCount, page, (HidGenericDesktopUsage)stick.AxisCaps[i].NotRange.Usage); stick.SetHat(collection, page, stick.AxisCaps[i].NotRange.Usage, HatPosition.Centered); break; default: Debug.Print("Unknown usage {0} for page {1}", gd_usage, page); break; } break; case HidPage.Simulation: switch ((HidSimulationUsage)stick.AxisCaps[i].NotRange.Usage) { case HidSimulationUsage.Rudder: case HidSimulationUsage.Throttle: Debug.Print("Found simulation axis {0} ({1} / {2})", stick.GetCapabilities().AxisCount, page, (HidSimulationUsage)stick.AxisCaps[i].NotRange.Usage); stick.SetAxis(collection, page, stick.AxisCaps[i].NotRange.Usage, 0); break; } break; default: Debug.Print("Unknown page {0}", page); break; } } for (var i = 0; i < stick.ButtonCaps.Count; i++) { Debug.Print("Analyzing button collection {0} {1} {2}", i, stick.ButtonCaps[i].IsRange ? "range" : "", stick.ButtonCaps[i].IsAlias ? "alias" : ""); if (stick.ButtonCaps[i].IsAlias) { Debug.Print("Skipping button collection {0}", i); continue; } var is_range = stick.ButtonCaps[i].IsRange; var page = stick.ButtonCaps[i].UsagePage; var collection = stick.ButtonCaps[i].LinkCollection; switch (page) { case HidPage.Button: if (is_range) { for (var usage = stick.ButtonCaps[i].Range.UsageMin; usage <= stick.ButtonCaps[i].Range.UsageMax; usage++) { Debug.Print("Found button {0} ({1} / {2})", stick.GetCapabilities().ButtonCount, page, usage); stick.SetButton(collection, page, usage, false); } } else { Debug.Print("Found button {0} ({1} / {2})", stick.GetCapabilities().ButtonCount, page, stick.ButtonCaps[i].NotRange.Usage); stick.SetButton(collection, page, stick.ButtonCaps[i].NotRange.Usage, false); } break; default: Debug.Print("Unknown page {0} for button.", page); break; } } } else { return false; } } finally { Debug.Unindent(); } return true; } private static bool GetDeviceCaps(Device stick, byte[] preparsed_data, out HidProtocolCaps caps) { // Query joystick capabilities caps = new HidProtocolCaps(); if (HidProtocol.GetCaps(preparsed_data, ref caps) != HidProtocolStatus.Success) { Debug.Print("[WinRawJoystick] HidProtocol.GetCaps() failed with {0}", Marshal.GetLastWin32Error()); return false; } // Make sure our caps arrays are big enough var axis_caps = new HidProtocolValueCaps[caps.NumberInputValueCaps]; var button_caps = new HidProtocolButtonCaps[caps.NumberInputButtonCaps]; // Axis capabilities var axis_count = (ushort)axis_caps.Length; if (HidProtocol.GetValueCaps(HidProtocolReportType.Input, axis_caps, ref axis_count, preparsed_data) != HidProtocolStatus.Success) { Debug.Print("[WinRawJoystick] HidProtocol.GetValueCaps() failed with {0}", Marshal.GetLastWin32Error()); return false; } // Button capabilities var button_count = (ushort)button_caps.Length; if (HidProtocol.GetButtonCaps(HidProtocolReportType.Input, button_caps, ref button_count, preparsed_data) != HidProtocolStatus.Success) { Debug.Print("[WinRawJoystick] HidProtocol.GetButtonCaps() failed with {0}", Marshal.GetLastWin32Error()); return false; } stick.AxisCaps.Clear(); stick.AxisCaps.AddRange(axis_caps); stick.ButtonCaps.Clear(); stick.ButtonCaps.AddRange(button_caps); return true; } // Get a DirectInput-compatible Guid // (equivalent to DIDEVICEINSTANCE guidProduct field) private Guid GetDeviceGuid(IntPtr handle) { // Retrieve a RID_DEVICE_INFO struct which contains the VID and PID var info = new RawInputDeviceInfo(); var size = info.Size; if (User32.RawInput.GetRawInputDeviceInfo(handle, GetRawInputDeviceInfoEnum.DeviceInfo, ref info, ref size) < 0) { Debug.Print("[WinRawJoystick] GetRawInputDeviceInfo(DEVICEINFO) failed with error {0}", Marshal.GetLastWin32Error()); return Guid.Empty; } // Todo: this Guid format is only valid for USB joysticks. // Bluetooth devices, such as OUYA controllers, have a totally // different PID/VID format in DirectInput. // Do we need to use the same guid or could we simply use PID/VID // there too? (Test with an OUYA controller.) var vid = info.Hid.VendorId; var pid = info.Hid.ProductId; return new Guid( (pid << 16) | vid, 0, 0, 0, 0, (byte)'P', (byte)'I', (byte)'D', (byte)'V', (byte)'I', (byte)'D'); } // Checks whether this is an XInput device. // XInput devices should be handled through // the XInput API. private bool IsXInput(IntPtr handle) { var is_xinput = false; unsafe { // Find out how much memory we need to allocate // for the DEVICENAME string uint size = 0; if (User32.RawInput.GetRawInputDeviceInfo(handle, GetRawInputDeviceInfoEnum.DeviceName, IntPtr.Zero, ref size) < 0 || size == 0) { Debug.Print("[WinRawJoystick] GetRawInputDeviceInfo(DEVICENAME) failed with error {0}", Marshal.GetLastWin32Error()); return is_xinput; } // Allocate memory and retrieve the DEVICENAME string sbyte* pname = stackalloc sbyte[(int)size + 1]; if (User32.RawInput.GetRawInputDeviceInfo(handle, GetRawInputDeviceInfoEnum.DeviceName, (IntPtr)pname, ref size) < 0) { Debug.Print("[WinRawJoystick] GetRawInputDeviceInfo(DEVICENAME) failed with error {0}", Marshal.GetLastWin32Error()); return is_xinput; } // Convert the buffer to a .Net string, and split it into parts var name = new string(pname); if (string.IsNullOrEmpty(name)) { Debug.Print("[WinRawJoystick] Failed to construct device name"); return is_xinput; } is_xinput = name.Contains("IG_"); } return is_xinput; } private Device GetDevice(IntPtr handle) { var hardware_id = handle.ToInt64(); var is_device_known = false; lock (UpdateLock) is_device_known = Devices.FromHardwareId(hardware_id) != null; if (!is_device_known) RefreshDevices(); lock (UpdateLock) return Devices.FromHardwareId(hardware_id); } private bool IsValid(int index) => Devices.FromIndex(index) != null; private class Device { private readonly Dictionary<int, int> axes = new Dictionary<int, int>(); internal readonly List<HidProtocolValueCaps> AxisCaps = new List<HidProtocolValueCaps>(); internal readonly List<HidProtocolButtonCaps> ButtonCaps = new List<HidProtocolButtonCaps>(); private readonly Dictionary<int, int> buttons = new Dictionary<int, int>(); private readonly Guid Guid; public readonly IntPtr Handle; private readonly Dictionary<int, JoystickHat> hats = new Dictionary<int, JoystickHat>(); internal readonly bool IsXInput; internal readonly int XInputIndex; private JoystickCapabilities Capabilities; private JoystickState State; public Device(IntPtr handle, Guid guid, bool is_xinput, int xinput_index) { Handle = handle; Guid = guid; IsXInput = is_xinput; XInputIndex = xinput_index; } public void ClearButtons() => State.ClearButtons(); public void SetAxis(short collection, HidPage page, short usage, short value) { // set axis only when HidPage is known by HidHelper.TranslateJoystickAxis() to avoid axis0 to be overwritten by unknown HidPage if (page == HidPage.GenericDesktop || page == HidPage.Simulation) { //Certain joysticks (Speedlink Black Widow, PS3 pad connected via USB) //return an invalid HID page of 1, so if (usage != 1) { var axis = GetAxis(collection, page, usage); State.SetAxis(axis, value); } } } public void SetButton(short collection, HidPage page, short usage, bool value) { var button = GetButton(collection, page, usage); State.SetButton(button, value); } public void SetHat(short collection, HidPage page, short usage, HatPosition pos) { var hat = GetHat(collection, page, usage); State.SetHat(hat, new JoystickHatState(pos)); } public void SetConnected(bool value) { Capabilities.SetIsConnected(value); State.SetIsConnected(value); } public JoystickCapabilities GetCapabilities() { Capabilities = new JoystickCapabilities( axes.Count, buttons.Count, hats.Count, Capabilities.IsConnected); return Capabilities; } internal void SetCapabilities(JoystickCapabilities caps) => Capabilities = caps; public Guid GetGuid() => Guid; public JoystickState GetState() => State; private static int MakeKey(short collection, HidPage page, short usage) { var coll_byte = unchecked((byte)collection); var page_byte = unchecked((byte)((((ushort)page & 0xff00) >> 8) | ((ushort)page & 0xff))); return (coll_byte << 24) | (page_byte << 16) | unchecked((ushort)usage); } private int GetAxis(short collection, HidPage page, short usage) { var key = MakeKey(collection, page, usage); if (!axes.ContainsKey(key)) { var axis = HidHelper.TranslateJoystickAxis(page, usage); axes.Add(key, axis); } return axes[key]; } private int GetButton(short collection, HidPage page, short usage) { var key = MakeKey(collection, page, usage); if (!buttons.ContainsKey(key)) buttons.Add(key, buttons.Count); return buttons[key]; } private JoystickHat GetHat(short collection, HidPage page, short usage) { var key = MakeKey(collection, page, usage); if (!hats.ContainsKey(key)) hats.Add(key, JoystickHat.Hat0 + hats.Count); return hats[key]; } } } }
40.044153
150
0.483923
[ "BSD-3-Clause" ]
copygirl/opentk
src/OpenTK/Platform/Windows/WinRawJoystick.cs
33,559
C#
using MapVisualization.Models; using MapVisualization.Services; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace MapVisualization.Controllers { [ApiController] [Route("[controller]")] public class DataController : ControllerBase { private readonly ILogger<DataController> logger; private readonly ICosmosDbService cosmosDbService; private readonly IConfiguration configuration; public DataController(ILogger<DataController> logger, ICosmosDbService cosmosDbService, IConfiguration configuration) { this.logger = logger; this.cosmosDbService = cosmosDbService; this.configuration = configuration; } [HttpGet("resources")] public async Task<ActionResult<List<Resource>>> GetResources() { var users = await cosmosDbService.GetUsersAsync($"SELECT * FROM c"); var resources = await cosmosDbService.GetResourcesAsync("SELECT c.CreatedById, c.Category, c.Name, c.Quantity, c.IsUnopened,c.CanShip, c.id FROM c"); var lookup = users.ToDictionary(u => u.Id); var result = new List<Resource>(); foreach (Resource resource in resources) { if (lookup.TryGetValue(resource.CreatedById, out User user)) { resource.Location = user.Location; resource.LocationCoordinates = user.LocationCoordinates; result.Add(resource); } continue; } return result; } [HttpGet("needs")] public async Task<ActionResult<List<Need>>> GetNeeds() { var users = await cosmosDbService.GetUsersAsync("SELECT c.id, c.Location, c.LocationCoordinates FROM c"); var needs = await cosmosDbService.GetNeedsAsync("SELECT c.CreatedById, c.Category, c.Name, c.Quantity, c.UnopenedOnly, c.Instructions, c.id FROM c"); var lookup = users.ToDictionary(u => u.Id); var result = new List<Need>(); foreach (Need need in needs) { if (lookup.TryGetValue(need.CreatedById, out User user)) { need.Location = user.Location; need.LocationCoordinates = user.LocationCoordinates; result.Add(need); } continue; } return result; } [HttpGet("locations")] public async Task<ActionResult<List<User>>> GetLocations() { return await cosmosDbService.GetUsersAsync("SELECT c.id, c.Location, c.LocationCoordinates FROM c"); } [HttpGet("totals")] public async Task<ActionResult<Dictionary<string, int>>> GetTotals() { int resourcesTotal = await cosmosDbService.GetResourceTotalAsync("SELECT * FROM c"); int needsTotal = await cosmosDbService.GetNeedTotalAsync("SELECT * FROM c"); return new Dictionary<string, int>() { { "resources", resourcesTotal }, { "needs", needsTotal } }; } } }
37.05618
161
0.60946
[ "MIT" ]
Community-Operations-Resource-Agent/Website
Website/Controllers/DataController.cs
3,300
C#
namespace PressCenters.Web.ViewModels.News { using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; using System.Text.RegularExpressions; using AngleSharp; using AngleSharp.Html.Parser; using AutoMapper; using Ganss.XSS; using PressCenters.Common; using PressCenters.Data.Models; using PressCenters.Services; using PressCenters.Services.Mapping; public class NewsViewModel : IMapFrom<News>, IHaveCustomMappings { public int Id { get; set; } public string Title { get; set; } public string Content { get; set; } public string SanitizedContent { get { // Sanitize var htmlSanitizer = new HtmlSanitizer(); htmlSanitizer.AllowedCssProperties.Remove("font-size"); htmlSanitizer.AllowedSchemes.Add("mailto"); htmlSanitizer.AllowDataAttributes = false; var html = htmlSanitizer.Sanitize(this.Content); // Parse document var parser = new HtmlParser(); var document = parser.ParseDocument(html); // Add .table class for tables var tables = document.QuerySelectorAll("table"); foreach (var table in tables) { table.ClassName += " table table-striped table-bordered table-hover table-sm"; } // Clear font size var fontElements = document.QuerySelectorAll("font"); foreach (var fontElement in fontElements) { if (fontElement.HasAttribute("size")) { fontElement.RemoveAttribute("size"); } } return document.ToHtml(); } } public string ShortContent => this.GetShortContent(235); public string ImageUrl { get; set; } public string SmallImageUrl => this.ImageUrl == null ? this.SourceDefaultImageUrl : $"/images/news/{this.Id % 1000}/small_{this.Id}.png"; public string BigImageUrl => this.ImageUrl == null ? this.SourceDefaultImageUrl : $"/images/news/{this.Id % 1000}/big_{this.Id}.png"; public string OriginalUrl { get; set; } public string RemoteId { get; set; } public string SourceName { get; set; } public string SourceShortName { get; set; } public string SourceDefaultImageUrl { get; set; } public string SourceUrl { get; set; } public IEnumerable<string> Tags { get; set; } public string ShorterOriginalUrl { get { if (this.OriginalUrl == null) { return string.Empty; } if (this.OriginalUrl.Length <= 65) { return this.OriginalUrl; } return $"{this.OriginalUrl.Substring(0, 30)}..{this.OriginalUrl.Substring(this.OriginalUrl.Length - 30, 30)}"; } } public DateTime CreatedOn { get; set; } public string CreatedOnAsString => this.CreatedOn.Hour == 0 && this.CreatedOn.Minute == 0 ? this.CreatedOn.ToString("ddd, dd MMM yyyy", new CultureInfo("bg-BG")) : this.CreatedOn.ToString("ddd, dd MMM yyyy HH:mm", new CultureInfo("bg-BG")); public string Url => $"/News/{this.Id}/{new SlugGenerator().GenerateSlug(this.Title)}"; public void CreateMappings(IProfileExpression configuration) { configuration.CreateMap<News, NewsViewModel>().ForMember( m => m.Tags, opt => opt.MapFrom(x => x.Tags.Select(t => t.Tag.Name))); } public string GetShortContent(int maxLength) { // TODO: Extract as a service var htmlSanitizer = new HtmlSanitizer(); var html = htmlSanitizer.Sanitize(this.Content); var strippedContent = WebUtility.HtmlDecode(html?.StripHtml() ?? string.Empty); strippedContent = strippedContent.Replace("\n", " "); strippedContent = strippedContent.Replace("\t", " "); strippedContent = Regex.Replace(strippedContent, @"\s+", " ").Trim(); return strippedContent.Length <= maxLength ? strippedContent : strippedContent.Substring(0, maxLength) + "..."; } } }
33.540146
126
0.557998
[ "MIT" ]
IliyanAng/PressCenters.com
src/Web/PressCenters.Web/ViewModels/News/NewsViewModel.cs
4,597
C#
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Windows.Input; using System.ComponentModel; using AssemblyDefender.Common; namespace AssemblyDefender.UI.Model { public class ErrorViewModel : DialogViewModel { #region Fields private bool _isReportVisible; private string _message; private string _helpLink; private string _reportText; #endregion #region Ctors public ErrorViewModel(ShellViewModel shell, Exception exception) : base(shell) { if (string.IsNullOrEmpty(exception.Message) && exception is InvalidOperationException) _message = Common.SR.InternalError; else _message = exception.Message; _helpLink = exception.HelpLink; _reportText = CoreUtils.Print(exception, true, true); } #endregion #region Properties [System.Reflection.Obfuscation(Feature = "rename,remove", Exclude = true)] public bool IsReportVisible { get { return _isReportVisible; } set { _isReportVisible = value; OnPropertyChanged("IsReportVisible"); } } [System.Reflection.Obfuscation(Feature = "rename,remove", Exclude = true)] public string Message { get { return _message; } } [System.Reflection.Obfuscation(Feature = "rename,remove", Exclude = true)] public bool HasHelpLink { get { return !string.IsNullOrEmpty(_helpLink); } } [System.Reflection.Obfuscation(Feature = "rename,remove", Exclude = true)] public string HelpLink { get { return _helpLink; } } [System.Reflection.Obfuscation(Feature = "rename,remove", Exclude = true)] public string ReportText { get { return _reportText; } } #endregion #region Methods public override void Close(bool result) { base.Close(result); } #endregion } }
20.511364
89
0.720222
[ "MIT" ]
nickyandreev/AssemblyDefender
src/AssemblyDefender.UI.Model/ErrorViewModel.cs
1,805
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace PomodorTimerDesktop.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
34.645161
151
0.58473
[ "MIT" ]
Fyzxs/PomodoroTimer
PomodorTimerDesktop/Properties/Settings.Designer.cs
1,076
C#
using System.Web; using System.Web.Optimization; namespace PosUP_CloudComputing_WebAPIDotNET { public class BundleConfig { // For more information on bundling, visit https://go.microsoft.com/fwlink/?LinkId=301862 public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new ScriptBundle("~/bundles/jquery").Include( "~/Scripts/jquery-{version}.js")); // Use the development version of Modernizr to develop with and learn from. Then, when you're // ready for production, use the build tool at https://modernizr.com to pick only the tests you need. bundles.Add(new ScriptBundle("~/bundles/modernizr").Include( "~/Scripts/modernizr-*")); bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include( "~/Scripts/bootstrap.js")); bundles.Add(new StyleBundle("~/Content/css").Include( "~/Content/bootstrap.css", "~/Content/site.css")); } } }
38.857143
113
0.597426
[ "MIT" ]
rogeriohc/posup-cloudcomputing
csharp/PosUP-CloudComputing-WebAPIDotNET/App_Start/BundleConfig.cs
1,090
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System.Collections.Generic; using Aliyun.Acs.Core; using Aliyun.Acs.Core.Http; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.Core.Utils; using Aliyun.Acs.Emr.Transform; using Aliyun.Acs.Emr.Transform.V20160408; namespace Aliyun.Acs.Emr.Model.V20160408 { public class TagResourcesSystemTagsRequest : RpcAcsRequest<TagResourcesSystemTagsResponse> { public TagResourcesSystemTagsRequest() : base("Emr", "2016-04-08", "TagResourcesSystemTags", "emr", "openAPI") { if (this.GetType().GetProperty("ProductEndpointMap") != null && this.GetType().GetProperty("ProductEndpointType") != null) { this.GetType().GetProperty("ProductEndpointMap").SetValue(this, Aliyun.Acs.Emr.Endpoint.endpointMap, null); this.GetType().GetProperty("ProductEndpointType").SetValue(this, Aliyun.Acs.Emr.Endpoint.endpointRegionalType, null); } Method = MethodType.POST; } private long? resourceOwnerId; private List<string> resourceIds = new List<string>(){ }; private long? tagOwnerUid; private string resourceType; private string scope; private List<Tag> tags = new List<Tag>(){ }; public long? ResourceOwnerId { get { return resourceOwnerId; } set { resourceOwnerId = value; DictionaryUtil.Add(QueryParameters, "ResourceOwnerId", value.ToString()); } } public List<string> ResourceIds { get { return resourceIds; } set { resourceIds = value; for (int i = 0; i < resourceIds.Count; i++) { DictionaryUtil.Add(QueryParameters,"ResourceId." + (i + 1) , resourceIds[i]); } } } public long? TagOwnerUid { get { return tagOwnerUid; } set { tagOwnerUid = value; DictionaryUtil.Add(QueryParameters, "TagOwnerUid", value.ToString()); } } public string ResourceType { get { return resourceType; } set { resourceType = value; DictionaryUtil.Add(QueryParameters, "ResourceType", value); } } public string Scope { get { return scope; } set { scope = value; DictionaryUtil.Add(QueryParameters, "Scope", value); } } public List<Tag> Tags { get { return tags; } set { tags = value; for (int i = 0; i < tags.Count; i++) { DictionaryUtil.Add(QueryParameters,"Tag." + (i + 1) + ".Key", tags[i].Key); DictionaryUtil.Add(QueryParameters,"Tag." + (i + 1) + ".Value", tags[i].Value); } } } public class Tag { private string key; private string value_; public string Key { get { return key; } set { key = value; } } public string Value { get { return value_; } set { value_ = value; } } } public override TagResourcesSystemTagsResponse GetResponse(UnmarshallerContext unmarshallerContext) { return TagResourcesSystemTagsResponseUnmarshaller.Unmarshall(unmarshallerContext); } } }
22.327778
134
0.622543
[ "Apache-2.0" ]
AxiosCros/aliyun-openapi-net-sdk
aliyun-net-sdk-emr/Emr/Model/V20160408/TagResourcesSystemTagsRequest.cs
4,019
C#
using System; using Microsoft.EntityFrameworkCore.Migrations; namespace GeoLocator.Migrations { public partial class InitialEntities : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Students", columns: table => new { Id = table.Column<Guid>(nullable: false), Name = table.Column<string>(nullable: true), Age = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Students", x => x.Id); }); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "Students"); } } }
29.096774
71
0.517738
[ "MIT" ]
DmitryBoyko/CVMaxmindTask
MyService/GeoLocator/Migrations/20190806104746_InitialEntities.cs
904
C#
using FlowScriptEngine; using PPDCoreModel; using PPDFramework; using PPDFramework.Vertex; using PPDSound; using System; using System.Collections.Generic; namespace FlowScriptEnginePPD { public class TypeAlias : TypeAliasBase { Dictionary<Type, string> dictionary; public TypeAlias() { dictionary = new Dictionary<Type, string> { { typeof(RectangleComponent), "PPD.Graphics.Rectangle" }, { typeof(PictureObject), "PPD.Graphics.Image" }, { typeof(TextureString), "PPD.Graphics.Text" }, { typeof(NumberPictureObject), "PPD.Graphics.Number" }, { typeof(EffectObject), "PPD.Graphics.Effect" }, { typeof(SpriteObject), "PPD.Graphics.Sprite" }, { typeof(PolygonObject), "PPD.Graphics.Polygon" }, { typeof(ColoredTexturedVertex), "PPD.Graphics.Vertex" }, { typeof(VertexInfo), "PPD.Graphics.VertexBuffer" }, { typeof(SoundResource), "PPD.Audio.Sound" }, { typeof(GameComponent), "PPD.Graphics" }, { typeof(PPDCoreModel.Data.EffectType), "PPD.Mark.EffectType" }, { typeof(PPDCoreModel.Data.LayerType), "PPD.LayerType" }, { typeof(PPDCoreModel.Data.MarkType), "PPD.MarkType" }, { typeof(Effect2D.EffectManager.PlayType), "PPD.Graphics.Effect.PlayType" }, { typeof(Effect2D.EffectManager.PlayState), "PPD.Graphics.Effect.PlayState" }, { typeof(EffectPool), "PPD.Graphics.Effect.Pool" }, { typeof(PPDFramework.MarkEvaluateType), "PPD.EvaluateType" }, { typeof(PPDFrameworkCore.Difficulty), "PPD.Difficulty" }, { typeof(Alignment), "PPD.Graphics.Number.Alignment" }, { typeof(PPDFramework.Mod.ModInfo), "PPD.Mod.ModInfo" }, { typeof(ResultInfo), "PPD.Song.Result" }, { typeof(ResultEvaluateType), "PPD.Song.Result.ResultType" }, { typeof(PPDFramework.NoteType), "PPD.NoteType" }, { typeof(PPDFramework.PPDStructure.PPDData.MarkDataBase), "PPD.Mark" }, { typeof(PPDFramework.ScreenFilters.ScreenFilterBase), "PPD.Graphics.ScreenFilter" }, { typeof(PPDFramework.Shaders.ColorFilterBase), "PPD.Graphics.ColorFilter" }, { typeof(Effect2D.BlendMode), "PPD.Graphics.Blend" }, { typeof(PPDFramework.Shaders.MaskType), "PPD.Graphics.MaskType" }, { typeof(PPDFramework.PrimitiveType), "PPD.Graphics.PrimitiveType" }, { typeof(PPDFramework.ScreenFilters.GaussianFilter), "PPD.Graphics.ScreenFilter.Gaussian" }, { typeof(PPDFramework.ScreenFilters.ColorScreenFilter), "PPD.Graphics.ScreenFilter.Color" }, { typeof(PPDFramework.Shaders.SaturationColorFilter), "PPD.Graphics.ColorFilter.Saturation" }, { typeof(PPDFramework.Shaders.NTSCGrayScaleColorFilter), "PPD.Graphics.ColorFilter.NTSCGrayScale" }, { typeof(PPDFramework.Shaders.MiddleGrayScaleColorFilter), "PPD.Graphics.ColorFilter.MiddleGrayScale" }, { typeof(PPDFramework.Shaders.MedianGrayScaleColorFilter), "PPD.Graphics.ColorFilter.MedianGrayScale" }, { typeof(PPDFramework.Shaders.MaxGrayScaleColorFilter), "PPD.Graphics.ColorFilter.MaxGrayScale" }, { typeof(PPDFramework.Shaders.InvertColorFilter), "PPD.Graphics.ColorFilter.Invert" }, { typeof(PPDFramework.Shaders.HueColorFilter), "PPD.Graphics.ColorFilter.Hue" }, { typeof(PPDFramework.Shaders.HDTVGrayScaleColorFilter), "PPD.Graphics.ColorFilter.HDTVGrayScale" }, { typeof(PPDFramework.Shaders.GreenGrayScaleColorFilter), "PPD.Graphics.ColorFilter.GreenGrayScale" }, { typeof(PPDFramework.Shaders.ColorFilter), "PPD.Graphics.ColorFilter.Color" }, { typeof(PPDFramework.Shaders.BrightnessColorFilter), "PPD.Graphics.ColorFilter.Brightness" }, { typeof(PPDFramework.Shaders.AverageGrayScaleColorFilter), "PPD.Graphics.ColorFilter.AverageGrayScale" } }; } public override IEnumerable<KeyValuePair<Type, string>> EnumerateAlias() { return dictionary; } } }
61.521127
121
0.635531
[ "Apache-2.0" ]
KHCmaster/PPD
Win/FlowScriptEnginePPD/TypeAlias.cs
4,370
C#
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Threading.Tasks; using Newtonsoft.Json; namespace CloudStack.Net { public class QuotaCreditsResponse { /// <summary> /// the credit deposited /// </summary> public decimal Credits { get; set; } /// <summary> /// currency /// </summary> public string Currency { get; set; } /// <summary> /// the user name of the admin who updated the credits /// </summary> public string Updated_by { get; set; } /// <summary> /// the account name of the admin who updated the credits /// </summary> public DateTime Updated_on { get; set; } public override string ToString() => JsonConvert.SerializeObject(this, Formatting.Indented); } }
25.676471
100
0.599084
[ "Apache-2.0" ]
chaeschpi/cloudstack.net
src/CloudStack.Net/Generated/QuotaCreditsResponse.cs
873
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.Text.Json; using System.Text.Json.Serialization; using Azure.Core; namespace Azure.ResourceManager.Models { [JsonConverter(typeof(ErrorAdditionalInfoConverter))] public partial class ErrorAdditionalInfo : IUtf8JsonSerializable { void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) { writer.WriteStartObject(); writer.WriteEndObject(); } internal static ErrorAdditionalInfo DeserializeErrorAdditionalInfo(JsonElement element) { Optional<string> type = default; Optional<BinaryData> info = default; foreach (var property in element.EnumerateObject()) { if (property.NameEquals("type")) { type = property.Value.GetString(); continue; } if (property.NameEquals("info")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } info = BinaryData.FromString(property.Value.GetRawText()); continue; } } return new ErrorAdditionalInfo(type.Value, info.Value); } internal partial class ErrorAdditionalInfoConverter : JsonConverter<ErrorAdditionalInfo> { public override void Write(Utf8JsonWriter writer, ErrorAdditionalInfo model, JsonSerializerOptions options) { writer.WriteObjectValue(model); } public override ErrorAdditionalInfo Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { using var document = JsonDocument.ParseValue(ref reader); return DeserializeErrorAdditionalInfo(document.RootElement); } } } }
34.142857
130
0.588099
[ "MIT" ]
AikoBB/azure-sdk-for-net
sdk/resourcemanager/Azure.ResourceManager/src/Common/Generated/Models/ErrorAdditionalInfo.Serialization.cs
2,151
C#
using DocFX.Repository.Extensions; using System; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using static System.Environment; namespace DocFX.Repository.Sweeper.Core { static class FileTokenCacheUtility { static readonly string SweeperRoamingDir = Path.Combine(GetFolderPath(SpecialFolder.ApplicationData), "DocFx Sweeper"); static readonly string CacheDir = Path.Combine(SweeperRoamingDir, "Cache"); internal static int CachedCount = 0; internal static async ValueTask<bool> TryFindCachedVersionAsync(FileToken token, Options options, string destination) { try { if (!options.EnableCaching) { return false; } var cachedTokenPath = await GetTokenCachePathAsync(token, options, destination); if (File.Exists(cachedTokenPath)) { token.MergeWith(cachedTokenPath.ReadFromProtoBufFile<FileToken>()); Interlocked.Increment(ref CachedCount); return true; } } catch { } return false; } internal static async ValueTask CacheTokenAsync(FileToken token, Options options, string destination) { try { if (!options.EnableCaching) { return; } token.WriteToProtoBufFile(await GetTokenCachePathAsync(token, options, destination)); } catch { } } static async ValueTask<string> GetTokenCachePathAsync(FileToken token, Options options, string destination) { var dest = string.IsNullOrWhiteSpace(destination) ? (await options.GetConfigAsync()).Build.Dest : destination; var destDir = Path.Combine(CacheDir, dest); if (!Directory.Exists(destDir)) { Directory.CreateDirectory(destDir); } return Path.Combine(destDir, token.CachedJsonFileName); } internal static void PurgeCache() { try { var thirtyDaysAgo = DateTime.Now.AddDays(-30); var dir = new DirectoryInfo(CacheDir); foreach (var file in dir.EnumerateFiles("*.*", SearchOption.AllDirectories) .Where(file => File.Exists(file.FullName))) { try { if (file.LastWriteTime < thirtyDaysAgo) { file.Delete(); } } catch { } } } catch { } } } }
30.19802
127
0.494098
[ "Apache-2.0" ]
IEvangelist/DocFX.Repository.Sweeper
DocFX.Repository.Sweeper/Core/FileTokenCacheUtility.cs
3,052
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System.Text.Json; using Azure.Core; namespace Azure.Messaging.EventGrid.SystemEvents { public partial class DeviceTwinProperties { internal static DeviceTwinProperties DeserializeDeviceTwinProperties(JsonElement element) { Optional<DeviceTwinMetadata> metadata = default; Optional<float> version = default; foreach (var property in element.EnumerateObject()) { if (property.NameEquals("metadata")) { metadata = DeviceTwinMetadata.DeserializeDeviceTwinMetadata(property.Value); continue; } if (property.NameEquals("version")) { version = property.Value.GetSingle(); continue; } } return new DeviceTwinProperties(metadata.Value, Optional.ToNullable(version)); } } }
30.361111
97
0.589204
[ "MIT" ]
AbelHu/azure-sdk-for-net
sdk/eventgrid/Azure.Messaging.EventGrid/src/Generated/Models/DeviceTwinProperties.Serialization.cs
1,093
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.CustomerInsights { public static class GetConnectorMapping { /// <summary> /// The connector mapping resource format. /// API Version: 2017-04-26. /// </summary> public static Task<GetConnectorMappingResult> InvokeAsync(GetConnectorMappingArgs args, InvokeOptions? options = null) => Pulumi.Deployment.Instance.InvokeAsync<GetConnectorMappingResult>("azure-native:customerinsights:getConnectorMapping", args ?? new GetConnectorMappingArgs(), options.WithVersion()); } public sealed class GetConnectorMappingArgs : Pulumi.InvokeArgs { /// <summary> /// The name of the connector. /// </summary> [Input("connectorName", required: true)] public string ConnectorName { get; set; } = null!; /// <summary> /// The name of the hub. /// </summary> [Input("hubName", required: true)] public string HubName { get; set; } = null!; /// <summary> /// The name of the connector mapping. /// </summary> [Input("mappingName", required: true)] public string MappingName { get; set; } = null!; /// <summary> /// The name of the resource group. /// </summary> [Input("resourceGroupName", required: true)] public string ResourceGroupName { get; set; } = null!; public GetConnectorMappingArgs() { } } [OutputType] public sealed class GetConnectorMappingResult { /// <summary> /// The connector mapping name /// </summary> public readonly string ConnectorMappingName; /// <summary> /// The connector name. /// </summary> public readonly string ConnectorName; /// <summary> /// Type of connector. /// </summary> public readonly string? ConnectorType; /// <summary> /// The created time. /// </summary> public readonly string Created; /// <summary> /// The DataFormat ID. /// </summary> public readonly string DataFormatId; /// <summary> /// The description of the connector mapping. /// </summary> public readonly string? Description; /// <summary> /// Display name for the connector mapping. /// </summary> public readonly string? DisplayName; /// <summary> /// Defines which entity type the file should map to. /// </summary> public readonly string EntityType; /// <summary> /// The mapping entity name. /// </summary> public readonly string EntityTypeName; /// <summary> /// Resource ID. /// </summary> public readonly string Id; /// <summary> /// The last modified time. /// </summary> public readonly string LastModified; /// <summary> /// The properties of the mapping. /// </summary> public readonly Outputs.ConnectorMappingPropertiesResponse MappingProperties; /// <summary> /// Resource name. /// </summary> public readonly string Name; /// <summary> /// The next run time based on customer's settings. /// </summary> public readonly string NextRunTime; /// <summary> /// The RunId. /// </summary> public readonly string RunId; /// <summary> /// State of connector mapping. /// </summary> public readonly string State; /// <summary> /// The hub name. /// </summary> public readonly string TenantId; /// <summary> /// Resource type. /// </summary> public readonly string Type; [OutputConstructor] private GetConnectorMappingResult( string connectorMappingName, string connectorName, string? connectorType, string created, string dataFormatId, string? description, string? displayName, string entityType, string entityTypeName, string id, string lastModified, Outputs.ConnectorMappingPropertiesResponse mappingProperties, string name, string nextRunTime, string runId, string state, string tenantId, string type) { ConnectorMappingName = connectorMappingName; ConnectorName = connectorName; ConnectorType = connectorType; Created = created; DataFormatId = dataFormatId; Description = description; DisplayName = displayName; EntityType = entityType; EntityTypeName = entityTypeName; Id = id; LastModified = lastModified; MappingProperties = mappingProperties; Name = name; NextRunTime = nextRunTime; RunId = runId; State = state; TenantId = tenantId; Type = type; } } }
29.068421
196
0.55803
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/CustomerInsights/GetConnectorMapping.cs
5,523
C#
using System; using System.Collections.Generic; using System.Text; using SimpleLexer; namespace SimpleLangParser { public class ParserException : System.Exception { public ParserException(string msg) : base(msg) { } } public class Parser { private SimpleLexer.Lexer l; public Parser(SimpleLexer.Lexer lexer) { l = lexer; } public void Progr() { Block(); } public void Expr() { // здесь мы проверяем на выржение if (l.LexKind == Tok.ID || l.LexKind == Tok.INUM) { // если число, то дальше ожидаем плюс или минус l.NextLexem(); if (l.LexKind == Tok.PLUS || l.LexKind == Tok.MINUS) { l.NextLexem(); // рекуррентно вызовем функию для того, чтобы продолжить проверку Expr(); } } else { SyntaxError("expression expected"); } } public void Assign() { l.NextLexem(); // пропуск id if (l.LexKind == Tok.ASSIGN) { l.NextLexem(); } else { SyntaxError(":= expected"); } Expr(); } public void For() { // цикл for, выглядит как паскалевский if (l.LexKind != Tok.FOR) { SyntaxError("for expected"); } l.NextLexem(); Assign(); if (l.LexKind != Tok.TO) { SyntaxError("to expected"); } l.NextLexem(); Expr(); if (l.LexKind != Tok.DO) { SyntaxError("do expected"); } l.NextLexem(); if (l.LexKind == Tok.BEGIN) { Block(); } else { Statement(); } } public void StatementList() { // список высказываний через запятую Statement(); while (l.LexKind == Tok.SEMICOLON) { l.NextLexem(); Statement(); } } public void Statement() { // высказывания разных типов switch (l.LexKind) { case Tok.BEGIN: { Block(); break; } case Tok.CYCLE: { Cycle(); break; } case Tok.ID: { Assign(); break; } case Tok.FOR: { For(); break; } default: { SyntaxError("Operator expected"); break; } } } public void Block() { // блок begin end l.NextLexem(); // пропуск begin StatementList(); if (l.LexKind == Tok.END) { l.NextLexem(); } else { SyntaxError("end expected"); } } public void Cycle() { // циклический обход l.NextLexem(); // пропуск cycle Expr(); Statement(); } public void SyntaxError(string message) { var errorMessage = "Syntax error in line " + l.LexRow.ToString() + ":\n"; errorMessage += l.FinishCurrentLine() + "\n"; errorMessage += new String(' ', l.LexCol - 1) + "^\n"; if (message != "") { errorMessage += message; } throw new ParserException(errorMessage); } } }
21.75
86
0.395246
[ "MIT" ]
myorn/MMCS_CS311
Module4/SimpleLangParser/SimpleLangParser.cs
4,069
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using SN_Net.DataModels; namespace SN_Net.MiscClass { /// <summary> /// This class is for retrieve processing result from Server /// e.g. Some data return from Server when users login is containing /// - result (success | failed) /// - message [optional] (a mesage from server to describe about failed cause) /// - users (JSON string data about that users on success | blank JSON string on failed)) /// /// So, should declare all the data model as List<model-class> and naming it like the value key that return from Server /// </summary> public class ServerResult { public const int SERVER_CREATE_RESULT_FAILED = 0; public const int SERVER_CREATE_RESULT_FAILED_EXIST = 1; public const int SERVER_READ_RESULT_FAILED = 2; public const int SERVER_UPDATE_RESULT_FAILED = 3; public const int SERVER_UPDATE_RESULT_FAILED_EXIST = 4; public const int SERVER_DELETE_RESULT_FAILED = 5; public const int SERVER_RESULT_SUCCESS = 99; public int result { get; set; } public string message { get; set; } //public List<int> serial_id_list { get; set; } public List<Users> users { get; set; } public List<MacAllowed> macallowed { get; set; } public List<Dealer> dealer { get; set; } public List<Problem> problem { get; set; } public List<Serial> serial { get; set; } public List<Istab> istab { get; set; } public List<Istab> busityp { get; set; } public List<Istab> area { get; set; } public List<Istab> howknown { get; set; } public List<Istab> verext { get; set; } public List<Istab> problem_code { get; set; } public List<SupportNote> support_note { get; set; } // for retrieve support note data from server public List<SupportNoteComment> support_note_comment { get; set; } // for retrieve support note comment data from server public List<Serial_list> serial_list { get; set; } // for inquiry window public List<MACloud> macloud_list { get; set; } // for inquiry window public List<Dealer_list> dealer_list { get; set; } // for inquiry window public List<RegisterData> register_data { get; set; } public List<D_msg> d_msg { get; set; } // for retrieve d_msg (F8 in dealer window) public List<EventCalendar> event_calendar { get; set; } // for retrieve event_calendar (display in calendar) public List<TrainingCalendar> training_calendar { get; set; } // for retrieve training_calendar (display in calendar) public List<NoteCalendar> note_calendar { get; set; } // for retrieve note_calendar (display in calendar) public List<SpyLog> spy_log { get; set; } // for retrieve spy_log (Search history) public List<SerialPassword> serial_password { get; set; } // for retrieve password data for service to customer (display in SnWindow, SupportNoteWindow) public List<Ma> ma { get; set; } // for retrieve ma data to show in SnWindow public List<CloudSrv> cloudsrv { get; set; } // for retrieve cloudsrv data to show in SnWindow public PrintPageSetup print_page_setup { get; set; } // for retrieve print page setup of each form } }
56.864407
160
0.671833
[ "MIT" ]
wee2tee/SN_Net_V1.1
SN_Net/MiscClass/ServerResult.cs
3,357
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace BorderlessGraphicViewer.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.7.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("Bildschirmausschnitte")] public string WindowName { get { return ((string)(this["WindowName"])); } set { this["WindowName"] = value; } } } }
39.076923
151
0.578084
[ "MIT" ]
p-vogt/BorderlessGraphicViewer
Properties/Settings.Designer.cs
1,526
C#
using FujiyBlog.Core.EntityFramework; using Microsoft.AspNetCore.Mvc.Razor; using Microsoft.Extensions.DependencyInjection; using System.Collections.Generic; using System.Linq; namespace FujiyBlog.Web.Models { public class ThemeViewLocationExpander : IViewLocationExpander { private const string THEME_KEY = "theme"; public void PopulateValues(ViewLocationExpanderContext context) { var theme = context.ActionContext.HttpContext.RequestServices.GetRequiredService<SettingRepository>().Theme; context.Values[THEME_KEY] = theme; } public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations) { if (context.AreaName == null) { string theme = null; if (context.Values.TryGetValue(THEME_KEY, out theme)) { viewLocations = new[] { $"/Views/Themes/{theme}/{{1}}/{{0}}.cshtml", $"/Views/Themes/{theme}/Shared/{{0}}.cshtml", } .Concat(viewLocations); } } return viewLocations; } } }
30.675
126
0.602282
[ "MIT" ]
felipepessoto/FujiyBlog
src/FujiyBlog.Web/Models/ThemeViewLocationExpander.cs
1,229
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 kendra-2019-02-03.normal.json service model. */ using Amazon.Kendra; using Amazon.Kendra.Model; using Moq; using System; using System.Linq; using AWSSDK_DotNet35.UnitTests.TestTools; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace AWSSDK_DotNet35.UnitTests.PaginatorTests { [TestClass] public class KendraPaginatorTests { private static Mock<AmazonKendraClient> _mockClient; [ClassInitialize()] public static void ClassInitialize(TestContext a) { _mockClient = new Mock<AmazonKendraClient>("access key", "secret", Amazon.RegionEndpoint.USEast1); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Kendra")] public void GetSnapshotsTest_TwoPages() { var request = InstantiateClassGenerator.Execute<GetSnapshotsRequest>(); var firstResponse = InstantiateClassGenerator.Execute<GetSnapshotsResponse>(); var secondResponse = InstantiateClassGenerator.Execute<GetSnapshotsResponse>(); secondResponse.NextToken = null; _mockClient.SetupSequence(x => x.GetSnapshots(request)).Returns(firstResponse).Returns(secondResponse); var paginator = _mockClient.Object.Paginators.GetSnapshots(request); Assert.AreEqual(2, paginator.Responses.ToList().Count); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Kendra")] [ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")] public void GetSnapshotsTest__OnlyUsedOnce() { var request = InstantiateClassGenerator.Execute<GetSnapshotsRequest>(); var response = InstantiateClassGenerator.Execute<GetSnapshotsResponse>(); response.NextToken = null; _mockClient.Setup(x => x.GetSnapshots(request)).Returns(response); var paginator = _mockClient.Object.Paginators.GetSnapshots(request); // Should work the first time paginator.Responses.ToList(); // Second time should throw an exception paginator.Responses.ToList(); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Kendra")] public void ListDataSourcesTest_TwoPages() { var request = InstantiateClassGenerator.Execute<ListDataSourcesRequest>(); var firstResponse = InstantiateClassGenerator.Execute<ListDataSourcesResponse>(); var secondResponse = InstantiateClassGenerator.Execute<ListDataSourcesResponse>(); secondResponse.NextToken = null; _mockClient.SetupSequence(x => x.ListDataSources(request)).Returns(firstResponse).Returns(secondResponse); var paginator = _mockClient.Object.Paginators.ListDataSources(request); Assert.AreEqual(2, paginator.Responses.ToList().Count); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Kendra")] [ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")] public void ListDataSourcesTest__OnlyUsedOnce() { var request = InstantiateClassGenerator.Execute<ListDataSourcesRequest>(); var response = InstantiateClassGenerator.Execute<ListDataSourcesResponse>(); response.NextToken = null; _mockClient.Setup(x => x.ListDataSources(request)).Returns(response); var paginator = _mockClient.Object.Paginators.ListDataSources(request); // Should work the first time paginator.Responses.ToList(); // Second time should throw an exception paginator.Responses.ToList(); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Kendra")] public void ListDataSourceSyncJobsTest_TwoPages() { var request = InstantiateClassGenerator.Execute<ListDataSourceSyncJobsRequest>(); var firstResponse = InstantiateClassGenerator.Execute<ListDataSourceSyncJobsResponse>(); var secondResponse = InstantiateClassGenerator.Execute<ListDataSourceSyncJobsResponse>(); secondResponse.NextToken = null; _mockClient.SetupSequence(x => x.ListDataSourceSyncJobs(request)).Returns(firstResponse).Returns(secondResponse); var paginator = _mockClient.Object.Paginators.ListDataSourceSyncJobs(request); Assert.AreEqual(2, paginator.Responses.ToList().Count); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Kendra")] [ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")] public void ListDataSourceSyncJobsTest__OnlyUsedOnce() { var request = InstantiateClassGenerator.Execute<ListDataSourceSyncJobsRequest>(); var response = InstantiateClassGenerator.Execute<ListDataSourceSyncJobsResponse>(); response.NextToken = null; _mockClient.Setup(x => x.ListDataSourceSyncJobs(request)).Returns(response); var paginator = _mockClient.Object.Paginators.ListDataSourceSyncJobs(request); // Should work the first time paginator.Responses.ToList(); // Second time should throw an exception paginator.Responses.ToList(); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Kendra")] public void ListEntityPersonasTest_TwoPages() { var request = InstantiateClassGenerator.Execute<ListEntityPersonasRequest>(); var firstResponse = InstantiateClassGenerator.Execute<ListEntityPersonasResponse>(); var secondResponse = InstantiateClassGenerator.Execute<ListEntityPersonasResponse>(); secondResponse.NextToken = null; _mockClient.SetupSequence(x => x.ListEntityPersonas(request)).Returns(firstResponse).Returns(secondResponse); var paginator = _mockClient.Object.Paginators.ListEntityPersonas(request); Assert.AreEqual(2, paginator.Responses.ToList().Count); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Kendra")] [ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")] public void ListEntityPersonasTest__OnlyUsedOnce() { var request = InstantiateClassGenerator.Execute<ListEntityPersonasRequest>(); var response = InstantiateClassGenerator.Execute<ListEntityPersonasResponse>(); response.NextToken = null; _mockClient.Setup(x => x.ListEntityPersonas(request)).Returns(response); var paginator = _mockClient.Object.Paginators.ListEntityPersonas(request); // Should work the first time paginator.Responses.ToList(); // Second time should throw an exception paginator.Responses.ToList(); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Kendra")] public void ListExperienceEntitiesTest_TwoPages() { var request = InstantiateClassGenerator.Execute<ListExperienceEntitiesRequest>(); var firstResponse = InstantiateClassGenerator.Execute<ListExperienceEntitiesResponse>(); var secondResponse = InstantiateClassGenerator.Execute<ListExperienceEntitiesResponse>(); secondResponse.NextToken = null; _mockClient.SetupSequence(x => x.ListExperienceEntities(request)).Returns(firstResponse).Returns(secondResponse); var paginator = _mockClient.Object.Paginators.ListExperienceEntities(request); Assert.AreEqual(2, paginator.Responses.ToList().Count); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Kendra")] [ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")] public void ListExperienceEntitiesTest__OnlyUsedOnce() { var request = InstantiateClassGenerator.Execute<ListExperienceEntitiesRequest>(); var response = InstantiateClassGenerator.Execute<ListExperienceEntitiesResponse>(); response.NextToken = null; _mockClient.Setup(x => x.ListExperienceEntities(request)).Returns(response); var paginator = _mockClient.Object.Paginators.ListExperienceEntities(request); // Should work the first time paginator.Responses.ToList(); // Second time should throw an exception paginator.Responses.ToList(); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Kendra")] public void ListExperiencesTest_TwoPages() { var request = InstantiateClassGenerator.Execute<ListExperiencesRequest>(); var firstResponse = InstantiateClassGenerator.Execute<ListExperiencesResponse>(); var secondResponse = InstantiateClassGenerator.Execute<ListExperiencesResponse>(); secondResponse.NextToken = null; _mockClient.SetupSequence(x => x.ListExperiences(request)).Returns(firstResponse).Returns(secondResponse); var paginator = _mockClient.Object.Paginators.ListExperiences(request); Assert.AreEqual(2, paginator.Responses.ToList().Count); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Kendra")] [ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")] public void ListExperiencesTest__OnlyUsedOnce() { var request = InstantiateClassGenerator.Execute<ListExperiencesRequest>(); var response = InstantiateClassGenerator.Execute<ListExperiencesResponse>(); response.NextToken = null; _mockClient.Setup(x => x.ListExperiences(request)).Returns(response); var paginator = _mockClient.Object.Paginators.ListExperiences(request); // Should work the first time paginator.Responses.ToList(); // Second time should throw an exception paginator.Responses.ToList(); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Kendra")] public void ListIndicesTest_TwoPages() { var request = InstantiateClassGenerator.Execute<ListIndicesRequest>(); var firstResponse = InstantiateClassGenerator.Execute<ListIndicesResponse>(); var secondResponse = InstantiateClassGenerator.Execute<ListIndicesResponse>(); secondResponse.NextToken = null; _mockClient.SetupSequence(x => x.ListIndices(request)).Returns(firstResponse).Returns(secondResponse); var paginator = _mockClient.Object.Paginators.ListIndices(request); Assert.AreEqual(2, paginator.Responses.ToList().Count); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Kendra")] [ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")] public void ListIndicesTest__OnlyUsedOnce() { var request = InstantiateClassGenerator.Execute<ListIndicesRequest>(); var response = InstantiateClassGenerator.Execute<ListIndicesResponse>(); response.NextToken = null; _mockClient.Setup(x => x.ListIndices(request)).Returns(response); var paginator = _mockClient.Object.Paginators.ListIndices(request); // Should work the first time paginator.Responses.ToList(); // Second time should throw an exception paginator.Responses.ToList(); } } }
41.301587
160
0.671637
[ "Apache-2.0" ]
andyhopp/aws-sdk-net
sdk/test/Services/Kendra/UnitTests/Generated/_bcl45+netstandard/Paginators/KendraPaginatorTests.cs
13,010
C#
/* Copyright (c) 2015 Tizian Zeltner, ETH Zurich * * 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 UnityEngine; using System.Collections; public class StartButtonPuzzleLogic : PuzzleLogic { // Puzzle data private bool isButtonPressed; // Trigger to change Puzzle data. public void PressButton() { isButtonPressed = true; } override protected void Reset() { isButtonPressed = false; } override protected bool CheckIfSolved() { return isButtonPressed; } }
35.022222
80
0.727157
[ "MIT" ]
fi-content2-games-platform/FIcontent.Gaming.Application.TreasureHunt
Assets/Scripts/Puzzles/StartButtonPuzzle/StartButtonPuzzleLogic.cs
1,578
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Extensions; namespace Microsoft.AspNetCore.Rewrite.UrlActions; internal class RewriteAction : UrlAction { public RuleResult Result { get; } public bool QueryStringAppend { get; } public bool QueryStringDelete { get; } public bool EscapeBackReferences { get; } public RewriteAction( RuleResult result, Pattern pattern, bool queryStringAppend, bool queryStringDelete, bool escapeBackReferences) { // For the replacement, we must have at least // one segment (cannot have an empty replacement) Result = result; Url = pattern; QueryStringAppend = queryStringAppend; QueryStringDelete = queryStringDelete; EscapeBackReferences = escapeBackReferences; } public RewriteAction( RuleResult result, Pattern pattern, bool queryStringAppend) : this(result, pattern, queryStringAppend, queryStringDelete: false, escapeBackReferences: false) { } public override void ApplyAction(RewriteContext context, BackReferenceCollection? ruleBackReferences, BackReferenceCollection? conditionBackReferences) { var pattern = Url!.Evaluate(context, ruleBackReferences, conditionBackReferences); var request = context.HttpContext.Request; if (string.IsNullOrEmpty(pattern)) { pattern = "/"; } if (EscapeBackReferences) { // because escapebackreferences will be encapsulated by the pattern, just escape the pattern pattern = Uri.EscapeDataString(pattern); } // TODO PERF, substrings, object creation, etc. if (pattern.IndexOf(Uri.SchemeDelimiter, StringComparison.Ordinal) >= 0) { string scheme; HostString host; PathString path; QueryString query; UriHelper.FromAbsolute(pattern, out scheme, out host, out path, out query, out _); if (query.HasValue) { if (QueryStringAppend) { request.QueryString = request.QueryString.Add(query); } else { request.QueryString = query; } } else if (QueryStringDelete) { request.QueryString = QueryString.Empty; } request.Scheme = scheme; request.Host = host; request.Path = path; } else { var split = pattern.IndexOf('?'); if (split >= 0) { var path = pattern.Substring(0, split); if (path[0] == '/') { request.Path = PathString.FromUriComponent(path); } else { request.Path = PathString.FromUriComponent('/' + path); } if (QueryStringAppend) { request.QueryString = request.QueryString.Add( QueryString.FromUriComponent( pattern.Substring(split))); } else { request.QueryString = QueryString.FromUriComponent( pattern.Substring(split)); } } else { if (pattern[0] == '/') { request.Path = PathString.FromUriComponent(pattern); } else { request.Path = PathString.FromUriComponent('/' + pattern); } if (QueryStringDelete) { request.QueryString = QueryString.Empty; } } } context.Result = Result; } }
30.333333
155
0.520306
[ "MIT" ]
Cosifne/aspnetcore
src/Middleware/Rewrite/src/UrlActions/RewriteAction.cs
4,186
C#
// // Encog(tm) Core v3.2 - .Net Version // http://www.heatonresearch.com/encog/ // // Copyright 2008-2014 Heaton Research, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using System; using System.Text; using Encog.Engine.Network.Activation; namespace Encog.Neural.NEAT.Training { /// <summary> /// Implements a NEAT neuron gene. /// /// NeuroEvolution of Augmenting Topologies (NEAT) is a genetic algorithm for the /// generation of evolving artificial neural networks. It was developed by Ken /// Stanley while at The University of Texas at Austin. /// /// ----------------------------------------------------------------------------- /// http://www.cs.ucf.edu/~kstanley/ Encog's NEAT implementation was drawn from /// the following three Journal Articles. For more complete BibTeX sources, see /// NEATNetwork.java. /// /// Evolving Neural Networks Through Augmenting Topologies /// /// Generating Large-Scale Neural Networks Through Discovering Geometric /// Regularities /// /// Automatic feature selection in neuroevolution /// </summary> [Serializable] public class NEATNeuronGene : NEATBaseGene { /// <summary> /// The neuron type. /// </summary> public NEATNeuronType NeuronType { get; set; } /// <summary> /// The activation function. /// </summary> public IActivationFunction ActivationFunction { get; set; } /// <summary> /// The default constructor. /// </summary> public NEATNeuronGene() { } /// <summary> /// Construct a neuron gene. /// </summary> /// <param name="type">The neuron type.</param> /// <param name="theActivationFunction">The activation function.</param> /// <param name="id">The neuron id.</param> /// <param name="innovationId">The innovation id.</param> public NEATNeuronGene(NEATNeuronType type, IActivationFunction theActivationFunction, long id, long innovationId) { NeuronType = type; InnovationId = innovationId; Id = id; ActivationFunction = theActivationFunction; } /// <summary> /// Construct this gene by comping another. /// </summary> /// <param name="other">The other gene to copy.</param> public NEATNeuronGene(NEATNeuronGene other) { Copy(other); } /// <summary> /// Copy another gene to this one. /// </summary> /// <param name="gene">The other gene.</param> public void Copy(NEATNeuronGene gene) { NEATNeuronGene other = gene; Id = other.Id; NeuronType = other.NeuronType; ActivationFunction = other.ActivationFunction; InnovationId = other.InnovationId; } /// <inheritdoc/> public override string ToString() { var result = new StringBuilder(); result.Append("[NEATNeuronGene: id="); result.Append(Id); result.Append(", type="); result.Append(NeuronType); result.Append("]"); return result.ToString(); } } }
33.719008
122
0.578676
[ "BSD-3-Clause" ]
a7866353/encog-dotnet-core_work01
encog-core-cs/Neural/NEAT/Training/NEATNeuronGene.cs
4,080
C#
using System; using System.Collections; using System.Collections.Generic; /* Pair Sums Given a list of n integers arr[0..(n-1)], determine the number of different pairs of elements within it which sum to k. If an integer appears in the list multiple times, each copy is considered to be different; that is, two pairs are considered different if one pair includes at least one array index which the other doesn't, even if they include the same values. Signature int numberOfWays(int[] arr, int k) Input n is in the range [1, 100,000]. Each value arr[i] is in the range [1, 1,000,000,000]. k is in the range [1, 1,000,000,000]. Output Return the number of different pairs of elements which sum to k. Example 1 n = 5 k = 6 arr = [1, 2, 3, 4, 3] output = 2 The valid pairs are 2+4 and 3+3. Example 2 n = 5 k = 6 arr = [1, 5, 3, 3, 3] output = 4 There's one valid pair 1+5, and three different valid pairs 3+3 (the 3rd and 4th elements, 3rd and 5th elements, and 4th and 5th elements). */ namespace PairSums { class Program { static void Main(string[] args) { int[] test2 = new int[]{1, 2, 3, 4, 3}; //k=6, output =2 int[] test3 = new int[]{1,5,3,3,3}; //k=6, output =4 Console.WriteLine(method(test2, 6)); Console.WriteLine(method(test3, 6)); } //brute force private static int bruteForce(int[] arr, int k) { int counter = 0; for(int i=0;i<arr.Length -1;i++) { for(int j=i+1;j<arr.Length;j++) { if(arr[i]+arr[j] == k) { counter++; } } } return counter; } private static int method(int[] arr, int k) { int counter = 0; //key = array value, value = occurrences Dictionary<int, int> dictionary = new Dictionary<int, int>(); for(int i=0;i<arr.Length;i++) { var currentValue = arr[i]; if(dictionary.ContainsKey(k-currentValue)) { int occurrences = 0; dictionary.TryGetValue(k-currentValue, out occurrences); counter+= occurrences; } //if key exists, increment the value if(dictionary.ContainsKey(arr[i])) { dictionary[arr[i]]++; } else { dictionary.Add(arr[i], 1); } } return counter; } } }
28.659794
247
0.497842
[ "MIT" ]
jrskerrett/Practice
PairSums/Program.cs
2,782
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Aparel_List.Models; namespace Aparel_List.Controllers { public class HomeController : Controller { public ActionResult Index() { if(Session["usuarioLogadoId"] != null) { return View(); } else { return RedirectToAction("Login"); } } public ActionResult Login() { return View(); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Login(tb_login u) { if(ModelState.IsValid) { using(DB_GENERALEntities dc = new DB_GENERALEntities()) { var v = dc.tb_login.Where(a => a.nomeUsuario.Equals(u.nomeUsuario) && a.senha.Equals(u.senha)).FirstOrDefault(); if(v != null) { Session["usuarioLogadoID"] = v.Id.ToString(); Session["nomeUsuarioLogado"] = v.nomeUsuario.ToString(); return RedirectToAction("Index"); } } } return View(u); } public ActionResult Registro() { return View(); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Registro(tb_login u) { { if (ModelState.IsValid) { using(DB_GENERALEntities dc = new DB_GENERALEntities()) { dc.tb_login.Add(u); dc.SaveChanges(); ModelState.Clear(); u = null; ViewBag.Message = "Usuário registrado com sucesso."; } } return View(u); } } } }
27.064103
133
0.425865
[ "MIT" ]
DavideLucca/List-Software
Controllers/HomeController.cs
2,114
C#
namespace Reporter.Email { public class EmailAddress { public EmailAddress(string name, string emailAddress) { Name = name; Address = emailAddress; } public string Name { get; } public string Address { get; } } }
19.333333
61
0.548276
[ "MIT" ]
coenm/FlexKidsScheduleExtractor
src/Reporter.Email/EmailAddress.cs
290
C#
namespace BeOrganized.Web.ViewModels.Calendar { using System; using System.Text.Json.Serialization; using BeOrganized.Data.Models; using BeOrganized.Services.Mapping; public class EventCalendarViewModel : IMapFrom<Event> { [JsonPropertyName("id")] public string Id { get; set; } [JsonPropertyName("title")] public string Title { get; set; } [JsonPropertyName("start")] public DateTime StartDateTime { get; set; } [JsonPropertyName("end")] public DateTime EndDateTime { get; set; } public string Location { get; set; } public string Coordinates { get; set; } public string Description { get; set; } public string CalendarId { get; set; } [JsonPropertyName("color")] public string ColorHex { get; set; } } }
24.485714
57
0.62077
[ "MIT" ]
EleonorManolova/BeOrganized
ASP.NET Core/Web/BeOrganized.Web.ViewModels/Calendar/EventCalendarViewModel.cs
859
C#
using FluentAssertions; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Tracer.Lib.Constructor; using Xunit; namespace Tracer.Lib.Tests.Constructor { public class SimpleType1_Implicit_Spec : LogSpec { [Fact] public void ShouldTrace_ImplicitConstructor() { // Arrange // Act SimpleType1_Implicit simpleType1_Implicit = new SimpleType1_Implicit(); // Assert _memoryTarget.Logs.Count.Should().Be(2); _memoryTarget.Logs[0].Should().Be("TRACE Tracer.Lib.Constructor.SimpleType1_Implicit Entered into .ctor()."); _memoryTarget.Logs[1].Should().StartWith("TRACE Tracer.Lib.Constructor.SimpleType1_Implicit Returned from .ctor() (). Time taken:"); } } }
29.413793
144
0.670574
[ "MIT" ]
hhko/Books
1.Tutorials/Observability/NLog/Tracer/Tracer.Lib.Tests/Constructor/SimpleType1_Implicit_Spec.cs
855
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Linq; using System.ServiceProcess; using System.Text; using System.Threading.Tasks; using System.Timers; namespace WindowsShutdown.Service { public partial class ShutdownService : ServiceBase { Timer shutDownTimer; public ShutdownService() { InitializeComponent(); this.AutoLog = false; } protected override void OnStart(string[] args) { shutDownTimer = new Timer(); shutDownTimer.Interval = 600000; shutDownTimer.Elapsed += (eventSender, eventArgs) => { //notifyWindowsShutDown.ShowBalloonTip }; shutDownTimer.Start(); windowsShutdownEventLog.WriteEntry("Windows Shutdown Service OnStart"); } protected override void OnStop() { windowsShutdownEventLog.WriteEntry("Windows Shutdown Service OnStop"); } } }
25.571429
83
0.630354
[ "Apache-2.0" ]
zerazobz/WindowsShutdownService
WindowsShutdown/WindowsShutdown.Service/ShutdownService.cs
1,076
C#
// <copyright file="AssemblyInfo.cs" company="Traced-Ideas, Czech republic"> // Copyright (c) 1990-2021 All Right Reserved // </copyright> // <author>vl</author> // <email></email> // <date>2021-09-01</date> // <summary>Part of Largo Composer</summary> using System.Reflection; using System.Runtime.InteropServices; // Obecné informace o sestavení se řídí přes následující // sadu atributů. Změnou hodnot těchto atributů se upraví informace // přidružené k sestavení. [assembly: AssemblyTitle("EditorPanels")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("EditorPanels")] [assembly: AssemblyCopyright("Copyright © 2021")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Nastavení ComVisible na false způsobí neviditelnost typů v tomto sestavení // pro komponenty modelu COM. Pokud potřebujete přístup k typu v tomto sestavení // modelu COM, nastavte atribut ComVisible daného typu na hodnotu True. [assembly: ComVisible(false)] // Následující GUID se používá pro ID knihovny typů, pokud je tento projekt vystavený pro COM. [assembly: Guid("41abed79-4ae2-457c-8b66-7a732358ce8e")] // Informace o verzi sestavení se skládá z těchto čtyř hodnot: // // Hlavní verze // Podverze // Číslo sestavení // Revize // // Můžete zadat všechny hodnoty nebo nastavit výchozí číslo buildu a revize // pomocí zástupného znaku * takto: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
35.840909
94
0.741915
[ "MIT" ]
Vladimir1965/LargoComposer
EditorPanels/Properties/AssemblyInfo.cs
1,636
C#
using System; using System.Collections.Generic; using NUnit.Framework; using ProtoBuf; namespace Examples.SimpleStream { [TestFixture] public class Collections { [ProtoContract] public class FooContainer { [ProtoMember(1)] public Foo Foo { get; set; } } [ProtoContract] public class Foo { [ProtoMember(1)] public List<Bar> Bars { get; set; } } [ProtoContract] public class Bar { [ProtoMember(1)] public int Value { get; set; } } static Foo GetFullFoo() { Foo foo = new Foo(); foo.Bars = new List<Bar>(); for (int i = Int16.MinValue; i <= Int16.MaxValue; i++) { foo.Bars.Add(new Bar { Value = i }); } return foo; } [Test] public void RunWrappedCollectionTest() { FooContainer fooContainer = new FooContainer(), cloneContainer; Foo foo = GetFullFoo(), clone; fooContainer.Foo = foo; cloneContainer = Serializer.DeepClone(fooContainer); clone = cloneContainer.Foo; Assert.IsNotNull(cloneContainer, "Clone Container"); Assert.IsTrue(CompareFoos(foo, clone)); } [Test] public void RunNakedCollectionTest() { Foo foo = GetFullFoo(), clone = Serializer.DeepClone(foo); Assert.IsTrue(CompareFoos(foo, clone)); } private static bool CompareFoos(Foo original, Foo clone) { Assert.IsNotNull(original, "Original"); Assert.IsNotNull(clone, "Clone"); Assert.AreEqual(original.Bars.Count, clone.Bars.Count, "Item count"); if (original == null || clone == null || original.Bars.Count != clone.Bars.Count) return false; int count = clone.Bars.Count; for (int i = 0; i < count; i++) { Assert.AreEqual(original.Bars[i].Value, clone.Bars[i].Value, "Value mismatch"); if (original.Bars[i].Value != clone.Bars[i].Value) return false; } return true; } } }
30.384615
96
0.502532
[ "Apache-2.0" ]
0xec/protobuf-net
Examples/SimpleStream/Collections.cs
2,372
C#
namespace Iterator_Merge_Menu { public interface ITerator { /// <summary> /// 用来判断下一个元素是否为空 /// </summary> /// <returns></returns> bool HasNext(); /// <summary> /// 用来获取当前元素 /// </summary> /// <returns></returns> object Next(); } }
18.111111
31
0.457055
[ "MIT" ]
JayChenFE/designPattern_examples
code/02_iterator/Iterator_Merge_Menu/Iterator_Merge_Menu/ITerator.cs
370
C#
using Microsoft.Extensions.Configuration; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Diagnostics.CodeAnalysis; namespace CM.WeeklyTeamReport.Domain { public interface IReportsFromTo<TEntity> : IRepository<ReportsFromTo> { public List<string[]> ReadReportTo(int idMemberTo); public List<string[]> ReadReportFrom(int idMemberFrom); public void DeleteFromTo(int reportTo, int reportFrom); } [ExcludeFromCodeCoverage] public class ReportsFromToRepository : IReportsFromTo<ReportsFromTo> { private readonly IConfiguration _configuration; public ReportsFromToRepository(IConfiguration configuration) { _configuration = configuration; } SqlConnection GetSqlConnection() { var connectionString = _configuration.GetConnectionString("Sql"); var connection = new SqlConnection(connectionString); connection.Open(); return connection; } public ReportsFromTo Create(ReportsFromTo reportFromTo) { using (var connection = GetSqlConnection()) { var command = new SqlCommand("INSERT INTO ReportFromTo (TeamMemberFrom, TeamMemberTo) " + "VALUES (@TeamMemberFrom, @TeamMemberTo);" + "SELECT * FROM ReportFromTo WHERE TeamMemberFrom = @TeamMemberFrom " + "AND TeamMemberTo = @TeamMemberTo", connection); SqlParameter TeamMemberFrom = new("@TeamMemberFrom", SqlDbType.Int) { Value = reportFromTo.TeamMemberFrom }; SqlParameter TeamMemberTo = new("@TeamMemberTo", SqlDbType.Int) { Value = reportFromTo.TeamMemberTo }; command.Parameters.Add(TeamMemberFrom); command.Parameters.Add(TeamMemberTo); var reader = command.ExecuteReader(); if (reader.Read()) { return MapReportFromTo(reader); } } return null; } public void Delete(int entityId) { throw new NotImplementedException(); } public List<string[]> ReadReportTo(int idMemberTo) { using (var connection = GetSqlConnection()) { List<string[]> membersWhichReportTo = new(); var command = new SqlCommand("SELECT Rep.TeamMemberFrom, TM.FirstName, TM.LastName " + "FROM ReportFromTo Rep JOIN TeamMembers TM " + "on Rep.TeamMemberFrom = TM.TeamMemberId " + "WHERE TeamMemberTo = @TeamMemberTo", connection); SqlParameter TeamMemberTo = new("@TeamMemberTo", SqlDbType.Int) { Value = idMemberTo }; command.Parameters.Add(TeamMemberTo); var reader = command.ExecuteReader(); while (reader.Read()) { var memberId = reader["TeamMemberFrom"].ToString(); var firstName = reader["FirstName"].ToString(); var lastName = reader["LastName"].ToString(); membersWhichReportTo.Add(new string[] { memberId, firstName, lastName }); } return membersWhichReportTo; } } public List<string[]> ReadReportFrom(int idMemberFrom) { using (var connection = GetSqlConnection()) { List<string[]> membersWhichReportTo = new(); var command = new SqlCommand("SELECT Rep.TeamMemberTo, TM.FirstName, TM.LastName " + "FROM ReportFromTo Rep JOIN TeamMembers TM " + "on Rep.TeamMemberTo = TM.TeamMemberId " + "WHERE TeamMemberFrom = @TeamMemberFrom", connection); SqlParameter TeamMemberFrom = new("@TeamMemberFrom", SqlDbType.Int) { Value = idMemberFrom }; command.Parameters.Add(TeamMemberFrom); var reader = command.ExecuteReader(); while (reader.Read()) { var memberId = reader["TeamMemberTo"].ToString(); var firstName = reader["FirstName"].ToString(); var lastName = reader["LastName"].ToString(); membersWhichReportTo.Add(new string[] { memberId,firstName,lastName}); } return membersWhichReportTo; } } public void DeleteFromTo(int reportTo, int reportFrom) { using (var connection = GetSqlConnection()) { var command = new SqlCommand("DELETE FROM ReportFromTo WHERE TeamMemberFrom = @TeamMemberFrom " + "AND TeamMemberTo = @TeamMemberTo", connection); SqlParameter TeamMemberFrom = new("@TeamMemberFrom", SqlDbType.Int) { Value = reportFrom }; SqlParameter TeamMemberTo = new("@TeamMemberTo", SqlDbType.Int) { Value = reportTo }; command.Parameters.Add(TeamMemberFrom); command.Parameters.Add(TeamMemberTo); command.ExecuteNonQuery(); } } public List<ReportsFromTo> ReadAll() { throw new NotImplementedException(); } public ReportsFromTo Update(ReportsFromTo entity) { throw new NotImplementedException(); } private static ReportsFromTo MapReportFromTo(SqlDataReader reader) { return new ReportsFromTo() { TeamMemberFrom = (int)reader["TeamMemberFrom"], TeamMemberTo = (int)reader["TeamMemberTo"] }; } public ReportsFromTo Read(int entityId) { throw new NotImplementedException(); } } }
38.920732
129
0.532822
[ "MIT" ]
1yoga/french-toast-weekly-report-1-api
CM.WeeklyTeamReport/src/CM.WeeklyTeamReport.Domain/Repositories/ReportsFromToRepository.cs
6,385
C#
using System; using System.Collections.Generic; using System.Linq; using NUnit.Framework; using Serilog.Core; using Serilog.Events; using Serilog.Tests.Support; namespace Serilog.Tests.Core { [TestFixture] public class LoggerTests { [Test] public void AnExceptionThrownByAnEnricherIsNotPropagated() { var thrown = false; var l = new LoggerConfiguration() .Enrich.With(new DelegatingEnricher((le, pf) => { thrown = true; throw new Exception("No go, pal."); })) .CreateLogger(); l.Information(Some.String()); Assert.IsTrue(thrown); } [Test] public void AContextualLoggerAddsTheSourceTypeName() { var evt = DelegatingSink.GetLogEvent(l => l.ForContext<LoggerTests>() .Information(Some.String())); var lv = evt.Properties[Constants.SourceContextPropertyName].LiteralValue(); Assert.AreEqual(typeof(LoggerTests).FullName, lv); } [Test] public void PropertiesInANestedContextOverrideParentContextValues() { var name = Some.String(); var v1 = Some.Int(); var v2 = Some.Int(); var evt = DelegatingSink.GetLogEvent(l => l.ForContext(name, v1) .ForContext(name, v2) .Write(Some.InformationEvent())); var pActual = evt.Properties[name]; Assert.AreEqual(v2, pActual.LiteralValue()); } [Test] public void ParametersForAnEmptyTemplateAreIgnored() { var e = DelegatingSink.GetLogEvent(l => l.Error("message", new object())); Assert.AreEqual("message", e.RenderMessage()); } [Test] public void LoggingLevelSwitchDynamicallyChangesLevel() { var events = new List<LogEvent>(); var sink = new DelegatingSink(events.Add); var levelSwitch = new LoggingLevelSwitch(LogEventLevel.Information); var log = new LoggerConfiguration() .MinimumLevel.ControlledBy(levelSwitch) .WriteTo.Sink(sink) .CreateLogger() .ForContext<LoggerTests>(); log.Debug("Suppressed"); log.Information("Emitted"); log.Warning("Emitted"); // Change the level levelSwitch.MinimumLevel = LogEventLevel.Error; log.Warning("Suppressed"); log.Error("Emitted"); log.Fatal("Emitted"); Assert.AreEqual(4, events.Count); Assert.That(events.All(evt => evt.RenderMessage() == "Emitted")); } } }
31.098901
88
0.549117
[ "Apache-2.0" ]
DavidSSL/serilog
test/Serilog.Tests/Core/LoggerTests.cs
2,832
C#
// // System.Web.EndEventHandler.cs // // Author: // Bob Smith <bob@thestuff.net> // // (C) Bob Smith // // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // namespace System.Web { public delegate void EndEventHandler(IAsyncResult ar); }
36.571429
73
0.745313
[ "Apache-2.0" ]
121468615/mono
mcs/class/System.Web/System.Web/EndEventHandler.cs
1,280
C#
namespace BashSoft { using System; using System.Collections.Generic; using System.IO; public class IOManager { public void TraverseDirectory(int depth) { OutputWriter.WriteEmptyLine(); int initialIdentation = SessionData.currentPath.Split('\\').Length; Queue<string> subFolders = new Queue<string>(); subFolders.Enqueue(SessionData.currentPath); while (subFolders.Count != 0) { string currentPath = subFolders.Dequeue(); int identation = currentPath.Split('\\').Length - initialIdentation; if (depth - identation < 0) { break; } OutputWriter.WriteMessageOnNewLine($"{new string('-', identation)}{currentPath}"); try { foreach (var file in Directory.GetFiles(currentPath)) { int indexOfLastSlash = file.LastIndexOf("\\"); string fileName = file.Substring(indexOfLastSlash); OutputWriter.WriteMessageOnNewLine(new string('-', indexOfLastSlash) + fileName); } foreach (string directoryPath in Directory.GetDirectories(currentPath)) { subFolders.Enqueue(directoryPath); } } catch (UnauthorizedAccessException) { OutputWriter.DisplayException(ExceptionMessages.UnauthorizedAccessExceptionMessage); } } } public void CreateDirectoryInCurrentFolder(string name) { string path = GetCurrentDirectoryPath() + "\\" + name; try { Directory.CreateDirectory(path); } catch (ArgumentException) { throw new ArgumentException(ExceptionMessages.ForbiddenSymbolsContainedInName); } } private string GetCurrentDirectoryPath() { return SessionData.currentPath; } public void ChangeCurrentDirectoryRelative(string relativePath) { if (relativePath == "..") { try { string currentPath = SessionData.currentPath; int indexOfLastSlash = currentPath.LastIndexOf("\\"); string newPath = currentPath.Substring(0, indexOfLastSlash); SessionData.currentPath = newPath; } catch (ArgumentOutOfRangeException) { throw new ArgumentOutOfRangeException("indexOfLastSlash", ExceptionMessages.InvalidPath); } } else { string currentPath = SessionData.currentPath; currentPath += "\\" + relativePath; ChangeCurrentDirectoryRelative(currentPath); } } public void ChangeCurrentDirectoryAbsolute(string absolutePath) { if (!Directory.Exists(absolutePath)) { throw new ArgumentException(ExceptionMessages.InvalidPath); } SessionData.currentPath = absolutePath; } } }
30.882883
109
0.515461
[ "MIT" ]
vsaraminev/C-Advance
BashSoft/BashSoft/BashSoft/IO/IOManager.cs
3,430
C#
namespace TrafficManager.Traffic { class TrafficSegment { public ushort Node1 = 0; public ushort Node2 = 0; public int Segment = 0; public PrioritySegment Instance1; public PrioritySegment Instance2; } }
18.428571
41
0.627907
[ "MIT" ]
iMarbot/Skylines-Traffic-Manager-Plus
TLM/TLM/Traffic/TrafficSegment.cs
258
C#
using System; using DataDynamics.PageFX.Common.Utilities; namespace DataDynamics.PageFX.Flash.Swf.Tags.Text { [TODO] [SwfTag(SwfTagCode.DefineFont3)] public sealed class SwfTagDefineFont3 : SwfTag { public override SwfTagCode TagCode { get { return SwfTagCode.DefineFont3; } } public override void ReadTagData(SwfReader reader) { throw new NotImplementedException(); } public override void WriteTagData(SwfWriter writer) { throw new NotImplementedException(); } } }
24.44
60
0.613748
[ "MIT" ]
GrapeCity/pagefx
source/libs/Flash/SWF/Tags/Text/SwfTagDefineFont3.cs
611
C#
using UnityEngine; using System.Collections; [ExecuteInEditMode] [RequireComponent(typeof(Camera))] public class AsciiArtFx : MonoBehaviour { public Color colorTint = Color.white; [Range(0, 1)] public float blendRatio = 1.0f; [Range(0.5f, 10.0f)] public float scaleFactor = 1.0f; [SerializeField] Shader shader; private Material _material; Material material { get { if (_material == null) { _material = new Material(shader); _material.hideFlags = HideFlags.HideAndDontSave; } return _material; } } void OnRenderImage(RenderTexture source, RenderTexture destination) { material.color = colorTint; material.SetFloat("_Alpha", blendRatio); material.SetFloat("_Scale", scaleFactor); Graphics.Blit(source, destination, material); } void OnDisable () { if (_material) DestroyImmediate(_material); } }
23.045455
71
0.606509
[ "MIT" ]
Adjuvant/videolab
Assets/Kino/AsciiArtFx/AsciiArtFx.cs
1,016
C#
using System; using System.Collections.Generic; using System.Linq; namespace Silent.Practices.EventStore { public class MemoryEventStore<TKey, TEvent> : IEventStore<TKey, TEvent> { private readonly IComparer<TEvent> _comparer; private readonly Dictionary<TKey, List<TEvent>> _events = new Dictionary<TKey, List<TEvent>>(); public MemoryEventStore(IComparer<TEvent> comparer) { _comparer = comparer; } public IReadOnlyCollection<TEvent> GetEventsById(TKey eventAggregateId) { IReadOnlyCollection<TEvent> events = _events.ContainsKey(eventAggregateId) ? _events[eventAggregateId].OrderBy(x => x, _comparer).ToList() : new List<TEvent>(); return events; } public IReadOnlyCollection<TEvent> GetEvents(Func<TEvent, bool> filter = null) { IReadOnlyCollection<TEvent> events = filter != null ? _events.Values.SelectMany(x => x).Where(filter).OrderBy(x => x, _comparer).ToList() : new List<TEvent>(); return events; } public bool SaveEvents(TKey eventAggregateId, IReadOnlyCollection<TEvent> unsavedChanges) { if (!_events.ContainsKey(eventAggregateId)) { _events.Add(eventAggregateId, new List<TEvent>()); } _events[eventAggregateId].AddRange(unsavedChanges); return true; } } }
32.042553
103
0.611554
[ "Apache-2.0" ]
JustMeGaaRa/Silent.Practices
src/Silent.Practices.EventStore/MemoryEventStore.cs
1,508
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace Lucene.Net.Support { public class TextReaderWrapper : TextReader { private TextReader tr; public TextReaderWrapper(TextReader tr) { this.tr = tr; } public override int Read(char[] buffer, int index, int count) { int numRead = tr.Read(buffer, index, count); return numRead == 0 ? -1 : numRead; } } }
20.038462
69
0.59309
[ "Apache-2.0" ]
BlueCurve-Team/lucenenet
src/Lucene.Net.Core/Support/TextReaderWrapper.cs
523
C#
using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using CocosSharp; namespace ChipmunkExample { public class AppDelegate : CCApplicationDelegate { static CCDirector sharedDirector; static CCWindow sharedWindow; static CCViewport sharedViewport; static CCCamera sharedCamera; public static CCDirector SharedDirector { get { return sharedDirector; } } public static CCWindow SharedWindow { get { return sharedWindow; } } public static CCViewport SharedViewport { get { return sharedViewport; } } public static CCCamera SharedCamera { get { return sharedCamera; } } public override void ApplicationDidFinishLaunching(CCApplication application) { //application.SupportedOrientations = CCDisplayOrientation.LandscapeRight | CCDisplayOrientation.LandscapeLeft; //application.AllowUserResizing = true; //application.PreferMultiSampling = false; application.ContentRootDirectory = "Content"; //CCRect boundsRect = new CCRect(0.0f, 0.0f, 960, 640); //sharedViewport = new CCViewport(new CCRect(0.0f, 0.0f, 1.0f, 1.0f)); //sharedWindow = application.MainWindow; //sharedCamera = new CCCamera(boundsRect.Size, new CCPoint3(boundsRect.Center, 100.0f), new CCPoint3(boundsRect.Center, 0.0f)); #if WINDOWS || WINDOWSGL || WINDOWSDX //application.PreferredBackBufferWidth = 1024; //application.PreferredBackBufferHeight = 768; #elif MACOS //application.PreferredBackBufferWidth = 960; //application.PreferredBackBufferHeight = 640; #endif #if WINDOWS_PHONE8 application.HandleMediaStateAutomatically = false; // Bug in MonoGame - https://github.com/Cocos2DXNA/cocos2d-xna/issues/325 #endif //sharedDirector = new CCDirector(); //director.DisplayStats = true; //director.AnimationInterval = 1.0 / 60; // if (sharedWindow.WindowSizeInPixels.Height > 320) // { // application.ContentSearchPaths.Insert(0,"HD"); // } sharedWindow.AddSceneDirector(sharedDirector); //CCScene scene = new CCScene(sharedWindow, sharedViewport, sharedDirector); //CCLayer layer = //layer.Camera = sharedCamera; //scene.AddChild(layer); sharedDirector.RunWithScene(ChipmunkDemoLayer.ActualScene); } public override void ApplicationDidEnterBackground(CCApplication application) { application.PauseGame(); } public override void ApplicationWillEnterForeground(CCApplication application) { application.ResumeGame(); } } }
27.804348
136
0.724394
[ "MIT" ]
iHaD/ChipmunkSharp
examples/ChipmunkExample/win8/AppDelegate.cs
2,560
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IBoxs.SDK.Enum { /// <summary> /// 临时会话类型 /// </summary> public enum TempMsgEnum { /// <summary> /// 来自群 /// </summary> Group=0, /// <summary> /// 来自讨论组 /// </summary> Discuss=1, /// <summary> /// 来自公众号 /// </summary> Official=129, /// <summary> /// 来自QQ咨询 /// </summary> Consulting=201 } }
17.84375
33
0.472855
[ "Apache-2.0" ]
zqu1016/GQRobotSDK
IBoxs.SDK/Enum/TempMsgEnum.cs
619
C#
namespace BundleTransformer.Core.Constants { /// <summary> /// Minifier names constants /// </summary> internal static class MinifierName { /// <summary> /// Name (key) of null minifier /// </summary> public const string NullMinifier = "NullMinifier"; } }
21.692308
53
0.64539
[ "Apache-2.0" ]
kapral/BundleTransformer
src/BundleTransformer.Core/Constants/MinifierName.cs
284
C#
// Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.ML.Data; namespace Microsoft.ML.AutoML { /// <summary> /// A catalog of all available AutoML tasks. /// </summary> public sealed class AutoCatalog { private readonly MLContext _context; internal AutoCatalog(MLContext context) { _context = context; } /// <summary> /// Creates a new AutoML experiment to run on a regression dataset. /// </summary> /// <param name="maxExperimentTimeInSeconds">Maximum number of seconds that experiment will run.</param> /// <returns>A new AutoML regression experiment.</returns> /// <remarks> /// <para>See <see cref="RegressionExperiment"/> for a more detailed code example of an AutoML regression experiment.</para> /// <para>An experiment may run for longer than <paramref name="maxExperimentTimeInSeconds"/>. /// This is because once AutoML starts training an ML.NET model, AutoML lets the /// model train to completion. For instance, if the first model /// AutoML trains takes 4 hours, and the second model trained takes 5 hours, /// but <paramref name="maxExperimentTimeInSeconds"/> was the number of seconds in 6 hours, /// the experiment will run for 4 + 5 = 9 hours (not 6 hours).</para> /// </remarks> public RegressionExperiment CreateRegressionExperiment(uint maxExperimentTimeInSeconds) { return new RegressionExperiment(_context, new RegressionExperimentSettings() { MaxExperimentTimeInSeconds = maxExperimentTimeInSeconds }); } /// <summary> /// Creates a new AutoML experiment to run on a regression dataset. /// </summary> /// <param name="experimentSettings">Settings for the AutoML experiment.</param> /// <returns>A new AutoML regression experiment.</returns> /// <remarks> /// See <see cref="RegressionExperiment"/> for a more detailed code example of an AutoML regression experiment. /// </remarks> public RegressionExperiment CreateRegressionExperiment(RegressionExperimentSettings experimentSettings) { return new RegressionExperiment(_context, experimentSettings); } /// <summary> /// Creates a new AutoML experiment to run on a binary classification dataset. /// </summary> /// <param name="maxExperimentTimeInSeconds">Maximum number of seconds that experiment will run.</param> /// <returns>A new AutoML binary classification experiment.</returns> /// <remarks> /// <para>See <see cref="BinaryClassificationExperiment"/> for a more detailed code example of an AutoML binary classification experiment.</para> /// <para>An experiment may run for longer than <paramref name="maxExperimentTimeInSeconds"/>. /// This is because once AutoML starts training an ML.NET model, AutoML lets the /// model train to completion. For instance, if the first model /// AutoML trains takes 4 hours, and the second model trained takes 5 hours, /// but <paramref name="maxExperimentTimeInSeconds"/> was the number of seconds in 6 hours, /// the experiment will run for 4 + 5 = 9 hours (not 6 hours).</para> /// </remarks> public BinaryClassificationExperiment CreateBinaryClassificationExperiment(uint maxExperimentTimeInSeconds) { return new BinaryClassificationExperiment(_context, new BinaryExperimentSettings() { MaxExperimentTimeInSeconds = maxExperimentTimeInSeconds }); } /// <summary> /// Creates a new AutoML experiment to run on a binary classification dataset. /// </summary> /// <param name="experimentSettings">Settings for the AutoML experiment.</param> /// <returns>A new AutoML binary classification experiment.</returns> /// <remarks> /// See <see cref="BinaryClassificationExperiment"/> for a more detailed code example of an AutoML binary classification experiment. /// </remarks> public BinaryClassificationExperiment CreateBinaryClassificationExperiment(BinaryExperimentSettings experimentSettings) { return new BinaryClassificationExperiment(_context, experimentSettings); } /// <summary> /// Creates a new AutoML experiment to run on a multiclass classification dataset. /// </summary> /// <param name="maxExperimentTimeInSeconds">Maximum number of seconds that experiment will run.</param> /// <returns>A new AutoML multiclass classification experiment.</returns> /// <remarks> /// <para>See <see cref="MulticlassClassificationExperiment"/> for a more detailed code example of an AutoML multiclass classification experiment.</para> /// <para>An experiment may run for longer than <paramref name="maxExperimentTimeInSeconds"/>. /// This is because once AutoML starts training an ML.NET model, AutoML lets the /// model train to completion. For instance, if the first model /// AutoML trains takes 4 hours, and the second model trained takes 5 hours, /// but <paramref name="maxExperimentTimeInSeconds"/> was the number of seconds in 6 hours, /// the experiment will run for 4 + 5 = 9 hours (not 6 hours).</para> /// </remarks> public MulticlassClassificationExperiment CreateMulticlassClassificationExperiment(uint maxExperimentTimeInSeconds) { return new MulticlassClassificationExperiment(_context, new MulticlassExperimentSettings() { MaxExperimentTimeInSeconds = maxExperimentTimeInSeconds }); } /// <summary> /// Creates a new AutoML experiment to run on a multiclass classification dataset. /// </summary> /// <param name="experimentSettings">Settings for the AutoML experiment.</param> /// <returns>A new AutoML multiclass classification experiment.</returns> /// <remarks> /// See <see cref="MulticlassClassificationExperiment"/> for a more detailed code example of an AutoML multiclass classification experiment. /// </remarks> public MulticlassClassificationExperiment CreateMulticlassClassificationExperiment(MulticlassExperimentSettings experimentSettings) { return new MulticlassClassificationExperiment(_context, experimentSettings); } /// <summary> /// Creates a new AutoML experiment to run on a recommendation classification dataset. /// </summary> /// <param name="maxExperimentTimeInSeconds">Maximum number of seconds that experiment will run.</param> /// <returns>A new AutoML recommendation classification experiment.</returns> /// <remarks> /// <para>See <see cref="RecommendationExperiment"/> for a more detailed code example of an AutoML multiclass classification experiment.</para> /// <para>An experiment may run for longer than <paramref name="maxExperimentTimeInSeconds"/>. /// This is because once AutoML starts training an ML.NET model, AutoML lets the /// model train to completion. For instance, if the first model /// AutoML trains takes 4 hours, and the second model trained takes 5 hours, /// but <paramref name="maxExperimentTimeInSeconds"/> was the number of seconds in 6 hours, /// the experiment will run for 4 + 5 = 9 hours (not 6 hours).</para> /// </remarks> public RecommendationExperiment CreateRecommendationExperiment(uint maxExperimentTimeInSeconds) { return new RecommendationExperiment(_context, new RecommendationExperimentSettings() { MaxExperimentTimeInSeconds = maxExperimentTimeInSeconds }); } /// <summary> /// Creates a new AutoML experiment to run on a recommendation dataset. /// </summary> /// <param name="experimentSettings">Settings for the AutoML experiment.</param> /// <returns>A new AutoML recommendation experiment.</returns> /// <remarks> /// See <see cref="RecommendationExperiment"/> for a more detailed code example of an AutoML recommendation experiment. /// </remarks> public RecommendationExperiment CreateRecommendationExperiment(RecommendationExperimentSettings experimentSettings) { return new RecommendationExperiment(_context, experimentSettings); } /// <summary> /// Infers information about the columns of a dataset in a file located at <paramref name="path"/>. /// </summary> /// <param name="path">Path to a dataset file.</param> /// <param name="labelColumnName">The name of the label column.</param> /// <param name="separatorChar">The character used as separator between data elements in a row. If <see langword="null"/>, AutoML will try to infer this value.</param> /// <param name="allowQuoting">Whether the file can contain columns defined by a quoted string. If <see langword="null"/>, AutoML will try to infer this value.</param> /// <param name="allowSparse">Whether the file can contain numerical vectors in sparse format. If <see langword="null"/>, AutoML will try to infer this value.</param> /// <param name="trimWhitespace">Whether trailing whitespace should be removed from dataset file lines.</param> /// <param name="groupColumns">Whether to group together (when possible) original columns in the dataset file into vector columns in the resulting data structures. See <see cref="TextLoader.Range"/> for more information.</param> /// <returns>Information inferred about the columns in the provided dataset.</returns> /// <remarks> /// Infers information about the name, data type, and purpose of each column. /// The returned <see cref="ColumnInferenceResults.TextLoaderOptions" /> can be used to /// instantiate a <see cref="TextLoader" />. The <see cref="TextLoader" /> can be used to /// obtain an <see cref="IDataView"/> that can be fed into an AutoML experiment, /// or used elsewhere in the ML.NET ecosystem (ie in <see cref="IEstimator{TTransformer}.Fit(IDataView)"/>. /// The <see cref="ColumnInformation"/> contains the inferred purpose of each column in the dataset. /// (For instance, is the column categorical, numeric, or text data? Should the column be ignored? Etc.) /// The <see cref="ColumnInformation"/> can be inspected and modified (or kept as is) and used by an AutoML experiment. /// </remarks> public ColumnInferenceResults InferColumns(string path, string labelColumnName = DefaultColumnNames.Label, char? separatorChar = null, bool? allowQuoting = null, bool? allowSparse = null, bool trimWhitespace = false, bool groupColumns = true) { UserInputValidationUtil.ValidateInferColumnsArgs(path, labelColumnName); return ColumnInferenceApi.InferColumns(_context, path, labelColumnName, separatorChar, allowQuoting, allowSparse, trimWhitespace, groupColumns); } /// <summary> /// Infers information about the columns of a dataset in a file located at <paramref name="path"/>. /// </summary> /// <param name="path">Path to a dataset file.</param> /// <param name="columnInformation">Column information for the dataset.</param> /// <param name="separatorChar">The character used as separator between data elements in a row. If <see langword="null"/>, AutoML will try to infer this value.</param> /// <param name="allowQuoting">Whether the file can contain columns defined by a quoted string. If <see langword="null"/>, AutoML will try to infer this value.</param> /// <param name="allowSparse">Whether the file can contain numerical vectors in sparse format. If <see langword="null"/>, AutoML will try to infer this value.</param> /// <param name="trimWhitespace">Whether trailing whitespace should be removed from dataset file lines.</param> /// <param name="groupColumns">Whether to group together (when possible) original columns in the dataset file into vector columns in the resulting data structures. See <see cref="TextLoader.Range"/> for more information.</param> /// <returns>Information inferred about the columns in the provided dataset.</returns> /// <remarks> /// Infers information about the name, data type, and purpose of each column. /// The returned <see cref="ColumnInferenceResults.TextLoaderOptions" /> can be used to /// instantiate a <see cref="TextLoader" />. The <see cref="TextLoader" /> can be used to /// obtain an <see cref="IDataView"/> that can be fed into an AutoML experiment, /// or used elsewhere in the ML.NET ecosystem (ie in <see cref="IEstimator{TTransformer}.Fit(IDataView)"/>. /// The <see cref="ColumnInformation"/> contains the inferred purpose of each column in the dataset. /// (For instance, is the column categorical, numeric, or text data? Should the column be ignored? Etc.) /// The <see cref="ColumnInformation"/> can be inspected and modified (or kept as is) and used by an AutoML experiment. /// </remarks> public ColumnInferenceResults InferColumns(string path, ColumnInformation columnInformation, char? separatorChar = null, bool? allowQuoting = null, bool? allowSparse = null, bool trimWhitespace = false, bool groupColumns = true) { columnInformation = columnInformation ?? new ColumnInformation(); UserInputValidationUtil.ValidateInferColumnsArgs(path, columnInformation); return ColumnInferenceApi.InferColumns(_context, path, columnInformation, separatorChar, allowQuoting, allowSparse, trimWhitespace, groupColumns); } /// <summary> /// Infers information about the columns of a dataset in a file located at <paramref name="path"/>. /// </summary> /// <param name="path">Path to a dataset file.</param> /// <param name="labelColumnIndex">Column index of the label column in the dataset.</param> /// <param name="hasHeader">Whether or not the dataset file has a header row.</param> /// <param name="separatorChar">The character used as separator between data elements in a row. If <see langword="null"/>, AutoML will try to infer this value.</param> /// <param name="allowQuoting">Whether the file can contain columns defined by a quoted string. If <see langword="null"/>, AutoML will try to infer this value.</param> /// <param name="allowSparse">Whether the file can contain numerical vectors in sparse format. If <see langword="null"/>, AutoML will try to infer this value.</param> /// <param name="trimWhitespace">Whether trailing whitespace should be removed from dataset file lines.</param> /// <param name="groupColumns">Whether to group together (when possible) original columns in the dataset file into vector columns in the resulting data structures. See <see cref="TextLoader.Range"/> for more information.</param> /// <returns>Information inferred about the columns in the provided dataset.</returns> /// <remarks> /// Infers information about the name, data type, and purpose of each column. /// The returned <see cref="ColumnInferenceResults.TextLoaderOptions" /> can be used to /// instantiate a <see cref="TextLoader" />. The <see cref="TextLoader" /> can be used to /// obtain an <see cref="IDataView"/> that can be fed into an AutoML experiment, /// or used elsewhere in the ML.NET ecosystem (ie in <see cref="IEstimator{TTransformer}.Fit(IDataView)"/>. /// The <see cref="ColumnInformation"/> contains the inferred purpose of each column in the dataset. /// (For instance, is the column categorical, numeric, or text data? Should the column be ignored? Etc.) /// The <see cref="ColumnInformation"/> can be inspected and modified (or kept as is) and used by an AutoML experiment. /// </remarks> public ColumnInferenceResults InferColumns(string path, uint labelColumnIndex, bool hasHeader = false, char? separatorChar = null, bool? allowQuoting = null, bool? allowSparse = null, bool trimWhitespace = false, bool groupColumns = true) { UserInputValidationUtil.ValidateInferColumnsArgs(path); return ColumnInferenceApi.InferColumns(_context, path, labelColumnIndex, hasHeader, separatorChar, allowQuoting, allowSparse, trimWhitespace, groupColumns); } } }
68.741935
236
0.680608
[ "MIT" ]
AhmedsafwatEwida/machinelearning
src/Microsoft.ML.AutoML/API/AutoCatalog.cs
17,048
C#
using CommonServiceLocator; using ReactiveHMI.M2MCommunication.Core.CommonTypes; using ReactiveHMI.M2MCommunication.Core.Interfaces; using System; using System.ComponentModel.Composition; using System.ComponentModel.Composition.Hosting; using System.IO; using System.Reflection; namespace ReactiveHMI.M2MCommunication.Services { public class ServiceContainerSetup : IDisposable { private readonly UaLibrarySettings _uaLibrarySettings; private readonly ILogger _logger; private ILoggerContainer loggerContainer; internal IServiceLocator DisposableServiceLocator { get; private set; } public ServiceContainerSetup(UaLibrarySettings settings, ILogger logger) { _uaLibrarySettings = settings; _logger = logger; } public ServiceContainerSetup Initialise() { _logger?.LogInfo("Initialising Managed Extensibility Framework container"); AggregateCatalog AggregateCatalog = new AggregateCatalog( new DirectoryCatalog( Path.Combine(Path.GetDirectoryName(Assembly.GetCallingAssembly().Location), _uaLibrarySettings.LibraryDirectory) ) ); CompositionContainer Container = new CompositionContainer(AggregateCatalog); _logger?.LogInfo("Composing configuration file name and logger instance"); Container.ComposeExportedValue(UaContractNames.ConfigurationFileNameContract, Path.Combine( Directory.GetCurrentDirectory(), _uaLibrarySettings.ResourcesDirectory, _uaLibrarySettings.LibraryDirectory, _uaLibrarySettings.ConsumerConfigurationFile) ); Container.ComposeExportedValue(_logger); _logger?.LogInfo("Setting a service locator"); DisposableServiceLocator = new UaooiServiceLocator(Container); ServiceLocator.SetLocatorProvider(() => DisposableServiceLocator); if (shouldComposeLoggers) { _logger?.LogInfo("Composing a common logger for all components"); loggerContainer = Container.GetExportedValue<ILoggerContainer>().EnableLoggers(); } return this; } #region IDisposable Support private bool disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { (DisposableServiceLocator as IDisposable)?.Dispose(); (loggerContainer as IDisposable)?.Dispose(); } DisposableServiceLocator = null; loggerContainer = null; ServiceLocator.SetLocatorProvider(() => null); disposedValue = true; } } // This code added to correctly implement the disposable pattern. public void Dispose() { // Do not change this code. Put cleanup code in Dispose(bool disposing) above. Dispose(true); } #endregion #region Unit test workaround private readonly bool shouldComposeLoggers = true; #endregion } }
35.698925
132
0.637349
[ "MIT" ]
210342/OPC-UA-OOI-webapp
M2M/M2MCommunication.Services/ServiceContainerSetup.cs
3,322
C#
// Copyright (c) 2022 AccelByte Inc. All Rights Reserved. // This is licensed software from AccelByte Inc, for limitations // and restrictions contact your company contract manager. // This code is generated by tool. DO NOT EDIT. using System.Text.Json.Serialization; namespace AccelByte.Sdk.Api.Ugc.Model { public class ModelsLikeState : AccelByte.Sdk.Core.Model { [JsonPropertyName("state")] public bool? State { get; set; } [JsonPropertyName("userId")] public string? UserId { get; set; } } }
28.578947
64
0.692449
[ "MIT" ]
AccelByte/accelbyte-csharp-sdk
AccelByte.Sdk/Api/Ugc/Model/ModelsLikeState.cs
543
C#
namespace KinderChatServer.Areas.HelpPage.ModelDescriptions { public class DictionaryModelDescription : KeyValuePairModelDescription { } }
25.166667
74
0.794702
[ "MIT" ]
XnainA/KinderChat
KinderChatServer/Areas/HelpPage/ModelDescriptions/DictionaryModelDescription.cs
153
C#
/* * Cosmo Tech Plaform API * * Cosmo Tech Platform API * * The version of the OpenAPI document: 0.0.11-SNAPSHOT * Contact: platform@cosmotech.com * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; using OpenAPIDateConverter = Com.Cosmotech.Client.OpenAPIDateConverter; namespace Com.Cosmotech.Model { /// <summary> /// an Organization /// </summary> [DataContract(Name = "Organization")] public partial class Organization : IEquatable<Organization>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="Organization" /> class. /// </summary> /// <param name="name">the Organization name.</param> /// <param name="users">users.</param> /// <param name="services">services.</param> public Organization(string name = default(string), List<OrganizationUser> users = default(List<OrganizationUser>), OrganizationServices services = default(OrganizationServices)) { this.Name = name; this.Users = users; this.Services = services; } /// <summary> /// the Organization unique identifier /// </summary> /// <value>the Organization unique identifier</value> [DataMember(Name = "id", EmitDefaultValue = false)] public string Id { get; private set; } /// <summary> /// Returns false as Id should not be serialized given that it's read-only. /// </summary> /// <returns>false (boolean)</returns> public bool ShouldSerializeId() { return false; } /// <summary> /// the Organization name /// </summary> /// <value>the Organization name</value> [DataMember(Name = "name", EmitDefaultValue = false)] public string Name { get; set; } /// <summary> /// the Owner User Id /// </summary> /// <value>the Owner User Id</value> [DataMember(Name = "ownerId", EmitDefaultValue = false)] public string OwnerId { get; private set; } /// <summary> /// Returns false as OwnerId should not be serialized given that it's read-only. /// </summary> /// <returns>false (boolean)</returns> public bool ShouldSerializeOwnerId() { return false; } /// <summary> /// Gets or Sets Users /// </summary> [DataMember(Name = "users", EmitDefaultValue = false)] public List<OrganizationUser> Users { get; set; } /// <summary> /// Gets or Sets Services /// </summary> [DataMember(Name = "services", EmitDefaultValue = false)] public OrganizationServices Services { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class Organization {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" OwnerId: ").Append(OwnerId).Append("\n"); sb.Append(" Users: ").Append(Users).Append("\n"); sb.Append(" Services: ").Append(Services).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as Organization); } /// <summary> /// Returns true if Organization instances are equal /// </summary> /// <param name="input">Instance of Organization to be compared</param> /// <returns>Boolean</returns> public bool Equals(Organization input) { if (input == null) { return false; } return ( this.Id == input.Id || (this.Id != null && this.Id.Equals(input.Id)) ) && ( this.Name == input.Name || (this.Name != null && this.Name.Equals(input.Name)) ) && ( this.OwnerId == input.OwnerId || (this.OwnerId != null && this.OwnerId.Equals(input.OwnerId)) ) && ( this.Users == input.Users || this.Users != null && input.Users != null && this.Users.SequenceEqual(input.Users) ) && ( this.Services == input.Services || (this.Services != null && this.Services.Equals(input.Services)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.Id != null) { hashCode = (hashCode * 59) + this.Id.GetHashCode(); } if (this.Name != null) { hashCode = (hashCode * 59) + this.Name.GetHashCode(); } if (this.OwnerId != null) { hashCode = (hashCode * 59) + this.OwnerId.GetHashCode(); } if (this.Users != null) { hashCode = (hashCode * 59) + this.Users.GetHashCode(); } if (this.Services != null) { hashCode = (hashCode * 59) + this.Services.GetHashCode(); } return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> public IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
33.949541
185
0.518984
[ "MIT" ]
Cosmo-Tech/cosmotech-api-csharp-client
src/Com.Cosmotech/Model/Organization.cs
7,401
C#
// <auto-generated> // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Lykke.Bitcoin.Api.Client.AutoGenerated.Models { using Newtonsoft.Json; using System.Linq; public partial class OffchainChannelInfo { /// <summary> /// Initializes a new instance of the OffchainChannelInfo class. /// </summary> public OffchainChannelInfo() { CustomInit(); } /// <summary> /// Initializes a new instance of the OffchainChannelInfo class. /// </summary> public OffchainChannelInfo(System.Guid? channelId = default(System.Guid?), System.DateTime? date = default(System.DateTime?), decimal? clientAmount = default(decimal?), decimal? hubAmount = default(decimal?), string transactionHash = default(string), bool? actual = default(bool?)) { ChannelId = channelId; Date = date; ClientAmount = clientAmount; HubAmount = hubAmount; TransactionHash = transactionHash; Actual = actual; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// </summary> [JsonProperty(PropertyName = "channelId")] public System.Guid? ChannelId { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "date")] public System.DateTime? Date { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "clientAmount")] public decimal? ClientAmount { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "hubAmount")] public decimal? HubAmount { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "transactionHash")] public string TransactionHash { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "actual")] public bool? Actual { get; set; } } }
31.205479
289
0.58209
[ "MIT" ]
LykkeCity/bitcoinservice
client/Lykke.Bitcoin.Api.Client/AutoGenerated/Models/OffchainChannelInfo.cs
2,278
C#
namespace Cafeteria { public class Program { public static void Main() { CoffeeShop coffeeShop = new CoffeeShop(); coffeeShop.DisplayDesserts(); } } }
17.666667
53
0.537736
[ "MIT" ]
Inseparable7v/Design-Patterns-master
StructuralPatterns/Adapter/Cafeteria/Program.cs
214
C#
using System; using System.Collections.Generic; using System.Text; namespace P05.BirthdayCelebrations { public class Pet : IMamal { public string Name { get; set; } public string Birthdate { get; set; } public List<string> Pets { get; set; } } }
17.875
46
0.636364
[ "MIT" ]
Karnalow/SoftUni
C# OOP/03. Interfaces and Abstraction/Exercise/P05.BirthdayCelebrations/Pet.cs
288
C#
using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNet.Antiforgery; using Microsoft.AspNet.Mvc; using Microsoft.Data.Entity; using Microsoft.Extensions.Primitives; using MusicStore.Models; using MusicStore.ViewModels; namespace MusicStore.Controllers { public class ShoppingCartController : Controller { public ShoppingCartController(MusicStoreContext dbContext) { DbContext = dbContext; } public MusicStoreContext DbContext { get; } // // GET: /ShoppingCart/ public async Task<IActionResult> Index() { var cart = ShoppingCart.GetCart(DbContext, HttpContext); // Set up our ViewModel var viewModel = new ShoppingCartViewModel { CartItems = await cart.GetCartItems(), CartTotal = await cart.GetTotal() }; // Return the view return View(viewModel); } // // GET: /ShoppingCart/AddToCart/5 public async Task<IActionResult> AddToCart(int id, CancellationToken requestAborted) { // Retrieve the album from the database var addedAlbum = DbContext.Albums .Single(album => album.AlbumId == id); // Add it to the shopping cart var cart = ShoppingCart.GetCart(DbContext, HttpContext); cart.AddToCart(addedAlbum); await DbContext.SaveChangesAsync(requestAborted); // Go back to the main store page for more shopping return RedirectToAction("Index"); } // // AJAX: /ShoppingCart/RemoveFromCart/5 [HttpPost] public async Task<IActionResult> RemoveFromCart( [FromServices] IAntiforgery antiforgery, int id, CancellationToken requestAborted) { var cookieToken = string.Empty; var formToken = string.Empty; StringValues tokenHeaders; string[] tokens = null; if (HttpContext.Request.Headers.TryGetValue("RequestVerificationToken", out tokenHeaders)) { tokens = tokenHeaders.First().Split(':'); if (tokens != null && tokens.Length == 2) { cookieToken = tokens[0]; formToken = tokens[1]; } } antiforgery.ValidateTokens(HttpContext, new AntiforgeryTokenSet(formToken, cookieToken)); // Retrieve the current user's shopping cart var cart = ShoppingCart.GetCart(DbContext, HttpContext); // Get the name of the album to display confirmation var cartItem = await DbContext.CartItems .Where(item => item.CartItemId == id) .Include(c => c.Album) .SingleOrDefaultAsync(); // Remove from cart int itemCount = cart.RemoveFromCart(id); await DbContext.SaveChangesAsync(requestAborted); string removed = (itemCount > 0) ? " 1 copy of " : string.Empty; // Display the confirmation message var results = new ShoppingCartRemoveViewModel { Message = removed + cartItem.Album.Title + " has been removed from your shopping cart.", CartTotal = await cart.GetTotal(), CartCount = await cart.GetCount(), ItemCount = itemCount, DeleteId = id }; return Json(results); } } }
31.695652
102
0.569547
[ "Apache-2.0" ]
reslea/MusicStore
src/MusicStore/Controllers/ShoppingCartController.cs
3,645
C#
namespace Programatica.Saft.Models { public interface IShipFromAddress { string AddressDetail { get; set; } string City { get; set; } string Country { get; set; } string PostalCode { get; set; } } }
24.3
42
0.592593
[ "MIT" ]
ruialexrib/Programatica.Saft.Models
Programatica.Saft.Models/IShipFromAddress.cs
245
C#