commit
stringlengths
40
40
subject
stringlengths
4
1.73k
repos
stringlengths
5
127k
old_file
stringlengths
2
751
new_file
stringlengths
2
751
new_contents
stringlengths
1
8.98k
old_contents
stringlengths
0
6.59k
license
stringclasses
13 values
lang
stringclasses
23 values
02498f854e43b3a3dae84e1ea0f427cd26179758
Remove unnecessary comment and format file.
Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW
src/NadekoBot/Modules/Verification/Exceptions/Exceptions.cs
src/NadekoBot/Modules/Verification/Exceptions/Exceptions.cs
using System; namespace Mitternacht.Modules.Verification.Exceptions { public class UserAlreadyVerifyingException : Exception { } public class UserAlreadyVerifiedException : Exception { } public class UserCannotVerifyException : Exception { } }
using System; namespace Mitternacht.Modules.Verification.Exceptions { public class UserAlreadyVerifyingException : Exception {} public class UserAlreadyVerifiedException : Exception {} public class UserCannotVerifyException : Exception { } //public class Exception : Exception { } }
mit
C#
cb58e89cf702df27b46eeaca73069f86efeed049
Document ContentPipe
izik1/JAGBE
JAGBE/UI/ContentPipe.cs
JAGBE/UI/ContentPipe.cs
using System.Drawing.Imaging; using System.Drawing; using OpenTK.Graphics.OpenGL; using System; namespace JAGBE.UI { /// <summary> /// This class contains functions to generate textures. /// </summary> internal static class ContentPipe { /// <summary> /// Generates a texture with the given <paramref name="bitmap"/><paramref name="width"/> and /// <paramref name="height"/>. /// </summary> /// <param name="bitmap">The bitmap.</param> /// <param name="width">The width.</param> /// <param name="height">The height.</param> /// <returns> /// A new <see cref="Texture2D"/> with width <paramref name="width"/>, height <paramref /// name="height"/>, and <see cref="Bitmap"/><paramref name="bitmap"/> /// </returns> public static Texture2D GenerateTexture(Bitmap bitmap, int width, int height) { int id = GL.GenTexture(); BitmapData bmpData = bitmap.LockBits( new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format32bppArgb); GL.BindTexture(TextureTarget.Texture2D, id); GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, width, height, 0, OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, bmpData.Scan0); bitmap.UnlockBits(bmpData); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Nearest); return new Texture2D(id, width, height); } /// <summary> /// Generates A rgba texture with <paramref name="src"/><paramref name="width"/> and /// <paramref name="height"/>. /// </summary> /// <param name="src">The source.</param> /// <param name="width">The width.</param> /// <param name="height">The height.</param> /// <returns> /// A new <see cref="Texture2D"/> with A bitmap made from <paramref name="src"/>, <paramref /// name="width"/> and <paramref name="height"/> /// </returns> public static Texture2D GenerateRgbaTexture(int[] src, int width, int height) { using (DirectBitmap bitmap = new DirectBitmap(width, height)) { Buffer.BlockCopy(src, 0, bitmap.Bits, 0, width * height * 4); return GenerateTexture(bitmap.Bitmap, width, height); } } } }
using System.Drawing.Imaging; using System.Drawing; using OpenTK.Graphics.OpenGL; using System; namespace JAGBE.UI { internal static class ContentPipe { public static Texture2D GenerateTexture(Bitmap bitmap, int width, int height) { int id = GL.GenTexture(); BitmapData bmpData = bitmap.LockBits( new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format32bppArgb); GL.BindTexture(TextureTarget.Texture2D, id); GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, width, height, 0, OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, bmpData.Scan0); bitmap.UnlockBits(bmpData); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Nearest); return new Texture2D(id, width, height); } public static Texture2D GenerateRgbaTexture(int[] src, int width, int height) { using (DirectBitmap bitmap = new DirectBitmap(width, height)) { Buffer.BlockCopy(src, 0, bitmap.Bits, 0, width * height * 4); return GenerateTexture(bitmap.Bitmap, width, height); } } } }
mit
C#
f20bfe7a554849d6d1fc762741e0fd4f084a4e07
Fix extra semicolon
johnneijzen/osu,smoogipoo/osu,NeoAdonis/osu,2yangk23/osu,smoogipooo/osu,peppy/osu,ppy/osu,NeoAdonis/osu,NeoAdonis/osu,peppy/osu-new,smoogipoo/osu,EVAST9919/osu,ppy/osu,peppy/osu,EVAST9919/osu,UselessToucan/osu,ppy/osu,peppy/osu,UselessToucan/osu,UselessToucan/osu,johnneijzen/osu,smoogipoo/osu,2yangk23/osu
osu.Game/Screens/Edit/Timing/DifficultySection.cs
osu.Game/Screens/Edit/Timing/DifficultySection.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Game.Beatmaps.ControlPoints; using osu.Game.Graphics.Sprites; namespace osu.Game.Screens.Edit.Timing { internal class DifficultySection : Section<DifficultyControlPoint> { private OsuSpriteText multiplier; [BackgroundDependencyLoader] private void load() { Flow.AddRange(new[] { multiplier = new OsuSpriteText(), }); } protected override void LoadComplete() { base.LoadComplete(); ControlPoint.BindValueChanged(point => { multiplier.Text = $"Multiplier: {point.NewValue?.SpeedMultiplier:0.##}x"; }); } protected override DifficultyControlPoint CreatePoint() { var reference = Beatmap.Value.Beatmap.ControlPointInfo.DifficultyPointAt(SelectedGroup.Value.Time); return new DifficultyControlPoint { SpeedMultiplier = reference.SpeedMultiplier, }; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Game.Beatmaps.ControlPoints; using osu.Game.Graphics.Sprites; namespace osu.Game.Screens.Edit.Timing { internal class DifficultySection : Section<DifficultyControlPoint> { private OsuSpriteText multiplier; [BackgroundDependencyLoader] private void load() { Flow.AddRange(new[] { multiplier = new OsuSpriteText(), }); } protected override void LoadComplete() { base.LoadComplete(); ControlPoint.BindValueChanged(point => { multiplier.Text = $"Multiplier: {point.NewValue?.SpeedMultiplier::0.##}x"; }); } protected override DifficultyControlPoint CreatePoint() { var reference = Beatmap.Value.Beatmap.ControlPointInfo.DifficultyPointAt(SelectedGroup.Value.Time); return new DifficultyControlPoint { SpeedMultiplier = reference.SpeedMultiplier, }; } } }
mit
C#
a9dade13f828536ab6bee0b36582e321a075df0c
Add styles and scripts to admin Layout.
alastairs/cgowebsite,alastairs/cgowebsite
src/CGO.Web/Areas/Admin/Views/Shared/_Layout.cshtml
src/CGO.Web/Areas/Admin/Views/Shared/_Layout.cshtml
<!DOCTYPE html> <html lang="en"> <head> <meta name="viewport" content="width=device-width" /> <title>@ViewBag.Title</title> @Styles.Render("~/Content/bootstrap.min.css") @Styles.Render("~/Content/bootstrap-responsive.min.css") @Styles.Render("~/bundles/font-awesome") <!-- HTML5 shim, for IE6-8 support of HTML5 elements --> <!--[if lt IE 9]> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> @Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/modernizr") @Scripts.Render("~/bundles/knockout") <script type="text/javascript"> Modernizr.load({ test: Modernizr.input.placeholder, nope: '/scripts/placeholder.js' }); Modernizr.load({ test: Modernizr.inputtypes.date, nope: '/scripts/datepicker.js' }); </script> </head> <body> <div> @RenderBody() </div> @RenderSection("Scripts", false) </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta name="viewport" content="width=device-width" /> <title>@ViewBag.Title</title> @Styles.Render("~/Content/bootstrap.min.css") </head> <body> <div> @RenderBody() </div> @RenderSection("Scripts", false) </body> </html>
mit
C#
15f9b1086572af6eb7ff3b0b42d6661c34dfb9b1
Add message parameter to XOr method
DaveSenn/Extend
PortableExtensions/PortableExtensions.ISpecification[T]/ISpecification.XOr.cs
PortableExtensions/PortableExtensions.ISpecification[T]/ISpecification.XOr.cs
#region Usings using System; using System.Collections.Generic; using System.Linq; #endregion namespace PortableExtensions { /// <summary> /// Class containing some extension methods for <see cref="ISpecification{T}"/>. /// </summary> public static partial class SpecificationEx { /// <summary> /// Combines the current specification with the given expression using a XOr link. /// </summary> /// <exception cref="ArgumentNullException">specification can not be null.</exception> /// <exception cref="ArgumentNullException">expression can not be null.</exception> /// <typeparam name="T">The target type of the specification.</typeparam> /// <param name="specification">The current specification.</param> /// <param name="expression">The expression to add.</param> /// <param name="message">The validation error message.</param> /// <returns>Returns the combined specifications.</returns> public static ISpecification<T> XOr<T>(this ISpecification<T> specification, Func<T, Boolean> expression, String message = null) { specification.ThrowIfNull(() => specification); expression.ThrowIfNull(() => expression); var newSpecification = new ExpressionSpecification<T>(expression, message); return specification.XOr(newSpecification); } } }
#region Usings using System; using System.Collections.Generic; using System.Linq; #endregion namespace PortableExtensions { /// <summary> /// Class containing some extension methods for <see cref="ISpecification{T}"/>. /// </summary> public static partial class SpecificationEx { /// <summary> /// Combines the current specification with the given expression using a XOr link. /// </summary> /// <typeparam name="T">The target type of the specification.</typeparam> /// <param name="specification">The current specification.</param> /// <param name="expression">The expression to add.</param> /// <returns>Returns the combined specifications.</returns> public static ISpecification<T> XOr<T>(this ISpecification<T> specification, Func<T, Boolean> expression) { var newSpecification = new ExpressionSpecification<T>(expression); return specification.XOr(newSpecification); } } }
mit
C#
dd006401b3d1bcbe41f56b907178ba4d42a691ae
Disable broken taiko hitsound fallback tests for now
UselessToucan/osu,smoogipooo/osu,ppy/osu,smoogipoo/osu,UselessToucan/osu,NeoAdonis/osu,ppy/osu,peppy/osu,smoogipoo/osu,peppy/osu,peppy/osu,NeoAdonis/osu,NeoAdonis/osu,UselessToucan/osu,smoogipoo/osu,ppy/osu,peppy/osu-new
osu.Game.Rulesets.Taiko.Tests/TestSceneTaikoHitObjectSamples.cs
osu.Game.Rulesets.Taiko.Tests/TestSceneTaikoHitObjectSamples.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Reflection; using NUnit.Framework; using osu.Framework.IO.Stores; using osu.Game.Tests.Beatmaps; namespace osu.Game.Rulesets.Taiko.Tests { public class TestSceneTaikoHitObjectSamples : HitObjectSampleTest { protected override Ruleset CreatePlayerRuleset() => new TaikoRuleset(); protected override IResourceStore<byte[]> RulesetResources => new DllResourceStore(Assembly.GetAssembly(typeof(TestSceneTaikoHitObjectSamples))); [TestCase("taiko-normal-hitnormal")] [TestCase("normal-hitnormal")] // [TestCase("hitnormal")] intentionally broken (will play classic default instead). public void TestDefaultCustomSampleFromBeatmap(string expectedSample) { SetupSkins(expectedSample, expectedSample); CreateTestWithBeatmap("taiko-hitobject-beatmap-custom-sample-bank.osu"); AssertBeatmapLookup(expectedSample); } [TestCase("taiko-normal-hitnormal")] [TestCase("normal-hitnormal")] // [TestCase("hitnormal")] intentionally broken (will play classic default instead). public void TestDefaultCustomSampleFromUserSkinFallback(string expectedSample) { SetupSkins(string.Empty, expectedSample); CreateTestWithBeatmap("taiko-hitobject-beatmap-custom-sample-bank.osu"); AssertUserLookup(expectedSample); } [TestCase("taiko-normal-hitnormal2")] [TestCase("normal-hitnormal2")] public void TestUserSkinLookupIgnoresSampleBank(string unwantedSample) { SetupSkins(string.Empty, unwantedSample); CreateTestWithBeatmap("taiko-hitobject-beatmap-custom-sample-bank.osu"); AssertNoLookup(unwantedSample); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Reflection; using NUnit.Framework; using osu.Framework.IO.Stores; using osu.Game.Tests.Beatmaps; namespace osu.Game.Rulesets.Taiko.Tests { public class TestSceneTaikoHitObjectSamples : HitObjectSampleTest { protected override Ruleset CreatePlayerRuleset() => new TaikoRuleset(); protected override IResourceStore<byte[]> RulesetResources => new DllResourceStore(Assembly.GetAssembly(typeof(TestSceneTaikoHitObjectSamples))); [TestCase("taiko-normal-hitnormal")] [TestCase("normal-hitnormal")] [TestCase("hitnormal")] public void TestDefaultCustomSampleFromBeatmap(string expectedSample) { SetupSkins(expectedSample, expectedSample); CreateTestWithBeatmap("taiko-hitobject-beatmap-custom-sample-bank.osu"); AssertBeatmapLookup(expectedSample); } [TestCase("taiko-normal-hitnormal")] [TestCase("normal-hitnormal")] [TestCase("hitnormal")] public void TestDefaultCustomSampleFromUserSkinFallback(string expectedSample) { SetupSkins(string.Empty, expectedSample); CreateTestWithBeatmap("taiko-hitobject-beatmap-custom-sample-bank.osu"); AssertUserLookup(expectedSample); } [TestCase("taiko-normal-hitnormal2")] [TestCase("normal-hitnormal2")] public void TestUserSkinLookupIgnoresSampleBank(string unwantedSample) { SetupSkins(string.Empty, unwantedSample); CreateTestWithBeatmap("taiko-hitobject-beatmap-custom-sample-bank.osu"); AssertNoLookup(unwantedSample); } } }
mit
C#
83c7bfcaf02d16d6804de899f15148dfd11197c3
Make internals visible to mysql lib.
jeroenpot/SqlHelper,mirabeau-nl/Mirabeau-Sql-Helper
Source/Mirabeau.Sql.Library/Properties/AssemblyInfo.cs
Source/Mirabeau.Sql.Library/Properties/AssemblyInfo.cs
using System; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Mirabeau.Sql.Library")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Mirabeau BV")] [assembly: AssemblyProduct("Mirabeau.Sql.Library")] [assembly: AssemblyCopyright("Copyright © Mirabeau BV 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: InternalsVisibleTo("Mirabeau.MsSql.Library, PublicKey=00240000048000009400000006020000002400005253413100040000010001005518300253e09e1480c8150286d1b8998d2fb905ac0f2a97cb482e682d6447ece4a3e6fbfa0eb34b5fb8a5914e61425fbce6ce78ddf610cda22281d48813d247fcef15fb4dbd7b457a5f550c9a7f2213c50093294d9e25e1016ddfcdc505147ab0e0c1fe5a9682b2901a677ecd52ce8c15653f69c82e3a5c83145d32e06bffb7")] [assembly: InternalsVisibleTo("Mirabeau.MySql.Library, PublicKey=0024000004800000940000000602000000240000525341310004000001000100ed11cadb5fe59c9da8cf0b220755b029dc9af656516a83b46721b68482abfcd99dfc0d4cf4e09b5d712a28d7ab7e656356553533dbacfd358661d6d4a7ed562a8aab399750846065998673835aae2797caddc6c8b8effc11d4556aaff97430b088fee2e73ffbe6da570678f3fa0325522f0f203d48a2e5bbe0be8dd37512a4ab")] // 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("fcaf4f57-412d-4ba5-9034-3599bce767f6")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: CLSCompliant(true)] [assembly: NeutralResourcesLanguage("")]
using System; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Mirabeau.Sql.Library")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Mirabeau BV")] [assembly: AssemblyProduct("Mirabeau.Sql.Library")] [assembly: AssemblyCopyright("Copyright © Mirabeau BV 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: InternalsVisibleTo("Mirabeau.MsSql.Library, PublicKey=00240000048000009400000006020000002400005253413100040000010001005518300253e09e1480c8150286d1b8998d2fb905ac0f2a97cb482e682d6447ece4a3e6fbfa0eb34b5fb8a5914e61425fbce6ce78ddf610cda22281d48813d247fcef15fb4dbd7b457a5f550c9a7f2213c50093294d9e25e1016ddfcdc505147ab0e0c1fe5a9682b2901a677ecd52ce8c15653f69c82e3a5c83145d32e06bffb7")] //[assembly: InternalsVisibleTo("Mirabeau.MySql.Library")] // 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("fcaf4f57-412d-4ba5-9034-3599bce767f6")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: CLSCompliant(true)] [assembly: NeutralResourcesLanguage("")]
bsd-3-clause
C#
4aa4a758b061e73e47bd87989edb0a377bdc526b
Split tests by functional and non-functional
dariusz-wozniak/TddCourse
TddCourse.Tests.Unit/Part15/CustomerRepositoryTests.cs
TddCourse.Tests.Unit/Part15/CustomerRepositoryTests.cs
using FluentAssertions; using Moq; using NUnit.Framework; using TddCourse.CustomerExample; namespace TddCourse.Tests.Unit.Part15 { [TestFixture] public class CustomerRepositoryTests { [Test] public void WhenTryingToAddCustomerThatIsNotValidated_ThenCustomerIsNotAdded() { var customerValidatorMock = Mock.Of<ICustomerValidator>(validator => validator.Validate(It.IsAny<ICustomer>()) == false); var customerRepository = new CustomerRepository(customerValidatorMock); customerRepository.Add(It.IsAny<ICustomer>()); customerRepository.AllCustomers.Should().BeEmpty(); } [Test] public void WhenTryingToAddMultipleCustomers_ThenOnlyValidatedOnesAreAdded() { var customerValidatorMock = Mock.Of<ICustomerValidator>(validator => validator.Validate(It.Is<ICustomer>(customer => customer.FirstName == "John")) == true); var customerRepository = new CustomerRepository(customerValidatorMock); customerRepository.Add(Mock.Of<ICustomer>(customer => customer.FirstName == "John")); customerRepository.Add(Mock.Of<ICustomer>(customer => customer.FirstName == "NotJohn")); customerRepository.AllCustomers.Should().HaveCount(1).And.OnlyContain(customer => customer.FirstName == "John"); } [Test] public void WhenAddingCustomer_ThenValidateMethodOfValidatorIsCalledOnce() { var customerValidatorMock = new Mock<ICustomerValidator>(); var customerRepository = new CustomerRepository(customerValidatorMock.Object); customerRepository.Add(Mock.Of<ICustomer>(customer => customer.FirstName == "John")); customerValidatorMock.Verify(x => x.Validate(It.IsAny<ICustomer>()), Times.Exactly(2)); } [Test] public void WhenAddingCustomer_ThenValidateMethodOfValidatorIsCalledOnce__Functional() { var customerValidatorMock = Mock.Of<ICustomerValidator>(); var customerRepository = new CustomerRepository(customerValidatorMock); customerRepository.Add(Mock.Of<ICustomer>(customer => customer.FirstName == "John")); Mock.Get(customerValidatorMock).Verify(validator => validator.Validate(It.Is<ICustomer>(customer => customer.FirstName == "John")), Times.Once); } } }
using FluentAssertions; using Moq; using NUnit.Framework; using TddCourse.CustomerExample; namespace TddCourse.Tests.Unit.Part15 { [TestFixture] public class CustomerRepositoryTests { [Test] public void WhenTryingToAddCustomerThatIsNotValidated_ThenCustomerIsNotAdded() { var customerValidatorMock = Mock.Of<ICustomerValidator>(validator => validator.Validate(It.IsAny<ICustomer>()) == false); var customerRepository = new CustomerRepository(customerValidatorMock); customerRepository.Add(It.IsAny<ICustomer>()); customerRepository.AllCustomers.Should().BeEmpty(); } [Test] public void WhenTryingToAddMultipleCustomers_ThenOnlyValidatedOnesAreAdded() { var customerValidatorMock = Mock.Of<ICustomerValidator>(validator => validator.Validate(It.Is<ICustomer>(customer => customer.FirstName == "John")) == true); var customerRepository = new CustomerRepository(customerValidatorMock); customerRepository.Add(Mock.Of<ICustomer>(customer => customer.FirstName == "John")); customerRepository.Add(Mock.Of<ICustomer>(customer => customer.FirstName == "NotJohn")); customerRepository.AllCustomers.Should().HaveCount(1).And.OnlyContain(customer => customer.FirstName == "John"); } [Test] public void WhenAddingCustomer_ThenValidateMethodOfValidatorIsCalledOnce() { var customerValidatorMock = Mock.Of<ICustomerValidator>(validator => validator.Validate(It.Is<ICustomer>(customer => customer.FirstName == "John"))); var customerRepository = new CustomerRepository(customerValidatorMock); customerRepository.Add(Mock.Of<ICustomer>(customer => customer.FirstName == "John")); Mock.Get(customerValidatorMock).Verify(validator => validator.Validate(It.Is<ICustomer>(customer => customer.FirstName == "John")), Times.Once); } } }
mit
C#
7a41c564375bab8354c308320ff98d2a5603f661
Put version info class under namespace.
soukoku/ModernWPF
VersionInfo.cs
VersionInfo.cs
using System.Reflection; [assembly: AssemblyCompany("Yin-Chun Wang")] [assembly: AssemblyCopyright("Copyright © Yin-Chun Wang 2014")] [assembly: AssemblyVersion(ModernWPF._ModernWPFVersionString.Release)] [assembly: AssemblyFileVersion(ModernWPF._ModernWPFVersionString.Build)] [assembly: AssemblyInformationalVersion(ModernWPF._ModernWPFVersionString.Build)] namespace ModernWPF { static class _ModernWPFVersionString { // keep this same in majors releases public const string Release = "1.0.0.0"; // change this for each nuget release public const string Build = "1.1.30"; } }
using System.Reflection; [assembly: AssemblyCompany("Yin-Chun Wang")] [assembly: AssemblyCopyright("Copyright © Yin-Chun Wang 2014")] [assembly: AssemblyVersion(_ModernWPFVersionString.Release)] [assembly: AssemblyFileVersion(_ModernWPFVersionString.Build)] [assembly: AssemblyInformationalVersion(_ModernWPFVersionString.Build)] static class _ModernWPFVersionString { // keep this same in majors releases public const string Release = "1.0.0.0"; // change this for each nuget release public const string Build = "1.1.30"; }
mit
C#
c95cf57f0c855279e8cdcb276dcba993c48ca380
Fix RateCounter calculation.
Microsoft/ApplicationInsights-SDK-Labs
AggregateMetrics/AggregateMetrics/AzureWebApp/RateCounter.cs
AggregateMetrics/AggregateMetrics/AzureWebApp/RateCounter.cs
namespace Microsoft.ApplicationInsights.Extensibility.AggregateMetrics.AzureWebApp { using System; using Microsoft.ApplicationInsights.DataContracts; using Microsoft.ApplicationInsights.Extensibility.AggregateMetrics.Two; /// <summary> /// Struct for metrics dependant on time. /// </summary> public class RateCounterGauge : ICounterValue { private string name; private double? lastValue; private ICacheHelper cacheHelper; /// <summary> /// DateTime object to keep track of the last time this metric was retrieved. /// </summary> private DateTimeOffset dateTime; /// <summary> /// Initializes a new instance of <see cref="RateCounterGauge"/> class. /// This constructor is intended for Unit Tests. /// </summary> /// <param name="name"> Name of the counter variable.</param> /// <param name="cache"> Cache object.</param> internal RateCounterGauge(string name, ICacheHelper cache) { this.name = name; this.cacheHelper = cache; } /// <summary> /// Initializes a new instance of the <see cref="RateCounterGauge"/> class. /// </summary> /// <param name="name"> Name of counter variable.</param> public RateCounterGauge(string name) : this(name, CacheHelper.Instance) { } /// <summary> /// Returns the current value of the rate counter if enough information exists. /// </summary> /// <returns> MetricTelemetry object.</returns> public MetricTelemetry GetValueAndReset() { MetricTelemetry metric = new MetricTelemetry(); metric.Name = this.name; DateTimeOffset currentTime = System.DateTimeOffset.Now; if (this.lastValue == null) { this.lastValue = cacheHelper.GetCounterValue(this.name); this.dateTime = currentTime; return metric; } metric.Value = (currentTime.Second - this.dateTime.Second != 0) ? (cacheHelper.GetCounterValue(this.name) - (double)this.lastValue) / (currentTime.Subtract(this.dateTime).Seconds) : 0; this.lastValue = cacheHelper.GetCounterValue(this.name); this.dateTime = currentTime; return metric; } } }
namespace Microsoft.ApplicationInsights.Extensibility.AggregateMetrics.AzureWebApp { using System; using Microsoft.ApplicationInsights.DataContracts; using Microsoft.ApplicationInsights.Extensibility.AggregateMetrics.Two; /// <summary> /// Struct for metrics dependant on time. /// </summary> public class RateCounterGauge : ICounterValue { private string name; private double? lastValue; private ICacheHelper cacheHelper; /// <summary> /// DateTime object to keep track of the last time this metric was retrieved. /// </summary> private DateTimeOffset dateTime; /// <summary> /// Initializes a new instance of <see cref="RateCounterGauge"/> class. /// This constructor is intended for Unit Tests. /// </summary> /// <param name="name"> Name of the counter variable.</param> /// <param name="cache"> Cache object.</param> internal RateCounterGauge(string name, ICacheHelper cache) { this.name = name; this.cacheHelper = cache; } /// <summary> /// Initializes a new instance of the <see cref="RateCounterGauge"/> class. /// </summary> /// <param name="name"> Name of counter variable.</param> public RateCounterGauge(string name) : this(name, CacheHelper.Instance) { } /// <summary> /// Returns the current value of the rate counter if enough information exists. /// </summary> /// <returns> MetricTelemetry object.</returns> public MetricTelemetry GetValueAndReset() { MetricTelemetry metric = new MetricTelemetry(); metric.Name = this.name; DateTimeOffset currentTime = System.DateTimeOffset.Now; if (this.lastValue == null) { this.lastValue = cacheHelper.GetCounterValue(this.name); this.dateTime = currentTime; return metric; } metric.Value = (currentTime.Second - this.dateTime.Second != 0) ? ((double)this.lastValue - cacheHelper.GetCounterValue(this.name)) / (currentTime.Second - this.dateTime.Second) : 0; this.lastValue = cacheHelper.GetCounterValue(this.name); this.dateTime = currentTime; return metric; } } }
mit
C#
2124e6bcf7b450084cf66f10c5333772d314f268
Revert "Logging has new overload for exceptions, use it"
tomkuijsten/vsjenkinsmanager
Devkoes.VSJenkinsManager/Devkoes.JenkinsManager.VSPackage/ExposedServices/VisualStudioWindowsHandler.cs
Devkoes.VSJenkinsManager/Devkoes.JenkinsManager.VSPackage/ExposedServices/VisualStudioWindowsHandler.cs
using Devkoes.JenkinsManager.Model.Contract; using Devkoes.JenkinsManager.UI; using Devkoes.JenkinsManager.UI.Views; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using System; namespace Devkoes.JenkinsManager.VSPackage.ExposedServices { public class VisualStudioWindowHandler : IVisualStudioWindowHandler { public void ShowToolWindow() { // Get the instance number 0 of this tool window. This window is single instance so this instance // is actually the only one. // The last flag is set to true so that if the tool window does not exists it will be created. ToolWindowPane window = VSJenkinsManagerPackage.Instance.FindToolWindow(typeof(JenkinsToolWindow), 0, true); if ((null == window) || (null == window.Frame)) { throw new NotSupportedException(Resources.CanNotCreateWindow); } IVsWindowFrame windowFrame = (IVsWindowFrame)window.Frame; Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(windowFrame.Show()); } public void ShowSettingsWindow() { try { VSJenkinsManagerPackage.Instance.ShowOptionPage(typeof(UserOptionsHost)); } catch (Exception ex) { ServicesContainer.OutputWindowLogger.LogOutput( "Showing settings panel failed:", ex.ToString()); } } } }
using Devkoes.JenkinsManager.Model.Contract; using Devkoes.JenkinsManager.UI; using Devkoes.JenkinsManager.UI.Views; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using System; namespace Devkoes.JenkinsManager.VSPackage.ExposedServices { public class VisualStudioWindowHandler : IVisualStudioWindowHandler { public void ShowToolWindow() { // Get the instance number 0 of this tool window. This window is single instance so this instance // is actually the only one. // The last flag is set to true so that if the tool window does not exists it will be created. ToolWindowPane window = VSJenkinsManagerPackage.Instance.FindToolWindow(typeof(JenkinsToolWindow), 0, true); if ((null == window) || (null == window.Frame)) { throw new NotSupportedException(Resources.CanNotCreateWindow); } IVsWindowFrame windowFrame = (IVsWindowFrame)window.Frame; Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(windowFrame.Show()); } public void ShowSettingsWindow() { try { VSJenkinsManagerPackage.Instance.ShowOptionPage(typeof(UserOptionsHost)); } catch (Exception ex) { ServicesContainer.OutputWindowLogger.LogOutput("Showing settings panel failed:", ex); } } } }
mit
C#
03501cba71675425530b7a4f966675c0d445f5f6
Fix MagicBytes unit tests
patchkit-net/patchkit-patcher-unity,patchkit-net/patchkit-patcher-unity,patchkit-net/patchkit-patcher-unity,patchkit-net/patchkit-patcher-unity
Assets/Editor/Tests/MagicBytesTest.cs
Assets/Editor/Tests/MagicBytesTest.cs
using NUnit.Framework; using PatchKit.Unity.Patcher.Data; public class MagicBytesTest { private string _macApp; private string _windowsApp; private string _linuxApp; [SetUp] public void SetUp() { _macApp = TestFixtures.GetFilePath("magicbytes-test/mac_app"); _windowsApp = TestFixtures.GetFilePath("magicbytes-test/windows_app"); _linuxApp = TestFixtures.GetFilePath("magicbytes-test/linux_app"); } [Test] public void IsMacExecutable_ForMacApp_ReturnsTrue() { Assert.IsTrue(MagicBytes.IsMacExecutable(_macApp)); } [Test] public void IsMacExecutable_ForWindowsApp_ReturnsFalse() { Assert.IsFalse(MagicBytes.IsMacExecutable(_windowsApp)); } [Test] public void IsMacExecutable_ForLinuxApp_ReturnsFalse() { Assert.IsFalse(MagicBytes.IsMacExecutable(_linuxApp)); } [Test] public void IsLinuxExecutable_ForMacApp_ReturnsFalse() { Assert.IsFalse(MagicBytes.IsLinuxExecutable(_macApp)); } [Test] public void IsLinuxExecutable_ForWindowsApp_ReturnsFalse() { Assert.IsFalse(MagicBytes.IsLinuxExecutable(_windowsApp)); } [Test] public void IsLinuxExecutable_ForLinuxApp_ReturnsTrue() { Assert.IsTrue(MagicBytes.IsLinuxExecutable(_linuxApp)); } }
using NUnit.Framework; using PatchKit.Unity.Patcher.Data; public class MagicBytesTest { private readonly string _macApp = TestFixtures.GetFilePath("magicbytes-test/mac_app"); private readonly string _windowsApp = TestFixtures.GetFilePath("magicbytes-test/windows_app"); private readonly string _linuxApp = TestFixtures.GetFilePath("magicbytes-test/linux_app"); [Test] public void IsMacExecutable_ForMacApp_ReturnsTrue() { Assert.IsTrue(MagicBytes.IsMacExecutable(_macApp)); } [Test] public void IsMacExecutable_ForWindowsApp_ReturnsFalse() { Assert.IsFalse(MagicBytes.IsMacExecutable(_windowsApp)); } [Test] public void IsMacExecutable_ForLinuxApp_ReturnsFalse() { Assert.IsFalse(MagicBytes.IsMacExecutable(_linuxApp)); } [Test] public void IsLinuxExecutable_ForMacApp_ReturnsFalse() { Assert.IsFalse(MagicBytes.IsLinuxExecutable(_macApp)); } [Test] public void IsLinuxExecutable_ForWindowsApp_ReturnsFalse() { Assert.IsFalse(MagicBytes.IsLinuxExecutable(_windowsApp)); } [Test] public void IsLinuxExecutable_ForLinuxApp_ReturnsTrue() { Assert.IsTrue(MagicBytes.IsLinuxExecutable(_linuxApp)); } }
mit
C#
218b57ccf3db2243bbf7fa44a9c7544e1b935bc8
Speed up alien start up positioning.
Elideb/PJEI
Assets/PJEI/Invaders/Scripts/Level.cs
Assets/PJEI/Invaders/Scripts/Level.cs
using UnityEngine; namespace PJEI.Invaders { public class Level : MonoBehaviour { public Alien[] lines; public int width = 11; public int pixelsBetweenAliens = 48; private Alien[] aliens; void Start() { StartCoroutine(InitGame()); } private System.Collections.IEnumerator InitGame() { aliens = new Alien[lines.Length * width]; for (int i = lines.Length - 1; i >= 0; --i) { for (int j = 0; j < width; ++j) { var alien = (Alien)Instantiate(lines[i]); alien.Initialize(new Vector2D(j - width / 2, -i + lines.Length / 2), i, pixelsBetweenAliens); aliens[i * width + j] = alien; yield return new WaitForSeconds(.05f); } } foreach (var alien in aliens) alien.Run(); } } }
using UnityEngine; namespace PJEI.Invaders { public class Level : MonoBehaviour { public Alien[] lines; public int width = 11; public int pixelsBetweenAliens = 48; private Alien[] aliens; void Start() { StartCoroutine(InitGame()); } private System.Collections.IEnumerator InitGame() { aliens = new Alien[lines.Length * width]; for (int i = lines.Length - 1; i >= 0; --i) { for (int j = 0; j < width; ++j) { var alien = (Alien)Instantiate(lines[i]); alien.Initialize(new Vector2D(j - width / 2, -i + lines.Length / 2), i, pixelsBetweenAliens); aliens[i * width + j] = alien; yield return new WaitForSeconds(.1f); } } foreach (var alien in aliens) alien.Run(); } } }
unlicense
C#
348286a19c4edba870b826f76a03e2f5c13d9a1f
Add test for Enterprise Connect Authorize User with enumerable string
cronofy/cronofy-csharp
test/Cronofy.Test/CronofyEnterpriseConnectAccountClientTests/AuthorizeUser.cs
test/Cronofy.Test/CronofyEnterpriseConnectAccountClientTests/AuthorizeUser.cs
using System; using NUnit.Framework; namespace Cronofy.Test.CronofyEnterpriseConnectAccountClientTests { internal sealed class AuthorizeUser : Base { [Test] public void CanAuthorizeUser() { const string email = "test@cronofy.com"; const string callbackUrl = "https://cronofy.com/test-callback"; const string scopes = "read_account list_calendars read_events create_event delete_event read_free_busy"; Http.Stub( HttpPost .Url("https://api.cronofy.com/v1/service_account_authorizations") .RequestHeader("Authorization", "Bearer " + AccessToken) .RequestHeader("Content-Type", "application/json; charset=utf-8") .RequestBodyFormat( "{{\"email\":\"{0}\"," + "\"callback_url\":\"{1}\"," + "\"scope\":\"{2}\"" + "}}", email, callbackUrl, scopes) .ResponseCode(202) ); Client.AuthorizeUser(email, callbackUrl, scopes); } [Test] public void CanAuthorizeUserWithEnumerableScopes() { const string email = "test@test.com"; const string callbackUrl = "https://test.com/test-callback"; string[] scopes = { "read_account", "list_calendars", "read_events", "create_event", "delete_event", "read_free_busy" }; Http.Stub( HttpPost .Url("https://api.cronofy.com/v1/service_account_authorizations") .RequestHeader("Authorization", "Bearer " + AccessToken) .RequestHeader("Content-Type", "application/json; charset=utf-8") .RequestBodyFormat( "{{\"email\":\"{0}\"," + "\"callback_url\":\"{1}\"," + "\"scope\":\"{2}\"" + "}}", email, callbackUrl, String.Join(" ", scopes)) .ResponseCode(202) ); Client.AuthorizeUser(email, callbackUrl, scopes); } } }
using System; using NUnit.Framework; namespace Cronofy.Test.CronofyEnterpriseConnectAccountClientTests { internal sealed class AuthorizeUser : Base { [Test] public void CanAuthorizeUser() { const string email = "test@cronofy.com"; const string callbackUrl = "https://cronofy.com/test-callback"; const string scopes = "read_account list_calendars read_events create_event delete_event read_free_busy"; Http.Stub( HttpPost .Url("https://api.cronofy.com/v1/service_account_authorizations") .RequestHeader("Authorization", "Bearer " + AccessToken) .RequestHeader("Content-Type", "application/json; charset=utf-8") .RequestBodyFormat( "{{\"email\":\"{0}\"," + "\"callback_url\":\"{1}\"," + "\"scope\":\"{2}\"" + "}}", email, callbackUrl, scopes) .ResponseCode(202) ); Client.AuthorizeUser(email, callbackUrl, scopes); } } }
mit
C#
9e34934395a77c5109a0c71a3f5b59161fee0063
use new guid.
AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet,AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet,AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet,AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet
test/Microsoft.IdentityModel.Tokens.Extensions.Tests/KeyVaultSecurityKeyConfidentialClientTheoryData.cs
test/Microsoft.IdentityModel.Tokens.Extensions.Tests/KeyVaultSecurityKeyConfidentialClientTheoryData.cs
//------------------------------------------------------------------------------ // // Copyright (c) Microsoft Corporation. // All rights reserved. // // This code is licensed under the MIT License. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files(the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and / or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions : // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // //------------------------------------------------------------------------------ using System; namespace Microsoft.IdentityModel.Tokens.KeyVault.Tests { public class KeyVaultSecurityKeyConfidentialClientTheoryData : KeyVaultSecurityKeyTheoryData { public string ClientId { get; set; } = $"{Guid.NewGuid():D}"; public string ClientSecret { get; set; } = Guid.NewGuid().ToString(); } }
//------------------------------------------------------------------------------ // // Copyright (c) Microsoft Corporation. // All rights reserved. // // This code is licensed under the MIT License. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files(the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and / or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions : // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // //------------------------------------------------------------------------------ using System; namespace Microsoft.IdentityModel.Tokens.KeyVault.Tests { public class KeyVaultSecurityKeyConfidentialClientTheoryData : KeyVaultSecurityKeyTheoryData { public string ClientId { get; set; } = $"{Guid.NewGuid():D}"; public string ClientSecret { get; set; } = "AwCuL6DFNwaIHv7fRKsPQw2RXfbSTEF5Z+5YiM1J9S4="; } }
mit
C#
c4002eda94412e4c6cbb1a8a7b3a8e832d784e0b
handle uppercase file extensions
milleniumbug/Taxonomy
TaxonomyWpf/FilePreview.xaml.cs
TaxonomyWpf/FilePreview.xaml.cs
using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace TaxonomyWpf { /// <summary> /// Interaction logic for FilePreview.xaml /// </summary> public partial class FilePreview : UserControl, INotifyPropertyChanged { public FilePreview() { Model = LoadModel(null); InitializeComponent(); Dispatcher.ShutdownStarted += (sender, args) => { Model.Dispose(); }; } public static readonly DependencyProperty FilePathProperty = DependencyProperty.Register( nameof(FilePath), typeof(string), typeof(FilePreview), new FrameworkPropertyMetadata(null, OnFilePathChanged) { BindsTwoWayByDefault = true }); private FilePreviewModel LoadModel(string path) { if (string.IsNullOrWhiteSpace(path)) return new NullPreviewModel(); switch (System.IO.Path.GetExtension(path).ToLowerInvariant()) { case ".txt": return new TextFilePreviewModel(path); case ".png": case ".jpg": case ".jpeg": return new ImagePreviewModel(path); case ".gif": return new AnimatedGifPreviewModel(path); case ".mp4": return new VideoPreviewModel(path); default: return new BinaryFilePreviewModel(path); } } private static void OnFilePathChanged(DependencyObject d, DependencyPropertyChangedEventArgs eventArgs) { var self = (FilePreview)d; var newValue = (string)eventArgs.NewValue; self.Model?.Dispose(); self.Model = self.LoadModel(newValue); } public string FilePath { get { return (string)GetValue(FilePathProperty); } set { SetValue(FilePathProperty, value); } } private FilePreviewModel model; public FilePreviewModel Model { get { return model; } set { if (model == value) return; model = value; OnPropertyChanged(); } } public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace TaxonomyWpf { /// <summary> /// Interaction logic for FilePreview.xaml /// </summary> public partial class FilePreview : UserControl, INotifyPropertyChanged { public FilePreview() { Model = LoadModel(null); InitializeComponent(); Dispatcher.ShutdownStarted += (sender, args) => { Model.Dispose(); }; } public static readonly DependencyProperty FilePathProperty = DependencyProperty.Register( nameof(FilePath), typeof(string), typeof(FilePreview), new FrameworkPropertyMetadata(null, OnFilePathChanged) { BindsTwoWayByDefault = true }); private FilePreviewModel LoadModel(string path) { if (string.IsNullOrWhiteSpace(path)) return new NullPreviewModel(); switch (System.IO.Path.GetExtension(path)) { case ".txt": return new TextFilePreviewModel(path); case ".png": case ".jpg": case ".jpeg": return new ImagePreviewModel(path); case ".gif": return new AnimatedGifPreviewModel(path); case ".mp4": return new VideoPreviewModel(path); default: return new BinaryFilePreviewModel(path); } } private static void OnFilePathChanged(DependencyObject d, DependencyPropertyChangedEventArgs eventArgs) { var self = (FilePreview)d; var newValue = (string)eventArgs.NewValue; self.Model?.Dispose(); self.Model = self.LoadModel(newValue); } public string FilePath { get { return (string)GetValue(FilePathProperty); } set { SetValue(FilePathProperty, value); } } private FilePreviewModel model; public FilePreviewModel Model { get { return model; } set { if (model == value) return; model = value; OnPropertyChanged(); } } public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } }
mit
C#
1d445e45032f598d2ac57db2965e604f513b197e
Reorder services configuration in Startup
Chess-Variants-Training/Chess-Variants-Training,Chess-Variants-Training/Chess-Variants-Training,Chess-Variants-Training/Chess-Variants-Training
src/AtomicChessPuzzles/Startup.cs
src/AtomicChessPuzzles/Startup.cs
using Microsoft.AspNet.Builder; using Microsoft.AspNet.Hosting; using Microsoft.Extensions.DependencyInjection; using AtomicChessPuzzles.Configuration; using AtomicChessPuzzles.DbRepositories; using AtomicChessPuzzles.MemoryRepositories; using AtomicChessPuzzles.Services; namespace AtomicChessPuzzles { public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddMvc(); // Configuration services.AddSingleton<ISettings, Settings>(); // Database repositories services.AddSingleton<ICommentRepository, CommentRepository>(); services.AddSingleton<ICommentVoteRepository, CommentVoteRepository>(); services.AddSingleton<IPositionRepository, PositionRepository>(); services.AddSingleton<IPuzzleRepository, PuzzleRepository>(); services.AddSingleton<IReportRepository, ReportRepository>(); services.AddSingleton<ITimedTrainingScoreRepository, TimedTrainingScoreRepository>(); services.AddSingleton<IUserRepository, UserRepository>(); // Memory repositories services.AddSingleton<IPuzzlesBeingEditedRepository, PuzzlesBeingEditedRepository>(); services.AddSingleton<IPuzzleTrainingSessionRepository, PuzzleTrainingSessionRepository>(); services.AddSingleton<ITimedTrainingSessionRepository, TimedTrainingSessionRepository>(); // Miscellaneous services services.AddSingleton<IMoveCollectionTransformer, MoveCollectionTransformer>(); services.AddSingleton<IPasswordHasher, PasswordHasher>(); services.AddSingleton<IRatingUpdater, RatingUpdater>(); services.AddSingleton<IValidator, Validator>(); services.AddCaching(); services.AddSession(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseIISPlatformHandler(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseSession(); app.UseStaticFiles(); app.UseMvc(); } public static void Main(string[] args) => WebApplication.Run<Startup>(args); } }
using Microsoft.AspNet.Builder; using Microsoft.AspNet.Hosting; using Microsoft.Extensions.DependencyInjection; using AtomicChessPuzzles.Configuration; using AtomicChessPuzzles.DbRepositories; using AtomicChessPuzzles.MemoryRepositories; using AtomicChessPuzzles.Services; namespace AtomicChessPuzzles { public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddSingleton<ISettings, Settings>(); services.AddSingleton<IUserRepository, UserRepository>(); services.AddSingleton<IPuzzlesBeingEditedRepository, PuzzlesBeingEditedRepository>(); services.AddSingleton<IPuzzleRepository, PuzzleRepository>(); services.AddSingleton<IPuzzleTrainingSessionRepository, PuzzleTrainingSessionRepository>(); services.AddSingleton<ICommentRepository, CommentRepository>(); services.AddSingleton<ICommentVoteRepository, CommentVoteRepository>(); services.AddSingleton<IReportRepository, ReportRepository>(); services.AddSingleton<IPositionRepository, PositionRepository>(); services.AddSingleton<ITimedTrainingSessionRepository, TimedTrainingSessionRepository>(); services.AddSingleton<ITimedTrainingScoreRepository, TimedTrainingScoreRepository>(); services.AddSingleton<IRatingUpdater, RatingUpdater>(); services.AddSingleton<IMoveCollectionTransformer, MoveCollectionTransformer>(); services.AddSingleton<IPasswordHasher, PasswordHasher>(); services.AddSingleton<IValidator, Validator>(); services.AddCaching(); services.AddSession(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseIISPlatformHandler(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseSession(); app.UseStaticFiles(); app.UseMvc(); } public static void Main(string[] args) => WebApplication.Run<Startup>(args); } }
agpl-3.0
C#
8861c42e6b1cbc33833c93b28b9c1f644af5edc6
Fix for logging issue, due to a new() vs new LogSource()
dapplo/Dapplo.Jira
src/Dapplo.Jira.Tests/TestBase.cs
src/Dapplo.Jira.Tests/TestBase.cs
// Copyright (c) Dapplo and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Globalization; using System.Threading; using Dapplo.HttpExtensions; using Dapplo.HttpExtensions.ContentConverter; using Dapplo.HttpExtensions.Extensions; using Dapplo.Log; using Dapplo.Log.XUnit; using Xunit.Abstractions; namespace Dapplo.Jira.Tests { /// <summary> /// Abstract base class for all tests /// </summary> public abstract class TestBase { protected static readonly LogSource Log = new LogSource(); protected const string TestProjectKey = "DIT"; protected const string TestIssueKey = "DIT-1"; protected const string TestIssueKey2 = "DIT-123"; // Test against a well known JIRA protected static readonly Uri TestJiraUri = new Uri("https://greenshot.atlassian.net"); /// <summary> /// Default test setup, can also take care of setting the authentication /// </summary> /// <param name="testOutputHelper">ITestOutputHelper</param> /// <param name="doLogin">bool</param> protected TestBase(ITestOutputHelper testOutputHelper, bool doLogin = true) { var ci = new CultureInfo("en-US"); Thread.CurrentThread.CurrentCulture = ci; Thread.CurrentThread.CurrentUICulture = ci; var defaultJsonHttpContentConverterConfiguration = new DefaultJsonHttpContentConverterConfiguration { LogThreshold = 0 }; HttpBehaviour.Current.SetConfig(defaultJsonHttpContentConverterConfiguration); LogSettings.RegisterDefaultLogger<XUnitLogger>(LogLevels.Verbose, testOutputHelper); Client = JiraClient.Create(TestJiraUri); Username = Environment.GetEnvironmentVariable("jira_test_username"); Password = Environment.GetEnvironmentVariable("jira_test_password"); if (doLogin && !string.IsNullOrEmpty(Username) && !string.IsNullOrEmpty(Password)) { Client.SetBasicAuthentication(Username, Password); } } /// <summary> /// The instance of the JiraClient /// </summary> protected IJiraClient Client { get; } protected string Username { get; } protected string Password { get; } } }
// Copyright (c) Dapplo and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Globalization; using System.Threading; using Dapplo.HttpExtensions; using Dapplo.HttpExtensions.ContentConverter; using Dapplo.HttpExtensions.Extensions; using Dapplo.Log; using Dapplo.Log.XUnit; using Xunit.Abstractions; namespace Dapplo.Jira.Tests { /// <summary> /// Abstract base class for all tests /// </summary> public abstract class TestBase { protected static readonly LogSource Log = new(); protected const string TestProjectKey = "DIT"; protected const string TestIssueKey = "DIT-1"; protected const string TestIssueKey2 = "DIT-123"; // Test against a well known JIRA protected static readonly Uri TestJiraUri = new Uri("https://greenshot.atlassian.net"); /// <summary> /// Default test setup, can also take care of setting the authentication /// </summary> /// <param name="testOutputHelper">ITestOutputHelper</param> /// <param name="doLogin">bool</param> protected TestBase(ITestOutputHelper testOutputHelper, bool doLogin = true) { var ci = new CultureInfo("en-US"); Thread.CurrentThread.CurrentCulture = ci; Thread.CurrentThread.CurrentUICulture = ci; var defaultJsonHttpContentConverterConfiguration = new DefaultJsonHttpContentConverterConfiguration { LogThreshold = 0 }; HttpBehaviour.Current.SetConfig(defaultJsonHttpContentConverterConfiguration); LogSettings.RegisterDefaultLogger<XUnitLogger>(LogLevels.Verbose, testOutputHelper); Client = JiraClient.Create(TestJiraUri); Username = Environment.GetEnvironmentVariable("jira_test_username"); Password = Environment.GetEnvironmentVariable("jira_test_password"); if (doLogin && !string.IsNullOrEmpty(Username) && !string.IsNullOrEmpty(Password)) { Client.SetBasicAuthentication(Username, Password); } } /// <summary> /// The instance of the JiraClient /// </summary> protected IJiraClient Client { get; } protected string Username { get; } protected string Password { get; } } }
mit
C#
74b2d74b955044e6f7978262b17366dbcf72382e
fix null in set hashcode
splitice/IPTables.Net,splitice/IPTables.Net,splitice/IPTables.Net,splitice/IPTables.Net
IPTables.Net/Iptables/IpTablesChainDetailEquality.cs
IPTables.Net/Iptables/IpTablesChainDetailEquality.cs
using System; using System.Collections.Generic; using System.Text; namespace IPTables.Net.Iptables { public class IpTablesChainDetailEquality : IEqualityComparer<IpTablesChain> { public bool Equals(IpTablesChain x, IpTablesChain y) { if (x == y) return true; if (x == null || y == null) return false; return x.Name == y.Name && x.Table == y.Table && x.IpVersion == y.IpVersion; } public int GetHashCode(IpTablesChain obj) { if (obj.Name == null) return 0; return obj.Name.GetHashCode(); } } }
using System; using System.Collections.Generic; using System.Text; namespace IPTables.Net.Iptables { public class IpTablesChainDetailEquality : IEqualityComparer<IpTablesChain> { public bool Equals(IpTablesChain x, IpTablesChain y) { if (x == y) return true; if (x == null || y == null) return false; return x.Name == y.Name && x.Table == y.Table && x.IpVersion == y.IpVersion; } public int GetHashCode(IpTablesChain obj) { return obj.Name.GetHashCode(); } } }
apache-2.0
C#
46da3523d090ed3f99c44e9c755ac5e1cbb5c94b
update TextChannelProperties to 6-hour slow mode
AntiTcb/Discord.Net,RogueException/Discord.Net
src/Discord.Net.Core/Entities/Channels/TextChannelProperties.cs
src/Discord.Net.Core/Entities/Channels/TextChannelProperties.cs
using System; namespace Discord { /// <summary> /// Provides properties that are used to modify an <see cref="ITextChannel"/> with the specified changes. /// </summary> /// <seealso cref="ITextChannel.ModifyAsync(System.Action{TextChannelProperties}, RequestOptions)"/> public class TextChannelProperties : GuildChannelProperties { /// <summary> /// Gets or sets the topic of the channel. /// </summary> /// <remarks> /// Setting this value to any string other than <c>null</c> or <see cref="string.Empty"/> will set the /// channel topic or description to the desired value. /// </remarks> public Optional<string> Topic { get; set; } /// <summary> /// Gets or sets whether this channel should be flagged as NSFW. /// </summary> /// <remarks> /// Setting this value to <c>true</c> will mark the channel as NSFW (Not Safe For Work) and will prompt the /// user about its possibly mature nature before they may view the channel; setting this value to <c>false</c> will /// remove the NSFW indicator. /// </remarks> public Optional<bool> IsNsfw { get; set; } /// <summary> /// Gets or sets the slow-mode ratelimit in seconds for this channel. /// </summary> /// <remarks> /// Setting this value to anything above zero will require each user to wait X seconds before /// sending another message; setting this value to <c>0</c> will disable slow-mode for this channel. /// <note> /// Users with <see cref="Discord.ChannelPermission.ManageMessages"/> or /// <see cref="ChannelPermission.ManageChannels"/> will be exempt from slow-mode. /// </note> /// </remarks> /// <exception cref="ArgumentOutOfRangeException">Thrown if the value does not fall within [0, 21600].</exception> public Optional<int> SlowModeInterval { get; set; } } }
using System; namespace Discord { /// <summary> /// Provides properties that are used to modify an <see cref="ITextChannel"/> with the specified changes. /// </summary> /// <seealso cref="ITextChannel.ModifyAsync(System.Action{TextChannelProperties}, RequestOptions)"/> public class TextChannelProperties : GuildChannelProperties { /// <summary> /// Gets or sets the topic of the channel. /// </summary> /// <remarks> /// Setting this value to any string other than <c>null</c> or <see cref="string.Empty"/> will set the /// channel topic or description to the desired value. /// </remarks> public Optional<string> Topic { get; set; } /// <summary> /// Gets or sets whether this channel should be flagged as NSFW. /// </summary> /// <remarks> /// Setting this value to <c>true</c> will mark the channel as NSFW (Not Safe For Work) and will prompt the /// user about its possibly mature nature before they may view the channel; setting this value to <c>false</c> will /// remove the NSFW indicator. /// </remarks> public Optional<bool> IsNsfw { get; set; } /// <summary> /// Gets or sets the slow-mode ratelimit in seconds for this channel. /// </summary> /// <remarks> /// Setting this value to anything above zero will require each user to wait X seconds before /// sending another message; setting this value to <c>0</c> will disable slow-mode for this channel. /// <note> /// Users with <see cref="Discord.ChannelPermission.ManageMessages"/> or /// <see cref="ChannelPermission.ManageChannels"/> will be exempt from slow-mode. /// </note> /// </remarks> /// <exception cref="ArgumentOutOfRangeException">Thrown if the value does not fall within [0, 120].</exception> public Optional<int> SlowModeInterval { get; set; } } }
mit
C#
fc6e7b4c5369bf296fd7026567dd67e4aaa3baa2
Use lookup before registering serializer
SRoddis/Mongo.Migration
Mongo.Migration/Services/MongoDB/MongoRegistrator.cs
Mongo.Migration/Services/MongoDB/MongoRegistrator.cs
using System; using Mongo.Migration.Documents; using Mongo.Migration.Documents.Serializers; using Mongo.Migration.Services.Interceptors; using MongoDB.Bson; using MongoDB.Bson.Serialization; namespace Mongo.Migration.Services.MongoDB { internal class MongoRegistrator : IMongoRegistrator { private readonly MigrationInterceptorProvider _provider; private readonly DocumentVersionSerializer _serializer; public MongoRegistrator(DocumentVersionSerializer serializer, MigrationInterceptorProvider provider) { _serializer = serializer; _provider = provider; } public void Register() { RegisterSerializationProvider(); RegisterSerializer(); } private void RegisterSerializationProvider() { BsonSerializer.RegisterSerializationProvider(_provider); } private void RegisterSerializer() { var foundSerializer = BsonSerializer.LookupSerializer(_serializer.ValueType); if (foundSerializer == null) BsonSerializer.RegisterSerializer(_serializer.ValueType, _serializer); } } }
using System; using Mongo.Migration.Documents; using Mongo.Migration.Documents.Serializers; using Mongo.Migration.Services.Interceptors; using MongoDB.Bson; using MongoDB.Bson.Serialization; namespace Mongo.Migration.Services.MongoDB { internal class MongoRegistrator : IMongoRegistrator { private readonly MigrationInterceptorProvider _provider; private readonly DocumentVersionSerializer _serializer; public MongoRegistrator(DocumentVersionSerializer serializer, MigrationInterceptorProvider provider) { _serializer = serializer; _provider = provider; } public void Register() { BsonSerializer.RegisterSerializationProvider(_provider); try { BsonSerializer.RegisterSerializer(typeof(DocumentVersion), _serializer); } catch (BsonSerializationException Exception) { // Catch if Serializer was registered already, not great. But for testing it must be catched. } } } }
mit
C#
a7a62b289e4886aab967e8f9547cc4d8d1c82628
Return null
SnowmanTackler/SamSeifert.Utilities,SnowmanTackler/SamSeifert.Utilities
DataStructures/DefaultDict.cs
DataStructures/DefaultDict.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SamSeifert.Utilities.DataStructures { /// <summary> /// Regular dictionary, except it has a default value. /// </summary> public class DefaultDict<TKey, TValue> : Dictionary<TKey, TValue> { private readonly Func<TKey, TValue> _DefaultFunc; public DefaultDict(Func<TValue> default_function) { this._DefaultFunc = (TKey k) => default_function(); } public DefaultDict(Func<TKey, TValue> default_function) { this._DefaultFunc = default_function; } public DefaultDict(TValue default_value) : base() { this._DefaultFunc = (TKey k) => default_value; } public new TValue this[TKey key] { get { TValue t; if (this.TryGetValue(key, out t)) return t; else { var newel = this._DefaultFunc(key); this[key] = newel; return newel; } } set { base[key] = value; } } /// <summary> /// Returns value for key if in dictionary, or default value (null). /// Handing when using dict.TryGetValue(key)?.Method(); /// </summary> /// <param name="key"></param> /// <returns></returns> public TValue TryGetValue(TKey key) { TValue t; if (this.TryGetValue(key, out t)) return t; else return default(TValue); // Null or Zero typically } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SamSeifert.Utilities.DataStructures { /// <summary> /// Regular dictionary, except it has a default value. /// </summary> public class DefaultDict<TKey, TValue> : Dictionary<TKey, TValue> { private readonly Func<TKey, TValue> _DefaultFunc; public DefaultDict(Func<TValue> default_function) { this._DefaultFunc = (TKey k) => default_function(); } public DefaultDict(Func<TKey, TValue> default_function) { this._DefaultFunc = default_function; } public DefaultDict(TValue default_value) : base() { this._DefaultFunc = (TKey k) => default_value; } public new TValue this[TKey key] { get { TValue t; if (this.TryGetValue(key, out t)) return t; else { var newel = this._DefaultFunc(key); this[key] = newel; return newel; } } set { base[key] = value; } } } }
mit
C#
a254740882655baf7da46dff854b58ae30409123
Update AssemblyInfo.cs
GHPReporter/Ghpr.NUnit
Ghpr.NUnit/Properties/AssemblyInfo.cs
Ghpr.NUnit/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Ghpr.NUnit")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Evgeniy Kosjakov")] [assembly: AssemblyProduct("Ghpr.NUnit")] [assembly: AssemblyCopyright("Copyright © Evgeniy Kosjakov 2016-2019")] [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("5325be5b-8372-46bc-b7cc-154bd3e9a830")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.9.9.0")] [assembly: AssemblyFileVersion("0.9.9.0")]
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Ghpr.NUnit")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Evgeniy Kosjakov")] [assembly: AssemblyProduct("Ghpr.NUnit")] [assembly: AssemblyCopyright("Copyright © Evgeniy Kosjakov 2016-2019")] [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("5325be5b-8372-46bc-b7cc-154bd3e9a830")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.9.4.1")] [assembly: AssemblyFileVersion("0.9.4.1")]
mit
C#
5cdd7806d0de6049e26c9276c6311dea36b98595
Fix problem with image adapter when an item has empty standard values.
galtrold/propeller.mvc,galtrold/propeller.mvc,galtrold/propeller.mvc,galtrold/propeller.mvc,galtrold/propeller.mvc
src/Framework/PropellerMvcModel/Adapters/Image.cs
src/Framework/PropellerMvcModel/Adapters/Image.cs
using Sitecore; using Sitecore.Data; using Sitecore.Data.Fields; using Sitecore.Data.Items; namespace Propeller.Mvc.Model.Adapters { public class Image : IFieldAdapter { public string Url { get; set; } public string Alt { get; set; } public void InitAdapter(Item item, ID propId) { Url = string.Empty; Alt = string.Empty; ImageField image = item.Fields[propId]; if (image == null ||image.MediaID == ItemIDs.Null) return; var mediaItem = image.MediaDatabase.GetItem(image.MediaID); Url = Sitecore.Resources.Media.MediaManager.GetMediaUrl(mediaItem); Alt = image.Alt; } } }
using Sitecore.Data; using Sitecore.Data.Fields; using Sitecore.Data.Items; namespace Propeller.Mvc.Model.Adapters { public class Image : IFieldAdapter { public string Url { get; set; } public string Alt { get; set; } public void InitAdapter(Item item, ID propId) { ImageField image = item.Fields[propId]; if (image == null) return; var mediaItem = image.MediaDatabase.GetItem(image.MediaID); Url = Sitecore.Resources.Media.MediaManager.GetMediaUrl(mediaItem); Alt = image.Alt; } } }
mit
C#
5283e05062e4be37c8e973d757417a5c130170dd
Implement Serialize method on ReadSingleOrEnumerableFormatter
elastic/elasticsearch-net,elastic/elasticsearch-net
src/Nest/CommonAbstractions/SerializationBehavior/GenericJsonConverters/ReadSingleOrEnumerableFormatter.cs
src/Nest/CommonAbstractions/SerializationBehavior/GenericJsonConverters/ReadSingleOrEnumerableFormatter.cs
using System; using System.Collections.Generic; using System.Linq; using Utf8Json; namespace Nest { internal class ReadSingleOrEnumerableFormatter<T> : IJsonFormatter<IEnumerable<T>> { public IEnumerable<T> Deserialize(ref JsonReader reader, IJsonFormatterResolver formatterResolver) { var token = reader.GetCurrentJsonToken(); return token == JsonToken.BeginArray ? formatterResolver.GetFormatter<IEnumerable<T>>().Deserialize(ref reader, formatterResolver) : new[] { formatterResolver.GetFormatter<T>().Deserialize(ref reader, formatterResolver) }; } public void Serialize(ref JsonWriter writer, IEnumerable<T> value, IJsonFormatterResolver formatterResolver) { if (value == null) { writer.WriteNull(); return; } var formatter = formatterResolver.GetFormatter<IEnumerable<T>>(); formatter.Serialize(ref writer, value, formatterResolver); } } }
using System; using System.Collections.Generic; using Utf8Json; namespace Nest { internal class ReadSingleOrEnumerableFormatter<T> : IJsonFormatter<IEnumerable<T>> { public IEnumerable<T> Deserialize(ref JsonReader reader, IJsonFormatterResolver formatterResolver) { var token = reader.GetCurrentJsonToken(); return token == JsonToken.BeginArray ? formatterResolver.GetFormatter<IEnumerable<T>>().Deserialize(ref reader, formatterResolver) : new[] { formatterResolver.GetFormatter<T>().Deserialize(ref reader, formatterResolver) }; } public void Serialize(ref JsonWriter writer, IEnumerable<T> value, IJsonFormatterResolver formatterResolver) => throw new NotSupportedException(); } }
apache-2.0
C#
dadc20427695b1f87e0fd05586b95a5f36ae16c4
Remove Parse(Uri) overload.
GetTabster/Tabster
Tabster.Core/Parsing/IWebTabParser.cs
Tabster.Core/Parsing/IWebTabParser.cs
#region using System; #endregion namespace Tabster.Core.Parsing { /// <summary> /// Web-based tab parser. /// </summary> public interface IWebTabParser : IStringTabParser { ///<summary> /// Determines whether a specified URL matches a specific pattern used by the parser. Used for web-based parsing. ///</summary> ///<param name="url"> The URL to check. </param> ///<returns> True if the URL matches the supported pattern; otherwise, False. </returns> bool MatchesUrlPattern(Uri url); } }
#region using System; using Tabster.Core.Data; using Tabster.Core.Types; #endregion namespace Tabster.Core.Parsing { /// <summary> /// Web-based tab parser. /// </summary> public interface IWebTabParser : IStringTabParser { /// <summary> /// Parses tab from URL. /// </summary> /// <param name="url"> Source url to parse. </param> /// <param name="type"> Explicitly defined type. </param> /// <returns> Parsed tab. </returns> TablatureDocument Parse(Uri url, TabType? type); //todo remove nullable ///<summary> /// Determines whether a specified URL matches a specific pattern used by the parser. Used for web-based parsing. ///</summary> ///<param name="url"> The URL to check. </param> ///<returns> True if the URL matches the supported pattern; otherwise, False. </returns> bool MatchesUrlPattern(Uri url); } }
apache-2.0
C#
f48d6a23508dfe89899c6f2aa6b62f83d1c726bc
Fix for B2C
mlorbetske/templating,seancpeters/templating,seancpeters/templating,mlorbetske/templating,seancpeters/templating,seancpeters/templating
template_feed/Microsoft.DotNet.Web.ProjectTemplates.2.0/content/StarterWeb-CSharp/Views/_ViewImports.cshtml
template_feed/Microsoft.DotNet.Web.ProjectTemplates.2.0/content/StarterWeb-CSharp/Views/_ViewImports.cshtml
@*#if (IndividualLocalAuth) @using Microsoft.AspNetCore.Identity #endif*@ @using Company.WebApplication1 @using Company.WebApplication1.Models @*#if (IndividualLocalAuth) @using Company.WebApplication1.Models.AccountViewModels @using Company.WebApplication1.Models.ManageViewModels #endif*@ @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@*#if (IndividualAuth) @using Microsoft.AspNetCore.Identity #endif*@ @using Company.WebApplication1 @using Company.WebApplication1.Models @*#if (IndividualAuth) @using Company.WebApplication1.Models.AccountViewModels @using Company.WebApplication1.Models.ManageViewModels #endif*@ @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
mit
C#
d3c11ed9c18f821617871ff8f66f9049daa21ca6
Update WallFilter description
vknet/vk,vknet/vk
VkNet/Enums/SafetyEnums/WallFilter.cs
VkNet/Enums/SafetyEnums/WallFilter.cs
using VkNet.Utils; namespace VkNet.Enums.SafetyEnums { /// <summary> /// Фильтр для задания типов сообщений, которые необходимо получить со стены. /// </summary> public sealed class WallFilter : SafetyEnum<WallFilter> { /// <summary> /// Необходимо получить сообщения на стене только от ее владельца. /// </summary> public static readonly WallFilter Owner = RegisterPossibleValue(value: "owner"); /// <summary> /// Необходимо получить сообщения на стене не от владельца стены. /// </summary> public static readonly WallFilter Others = RegisterPossibleValue(value: "others"); /// <summary> /// Необходимо получить все сообщения на стене (Owner + Others). /// </summary> [DefaultValue] public static readonly WallFilter All = RegisterPossibleValue(value: "all"); /// <summary> /// Предложенные записи на стене сообщества /// </summary> public static readonly WallFilter Suggests = RegisterPossibleValue(value: "suggests"); /// <summary> /// Отложенные записи /// </summary> public static readonly WallFilter Postponed = RegisterPossibleValue(value: "postponed"); } }
using VkNet.Utils; namespace VkNet.Enums.SafetyEnums { /// <summary> /// Фильтр для задания типов сообщений, которые необходимо получить со стены. /// </summary> public sealed class WallFilter : SafetyEnum<WallFilter> { /// <summary> /// Необходимо получить сообщения на стене только от ее владельца. /// </summary> public static readonly WallFilter Owner = RegisterPossibleValue(value: "owner"); /// <summary> /// Необходимо получить сообщения на стене не от владельца стены. /// </summary> public static readonly WallFilter Others = RegisterPossibleValue(value: "others"); /// <summary> /// Необходимо получить все сообщения на стене (Owner + Others). /// </summary> [DefaultValue] public static readonly WallFilter All = RegisterPossibleValue(value: "all"); /// <summary> /// Отложенные записи /// </summary> public static readonly WallFilter Suggests = RegisterPossibleValue(value: "suggests"); /// <summary> /// Предложенные записи на стене сообщества /// </summary> public static readonly WallFilter Postponed = RegisterPossibleValue(value: "postponed"); } }
mit
C#
6aaf7dbe7e025f8df8c61feeffae83b9d183ed34
Bump commit
xamarin/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents
XPlat/ExposureNotification/build.cake
XPlat/ExposureNotification/build.cake
var TARGET = Argument("t", Argument("target", "ci")); var SRC_COMMIT = "a44c9b6646195a3d3089220e79ffcbed3d18b94c"; var SRC_URL = $"https://github.com/xamarin/xamarin.exposurenotification/archive/{SRC_COMMIT}.zip"; var OUTPUT_PATH = (DirectoryPath)"./output/"; var NUGET_VERSION = "0.1.0-beta1"; Task("externals") .Does(() => { DownloadFile(SRC_URL, "./src.zip"); Unzip("./src.zip", "./"); MoveDirectory($"./xamarin.exposurenotification-{SRC_COMMIT}", "./src"); }); Task("libs") .IsDependentOn("externals") .Does(() => { EnsureDirectoryExists(OUTPUT_PATH); MSBuild($"./src/Xamarin.ExposureNotification/Xamarin.ExposureNotification.csproj", c => c .SetConfiguration("Release") .WithRestore() .WithTarget("Build") .WithTarget("Pack") .WithProperty("PackageVersion", NUGET_VERSION) .WithProperty("PackageOutputPath", MakeAbsolute(OUTPUT_PATH).FullPath)); }); Task("nuget") .IsDependentOn("libs"); Task("samples") .IsDependentOn("nuget"); Task("clean") .Does(() => { CleanDirectories("./externals/"); }); Task("ci") .IsDependentOn("nuget"); RunTarget(TARGET);
var TARGET = Argument("t", Argument("target", "ci")); var SRC_COMMIT = "ac5614ee1c7438c06a04d2c96fa451b00ecad408"; var SRC_URL = $"https://github.com/xamarin/xamarin.exposurenotification/archive/{SRC_COMMIT}.zip"; var OUTPUT_PATH = (DirectoryPath)"./output/"; var NUGET_VERSION = "0.1.0-beta1"; Task("externals") .Does(() => { DownloadFile(SRC_URL, "./src.zip"); Unzip("./src.zip", "./"); }); Task("libs") .IsDependentOn("externals") .Does(() => { EnsureDirectoryExists(OUTPUT_PATH); MSBuild("./Xamarin.ExposureNotification/Xamarin.ExposureNotification.csproj", c => c .SetConfiguration("Release") .WithRestore() .WithTarget("Build") .WithTarget("Pack") .WithProperty("PackageVersion", NUGET_VERSION) .WithProperty("PackageOutputPath", MakeAbsolute(OUTPUT_PATH).FullPath)); }); Task("nuget") .IsDependentOn("libs"); Task("samples") .IsDependentOn("nuget"); Task("clean") .Does(() => { CleanDirectories("./externals/"); }); Task("ci") .IsDependentOn("nuget"); RunTarget(TARGET);
mit
C#
d8563ad22da1849561815c9107fab2b30da456b0
Update Assets/MRTK/SDK/Experimental/PulseShader/Scripts/HideOnDevice.cs
killerantz/HoloToolkit-Unity,DDReaper/MixedRealityToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity
Assets/MRTK/SDK/Experimental/PulseShader/Scripts/HideOnDevice.cs
Assets/MRTK/SDK/Experimental/PulseShader/Scripts/HideOnDevice.cs
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; using System.Collections.Generic; using UnityEngine; public class HideOnDevice : MonoBehaviour { // Start is called before the first frame update void Start() { #if !UNITY_EDITOR gameObject.SetActive(false); #endif } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class HideOnDevice : MonoBehaviour { // Start is called before the first frame update void Start() { #if !UNITY_EDITOR gameObject.SetActive(false); #endif } }
mit
C#
f5f166e4fc4a79d870dd07e724556ea5c86a362b
Update Obs.cs
ADAPT/ADAPT
source/ADAPT/Documents/Obs.cs
source/ADAPT/Documents/Obs.cs
/******************************************************************************* * Copyright (C) 2019 AgGateway; PAIL and ADAPT Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html <http://www.eclipse.org/legal/epl-v10.html> * * Contributors: 20190710 R. Andres Ferreyra: Translate from PAIL Part 2 Schema * 20201209 R. Andres Ferreyra: Adding code components by value *******************************************************************************/ using System.Collections.Generic; using AgGateway.ADAPT.ApplicationDataModel.Common; using AgGateway.ADAPT.ApplicationDataModel.Shapes; namespace AgGateway.ADAPT.ApplicationDataModel.Documents { public class Obs // Corresponds to the original PAIL OM; renamed for clarity. { public Obs() { Id = CompoundIdentifierFactory.Instance.Create(); CodeComponents = new List<ObsCodeComponent>(); // List of code components by value to allow parameters, semantic refinement TimeScopes = new List<TimeScope>(); // PhenomenonTime / ResultTime / ValidityRange as per ISO 19156 ContextItems = new List<ContextItem>(); } public CompoundIdentifier Id { get; private set; } public int? OMSourceId { get; set; } // OMSource reduces Obs to (mostly) key,value pair even with sensors, installation public int? OMCodeId { get; set; } // OMCode reduces Obs to (mostly) key,value pair when installation data is not needed public string OMCode { get; set; } // The string value provides the simplest form of meaning, by referring a pre-existing semantic resource by name (code). public List<ObsCodeComponent> CodeComponents { get; set; } // List of code components (by value) to allow parameters, semantic refinement public List<TimeScope> TimeScopes { get; set; } public int? GrowerId { get; set; } // Optional, provides ability to put an Obs in the context of a grower public int? PlaceId { get; set; } // Optional, provides ability to put an Obs in the context of a Place public Shape SpatialExtent { get; set; } // Optional, includes Point, Polyline, and Polygon features of interest // Note: PlaceId provides a feature of interest by reference; SpatialExtent does so by value. They are not necessarily // mutually exclusive. public string Value { get; set; } // The actual value of the observation. Its meaning is described by the OMCodeDefinition public string UoMCode { get; set; } // ADAPT codes for units of measure (e.g., "m1s-1" for meter/second) are required here. // PAIL allows different UoMAuthorities; but translation must happen in the PAIL plug-in level. public List<ContextItem> ContextItems { get; set; } } }
/******************************************************************************* * Copyright (C) 2019 AgGateway; PAIL and ADAPT Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html <http://www.eclipse.org/legal/epl-v10.html> * * Contributors: 20190710 R. Andres Ferreyra: Translate from PAIL Part 2 Schema * 20201209 R. Andres Ferreyra: Adding code components by value *******************************************************************************/ using System.Collections.Generic; using AgGateway.ADAPT.ApplicationDataModel.Common; using AgGateway.ADAPT.ApplicationDataModel.Shapes; namespace AgGateway.ADAPT.ApplicationDataModel.Documents { public class Obs // Corresponds to the original PAIL OM; renamed for clarity. { public Obs() { Id = CompoundIdentifierFactory.Instance.Create(); CodeComponentIds = new List<int>(); // List of code components by reference to allow parameters, semantic refinement CodeComponents = new List<ObsCodeComponent>(); // List of code components by value to allow parameters, semantic refinement TimeScopes = new List<TimeScope>(); // PhenomenonTime / ResultTime / ValidityRange as per ISO 19156 ContextItems = new List<ContextItem>(); } public CompoundIdentifier Id { get; private set; } public int? OMSourceId { get; set; } // OMSource reduces Obs to (mostly) key,value pair even with sensors, installation public int? OMCodeId { get; set; } // OMCode reduces Obs to (mostly) key,value pair when installation data is not needed public string OMCode { get; set; } // The string value provides the simplest form of meaning, by referring a pre-existing semantic resource by name (code). public List<int> CodeComponentIds { get; set; } // List of code components refs to allow parameters, semantic refinement public List<int> CodeComponents { get; set; } // List of code components (by value) to allow parameters, semantic refinement public List<TimeScope> TimeScopes { get; set; } public int? GrowerId { get; set; } // Optional, provides ability to put an Obs in the context of a grower public int? PlaceId { get; set; } // Optional, provides ability to put an Obs in the context of a Place public Shape SpatialExtent { get; set; } // Optional, includes Point, Polyline, and Polygon features of interest // Note: PlaceId provides a feature of interest by reference; SpatialExtent does so by value. They are not necessarily // mutually exclusive. public string Value { get; set; } // The actual value of the observation. Its meaning is described by the OMCodeDefinition public string UoMCode { get; set; } // ADAPT codes for units of measure (e.g., "m1s-1" for meter/second) are required here. // PAIL allows different UoMAuthorities; but translation must happen in the PAIL plug-in level. public List<ContextItem> ContextItems { get; set; } } }
epl-1.0
C#
107b91586670c78ca70370a1008ff024adaeb4b3
Test [Edit] on NakedObjects as a contributed action
NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework
Test/AdventureWorksModel/Sales/SpecialOfferContributedActions.cs
Test/AdventureWorksModel/Sales/SpecialOfferContributedActions.cs
using System; using System.Linq; using NakedObjects; namespace AdventureWorksModel.Sales { public class SpecialOfferContributedActions { public void ExtendOffers([ContributedAction] IQueryable<SpecialOffer> offers, DateTime toDate) { foreach (SpecialOffer offer in offers) { offer.EndDate = toDate; } } public void TerminateActiveOffers([ContributedAction] IQueryable<SpecialOffer> offers) { foreach (SpecialOffer offer in offers) { var yesterday = DateTime.Today.AddDays(-1); if (offer.EndDate > yesterday) //i.e. only terminate offers not already completed { offer.EndDate = yesterday; } } } public void ChangeType( [ContributedAction] IQueryable<SpecialOffer> offers, string newType) { foreach (SpecialOffer offer in offers) { offer.Type = newType; } } public void ChangeMaxQuantity([ContributedAction] IQueryable<SpecialOffer> offers, int newMax) { foreach (SpecialOffer offer in offers) { offer.MaxQty = newMax; } } public void ChangeDiscount([ContributedAction] IQueryable<SpecialOffer> offers, decimal newDiscount) { foreach (SpecialOffer offer in offers) { offer.DiscountPct = newDiscount; } } //To test an empty param public void AppendToDescription([ContributedAction] IQueryable<SpecialOffer> offers, [Optionally] string text) { if (string.IsNullOrEmpty(text)) return; foreach (SpecialOffer offer in offers) { offer.Description += text; } } [Edit] public void EditMaxQty([ContributedAction] SpecialOffer specialOffer, int maxQty) { specialOffer.MaxQty = maxQty; } } }
using System; using System.Linq; using NakedObjects; namespace AdventureWorksModel.Sales { public class SpecialOfferContributedActions { public void ExtendOffers([ContributedAction] IQueryable<SpecialOffer> offers, DateTime toDate) { foreach (SpecialOffer offer in offers) { offer.EndDate = toDate; } } public void TerminateActiveOffers([ContributedAction] IQueryable<SpecialOffer> offers) { foreach (SpecialOffer offer in offers) { var yesterday = DateTime.Today.AddDays(-1); if (offer.EndDate > yesterday) //i.e. only terminate offers not already completed { offer.EndDate = yesterday; } } } public void ChangeType( [ContributedAction] IQueryable<SpecialOffer> offers, string newType) { foreach (SpecialOffer offer in offers) { offer.Type = newType; } } public void ChangeMaxQuantity([ContributedAction] IQueryable<SpecialOffer> offers, int newMax) { foreach (SpecialOffer offer in offers) { offer.MaxQty = newMax; } } public void ChangeDiscount([ContributedAction] IQueryable<SpecialOffer> offers, decimal newDiscount) { foreach (SpecialOffer offer in offers) { offer.DiscountPct = newDiscount; } } //To test an empty param public void AppendToDescription([ContributedAction] IQueryable<SpecialOffer> offers, [Optionally] string text) { if (string.IsNullOrEmpty(text)) return; foreach (SpecialOffer offer in offers) { offer.Description += text; } } } }
apache-2.0
C#
5a349f58c39a4a8045358f451004890582ca1db2
fix bug can't shoot barrel edit
LNWPOR/HamsterRushVR-Client
Assets/Scripts/GameManager.cs
Assets/Scripts/GameManager.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GameManager : MonoBehaviour { public string URL = "http://localhost:8000"; public PlayerData playerData; public int characterType; private static GameManager _instance; public static GameManager Instance { get { if (_instance == null) { _instance = new GameObject("GameManager").AddComponent<GameManager>(); } return _instance; } } void Awake() { playerData = new PlayerData("58e28708a8730c1ed41dd793", "LNWPOR", 0, 0); characterType = 0; DontDestroyOnLoad(gameObject); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GameManager : MonoBehaviour { public string URL = "http://localhost:8000"; public PlayerData playerData; public int characterType; private static GameManager _instance; public static GameManager Instance { get { if (_instance == null) { _instance = new GameObject("GameManager").AddComponent<GameManager>(); } return _instance; } } void Awake() { playerData = new PlayerData("58e28708a8730c1ed41dd793", "LNWPOR", 0, 0); characterType = 2; DontDestroyOnLoad(gameObject); } }
mit
C#
c16babaf9cd136a302515dec4e6d590cf61f8692
fix bug score
ifgx/rtm-phase2
Assets/scripts/hero/Wizard.cs
Assets/scripts/hero/Wizard.cs
using UnityEngine; using System.Collections; /** * @author HugoLS * @version 1.0 **/ public class Wizard : Hero { float specialCapacityCooldown = 30.0f; float specialCapacityTimer = 5.0f; float shieldSize = 0.0f; public float fireBallDiameter = 0.6f; // Use this for initialization void Start () { gameObject.GetComponent<Renderer>().material.color = Color.cyan; } // Update is called once per frame void Update () { base.Update(); if(PowerQuantity < MaxPowerQuantity) { if(base.lastRegenPower + 1 < Time.time) { base.RegenPower(); } } } /** * Constructeur de la classe Wizard * @version 1.0 **/ public Wizard() :base( HeroConfigurator.wizardRange, HeroConfigurator.wizardXpQuantity, HeroConfigurator.wizardBlockingPercent, "baton", HeroConfigurator.wizardPowerQuantity, HeroConfigurator.wizardHpRefresh, HeroConfigurator.wizardPowerRefresh, HeroConfigurator.wizardHp, HeroConfigurator.wizardDamage, HeroConfigurator.wizardMovementSpeed, "distance", "Gandalf"){ } /** * {@inheritDoc} **/ public override void HasKilled(float XP) { GiveXP(XP); RegenPower(); RegenPower(); powerQuantity += HeroConfigurator.wizardRegenAttack; GameModel.Score += 100; } /** * {@inheritDoc} **/ public override void adaptStatAccordingToLevel() { if(level > 5) { //Debug.LogError("LVL UP 6"); SpecialCapacityUnlocked = true; LastCapacityUsed = Time.time; } else if(level > 4) { //Debug.LogError("LVL 5"); fireBallDiameter *=2; Damage *= 1.1f; } else if(level > 3) { //Debug.LogError("LVL 4"); MaxHealthPoint *= 1.1f; } else if(level > 2) { //Debug.LogError("LVL 3"); Damage *= 1.1f; } else if(level > 1) { //Debug.LogError("LVL 2"); Damage *= 1.1f; } } /** * {@inheritDoc} **/ public override void SpecialCapacitySpell() { } /** * {@inheritDoc} **/ public override void PreAttack() { } /** * {@inheritDoc} **/ public override void PostAttack() { } }
using UnityEngine; using System.Collections; /** * @author HugoLS * @version 1.0 **/ public class Wizard : Hero { float specialCapacityCooldown = 30.0f; float specialCapacityTimer = 5.0f; float shieldSize = 0.0f; public float fireBallDiameter = 0.6f; // Use this for initialization void Start () { gameObject.GetComponent<Renderer>().material.color = Color.cyan; } // Update is called once per frame void Update () { base.Update(); if(PowerQuantity < MaxPowerQuantity) { if(base.lastRegenPower + 1 < Time.time) { base.RegenPower(); } } } /** * Constructeur de la classe Wizard * @version 1.0 **/ public Wizard() :base( HeroConfigurator.wizardRange, HeroConfigurator.wizardXpQuantity, HeroConfigurator.wizardBlockingPercent, "baton", HeroConfigurator.wizardPowerQuantity, HeroConfigurator.wizardHpRefresh, HeroConfigurator.wizardPowerRefresh, HeroConfigurator.wizardHp, HeroConfigurator.wizardDamage, HeroConfigurator.wizardMovementSpeed, "distance", "Gandalf"){ } /** * {@inheritDoc} **/ public override void HasKilled(float XP) { GiveXP(XP); RegenPower(); RegenPower(); powerQuantity += HeroConfigurator.wizardRegenAttack; } /** * {@inheritDoc} **/ public override void adaptStatAccordingToLevel() { if(level > 5) { //Debug.LogError("LVL UP 6"); SpecialCapacityUnlocked = true; LastCapacityUsed = Time.time; } else if(level > 4) { //Debug.LogError("LVL 5"); fireBallDiameter *=2; Damage *= 1.1f; } else if(level > 3) { //Debug.LogError("LVL 4"); MaxHealthPoint *= 1.1f; } else if(level > 2) { //Debug.LogError("LVL 3"); Damage *= 1.1f; } else if(level > 1) { //Debug.LogError("LVL 2"); Damage *= 1.1f; } } /** * {@inheritDoc} **/ public override void SpecialCapacitySpell() { } /** * {@inheritDoc} **/ public override void PreAttack() { } /** * {@inheritDoc} **/ public override void PostAttack() { } }
cc0-1.0
C#
1a4c37088da5ed7aa3a96b1ab706a41582b0022f
Revert "Added to ImplementTypeEnum. --Signed-off-by Scott Straka <strakascotte@johndeere.com>"
tarakreddy/ADAPT,ADAPT/ADAPT
source/ADAPT/Equipment/ImplementTypeEnum.cs
source/ADAPT/Equipment/ImplementTypeEnum.cs
/******************************************************************************* * Copyright (C) 2015 AgGateway and ADAPT Contributors * Copyright (C) 2015 Deere and Company * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html <http://www.eclipse.org/legal/epl-v10.html> * * Contributors: * Kathleen Oneal - initial API and implementation *******************************************************************************/ namespace AgGateway.ADAPT.ApplicationDataModel.Equipment { public enum ImplementTypeEnum { } }
/******************************************************************************* * Copyright (C) 2015 AgGateway and ADAPT Contributors * Copyright (C) 2015 Deere and Company * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html <http://www.eclipse.org/legal/epl-v10.html> * * Contributors: * Kathleen Oneal - initial API and implementation *******************************************************************************/ namespace AgGateway.ADAPT.ApplicationDataModel.Equipment { public enum ImplementTypeEnum { Tillage = 2, SecondaryTillage = 3, Seeders_Planters = 4, Fertilizers = 5, Sprayers = 6, Harvesters = 7, RootHarvesters = 8, Forage = 9, Irrigation = 10, Transport_Trailers = 11, FarmsteadOperations = 12, PoweredAuxiliaryDevices = 13, SpecialCrop = 14, Earthworks = 15, Skidders = 16, SensorSystems = 17, SlurryApplicators = 25, Planter, Seeder, PullBehindSprayer, LiquidFertTool, NH3Tool, GrainDrill, DrySpreader, BeltPickup, Draper, Platform, CornHead, RowCropHead, RowUnits, RowDependent, RowIndependent, Boom, Other, RotaryDitcher, Scraper, Pickup, AirCart, Cart, ChoppingCornHead, RigidPlatform, FlexibleDraper, FlexPlatform, HydraflexPlatform, UnknownHead, Baler, CottonStripper, CaneHarvester, CottonPicker, Rotary } }
epl-1.0
C#
cbbc1cb30e5f70138a2e6c8f439a45b9fd6ef92b
Delete [Display](all work's without it), fix Date format in Create
DevRainSolutions/asp-net-mvc-localization,DevRainSolutions/asp-net-mvc-localization,DevRainSolutions/asp-net-mvc-localization
asp-net-mvc-localization/asp-net-mvc-localization/Models/User.cs
asp-net-mvc-localization/asp-net-mvc-localization/Models/User.cs
using System.ComponentModel.DataAnnotations; using System; using asp_net_mvc_localization.Utils; using Newtonsoft.Json.Serialization; namespace asp_net_mvc_localization.Models { public class User { [Required] public string Username { get; set; } [Required] [MyEmailAddress] public string Email { get; set; } [Required] [MinLength(6)] [MaxLength(64)] public string Password { get; set; } [Range(1,125)] public int Age { get; set; } [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:d}")] public DateTime Birthday { get; set; } [Required] [Range(0.1, 9.9)] public double Rand { get; set; } } }
using System.ComponentModel.DataAnnotations; using System; using asp_net_mvc_localization.Utils; using Newtonsoft.Json.Serialization; namespace asp_net_mvc_localization.Models { public class User { [Required] public string Username { get; set; } [Display] [Required] [MyEmailAddress] public string Email { get; set; } [Display] [Required] [MinLength(6)] [MaxLength(64)] public string Password { get; set; } [Display] [Range(1,125)] public int Age { get; set; } [Display] public DateTime Birthday { get; set; } [Display] [Required] [Range(0.1, 9.9)] public double Rand { get; set; } } }
mit
C#
8d7803a7bcdfea154436893e218c0707d74ec166
Fix linebreaks
OpenStreamDeck/StreamDeckSharp
src/StreamDeckSharp/DeviceInfo.cs
src/StreamDeckSharp/DeviceInfo.cs
using HidLibrary; using OpenMacroBoard.SDK; namespace StreamDeckSharp { /// <summary> /// Device information about Stream Deck /// </summary> public class DeviceRefereceHandle : IStreamDeckRefHandle { internal DeviceRefereceHandle(string devicePath) : this(devicePath, null) { } internal DeviceRefereceHandle(string devicePath, string deviceName) { DevicePath = devicePath; DeviceName = deviceName; } /// <summary> /// Unique identifier for human interface device /// </summary> public string DevicePath { get; } public string DeviceName { get; } public override string ToString() => DeviceName; /// <summary> /// Opens the StreamDeck handle /// </summary> /// <returns>Returns an <see cref="IMacroBoard"/> reference</returns> public IStreamDeckBoard Open() => StreamDeck.OpenDevice(DevicePath); IMacroBoard IDeviceReferenceHandle.Open() => Open(); } }
using HidLibrary; using OpenMacroBoard.SDK; namespace StreamDeckSharp { /// <summary> /// Device information about Stream Deck /// </summary> public class DeviceRefereceHandle : IStreamDeckRefHandle { internal DeviceRefereceHandle(string devicePath) : this(devicePath, null) { } internal DeviceRefereceHandle(string devicePath, string deviceName) { DevicePath = devicePath; DeviceName = deviceName; } /// <summary> /// Unique identifier for human interface device /// </summary> public string DevicePath { get; } public string DeviceName { get; } public override string ToString() => DeviceName; /// <summary> /// Opens the StreamDeck handle /// </summary> /// <returns>Returns an <see cref="IMacroBoard"/> reference</returns> public IStreamDeckBoard Open() => StreamDeck.OpenDevice(DevicePath); IMacroBoard IDeviceReferenceHandle.Open() => Open(); } }
mit
C#
8e39a188e3fb550acaf2239110459ec76c37abcb
Test window spans larger than input
robkeim/xcsharp,robkeim/xcsharp,ErikSchierboom/xcsharp,GKotfis/csharp,exercism/xcsharp,GKotfis/csharp,ErikSchierboom/xcsharp,exercism/xcsharp
exercises/largest-series-product/LargestSeriesProductTest.cs
exercises/largest-series-product/LargestSeriesProductTest.cs
using System; using NUnit.Framework; [TestFixture] public class LargestSeriesProductTest { [TestCase("01234567890", 2, ExpectedResult = 72)] [TestCase("1027839564", 3, ExpectedResult = 270)] public int Gets_the_largest_product(string digits, int seriesLength) { return new LargestSeriesProduct(digits).GetLargestProduct(seriesLength); } [Ignore("Remove to run test")] [Test] public void Largest_product_works_for_small_numbers() { Assert.That(new LargestSeriesProduct("19").GetLargestProduct(2), Is.EqualTo(9)); } [Ignore("Remove to run test")] [Test] public void Largest_product_works_for_large_numbers() { const string LARGE_NUMBER = "73167176531330624919225119674426574742355349194934"; Assert.That(new LargestSeriesProduct(LARGE_NUMBER).GetLargestProduct(6), Is.EqualTo(23520)); } [Ignore("Remove to run test")] [TestCase("0000", 2, ExpectedResult = 0)] [TestCase("99099", 3, ExpectedResult = 0)] public int Largest_product_works_if_all_spans_contain_zero(string digits, int seriesLength) { return new LargestSeriesProduct(digits).GetLargestProduct(seriesLength); } [Ignore("Remove to run test")] [TestCase("", ExpectedResult = 1)] [TestCase("123", ExpectedResult = 1)] public int Largest_product_for_empty_span_is_1(string digits) { return new LargestSeriesProduct(digits).GetLargestProduct(0); } [Ignore("Remove to run test")] [TestCase("123", 4)] [TestCase("", 1)] public void Cannot_take_largest_product_of_more_digits_than_input(string digits, int seriesLength) { Assert.Throws<ArgumentException>(() => new LargestSeriesProduct(digits).GetLargestProduct(seriesLength)); } }
using System; using NUnit.Framework; [TestFixture] public class LargestSeriesProductTest { [TestCase("01234567890", 2, ExpectedResult = 72)] [TestCase("1027839564", 3, ExpectedResult = 270)] public int Gets_the_largest_product(string digits, int seriesLength) { return new LargestSeriesProduct(digits).GetLargestProduct(seriesLength); } [Ignore("Remove to run test")] [Test] public void Largest_product_works_for_small_numbers() { Assert.That(new LargestSeriesProduct("19").GetLargestProduct(2), Is.EqualTo(9)); } [Ignore("Remove to run test")] [Test] public void Largest_product_works_for_large_numbers() { const string LARGE_NUMBER = "73167176531330624919225119674426574742355349194934"; Assert.That(new LargestSeriesProduct(LARGE_NUMBER).GetLargestProduct(6), Is.EqualTo(23520)); } [Ignore("Remove to run test")] [TestCase("0000", 2, ExpectedResult = 0)] [TestCase("99099", 3, ExpectedResult = 0)] public int Largest_product_works_if_all_spans_contain_zero(string digits, int seriesLength) { return new LargestSeriesProduct(digits).GetLargestProduct(seriesLength); } [Ignore("Remove to run test")] [TestCase("", ExpectedResult = 1)] [TestCase("123", ExpectedResult = 1)] public int Largest_product_for_empty_span_is_1(string digits) { return new LargestSeriesProduct(digits).GetLargestProduct(0); } }
mit
C#
eb77b07ff6fde0436cd32615816f16b05744f781
Remove environment variable
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
test/LocalizationWebsite/Program.cs
test/LocalizationWebsite/Program.cs
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; namespace LocalizationWebsite { public static class Program { public static void Main(string[] args) { var config = new ConfigurationBuilder() .AddCommandLine(args) .Build(); var host = new WebHostBuilder() .UseKestrel() .UseConfiguration(config) .UseStartup("LocalizationWebsite") .Build(); host.Run(); } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; namespace LocalizationWebsite { public static class Program { public static void Main(string[] args) { var config = new ConfigurationBuilder() .AddCommandLine(args) .AddEnvironmentVariables(prefix: "ASPNETCORE_") .Build(); var host = new WebHostBuilder() .UseKestrel() .UseConfiguration(config) .UseStartup("LocalizationWebsite") .Build(); host.Run(); } } }
apache-2.0
C#
fe9c9bd49a9e5b609d02f97dc33963848d208c68
Fix build error from the last commit
couchbase/couchbase-lite-net,couchbase/couchbase-lite-net,couchbase/couchbase-lite-net
src/Couchbase.Lite.Support.UWP/Support/Reachability.cs
src/Couchbase.Lite.Support.UWP/Support/Reachability.cs
// // Reachability.cs // // Copyright (c) 2017 Couchbase, Inc 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. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Threading.Tasks; using Couchbase.Lite.DI; using Couchbase.Lite.Sync; using Windows.Networking.Connectivity; namespace Couchbase.Lite.Support { [CouchbaseDependency(Transient = true)] internal sealed class Reachability : IReachability { #region Variables public event EventHandler<NetworkReachabilityChangeEventArgs> StatusChanged; #endregion #region Properties public Uri Url { get; set; } #endregion #region Private Methods private void OnNetworkStatusChanged(object sender) { var connection = NetworkInformation.GetInternetConnectionProfile(); var status = connection == null ? NetworkReachabilityStatus.Unreachable : NetworkReachabilityStatus.Reachable; Task.Factory.StartNew(() => { StatusChanged?.Invoke(this, new NetworkReachabilityChangeEventArgs(status)); }); } #endregion #region IReachability public void Start() { NetworkInformation.NetworkStatusChanged += OnNetworkStatusChanged; } public void Stop() { NetworkInformation.NetworkStatusChanged -= OnNetworkStatusChanged; } #endregion } }
// // Reachability.cs // // Copyright (c) 2017 Couchbase, Inc 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. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Threading.Tasks; using Couchbase.Lite.DI; using Couchbase.Lite.Sync; using Windows.Networking.Connectivity; namespace Couchbase.Lite.Support { [CouchbaseDependency(Transient = true)] internal sealed class Reachability : IReachability { #region Variables public event EventHandler<NetworkReachabilityChangeEventArgs> StatusChanged; #endregion #region Private Methods private void OnNetworkStatusChanged(object sender) { var connection = NetworkInformation.GetInternetConnectionProfile(); var status = connection == null ? NetworkReachabilityStatus.Unreachable : NetworkReachabilityStatus.Reachable; Task.Factory.StartNew(() => { StatusChanged?.Invoke(this, new NetworkReachabilityChangeEventArgs(status)); }); } #endregion #region IReachability public void Start() { NetworkInformation.NetworkStatusChanged += OnNetworkStatusChanged; } public void Stop() { NetworkInformation.NetworkStatusChanged -= OnNetworkStatusChanged; } #endregion } }
apache-2.0
C#
bdd2a7be0fcf339971ddbe16706e7cd44caf9cc2
Fix for #338 - StackOverflowException in AppiumOptions.ToDictionary() (#346)
appium/appium-dotnet-driver
src/Appium.Net/Appium/AppiumCapabilities.cs
src/Appium.Net/Appium/AppiumCapabilities.cs
using System.Collections.Generic; using System.Reflection; using OpenQA.Selenium.Remote; namespace OpenQA.Selenium.Appium { /// <summary> /// Appium capabilities /// </summary> public class AppiumCapabilities : DesiredCapabilities { /// <summary> /// Get the capabilities back as a dictionary /// /// This method uses Reflection and should be removed once /// AppiumOptions class is avalaible for each driver /// </summary> /// <returns></returns> public Dictionary<string, object> ToDictionary() { var bindingFlags = BindingFlags.Instance | BindingFlags.NonPublic; FieldInfo capsField = typeof(DesiredCapabilities) .GetField("capabilities", bindingFlags); return capsField?.GetValue(this) as Dictionary<string, object>; } } }
using OpenQA.Selenium.Remote; using System; using System.Collections.Generic; namespace OpenQA.Selenium.Appium { /// <summary> /// Appium capabilities /// </summary> public class AppiumCapabilities : DesiredCapabilities { /// <summary> /// Get the capabilities back as a dictionary /// </summary> /// <returns></returns> public Dictionary<string, object> ToDictionary() { return this.ToDictionary(); } } }
apache-2.0
C#
a721074827c1ef179ea77bece64539fb375ddf4e
Add IsBroadcaster property to ChatStatus
damagefilter/damagebot4twitch
DamageLib/Users/ChatStatus.cs
DamageLib/Users/ChatStatus.cs
namespace DamageBot.Users { /// <summary> /// Contains information about the last messages chat status. /// Since it is sent through twitch on every message it would appear /// to make no sense to store it anywhere. /// Also, while you CAN change the values here it's actually read-only. /// This will be renewed on ever message. /// </summary> public struct ChatStatus { /// <summary> /// Who is the guy? /// A viewer, a moderator or the broadcaster himself? /// </summary> public Elevation UserElevation { get; set; } /// <summary> /// Is this person a subscriber? /// </summary> public bool IsSubscriber { get; set; } /// <summary> /// Is this the channel operator (broadcaster)? /// </summary> public bool IsBroadcaster => this.UserElevation == Elevation.Broadcaster; public string Channel { get; set; } public ChatStatus(Elevation el, string channel, bool isSub) { this.UserElevation = el; this.IsSubscriber = isSub; this.Channel = channel; } } }
namespace DamageBot.Users { /// <summary> /// Contains information about the last messages chat status. /// Since it is sent through twitch on every message it would appear /// to make no sense to store it anywhere. /// </summary> public struct ChatStatus { /// <summary> /// Who is the guy? /// A viewer, a moderator or the broadcaster himself? /// </summary> public Elevation UserElevation { get; set; } /// <summary> /// Is this person a subscriber? /// </summary> public bool IsSubscriber { get; set; } public string Channel { get; set; } public ChatStatus(Elevation el, string channel, bool isSub) { this.UserElevation = el; this.IsSubscriber = isSub; this.Channel = channel; } } }
mit
C#
81361593ac5e8a2a9bdd8769d817dc91c6c5455e
Fix feed url for @ghuntley (#358)
planetxamarin/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin
src/Firehose.Web/Authors/GeoffreyHuntley.cs
src/Firehose.Web/Authors/GeoffreyHuntley.cs
using System; using System.Collections.Generic; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class GeoffreyHuntley : IAmAMicrosoftMVP, IAmAXamarinMVP { public string FirstName => "Geoffrey"; public string LastName => "Huntley"; public string ShortBioOrTagLine => "has been involved in the Xamarin community since the early ​monotouch/monodroid days"; public string StateOrRegion => "Sydney, Australia"; public string EmailAddress => "ghuntley@ghuntley.com"; public string TwitterHandle => "geoffreyhuntley"; public Uri WebSite => new Uri("https://ghuntley.com/"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://ghuntley.com/feed.atom"); } } public string GravatarHash => ""; public string GitHubHandle => "ghuntley"; public GeoPosition Position => new GeoPosition(-33.8641859, 151.2143821); } }
using System; using System.Collections.Generic; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class GeoffreyHuntley : IAmAMicrosoftMVP, IAmAXamarinMVP { public string FirstName => "Geoffrey"; public string LastName => "Huntley"; public string ShortBioOrTagLine => "has been involved in the Xamarin community since the early ​monotouch/monodroid days"; public string StateOrRegion => "Sydney, Australia"; public string EmailAddress => "ghuntley@ghuntley.com"; public string TwitterHandle => "geoffreyhuntley"; public Uri WebSite => new Uri("https://ghuntley.com/"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://ghuntley.com/atom.xml"); } } public string GravatarHash => ""; public string GitHubHandle => "ghuntley"; public GeoPosition Position => new GeoPosition(-33.8641859, 151.2143821); } }
mit
C#
913d30885f3a079da6a617e9404b4ad0b7872864
Update MichaelMilitoni.cs
planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell
src/Firehose.Web/Authors/MichaelMilitoni.cs
src/Firehose.Web/Authors/MichaelMilitoni.cs
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using System.Web; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class MichaelMilitoni : IAmACommunityMember { public string FirstName => "Michael" public string LastName => "Militoni"; public string ShortBioOrTagLine => "An IT pro passionned and specialized in Virtualization"; public string StateOrRegion => "Brussles, Belgium"; public string EmailAddress => "mm@v-itpassion.be"; public string TwitterHandle => "MichaelMilitoni"; public string GitHubHandle => "itguru4u-be"; public string GravatarHash => ""; public GeoPosition Position => new GeoPosition(41.887212,-88.302487); public Uri WebSite => new Uri("https://www.v-itpassion.be"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://www.v-itpassion.be/category/Powershell/feed/"); } } public string FeedLanguageCode => "en"; } }
mit
C#
c1a7e8cac9b3d6ffd3028ffa20b2586b0a14cc5e
Fix Add Pos
vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf
src/backend/SO115App.Models/Servizi/CQRS/Commands/GestioneSoccorso/GestionePOS/InsertPos/AddPosCommandHandler.cs
src/backend/SO115App.Models/Servizi/CQRS/Commands/GestioneSoccorso/GestionePOS/InsertPos/AddPosCommandHandler.cs
//----------------------------------------------------------------------- // <copyright file="AddPosCommandHandler.cs" company="CNVVF"> // Copyright (C) 2017 - CNVVF // // This file is part of SOVVF. // SOVVF is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // SOVVF is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // </copyright> //----------------------------------------------------------------------- using CQRS.Commands; using Microsoft.Extensions.Configuration; using SO115App.Models.Servizi.Infrastruttura.GestionePOS; using System.IO; using System.Text; namespace SO115App.Models.Servizi.CQRS.Commands.GestioneSoccorso.GestionePOS.InsertPos { public class AddPosCommandHandler : ICommandHandler<AddPosCommand> { private readonly ISavePos _savePos; private readonly IConfiguration _config; public AddPosCommandHandler(ISavePos savePos, IConfiguration config) { _savePos = savePos; _config = config; } public void Handle(AddPosCommand command) { var PathFile = _config.GetSection("GenericSettings").GetSection("PathfilePOS").Value; var PathDirectory = PathFile + "\\" + command.Pos.CodSede; var PathCompleto = PathDirectory + "\\" + command.Pos.FDFile.FileName; //Creo una directory con il nome della sede qualora non esistesse if (!Directory.Exists(PathDirectory)) Directory.CreateDirectory(PathDirectory); using (var stream = File.Create(PathCompleto)) { command.Pos.FDFile.CopyTo(stream); } command.Pos.FilePath = PathCompleto; _savePos.Save(command.Pos); } } }
//----------------------------------------------------------------------- // <copyright file="AddPosCommandHandler.cs" company="CNVVF"> // Copyright (C) 2017 - CNVVF // // This file is part of SOVVF. // SOVVF is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // SOVVF is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // </copyright> //----------------------------------------------------------------------- using CQRS.Commands; using Microsoft.Extensions.Configuration; using SO115App.Models.Servizi.Infrastruttura.GestionePOS; using System.IO; using System.Text; namespace SO115App.Models.Servizi.CQRS.Commands.GestioneSoccorso.GestionePOS.InsertPos { public class AddPosCommandHandler : ICommandHandler<AddPosCommand> { private readonly ISavePos _savePos; private readonly IConfiguration _config; public AddPosCommandHandler(ISavePos savePos, IConfiguration config) { _savePos = savePos; _config = config; } public void Handle(AddPosCommand command) { var PathFile = _config.GetSection("GenericSettings").GetSection("PathfilePOS").Value; var PathDirectory = PathFile + "\\" + command.Pos.CodSede; var PathCompleto = PathDirectory + "\\" + command.Pos.FDFile.FileName; //Creo una directory con il nome della sede qualora non esistesse if (!Directory.Exists(PathDirectory)) Directory.CreateDirectory(PathDirectory); if (command.Pos.FDFile.Length > 0) { var filePath = Path.GetTempFileName(); using (var stream = File.Create(PathCompleto)) { command.Pos.FDFile.CopyTo(stream); } } command.Pos.FilePath = PathCompleto; _savePos.Save(command.Pos); } } }
agpl-3.0
C#
2a94d1b85e6e1f4a62be731d7bace5833fd62813
Fix TeamCity shortcoming: when a branch is called "develop" or "master", it is considered a default branch. Possible future improvement: make this configurable per view and per tile.
amoerie/teamcity-theatre,amoerie/teamcity-theatre,amoerie/teamcity-theatre,amoerie/teamcity-theatre,amoerie/teamcity-theatre
src/TeamCityTheatre.Core/Client/Mappers/BuildMapper.cs
src/TeamCityTheatre.Core/Client/Mappers/BuildMapper.cs
using System; using System.Collections.Generic; using System.Linq; using TeamCityTheatre.Core.Client.Responses; using TeamCityTheatre.Core.Models; namespace TeamCityTheatre.Core.Client.Mappers { public class BuildMapper : IBuildMapper { readonly IAgentMapper _agentMapper; readonly IBuildStatusMapper _buildStatusMapper; readonly IBuildChangeMapper _buildChangeMapper; readonly IBuildConfigurationMapper _buildConfigurationMapper; readonly IPropertyMapper _propertyMapper; public BuildMapper( IBuildConfigurationMapper buildConfigurationMapper, IBuildChangeMapper buildChangeMapper, IPropertyMapper propertyMapper, IAgentMapper agentMapper, IBuildStatusMapper buildStatusMapper) { _buildConfigurationMapper = buildConfigurationMapper ?? throw new ArgumentNullException(nameof(buildConfigurationMapper)); _buildChangeMapper = buildChangeMapper ?? throw new ArgumentNullException(nameof(buildChangeMapper)); _propertyMapper = propertyMapper ?? throw new ArgumentNullException(nameof(propertyMapper)); _agentMapper = agentMapper ?? throw new ArgumentNullException(nameof(agentMapper)); _buildStatusMapper = buildStatusMapper ?? throw new ArgumentNullException(nameof(buildStatusMapper)); } public Build Map(BuildResponse build) { if (build == null) return null; return new Build { Id = build.Id, BuildConfigurationId = build.BuildTypeId, Agent = _agentMapper.Map(build.Agent), ArtifactDependencies = Map(build.ArtifactDependencies), BranchName = build.BranchName, BuildConfiguration = _buildConfigurationMapper.Map(build.BuildType), FinishDate = build.FinishDate, Href = build.Href, IsDefaultBranch = build.DefaultBranch || string.Equals(build.BranchName, "develop") || string.Equals(build.BranchName, "master"), LastChanges = _buildChangeMapper.Map(build.LastChanges), Number = build.Number, PercentageComplete = build.PercentageComplete ?? build.RunningInfo?.PercentageComplete, ElapsedSeconds = build.RunningInfo?.ElapsedSeconds, EstimatedTotalSeconds = build.RunningInfo?.EstimatedTotalSeconds, CurrentStageText = build.RunningInfo?.CurrentStageText, Properties = _propertyMapper.Map(build.Properties), QueuedDate = build.QueuedDate, SnapshotDependencies = Map(build.SnapshotDependencies), StartDate = build.StartDate, State = build.State, Status = _buildStatusMapper.Map(build.Status), StatusText = build.StatusText, WebUrl = build.WebUrl }; } public IReadOnlyCollection<Build> Map(BuildsResponse builds) { if (builds?.Build == null) return new List<Build>(); return builds.Build.Select(Map).ToList(); } } }
using System; using System.Collections.Generic; using System.Linq; using TeamCityTheatre.Core.Client.Responses; using TeamCityTheatre.Core.Models; namespace TeamCityTheatre.Core.Client.Mappers { public class BuildMapper : IBuildMapper { readonly IAgentMapper _agentMapper; readonly IBuildStatusMapper _buildStatusMapper; readonly IBuildChangeMapper _buildChangeMapper; readonly IBuildConfigurationMapper _buildConfigurationMapper; readonly IPropertyMapper _propertyMapper; public BuildMapper( IBuildConfigurationMapper buildConfigurationMapper, IBuildChangeMapper buildChangeMapper, IPropertyMapper propertyMapper, IAgentMapper agentMapper, IBuildStatusMapper buildStatusMapper) { _buildConfigurationMapper = buildConfigurationMapper ?? throw new ArgumentNullException(nameof(buildConfigurationMapper)); _buildChangeMapper = buildChangeMapper ?? throw new ArgumentNullException(nameof(buildChangeMapper)); _propertyMapper = propertyMapper ?? throw new ArgumentNullException(nameof(propertyMapper)); _agentMapper = agentMapper ?? throw new ArgumentNullException(nameof(agentMapper)); _buildStatusMapper = buildStatusMapper ?? throw new ArgumentNullException(nameof(buildStatusMapper)); } public Build Map(BuildResponse build) { if (build == null) return null; return new Build { Id = build.Id, BuildConfigurationId = build.BuildTypeId, Agent = _agentMapper.Map(build.Agent), ArtifactDependencies = Map(build.ArtifactDependencies), BranchName = build.BranchName, BuildConfiguration = _buildConfigurationMapper.Map(build.BuildType), FinishDate = build.FinishDate, Href = build.Href, IsDefaultBranch = build.DefaultBranch, LastChanges = _buildChangeMapper.Map(build.LastChanges), Number = build.Number, PercentageComplete = build.PercentageComplete ?? build.RunningInfo?.PercentageComplete, ElapsedSeconds = build.RunningInfo?.ElapsedSeconds, EstimatedTotalSeconds = build.RunningInfo?.EstimatedTotalSeconds, CurrentStageText = build.RunningInfo?.CurrentStageText, Properties = _propertyMapper.Map(build.Properties), QueuedDate = build.QueuedDate, SnapshotDependencies = Map(build.SnapshotDependencies), StartDate = build.StartDate, State = build.State, Status = _buildStatusMapper.Map(build.Status), StatusText = build.StatusText, WebUrl = build.WebUrl }; } public IReadOnlyCollection<Build> Map(BuildsResponse builds) { if (builds?.Build == null) return new List<Build>(); return builds.Build.Select(Map).ToList(); } } }
mit
C#
2e866ce0fed74b9936aae44b51ad21fca7a9fe15
Implement SynchronousIOManager.GetFiles
Cyberboss/tgstation-server,tgstation/tgstation-server,tgstation/tgstation-server-tools,tgstation/tgstation-server,Cyberboss/tgstation-server
src/Tgstation.Server.Host/Core/SynchronousIOManager.cs
src/Tgstation.Server.Host/Core/SynchronousIOManager.cs
using System; using System.Collections.Generic; using System.IO; using System.Threading; namespace Tgstation.Server.Host.Core { /// <inheritdoc /> sealed class SynchronousIOManager : ISynchronousIOManager { /// <inheritdoc /> public IEnumerable<string> GetDirectories(string path, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); foreach (var I in Directory.EnumerateDirectories(path)) { yield return I; cancellationToken.ThrowIfCancellationRequested(); } } /// <inheritdoc /> public IEnumerable<string> GetFiles(string path, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); foreach (var I in Directory.EnumerateFiles(path)) { yield return I; cancellationToken.ThrowIfCancellationRequested(); } } /// <inheritdoc /> public byte[] ReadFile(string path, CancellationToken cancellationToken) { throw new NotImplementedException(); } /// <inheritdoc /> public bool WriteFileChecked(string path, byte[] data, string previousSha1, CancellationToken cancellationToken) { throw new NotImplementedException(); } } }
using System; using System.Collections.Generic; using System.IO; using System.Threading; namespace Tgstation.Server.Host.Core { /// <inheritdoc /> sealed class SynchronousIOManager : ISynchronousIOManager { /// <inheritdoc /> public IEnumerable<string> GetDirectories(string path, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); foreach (var I in Directory.EnumerateDirectories(path)) { yield return I; cancellationToken.ThrowIfCancellationRequested(); } } /// <inheritdoc /> public IEnumerable<string> GetFiles(string path, CancellationToken cancellationToken) { throw new NotImplementedException(); } /// <inheritdoc /> public byte[] ReadFile(string path, CancellationToken cancellationToken) { throw new NotImplementedException(); } /// <inheritdoc /> public bool WriteFileChecked(string path, byte[] data, string previousSha1, CancellationToken cancellationToken) { throw new NotImplementedException(); } } }
agpl-3.0
C#
826be4f70c8cdb94b90d16cfa9552fc19275c94c
Apply PR #69 from andreabalducci that was sent to WebAPIContrib.
WebApiContrib/WebApiContrib.IoC.CastleWindsor,modulexcite/WebApiContrib.IoC.CastleWindsor,kalyanraman/WebApiContrib.IoC.CastleWindsor,WebApiContrib/WebApiContrib.IoC.CastleWindsor
src/WebApiContrib.IoC.CastleWindsor/WindsorResolver.cs
src/WebApiContrib.IoC.CastleWindsor/WindsorResolver.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web.Http.Dependencies; using Castle.Windsor; namespace WebApiContrib.IoC.CastleWindsor { public class WindsorDependencyScope : IDependencyScope { private IWindsorContainer container; public WindsorDependencyScope(IWindsorContainer container) { if (container == null) throw new ArgumentNullException("container"); this.container = container; } public object GetService(Type serviceType) { if (container == null) throw new ObjectDisposedException("this", "This scope has already been disposed."); if (!container.Kernel.HasComponent(serviceType)) return null; return container.Resolve(serviceType); } public IEnumerable<object> GetServices(Type serviceType) { if (container == null) throw new ObjectDisposedException("this", "This scope has already been disposed."); if (!container.Kernel.HasComponent(serviceType)) return Enumerable.Empty<object>(); return container.ResolveAll(serviceType).Cast<object>(); } public void Dispose() { container.Dispose(); container = null; } } public class WindsorResolver : WindsorDependencyScope, IDependencyResolver { private readonly IWindsorContainer container; public WindsorResolver(IWindsorContainer container) : base(container) { if (container == null) throw new ArgumentNullException("container"); this.container = container; } public IDependencyScope BeginScope() { var scope = new WindsorContainer(); container.AddChildContainer(scope); return new WindsorDependencyScope(scope); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web.Http.Dependencies; using Castle.Windsor; namespace WebApiContrib.IoC.CastleWindsor { public class WindsorDependencyScope : IDependencyScope { private IWindsorContainer container; public WindsorDependencyScope(IWindsorContainer container) { if (container == null) throw new ArgumentNullException("container"); this.container = container; } public object GetService(Type serviceType) { if (container == null) throw new ObjectDisposedException("this", "This scope has already been disposed."); if (!container.Kernel.HasComponent(serviceType)) return null; return container.Resolve(serviceType); } public IEnumerable<object> GetServices(Type serviceType) { if (container == null) throw new ObjectDisposedException("this", "This scope has already been disposed."); if (!container.Kernel.HasComponent(serviceType)) return Enumerable.Empty<object>(); return container.ResolveAll(serviceType).Cast<object>(); } public void Dispose() { container.Dispose(); container = null; } } public class WindsorResolver : WindsorDependencyScope, IDependencyResolver { private readonly IWindsorContainer container; public WindsorResolver(IWindsorContainer container) : base(container) { if (container == null) throw new ArgumentNullException("container"); this.container = container; } public IDependencyScope BeginScope() { var scope = new WindsorContainer(); container.AddChildContainer(container); return new WindsorDependencyScope(scope); } } }
mit
C#
96d41d9027eaa3f0460a69ddc9de6161256f83aa
Change description of assembly
paralleltree/Scallion.Tools
vmdscale/Properties/AssemblyInfo.cs
vmdscale/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("vmdscale")] [assembly: AssemblyDescription("scale a vmd file and write to a file")] [assembly: AssemblyCompany("paltee.net")] [assembly: AssemblyProduct("vmdscale")] [assembly: AssemblyCopyright("Copyright (C) 2016 Paralleltree")] [assembly: ComVisible(false)] [assembly: Guid("9572f9f5-0b78-4f34-b664-b62306fed607")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("vmdscale")] [assembly: AssemblyDescription("scale vmd files and output to a file")] [assembly: AssemblyCompany("paltee.net")] [assembly: AssemblyProduct("vmdscale")] [assembly: AssemblyCopyright("Copyright (C) 2016 Paralleltree")] [assembly: ComVisible(false)] [assembly: Guid("9572f9f5-0b78-4f34-b664-b62306fed607")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")]
mit
C#
500be44ffa3a899593fde0d5d665b55aa71fe5c1
Move config
DarkIrata/WinCommandPalette
WinCommandPalette/App.xaml.cs
WinCommandPalette/App.xaml.cs
using System; using System.Diagnostics; using System.IO; using System.Windows; using WinCommandPalette.Helper; using WinCommandPalette.PluginSystem; using WinCommandPalette.Views; namespace WinCommandPalette { /// <summary> /// Interaktionslogik für "App.xaml" /// </summary> public partial class App : Application { private const string CONFIG_FILE_NAME = "config.xml"; private readonly string configDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "IrataProjects", "WinCommandPalette"); private readonly string configFilePath; private Config config; public App() { #if DEBUG this.configFilePath = Path.Combine(this.configDir, "debug", CONFIG_FILE_NAME); #else this.configFilePath = Path.Combine(this.configDir, CONFIG_FILE_NAME); #endif if (Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName).Length > 1) { MessageBox.Show("An instance of WinCommand Palette is already running.", "WinCommand Palette", MessageBoxButton.OK, MessageBoxImage.Information); Current.Shutdown(1); } Directory.CreateDirectory(this.configDir); PluginHelper.Load(); this.config = new Config(); // This will be removed later if (File.Exists(CONFIG_FILE_NAME)) { File.Move(CONFIG_FILE_NAME, this.configFilePath); } if (File.Exists(this.configFilePath)) { this.config = Config.Load(this.configFilePath); } else { new OptionsView(this.config).Show(); } } private void Application_Startup(object sender, StartupEventArgs e) { var mainWindow = new MainWindow(this.config); mainWindow.Show(); } protected override void OnExit(ExitEventArgs e) { this.config.Save("config.xml"); Win32Helper.UnregisterHotKey(); base.OnExit(e); } } }
using System.Diagnostics; using System.IO; using System.Windows; using WinCommandPalette.Helper; using WinCommandPalette.PluginSystem; using WinCommandPalette.Views; namespace WinCommandPalette { /// <summary> /// Interaktionslogik für "App.xaml" /// </summary> public partial class App : Application { private Config config; public App() { if (Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName).Length > 1) { MessageBox.Show("An instance of WinCommand Palette is already running.", "WinCommand Palette", MessageBoxButton.OK, MessageBoxImage.Information); Current.Shutdown(1); } PluginHelper.Load(); this.config = new Config(); if (File.Exists("config.xml")) { this.config = Config.Load("config.xml"); } else { new OptionsView(this.config).Show(); } } private void Application_Startup(object sender, StartupEventArgs e) { var mainWindow = new MainWindow(this.config); mainWindow.Show(); } protected override void OnExit(ExitEventArgs e) { this.config.Save("config.xml"); Win32Helper.UnregisterHotKey(); base.OnExit(e); } } }
mit
C#
5058b55784582041a1a13070408724e440bdea4b
Change in comment oonly.
bar-and-c/bubbles
GameObjectTemplateSelector.cs
GameObjectTemplateSelector.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; namespace Bubbles { public class GameObjectTemplateSelector : DataTemplateSelector { // TODO: Add/remove DataTemplate properties as applicable. public DataTemplate OtherTemplate { get; set; } public DataTemplate BubbleTemplate { get; set; } protected override DataTemplate SelectTemplateCore(object item, DependencyObject container) { if (item is GameObject) { // TODO: Later on, there might be more GameObject classes than Bubble, something like Obstacle, and possibly other... //GameObject gameObject = (GameObject)item; DataTemplate dt = item is Bubble ? this.BubbleTemplate : this.OtherTemplate; return dt; } return base.SelectTemplate(item, container); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; namespace Bubbles { public class GameObjectTemplateSelector : DataTemplateSelector { // TODO: Change these names! Add/remove DataTemplate properties as applicable. public DataTemplate OtherTemplate { get; set; } public DataTemplate BubbleTemplate { get; set; } protected override DataTemplate SelectTemplateCore(object item, DependencyObject container) { if (item is GameObject) { // TODO: Later on, there will be a more GameObject classes than Bubble, something like Obstacle, and possibly other... //GameObject gameObject = (GameObject)item; DataTemplate dt = item is Bubble ? this.BubbleTemplate : this.OtherTemplate; return dt; } return base.SelectTemplate(item, container); } } }
mit
C#
391057ba2847f8ebf39f1dd348ccf20ad5dcdfa1
Comment updated
alvivar/Hasten
Gigas/EntitySet.cs
Gigas/EntitySet.cs
// This file is auto-generated. Modifications won't be saved, be cool. // EntitySet is a static database of GameObjects (Entities) and MonoBehaviour // classes (Components). Check out 'Femto.cs' for more information about the // code generated. // Refresh with the menu item 'Tools/Gigas/Generate EntitySet.cs' public static class EntitySet { }
// This file is auto-generated. Modifications won't be saved, be cool. // EntitySet is a static database of MonoBehaviour classes that are considered a // Entity, classes with '// !Gigas' somewhere in their file. // Refresh with the menu item 'Tools/Gigas/Generate EntitySet.cs' public static class EntitySet { }
mit
C#
54a1aa921fafa23ac2750027ce83e11184eaf3ba
Remove useless method.
ZooPin/CK-Glouton,ZooPin/CK-Glouton,ZooPin/CK-Glouton,ZooPin/CK-Glouton
src/CK.Glouton.Lucene/LuceneConstant.cs
src/CK.Glouton.Lucene/LuceneConstant.cs
using System; using System.IO; namespace CK.Glouton.Lucene { public class LuceneConstant { internal const int MaxSearch = 10; /// <summary> /// Test in the directory of the indexer. /// On windows in appdata, in other os in home. /// If he doesn't find anything create the directory. /// </summary> public static string GetPath() { string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Glouton", "Logs", "Default"); if (!Directory.Exists(path)) Directory.CreateDirectory(path); return path; } /// <summary> /// Test in the directory of the indexer. /// On windows in appdata, in other os in home. /// If he doesn't find anything create the directory. /// <param name="dirName">The name of the directory where the data will be indexed</param> /// </summary> public static string GetPath(string dirName) { string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Glouton", "Logs", dirName); if (!Directory.Exists(path)) Directory.CreateDirectory(path); return path; } } }
using System; using System.IO; namespace CK.Glouton.Lucene { public class LuceneConstant { internal const int MaxSearch = 10; /// <summary> /// Test in the directory of the indexer. /// On windows in appdata, in other os in home. /// If he doesn't find anything create the directory. /// </summary> public static string GetPath() { string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Glouton", "Logs", "Default"); if (!Directory.Exists(path)) Directory.CreateDirectory(path); return path; } /// <summary> /// Test in the directory of the indexer. /// On windows in appdata, in other os in home. /// If he doesn't find anything create the directory. /// <param name="dirName">The name of the directory where the data will be indexed</param> /// </summary> public static string GetPath(string dirName) { string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Glouton", "Logs", dirName); if (!Directory.Exists(path)) Directory.CreateDirectory(path); return path; } /// <summary> /// Test in the directory of the indexer. /// On windows in appdata, in other os in home. /// If he doesn't find anything create the directory. /// </summary> /// <param name="dirNames"> the string array that contain the AppName, the name of the machine executing the app and the app GUID </param> /// <returns></returns> public static string GetPath(string[] dirNames) { if (dirNames.Length > 3) throw new ArgumentException("The array is too big.", nameof(dirNames)); string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Glouton", "Logs", dirNames[0], dirNames[1], dirNames[2]); if (!Directory.Exists(path)) Directory.CreateDirectory(path); return path; } } }
mit
C#
6c5036207646662f723b7185dc8ad85c75d6c348
Add statusline logdebug exception
nopara73/DotNetTor
src/DotNetTor/Http/Models/StatusLine.cs
src/DotNetTor/Http/Models/StatusLine.cs
using System; using static DotNetTor.Http.Constants; using System.Net; using DotNetEssentials.Logging; namespace DotNetTor.Http.Models { public class StatusLine : StartLine { public HttpStatusCode StatusCode { get; private set; } public StatusLine(HttpProtocol protocol, HttpStatusCode status) { Protocol = protocol; StatusCode = status; StartLineString = Protocol.ToString() + SP + (int)StatusCode + SP + StatusCode.ToReasonString() + CRLF; } public static StatusLine CreateNew(string statusLineString) { try { var parts = GetParts(statusLineString); var protocolString = parts[0]; var codeString = parts[1]; var reason = parts[2]; var protocol = new HttpProtocol(protocolString); var code = int.Parse(codeString); if (!HttpStatusCodeHelper.IsValidCode(code)) { throw new NotSupportedException($"Invalid HTTP status code: {code}."); } var statusCode = (HttpStatusCode)code; // https://tools.ietf.org/html/rfc7230#section-3.1.2 // The reason-phrase element exists for the sole purpose of providing a // textual description associated with the numeric status code, mostly // out of deference to earlier Internet application protocols that were // more frequently used with interactive text clients.A client SHOULD // ignore the reason - phrase content. return new StatusLine(protocol, statusCode); } catch (Exception ex) { Logger.LogDebug<StatusLine>(ex); throw new NotSupportedException($"Invalid {nameof(StatusLine)}: {statusLineString}.", ex); } } } }
using System; using static DotNetTor.Http.Constants; using System.Net; namespace DotNetTor.Http.Models { public class StatusLine : StartLine { public HttpStatusCode StatusCode { get; private set; } public StatusLine(HttpProtocol protocol, HttpStatusCode status) { Protocol = protocol; StatusCode = status; StartLineString = Protocol.ToString() + SP + (int)StatusCode + SP + StatusCode.ToReasonString() + CRLF; } public static StatusLine CreateNew(string statusLineString) { try { var parts = GetParts(statusLineString); var protocolString = parts[0]; var codeString = parts[1]; var reason = parts[2]; var protocol = new HttpProtocol(protocolString); var code = int.Parse(codeString); if (!HttpStatusCodeHelper.IsValidCode(code)) { throw new NotSupportedException($"Invalid HTTP status code: {code}."); } var statusCode = (HttpStatusCode)code; // https://tools.ietf.org/html/rfc7230#section-3.1.2 // The reason-phrase element exists for the sole purpose of providing a // textual description associated with the numeric status code, mostly // out of deference to earlier Internet application protocols that were // more frequently used with interactive text clients.A client SHOULD // ignore the reason - phrase content. return new StatusLine(protocol, statusCode); } catch (Exception ex) { throw new NotSupportedException($"Invalid {nameof(StatusLine)}: {statusLineString}.", ex); } } } }
mit
C#
494d198df0494281d391fed24462e15cf0bb6d75
Test code
aidka011/apmathcloudaida
site/index.cshtml
site/index.cshtml
@{ var txt = "fdsjfl"; } <html> <body> <p>The dateTime is @txt</p> </body> </html>
@{ var txt = DateTime.Now; } <html> <body> <p>The dateTime is @txt</p> </body> </html>
mit
C#
4b7ab15a8ce4dd62d5b87c38a1df57e80aba3a65
remove required setter for IDomainObject.ID to allow for better Record type support
ahanusa/Peasy.NET,ahanusa/facile.net,peasy/Peasy.NET
src/Peasy/IDomainObject.cs
src/Peasy/IDomainObject.cs
namespace Peasy { /// <summary> /// A marker interface that represents a domain object or resource. /// </summary> public interface IDomainObject { } /// <summary> /// Represents a domain object or resource. /// </summary> /// <typeparam name="TKey">Represents an identifier for a domain object or resource and can be any type.</typeparam> public interface IDomainObject<TKey> : IDomainObject { /// <summary> /// Represents the identifier of a domain object or resource. /// </summary> TKey ID { get; } } }
namespace Peasy { /// <summary> /// A marker interface that represents a domain object or resource. /// </summary> public interface IDomainObject { } /// <summary> /// Represents a domain object or resource. /// </summary> /// <typeparam name="TKey">Represents an identifier for a domain object or resource and can be any type.</typeparam> public interface IDomainObject<TKey> : IDomainObject { /// <summary> /// Represents the identifier of a domain object or resource. /// </summary> TKey ID { get; set; } } }
mit
C#
17fe39607092d287b4489f3f13287ae66bdc310e
Add accumulated cost into SummaryData
nfleet/.net-sdk
NFleetSDK/Data/SummaryData.cs
NFleetSDK/Data/SummaryData.cs
 namespace NFleet.Data { public class SummaryData { public double TravelDistanceSum { get; set; } public double WorkingTimeSum { get; set; } public int TotalTaskCount { get; set; } public int PlannedTaskCount { get; set; } public int TotalVehicleCount { get; set; } public int UsedVehicleCount { get; set; } public double AccumulatedCost { get; set; } } }
 namespace NFleet.Data { public class SummaryData { public double TravelDistanceSum { get; set; } public double WorkingTimeSum { get; set; } public int TotalTaskCount { get; set; } public int PlannedTaskCount { get; set; } public int TotalVehicleCount { get; set; } public int UsedVehicleCount { get; set; } } }
mit
C#
39664ac0979780fef4f02357290066902b9adf37
test commit to master
bytePassion/OpenQuoridorFramework
OpenQuoridorFramework/OQF.PlayerVsBot.Visualization/ViewModels/BoardPlacement/BoardPlacementViewModelSampleData.cs
OpenQuoridorFramework/OQF.PlayerVsBot.Visualization/ViewModels/BoardPlacement/BoardPlacementViewModelSampleData.cs
using System.Collections.ObjectModel; using System.ComponentModel; using System.Windows.Input; using Lib.SemanicTypes; using OQF.Bot.Contracts.Coordination; using OQF.Bot.Contracts.GameElements; #pragma warning disable 0067 namespace OQF.PlayerVsBot.Visualization.ViewModels.BoardPlacement { internal class BoardPlacementViewModelSampleData : IBoardPlacementViewModel { public BoardPlacementViewModelSampleData() { var player = new Player(PlayerType.BottomPlayer); PossibleMoves = new ObservableCollection<PlayerState> { new PlayerState(player, new FieldCoordinate(XField.D, YField.One), 10), new PlayerState(player, new FieldCoordinate(XField.E, YField.Two), 10), new PlayerState(player, new FieldCoordinate(XField.F, YField.One), 10), }; PotentialPlacedWall = new ObservableCollection<Wall> { new Wall(new FieldCoordinate(XField.C, YField.Five), WallOrientation.Horizontal) }; BoardSize = new Size(new Width(300), new Height(300)); } public ICommand BoardClick => null; public ObservableCollection<PlayerState> PossibleMoves { get; } public ObservableCollection<Wall> PotentialPlacedWall { get; } public Point MousePosition { set {} } public Size BoardSize { get; set; } public void Dispose () { } public event PropertyChangedEventHandler PropertyChanged; } }
using System.Collections.ObjectModel; using System.ComponentModel; using System.Windows.Input; using Lib.SemanicTypes; using OQF.Bot.Contracts.Coordination; using OQF.Bot.Contracts.GameElements; #pragma warning disable 0067 namespace OQF.PlayerVsBot.Visualization.ViewModels.BoardPlacement { internal class BoardPlacementViewModelSampleData : IBoardPlacementViewModel { public BoardPlacementViewModelSampleData() { var player = new Player(PlayerType.BottomPlayer); PossibleMoves = new ObservableCollection<PlayerState> { new PlayerState(player, new FieldCoordinate(XField.D, YField.One), 10), new PlayerState(player, new FieldCoordinate(XField.E, YField.Two), 10), new PlayerState(player, new FieldCoordinate(XField.F, YField.One), 10), }; PotentialPlacedWall = new ObservableCollection<Wall> { new Wall(new FieldCoordinate(XField.C, YField.Five), WallOrientation.Horizontal) }; BoardSize = new Size(new Width(300), new Height(300)); } public ICommand BoardClick => null; public ObservableCollection<PlayerState> PossibleMoves { get; } public ObservableCollection<Wall> PotentialPlacedWall { get; } public Point MousePosition { set {} } public Size BoardSize { get; set; } public void Dispose () { } public event PropertyChangedEventHandler PropertyChanged; } }
apache-2.0
C#
07ab2ddcc0dec9a8d1870aea60aa444769593c91
save input manager
tim-hub/TiminesSweeper-3D-
Assets/_Scripts/InputManager.cs
Assets/_Scripts/InputManager.cs
using UnityEngine; using System.Collections; public class InputManager : MonoBehaviour { public GameObject ParentObject; public float Speed=3f; //move speed //fild of view public float MinFov=15f; public float MaxFov=90f; public float SensitivityFox=10f; private float fov; // Use this for initialization void Start () { fov = Camera.main.fieldOfView; } void LateUpdate() { // Does the main camera exist? if (Camera.main != null) { #if UNITY_ANDROID // Make sure the pinch scale is valid if (Lean.LeanTouch.PinchScale > 0.0f) { // Scale the FOV based on the pinch scale Camera.main.fieldOfView /= Lean.LeanTouch.PinchScale/1f; // Make sure the new FOV is within our min/max Camera.main.fieldOfView = Mathf.Clamp(Camera.main.fieldOfView, MinFov, MaxFov); } #else //use mouse wheel to control dield view fov+=Input.GetAxis("Mouse ScrollWheel")*SensitivityFox*-1; fov=Mathf.Clamp(fov,MinFov,MaxFov); Camera.main.fieldOfView=fov; #endif } // #if UNITY_ANDROID // // // // // // #else // // if (Input.GetMouseButton(1)){ // // Debug.Log("Right Mouse Button Rotate"); // // // ParentObject.transform.RotateAround(Vector3.zero,new Vector3(-Input.GetAxis("Mouse Y"), // -Input.GetAxis("Mouse X"),0f), // RotateSpeed); // // // } // #endif } }
using UnityEngine; using System.Collections; public class InputManager : MonoBehaviour { public GameObject ParentObject; public float Speed=3f; //move speed public float RotateSpeed=3f; //rotate speed public float SwipeThreshold=50f; //fild of view public float MinFov=15f; public float MaxFov=90f; public float SensitivityFox=10f; private float fov; void OnEnable() { // Hook into the OnSwipe event Lean.LeanTouch.OnFingerSwipe += OnFingerSwipe; } void OnDisable() { // Unhook into the OnSwipe event Lean.LeanTouch.OnFingerSwipe -= OnFingerSwipe; } // Use this for initialization void Start () { fov = Camera.main.fieldOfView; } void LateUpdate() { // Does the main camera exist? if (Camera.main != null) { #if UNITY_ANDROID // Make sure the pinch scale is valid if (Lean.LeanTouch.PinchScale > 0.0f) { // Scale the FOV based on the pinch scale Camera.main.fieldOfView /= Lean.LeanTouch.PinchScale/1f; // Make sure the new FOV is within our min/max Camera.main.fieldOfView = Mathf.Clamp(Camera.main.fieldOfView, MinFov, MaxFov); } #else //use mouse wheel to control dield view fov+=Input.GetAxis("Mouse ScrollWheel")*SensitivityFox*-1; fov=Mathf.Clamp(fov,MinFov,MaxFov); Camera.main.fieldOfView=fov; #endif } // #if UNITY_ANDROID // // // // // // #else // // if (Input.GetMouseButton(1)){ // // Debug.Log("Right Mouse Button Rotate"); // // // ParentObject.transform.RotateAround(Vector3.zero,new Vector3(-Input.GetAxis("Mouse Y"), // -Input.GetAxis("Mouse X"),0f), // RotateSpeed); // // // } // #endif } public void OnFingerSwipe(Lean.LeanFinger finger){ // Store the swipe delta in a temp variable var swipe = finger.SwipeDelta; if(swipe.magnitude>SwipeThreshold){ if (swipe.x < -Mathf.Abs(swipe.y)) { Debug.Log( "You swiped left!"); } if (swipe.x > Mathf.Abs(swipe.y)) { } if (swipe.y < -Mathf.Abs(swipe.x)) { } if (swipe.y > Mathf.Abs(swipe.x)) { } } } }
epl-1.0
C#
2b8ade5615560cad060d1c5a197c680bdf21f948
Support 404 url suggestions for /rooms/xyz in addition to /xyz.
timgranstrom/JabbR,e10/JabbR,JabbR/JabbR,borisyankov/JabbR,18098924759/JabbR,yadyn/JabbR,SonOfSam/JabbR,SonOfSam/JabbR,M-Zuber/JabbR,M-Zuber/JabbR,18098924759/JabbR,borisyankov/JabbR,ajayanandgit/JabbR,yadyn/JabbR,mzdv/JabbR,borisyankov/JabbR,timgranstrom/JabbR,mzdv/JabbR,e10/JabbR,JabbR/JabbR,ajayanandgit/JabbR,yadyn/JabbR
JabbR/Nancy/ErrorPageHandler.cs
JabbR/Nancy/ErrorPageHandler.cs
using System.Text.RegularExpressions; using JabbR.Services; using Nancy; using Nancy.ErrorHandling; using Nancy.ViewEngines; namespace JabbR.Nancy { public class ErrorPageHandler : DefaultViewRenderer, IStatusCodeHandler { private readonly IJabbrRepository _repository; public ErrorPageHandler(IViewFactory factory, IJabbrRepository repository) : base(factory) { _repository = repository; } public bool HandlesStatusCode(HttpStatusCode statusCode, NancyContext context) { // only handle 40x and 50x return (int)statusCode >= 400; } public void Handle(HttpStatusCode statusCode, NancyContext context) { string suggestRoomName = null; if (statusCode == HttpStatusCode.NotFound) { var match = Regex.Match(context.Request.Url.Path, "^/(rooms/)?(?<roomName>[^/]+)$", RegexOptions.IgnoreCase); if (match.Success) { var potentialRoomName = match.Groups["roomName"].Value; if (_repository.GetRoomByName(potentialRoomName) != null) { suggestRoomName = potentialRoomName; } } } var response = RenderView( context, "errorPage", new { Error = statusCode, ErrorCode = (int)statusCode, SuggestRoomName = suggestRoomName }); response.StatusCode = statusCode; context.Response = response; } } }
using System.Linq; using JabbR.Services; using Nancy; using Nancy.ErrorHandling; using Nancy.ViewEngines; namespace JabbR.Nancy { public class ErrorPageHandler : DefaultViewRenderer, IStatusCodeHandler { private readonly IJabbrRepository _repository; public ErrorPageHandler(IViewFactory factory, IJabbrRepository repository) : base(factory) { _repository = repository; } public bool HandlesStatusCode(HttpStatusCode statusCode, NancyContext context) { // only handle 40x and 50x return (int)statusCode >= 400; } public void Handle(HttpStatusCode statusCode, NancyContext context) { string suggestRoomName = null; if (statusCode == HttpStatusCode.NotFound && context.Request.Url.Path.Count(e => e == '/') == 1) { // trim / from start of path var potentialRoomName = context.Request.Url.Path.Substring(1); if (_repository.GetRoomByName(potentialRoomName) != null) { suggestRoomName = potentialRoomName; } } var response = RenderView( context, "errorPage", new { Error = statusCode, ErrorCode = (int)statusCode, SuggestRoomName = suggestRoomName }); response.StatusCode = statusCode; context.Response = response; } } }
mit
C#
9678bee214e1c004915dffffcb0045eafbfc9623
fix the argument type of Component.Inspect() extend method.
hecomi/uREPL
Assets/uREPL/Scripts/Core/Utility.cs
Assets/uREPL/Scripts/Core/Utility.cs
using UnityEngine; using System.Reflection; using System.Linq; namespace uREPL { static public class Utility { static public string GetPath(this Transform tform) { if (tform.parent == null) { return "/" + tform.name; } return tform.parent.GetPath() + "/" + tform.name; } static public GameObject[] GetAllGameObjects() { return GameObject.FindObjectsOfType<GameObject>(); } static public string[] GetAllGameObjectPaths() { return GetAllGameObjects().Select(go => go.transform.GetPath()).ToArray(); } static public void Inspect(this GameObject gameObject) { Inspector.Inspect(gameObject); } static public void Inspect<T>(this T component) where T : Component { Inspector.Inspect(component); } } }
using UnityEngine; using System.Reflection; using System.Linq; namespace uREPL { static public class Utility { static public string GetPath(this Transform tform) { if (tform.parent == null) { return "/" + tform.name; } return tform.parent.GetPath() + "/" + tform.name; } static public GameObject[] GetAllGameObjects() { return GameObject.FindObjectsOfType<GameObject>(); } static public string[] GetAllGameObjectPaths() { return GetAllGameObjects().Select(go => go.transform.GetPath()).ToArray(); } static public void Inspect(this GameObject gameObject) { Inspector.Inspect(gameObject); } static public void Inspect(this Component component) { Inspector.Inspect(component); } } }
mit
C#
1c898b398d29371fbab00ef17c9c550326592075
Update Index.cshtml
ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab
Anlab.Mvc/Views/Home/Index.cshtml
Anlab.Mvc/Views/Home/Index.cshtml
@{ ViewData["Title"] = "Home Page"; } <div class="col-8"> @*<h2 style="color: blue">PLEASE NOTE: The Analytical Lab will be closed on July 4th and 5th.</h2>*@ <p class="lead">The UC Davis Analytical Laboratory is a core support facility of the UC Davis College of Agriculture and Environmental Sciences.</p> <p>Analytical Laboratory clients are University of California academics, other educational institutions, government agencies, and research-based businesses. </p> <p>In addition to analytical services, the Laboratory provides project assistance in the areas of analytical, agricultural and environmental chemistry. The Laboratory has an educational role, providing training to students and researchers in the operation of a number of analytical methods and instruments.</p> <p>Please Note: Dirk Holstege has recently retired as Laboratory Director of the UC Davis Analytical Laboratory. We thank him for his nearly twenty years of service as Director of the Analytical Lab and his thirty-two years of service as a UC Davis employee. We wish him all the best in his retirement.<br/> <br/> Traci Francis, Laboratory Supervisor, is serving as Interim Director. </p> </div> <div class="col-4"> <address> <p>UC Davis Analytical Lab<br> University of California Davis, California <br> 95616-5270 <br> Phone: <span style="white-space: nowrap">(530) 752-0147</span> <br> Fax: <span style="white-space: nowrap">(530) 752-9892</span> <br> Email: <a href="mailto:anlab@ucdavis.edu">anlab@ucdavis.edu</a></p> </address> </div>
@{ ViewData["Title"] = "Home Page"; } <div class="col-8"> @*<h2 style="color: blue">PLEASE NOTE: The Analytical Lab will be closed on July 4th and 5th.</h2>*@ <p class="lead">The UC Davis Analytical Laboratory is a core support facility of the UC Davis College of Agriculture and Environmental Sciences.</p> <p>Analytical Laboratory clients are University of California academics, other educational institutions, government agencies, and research-based businesses. </p> <p>In addition to analytical services, the Laboratory provides project assistance in the areas of analytical, agricultural and environmental chemistry. The Laboratory has an educational role, providing training to students and researchers in the operation of a number of analytical methods and instruments.</p> <p>Please Note: Dirk Holstege has recently retired as Laboratory Director of the UC Davis Analytical Laboratory. We thank him for his nearly twenty years of service as Director of the Analytical Lab and his thirty-two years of service as a UC Davis employee. We wish him all the best in his retirement.<br/> <br/> Traci Fracis, Laboratory Supervisor, is serviing as Interim Director. </p> </div> <div class="col-4"> <address> <p>UC Davis Analytical Lab<br> University of California Davis, California <br> 95616-5270 <br> Phone: <span style="white-space: nowrap">(530) 752-0147</span> <br> Fax: <span style="white-space: nowrap">(530) 752-9892</span> <br> Email: <a href="mailto:anlab@ucdavis.edu">anlab@ucdavis.edu</a></p> </address> </div>
mit
C#
c2f4e0d1ccc39d68fd608f3f83f955c0b83a6aea
Update Index.cshtml
ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab
Anlab.Mvc/Views/Home/Index.cshtml
Anlab.Mvc/Views/Home/Index.cshtml
@{ ViewData["Title"] = "Home Page"; } <div class="col-8"> <div class="alert alert-info"> <button type="button" class="close" data-dismiss="alert">×</button> <h3>The lab is experiencing much longer turnarounds than normal. Most tests are subject to at least 10 weeks.</h3> <strong> We apologize for this inconvenience. We have expanded our staffing to address this issue. However, due to the rapid spread of Covid there may be absences which are unpredictable.</strong><br /><br /> Thank you for your understanding and patience.<br /> ~ Jan 19, 2022 </div> <div class="alert alert-info"> <button type="button" class="close" data-dismiss="alert">×</button> Update posted: Jan 3, 2022<br /><br /> <strong>Now offering</strong><br /><br /> Crude Fiber<br /> Crude Fat by Acid Hydrolysis<br /> </div> <p class="lead">The UC Davis Analytical Laboratory is a core support facility of the UC Davis College of Agriculture and Environmental Sciences.</p> <p>The laboratory is located in Hoagland Hall with a Sample Receiving area in nearby Hoagland Annex. </p> <p>The laboratory performs analyses on selected chemical constituents of soil, plant, water and waste water, and feed in support of agricultural and environmental research.</p> <p>For new clients, please note the drop-down menu under “Lab Information” which contains an “Order Completion Help” section to help guide you in creating a work order. Also helpful under the “Lab Information” drop-down menu is the “Methods of Analysis” section which provides brief descriptions of our current methods.</p> <p>Please feel free to contact the lab with any questions.</p> </div> <div class="col-4"> <address> <p>UC Davis Analytical Lab<br> University of California Davis, California <br> 95616-5270 <br> Phone: <span style="white-space: nowrap">(530) 752-0147</span> <br> Fax: <span style="white-space: nowrap">(530) 752-9892</span> <br> Email: <a href="mailto:anlab@ucdavis.edu">anlab@ucdavis.edu</a></p> <p>Receiving Hours: 8am - 5pm M - F, </br> except University holidays </br> Sample Receiving Area: Hoagland Annex, </br>Phone: 530-752-0266</p> </address> <p><a href="/media/pdf/UC-Davis-Analytical-Laboratory-Handout.pdf" target="_blank" title="Anlab Flyer"><div><img src="~/Images/AnlabFlyerThumb.png"/><br/>Lab Flyer</div> </a></p> </div>
@{ ViewData["Title"] = "Home Page"; } <div class="col-8"> <div class="alert alert-info"> <button type="button" class="close" data-dismiss="alert">×</button> <h3>The lab is experiencing much longer turnarounds than normal. Most tests are subject to at least 6 - 8 weeks.</h3> <strong> We apologize for this inconvenience. We have expanded our staffing to address this issue. However, due to the rapid spread of Covid there may be absences which are unpredictable.</strong><br /><br /> Thank you for your understanding and patience.<br /> ~ Jan 3, 2022 </div> <div class="alert alert-info"> <button type="button" class="close" data-dismiss="alert">×</button> Update posted: Jan 3, 2022<br /><br /> <strong>Now offering</strong><br /><br /> Crude Fiber<br /> Crude Fat by Acid Hydrolysis<br /> </div> <p class="lead">The UC Davis Analytical Laboratory is a core support facility of the UC Davis College of Agriculture and Environmental Sciences.</p> <p>The laboratory is located in Hoagland Hall with a Sample Receiving area in nearby Hoagland Annex. </p> <p>The laboratory performs analyses on selected chemical constituents of soil, plant, water and waste water, and feed in support of agricultural and environmental research.</p> <p>For new clients, please note the drop-down menu under “Lab Information” which contains an “Order Completion Help” section to help guide you in creating a work order. Also helpful under the “Lab Information” drop-down menu is the “Methods of Analysis” section which provides brief descriptions of our current methods.</p> <p>Please feel free to contact the lab with any questions.</p> </div> <div class="col-4"> <address> <p>UC Davis Analytical Lab<br> University of California Davis, California <br> 95616-5270 <br> Phone: <span style="white-space: nowrap">(530) 752-0147</span> <br> Fax: <span style="white-space: nowrap">(530) 752-9892</span> <br> Email: <a href="mailto:anlab@ucdavis.edu">anlab@ucdavis.edu</a></p> <p>Receiving Hours: 8am - 5pm M - F, </br> except University holidays </br> Sample Receiving Area: Hoagland Annex, </br>Phone: 530-752-0266</p> </address> <p><a href="/media/pdf/UC-Davis-Analytical-Laboratory-Handout.pdf" target="_blank" title="Anlab Flyer"><div><img src="~/Images/AnlabFlyerThumb.png"/><br/>Lab Flyer</div> </a></p> </div>
mit
C#
52126522dbf3ad96e1724b7d72a14101efb0d461
FIX IsPalindrome() to not accept whitespace input
martinlindhe/Punku
punku/Extensions/StringExtensions.cs
punku/Extensions/StringExtensions.cs
using System; using System.Text; using Punku; public static class StringExtensions { /** * repeat the string count times */ public static string Repeat (this string input, int count) { var builder = new StringBuilder ((input == null ? 0 : input.Length) * count); for (int i = 0; i < count; i++) builder.Append (input); return builder.ToString (); } /** * return the number of times letter occurs */ public static int Count (this string input, char letter) { int count = 0; foreach (char c in input) if (c == letter) count++; return count; } /** * true if string only contains 0-9 */ public static bool IsNumbersOnly (this string input) { if (input == "") return false; foreach (char c in input) if (c < '0' || c > '9') return false; return true; } /** * true if string only contains 0-9, a-z or A-Z */ public static bool IsAlphanumeric (this string input) { if (input == "") return false; foreach (char c in input) if ((c < '0' || c > '9') && (c < 'a' || c > 'z') && (c < 'A' || c > 'Z')) return false; return true; } /** * true if string is a palindrome, like "racecar" */ public static bool IsPalindrome (this string input) { if (input.Trim ().Length < 1) return false; char[] a1 = input.ToCharArray (); char[] a2 = input.ToCharArray (); Array.Reverse (a2); for (int i = 0; i < a1.Length; i++) if (a1 [i] != a2 [i]) return false; return true; } }
using System; using System.Text; using Punku; public static class StringExtensions { /** * repeat the string count times */ public static string Repeat (this string input, int count) { var builder = new StringBuilder ((input == null ? 0 : input.Length) * count); for (int i = 0; i < count; i++) builder.Append (input); return builder.ToString (); } /** * return the number of times letter occurs */ public static int Count (this string input, char letter) { int count = 0; foreach (char c in input) if (c == letter) count++; return count; } /** * true if string only contains 0-9 */ public static bool IsNumbersOnly (this string input) { if (input == "") return false; foreach (char c in input) if (c < '0' || c > '9') return false; return true; } /** * true if string only contains 0-9, a-z or A-Z */ public static bool IsAlphanumeric (this string input) { if (input == "") return false; foreach (char c in input) if ((c < '0' || c > '9') && (c < 'a' || c > 'z') && (c < 'A' || c > 'Z')) return false; return true; } /** * true if string is a palindrome, like "racecar" */ public static bool IsPalindrome (this string input) { if (input.Length < 1) return false; char[] a1 = input.ToCharArray (); char[] a2 = input.ToCharArray (); Array.Reverse (a2); for (int i = 0; i < a1.Length; i++) if (a1 [i] != a2 [i]) return false; return true; } }
mit
C#
8029dc421d1e04725b4f9b229b9c1e8c16c5500b
Fix typo on CultureView-de-De in Localization Demo
jmptrader/Nancy,VQComms/Nancy,anton-gogolev/Nancy,damianh/Nancy,sloncho/Nancy,danbarua/Nancy,AlexPuiu/Nancy,nicklv/Nancy,jeff-pang/Nancy,grumpydev/Nancy,ccellar/Nancy,malikdiarra/Nancy,joebuschmann/Nancy,sloncho/Nancy,murador/Nancy,EIrwin/Nancy,hitesh97/Nancy,sadiqhirani/Nancy,phillip-haydon/Nancy,rudygt/Nancy,EliotJones/NancyTest,jonathanfoster/Nancy,adamhathcock/Nancy,jchannon/Nancy,VQComms/Nancy,horsdal/Nancy,charleypeng/Nancy,tparnell8/Nancy,AcklenAvenue/Nancy,xt0rted/Nancy,davidallyoung/Nancy,sadiqhirani/Nancy,fly19890211/Nancy,SaveTrees/Nancy,damianh/Nancy,cgourlay/Nancy,jchannon/Nancy,duszekmestre/Nancy,felipeleusin/Nancy,sloncho/Nancy,thecodejunkie/Nancy,jchannon/Nancy,jongleur1983/Nancy,fly19890211/Nancy,phillip-haydon/Nancy,guodf/Nancy,jchannon/Nancy,nicklv/Nancy,vladlopes/Nancy,lijunle/Nancy,Novakov/Nancy,EliotJones/NancyTest,daniellor/Nancy,nicklv/Nancy,phillip-haydon/Nancy,danbarua/Nancy,grumpydev/Nancy,khellang/Nancy,rudygt/Nancy,duszekmestre/Nancy,MetSystem/Nancy,Novakov/Nancy,MetSystem/Nancy,AIexandr/Nancy,charleypeng/Nancy,JoeStead/Nancy,asbjornu/Nancy,wtilton/Nancy,jmptrader/Nancy,xt0rted/Nancy,asbjornu/Nancy,SaveTrees/Nancy,albertjan/Nancy,joebuschmann/Nancy,ccellar/Nancy,tareq-s/Nancy,khellang/Nancy,adamhathcock/Nancy,davidallyoung/Nancy,duszekmestre/Nancy,charleypeng/Nancy,tareq-s/Nancy,joebuschmann/Nancy,AcklenAvenue/Nancy,NancyFx/Nancy,sroylance/Nancy,thecodejunkie/Nancy,phillip-haydon/Nancy,hitesh97/Nancy,vladlopes/Nancy,jeff-pang/Nancy,EliotJones/NancyTest,VQComms/Nancy,NancyFx/Nancy,albertjan/Nancy,thecodejunkie/Nancy,dbolkensteyn/Nancy,jmptrader/Nancy,thecodejunkie/Nancy,hitesh97/Nancy,JoeStead/Nancy,dbolkensteyn/Nancy,jonathanfoster/Nancy,NancyFx/Nancy,AIexandr/Nancy,sroylance/Nancy,joebuschmann/Nancy,MetSystem/Nancy,jchannon/Nancy,wtilton/Nancy,felipeleusin/Nancy,vladlopes/Nancy,Worthaboutapig/Nancy,tsdl2013/Nancy,horsdal/Nancy,dbabox/Nancy,khellang/Nancy,tareq-s/Nancy,blairconrad/Nancy,anton-gogolev/Nancy,xt0rted/Nancy,jongleur1983/Nancy,vladlopes/Nancy,JoeStead/Nancy,AlexPuiu/Nancy,ayoung/Nancy,jongleur1983/Nancy,khellang/Nancy,fly19890211/Nancy,tparnell8/Nancy,EliotJones/NancyTest,davidallyoung/Nancy,tparnell8/Nancy,albertjan/Nancy,jmptrader/Nancy,wtilton/Nancy,daniellor/Nancy,ccellar/Nancy,jonathanfoster/Nancy,dbolkensteyn/Nancy,tsdl2013/Nancy,anton-gogolev/Nancy,adamhathcock/Nancy,Worthaboutapig/Nancy,hitesh97/Nancy,cgourlay/Nancy,malikdiarra/Nancy,nicklv/Nancy,MetSystem/Nancy,grumpydev/Nancy,AIexandr/Nancy,blairconrad/Nancy,lijunle/Nancy,EIrwin/Nancy,duszekmestre/Nancy,damianh/Nancy,jongleur1983/Nancy,guodf/Nancy,ccellar/Nancy,Worthaboutapig/Nancy,sadiqhirani/Nancy,sadiqhirani/Nancy,grumpydev/Nancy,felipeleusin/Nancy,malikdiarra/Nancy,cgourlay/Nancy,murador/Nancy,jeff-pang/Nancy,ayoung/Nancy,murador/Nancy,EIrwin/Nancy,lijunle/Nancy,tsdl2013/Nancy,xt0rted/Nancy,anton-gogolev/Nancy,guodf/Nancy,AIexandr/Nancy,Novakov/Nancy,asbjornu/Nancy,jeff-pang/Nancy,davidallyoung/Nancy,Worthaboutapig/Nancy,horsdal/Nancy,cgourlay/Nancy,tareq-s/Nancy,dbabox/Nancy,horsdal/Nancy,davidallyoung/Nancy,dbabox/Nancy,blairconrad/Nancy,charleypeng/Nancy,felipeleusin/Nancy,asbjornu/Nancy,NancyFx/Nancy,jonathanfoster/Nancy,EIrwin/Nancy,tparnell8/Nancy,murador/Nancy,sloncho/Nancy,VQComms/Nancy,charleypeng/Nancy,rudygt/Nancy,AcklenAvenue/Nancy,ayoung/Nancy,asbjornu/Nancy,albertjan/Nancy,Novakov/Nancy,wtilton/Nancy,rudygt/Nancy,AIexandr/Nancy,sroylance/Nancy,fly19890211/Nancy,danbarua/Nancy,dbolkensteyn/Nancy,dbabox/Nancy,AlexPuiu/Nancy,AlexPuiu/Nancy,lijunle/Nancy,JoeStead/Nancy,VQComms/Nancy,blairconrad/Nancy,adamhathcock/Nancy,guodf/Nancy,sroylance/Nancy,SaveTrees/Nancy,SaveTrees/Nancy,danbarua/Nancy,daniellor/Nancy,tsdl2013/Nancy,malikdiarra/Nancy,daniellor/Nancy,ayoung/Nancy,AcklenAvenue/Nancy
src/Nancy.Demo.Razor.Localization/Views/CultureView-de-DE.cshtml
src/Nancy.Demo.Razor.Localization/Views/CultureView-de-DE.cshtml
@inherits Nancy.ViewEngines.Razor.NancyRazorViewBase<dynamic> @{ Layout = "razor-layout.cshtml"; } <h1>You're here based on the German culture set in HomeModule however the HomeModule only calls return View["CultureView"]. It uses View Location Conventions therefore there must be a file called CultureView-de-DE.cshtml</h1>
@inherits Nancy.ViewEngines.Razor.NancyRazorViewBase<dynamic> @{ Layout = "razor-layout.cshtml"; } <h1>You're here based on ther German culture set in HomeModule however the HomeModule only calls return View["CultureView"]. It uses View Location Conventions therefore there must be a file called CultureView-de-DE.cshtml</h1>
mit
C#
5879746e298400e0ec638340236689ee79211000
move cached tile manager stream reader inside using statement
brnkhy/MapzenGo,brnkhy/MapzenGo
Assets/MapzenGo/Models/CachedDynamicTileManager.cs
Assets/MapzenGo/Models/CachedDynamicTileManager.cs
using System.IO; using System.Text; using MapzenGo.Helpers; using UniRx; using UnityEngine; namespace MapzenGo.Models { public class CachedDynamicTileManager : DynamicTileManager { public string RelativeCachePath = "../CachedTileData/{0}/"; protected string CacheFolderPath; public override void Start() { CacheFolderPath = Path.Combine(Application.persistentDataPath, RelativeCachePath); CacheFolderPath = CacheFolderPath.Format(Zoom); if (!Directory.Exists(CacheFolderPath)) Directory.CreateDirectory(CacheFolderPath); base.Start(); } protected override void LoadTile(Vector2d tileTms, Tile tile) { var url = string.Format(_mapzenUrl, _mapzenLayers, Zoom, tileTms.x, tileTms.y, _mapzenFormat, _key); var tilePath = Path.Combine(CacheFolderPath, tileTms.x + "_" + tileTms.y); if (File.Exists(tilePath)) { using (var r = new StreamReader(tilePath, Encoding.Default)) { var mapData = r.ReadToEnd(); ConstructTile(mapData, tile); } } else { ObservableWWW.Get(url).Subscribe( success => { var sr = File.CreateText(tilePath); sr.Write(success); sr.Close(); ConstructTile(success, tile); }, error => { Debug.Log(error); }); } } } }
using System.IO; using System.Text; using MapzenGo.Helpers; using UniRx; using UnityEngine; namespace MapzenGo.Models { public class CachedDynamicTileManager : DynamicTileManager { public string RelativeCachePath = "../CachedTileData/{0}/"; protected string CacheFolderPath; public override void Start() { CacheFolderPath = Path.Combine(Application.persistentDataPath, RelativeCachePath); CacheFolderPath = CacheFolderPath.Format(Zoom); if (!Directory.Exists(CacheFolderPath)) Directory.CreateDirectory(CacheFolderPath); base.Start(); } protected override void LoadTile(Vector2d tileTms, Tile tile) { var url = string.Format(_mapzenUrl, _mapzenLayers, Zoom, tileTms.x, tileTms.y, _mapzenFormat, _key); var tilePath = Path.Combine(CacheFolderPath, tileTms.x + "_" + tileTms.y); if (File.Exists(tilePath)) { var r = new StreamReader(tilePath, Encoding.Default); var mapData = r.ReadToEnd(); ConstructTile(mapData, tile); } else { ObservableWWW.Get(url).Subscribe( success => { var sr = File.CreateText(tilePath); sr.Write(success); sr.Close(); ConstructTile(success, tile); }, error => { Debug.Log(error); }); } } } }
mit
C#
94e36cb5fa375d2d319929fef23b57d88c4ea73e
Change accessibility modifiers of MySqlOldGuidTypeMapping to be consistent with the project's other type mapping classes.
PomeloFoundation/Pomelo.EntityFrameworkCore.MySql,PomeloFoundation/Pomelo.EntityFrameworkCore.MySql,caleblloyd/Pomelo.EntityFrameworkCore.MySql,caleblloyd/Pomelo.EntityFrameworkCore.MySql
src/EFCore.MySql/Storage/Internal/MySqlOldGuidTypeMapping.cs
src/EFCore.MySql/Storage/Internal/MySqlOldGuidTypeMapping.cs
// Copyright (c) Pomelo Foundation. All rights reserved. // Licensed under the MIT. See LICENSE in the project root for license information. using System; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using Pomelo.EntityFrameworkCore.MySql.Utilities; namespace Microsoft.EntityFrameworkCore.Storage { /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public class MySqlOldGuidTypeMapping : GuidTypeMapping { /// <summary> /// Initializes a new instance of the <see cref="MySqlOldGuidTypeMapping" /> class. /// </summary> public MySqlOldGuidTypeMapping() : base("binary(16)", System.Data.DbType.Guid) { } /// <summary> /// Initializes a new instance of the <see cref="MySqlOldGuidTypeMapping" /> /// class from a <see cref="RelationalTypeMappingParameters"/> instance. /// </summary> /// <param name="parmeters"></param> protected MySqlOldGuidTypeMapping(RelationalTypeMappingParameters parameters) : base(parameters) { } /// <summary> /// Generates the SQL representation of a literal value. /// </summary> /// <param name="value">The literal value.</param> /// <returns> /// The generated string. /// </returns> protected sealed override string GenerateNonNullSqlLiteral([CanBeNull] object value) => ByteArrayFormatter.ToHex(((Guid)value).ToByteArray()); /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public override RelationalTypeMapping Clone(string storeType, int? size) => new MySqlOldGuidTypeMapping(Parameters.WithStoreTypeAndSize(storeType, size)); /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public override CoreTypeMapping Clone(ValueConverter converter) => new MySqlOldGuidTypeMapping(Parameters.WithComposedConverter(converter)); } }
// Copyright (c) Pomelo Foundation. All rights reserved. // Licensed under the MIT. See LICENSE in the project root for license information. using System; using JetBrains.Annotations; using Pomelo.EntityFrameworkCore.MySql.Utilities; namespace Microsoft.EntityFrameworkCore.Storage { /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> internal sealed class MySqlOldGuidTypeMapping : GuidTypeMapping { /// <summary> /// Initializes a new instance of the <see cref="MySqlOldGuidTypeMapping" /> class. /// </summary> public MySqlOldGuidTypeMapping() : base("binary(16)", System.Data.DbType.Guid) { } /// <summary> /// Generates the SQL representation of a literal value. /// </summary> /// <param name="value">The literal value.</param> /// <returns> /// The generated string. /// </returns> protected sealed override string GenerateNonNullSqlLiteral([CanBeNull] object value) => ByteArrayFormatter.ToHex(((Guid)value).ToByteArray()); } }
mit
C#
f99a4cf9d1dbc498f99e4426cd6d1e0b62766029
Remove constructor parameter of type IUnitOfWork.
Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW
src/MitternachtBot/Modules/Utility/Services/RemindService.cs
src/MitternachtBot/Modules/Utility/Services/RemindService.cs
using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Discord; using Discord.WebSocket; using Mitternacht.Common.Replacements; using Mitternacht.Extensions; using Mitternacht.Services; using Mitternacht.Services.Database; using Mitternacht.Services.Database.Models; using Mitternacht.Services.Impl; using NLog; namespace Mitternacht.Modules.Utility.Services { public class RemindService : IMService { private readonly Logger _log; private readonly CancellationToken _cancelAllToken; private readonly DiscordSocketClient _client; private readonly DbService _db; private readonly IBotConfigProvider _bcp; public string RemindMessageFormat => _bcp.BotConfig.RemindMessageFormat; public RemindService(DiscordSocketClient client, IBotConfigProvider bcp, DbService db, StartingGuildsService guilds) { _log = LogManager.GetCurrentClassLogger(); _client = client; _db = db; _bcp = bcp; var cancelSource = new CancellationTokenSource(); _cancelAllToken = cancelSource.Token; using var uow = _db.UnitOfWork; var reminders = uow.Reminders.GetIncludedReminders(guilds).ToList(); foreach(var r in reminders) { Task.Run(() => StartReminder(r)); } } public async Task StartReminder(Reminder r) { var t = _cancelAllToken; var now = DateTime.UtcNow; var time = r.When - now; if(time.TotalMilliseconds > int.MaxValue) return; await Task.Delay(time, t).ConfigureAwait(false); try { IMessageChannel ch; if(r.IsPrivate) { var user = _client.GetGuild(r.ServerId).GetUser(r.ChannelId); if(user == null) return; ch = await user.GetOrCreateDMChannelAsync().ConfigureAwait(false); } else { ch = _client.GetGuild(r.ServerId)?.GetTextChannel(r.ChannelId); } if(ch == null) return; var rep = new ReplacementBuilder() .WithOverride("%user%", () => $"<@!{r.UserId}>") .WithOverride("%message%", () => r.Message) .WithOverride("%target%", () => r.IsPrivate ? "Direct Message" : $"<#{r.ChannelId}>") .Build(); await ch.SendMessageAsync(rep.Replace(RemindMessageFormat).SanitizeMentions()).ConfigureAwait(false); } catch(Exception ex) { _log.Warn(ex); } finally { using var uow = _db.UnitOfWork; uow.Reminders.Remove(r); await uow.SaveChangesAsync(); } } } }
using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Discord; using Discord.WebSocket; using Mitternacht.Common.Replacements; using Mitternacht.Extensions; using Mitternacht.Services; using Mitternacht.Services.Database; using Mitternacht.Services.Database.Models; using Mitternacht.Services.Impl; using NLog; namespace Mitternacht.Modules.Utility.Services { public class RemindService : IMService { private readonly Logger _log; private readonly CancellationToken _cancelAllToken; private readonly DiscordSocketClient _client; private readonly DbService _db; private readonly IBotConfigProvider _bcp; public string RemindMessageFormat => _bcp.BotConfig.RemindMessageFormat; public RemindService(DiscordSocketClient client, IBotConfigProvider bcp, DbService db, StartingGuildsService guilds, IUnitOfWork uow) { _log = LogManager.GetCurrentClassLogger(); _client = client; _db = db; _bcp = bcp; var cancelSource = new CancellationTokenSource(); _cancelAllToken = cancelSource.Token; var reminders = uow.Reminders.GetIncludedReminders(guilds).ToList(); foreach(var r in reminders) { Task.Run(() => StartReminder(r)); } } public async Task StartReminder(Reminder r) { var t = _cancelAllToken; var now = DateTime.UtcNow; var time = r.When - now; if(time.TotalMilliseconds > int.MaxValue) return; await Task.Delay(time, t).ConfigureAwait(false); try { IMessageChannel ch; if(r.IsPrivate) { var user = _client.GetGuild(r.ServerId).GetUser(r.ChannelId); if(user == null) return; ch = await user.GetOrCreateDMChannelAsync().ConfigureAwait(false); } else { ch = _client.GetGuild(r.ServerId)?.GetTextChannel(r.ChannelId); } if(ch == null) return; var rep = new ReplacementBuilder() .WithOverride("%user%", () => $"<@!{r.UserId}>") .WithOverride("%message%", () => r.Message) .WithOverride("%target%", () => r.IsPrivate ? "Direct Message" : $"<#{r.ChannelId}>") .Build(); await ch.SendMessageAsync(rep.Replace(RemindMessageFormat).SanitizeMentions()).ConfigureAwait(false); } catch(Exception ex) { _log.Warn(ex); } finally { using var uow = _db.UnitOfWork; uow.Reminders.Remove(r); await uow.SaveChangesAsync(); } } } }
mit
C#
f37a33dbf5b5d097d7b6d97631c1ee49a7cbf3f9
Fix nullable reference type issue
jskeet/nodatime.org,jskeet/nodatime.org,jskeet/nodatime.org,jskeet/nodatime.org
src/NodaTime.Web/ViewModels/CompareTypesByCommitViewModel.cs
src/NodaTime.Web/ViewModels/CompareTypesByCommitViewModel.cs
// Copyright 2017 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using MoreLinq; using NodaTime.Benchmarks; using NodaTime.Web.Helpers; using System; using System.Collections.Generic; using System.Linq; namespace NodaTime.Web.ViewModels { /// <summary> /// View-model for comparing two runs of the same type, in the same environment, at different commits. /// </summary> public class CompareTypesByCommitViewModel { public BenchmarkEnvironment Environment => Left.Environment; public BenchmarkType Left { get; } public BenchmarkType Right { get; } public CompareTypesByCommitViewModel(BenchmarkType left, BenchmarkType right) { Left = left; Right = right; } public IEnumerable<(Benchmark description, Statistics? left, Statistics? right, bool important)> GetBenchmarks() { // TODO: Handle missing types var leftBenchmarks = Left.Benchmarks.ToDictionary(b => b.Method); var rightBenchmarks = Right.Benchmarks.ToDictionary(b => b.Method); var union = Left.Benchmarks.Concat(Right.Benchmarks).DistinctBy(b => b.Method).OrderBy(b => b.Method); foreach (var benchmark in union) { var leftStats = leftBenchmarks.GetValueOrDefault(benchmark.Method)?.Statistics; var rightStats = rightBenchmarks.GetValueOrDefault(benchmark.Method)?.Statistics; yield return (benchmark, leftStats, rightStats, IsImportant(leftStats, rightStats)); } } private static bool IsImportant(Statistics? left, Statistics? right) { if (left == null || right == null) { return false; } // Just in case we have strange results that might cause problems on division. (If something takes // less than a picosecond, I'm suspicious...) if (left.Mean < 0.001 || right.Mean < 0.001) { return true; } double min = Math.Min(left.Mean, right.Mean); double max = Math.Max(left.Mean, right.Mean); return min / max < 0.8; // A 20% change either way is important. (Arbitrary starting point...) } } }
// Copyright 2017 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using MoreLinq; using NodaTime.Benchmarks; using NodaTime.Web.Helpers; using System; using System.Collections.Generic; using System.Linq; namespace NodaTime.Web.ViewModels { /// <summary> /// View-model for comparing two runs of the same type, in the same environment, at different commits. /// </summary> public class CompareTypesByCommitViewModel { public BenchmarkEnvironment Environment => Left.Environment; public BenchmarkType Left { get; } public BenchmarkType Right { get; } public CompareTypesByCommitViewModel(BenchmarkType left, BenchmarkType right) { Left = left; Right = right; } public IEnumerable<(Benchmark description, Statistics left, Statistics right, bool important)> GetBenchmarks() { // TODO: Handle missing types var leftBenchmarks = Left.Benchmarks.ToDictionary(b => b.Method); var rightBenchmarks = Right.Benchmarks.ToDictionary(b => b.Method); var union = Left.Benchmarks.Concat(Right.Benchmarks).DistinctBy(b => b.Method).OrderBy(b => b.Method); foreach (var benchmark in union) { var leftStats = leftBenchmarks.GetValueOrDefault(benchmark.Method)?.Statistics; var rightStats = rightBenchmarks.GetValueOrDefault(benchmark.Method)?.Statistics; yield return (benchmark, leftStats, rightStats, IsImportant(leftStats, rightStats)); } } private static bool IsImportant(Statistics left, Statistics right) { if (left == null || right == null) { return false; } // Just in case we have strange results that might cause problems on division. (If something takes // less than a picosecond, I'm suspicious...) if (left.Mean < 0.001 || right.Mean < 0.001) { return true; } double min = Math.Min(left.Mean, right.Mean); double max = Math.Max(left.Mean, right.Mean); return min / max < 0.8; // A 20% change either way is important. (Arbitrary starting point...) } } }
apache-2.0
C#
1096685d0ee16f5a28a2cda7d3a29314661decf1
order properties base type first
kevinphelps/base-rest
BaseWeb/WebApiContractResolver.cs
BaseWeb/WebApiContractResolver.cs
using BaseService.General; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using System.Collections.Generic; using System.Linq; using System.Reflection; using System; namespace BaseWeb { public class WebApiContractResolver : CamelCasePropertyNamesContractResolver { protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization) { JsonProperty property = base.CreateProperty(member, memberSerialization); if (typeof(IDto).IsAssignableFrom(property.DeclaringType)) { if (property.PropertyName.ToLower() == nameof(IDto.ExcludedProperties).ToLower()) { property.ShouldSerialize = instance => false; } else { property.ShouldSerialize = instance => { IDto dto = instance as IDto; if (dto.ExcludedProperties != null && dto.ExcludedProperties.Length > 0) { string lowerPropertyName = property.PropertyName.ToLower(); return !dto.ExcludedProperties.Any(p => p.ToLower() == lowerPropertyName); } return true; }; } } return property; } protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization) { var properties = base.CreateProperties(type, memberSerialization); if (properties != null) return properties.OrderBy(p => p.DeclaringType.CountInheritanceDepth()).ToList(); return properties; } } public static class TypeExtensions { public static int CountInheritanceDepth(this Type type) { int count = 0; Type baseType = type; while (baseType != null) { count++; baseType = baseType.BaseType; } return count; } } }
using BaseService.General; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using System.Linq; using System.Reflection; namespace BaseWeb { public class WebApiContractResolver : CamelCasePropertyNamesContractResolver { protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization) { JsonProperty property = base.CreateProperty(member, memberSerialization); if (typeof(IDto).IsAssignableFrom(property.DeclaringType)) { if (property.PropertyName.ToLower() == nameof(IDto.ExcludedProperties).ToLower()) { property.ShouldSerialize = instance => false; } else { property.ShouldSerialize = instance => { IDto dto = instance as IDto; if (dto.ExcludedProperties != null && dto.ExcludedProperties.Length > 0) { string lowerPropertyName = property.PropertyName.ToLower(); return !dto.ExcludedProperties.Any(p => p.ToLower() == lowerPropertyName); } return true; }; } } return property; } } }
mit
C#
ef99780d45c8c2be643a6badf0f7335f5ac4f5cd
Put in (temporary) check to throw an exception if no character-verse data is loaded (trying to diagnose problem on TC)
sillsdev/Glyssen,sillsdev/Glyssen
ProtoScript/CharacterVerse.cs
ProtoScript/CharacterVerse.cs
using System; using System.Collections.Generic; using System.Linq; using SIL.ScriptureUtils; namespace ProtoScript { public class CharacterVerse { private static IEnumerable<CharacterVerse> s_data; static CharacterVerse() { LoadAll(); } public static int GetCharacter(string bookId, int chapter, int verse) { IList<CharacterVerse> matches = s_data.Where(cv => cv.BookId == bookId && cv.Chapter == chapter && cv.Verse == verse).ToList(); if (matches.Count == 1) return matches.First().CharacterId; return Block.kUnknownCharacterId; } private static void LoadAll() { if (s_data != null) return; var list = new List<CharacterVerse>(); foreach (var line in CharacterVerseData.CharacterVerse.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries)) { string[] items = line.Split(new[] { "\t" }, StringSplitOptions.None); list.Add(new CharacterVerse { BookId = items[0], Chapter = Int32.Parse(items[1]), Verse = ScrReference.VerseToIntStart(items[2]), Character = items[3], CharacterId = Int32.Parse(items[4]), Delivery = items[5]//, //Alias = items[6] }); } if (!list.Any()) throw new ApplicationException("No character verse data available!"); s_data = list; } public string Character; public int CharacterId; public string BookId; public int Chapter; public int Verse; public string Delivery; public string Alias; } }
using System; using System.Collections.Generic; using System.Linq; using SIL.ScriptureUtils; namespace ProtoScript { public class CharacterVerse { private static IEnumerable<CharacterVerse> s_data; static CharacterVerse() { LoadAll(); } public static int GetCharacter(string bookId, int chapter, int verse) { IList<CharacterVerse> matches = s_data.Where(cv => cv.BookId == bookId && cv.Chapter == chapter && cv.Verse == verse).ToList(); if (matches.Count == 1) return matches.First().CharacterId; return Block.kUnknownCharacterId; } private static void LoadAll() { if (s_data != null) return; var list = new List<CharacterVerse>(); foreach (var line in CharacterVerseData.CharacterVerse.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries)) { string[] items = line.Split(new[] { "\t" }, StringSplitOptions.None); list.Add(new CharacterVerse { BookId = items[0], Chapter = Int32.Parse(items[1]), Verse = ScrReference.VerseToIntStart(items[2]), Character = items[3], CharacterId = Int32.Parse(items[4]), Delivery = items[5]//, //Alias = items[6] }); } s_data = list; } public string Character; public int CharacterId; public string BookId; public int Chapter; public int Verse; public string Delivery; public string Alias; } }
mit
C#
332f0b8806a6e462e191c51e7138a5d0f1d5960e
Create tests for each method
kropp/ReSharper-TestToolsPlugin
CreateTestPlugin/CreateTestAction.cs
CreateTestPlugin/CreateTestAction.cs
using System; using JetBrains.Application; using JetBrains.Application.Progress; using JetBrains.ProjectModel; using JetBrains.ReSharper.Feature.Services.Bulbs; using JetBrains.ReSharper.Feature.Services.CSharp.Bulbs; using JetBrains.ReSharper.Intentions.Extensibility; using JetBrains.ReSharper.Psi; using JetBrains.ReSharper.Psi.CSharp; using JetBrains.ReSharper.Psi.CSharp.Tree; using JetBrains.ReSharper.Psi.ExtensionsAPI.Tree; using JetBrains.ReSharper.Psi.Impl.Search; using JetBrains.ReSharper.Psi.Tree; using JetBrains.TextControl; using JetBrains.Util; namespace CreateTestPlugin { /// <summary> /// This is an example context action. The test project demonstrates tests for /// availability and execution of this action. /// </summary> [ContextAction(Name = "CreateTest", Description = "Creates a test", Group = "C#")] public class CreateTestAction : ContextActionBase { private readonly ICSharpContextActionDataProvider myProvider; private IClassDeclaration myClassDeclaration; public CreateTestAction(ICSharpContextActionDataProvider provider) { myProvider = provider; } public override bool IsAvailable(IUserDataHolder cache) { myClassDeclaration = myProvider.GetSelectedElement<IClassDeclaration>(true, true); return myClassDeclaration != null; } protected override Action<ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { var factory = CSharpElementFactory.GetInstance(myProvider.PsiModule); var testClassName = myClassDeclaration.DeclaredName + "Test"; var file = factory.CreateFile("public class " + testClassName + " {}"); var testClass = file.TypeDeclarations.First() as IClassDeclaration; if (testClass == null) return null; var nunitFixtureType = TypeFactory.CreateTypeByCLRName("NUnit.Framework.TestFixtureAttribute", myProvider.PsiModule, myClassDeclaration.GetProject().GetResolveContext()); var attribute = factory.CreateAttribute(nunitFixtureType.GetTypeElement()); testClass.AddAttributeBefore(attribute, null); var nunitTestType = TypeFactory.CreateTypeByCLRName("NUnit.Framework.TestAttribute", myProvider.PsiModule, myClassDeclaration.GetProject().GetResolveContext()).GetTypeElement(); foreach (var methodDeclaration in myClassDeclaration.MethodDeclarations) { var testMethod = factory.CreateTypeMemberDeclaration("public void Test" + methodDeclaration.DeclaredName + "(){}") as IClassMemberDeclaration; if (testMethod == null) continue; testMethod.AddAttributeBefore(factory.CreateAttribute(nunitTestType), null); testClass.AddClassMemberDeclaration(testMethod); } using (WriteLockCookie.Create()) ModificationUtil.AddChildAfter(myClassDeclaration, testClass); return null; } public override string Text { get { return "Create a test"; } } } }
using System; using JetBrains.Application; using JetBrains.Application.Progress; using JetBrains.ProjectModel; using JetBrains.ReSharper.Feature.Services.Bulbs; using JetBrains.ReSharper.Feature.Services.CSharp.Bulbs; using JetBrains.ReSharper.Intentions.Extensibility; using JetBrains.ReSharper.Psi; using JetBrains.ReSharper.Psi.CSharp; using JetBrains.ReSharper.Psi.CSharp.Tree; using JetBrains.ReSharper.Psi.ExtensionsAPI.Tree; using JetBrains.ReSharper.Psi.Tree; using JetBrains.TextControl; using JetBrains.Util; namespace CreateTestPlugin { /// <summary> /// This is an example context action. The test project demonstrates tests for /// availability and execution of this action. /// </summary> [ContextAction(Name = "CreateTest", Description = "Creates a test", Group = "C#")] public class CreateTestAction : ContextActionBase { private readonly ICSharpContextActionDataProvider myProvider; private IClassDeclaration myClassDeclaration; public CreateTestAction(ICSharpContextActionDataProvider provider) { myProvider = provider; } public override bool IsAvailable(IUserDataHolder cache) { myClassDeclaration = myProvider.GetSelectedElement<IClassDeclaration>(true, true); return myClassDeclaration != null; } protected override Action<ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { var factory = CSharpElementFactory.GetInstance(myProvider.PsiModule); var file = factory.CreateFile("public class "+ myClassDeclaration.DeclaredName +"Test {}"); var testClass = file.TypeDeclarations.First(); var nunitFixtureType = TypeFactory.CreateTypeByCLRName("NUnit.Framework.TestFixtureAttribute", myProvider.PsiModule, myClassDeclaration.GetProject().GetResolveContext()); var typeElement = nunitFixtureType.GetTypeElement(); var attribute = factory.CreateAttribute(typeElement); testClass.AddAttributeBefore(attribute, null); using (WriteLockCookie.Create()) ModificationUtil.AddChildAfter(myClassDeclaration, testClass); return null; } public override string Text { get { return "Create a test"; } } } }
apache-2.0
C#
dcd8ae86889dd4adabfeb4535f043828de3e687a
add dummy test function for builtin functions
maul-esel/CobaltAHK,maul-esel/CobaltAHK
CobaltAHK/ExpressionTree/Scope.cs
CobaltAHK/ExpressionTree/Scope.cs
using System; using System.Collections.Generic; using System.Linq.Expressions; namespace CobaltAHK.ExpressionTree { public class Scope { public Scope() : this(null) { } public Scope(Scope parentScope) { parent = parentScope; #if DEBUG var msgbox = Expression.Lambda<Action>( Expression.Block( Expression.Call(typeof(Scope).GetMethod("MsgBox", new[] { typeof(string) }), Expression.Constant("MSGBOX dummy")) ) ); AddFunction("MsgBox", msgbox); #endif } #if DEBUG public static void MsgBox(string text) { Console.WriteLine(text); } #endif private readonly Scope parent; public bool IsRoot { get { return parent == null; } } private readonly IDictionary<string, LambdaExpression> functions = new Dictionary<string, LambdaExpression>(); public void AddFunction(string name, LambdaExpression func) { functions[name.ToLower()] = func; } public LambdaExpression ResolveFunction(string name) { if (functions.ContainsKey(name.ToLower())) { return functions[name.ToLower()]; } else if (parent != null) { return parent.ResolveFunction(name); } throw new Exception(); // todo } private readonly IDictionary<string, ParameterExpression> variables = new Dictionary<string, ParameterExpression>(); public void AddVariable(string name, ParameterExpression variable) { variables.Add(name.ToLower(), variable); } public ParameterExpression ResolveVariable(string name) { if (!variables.ContainsKey(name.ToLower())) { AddVariable(name, Expression.Parameter(typeof(object), name)); } return variables[name.ToLower()]; } // todo: RootScope() initialized with builtin functions and commands } }
using System; using System.Collections.Generic; using System.Linq.Expressions; namespace CobaltAHK.ExpressionTree { public class Scope { public Scope() : this(null) { } public Scope(Scope parentScope) { parent = parentScope; } private readonly Scope parent; public bool IsRoot { get { return parent == null; } } private readonly IDictionary<string, LambdaExpression> functions = new Dictionary<string, LambdaExpression>(); public void AddFunction(string name, LambdaExpression func) { functions[name.ToLower()] = func; } public LambdaExpression ResolveFunction(string name) { if (functions.ContainsKey(name.ToLower())) { return functions[name.ToLower()]; } else if (parent != null) { return parent.ResolveFunction(name); } throw new Exception(); // todo } private readonly IDictionary<string, ParameterExpression> variables = new Dictionary<string, ParameterExpression>(); public void AddVariable(string name, ParameterExpression variable) { variables.Add(name.ToLower(), variable); } public ParameterExpression ResolveVariable(string name) { if (!variables.ContainsKey(name.ToLower())) { AddVariable(name, Expression.Parameter(typeof(object), name)); } return variables[name.ToLower()]; } // todo: RootScope() initialized with builtin functions and commands } }
mit
C#
aecd6bc5137a9251e2484c69840c33e3a749c926
Update AutoMapperConfiguration.cs - Added SkillEntity, Skill Map.
NinjaVault/NinjaHive,NinjaVault/NinjaHive
NinjaHive.BusinessLayer/AutoMapperConfiguration.cs
NinjaHive.BusinessLayer/AutoMapperConfiguration.cs
using AutoMapper; using NinjaHive.Contract.DTOs; using NinjaHive.Domain; namespace NinjaHive.BusinessLayer { public class AutoMapperConfiguration { public static void Configure() { Mapper.CreateMap<EquipmentItemEntity, EquipmentItem>() .ForMember(destination => destination.UpgradeElement, options => options.MapFrom(source => source.IsUpgrader)) .ForMember(destination => destination.CraftingElement, options => options.MapFrom(source => source.IsCrafter)) .ForMember(destination => destination.QuestItem, options => options.MapFrom(source => source.IsQuestItem)); Mapper.CreateMap<SkillEntity, Skill>() .ForMember(destination => destination.friendly, options => options.MapFrom(source => source.Friendly)) .ForMember(destination => destination.Name, options => options.MapFrom(source => source.Name)) .ForMember(destination => destination.Radius, options => options.MapFrom(source => source.Radius)) .ForMember(destination => destination.Radius, options => options.MapFrom(source => source.Radius)) .ForMember(destination => destination.Range, options => options.MapFrom(source => source.Range)) .ForMember(destination => destination.target, options => options.MapFrom(source => source.Target)) .ForMember(destination => destination.targetCount, options => options.MapFrom(source => source.Targets)); } }; }
using AutoMapper; using NinjaHive.Contract.DTOs; using NinjaHive.Domain; namespace NinjaHive.BusinessLayer { public class AutoMapperConfiguration { public static void Configure() { Mapper.CreateMap<EquipmentItemEntity, EquipmentItem>() .ForMember(destination => destination.UpgradeElement, options => options.MapFrom(source => source.IsUpgrader)) .ForMember(destination => destination.CraftingElement, options => options.MapFrom(source => source.IsCrafter)) .ForMember(destination => destination.QuestItem, options => options.MapFrom(source => source.IsQuestItem)); } } }
apache-2.0
C#
574cce11c2b525afb2b03c4d65e0c96eae6fec2e
Revert 'Terms of Use Form closes in a better way'
quasar/QuasarRAT,quasar/QuasarRAT
Server/Forms/FrmTermsOfUse.cs
Server/Forms/FrmTermsOfUse.cs
using System; using System.Threading; using System.Windows.Forms; using xServer.Settings; namespace xServer.Forms { public partial class FrmTermsOfUse : Form { private static bool _exit = true; public FrmTermsOfUse() { InitializeComponent(); rtxtContent.Text = Properties.Resources.TermsOfUse; } private void FrmTermsOfUse_Load(object sender, EventArgs e) { lblToU.Left = (this.Width / 2) - (lblToU.Width / 2); Thread t = new Thread(Wait20Sec); t.Start(); } private void FrmTermsOfUse_FormClosing(object sender, FormClosingEventArgs e) { if (e.CloseReason == CloseReason.UserClosing && _exit) System.Diagnostics.Process.GetCurrentProcess().Kill(); } private void btnAccept_Click(object sender, EventArgs e) { XMLSettings.WriteValue("ShowToU", (!chkDontShowAgain.Checked).ToString()); _exit = false; this.Close(); } private void btnDecline_Click(object sender, EventArgs e) { System.Diagnostics.Process.GetCurrentProcess().Kill(); } private void Wait20Sec() { for (int i = 19; i >= 0; i--) { Thread.Sleep(1000); try { this.Invoke((MethodInvoker)delegate { btnAccept.Text = "Accept (" + i + ")"; }); } catch { } } this.Invoke((MethodInvoker)delegate { btnAccept.Text = "Accept"; btnAccept.Enabled = true; }); } } }
using System; using System.Threading; using System.Windows.Forms; using xServer.Settings; namespace xServer.Forms { public partial class FrmTermsOfUse : Form { private static bool _exit = true; public FrmTermsOfUse() { InitializeComponent(); rtxtContent.Text = Properties.Resources.TermsOfUse; } private void FrmTermsOfUse_Load(object sender, EventArgs e) { lblToU.Left = (this.Width / 2) - (lblToU.Width / 2); Thread t = new Thread(Wait20Sec); t.Start(); } private void FrmTermsOfUse_FormClosing(object sender, FormClosingEventArgs e) { if (e.CloseReason == CloseReason.UserClosing && _exit) Application.Exit(); } private void btnAccept_Click(object sender, EventArgs e) { XMLSettings.WriteValue("ShowToU", (!chkDontShowAgain.Checked).ToString()); _exit = false; this.Close(); } private void btnDecline_Click(object sender, EventArgs e) { Application.Exit(); } private void Wait20Sec() { for (int i = 19; i >= 0; i--) { Thread.Sleep(1000); try { this.Invoke((MethodInvoker)delegate { btnAccept.Text = "Accept (" + i + ")"; }); } catch { } } this.Invoke((MethodInvoker)delegate { btnAccept.Text = "Accept"; btnAccept.Enabled = true; }); } } }
mit
C#
4fd755fd2294a1813957569c6043be96a64580df
Use nested class.
JohanLarsson/Gu.ChangeTracking,JohanLarsson/Gu.State,JohanLarsson/Gu.State
Gu.ChangeTracking.Tests/EqualBy/EqualByPropertiesSettingsTests.cs
Gu.ChangeTracking.Tests/EqualBy/EqualByPropertiesSettingsTests.cs
namespace Gu.ChangeTracking.Tests { using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using NUnit.Framework; public class EqualByPropertiesSettingsTests { [Test] public void Ignores() { var type = typeof(ComplexType); var nameProperty = type.GetProperty(nameof(ComplexType.Name)); var valueProperty = type.GetProperty(nameof(ComplexType.Value)); var settings = new EqualByPropertiesSettings(type, new[] { nameProperty.Name }, Constants.DefaultPropertyBindingFlags, ReferenceHandling.Throw); Assert.AreEqual(true, settings.IsIgnoringProperty(nameProperty)); Assert.AreEqual(false, settings.IsIgnoringProperty(valueProperty)); } [Test] public void IgnoresNull() { var settings = new EqualByPropertiesSettings(null, Constants.DefaultPropertyBindingFlags, ReferenceHandling.Throw); Assert.AreEqual(true, settings.IsIgnoringProperty(null)); } [Test] public void IgnoresIndexer() { var type = typeof(List<int>); var countProperty = type.GetProperty(nameof(IList.Count)); var indexerProperty = type.GetProperties().Single(x => x.GetIndexParameters().Length > 0); var settings = new EqualByPropertiesSettings(null, Constants.DefaultPropertyBindingFlags, ReferenceHandling.Throw); Assert.AreEqual(false, settings.IsIgnoringProperty(countProperty)); Assert.AreEqual(true, settings.IsIgnoringProperty(indexerProperty)); } [TestCase(BindingFlags.Public, ReferenceHandling.Throw)] [TestCase(BindingFlags.Public, ReferenceHandling.Structural)] public void Cache(BindingFlags bindingFlags, ReferenceHandling referenceHandling) { var settings = EqualByPropertiesSettings.GetOrCreate(bindingFlags, referenceHandling); Assert.AreEqual(bindingFlags, settings.BindingFlags); Assert.AreEqual(referenceHandling, settings.ReferenceHandling); var second = EqualByPropertiesSettings.GetOrCreate(BindingFlags.Public, referenceHandling); Assert.AreSame(settings, second); } private class ComplexType { public string Name { get; set; } public int Value { get; set; } } } }
namespace Gu.ChangeTracking.Tests { using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using Gu.ChangeTracking.Tests.CopyStubs; using NUnit.Framework; public class EqualByPropertiesSettingsTests { [Test] public void Ignores() { var type = typeof(ComplexType); var nameProperty = type.GetProperty(nameof(ComplexType.Name)); var valueProperty = type.GetProperty(nameof(ComplexType.Value)); var settings = new EqualByPropertiesSettings(type, new[] { nameProperty.Name }, Constants.DefaultPropertyBindingFlags, ReferenceHandling.Throw); Assert.AreEqual(true, settings.IsIgnoringProperty(nameProperty)); Assert.AreEqual(false, settings.IsIgnoringProperty(valueProperty)); } [Test] public void IgnoresNull() { var settings = new EqualByPropertiesSettings(null, Constants.DefaultPropertyBindingFlags, ReferenceHandling.Throw); Assert.AreEqual(true, settings.IsIgnoringProperty(null)); } [Test] public void IgnoresIndexer() { var type = typeof(List<int>); var countProperty = type.GetProperty(nameof(IList.Count)); var indexerProperty = type.GetProperties().Single(x => x.GetIndexParameters().Length > 0); var settings = new EqualByPropertiesSettings(null, Constants.DefaultPropertyBindingFlags, ReferenceHandling.Throw); Assert.AreEqual(false, settings.IsIgnoringProperty(countProperty)); Assert.AreEqual(true, settings.IsIgnoringProperty(indexerProperty)); } [TestCase(BindingFlags.Public, ReferenceHandling.Throw)] [TestCase(BindingFlags.Public, ReferenceHandling.Structural)] public void Cache(BindingFlags bindingFlags, ReferenceHandling referenceHandling) { var settings = EqualByPropertiesSettings.GetOrCreate(bindingFlags, referenceHandling); Assert.AreEqual(bindingFlags, settings.BindingFlags); Assert.AreEqual(referenceHandling, settings.ReferenceHandling); var second = EqualByPropertiesSettings.GetOrCreate(BindingFlags.Public, referenceHandling); Assert.AreSame(settings, second); } } }
mit
C#
b8e852a4736b281e10754edbaacb6403e3d2cae6
Use the new OperatingSystem class.
dlemstra/Magick.NET,dlemstra/Magick.NET
tests/Magick.NET.Tests/MagickNETTests/TheFeaturesProperty.cs
tests/Magick.NET.Tests/MagickNETTests/TheFeaturesProperty.cs
// Copyright 2013-2020 Dirk Lemstra <https://github.com/dlemstra/Magick.NET/> // // Licensed under the ImageMagick License (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // https://www.imagemagick.org/script/license.php // // 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 ImageMagick; using Xunit; namespace Magick.NET.Tests { public partial class MagickNETTests { public class TheFeaturesProperty { [Fact] public void ContainsExpectedFeatures() { var expected = "Cipher DPC "; #if Q16HDRI expected += "HDRI "; #endif if (OperatingSystem.IsWindows) expected += "OpenCL "; #if OPENMP expected += "OpenMP(2.0) "; #endif #if DEBUG_TEST expected = "Debug " + expected; #endif Assert.Equal(expected, MagickNET.Features); } } } }
// Copyright 2013-2020 Dirk Lemstra <https://github.com/dlemstra/Magick.NET/> // // Licensed under the ImageMagick License (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // https://www.imagemagick.org/script/license.php // // 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 ImageMagick; using Xunit; namespace Magick.NET.Tests { public partial class MagickNETTests { public class TheFeaturesProperty { [Fact] public void ContainsExpectedFeatures() { var expected = "Cipher DPC "; #if Q16HDRI expected += "HDRI "; #endif #if WINDOWS_BUILD expected += "OpenCL "; #endif #if OPENMP expected += "OpenMP(2.0) "; #endif #if DEBUG_TEST expected = "Debug " + expected; #endif Assert.Equal(expected, MagickNET.Features); } } } }
apache-2.0
C#
bb3c2b24986ad424f6ec608530f18bcc22e33024
Change NaN with large number (#817)
facebook/yoga,facebook/css-layout,facebook/yoga,facebook/css-layout,facebook/yoga,facebook/css-layout,facebook/css-layout,facebook/yoga,facebook/yoga,facebook/css-layout,facebook/yoga,facebook/css-layout,facebook/yoga,facebook/css-layout,facebook/yoga,facebook/yoga,facebook/yoga,facebook/css-layout,facebook/css-layout
csharp/Facebook.Yoga/YogaConstants.cs
csharp/Facebook.Yoga/YogaConstants.cs
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ namespace Facebook.Yoga { public static class YogaConstants { /** * Large positive number signifies that the property(float) is undefined. Earlier we used to have * YGundefined as NAN, but the downside of this is that we can't use -ffast-math compiler flag as * it assumes all floating-point calculation involve and result into finite numbers. For more * information regarding -ffast-math compiler flag in clang, have a look at * https://clang.llvm.org/docs/UsersManual.html#cmdoption-ffast-math */ public const float Undefined = 10E20F; public static bool IsUndefined(float value) { // Value of a float in the case of it being not defined is 10.1E20. Earlier it used to be NAN, // the benefit of which // was that if NAN is involved in any mathematical expression the result was NAN. But since we // want to have `-ffast-math` // flag being used by compiler which assumes that the floating point values are not NAN and Inf, // we represent YGUndefined as 10.1E20. // But now if YGUndefined is involved in any mathematical operations this value(10.1E20) would // change. // So the following check makes sure that if the value is outside a range (-10E8, 10E8) then it // is undefined. return value >= 10E8F || value <= -10E8; } public static bool IsUndefined(YogaValue value) { return value.Unit == YogaUnit.Undefined; } } }
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ namespace Facebook.Yoga { public static class YogaConstants { public const float Undefined = float.NaN; public static bool IsUndefined(float value) { return float.IsNaN(value); } public static bool IsUndefined(YogaValue value) { return value.Unit == YogaUnit.Undefined; } } }
mit
C#
afe77b5a7192107bb14378dc6ba9cadb2fc6d110
Initialize zoom
EasyPeasyLemonSqueezy/MadCat
MadCat/NutEngine/Camera/Camera2D.cs
MadCat/NutEngine/Camera/Camera2D.cs
using Microsoft.Xna.Framework; namespace NutEngine.Camera { public abstract class Camera2D { public abstract Matrix2D Transform { get; } public Vector2 Position { get; set; } public float Rotation { get; set; } public float Zoom { get; set; } public Vector2 Frame { get; set; } public Vector2 Origin { get; set; } public Camera2D(Vector2 frame) { Frame = frame; Origin = frame / 2; Zoom = 1f; } } }
using Microsoft.Xna.Framework; namespace NutEngine.Camera { public abstract class Camera2D { public abstract Matrix2D Transform { get; } public Vector2 Position { get; set; } public float Rotation { get; set; } public float Zoom { get; set; } public Vector2 Frame { get; set; } public Vector2 Origin { get; set; } public Camera2D(Vector2 frame) { Frame = frame; Origin = frame / 2; } } }
mit
C#
e89e3ece66e48b300530768200a05a7d9501a1ed
Add test for RacingKingsChessGame.IsDraw
ProgramFOX/Chess.NET
ChessDotNet.Variants.Tests/RacingKingsChessGameTests.cs
ChessDotNet.Variants.Tests/RacingKingsChessGameTests.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NUnit.Framework; namespace ChessDotNet.Variants.Tests { using RacingKings; [TestFixture] public class RacingKingsChessGameTests { [Test] public static void TestStartPosition() { RacingKingsChessGame game = new RacingKingsChessGame(); Assert.AreEqual("8/8/8/8/8/8/krbnNBRK/qrbnNBRQ w - - 0 1", game.GetFen()); } [Test] public static void TestInvalidMove_NoCheck() { RacingKingsChessGame game = new RacingKingsChessGame(); Assert.False(game.IsValidMove(new Move("E2", "C1", Player.White))); } [Test] public static void TestGetValidMoves() { RacingKingsChessGame game = new RacingKingsChessGame(); Assert.AreEqual(21, game.GetValidMoves(Player.White).Count); } [Test] public static void TestIsWinnerWhite1() { RacingKingsChessGame game = new RacingKingsChessGame("5K2/1k6/8/8/8/8/1rbnNBR1/qrbnNBRQ b - - 11 6"); Assert.False(game.IsWinner(Player.White)); game.ApplyMove(new Move("B7", "C7", Player.Black), true); Assert.True(game.IsWinner(Player.White)); } [Test] public static void TestIsWinnerWhite2() { RacingKingsChessGame game = new RacingKingsChessGame("5K2/1k6/8/8/8/8/1rbnNBR1/qrbnNBRQ b - - 11 6"); Assert.False(game.IsWinner(Player.White)); game.ApplyMove(new Move("B7", "B8", Player.Black), true); Assert.False(game.IsWinner(Player.White)); Assert.True(game.IsDraw()); } [Test] public static void TestIsWinnerBlack() { RacingKingsChessGame game = new RacingKingsChessGame("2k5/5K2/8/8/8/8/1rbnNBR1/qrbnNBRQ w - - 12 7"); Assert.True(game.IsWinner(Player.Black)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NUnit.Framework; namespace ChessDotNet.Variants.Tests { using RacingKings; [TestFixture] public class RacingKingsChessGameTests { [Test] public static void TestStartPosition() { RacingKingsChessGame game = new RacingKingsChessGame(); Assert.AreEqual("8/8/8/8/8/8/krbnNBRK/qrbnNBRQ w - - 0 1", game.GetFen()); } [Test] public static void TestInvalidMove_NoCheck() { RacingKingsChessGame game = new RacingKingsChessGame(); Assert.False(game.IsValidMove(new Move("E2", "C1", Player.White))); } [Test] public static void TestGetValidMoves() { RacingKingsChessGame game = new RacingKingsChessGame(); Assert.AreEqual(21, game.GetValidMoves(Player.White).Count); } [Test] public static void TestIsWinnerWhite1() { RacingKingsChessGame game = new RacingKingsChessGame("5K2/1k6/8/8/8/8/1rbnNBR1/qrbnNBRQ b - - 11 6"); Assert.False(game.IsWinner(Player.White)); game.ApplyMove(new Move("B7", "C7", Player.Black), true); Assert.True(game.IsWinner(Player.White)); } [Test] public static void TestIsWinnerWhite2() { RacingKingsChessGame game = new RacingKingsChessGame("5K2/1k6/8/8/8/8/1rbnNBR1/qrbnNBRQ b - - 11 6"); Assert.False(game.IsWinner(Player.White)); game.ApplyMove(new Move("B7", "B8", Player.Black), true); Assert.False(game.IsWinner(Player.White)); } [Test] public static void TestIsWinnerBlack() { RacingKingsChessGame game = new RacingKingsChessGame("2k5/5K2/8/8/8/8/1rbnNBR1/qrbnNBRQ w - - 12 7"); Assert.True(game.IsWinner(Player.Black)); } } }
mit
C#
e819e0f2f64e029b00072dd20a585f8040a57f47
add newlines between static functions and classes
biboudis/LambdaMicrobenchmarking
LambdaMicrobenchmarking/Script.cs
LambdaMicrobenchmarking/Script.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LambdaMicrobenchmarking { public static class Script { public static Script<T> Of<T>(params Tuple<String, Func<T>>[] actions) { return Script<T>.Of(actions); } public static Script<T> Of<T>(String name, Func<T> action) { return Of(Tuple.Create(name, action)); } } public class Script<T> { static public int Iterations { get { return Run<T>.iterations; } set { Run<T>.iterations = value; } } static public int WarmupIterations { get { return Run<T>.warmups; } set { Run<T>.warmups = value; } } public static double MinRunningSecs { get { return Run<T>.minimumSecs; } set { Run<T>.minimumSecs = value; } } private List<Tuple<String, Func<T>>> actions { get; set; } private Script(params Tuple<String, Func<T>>[] actions) { this.actions = actions.ToList(); } public static Script<T> Of(params Tuple<String, Func<T>>[] actions) { return new Script<T>(actions); } public Script<T> Of(String name, Func<T> action) { actions.Add(Tuple.Create(name,action)); return this; } public Script<T> WithHead() { Console.WriteLine(Run<T>.FORMAT, "Benchmark", "Mean", "Mean-Error", "Sdev", "Unit", "Count"); return this; } public Script<T> RunAll() { actions.Select(action => new Run<T>(action)).ToList().ForEach(run => run.Measure()); return this; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LambdaMicrobenchmarking { public static class Script { public static Script<T> Of<T>(params Tuple<String, Func<T>>[] actions) { return Script<T>.Of(actions); } public static Script<T> Of<T>(String name, Func<T> action) { return Of(Tuple.Create(name, action)); } } public class Script<T> { static public int Iterations { get { return Run<T>.iterations; } set { Run<T>.iterations = value; } } static public int WarmupIterations { get { return Run<T>.warmups; } set { Run<T>.warmups = value; } } public static double MinRunningSecs { get { return Run<T>.minimumSecs; } set { Run<T>.minimumSecs = value; } } private List<Tuple<String, Func<T>>> actions { get; set; } private Script(params Tuple<String, Func<T>>[] actions) { this.actions = actions.ToList(); } public static Script<T> Of(params Tuple<String, Func<T>>[] actions) { return new Script<T>(actions); } public Script<T> Of(String name, Func<T> action) { actions.Add(Tuple.Create(name,action)); return this; } public Script<T> WithHead() { Console.WriteLine(Run<T>.FORMAT, "Benchmark", "Mean", "Mean-Error", "Sdev", "Unit", "Count"); return this; } public Script<T> RunAll() { actions.Select(action => new Run<T>(action)).ToList().ForEach(run => run.Measure()); return this; } } }
apache-2.0
C#
fd81adb595ae4c19fabcc0cb099e789c350af06a
Stop TCP listeners
Fredi/NetIRC
tests/NetIRC.Tests/ClientConnectionTests.cs
tests/NetIRC.Tests/ClientConnectionTests.cs
using NetIRC.Extensions; using System.IO; using System.Net; using System.Net.Sockets; using System.Threading.Tasks; using Xunit; namespace NetIRC.Tests { public class ClientConnectionTests { private static User FakeUser = new User("test", "test"); [Fact] public async Task WhenConnecting_ClientShouldSendRegistrationMessages() { var port = 6669; var nickMessage = $"NICK {FakeUser.Nick}"; var userMessage = $"USER {FakeUser.Nick} 0 - {FakeUser.RealName}"; var tcpListener = new TcpListener(IPAddress.Loopback, port); tcpListener.Start(); using var client = new Client(FakeUser); client.ConnectAsync("localhost", port) .SafeFireAndForget(continueOnCapturedContext: false); using var server = await tcpListener.AcceptTcpClientAsync(); using var stream = new StreamReader(server.GetStream()); Assert.Equal(nickMessage, await stream.ReadLineAsync()); Assert.Equal(userMessage, await stream.ReadLineAsync()); tcpListener.Stop(); } [Fact] public async Task WhenConnectingWithPassword_ClientShouldSendPassMessage() { var port = 6670; var password = "passw0rd123"; var passMessage = $"PASS {password}"; var tcpListener = new TcpListener(IPAddress.Loopback, port); tcpListener.Start(); using var client = new Client(FakeUser, password); client.ConnectAsync("localhost", port) .SafeFireAndForget(continueOnCapturedContext: false); using var server = await tcpListener.AcceptTcpClientAsync(); using var stream = new StreamReader(server.GetStream()); Assert.Equal(passMessage, await stream.ReadLineAsync()); tcpListener.Stop(); } } }
using NetIRC.Extensions; using System.IO; using System.Net; using System.Net.Sockets; using System.Threading.Tasks; using Xunit; namespace NetIRC.Tests { public class ClientConnectionTests { private static User FakeUser = new User("test", "test"); [Fact] public async Task WhenConnecting_ClientShouldSendRegistrationMessages() { var port = 6669; var nickMessage = $"NICK {FakeUser.Nick}"; var userMessage = $"USER {FakeUser.Nick} 0 - {FakeUser.RealName}"; var tcpListener = new TcpListener(IPAddress.Loopback, port); tcpListener.Start(); using var client = new Client(FakeUser); client.ConnectAsync("localhost", port) .SafeFireAndForget(continueOnCapturedContext: false); using var server = await tcpListener.AcceptTcpClientAsync(); using var stream = new StreamReader(server.GetStream()); Assert.Equal(nickMessage, await stream.ReadLineAsync()); Assert.Equal(userMessage, await stream.ReadLineAsync()); } [Fact] public async Task WhenConnectingWithPassword_ClientShouldSendPassMessage() { var port = 6670; var password = "passw0rd123"; var passMessage = $"PASS {password}"; var tcpListener = new TcpListener(IPAddress.Loopback, port); tcpListener.Start(); using var client = new Client(FakeUser, password); client.ConnectAsync("localhost", port) .SafeFireAndForget(continueOnCapturedContext: false); using var server = await tcpListener.AcceptTcpClientAsync(); using var stream = new StreamReader(server.GetStream()); Assert.Equal(passMessage, await stream.ReadLineAsync()); } } }
mit
C#
6758c6ed34edc10d71f8b000809ba1b875b3c766
add normals to object-cube
RealRui/SimpleScene,Namone/SimpleScene,smoothdeveloper/SimpleScene,jeske/SimpleScene
SimpleScene/Objects/SSObjectCube.cs
SimpleScene/Objects/SSObjectCube.cs
// Copyright(C) David W. Jeske, 2013 // Released to the public domain. Use, modify and relicense at will. using System; using OpenTK; using OpenTK.Graphics.OpenGL; namespace SimpleScene { public class SSObjectCube : SSObject { private void drawQuadFace(Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p3) { GL.Normal3(Vector3.Cross(p1-p0,p2-p0).Normalized()); GL.Vertex3(p0); GL.Vertex3(p1); GL.Vertex3(p2); GL.Normal3(Vector3.Cross(p2-p0,p3-p0).Normalized()); GL.Vertex3(p0); GL.Vertex3(p2); GL.Vertex3(p3); } public override void Render(ref SSRenderConfig renderConfig) { base.Render (ref renderConfig); var p0 = new Vector3 (-1, -1, 1); var p1 = new Vector3 ( 1, -1, 1); var p2 = new Vector3 ( 1, 1, 1); var p3 = new Vector3 (-1, 1, 1); var p4 = new Vector3 (-1, -1, -1); var p5 = new Vector3 ( 1, -1, -1); var p6 = new Vector3 ( 1, 1, -1); var p7 = new Vector3 (-1, 1, -1); GL.Begin(BeginMode.Triangles); GL.Color3(0.5f, 0.5f, 0.5f); drawQuadFace(p0, p1, p2, p3); drawQuadFace(p7, p6, p5, p4); drawQuadFace(p1, p0, p4, p5); drawQuadFace(p2, p1, p5, p6); drawQuadFace(p3, p2, p6, p7); drawQuadFace(p0, p3, p7, p4); GL.End(); } public SSObjectCube () : base() { } } }
// Copyright(C) David W. Jeske, 2013 // Released to the public domain. Use, modify and relicense at will. using System; using OpenTK; using OpenTK.Graphics.OpenGL; namespace SimpleScene { public class SSObjectCube : SSObject { private void drawQuadFace(Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p3) { GL.Vertex3(p0); GL.Vertex3(p1); GL.Vertex3(p2); GL.Vertex3(p0); GL.Vertex3(p2); GL.Vertex3(p3); } public override void Render(ref SSRenderConfig renderConfig) { base.Render (ref renderConfig); var p0 = new Vector3 (-1, -1, 1); var p1 = new Vector3 ( 1, -1, 1); var p2 = new Vector3 ( 1, 1, 1); var p3 = new Vector3 (-1, 1, 1); var p4 = new Vector3 (-1, -1, -1); var p5 = new Vector3 ( 1, -1, -1); var p6 = new Vector3 ( 1, 1, -1); var p7 = new Vector3 (-1, 1, -1); GL.Begin(BeginMode.Triangles); GL.Color3(0.5f, 0.5f, 0.5f); drawQuadFace(p0, p1, p2, p3); drawQuadFace(p7, p6, p5, p4); drawQuadFace(p1, p0, p4, p5); drawQuadFace(p2, p1, p5, p6); drawQuadFace(p3, p2, p6, p7); drawQuadFace(p0, p3, p7, p4); GL.End(); } public SSObjectCube () : base() { } } }
apache-2.0
C#
7a260cb3cc9ec19ffd0007b04220f93ed92130c9
fix bug in SoundInfoStruct
Alexx999/SwfSharp
SwfSharp/Structs/SoundInfoStruct.cs
SwfSharp/Structs/SoundInfoStruct.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using SwfSharp.Utils; namespace SwfSharp.Structs { public class SoundInfoStruct { public bool SyncStop { get; set; } public bool SyncNoMultiple { get; set; } public bool HasEnvelope { get; set; } public bool HasLoops { get; set; } public bool HasOutPoint { get; set; } public bool HasInPoint { get; set; } public uint InPoint { get; set; } public uint OutPoint { get; set; } public ushort LoopCount { get; set; } public IList<SoundEnvelopeStruct> EnvelopeRecords { get; set; } private void FromStream(BitReader reader) { reader.ReadBits(2); SyncStop = reader.ReadBoolBit(); SyncNoMultiple = reader.ReadBoolBit(); HasEnvelope = reader.ReadBoolBit(); HasLoops = reader.ReadBoolBit(); HasOutPoint = reader.ReadBoolBit(); HasInPoint = reader.ReadBoolBit(); if (HasInPoint) { InPoint = reader.ReadUI32(); } if (HasOutPoint) { OutPoint = reader.ReadUI32(); } if (HasLoops) { LoopCount = reader.ReadUI16(); } if (HasEnvelope) { var envPoints = reader.ReadUI8(); EnvelopeRecords = new List<SoundEnvelopeStruct>(envPoints); for (int i = 0; i < envPoints; i++) { EnvelopeRecords.Add(SoundEnvelopeStruct.CreateFromStream(reader)); } } } internal static SoundInfoStruct CreateFromStream(BitReader reader) { var result = new SoundInfoStruct(); result.FromStream(reader); return result; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using SwfSharp.Utils; namespace SwfSharp.Structs { public class SoundInfoStruct { public bool SyncStop { get; set; } public bool SyncNoMultiple { get; set; } public bool HasEnvelope { get; set; } public bool HasLoops { get; set; } public bool HasOutPoint { get; set; } public bool HasInPoint { get; set; } public uint InPoint { get; set; } public uint OutPoint { get; set; } public ushort LoopCount { get; set; } public IList<SoundEnvelopeStruct> EnvelopeRecords { get; set; } private void FromStream(BitReader reader) { reader.ReadBits(2); SyncStop = reader.ReadBoolBit(); SyncNoMultiple = reader.ReadBoolBit(); HasEnvelope = reader.ReadBoolBit(); HasLoops = reader.ReadBoolBit(); HasOutPoint = reader.ReadBoolBit(); HasInPoint = reader.ReadBoolBit(); if (HasInPoint) { InPoint = reader.ReadUI32(); } if (HasOutPoint) { OutPoint = reader.ReadUI32(); } if (HasEnvelope) { var envPoints = reader.ReadUI8(); EnvelopeRecords = new List<SoundEnvelopeStruct>(envPoints); for (int i = 0; i < envPoints; i++) { EnvelopeRecords.Add(SoundEnvelopeStruct.CreateFromStream(reader)); } } } internal static SoundInfoStruct CreateFromStream(BitReader reader) { var result = new SoundInfoStruct(); result.FromStream(reader); return result; } } }
mit
C#
18c45f2a304bedfbbd41e20512e2a7637b749f00
Remove explicit private setter for bullets (#5)
ForNeVeR/TankDriver
TankDriver.App/Logic/BulletSpace.cs
TankDriver.App/Logic/BulletSpace.cs
using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using TankDriver.Models; namespace TankDriver.Logic { internal class BulletSpace { public List<Bullet> Bullets { get; } private Rectangle _bounds; private TextureStorage _textureStorage; public BulletSpace (Rectangle bounds) { Bullets = new List<Bullet> (); _bounds = bounds; } public void AddBullet (double x, double y, double heading) { var bullet = new Bullet (x, y, heading); bullet.GetModel ().LoadTextures (_textureStorage); Bullets.Add (bullet); } public void LoadTexture(TextureStorage textureStorage) { _textureStorage = textureStorage; } public void Render(SpriteBatch spriteBatch) { foreach (var bullet in Bullets) { bullet.GetModel ().Render (spriteBatch); } } public void Update(TimeSpan timeDelta) { foreach (var bullet in Bullets) { bullet.UpdatePosition (timeDelta); } Bullets.RemoveAll (delegate(Bullet bullet) { return !_bounds.Contains((Vector2) bullet.Position); }); } } }
using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using TankDriver.Models; namespace TankDriver.Logic { internal class BulletSpace { public List<Bullet> Bullets { get; private set; } private Rectangle _bounds; private TextureStorage _textureStorage; public BulletSpace (Rectangle bounds) { Bullets = new List<Bullet> (); _bounds = bounds; } public void AddBullet (double x, double y, double heading) { var bullet = new Bullet (x, y, heading); bullet.GetModel ().LoadTextures (_textureStorage); Bullets.Add (bullet); } public void LoadTexture(TextureStorage textureStorage) { _textureStorage = textureStorage; } public void Render(SpriteBatch spriteBatch) { foreach (var bullet in Bullets) { bullet.GetModel ().Render (spriteBatch); } } public void Update(TimeSpan timeDelta) { foreach (var bullet in Bullets) { bullet.UpdatePosition (timeDelta); } Bullets.RemoveAll (delegate(Bullet bullet) { return !_bounds.Contains((Vector2) bullet.Position); }); } } }
mit
C#
8c02c40e5718659c74551b3c4c656d0306f72723
Fix vxtwitter
stanriders/den0bot,stanriders/den0bot
den0bot/Modules/ModVxtwitter.cs
den0bot/Modules/ModVxtwitter.cs
// den0bot (c) StanR 2022 - MIT License using System.Linq; using Telegram.Bot.Types; using System.Threading.Tasks; using System.Text.RegularExpressions; using den0bot.Types; namespace den0bot.Modules { internal class ModVxtwitter : IModule, IReceiveAllMessages { private readonly Regex regex = new(@".+\/\/twitter\.com\/(.+)", RegexOptions.Compiled | RegexOptions.IgnoreCase); public async Task ReceiveMessage(Message message) { if (string.IsNullOrEmpty(message.Text)) return; Match regexMatch = regex.Match(message.Text); if (regexMatch.Groups.Count > 1) { var tail = regexMatch.Groups.Values.ToArray()[1]; await API.SendMessage($"https://vxtwitter.com/{tail}", message.Chat.Id, replyToId: message.MessageId); } } } }
// den0bot (c) StanR 2022 - MIT License using System; using System.Linq; using Telegram.Bot.Types; using Newtonsoft.Json.Linq; using System.Collections.Generic; using System.Threading.Tasks; using System.Text.RegularExpressions; using den0bot.Util; using den0bot.Types; namespace den0bot.Modules { internal class ModVxtwitter : IModule, IReceiveAllMessages { private readonly Regex regex = new(@".+\/\/twitter\.com\/(.+)", RegexOptions.Compiled | RegexOptions.IgnoreCase); public async Task ReceiveMessage(Message message) { if (string.IsNullOrEmpty(message.Text)) return; Match regexMatch = regex.Match(message.Text); if (regexMatch.Groups.Count > 1) { var tail = regexMatch.Groups.Values[1]; await API.SendMessage($"https://vxtwitter.com/{tail}", message.Chat.Id, replyToId: message.MessageId); } } } }
mit
C#
994b031a2def2af81abfadf093bf8c8239128f8d
Package Version Bump #CHANGE: Pseudo-change to bump package versions after weird CI deployment, just to be sure.
mfep/duality,AdamsLair/duality,BraveSirAndrew/duality,SirePi/duality,Barsonax/duality
Source/Core/Duality/CorePlugin.cs
Source/Core/Duality/CorePlugin.cs
using System; using System.Linq; using System.Reflection; namespace Duality { public abstract class CorePlugin : DualityPlugin { /// <summary> /// Called when initializing the plugin. It is guaranteed that all plugins have been loaded at this point, so /// this is the ideal place to establish communication with other plugins or load Resources that may rely on them. /// It is NOT defined whether or not other plugins have been initialized yet. /// </summary> internal protected virtual void InitPlugin() {} /// <summary> /// Called before Duality updates the game scene /// </summary> internal protected virtual void OnBeforeUpdate() {} /// <summary> /// Called after Duality updates the game scene /// </summary> internal protected virtual void OnAfterUpdate() {} /// <summary> /// Called when Dualitys <see cref="DualityApp.ExecutionContext"/> changes. /// </summary> internal protected virtual void OnExecContextChanged(DualityApp.ExecutionContext previousContext) {} } }
using System; using System.Linq; using System.Reflection; namespace Duality { public abstract class CorePlugin : DualityPlugin { /// <summary> /// Called when initializing the plugin. It is guaranteed that all plugins have been loaded at this point, so /// this is the ideal place to establish communication with other plugins or load Resources that may rely on them. /// It is NOT defined whether or not other plugins have been initialized yet. /// </summary> internal protected virtual void InitPlugin() {} /// <summary> /// Called before Duality updates the game scene /// </summary> internal protected virtual void OnBeforeUpdate() {} /// <summary> /// Called after Duality updates the game scene /// </summary> internal protected virtual void OnAfterUpdate() {} /// <summary> /// Called when Dualitys <see cref="DualityApp.ExecutionContext"/> changes. /// </summary> internal protected virtual void OnExecContextChanged(DualityApp.ExecutionContext previousContext) {} } }
mit
C#
7393e9510fcf95897db4bfaba15e92c3a46cd53f
Extend ISound
tainicom/Aether
Source/Elementary/Audio/ISound.cs
Source/Elementary/Audio/ISound.cs
#region License // Copyright 2015 Kastellanos Nikolaos // // 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 namespace tainicom.Aether.Elementary.Audio { public interface ISound: IAether { void Play(); void Play(float volume, float pitch, float pan); void Stop(); } }
#region License // Copyright 2015 Kastellanos Nikolaos // // 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 namespace tainicom.Aether.Elementary.Audio { public interface ISound: IAether { void Play(float volume, float pitch, float panning); } }
apache-2.0
C#
36bd8cdc0f3fc657a9dc0e6993005b7745df4bca
Use the correct assertion for testing null
tempodb/tempodb-net
TempoDB.Tests/src/TempoDBTests.cs
TempoDB.Tests/src/TempoDBTests.cs
using NUnit.Framework; using RestSharp; namespace TempoDB.Tests { [TestFixture] public class TempoDBTests { [Test] public void Defaults() { var tempodb = new TempoDB("key", "secret"); Assert.AreEqual("key", tempodb.Key); Assert.AreEqual("secret", tempodb.Secret); Assert.AreEqual("api.tempo-db.com", tempodb.Host); Assert.AreEqual(443, tempodb.Port); Assert.AreEqual(true, tempodb.Secure); Assert.AreEqual("v1", tempodb.Version); Assert.IsNotNull(tempodb.Client); Assert.IsInstanceOfType(typeof(RestClient), tempodb.Client); } } }
using NUnit.Framework; using RestSharp; namespace TempoDB.Tests { [TestFixture] public class TempoDBTests { [Test] public void Defaults() { var tempodb = new TempoDB("key", "secret"); Assert.AreEqual("key", tempodb.Key); Assert.AreEqual("secret", tempodb.Secret); Assert.AreEqual("api.tempo-db.com", tempodb.Host); Assert.AreEqual(443, tempodb.Port); Assert.AreEqual(true, tempodb.Secure); Assert.AreEqual("v1", tempodb.Version); Assert.AreNotEqual(null, tempodb.Client); Assert.IsInstanceOfType(typeof(RestClient), tempodb.Client); } } }
mit
C#
8b0fe71d118d2bdca5ca51dd95eaf0fadc8230c8
Add comments to code
mplacona/TwilioMakeAndReceiveCalls
TwilioMakeAndReceiveCalls/Controllers/HomeController.cs
TwilioMakeAndReceiveCalls/Controllers/HomeController.cs
using System; using System.Web.Mvc; using Twilio; using Twilio.TwiML; using Twilio.TwiML.Mvc; namespace TwilioMakeAndReceiveCalls.Controllers { public class HomeController : TwilioController { //Get: Index public ActionResult Index() { return View(); } // GET: MakeCall public ActionResult MakeCall(string id) { // Instantiate new Rest API object var client = new TwilioRestClient(Settings.AccountSid, Settings.AuthToken); client.InitiateOutboundCall(Settings.MyNumber, string.Format("+{0}", id), "http://www.televisiontunes.com/uploads/audio/Star%20Wars%20-%20The%20Imperial%20March.mp3"); return Content("The call has been is initiated"); } // Get: ReceiveCall public ActionResult ReceiveCall() { var twiml = new TwilioResponse(); return TwiML(twiml.Say("You are calling Marcos Placona").Dial(Settings.MyNumber)); } } }
using System; using System.Web.Mvc; using Twilio; using Twilio.TwiML; using Twilio.TwiML.Mvc; namespace TwilioMakeAndReceiveCalls.Controllers { public class HomeController : TwilioController { //Get: Index public ActionResult Index() { return View(); } // GET: MakeCall public ActionResult MakeCall(string id) { var client = new TwilioRestClient(Settings.AccountSid, Settings.AuthToken); client.InitiateOutboundCall(Settings.MyNumber, string.Format("+{0}", id), "http://www.televisiontunes.com/uploads/audio/Star%20Wars%20-%20The%20Imperial%20March.mp3"); return Content("The call has been is initiated"); } public ActionResult ReceiveCall() { var twiml = new TwilioResponse(); return TwiML(twiml.Say("You are calling Marcos Placona").Dial(Settings.MyNumber)); } } }
mit
C#
4696e5a1552fafdd5e94da9c03680250e2d079c7
Add README
atbyrd/Withings.NET,atbyrd/Withings.NET
Withings.Net.Specifications/When/GettingRequestToken.cs
Withings.Net.Specifications/When/GettingRequestToken.cs
using Withings.NET; using Machine.Specifications; namespace When { [Tags("Integration")] public class GettingRequestToken { static WithingsClient Subject; Because GetRequstTokenHasNotBeenCalled = () => Subject = new WithingsClient(); It ShouldHaveANullOauthToken = () => Subject.oauthToken.ShouldBeNull(); } }
using Withings.NET; using Machine.Specifications; namespace When { public class GettingRequestToken { static WithingsClient Subject; Because GetRequstTokenHasNotBeenCalled = () => Subject = new WithingsClient(); It ShouldHaveANullOauthToken = () => Subject.oauthToken.ShouldBeNull(); } }
mit
C#
ca1decec85ec5e39a0b03e3c385214b685133ac0
add StringFormat
TakeAsh/cs-WpfUtility
WpfUtility/DataGridExAttribute.cs
WpfUtility/DataGridExAttribute.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace WpfUtility { [AttributeUsage(AttributeTargets.Property)] public class DataGridExAttribute : Attribute { public DataGridExAttribute() { } public DataGridExAttribute(string header) { Header = header; } public string Header { get; set; } public bool Ignore { get; set; } public string StringFormat { get; set; } public override string ToString() { return String.Join(", ", new[] { "Header:{" + Header + "}", "Ignore:" + Ignore, "StringFormat:{" + StringFormat + "}", }); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace WpfUtility { [AttributeUsage(AttributeTargets.Property)] public class DataGridExAttribute : Attribute { public DataGridExAttribute() { } public DataGridExAttribute(string header) { Header = header; } public string Header { get; set; } public bool Ignore { get; set; } public override string ToString() { var list = new List<string>(); list.Add("Header:'" + Header + "'"); list.Add("Ignore:" + Ignore); return String.Join(", ", list); } } }
mit
C#
c88fe822ce8903d3bf69fd777e7b7ccbef9dbe4d
add sql insert user
ravjotsingh9/DBLike
DBLike/Server/DatabaseAccess/Query.SignUp.cs
DBLike/Server/DatabaseAccess/Query.SignUp.cs
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Server.DatabaseAccess { public partial class Query { // return true if user exists // thread should use this first so we can know the reason is whether user exists or sth. else public bool checkIfUserExists(string userName, SqlConnection sqlConnection) { try { SqlDataReader myReader = null; SqlCommand myCommand = new SqlCommand("select * from dbo.Users where UserName = @UserName", sqlConnection); myCommand.Parameters.AddWithValue("@UserName", userName); myReader = myCommand.ExecuteReader(); // if user exists if (myReader.Read()) { return true; } return false; } catch (Exception e) { Console.WriteLine(e.ToString()); return true; } finally { sqlConnection.Close(); } } // insert user info into db // return true if insert is succeessful // make sure if user doesn't exist by using the above function public bool insertNewUser(string userName, string psw, SqlConnection sqlConnection) { try { string sqlString = "INSERT INTO Users (UserName, Password) VALUES (@UserName, @psw)"; SqlCommand myCommand = new SqlCommand(sqlString, sqlConnection); myCommand.Parameters.AddWithValue("@UserName", userName); myCommand.Parameters.AddWithValue("@psw", psw); // insert into the db myCommand.ExecuteNonQuery(); // check if insert successfully if (checkIfUserExists(userName, sqlConnection)) { return true; } else { return false; } } catch (Exception e) { Console.WriteLine(e.ToString()); return false; } finally { sqlConnection.Close(); } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Server.DatabaseAccess { public partial class Query { // return true if user exists public bool checkIfUserExists(string userName, SqlConnection sqlConnection) { try { SqlDataReader myReader = null; SqlCommand myCommand = new SqlCommand("select * from dbo.Users where UserName = @UserName", sqlConnection); myCommand.Parameters.AddWithValue("@UserName", userName); myReader = myCommand.ExecuteReader(); // if user exists if (myReader.Read()) { return true; } return false; } catch (Exception e) { Console.WriteLine(e.ToString()); return true; } finally { sqlConnection.Close(); } } } }
apache-2.0
C#
298c429cf9fe8d793df6f9c5d093f92d9c8373d7
Create floating coin effect
LadyNatika/MazeUdacity
Assets/UdacityVR/Scripts/Coin.cs
Assets/UdacityVR/Scripts/Coin.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Coin : MonoBehaviour { //Create a reference to the CoinPoofPrefab public GameObject coinPoof; private float _basePositionY; public void Start() { _basePositionY = transform.position.y; } public void Update() { transform.position = new Vector3(transform.position.x, _basePositionY + Mathf.Sin(Time.time * 3.0f)/2, transform.position.z); } public void OnCoinClicked() { // Instantiate the CoinPoof Prefab where this coin is located GameObject.Instantiate(coinPoof, new Vector3(transform.position.x, transform.position.y, transform.position.z), transform.rotation * Quaternion.Euler(-90f, 0f, 0f)); // Make sure the poof animates vertically // Play sound // _audioSource.Play(); // Destroy this coin. Check the Unity documentation on how to use Destroy GameObject.Destroy(gameObject); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Coin : MonoBehaviour { //Create a reference to the CoinPoofPrefab public GameObject coinPoof; // public AudioClip clipClick; //private AudioSource _audioSource; // private void Awake() { // _audioSource = gameObject.GetComponent<AudioSource>(); // _audioSource.clip = clipClick; // _audioSource.playOnAwake = false; //} public void OnCoinClicked() { // Instantiate the CoinPoof Prefab where this coin is located GameObject.Instantiate(coinPoof, new Vector3(transform.position.x, transform.position.y, transform.position.z), transform.rotation * Quaternion.Euler(-90f, 0f, 0f)); // Make sure the poof animates vertically // Play sound // _audioSource.Play(); // Destroy this coin. Check the Unity documentation on how to use Destroy GameObject.Destroy(gameObject); } }
mit
C#
d0f375a87b5e5139c028b9d3000c03e9c8890b52
Update assembly info
LordMike/B2Lib
B2Lib/Properties/AssemblyInfo.cs
B2Lib/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("B2Lib")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("MBWarez")] [assembly: AssemblyProduct("B2Lib")] [assembly: AssemblyCopyright("Copyright © 2015 Michael Bisbjerg")] [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("611d9b5b-8ae1-4137-b1d4-9fbf996f704e")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.0.1.0")] [assembly: AssemblyFileVersion("0.0.1.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("B2Lib")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("B2Lib")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("611d9b5b-8ae1-4137-b1d4-9fbf996f704e")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#
07bd6a924f1999f5de0fb66374e41ece2e6d4862
Update Program.cs
mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander
Battery-Commander.Web/Program.cs
Battery-Commander.Web/Program.cs
namespace BatteryCommander.Web { using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; using Serilog; using Serilog.Core; public class Program { public static LoggingLevelSwitch LogLevel { get; } = new LoggingLevelSwitch(Serilog.Events.LogEventLevel.Information); public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } private static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder .UseSentry(dsn: "https://78e464f7456f49a98e500e78b0bb4b13@o255975.ingest.sentry.io/1447369") .UseStartup<Startup>(); }) .ConfigureLogging((context, builder) => { Log.Logger = new LoggerConfiguration() .Enrich.FromLogContext() .Enrich.WithProperty("Application", context.HostingEnvironment.ApplicationName) .Enrich.WithProperty("Environment", context.HostingEnvironment.EnvironmentName) .Enrich.WithProperty("Version", $"{typeof(Startup).Assembly.GetName().Version}") .MinimumLevel.ControlledBy(LogLevel) .CreateLogger(); builder.AddSerilog(); }); } }
namespace BatteryCommander.Web { using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Serilog; using Serilog.Core; public class Program { public static LoggingLevelSwitch LogLevel { get; } = new LoggingLevelSwitch(Serilog.Events.LogEventLevel.Information); public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } private static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder .UseSentry(dsn: "https://78e464f7456f49a98e500e78b0bb4b13@o255975.ingest.sentry.io/1447369") .UseStartup<Startup>(); }) .ConfigureLogging((context, builder) => { Log.Logger = new LoggerConfiguration() .Enrich.FromLogContext() .Enrich.WithProperty("Application", context.HostingEnvironment.ApplicationName) .Enrich.WithProperty("Environment", context.HostingEnvironment.EnvironmentName) .Enrich.WithProperty("Version", $"{typeof(Startup).Assembly.GetName().Version}") .MinimumLevel.ControlledBy(LogLevel) .CreateLogger(); builder.AddSerilog(); }); } }
mit
C#
fb067403a3aa2ad75ef32211f63e8b8b1f971243
Fix widget IDs not read only
danielchalmers/DesktopWidgets
DesktopWidgets/Classes/WidgetSettings.cs
DesktopWidgets/Classes/WidgetSettings.cs
using System.Windows; using System.Windows.Media; using DesktopWidgets.Helpers; namespace DesktopWidgets.Classes { public class WidgetSettings { public Thickness Padding { get; set; } = new Thickness(2); //public Point ScreenDpi = new Point(96, 96); public string Name { get; set; } = ""; public bool ShowName { get; set; } = true; public bool Disabled { get; set; } = false; public WidgetId ID { get; } = new WidgetId(); public FontFamily FontFamily { get; set; } = new FontFamily("Segoe UI"); public Color TextColor { get; set; } = Colors.Black; public Color BackgroundColor { get; set; } = Colors.White; public Color BorderColor { get; set; } = Colors.DimGray; public double BackgroundOpacity { get; set; } = 1; public double BorderOpacity { get; set; } = 1; public double Width { get; set; } = double.NaN; public double Height { get; set; } = double.NaN; public double MinWidth { get; set; } = double.NaN; public double MinHeight { get; set; } = double.NaN; public double MaxWidth { get; set; } = double.NaN; public double MaxHeight { get; set; } = double.NaN; public double Left { get; set; } = double.NaN; public double Top { get; set; } = double.NaN; //public int ShowDelay { get; set; } = 0; //public int HideDelay { get; set; } = 0; //public int AnimationTime { get; set; } = 150; //public int Monitor { get; set; } = -1; public int FontSize { get; set; } = 16; public bool OnTop { get; set; } = true; public bool ForceOnTop { get; set; } = true; public bool BorderEnabled { get; set; } = true; public bool SnapToScreenEdges { get; set; } = true; //public bool AnimationEase { get; set; } = true; public override string ToString() { return ID.GetName(); } } }
using System.Windows; using System.Windows.Media; using DesktopWidgets.Helpers; namespace DesktopWidgets.Classes { public class WidgetSettings { public Thickness Padding { get; set; } = new Thickness(2); //public Point ScreenDpi = new Point(96, 96); public string Name { get; set; } = ""; public bool ShowName { get; set; } = true; public bool Disabled { get; set; } = false; public WidgetId ID { get; set; } = new WidgetId(); public FontFamily FontFamily { get; set; } = new FontFamily("Segoe UI"); public Color TextColor { get; set; } = Colors.Black; public Color BackgroundColor { get; set; } = Colors.White; public Color BorderColor { get; set; } = Colors.DimGray; public double BackgroundOpacity { get; set; } = 1; public double BorderOpacity { get; set; } = 1; public double Width { get; set; } = double.NaN; public double Height { get; set; } = double.NaN; public double MinWidth { get; set; } = double.NaN; public double MinHeight { get; set; } = double.NaN; public double MaxWidth { get; set; } = double.NaN; public double MaxHeight { get; set; } = double.NaN; public double Left { get; set; } = double.NaN; public double Top { get; set; } = double.NaN; //public int ShowDelay { get; set; } = 0; //public int HideDelay { get; set; } = 0; //public int AnimationTime { get; set; } = 150; //public int Monitor { get; set; } = -1; public int FontSize { get; set; } = 16; public bool OnTop { get; set; } = true; public bool ForceOnTop { get; set; } = true; public bool BorderEnabled { get; set; } = true; public bool SnapToScreenEdges { get; set; } = true; //public bool AnimationEase { get; set; } = true; public override string ToString() { return ID.GetName(); } } }
apache-2.0
C#
4324cc9d01186a43493ab56bddd3d07d3e8e7c36
Test para comprobar qeu soporta ficheros de 55Mb.
JuanQuijanoAbad/UniversalSync,JuanQuijanoAbad/UniversalSync
Storage/Azure/StorageAzureTests/BlobTests.cs
Storage/Azure/StorageAzureTests/BlobTests.cs
using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.IO; namespace StorageAzure.Tests { [TestClass()] public class BlobTests { public Boolean Exist(string fileName) { var container = new BlobContanier().Create(); var blob = container.GetBlockBlobReference(fileName); return blob.Exists(); } [TestMethod()] public void BlobPut() { var blob = new Blob(); var objeto = File.OpenRead(@"..\..\20160514_195832.jpg"); var fileName = Path.GetFileName(objeto.Name); blob.Put(objeto); objeto.Close(); Assert.IsTrue(Exist(fileName)); } [TestMethod()] public void BlobPut_Fichero_de_55_Mb() { var blob = new Blob(); var objeto = File.OpenRead(@"..\..\20160512_194750.mp4"); var fileName = Path.GetFileName(objeto.Name); blob.Put(objeto); objeto.Close(); Assert.IsTrue(Exist(fileName)); } [TestMethod()] public void BlobGet() { var blob = new Blob(); var fileName = "20160514_195832.jpg"; var fichero = blob.Get(fileName); Assert.IsNotNull(fichero); Assert.IsTrue(fichero.Length > 0); } [TestMethod()] public void BlobDelete() { var blob = new Blob(); var fileName = "20160514_195832.jpg"; blob.Delete(fileName); Assert.IsFalse(Exist(fileName)); } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.IO; namespace StorageAzure.Tests { [TestClass()] public class BlobTests { public Boolean Exist(string fileName) { var container = new BlobContanier().Create(); var blob = container.GetBlockBlobReference(fileName); return blob.Exists(); } [TestMethod()] public void BlobPut() { var blob = new Blob(); var objeto = File.OpenRead(@"..\..\20160514_195832.jpg"); var fileName = Path.GetFileName(objeto.Name); blob.Put(objeto); objeto.Close(); Assert.IsTrue(Exist(fileName)); } [TestMethod()] public void BlobGet() { var blob = new Blob(); var fileName = "20160514_195832.jpg"; var fichero = blob.Get(fileName); Assert.IsNotNull(fichero); Assert.IsTrue(fichero.Length > 0); } [TestMethod()] public void BlobDelete() { var blob = new Blob(); var fileName = "20160514_195832.jpg"; blob.Delete(fileName); Assert.IsFalse(Exist(fileName)); } } }
mit
C#
63a0872ae3014b0c1aa9250253bc0d68f4bab0a0
Remove test code
nbarbettini/beautiful-rest-api-aspnetcore
src/BeautifulRestApi/Controllers/PeopleController.cs
src/BeautifulRestApi/Controllers/PeopleController.cs
using System; using System.Dynamic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using BeautifulRestApi.Dal; using BeautifulRestApi.Models; using BeautifulRestApi.Queries; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Options; namespace BeautifulRestApi.Controllers { [Route(Endpoint)] public class PeopleController : Controller { public const string Endpoint = "people"; private readonly BeautifulContext _context; private readonly PagedCollectionParameters _defaultPagingOptions; public PeopleController(BeautifulContext context, IOptions<PagedCollectionParameters> defaultPagingOptions) { _context = context; _defaultPagingOptions = defaultPagingOptions.Value; } [HttpGet] public async Task<IActionResult> Get(PagedCollectionParameters parameters) { var getAllQuery = new GetAllPeopleQuery(_context, Endpoint, _defaultPagingOptions); var results = await getAllQuery.Execute(parameters); // Attach form definitions for discoverability results.Forms = new[] {Form.FromModel<PersonCreateModel>(Endpoint, "POST", "create-form")}; return new ObjectResult(results); } [HttpGet] [Route("{id}")] public async Task<IActionResult> Get(string id) { var getQuery = new GetPersonQuery(_context, Endpoint); var person = await getQuery.Execute(id); return person == null ? new NotFoundResult() as ActionResult : new ObjectResult(person); } [HttpPost] public async Task<IActionResult> Post([FromBody]PersonCreateModel model) { if (!ModelState.IsValid) { return BadRequest(new { code = 400, message = ModelState.Values.First().Errors.First().ErrorMessage }); } var createQuery = new InsertPersonQuery(_context, Endpoint); var person = await createQuery.Execute(model); return new CreatedAtRouteResult("default", new { controller = Endpoint, id = (person.Meta as ResourceLink).Id}, person); } } }
using System; using System.Dynamic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using BeautifulRestApi.Dal; using BeautifulRestApi.Models; using BeautifulRestApi.Queries; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Options; namespace BeautifulRestApi.Controllers { [Route(Endpoint)] public class PeopleController : Controller { public const string Endpoint = "people"; private readonly BeautifulContext _context; private readonly PagedCollectionParameters _defaultPagingOptions; public PeopleController(BeautifulContext context, IOptions<PagedCollectionParameters> defaultPagingOptions) { _context = context; _defaultPagingOptions = defaultPagingOptions.Value; } [HttpGet] public async Task<IActionResult> Get(PagedCollectionParameters parameters) { throw new NotImplementedException(); var getAllQuery = new GetAllPeopleQuery(_context, Endpoint, _defaultPagingOptions); var results = await getAllQuery.Execute(parameters); // Attach form definitions for discoverability results.Forms = new[] {Form.FromModel<PersonCreateModel>(Endpoint, "POST", "create-form")}; return new ObjectResult(results); } [HttpGet] [Route("{id}")] public async Task<IActionResult> Get(string id) { var getQuery = new GetPersonQuery(_context, Endpoint); var person = await getQuery.Execute(id); return person == null ? new NotFoundResult() as ActionResult : new ObjectResult(person); } [HttpPost] public async Task<IActionResult> Post([FromBody]PersonCreateModel model) { if (!ModelState.IsValid) { return BadRequest(new { code = 400, message = ModelState.Values.First().Errors.First().ErrorMessage }); } var createQuery = new InsertPersonQuery(_context, Endpoint); var person = await createQuery.Execute(model); return new CreatedAtRouteResult("default", new { controller = Endpoint, id = (person.Meta as ResourceLink).Id}, person); } } }
apache-2.0
C#
5dfeacd2e5f57f2d824bc870b683746b3a6314d1
Set the version
drmohundro/Jump-Location,drmohundro/Jump-Location,tkellogg/Jump-Location
Jump.Location/Properties/AssemblyInfo.cs
Jump.Location/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Jump.Location")] [assembly: AssemblyDescription("Powershell Cmdlet to jump around")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Tim Kellogg")] [assembly: AssemblyProduct("Jump.Location")] [assembly: AssemblyCopyright("Copyright © Tim Kellogg 2012")] [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("f0e2fb34-f28f-4fd9-bbf2-0e58ec55b429")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.4.1.0")] [assembly: AssemblyFileVersion("0.4.1.0")] [assembly: InternalsVisibleTo("Jump.Location.Specs")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Jump.Location")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Hewlett-Packard")] [assembly: AssemblyProduct("Jump.Location")] [assembly: AssemblyCopyright("Copyright © Hewlett-Packard 2012")] [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("f0e2fb34-f28f-4fd9-bbf2-0e58ec55b429")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: InternalsVisibleTo("Jump.Location.Specs")]
mit
C#