doc_id
stringlengths
36
36
metadata
dict
input
stringlengths
28
4.3k
output
stringlengths
11
5.45k
20c964de-05b7-4044-9e20-d22bf952a982
{ "language": "C#" }
```c# // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using OpenTK.Graphics; using OpenTK.Input; using osu.Framework.Input; using System; namespace osu.Game.Graphics.UserInterface { /// <summary> /// A textbox which holds focus eagerly. /// </summary> public class FocusedTextBox : OsuTextBox { protected override Color4 BackgroundUnfocused => new Color4(10, 10, 10, 255); protected override Color4 BackgroundFocused => new Color4(10, 10, 10, 255); public Action Exit; private bool focus; public bool HoldFocus { get { return focus; } set { focus = value; if (!focus && HasFocus) GetContainingInputManager().ChangeFocus(null); } } protected override void OnFocus(InputState state) { base.OnFocus(state); BorderThickness = 0; } protected override bool OnKeyDown(InputState state, KeyDownEventArgs args) { if (!args.Repeat && args.Key == Key.Escape) { if (Text.Length > 0) Text = string.Empty; else Exit?.Invoke(); return true; } return base.OnKeyDown(state, args); } public override bool RequestsFocus => HoldFocus; } } ``` Add override to fix left/right arrow control
```c# // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using OpenTK.Graphics; using OpenTK.Input; using osu.Framework.Input; using System; namespace osu.Game.Graphics.UserInterface { /// <summary> /// A textbox which holds focus eagerly. /// </summary> public class FocusedTextBox : OsuTextBox { protected override Color4 BackgroundUnfocused => new Color4(10, 10, 10, 255); protected override Color4 BackgroundFocused => new Color4(10, 10, 10, 255); public Action Exit; public override bool HandleLeftRightArrows => false; private bool focus; public bool HoldFocus { get { return focus; } set { focus = value; if (!focus && HasFocus) GetContainingInputManager().ChangeFocus(null); } } protected override void OnFocus(InputState state) { base.OnFocus(state); BorderThickness = 0; } protected override bool OnKeyDown(InputState state, KeyDownEventArgs args) { if (!args.Repeat && args.Key == Key.Escape) { if (Text.Length > 0) Text = string.Empty; else Exit?.Invoke(); return true; } return base.OnKeyDown(state, args); } public override bool RequestsFocus => HoldFocus; } } ```
05ca8f27-dd7c-48cb-b3c3-8b877272520d
{ "language": "C#" }
```c# // // Copyright (c) Microsoft. 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.Reflection; using System.Resources; [assembly: AssemblyTitle("Microsoft Azure Network Management Library")] [assembly: AssemblyDescription("Provides Microsoft Azure Network management functions for managing the Microsoft Azure Network service.")] [assembly: AssemblyVersion("6.1.1.0")] [assembly: AssemblyFileVersion("6.1.1.0")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Microsoft Azure .NET SDK")] [assembly: AssemblyCopyright("Copyright (c) Microsoft Corporation")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] ``` Change assembly version to be major version
```c# // // Copyright (c) Microsoft. 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.Reflection; using System.Resources; [assembly: AssemblyTitle("Microsoft Azure Network Management Library")] [assembly: AssemblyDescription("Provides Microsoft Azure Network management functions for managing the Microsoft Azure Network service.")] [assembly: AssemblyVersion("6.0.0.0")] [assembly: AssemblyFileVersion("6.1.1.0")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Microsoft Azure .NET SDK")] [assembly: AssemblyCopyright("Copyright (c) Microsoft Corporation")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] ```
b48d2e9f-4bbd-41d2-a2b2-c6fe7caf63c1
{ "language": "C#" }
```c# using Microsoft.AspNet.Http; using Microsoft.AspNet.Http.Core; using Microsoft.AspNet.Http.Core.Collections; using Xunit; namespace MusicStore.Models { public class ShoppingCartTest { [Fact] public void GetCartId_ReturnsCartIdFromCookies() { // Arrange var cartId = "cartId_A"; var httpContext = new DefaultHttpContext(); httpContext.SetFeature<IRequestCookiesFeature>(new CookiesFeature("Session=" + cartId)); var cart = new ShoppingCart(new MusicStoreContext()); // Act var result = cart.GetCartId(httpContext); // Assert Assert.NotNull(result); Assert.Equal(cartId, result); } private class CookiesFeature : IRequestCookiesFeature { private readonly RequestCookiesCollection _cookies; public CookiesFeature(string cookiesHeader) { _cookies = new RequestCookiesCollection(); _cookies.Reparse(cookiesHeader); } public IReadableStringCollection Cookies { get { return _cookies; } } } } } ``` Handle change to cookie parser.
```c# using System.Collections.Generic; using Microsoft.AspNet.Http; using Microsoft.AspNet.Http.Core; using Microsoft.AspNet.Http.Core.Collections; using Xunit; namespace MusicStore.Models { public class ShoppingCartTest { [Fact] public void GetCartId_ReturnsCartIdFromCookies() { // Arrange var cartId = "cartId_A"; var httpContext = new DefaultHttpContext(); httpContext.SetFeature<IRequestCookiesFeature>(new CookiesFeature("Session", cartId)); var cart = new ShoppingCart(new MusicStoreContext()); // Act var result = cart.GetCartId(httpContext); // Assert Assert.NotNull(result); Assert.Equal(cartId, result); } private class CookiesFeature : IRequestCookiesFeature { private readonly IReadableStringCollection _cookies; public CookiesFeature(string key, string value) { _cookies = new ReadableStringCollection(new Dictionary<string, string[]>() { { key, new[] { value } } }); } public IReadableStringCollection Cookies { get { return _cookies; } } } } } ```
97fbb17e-9f22-443f-b323-040c254ef06f
{ "language": "C#" }
```c# using System; using System.Threading; using UnityEngine; using UnityEngine.UI; namespace PatchKit.Unity.Patcher.Licensing { public class KeyLicenseObtainer : MonoBehaviour, ILicenseObtainer { private State _state = State.None; private KeyLicense _keyLicense; private Animator _animator; public InputField KeyInputField; public GameObject ErrorMessage; private void Awake() { _animator = GetComponent<Animator>(); } private void Update() { _animator.SetBool("IsOpened", _state == State.Obtaining); ErrorMessage.SetActive(ShowError); } public void Cancel() { _state = State.Cancelled; } public void Confirm() { _keyLicense = new KeyLicense { Key = KeyInputField.text }; _state = State.Confirmed; } public bool ShowError { get; set; } ILicense ILicenseObtainer.Obtain() { _state = State.Obtaining; while (_state != State.Confirmed && _state != State.Cancelled) { Thread.Sleep(10); } if (_state == State.Cancelled) { throw new OperationCanceledException(); } return _keyLicense; } private enum State { None, Obtaining, Confirmed, Cancelled } } }``` Fix problem with invalid whitespaces and lower characters in input license key code
```c# using System; using System.Threading; using UnityEngine; using UnityEngine.UI; namespace PatchKit.Unity.Patcher.Licensing { public class KeyLicenseObtainer : MonoBehaviour, ILicenseObtainer { private State _state = State.None; private KeyLicense _keyLicense; private Animator _animator; public InputField KeyInputField; public GameObject ErrorMessage; private void Awake() { _animator = GetComponent<Animator>(); } private void Update() { _animator.SetBool("IsOpened", _state == State.Obtaining); ErrorMessage.SetActive(ShowError); } public void Cancel() { _state = State.Cancelled; } public void Confirm() { string key = KeyInputField.text; key = key.ToUpper().Trim(); _keyLicense = new KeyLicense { Key = KeyInputField.text }; _state = State.Confirmed; } public bool ShowError { get; set; } ILicense ILicenseObtainer.Obtain() { _state = State.Obtaining; while (_state != State.Confirmed && _state != State.Cancelled) { Thread.Sleep(10); } if (_state == State.Cancelled) { throw new OperationCanceledException(); } return _keyLicense; } private enum State { None, Obtaining, Confirmed, Cancelled } } }```
d50d3fb5-d57b-4ce2-b450-722638ef74e7
{ "language": "C#" }
```c# using System; namespace WorkshopManager.Forms.RequestsDatabaseView { public class RequestsDatabasePresenter { private IRequestsDatabaseView _view; public RequestsDatabasePresenter(IRequestsDatabaseView view) { _view = view; _view.Presenter = this; Init(); } public void Init() { SetActiveComboBoxDataSource(); } private void SetActiveComboBoxDataSource() { _view.ActiveDataComboBox = Enum.GetValues(typeof (RequestsCategory)); } } } ``` Revert "Added form initialization method in Presenter"
```c# namespace WorkshopManager.Forms.RequestsDatabaseView { public class RequestsDatabasePresenter { public RequestsDatabasePresenter(IRequestsDatabaseView view) { } } } ```
d0c751c0-46b2-4fad-bcb4-7d5b5c648490
{ "language": "C#" }
```c# using System; namespace KpdApps.Common.MsCrm2015 { public class BasePluginAction { public PluginState State { get; set; } public BasePluginAction(PluginState state) { State = state; } public virtual void Execute() { throw new NotImplementedException(); } } } ``` Add short link to Service
```c# using System; using Microsoft.Xrm.Sdk; namespace KpdApps.Common.MsCrm2015 { public class BasePluginAction { public PluginState State { get; set; } public IOrganizationService Service => State.Service; public BasePluginAction(PluginState state) { State = state; } public virtual void Execute() { throw new NotImplementedException(); } } } ```
ddaf311b-0fef-47de-bc21-30e136c3b110
{ "language": "C#" }
```c# namespace Cassette.Configuration { public interface IFileSearchModifier<T> { void Modify(FileSearch fileSearch); } }``` Clarify the apparently unused generic type parameter.
```c# namespace Cassette.Configuration { // ReSharper disable UnusedTypeParameter // The T type parameter makes it easy to distinguish between file search modifiers for the different type of bundles public interface IFileSearchModifier<T> where T : Bundle // ReSharper restore UnusedTypeParameter { void Modify(FileSearch fileSearch); } }```
552a62d5-fe57-4cbb-a847-ccb65ff6e57e
{ "language": "C#" }
```c# using System; namespace Glimpse.Server { public class GlimpseServerWebOptions { public bool AllowRemote { get; set; } } }``` Add option for allowed user roles
```c# using System; using System.Collections.Generic; namespace Glimpse.Server { public class GlimpseServerWebOptions { public GlimpseServerWebOptions() { AllowedUserRoles = new List<string>(); } public bool AllowRemote { get; set; } public IList<string> AllowedUserRoles { get; } } }```
897c1f02-572b-4603-a9e3-32ecbc952300
{ "language": "C#" }
```c# // 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 BenchmarkDotNet.Running; namespace osu.Game.Benchmarks { public static class Program { public static void Main(string[] args) { BenchmarkSwitcher .FromAssembly(typeof(Program).Assembly) .Run(args); } } } ``` Disable optimisations validator (in line with framework project)
```c# // 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 BenchmarkDotNet.Configs; using BenchmarkDotNet.Running; namespace osu.Game.Benchmarks { public static class Program { public static void Main(string[] args) { BenchmarkSwitcher .FromAssembly(typeof(Program).Assembly) .Run(args, DefaultConfig.Instance.WithOption(ConfigOptions.DisableOptimizationsValidator, true)); } } } ```
38f00fea-b7c2-46a1-80bc-da99156d8d48
{ "language": "C#" }
```c# // 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; using osu.Game.Beatmaps; using osu.Game.Database; using osu.Game.Rulesets; using osu.Game.Users; namespace osu.Game.Scoring { public interface IScoreInfo : IHasOnlineID<long> { User User { get; } long TotalScore { get; } int MaxCombo { get; } double Accuracy { get; } bool HasReplay { get; } DateTimeOffset Date { get; } double? PP { get; } IBeatmapInfo Beatmap { get; } IRulesetInfo Ruleset { get; } public ScoreRank Rank { get; } // Mods is currently missing from this interface as the `IMod` class has properties which can't be fulfilled by `APIMod`, // but also doesn't expose `Settings`. We can consider how to implement this in the future if required. // Statistics is also missing. This can be reconsidered once changes in serialisation have been completed. } } ``` Remove misplaced access modifier in interface specification
```c# // 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; using osu.Game.Beatmaps; using osu.Game.Database; using osu.Game.Rulesets; using osu.Game.Users; namespace osu.Game.Scoring { public interface IScoreInfo : IHasOnlineID<long> { User User { get; } long TotalScore { get; } int MaxCombo { get; } double Accuracy { get; } bool HasReplay { get; } DateTimeOffset Date { get; } double? PP { get; } IBeatmapInfo Beatmap { get; } IRulesetInfo Ruleset { get; } ScoreRank Rank { get; } // Mods is currently missing from this interface as the `IMod` class has properties which can't be fulfilled by `APIMod`, // but also doesn't expose `Settings`. We can consider how to implement this in the future if required. // Statistics is also missing. This can be reconsidered once changes in serialisation have been completed. } } ```
5979dfa1-d081-4323-886a-954f8cded790
{ "language": "C#" }
```c# // 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.Runtime.CompilerServices; // We publish our internal attributes to other sub-projects of the framework. // Note, that we omit visual tests as they are meant to test the framework // behavior "in the wild". [assembly: InternalsVisibleTo("osu.Framework.Tests")] [assembly: InternalsVisibleTo("osu.Framework.Tests.Dynamic")] ``` Declare storage permission at assembly level
```c# // 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.Runtime.CompilerServices; using Android.App; // We publish our internal attributes to other sub-projects of the framework. // Note, that we omit visual tests as they are meant to test the framework // behavior "in the wild". [assembly: InternalsVisibleTo("osu.Framework.Tests")] [assembly: InternalsVisibleTo("osu.Framework.Tests.Dynamic")] // https://docs.microsoft.com/en-us/answers/questions/182601/does-xamarinandroid-suppor-manifest-merging.html [assembly: UsesPermission(Android.Manifest.Permission.ReadExternalStorage)] ```
a6d3e824-27a7-4fcf-9d5a-744bafd92cf0
{ "language": "C#" }
```c# using System; namespace CSF.Screenplay.Scenarios { /// <summary> /// Builder service which assists in the creation of service registrations. /// </summary> public interface IServiceRegistryBuilder { /// <summary> /// Registers a service which will be used across all scenarios within a test run. /// </summary> /// <param name="instance">Instance.</param> /// <param name="name">Name.</param> /// <typeparam name="TService">The 1st type parameter.</typeparam> void RegisterSingleton<TService>(TService instance, string name = null) where TService : class; /// <summary> /// Registers a service which will be constructed afresh (using the given factory function) for /// each scenario within a test run. /// </summary> /// <param name="factory">Factory.</param> /// <param name="name">Name.</param> /// <typeparam name="TService">The 1st type parameter.</typeparam> void RegisterPerScenario<TService>(Func<IServiceResolver,TService> factory, string name = null) where TService : class; } } ``` Fix mistake in registration (method not on interface)
```c# using System; namespace CSF.Screenplay.Scenarios { /// <summary> /// Builder service which assists in the creation of service registrations. /// </summary> public interface IServiceRegistryBuilder { /// <summary> /// Registers a service which will be used across all scenarios within a test run. /// </summary> /// <param name="instance">Instance.</param> /// <param name="name">Name.</param> /// <typeparam name="TService">The 1st type parameter.</typeparam> void RegisterSingleton<TService>(TService instance, string name = null) where TService : class; /// <summary> /// Registers a service which will be used across all scenarios within a test run. /// </summary> /// <param name="initialiser">Initialiser.</param> /// <param name="name">Name.</param> /// <typeparam name="TService">The 1st type parameter.</typeparam> void RegisterSingleton<TService>(Func<TService> initialiser, string name = null) where TService : class; /// <summary> /// Registers a service which will be constructed afresh (using the given factory function) for /// each scenario within a test run. /// </summary> /// <param name="factory">Factory.</param> /// <param name="name">Name.</param> /// <typeparam name="TService">The 1st type parameter.</typeparam> void RegisterPerScenario<TService>(Func<IServiceResolver,TService> factory, string name = null) where TService : class; } } ```
d5111f7a-c686-45a0-9a0f-fbcdfad05db4
{ "language": "C#" }
```c# // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Reflection; using System.Resources; using System.Runtime.InteropServices; #if !BUILD_GENERATED_VERSION [assembly: AssemblyCompany("Microsoft Corporation.")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] #endif [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] #if !NOT_CLS_COMPLIANT [assembly: CLSCompliant(true)] #endif [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyMetadata("Serviceable", "True")] // =========================================================================== // DO NOT EDIT OR REMOVE ANYTHING BELOW THIS COMMENT. // Version numbers are automatically generated based on regular expressions. // =========================================================================== #if ASPNETODATA #if !BUILD_GENERATED_VERSION [assembly: AssemblyVersion("5.5.2.0")] // ASPNETODATA [assembly: AssemblyFileVersion("5.5.2.0")] // ASPNETODATA #endif [assembly: AssemblyProduct("Microsoft OData Web API")] #endif``` Upgrade OData WebAPI Version to 5.6.0
```c# // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Reflection; using System.Resources; using System.Runtime.InteropServices; #if !BUILD_GENERATED_VERSION [assembly: AssemblyCompany("Microsoft Corporation.")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] #endif [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] #if !NOT_CLS_COMPLIANT [assembly: CLSCompliant(true)] #endif [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyMetadata("Serviceable", "True")] // =========================================================================== // DO NOT EDIT OR REMOVE ANYTHING BELOW THIS COMMENT. // Version numbers are automatically generated based on regular expressions. // =========================================================================== #if ASPNETODATA #if !BUILD_GENERATED_VERSION [assembly: AssemblyVersion("5.6.0.0")] // ASPNETODATA [assembly: AssemblyFileVersion("5.6.0.0")] // ASPNETODATA #endif [assembly: AssemblyProduct("Microsoft OData Web API")] #endif```
0c0ecaf4-9ab1-4c08-a9ae-02e4b721a9d9
{ "language": "C#" }
```c# using System; using CoreGraphics; using Foundation; using UIKit; namespace TextKitDemo { public partial class CollectionViewCell : UICollectionViewCell { public CollectionViewCell (IntPtr handle) : base (handle) { BackgroundColor = UIColor.DarkGray; Layer.CornerRadius = 5; UIApplication.Notifications.ObserveContentSizeCategoryChanged (delegate { CalculateAndSetFonts (); }); } public void FormatCell (DemoModel demo) { containerView.Layer.CornerRadius = 2; labelView.Text = demo.Title; textView.AttributedText = demo.GetAttributedText (); CalculateAndSetFonts (); } void CalculateAndSetFonts () { const float cellTitleTextScaleFactor = 0.85f; const float cellBodyTextScaleFactor = 0.7f; UIFont cellTitleFont = Font.GetPreferredFont (labelView.Font.FontDescriptor.TextStyle, cellTitleTextScaleFactor); UIFont cellBodyFont = Font.GetPreferredFont (textView.Font.FontDescriptor.TextStyle, cellBodyTextScaleFactor); labelView.Font = cellTitleFont; textView.Font = cellBodyFont; } } } ``` Fix ctor, we must use initWithCoder when loading from a storyboard
```c# using System; using CoreGraphics; using Foundation; using UIKit; namespace TextKitDemo { public partial class CollectionViewCell : UICollectionViewCell { public CollectionViewCell (IntPtr handle) : base (handle) { Initialize (); } [Export ("initWithCoder:")] public CollectionViewCell (NSCoder coder) : base (coder) { Initialize (); } void Initialize () { BackgroundColor = UIColor.DarkGray; Layer.CornerRadius = 5; UIApplication.Notifications.ObserveContentSizeCategoryChanged (delegate { CalculateAndSetFonts (); }); } public void FormatCell (DemoModel demo) { containerView.Layer.CornerRadius = 2; labelView.Text = demo.Title; textView.AttributedText = demo.GetAttributedText (); CalculateAndSetFonts (); } void CalculateAndSetFonts () { const float cellTitleTextScaleFactor = 0.85f; const float cellBodyTextScaleFactor = 0.7f; UIFont cellTitleFont = Font.GetPreferredFont (labelView.Font.FontDescriptor.TextStyle, cellTitleTextScaleFactor); UIFont cellBodyFont = Font.GetPreferredFont (textView.Font.FontDescriptor.TextStyle, cellBodyTextScaleFactor); labelView.Font = cellTitleFont; textView.Font = cellBodyFont; } } } ```
c0729660-4929-47eb-b937-bbeb5a2ea3b7
{ "language": "C#" }
```c# using System.Threading.Tasks; using MediatR; using SFA.DAS.EmployerAccounts.Configuration; using SFA.DAS.EmployerAccounts.Interfaces; namespace SFA.DAS.EmployerAccounts.Commands.UnsubscribeProviderEmail { public class UnsubscribeProviderEmailQueryHandler : AsyncRequestHandler<UnsubscribeProviderEmailQuery> { private readonly EmployerAccountsConfiguration _configuration; private readonly IHttpService _httpService; public UnsubscribeProviderEmailQueryHandler( IHttpServiceFactory httpServiceFactory, EmployerAccountsConfiguration configuration) { _configuration = configuration; _httpService = httpServiceFactory.Create( configuration.ProviderRelationsApi.ClientId, configuration.ProviderRelationsApi.ClientSecret, configuration.ProviderRelationsApi.IdentifierUri, configuration.ProviderRelationsApi.Tenant ); } protected override async Task HandleCore(UnsubscribeProviderEmailQuery message) { var baseUrl = GetBaseUrl(); var url = $"{baseUrl}unsubscribe/{message.CorrelationId.ToString()}"; await _httpService.GetAsync(url, false); } private string GetBaseUrl() { var baseUrl = _configuration.ProviderRelationsApi.BaseUrl.EndsWith("/") ? _configuration.ProviderRelationsApi.BaseUrl : _configuration.ProviderRelationsApi.BaseUrl + "/"; return baseUrl; } } }``` Change to call new API
```c# using System.Threading.Tasks; using MediatR; using SFA.DAS.EmployerAccounts.Configuration; using SFA.DAS.EmployerAccounts.Interfaces; namespace SFA.DAS.EmployerAccounts.Commands.UnsubscribeProviderEmail { public class UnsubscribeProviderEmailQueryHandler : AsyncRequestHandler<UnsubscribeProviderEmailQuery> { private readonly EmployerAccountsConfiguration _configuration; private readonly IHttpService _httpService; public UnsubscribeProviderEmailQueryHandler( IHttpServiceFactory httpServiceFactory, EmployerAccountsConfiguration configuration) { _configuration = configuration; _httpService = httpServiceFactory.Create( configuration.ProviderRegistrationsApi.ClientId, configuration.ProviderRegistrationsApi.ClientSecret, configuration.ProviderRegistrationsApi.IdentifierUri, configuration.ProviderRegistrationsApi.Tenant ); } protected override async Task HandleCore(UnsubscribeProviderEmailQuery message) { var baseUrl = GetBaseUrl(); var url = $"{baseUrl}api/unsubscribe/{message.CorrelationId.ToString()}"; await _httpService.GetAsync(url, false); } private string GetBaseUrl() { var baseUrl = _configuration.ProviderRegistrationsApi.BaseUrl.EndsWith("/") ? _configuration.ProviderRegistrationsApi.BaseUrl : _configuration.ProviderRegistrationsApi.BaseUrl + "/"; return baseUrl; } } }```
089d94cf-bd9c-44b9-b2f1-6c73ba1fe6c6
{ "language": "C#" }
```c# using System; namespace Dotnet.Microservice.Health { /// <summary> /// Represents a health check response /// </summary> public struct HealthResponse { public readonly bool IsHealthy; public readonly string Message; private HealthResponse(bool isHealthy, string statusMessage) { IsHealthy = isHealthy; Message = statusMessage; } public static HealthResponse Healthy() { return Healthy("OK"); } public static HealthResponse Healthy(string message) { return new HealthResponse(true, message); } public static HealthResponse Unhealthy() { return Unhealthy("FAILED"); } public static HealthResponse Unhealthy(string message) { return new HealthResponse(false, message); } public static HealthResponse Unhealthy(Exception exception) { var message = $"EXCEPTION: {exception.GetType().Name}, {exception.Message}"; return new HealthResponse(false, message); } } } ``` Allow the status to be any object instead of just a string.
```c# using System; namespace Dotnet.Microservice.Health { /// <summary> /// Represents a health check response /// </summary> public struct HealthResponse { public readonly bool IsHealthy; public readonly object Response; private HealthResponse(bool isHealthy, object statusObject) { IsHealthy = isHealthy; Response = statusObject; } public static HealthResponse Healthy() { return Healthy("OK"); } public static HealthResponse Healthy(object response) { return new HealthResponse(true, response); } public static HealthResponse Unhealthy() { return Unhealthy("FAILED"); } public static HealthResponse Unhealthy(object response) { return new HealthResponse(false, response); } public static HealthResponse Unhealthy(Exception exception) { var message = $"EXCEPTION: {exception.GetType().Name}, {exception.Message}"; return new HealthResponse(false, message); } } } ```
fdb36d20-055f-419c-90e3-9c0431eb1bb1
{ "language": "C#" }
```c# using System.IO; using NUnit.Framework; namespace BrightstarDB.InternalTests { internal static class TestPaths { public static string DataPath => Path.Combine(TestContext.CurrentContext.TestDirectory, "..\\..\\..\\BrightstarDB.Tests\\Data\\"); } } ``` Fix path to SPARQL test suite files
```c# using System.IO; using NUnit.Framework; namespace BrightstarDB.InternalTests { internal static class TestPaths { public static string DataPath => Path.Combine(TestContext.CurrentContext.TestDirectory, "..\\..\\..\\..\\BrightstarDB.Tests\\Data\\"); } } ```
f14e14ad-123a-4fe0-ac98-b2039a81b143
{ "language": "C#" }
```c# using System; using Newtonsoft.Json; namespace BmpListener.Bmp { public class BmpHeader { public BmpHeader(byte[] data) { ParseBytes(data); } public byte Version { get; private set; } [JsonIgnore] public uint Length { get; private set; } public MessageType Type { get; private set; } public void ParseBytes(byte[] data) { Version = data[0]; //if (Version != 3) //{ // throw new Exception("invalid BMP version"); //} Length = data.ToUInt32(1); Type = (MessageType) data[5]; } } }``` Move initialization logic to ctor
```c# using System; using Newtonsoft.Json; using System.Linq; using BmpListener; namespace BmpListener.Bmp { public class BmpHeader { public BmpHeader(byte[] data) { Version = data.First(); //if (Version != 3) //{ // throw new Exception("invalid BMP version"); //} Length = data.ToUInt32(1); Type = (MessageType)data.ElementAt(5); } public byte Version { get; private set; } [JsonIgnore] public uint Length { get; private set; } public MessageType Type { get; private set; } } }```
c895d7e6-3462-4aca-834c-d0762512d7eb
{ "language": "C#" }
```c# // 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. #nullable enable namespace osu.Game.Database { public interface IHasOnlineID { /// <summary> /// The server-side ID representing this instance, if one exists. -1 denotes a missing ID. /// </summary> int OnlineID { get; } } } ``` Add xmldoc mention of valid `OnlineID` values
```c# // 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. #nullable enable namespace osu.Game.Database { public interface IHasOnlineID { /// <summary> /// The server-side ID representing this instance, if one exists. Any value 0 or less denotes a missing ID. /// </summary> /// <remarks> /// Generally we use -1 when specifying "missing" in code, but values of 0 are also considered missing as the online source /// is generally a MySQL autoincrement value, which can never be 0. /// </remarks> int OnlineID { get; } } } ```
9adcb3b8-1f47-498b-9a43-fb4c9b2460b0
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace NSuperTest.Registration { public class RegistrationDiscoverer { public IEnumerable<IRegisterServers> FindRegistrations() { var type = typeof(IRegisterServers); var registries = AppDomain.CurrentDomain.GetAssemblies() .SelectMany(t => t.GetTypes()) .Where(t => type.IsAssignableFrom(t) && !t.IsInterface) .Select(t => Activator.CreateInstance(t) as IRegisterServers); return registries; } } } ``` Fix for blinking tests issue
```c# using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; namespace NSuperTest.Registration { public static class AssemblyExtensions { public static IEnumerable<Type> GetLoadableTypes(this Assembly assembly) { try { return assembly.GetTypes(); } catch (ReflectionTypeLoadException e) { return e.Types.Where(t => t != null); } } } public class RegistrationDiscoverer { public IEnumerable<IRegisterServers> FindRegistrations() { var type = typeof(IRegisterServers); var registries = AppDomain.CurrentDomain.GetAssemblies() .SelectMany(t => t.GetLoadableTypes()) .Where(t => type.IsAssignableFrom(t) && !t.IsInterface) .Select(t => Activator.CreateInstance(t) as IRegisterServers); return registries; } } } ```
1d2eb55f-16b1-4ee9-807e-8d405674e070
{ "language": "C#" }
```c# //using System; using System.Collections.Generic; using System.Dynamic; namespace Arango.Client { public class ArangoDocument { public string Handle { get; set; } public string Revision { get; set; } public dynamic JsonObject { get; set; } public ArangoDocument() { JsonObject = new ExpandoObject(); } public bool Has(string fieldName) { if (fieldName.Contains(".")) { var fields = fieldName.Split('.'); var iteration = 1; var json = (IDictionary<string, object>)JsonObject; foreach (var field in fields) { if (json.ContainsKey(field)) { if (iteration == fields.Length) { return true; } json = (IDictionary<string, object>)json[field]; iteration++; } else { return false; } } } else { return ((IDictionary<string, object>)JsonObject).ContainsKey(fieldName); } return false; } } } ``` Change document handle to id.
```c# //using System; using System.Collections.Generic; using System.Dynamic; namespace Arango.Client { public class ArangoDocument { public string ID { get; set; } public string Revision { get; set; } public dynamic JsonObject { get; set; } public ArangoDocument() { JsonObject = new ExpandoObject(); } public bool Has(string fieldName) { if (fieldName.Contains(".")) { var fields = fieldName.Split('.'); var iteration = 1; var json = (IDictionary<string, object>)JsonObject; foreach (var field in fields) { if (json.ContainsKey(field)) { if (iteration == fields.Length) { return true; } json = (IDictionary<string, object>)json[field]; iteration++; } else { return false; } } } else { return ((IDictionary<string, object>)JsonObject).ContainsKey(fieldName); } return false; } } } ```
68166aa1-d48d-460e-8fa9-90b15b13f195
{ "language": "C#" }
```c# namespace LibGit2Sharp { /// <summary> /// Git specific modes for entries. /// </summary> public enum Mode { // Inspired from http://stackoverflow.com/a/8347325/335418 /// <summary> /// 000000 file mode (the entry doesn't exist) /// </summary> Nonexistent = 0, /// <summary> /// 040000 file mode /// </summary> Directory = 0x4000, /// <summary> /// 100644 file mode /// </summary> NonExecutableFile = 0x81A4, /// <summary> /// 100664 file mode /// </summary> NonExecutableGroupWritableFile = 0x81B4, /// <summary> /// 100755 file mode /// </summary> ExecutableFile = 0x81ED, /// <summary> /// 120000 file mode /// </summary> SymbolicLink = 0xA000, /// <summary> /// 160000 file mode /// </summary> GitLink = 0xE000 } } ``` Improve documentation of 0100664 mode usage
```c# namespace LibGit2Sharp { /// <summary> /// Git specific modes for entries. /// </summary> public enum Mode { // Inspired from http://stackoverflow.com/a/8347325/335418 /// <summary> /// 000000 file mode (the entry doesn't exist) /// </summary> Nonexistent = 0, /// <summary> /// 040000 file mode /// </summary> Directory = 0x4000, /// <summary> /// 100644 file mode /// </summary> NonExecutableFile = 0x81A4, /// <summary> /// Obsolete 100664 file mode. /// <para>0100664 mode is an early Git design mistake. It's kept for /// ascendant compatibility as some <see cref="Tree"/> and /// <see cref="Repository.Index"/> entries may still bear /// this mode in some old git repositories, but it's now deprecated. /// </para> /// </summary> NonExecutableGroupWritableFile = 0x81B4, /// <summary> /// 100755 file mode /// </summary> ExecutableFile = 0x81ED, /// <summary> /// 120000 file mode /// </summary> SymbolicLink = 0xA000, /// <summary> /// 160000 file mode /// </summary> GitLink = 0xE000 } } ```
7d71db2f-71fe-47c1-a8bc-3f8226bf84ab
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Newtonsoft.Json; using PrintNodeNet.Http; namespace PrintNodeNet { public sealed class PrintNodeComputer { [JsonProperty("id")] public long Id { get; set; } [JsonProperty("name")] public string Name { get; set; } [JsonProperty("inet")] public string Inet { get; set; } [JsonProperty("inet6")] public string Inet6 { get; set; } [JsonProperty("hostName")] public string HostName { get; set; } [JsonProperty("jre")] public string Jre { get; set; } [JsonProperty("createTimeStamp")] public DateTime CreateTimeStamp { get; set; } [JsonProperty("state")] public string State { get; set; } public static async Task<IEnumerable<PrintNodeComputer>> ListAsync(PrintNodeRequestOptions options = null) { var response = await PrintNodeApiHelper.Get("/computers", options); return JsonConvert.DeserializeObject<List<PrintNodeComputer>>(response); } public static async Task<PrintNodeComputer> GetAsync(long id, PrintNodeRequestOptions options = null) { var response = await PrintNodeApiHelper.Get($"/computers/{id}", options); var list = JsonConvert.DeserializeObject<List<PrintNodeComputer>>(response); return list.FirstOrDefault(); } } } ``` Add method to get a computer’s printers
```c# using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Newtonsoft.Json; using PrintNodeNet.Http; namespace PrintNodeNet { public sealed class PrintNodeComputer { [JsonProperty("id")] public long Id { get; set; } [JsonProperty("name")] public string Name { get; set; } [JsonProperty("inet")] public string Inet { get; set; } [JsonProperty("inet6")] public string Inet6 { get; set; } [JsonProperty("hostName")] public string HostName { get; set; } [JsonProperty("jre")] public string Jre { get; set; } [JsonProperty("createTimeStamp")] public DateTime CreateTimeStamp { get; set; } [JsonProperty("state")] public string State { get; set; } public static async Task<IEnumerable<PrintNodeComputer>> ListAsync(PrintNodeRequestOptions options = null) { var response = await PrintNodeApiHelper.Get("/computers", options); return JsonConvert.DeserializeObject<List<PrintNodeComputer>>(response); } public static async Task<PrintNodeComputer> GetAsync(long id, PrintNodeRequestOptions options = null) { var response = await PrintNodeApiHelper.Get($"/computers/{id}", options); var list = JsonConvert.DeserializeObject<List<PrintNodeComputer>>(response); return list.FirstOrDefault(); } public async Task<IEnumerable<PrintNodePrinter>> ListPrinters(PrintNodeRequestOptions options = null) { var response = await PrintNodeApiHelper.Get($"/computers/{Id}/printers", options); return JsonConvert.DeserializeObject<List<PrintNodePrinter>>(response); } } } ```
420bcdb2-5986-4737-a5cc-3054c515e733
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Thinktecture.IdentityServer.Web.ViewModels { public class RelyingPartyViewModel { public int ID { get; set; } public string DisplayName { get; set; } } }``` Build edit page for enabled RPs
```c# using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Thinktecture.IdentityServer.Web.ViewModels { public class RelyingPartyViewModel { public string ID { get; set; } public string DisplayName { get; set; } public bool Enabled { get; set; } } }```
6e228d03-fc08-4429-8e72-ef539b339fda
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data; namespace dbms_objects_data { class Table { public DataTable table = new DataTable(); public Table() { } public bool insertRows(string[] listOfNames, Type[] listOfTypes) { if((listOfNames == null) || (listOfTypes == null)) { return false; } for(int i = 0; i < listOfNames.Length; i++) { table.Columns.Add(listOfNames[i], listOfTypes[i]); } return true; } } } ``` Update in creation of table
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data; namespace dbms_objects_data { class Table { public DataTable table = new DataTable(); public Table() { } public bool insertRows(string[] listOfNames, Type[] listOfTypes) { if((listOfNames == null) || (listOfTypes == null)) { return false; } if(listOfNames.Length != listOfTypes.Length) { return false; } for(int i = 0; i < listOfNames.Length; i++) { table.Columns.Add(listOfNames[i], listOfTypes[i]); } return true; } } } ```
ec0f9e90-4c9d-4967-9e28-4e673f232a56
{ "language": "C#" }
```c# /* * Copyright 2014 Dominick Baier, Brock Allen * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Thinktecture.IdentityServer.Core.Models { public class ClientSecret { public string Id { get; set; } public string Value { get; set; } public ClientSecret(string value) { Value = value; } public ClientSecret(string id, string value) { Id = id; Value = value; } } }``` Add expiration to client secret
```c# /* * Copyright 2014 Dominick Baier, Brock Allen * * 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; namespace Thinktecture.IdentityServer.Core.Models { /// <summary> /// Models a client secret with identifier and expiration /// </summary> public class ClientSecret { /// <summary> /// Gets or sets the identifier. /// </summary> /// <value> /// The identifier. /// </value> public string Id { get; set; } /// <summary> /// Gets or sets the value. /// </summary> /// <value> /// The value. /// </value> public string Value { get; set; } /// <summary> /// Gets or sets the expiration. /// </summary> /// <value> /// The expiration. /// </value> public DateTimeOffset? Expiration { get; set; } /// <summary> /// Initializes a new instance of the <see cref="ClientSecret"/> class. /// </summary> /// <param name="value">The value.</param> /// <param name="expiration">The expiration.</param> public ClientSecret(string value, DateTimeOffset? expiration = null) { Value = value; Expiration = expiration; } /// <summary> /// Initializes a new instance of the <see cref="ClientSecret"/> class. /// </summary> /// <param name="id">The identifier.</param> /// <param name="value">The value.</param> /// <param name="expiration">The expiration.</param> public ClientSecret(string id, string value, DateTimeOffset? expiration = null) { Id = id; Value = value; Expiration = expiration; } } }```
45042c82-1553-47f6-b6f9-d8cc2b77125b
{ "language": "C#" }
```c# using UnityEngine; namespace NaughtyAttributes.Test { public class ValidateInputTest : MonoBehaviour { [ValidateInput("NotZero0", "int0 must not be zero")] public int int0; private bool NotZero0(int value) { return value != 0; } public ValidateInputNest1 nest1; } [System.Serializable] public class ValidateInputNest1 { [ValidateInput("NotZero1")] [AllowNesting] // Because it's nested we need to explicitly allow nesting public int int1; private bool NotZero1(int value) { return value != 0; } public ValidateInputNest2 nest2; } [System.Serializable] public class ValidateInputNest2 { [ValidateInput("NotZero2")] [AllowNesting] // Because it's nested we need to explicitly allow nesting public int int2; private bool NotZero2(int value) { return value != 0; } } } ``` Create test for inherited private validator function
```c# using UnityEngine; namespace NaughtyAttributes.Test { public class ValidateInputTest : MonoBehaviour { [ValidateInput("NotZero0", "int0 must not be zero")] public int int0; private bool NotZero0(int value) { return value != 0; } public ValidateInputNest1 nest1; public ValidateInputInheritedNest inheritedNest; } [System.Serializable] public class ValidateInputNest1 { [ValidateInput("NotZero1")] [AllowNesting] // Because it's nested we need to explicitly allow nesting public int int1; private bool NotZero1(int value) { return value != 0; } public ValidateInputNest2 nest2; } [System.Serializable] public class ValidateInputNest2 { [ValidateInput("NotZero2")] [AllowNesting] // Because it's nested we need to explicitly allow nesting public int int2; private bool NotZero2(int value) { return value != 0; } } [System.Serializable] public class ValidateInputInheritedNest : ValidateInputNest1 { } } ```
695e31a5-0370-4698-bf2d-c8e5665b3518
{ "language": "C#" }
```c# using static System.Console; public class Counter { public Counter() { } public int Count; public Counter Increment() { Count++; return this; } } public static class Program { public static readonly Counter printCounter = new Counter(); public static void Main() { WriteLine(printCounter.Increment().Coutn); WriteLine(printCounter.Inrement().Count); } }``` Add unqualified name lookup to the MissingMemberName test
```c# using static System.Console; public class Counter { public Counter() { } public int Count; public Counter Increment() { Count++; return this; } } public static class Program { public static readonly Counter printCounter = new Counter(); public static void Main() { WriteLine(printCounter.Increment().Coutn); WriteLine(printCounter.Inrement().Count); WriteLine(printCoutner.Increment().Count); } }```
35d21971-0727-48e6-ad3d-7741535bc113
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; namespace Xtrmstep.Extractor.Core.Tests { public class FileReaderTests { const string testDataFolder = @"f:\TestData\"; [Fact(DisplayName = "Read JSON Files / One entry")] public void Should_read_an_entry() { var filePath = testDataFolder + "jsonFormat.txt"; var fileReader = new FileReader(); var values = fileReader.Read(filePath).ToArray(); Assert.Equal(1, values.Length); Assert.Equal("url_text", values[0].url); Assert.Equal("html_text", values[0].result); } [Fact(DisplayName = "Read JSON Files / Several entries")] public void Should_read_sequence() { throw new NotImplementedException(); } [Fact(DisplayName = "Read JSON Files / Big file")] public void Should_read_big_file() { throw new NotImplementedException(); } } } ``` Test for sequence in JSON
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; namespace Xtrmstep.Extractor.Core.Tests { public class FileReaderTests { const string testDataFolder = @"c:\TestData\"; [Fact(DisplayName = "Read JSON Files / One entry")] public void Should_read_an_entry() { var filePath = testDataFolder + "jsonFormat.txt"; var fileReader = new FileReader(); var values = fileReader.Read(filePath).ToArray(); Assert.Equal(1, values.Length); Assert.Equal("url_text", values[0].url); Assert.Equal("html_text", values[0].result); } [Fact(DisplayName = "Read JSON Files / Several entries")] public void Should_read_sequence() { var filePath = testDataFolder + "jsonSequence.txt"; var fileReader = new FileReader(); var values = fileReader.Read(filePath).ToArray(); Assert.Equal(2, values.Length); Assert.Equal("url_text_1", values[0].url); Assert.Equal("html_text_1", values[0].result); Assert.Equal("url_text_2", values[1].url); Assert.Equal("html_text_2", values[1].result); } [Fact(DisplayName = "Read JSON Files / Big file")] public void Should_read_big_file() { throw new NotImplementedException(); } } } ```
e1c5e888-2c99-48d1-98da-ba385df1fdc4
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Threading; using System.Web; using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using Newtonsoft.Json; using VotingApplication.Data.Context; using VotingApplication.Web.Api.Migrations; namespace VotingApplication.Web.Api { public class WebApiApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); // Fix the infinite recursion of Session.OptionSet.Options[0].OptionSets[0].Options[0].[...] // by not populating the Option.OptionSets after already encountering Session.OptionSet GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; //Enable automatic migrations //Database.SetInitializer(new MigrateDatabaseToLatestVersion<VotingContext, Configuration>()); //new VotingContext().Database.Initialize(false); } } } ``` Revert "Force fix for new databases"
```c# using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Threading; using System.Web; using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using Newtonsoft.Json; using VotingApplication.Data.Context; using VotingApplication.Web.Api.Migrations; namespace VotingApplication.Web.Api { public class WebApiApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); // Fix the infinite recursion of Session.OptionSet.Options[0].OptionSets[0].Options[0].[...] // by not populating the Option.OptionSets after already encountering Session.OptionSet GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; //Enable automatic migrations Database.SetInitializer(new MigrateDatabaseToLatestVersion<VotingContext, Configuration>()); new VotingContext().Database.Initialize(false); } } } ```
5aa5547f-d5cc-4eb9-949b-d5e8b4acd89e
{ "language": "C#" }
```c# using Hangfire; using StructureMap; using SupportManager.Control.Infrastructure; using Topshelf; namespace SupportManager.Control { public class SupportManagerService : ServiceControl { private readonly IContainer container; private BackgroundJobServer jobServer; public SupportManagerService() { GlobalConfiguration.Configuration.UseSqlServerStorage("HangFire"); container = new Container(c => c.AddRegistry<AppRegistry>()); } public bool Start(HostControl hostControl) { jobServer = new BackgroundJobServer(GetJobServerOptions()); return true; } public bool Stop(HostControl hostControl) { jobServer.Dispose(); return true; } private BackgroundJobServerOptions GetJobServerOptions() { return new BackgroundJobServerOptions { Activator = new NestedContainerActivator(container) }; } } }``` Add recurring job for reading status
```c# using Hangfire; using StructureMap; using SupportManager.Contracts; using SupportManager.Control.Infrastructure; using Topshelf; namespace SupportManager.Control { public class SupportManagerService : ServiceControl { private readonly IContainer container; private BackgroundJobServer jobServer; public SupportManagerService() { GlobalConfiguration.Configuration.UseSqlServerStorage("HangFire"); container = new Container(c => c.AddRegistry<AppRegistry>()); } public bool Start(HostControl hostControl) { jobServer = new BackgroundJobServer(GetJobServerOptions()); RecurringJob.AddOrUpdate<IForwarder>(f => f.ReadAllTeamStatus(), Cron.Minutely); return true; } public bool Stop(HostControl hostControl) { jobServer.Dispose(); return true; } private BackgroundJobServerOptions GetJobServerOptions() { return new BackgroundJobServerOptions { Activator = new NestedContainerActivator(container) }; } } }```
ade1e05c-9911-4749-9db1-989823cde2a1
{ "language": "C#" }
```c# using NUnit.Framework; using OpenQA.Selenium; using System.Linq; namespace Vidyano.Test { [TestFixture("chrome")] [TestFixture("safari")] [TestFixture("firefox")] [TestFixture("edge")] [TestFixture("ie")] [Parallelizable(ParallelScope.Fixtures)] public class GlobalSearch: BrowserStackTestBase { public GlobalSearch(string profile): base(profile) {} [Test] public void Search() { var search = "pei"; var input = driver.FindElement(By.CssSelector("vi-menu vi-input-search > input")); input.SendKeys(search); input.SendKeys(Keys.Enter); var firstRow = driver.FindElement(By.CssSelector("vi-query-grid tr[is='vi-query-grid-table-data-row']:first-of-type")); Assert.That(firstRow, Is.Not.Null, "Unable to find first data row."); Assert.That(driver.Title.StartsWith(search), Is.True, "Invalid title after search."); var cells = firstRow.FindElements(By.TagName("vi-query-grid-cell-default")); Assert.That(cells.FirstOrDefault(c => c.Text.Contains(search)), Is.Not.Null, "No match found."); } } } ``` Make sure grid is not still initializing when verifying its data
```c# using NUnit.Framework; using OpenQA.Selenium; using System.Linq; namespace Vidyano.Test { [TestFixture("chrome")] [TestFixture("safari")] [TestFixture("firefox")] [TestFixture("edge")] [TestFixture("ie")] [Parallelizable(ParallelScope.Fixtures)] public class GlobalSearch: BrowserStackTestBase { public GlobalSearch(string profile): base(profile) {} [Test] public void Search() { var search = "pei"; var input = driver.FindElement(By.CssSelector("vi-menu vi-input-search > input")); input.SendKeys(search); input.SendKeys(Keys.Enter); Assert.That(driver.FindElement(By.CssSelector("vi-query-grid:not(.initializing)")), Is.Not.Null); var firstRow = driver.FindElement(By.CssSelector("vi-query-grid tr[is='vi-query-grid-table-data-row']:first-of-type")); Assert.That(firstRow, Is.Not.Null, "Unable to find first data row."); Assert.That(driver.Title.StartsWith(search), Is.True, "Invalid title after search."); var cells = firstRow.FindElements(By.TagName("vi-query-grid-cell-default")); Assert.That(cells.FirstOrDefault(c => c.Text.Contains(search)), Is.Not.Null, "No match found."); } } } ```
b37fed42-cf98-475b-92d3-5fd6c73405b1
{ "language": "C#" }
```c# using DocumentFormat.OpenXml; namespace ClosedXML.Utils { internal static class OpenXmlHelper { public static BooleanValue GetBooleanValue(bool value, bool defaultValue) { return value == defaultValue ? null : new BooleanValue(value); } public static bool GetBooleanValueAsBool(BooleanValue value, bool defaultValue) { return value.HasValue ? value.Value : defaultValue; } } } ``` Fix converter for possible null values.
```c# using DocumentFormat.OpenXml; namespace ClosedXML.Utils { internal static class OpenXmlHelper { public static BooleanValue GetBooleanValue(bool value, bool defaultValue) { return value == defaultValue ? null : new BooleanValue(value); } public static bool GetBooleanValueAsBool(BooleanValue value, bool defaultValue) { return (value?.HasValue ?? false) ? value.Value : defaultValue; } } } ```
cccb4ccb-3c10-4875-b8d5-a51b02183541
{ "language": "C#" }
```c# using UIKit; namespace CSharpMath.Ios.Example { public class IosMathViewController : UIViewController { public override void ViewDidLoad() { View.BackgroundColor = UIColor.White; var latexView = IosMathLabels.MathView(Rendering.Tests.MathData.ColorBox, 50); // WJWJWJ latex here latexView.ContentInsets = new UIEdgeInsets(10, 10, 10, 10); var size = latexView.SizeThatFits(new CoreGraphics.CGSize(370, 280)); latexView.Frame = new CoreGraphics.CGRect(0, 40, size.Width, size.Height); View.Add(latexView); } } }``` Use an actual available choice for LaTeX
```c# using UIKit; namespace CSharpMath.Ios.Example { public class IosMathViewController : UIViewController { public override void ViewDidLoad() { View.BackgroundColor = UIColor.White; var latexView = IosMathLabels.MathView(Rendering.Tests.MathData.IntegralColorBoxCorrect, 50); // WJWJWJ latex here latexView.ContentInsets = new UIEdgeInsets(10, 10, 10, 10); var size = latexView.SizeThatFits(new CoreGraphics.CGSize(370, 280)); latexView.Frame = new CoreGraphics.CGRect(0, 40, size.Width, size.Height); View.Add(latexView); } } } ```
9ae04181-c3b2-4b18-886b-e369f2dae05d
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Sketchball.Elements { public class Ball : PinballElement, IPhysics { private Vector2 v; private Vector2 v0; long t = 0; public Vector2 Velocity { get { return v; } set { v0 = value; t = 0; v = v0; } } public Ball() { Velocity = new Vector2(); Mass = 0.2f; Width = 60; Height = 60; } public override void Draw(System.Drawing.Graphics g) { //g.FillEllipse(Brushes.Peru, 0, 0, Width, Height); g.DrawImage(Properties.Resources.BallWithAlpha, 0, 0, Width, Height); } public override void Update(long delta) { t += delta; base.Update(delta); v = v0 + (t / 1000f) * World.Acceleration; Location += v * (delta / 1000f); } public float Mass { get; set; } } } ``` Move away from v0 approach.
```c# using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Sketchball.Elements { public class Ball : PinballElement, IPhysics { public Vector2 Velocity { get; set; } public Ball() { Velocity = new Vector2(); Mass = 0.2f; Width = 60; Height = 60; } public override void Draw(System.Drawing.Graphics g) { //g.FillEllipse(Brushes.Peru, 0, 0, Width, Height); g.DrawImage(Properties.Resources.BallWithAlpha, 0, 0, Width, Height); } public override void Update(long delta) { base.Update(delta); Velocity += World.Acceleration * (delta / 1000f); Location += Velocity * (delta / 1000f); } public float Mass { get; set; } } } ```
4f76238a-61f9-468a-bbd0-350bd728f021
{ "language": "C#" }
```c#  using System; using Mono.Addins; using Mono.Addins.Description; [assembly:Addin ("TypeScript", Namespace = "MonoDevelop", Version = "0.6", Category = "Web Development")] [assembly:AddinName ("TypeScript")] [assembly:AddinDescription ("Adds TypeScript support. Updated to use TypeScript 1.4")] [assembly:AddinDependency ("Core", "5.0")] [assembly:AddinDependency ("Ide", "5.0")] [assembly:AddinDependency ("SourceEditor2", "5.0")] [assembly:AddinDependency ("Refactoring", "5.0")] ``` Update addin info showing that addin uses TypeScript 1.5.3
```c#  using System; using Mono.Addins; using Mono.Addins.Description; [assembly:Addin ("TypeScript", Namespace = "MonoDevelop", Version = "0.6", Category = "Web Development")] [assembly:AddinName ("TypeScript")] [assembly:AddinDescription ("Adds TypeScript support. Updated to use TypeScript 1.5.3")] [assembly:AddinDependency ("Core", "5.0")] [assembly:AddinDependency ("Ide", "5.0")] [assembly:AddinDependency ("SourceEditor2", "5.0")] [assembly:AddinDependency ("Refactoring", "5.0")] ```
fff30445-7332-4b6e-8659-8ab2133a4c3c
{ "language": "C#" }
```c# using System; using Microsoft.Deployment.WindowsInstaller; namespace Wix.CustomActions { using System.IO; using System.Diagnostics; public class CustomActions { [CustomAction] public static ActionResult CloseIt(Session session) { try { Debugger.Launch(); const string fileFullPath = @"c:\KensCustomAction.txt"; if (!File.Exists(fileFullPath)) File.Create(fileFullPath); File.AppendAllText(fileFullPath, string.Format("{0}Yes, we have a hit at {1}", Environment.NewLine, DateTime.Now)); session.Log("Close DotTray!"); } catch (Exception ex) { session.Log("ERROR in custom action CloseIt {0}", ex.ToString()); return ActionResult.Failure; } return ActionResult.Success; } } } ``` Make the custom action not have to use Debugger.Launch to prove that it works.
```c# using Microsoft.Deployment.WindowsInstaller; using System; using System.IO; namespace Wix.CustomActions { public class CustomActions { [CustomAction] public static ActionResult CloseIt(Session session) { try { string fileFullPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "CustomAction.txt"); if (!File.Exists(fileFullPath)) File.Create(fileFullPath); File.AppendAllText(fileFullPath, string.Format("{0}Yes, we have a hit at {1}", Environment.NewLine, DateTime.Now)); session.Log("Close DotTray!"); } catch (Exception ex) { session.Log("ERROR in custom action CloseIt {0}", ex.ToString()); return ActionResult.Failure; } return ActionResult.Success; } } }```
dcbd457f-d200-4495-bf8e-4b55d2df1b7f
{ "language": "C#" }
```c# // 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.Framework.Bindables; using osu.Game.Beatmaps.ControlPoints; namespace osu.Game.Screens.Edit.Timing { internal class DifficultySection : Section<DifficultyControlPoint> { private SliderWithTextBoxInput<double> multiplierSlider; [BackgroundDependencyLoader] private void load() { Flow.AddRange(new[] { multiplierSlider = new SliderWithTextBoxInput<double>("Speed Multiplier") { Current = new DifficultyControlPoint().SpeedMultiplierBindable } }); } protected override void OnControlPointChanged(ValueChangedEvent<DifficultyControlPoint> point) { if (point.NewValue != null) { multiplierSlider.Current = point.NewValue.SpeedMultiplierBindable; } } protected override DifficultyControlPoint CreatePoint() { var reference = Beatmap.Value.Beatmap.ControlPointInfo.DifficultyPointAt(SelectedGroup.Value.Time); return new DifficultyControlPoint { SpeedMultiplier = reference.SpeedMultiplier, }; } } } ``` Add change handling for difficulty section
```c# // 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.Framework.Bindables; using osu.Game.Beatmaps.ControlPoints; namespace osu.Game.Screens.Edit.Timing { internal class DifficultySection : Section<DifficultyControlPoint> { private SliderWithTextBoxInput<double> multiplierSlider; [BackgroundDependencyLoader] private void load() { Flow.AddRange(new[] { multiplierSlider = new SliderWithTextBoxInput<double>("Speed Multiplier") { Current = new DifficultyControlPoint().SpeedMultiplierBindable } }); } protected override void OnControlPointChanged(ValueChangedEvent<DifficultyControlPoint> point) { if (point.NewValue != null) { multiplierSlider.Current = point.NewValue.SpeedMultiplierBindable; multiplierSlider.Current.BindValueChanged(_ => ChangeHandler?.SaveState()); } } protected override DifficultyControlPoint CreatePoint() { var reference = Beatmap.Value.Beatmap.ControlPointInfo.DifficultyPointAt(SelectedGroup.Value.Time); return new DifficultyControlPoint { SpeedMultiplier = reference.SpeedMultiplier, }; } } } ```
c387f4d9-f011-4ae1-bf75-4314eea72acd
{ "language": "C#" }
```c# namespace NEventStore { using FluentAssertions; using NEventStore.Persistence.AcceptanceTests; using NEventStore.Persistence.AcceptanceTests.BDD; using System; using Xunit; public class DefaultSerializationWireupTests { public class when_building_an_event_store_without_an_explicit_serializer : SpecificationBase { private Wireup _wireup; private Exception _exception; private IStoreEvents _eventStore; protected override void Context() { _wireup = Wireup.Init() .UsingSqlPersistence("fakeConnectionString") .WithDialect(new Persistence.Sql.SqlDialects.MsSqlDialect()); } protected override void Because() { _exception = Catch.Exception(() => { _eventStore = _wireup.Build(); }); } protected override void Cleanup() { _eventStore.Dispose(); } [Fact] public void should_not_throw_an_argument_null_exception() { _exception.GetType().Should().NotBe(typeof(ArgumentNullException)); } } } } ``` Fix assertion, need to check if it's not null first.
```c# namespace NEventStore { using FluentAssertions; using NEventStore.Persistence.AcceptanceTests; using NEventStore.Persistence.AcceptanceTests.BDD; using System; using Xunit; public class DefaultSerializationWireupTests { public class when_building_an_event_store_without_an_explicit_serializer : SpecificationBase { private Wireup _wireup; private Exception _exception; private IStoreEvents _eventStore; protected override void Context() { _wireup = Wireup.Init() .UsingSqlPersistence("fakeConnectionString") .WithDialect(new Persistence.Sql.SqlDialects.MsSqlDialect()); } protected override void Because() { _exception = Catch.Exception(() => { _eventStore = _wireup.Build(); }); } protected override void Cleanup() { _eventStore.Dispose(); } [Fact] public void should_not_throw_an_argument_null_exception() { if (_exception != null) { _exception.GetType().Should().NotBe<ArgumentNullException>(); } } } } } ```
68a33ae6-803b-48dc-94dd-7d43013c8b82
{ "language": "C#" }
```c# namespace SnappyMap.CommandLine { using System.Collections.Generic; using global::CommandLine; using global::CommandLine.Text; public class Options { [Option('s', "size", DefaultValue = "8x8", HelpText = "Set the size of the output map.")] public string Size { get; set; } [Option('l', "library", DefaultValue = "library", HelpText = "Set the directory to search for tilesets in.")] public string LibraryPath { get; set; } [Option('c', "config", DefaultValue = "config.xml", HelpText = "Set the path to the section config file.")] public string ConfigFile { get; set; } [ValueList(typeof(List<string>), MaximumElements = 2)] public IList<string> Items { get; set; } [HelpOption] public string GetUsage() { var help = new HelpText { Heading = new HeadingInfo("Snappy Map", "alpha"), Copyright = new CopyrightInfo("Armoured Fish", 2014), AddDashesToOption = true, AdditionalNewLineAfterOption = true, }; help.AddPreOptionsLine(string.Format("Usage: {0} [-s NxM] [-l <library_path>] [-c <config_file>] <input_file> [output_file]", "SnappyMap")); help.AddOptions(this); return help; } } } ``` Change library command line option
```c# namespace SnappyMap.CommandLine { using System.Collections.Generic; using global::CommandLine; using global::CommandLine.Text; public class Options { [Option('s', "size", DefaultValue = "8x8", HelpText = "Set the size of the output map.")] public string Size { get; set; } [Option('t', "tileset-dir", DefaultValue = "tilesets", HelpText = "Set the directory to search for tilesets in.")] public string LibraryPath { get; set; } [Option('c', "config", DefaultValue = "config.xml", HelpText = "Set the path to the section config file.")] public string ConfigFile { get; set; } [ValueList(typeof(List<string>), MaximumElements = 2)] public IList<string> Items { get; set; } [HelpOption] public string GetUsage() { var help = new HelpText { Heading = new HeadingInfo("Snappy Map", "alpha"), Copyright = new CopyrightInfo("Armoured Fish", 2014), AddDashesToOption = true, AdditionalNewLineAfterOption = true, }; help.AddPreOptionsLine(string.Format("Usage: {0} [-s NxM] [-l <library_path>] [-c <config_file>] <input_file> [output_file]", "SnappyMap")); help.AddOptions(this); return help; } } } ```
f0096155-60b9-47bf-a165-d43513d6bf2a
{ "language": "C#" }
```c# using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Sieve.NET.Core")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Sieve.NET.Core")] [assembly: AssemblyCopyright("Copyright © 2014")] [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("fe4a2ebf-8685-4948-87f4-56fe7d986c5a")] // 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")] ``` Update assembly to version 0.
```c# using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Sieve.NET.Core")] [assembly: AssemblyDescription("An expression-based filtering library for .NET")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Sieve.NET.Core")] [assembly: AssemblyCopyright("Copyright © 2014")] [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("fe4a2ebf-8685-4948-87f4-56fe7d986c5a")] // 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.0.0")] [assembly: AssemblyFileVersion("0.0.0.0")] ```
28ddbd62-c60b-4dca-82cf-7b027ed4d114
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using TodoPad.Models; using TodoPad.Task_Parser; namespace TodoPad.Views { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void DocumentBoxTextChanged(object sender, TextChangedEventArgs e) { RichTextBox textBox = (RichTextBox)sender; // Remove this handler so we don't trigger it when formatting. textBox.TextChanged -= DocumentBoxTextChanged; Paragraph currentParagraph = textBox.Document.Blocks.FirstBlock as Paragraph; while (currentParagraph != null) { // Get the text on this row. TextPointer start = currentParagraph.ContentStart; TextPointer end = currentParagraph.ContentEnd; TextRange currentTextRange = new TextRange(start, end); // Parse the row. Row currentRow = new Row(currentTextRange.Text); // Format the displayed text. TaskParser.FormatTextRange(currentTextRange, currentRow); currentParagraph = currentParagraph.NextBlock as Paragraph; } // Restore this handler. textBox.TextChanged += DocumentBoxTextChanged; } } } ``` Change parsing to only trigger on changed lines.
```c# using System; using System.Collections.Generic; using System.Diagnostics; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using TodoPad.Models; using TodoPad.Task_Parser; namespace TodoPad.Views { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void DocumentBoxTextChanged(object sender, TextChangedEventArgs e) { RichTextBox textBox = (RichTextBox)sender; // Remove this handler so we don't trigger it when formatting. textBox.TextChanged -= DocumentBoxTextChanged; // Get the line that was changed. foreach (TextChange currentChange in e.Changes) { TextPointer offSet = textBox.Document.ContentStart.GetPositionAtOffset(currentChange.Offset, LogicalDirection.Forward); if (offSet != null) { Paragraph currentParagraph = offSet.Paragraph; if (offSet.Parent == textBox.Document) { // Format the entire document. currentParagraph = textBox.Document.Blocks.FirstBlock as Paragraph; while (currentParagraph != null) { FormatParagraph(currentParagraph); currentParagraph = currentParagraph.NextBlock as Paragraph; } } else if (currentParagraph != null) { FormatParagraph(currentParagraph); } } } // Restore this handler. textBox.TextChanged += DocumentBoxTextChanged; } private static void FormatParagraph(Paragraph currentParagraph) { // Get the text on this row. TextPointer start = currentParagraph.ContentStart; TextPointer end = currentParagraph.ContentEnd; TextRange currentTextRange = new TextRange(start, end); // Parse the row. Row currentRow = new Row(currentTextRange.Text); // Format the displayed text. TaskParser.FormatTextRange(currentTextRange, currentRow); } } } ```
dad074d7-6a80-477c-aa69-5346d8c6a839
{ "language": "C#" }
```c# using System.Linq; using NUnit.Framework; using Xamarin.UITest; namespace MvvmLightBindings.UITest { [TestFixture(Platform.Android)] [TestFixture(Platform.iOS)] public class Tests { IApp app; Platform platform; public Tests(Platform platform) { this.platform = platform; } [SetUp] public void BeforeEachTest() { app = AppInitializer.StartApp(platform); } [Test] public void AppLaunches() { app.Repl(); } [Test] public void EnterAndSubmitText_ItAppearsInTheSubmittedTextLabel() { app.EnterText(q => q.Marked("InputMessageEntry"), "Hello from Xamarin Test Cloud"); app.Screenshot("Has entered text"); app.Tap(q => q.Marked("SubmitMessageButton")); app.Screenshot("Has taped the submit button."); Assert.IsFalse(string.IsNullOrEmpty(app.Query(q => q.Marked("SubmittedMessageLabel")).First().Text)); } } } ``` Add category to test run
```c# using System.Linq; using NUnit.Framework; using Xamarin.UITest; namespace MvvmLightBindings.UITest { [TestFixture(Platform.Android)] [TestFixture(Platform.iOS)] public class Tests { IApp app; Platform platform; public Tests(Platform platform) { this.platform = platform; } [SetUp] public void BeforeEachTest() { app = AppInitializer.StartApp(platform); } [Test] [Ignore] public void AppLaunches() { app.Repl(); } [Test] [Category("all")] public void EnterAndSubmitText_ItAppearsInTheSubmittedTextLabel() { app.EnterText(q => q.Marked("InputMessageEntry"), "Hello from Xamarin Test Cloud"); app.Screenshot("Has entered text"); app.Tap(q => q.Marked("SubmitMessageButton")); app.Screenshot("Has taped the submit button."); Assert.IsFalse(string.IsNullOrEmpty(app.Query(q => q.Marked("SubmittedMessageLabel")).First().Text)); } } } ```
0cbdb002-0bbc-4a0b-8cd1-379735c4ad52
{ "language": "C#" }
```c# using System; namespace SPAD.neXt.Interfaces.SimConnect { public interface IDataItemAttributeBase { int ItemIndex { get; set; } int ItemSize { get; set; } float ItemEpsilon { get; set; } int ItemOffset { get; set; } } public interface IDataItemBoundBase { string DatumName { get; } string UnitsName { get; } string ID { get; } } } ``` Add support for fixed structures
```c# using System; namespace SPAD.neXt.Interfaces.SimConnect { public interface IDataItemAttributeBase { int ItemIndex { get; set; } int ItemSize { get; set; } float ItemEpsilon { get; set; } int ItemOffset { get; set; } bool IsFixedSize { get; set; } } public interface IDataItemBoundBase { string DatumName { get; } string UnitsName { get; } string ID { get; } } } ```
0a23bb46-3400-4cde-a589-eac4b290d378
{ "language": "C#" }
```c# using System; using Digipost.Api.Client.Domain.Enums; namespace Digipost.Api.Client.Domain.Identify { public class IdentificationById : IIdentification { public IdentificationById(IdentificationType identificationType, string value) { IdentificationType = identificationType; Value = value; } public IdentificationType IdentificationType { get; private set; } public object Data { get { return IdentificationType; } } [Obsolete("Use IdentificationType instead. Will be removed in future versions" )] public IdentificationChoiceType IdentificationChoiceType { get { return ParseIdentificationChoiceToIdentificationChoiceType(); } } internal IdentificationChoiceType ParseIdentificationChoiceToIdentificationChoiceType() { if (IdentificationType == IdentificationType.OrganizationNumber) { return IdentificationChoiceType.OrganisationNumber; } return (IdentificationChoiceType) Enum.Parse(typeof (IdentificationChoiceType), IdentificationType.ToString(), true); } public string Value { get; set; } } } ``` Add descriptor to IgnoreCase for parsing of enum
```c# using System; using Digipost.Api.Client.Domain.Enums; namespace Digipost.Api.Client.Domain.Identify { public class IdentificationById : IIdentification { public IdentificationById(IdentificationType identificationType, string value) { IdentificationType = identificationType; Value = value; } public IdentificationType IdentificationType { get; private set; } public object Data { get { return IdentificationType; } } [Obsolete("Use IdentificationType instead. Will be removed in future versions" )] public IdentificationChoiceType IdentificationChoiceType { get { return ParseIdentificationChoiceToIdentificationChoiceType(); } } internal IdentificationChoiceType ParseIdentificationChoiceToIdentificationChoiceType() { if (IdentificationType == IdentificationType.OrganizationNumber) { return IdentificationChoiceType.OrganisationNumber; } return (IdentificationChoiceType) Enum.Parse(typeof (IdentificationChoiceType), IdentificationType.ToString(), ignoreCase: true); } public string Value { get; set; } } } ```
90e4fae9-eb2a-4daa-b5d3-ca71d6f19256
{ "language": "C#" }
```c# @model SendLogInLinkModel @{ ViewBag.Title = "Send Log In Link"; } <div class="jumbotron"> <div class="row"> <div class="col-lg-6"> <h1>Welcome to Secret Santa!</h1> @using (Html.BeginForm("LogIn", "Account", FormMethod.Post, new { role = "form", @class = "form-horizontal" })) { <fieldset> <legend>@ViewBag.Title</legend> <p> If you misplaced your log-in email, you can use this form to have another log-in link sent to you. </p> <div class="form-group"> <small>@Html.LabelFor(m => m.Email, new { @class = "control-label col-sm-4" })</small> <div class="col-sm-6"> @Html.EditorFor(m => m.Email) <small>@Html.ValidationMessageFor(m => m.Email)</small> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-default">Send Log-In Link</button> </div> </div> </fieldset> } </div> <div class="col-lg-6"> <img class="img-responsive" src="@Url.Content("~/Content/Images/santa.png")" alt="Santa" /> </div> </div> </div>``` Correct action for send log in link form
```c# @model SendLogInLinkModel @{ ViewBag.Title = "Send Log In Link"; } <div class="jumbotron"> <div class="row"> <div class="col-lg-6"> <h1>Welcome to Secret Santa!</h1> @using (Html.BeginForm("SendLogInLink", "Account", FormMethod.Post, new { role = "form", @class = "form-horizontal" })) { <fieldset> <legend>@ViewBag.Title</legend> <p> If you misplaced your log-in email, you can use this form to have another log-in link sent to you. </p> <div class="form-group"> <small>@Html.LabelFor(m => m.Email, new { @class = "control-label col-sm-4" })</small> <div class="col-sm-6"> @Html.EditorFor(m => m.Email) <small>@Html.ValidationMessageFor(m => m.Email)</small> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-default">Send Log-In Link</button> </div> </div> </fieldset> } </div> <div class="col-lg-6"> <img class="img-responsive" src="@Url.Content("~/Content/Images/santa.png")" alt="Santa" /> </div> </div> </div>```
ec1da6e4-4cf4-4ddc-b89b-47eb708022f8
{ "language": "C#" }
```c# using System; using FluentAssertions; using NUnit.Framework; using Withings.NET.Client; namespace Withings.Specifications { [TestFixture] public class DateTimeExtensionsTests { [Test] public void DoubleFromUnixTimeTest() { ((double)1491934309).FromUnixTime().Date.Should().Equals(DateTime.Parse("04/11/2017")); } [Test] public void LongFromUnixTimeTest() { ((long)1491934309).FromUnixTime().Date.Should().Equals(DateTime.Parse("04/11/2017")); } [Test] public void IntFromUnixTimeTest() { 1491934309.FromUnixTime().Date.Should().Equals(DateTime.Parse("04/11/2017")); } [Test] public void DateTimeToUnixTimeTest() { DateTime.Parse("04/11/2017").Should().Equals(1491934309); } } }``` Add Tests For DateTime Extensions
```c# using System; using FluentAssertions; using NUnit.Framework; using Withings.NET.Client; namespace Withings.Specifications { [TestFixture] public class DateTimeExtensionsTests { [Test] public void DoubleFromUnixTimeTest() { ((double)1491934309).FromUnixTime().Date.Should().Equals(DateTime.Parse("04/11/2017")); } [Test] public void LongFromUnixTimeTest() { ((long)1491934309).FromUnixTime().Date.Should().Equals(DateTime.Parse("04/11/2017")); } [Test] public void IntFromUnixTimeTest() { 1491934309.FromUnixTime().Date.Should().Equals(DateTime.Parse("04/11/2017")); } [Test] public void DateTimeToUnixTimeTest() { DateTime.Parse("04/11/2017").ToUnixTime().Should().Equals(1491934309); } } }```
3469871b-052b-49df-b9d4-3e0564ab521d
{ "language": "C#" }
```c# // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System; using System.Threading; using NUnit.Framework; using osu.Framework.Platform; namespace osu.Framework.Tests.Platform { [TestFixture] public class HeadlessGameHostTest { private class Foobar { public string Bar; } [Test] public void TestIpc() { using (var server = new HeadlessGameHost(@"server", true)) using (var client = new HeadlessGameHost(@"client", true)) { Assert.IsTrue(server.IsPrimaryInstance, @"Server wasn't able to bind"); Assert.IsFalse(client.IsPrimaryInstance, @"Client was able to bind when it shouldn't have been able to"); var serverChannel = new IpcChannel<Foobar>(server); var clientChannel = new IpcChannel<Foobar>(client); Action waitAction = () => { bool received = false; serverChannel.MessageReceived += message => { Assert.AreEqual("example", message.Bar); received = true; }; clientChannel.SendMessageAsync(new Foobar { Bar = "example" }).Wait(); while (!received) Thread.Sleep(1); }; Assert.IsTrue(waitAction.BeginInvoke(null, null).AsyncWaitHandle.WaitOne(10000), @"Message was not received in a timely fashion"); } } } } ``` Fix usage of deprecated Action.BeginInvoke()
```c# // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System; using System.Threading; using System.Threading.Tasks; using NUnit.Framework; using osu.Framework.Platform; namespace osu.Framework.Tests.Platform { [TestFixture] public class HeadlessGameHostTest { private class Foobar { public string Bar; } [Test] public void TestIpc() { using (var server = new HeadlessGameHost(@"server", true)) using (var client = new HeadlessGameHost(@"client", true)) { Assert.IsTrue(server.IsPrimaryInstance, @"Server wasn't able to bind"); Assert.IsFalse(client.IsPrimaryInstance, @"Client was able to bind when it shouldn't have been able to"); var serverChannel = new IpcChannel<Foobar>(server); var clientChannel = new IpcChannel<Foobar>(client); Action waitAction = () => { bool received = false; serverChannel.MessageReceived += message => { Assert.AreEqual("example", message.Bar); received = true; }; clientChannel.SendMessageAsync(new Foobar { Bar = "example" }).Wait(); while (!received) Thread.Sleep(1); }; Assert.IsTrue(Task.Run(waitAction).Wait(10000), @"Message was not received in a timely fashion"); } } } } ```
a234b6e8-407e-4fe9-8336-10cd26c20128
{ "language": "C#" }
```c# // 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 NUnit.Framework; using osu.Framework.Screens; using osu.Game.Screens.Menu; namespace osu.Game.Tests.Visual.Menus { [TestFixture] public class TestSceneIntroWelcome : IntroTestScene { protected override IScreen CreateScreen() => new IntroWelcome(); public TestSceneIntroWelcome() { AddAssert("check if menu music loops", () => { var menu = IntroStack?.CurrentScreen as MainMenu; if (menu == null) return false; return menu.Track.Looping; }); } } } ``` Fix "welcome" intro test failure due to no wait logic
```c# // 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 NUnit.Framework; using osu.Framework.Audio.Track; using osu.Framework.Screens; using osu.Game.Screens.Menu; namespace osu.Game.Tests.Visual.Menus { [TestFixture] public class TestSceneIntroWelcome : IntroTestScene { protected override IScreen CreateScreen() => new IntroWelcome(); public TestSceneIntroWelcome() { AddUntilStep("wait for load", () => getTrack() != null); AddAssert("check if menu music loops", () => getTrack().Looping); } private Track getTrack() => (IntroStack?.CurrentScreen as MainMenu)?.Track; } } ```
431606cd-2c1e-4e23-9a87-7cfbe758d055
{ "language": "C#" }
```c# using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Security.Permissions; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle("MongoDBDriver")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion("1.0.*")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyFile("")] [assembly: System.Runtime.InteropServices.ComVisible(false)] [assembly: CLSCompliantAttribute(true)] [assembly: InternalsVisibleTo("MongoDB.Driver.Tests")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Bson")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Bson")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, Execution = true)] ``` Revert last commit since it is currently not possible.
```c# using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Security.Permissions; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle("MongoDBDriver")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion("1.0.*")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyFile("")] [assembly: System.Runtime.InteropServices.ComVisible(false)] [assembly: CLSCompliantAttribute(true)] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Bson")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Bson")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, Execution = true)] ```
9f461bff-b33b-4944-9f16-0227145ed4e6
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; namespace SGEnviro.Utilities { public class NumberParseException : Exception { public NumberParseException(string message) { } } public class Parsing { public static void ParseFloatOrThrowException(string value, out float destination, string message) { if (!float.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out destination)) { throw new Exception(message); } } } } ``` Add method to parse ints and throw exception on failure.
```c# using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; namespace SGEnviro.Utilities { public class NumberParseException : Exception { public NumberParseException(string message) { } } public class Parsing { public static void ParseFloatOrThrowException(string value, out float destination, string message) { if (!float.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out destination)) { throw new NumberParseException(message); } } public static void ParseIntOrThrowException(string value, out int destination, string message) { if (!int.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out destination)) { throw new NumberParseException(message); } } } } ```
f5172c12-01e7-42d8-93e2-54c297f49676
{ "language": "C#" }
```c# using System; using System.Collections.Generic; namespace WendySharp { class Parrot : Command { public Parrot() { Match = new List<string> { "parrot" }; Usage = "<text>"; ArgumentMatch = "(?<text>.+)$"; HelpText = "Echo a message back to the channel."; } public override void OnCommand(CommandArguments command) { var text = command.Arguments.Groups["text"].Value; Log.WriteInfo("Parrot", "'{0}' said to '{1}': {2}", command.Event.Sender, command.Event.Recipient, text); Bootstrap.Client.Client.Message(command.Event.Recipient, string.Format("\u200B{0}", text)); } } } ``` Add max length to parrot
```c# using System; using System.Collections.Generic; namespace WendySharp { class Parrot : Command { public Parrot() { Match = new List<string> { "parrot" }; Usage = "<text>"; ArgumentMatch = "(?<text>.+)$"; HelpText = "Echo a message back to the channel."; } public override void OnCommand(CommandArguments command) { var text = command.Arguments.Groups["text"].Value; if (text.Length > 140) { command.Reply("That message is too long to be parroted."); return; } Log.WriteInfo("Parrot", "'{0}' said to '{1}': {2}", command.Event.Sender, command.Event.Recipient, text); Bootstrap.Client.Client.Message(command.Event.Recipient, string.Format("\u200B{0}", text)); } } } ```
f337cc88-81bd-4bae-9f31-42ebfade230b
{ "language": "C#" }
```c# using Ninject; using Ninject.Modules; using Ninject.Web.Common; using Raven.Client; using Raven.Client.Embedded; namespace CGO.Web.NinjectModules { public class RavenModule : NinjectModule { public override void Load() { Kernel.Bind<IDocumentStore>().ToMethod(_ => InitialiseDocumentStore()).InSingletonScope(); Kernel.Bind<IDocumentSession>().ToMethod(_ => Kernel.Get<IDocumentStore>().OpenSession()).InRequestScope(); } private static IDocumentStore InitialiseDocumentStore() { var documentStore = new EmbeddableDocumentStore { DataDirectory = "CGO.raven", UseEmbeddedHttpServer = true, Configuration = { Port = 28645 } }; documentStore.Initialize(); documentStore.InitializeProfiling(); return documentStore; } } }``` Disable Raven's Embedded HTTP server
```c# using Ninject; using Ninject.Modules; using Ninject.Web.Common; using Raven.Client; using Raven.Client.Embedded; namespace CGO.Web.NinjectModules { public class RavenModule : NinjectModule { public override void Load() { Kernel.Bind<IDocumentStore>().ToMethod(_ => InitialiseDocumentStore()).InSingletonScope(); Kernel.Bind<IDocumentSession>().ToMethod(_ => Kernel.Get<IDocumentStore>().OpenSession()).InRequestScope(); } private static IDocumentStore InitialiseDocumentStore() { var documentStore = new EmbeddableDocumentStore { DataDirectory = "CGO.raven", Configuration = { Port = 28645 } }; documentStore.Initialize(); documentStore.InitializeProfiling(); return documentStore; } } }```
c94df11e-eb7f-42c9-b93e-b27c1dcecda8
{ "language": "C#" }
```c# // 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.Statistics; using System; using System.Collections.Generic; using osu.Framework.Audio; namespace osu.Framework.Threading { public class AudioThread : GameThread { public AudioThread() : base(name: "Audio") { OnNewFrame = onNewFrame; } internal override IEnumerable<StatisticsCounterType> StatisticsCounters => new[] { StatisticsCounterType.TasksRun, StatisticsCounterType.Tracks, StatisticsCounterType.Samples, StatisticsCounterType.SChannels, StatisticsCounterType.Components, }; private readonly List<AudioManager> managers = new List<AudioManager>(); private void onNewFrame() { lock (managers) foreach (var m in managers) m.Update(); } public void RegisterManager(AudioManager manager) { lock (managers) { if (managers.Contains(manager)) throw new InvalidOperationException($"{manager} was already registered"); managers.Add(manager); } } public void UnregisterManager(AudioManager manager) { lock (managers) managers.Remove(manager); } protected override void PerformExit() { base.PerformExit(); ManagedBass.Bass.Free(); } } } ``` Use for loop to avoid nested unregister case
```c# // 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.Statistics; using System; using System.Collections.Generic; using osu.Framework.Audio; namespace osu.Framework.Threading { public class AudioThread : GameThread { public AudioThread() : base(name: "Audio") { OnNewFrame = onNewFrame; } internal override IEnumerable<StatisticsCounterType> StatisticsCounters => new[] { StatisticsCounterType.TasksRun, StatisticsCounterType.Tracks, StatisticsCounterType.Samples, StatisticsCounterType.SChannels, StatisticsCounterType.Components, }; private readonly List<AudioManager> managers = new List<AudioManager>(); private void onNewFrame() { lock (managers) { for (var i = 0; i < managers.Count; i++) { var m = managers[i]; m.Update(); } } } public void RegisterManager(AudioManager manager) { lock (managers) { if (managers.Contains(manager)) throw new InvalidOperationException($"{manager} was already registered"); managers.Add(manager); } } public void UnregisterManager(AudioManager manager) { lock (managers) managers.Remove(manager); } protected override void PerformExit() { base.PerformExit(); ManagedBass.Bass.Free(); } } } ```
8db72dfc-d640-4453-acc4-6c18fc185565
{ "language": "C#" }
```c# using System.Collections.Generic; namespace BmpListener.Serialization.Models { public class UpdateModel { public PeerHeaderModel Peer { get; set; } public string Origin { get; set; } public IList<int> AsPath { get; set; } public IList<AnnounceModel> Announce { get; set; } public IList<WithdrawModel> Withdraw { get; set; } } } ``` Add BGP and BMP message lengths to JSON
```c# using System.Collections.Generic; namespace BmpListener.Serialization.Models { public class UpdateModel { public int BmpMsgLength { get; set; } public int BgpMsgLength { get; set; } public PeerHeaderModel Peer { get; set; } public string Origin { get; set; } public IList<int> AsPath { get; set; } public IList<AnnounceModel> Announce { get; set; } public IList<WithdrawModel> Withdraw { get; set; } } } ```
75869e56-a377-43bc-98bb-40edd6100aa0
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Raven.Contrib.AspNet.Demo.Extensions { public static class UriExtensions { public static Uri AddQueryParameter(this Uri uri, KeyValuePair<string, string> pair) { return uri.AddQueryParameter(pair.Key, pair.Value); } public static Uri AddQueryParameter(this Uri uri, string key, string value) { var builder = new UriBuilder(uri); string encodedKey = Uri.EscapeDataString(key); string encodedValue = Uri.EscapeDataString(value); string queryString = String.Format("{0}={1}", encodedKey, encodedValue); builder.Query += String.IsNullOrEmpty(builder.Query) ? queryString : "&" + queryString; return builder.Uri; } } }``` Fix "double question mark" bug in UriBuilder
```c# using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Raven.Contrib.AspNet.Demo.Extensions { public static class UriExtensions { public static Uri AddQueryParameter(this Uri uri, KeyValuePair<string, string> pair) { return uri.AddQueryParameter(pair.Key, pair.Value); } public static Uri AddQueryParameter(this Uri uri, string key, string value) { var builder = new UriBuilder(uri); string encodedKey = Uri.EscapeDataString(key); string encodedValue = Uri.EscapeDataString(value); string queryString = String.Format("{0}={1}", encodedKey, encodedValue); builder.Query = String.IsNullOrEmpty(builder.Query) ? queryString : builder.Query.Substring(1) + "&" + queryString; return builder.Uri; } } } ```
0e02de8a-cf1c-4cf6-b8b7-a7a84bea93ed
{ "language": "C#" }
```c# using System.Collections.Generic; using System.Linq; using QuantConnect.Data; namespace QuantConnect.Algorithm.CSharp.Benchmarks { public class EmptyMinute400EquityAlgorithm : QCAlgorithm { public override void Initialize() { SetStartDate(2015, 09, 28); SetEndDate(2015, 10, 28); foreach (var symbol in Symbols.Equity.All.Take(400)) { AddSecurity(SecurityType.Equity, symbol); } } public override void OnData(Slice slice) { } } }``` Increase length of benchmark algorithm
```c# using System.Collections.Generic; using System.Linq; using QuantConnect.Data; namespace QuantConnect.Algorithm.CSharp.Benchmarks { public class EmptyMinute400EquityAlgorithm : QCAlgorithm { public override void Initialize() { SetStartDate(2015, 09, 28); SetEndDate(2015, 11, 13); foreach (var symbol in Symbols.Equity.All.Take(400)) { AddSecurity(SecurityType.Equity, symbol); } } public override void OnData(Slice slice) { } } }```
a3ab3837-c6c9-471f-b28b-de99b87794fe
{ "language": "C#" }
```c# <?xml version="1.0" encoding="UTF-8"?> <feed xmlns="http://www.w3.org/2005/Atom"> <title type="text"><?cs var:title ?></title> <subtitle type="text"><?cs var:title ?></subtitle> <id><?cs var:url ?>/</id> <link rel="self" href="<?cs var:url ?><?cs var:CGI.RequestURI ?>" /> <link rel="alternate" type="text/html" href="<?cs var:url ?>" /> <updated><?cs var:gendate ?></updated> <author><name><?cs var:author ?></name></author> <generator uri="<?cs var:CBlog.url ?>" version="<?cs var:CBlog.version ?>"><?cs var:CBlog.version ?></generator> <?cs each:post = Posts ?> <entry> <title type="text"><?cs var:post.title ?></title> <author><name>Bapt</name></author> <content type="html"><?cs var:html_escape(post.html) ?></content> <?cs each:tag = post.tags ?><category term="<?cs var:tag.name ?>" /><?cs /each ?> <id><?cs var:url ?>post/<?cs var:post.filename ?></id> <link rel="alternate" href="<?cs var:url ?>/post/<?cs var:post.filename ?>" /> <updated><?cs var:post.date ?></updated> <published><?cs var:post.date ?></published> </entry> <?cs /each ?> </feed> ``` Use new author var for posts too
```c# <?xml version="1.0" encoding="UTF-8"?> <feed xmlns="http://www.w3.org/2005/Atom"> <title type="text"><?cs var:title ?></title> <subtitle type="text"><?cs var:title ?></subtitle> <id><?cs var:url ?>/</id> <link rel="self" href="<?cs var:url ?><?cs var:CGI.RequestURI ?>" /> <link rel="alternate" type="text/html" href="<?cs var:url ?>" /> <updated><?cs var:gendate ?></updated> <author><name><?cs var:author ?></name></author> <generator uri="<?cs var:CBlog.url ?>" version="<?cs var:CBlog.version ?>"><?cs var:CBlog.version ?></generator> <?cs each:post = Posts ?> <entry> <title type="text"><?cs var:post.title ?></title> <author><name><?cs var:author ?></name></author> <content type="html"><?cs var:html_escape(post.html) ?></content> <?cs each:tag = post.tags ?><category term="<?cs var:tag.name ?>" /><?cs /each ?> <id><?cs var:url ?>post/<?cs var:post.filename ?></id> <link rel="alternate" href="<?cs var:url ?>/post/<?cs var:post.filename ?>" /> <updated><?cs var:post.date ?></updated> <published><?cs var:post.date ?></published> </entry> <?cs /each ?> </feed> ```
71c12b2b-26f3-4db0-8ab1-2b5b30d47f1e
{ "language": "C#" }
```c# using System; using Prism.Mvvm; using Prism.Navigation; using Reactive.Bindings; namespace BlueMonkey.ViewModels { /// <summary> /// ViewModel for MainPage. /// </summary> public class MainPageViewModel : BindableBase { /// <summary> /// NavigationService /// </summary> private readonly INavigationService _navigationService; /// <summary> /// Command of navigate next pages. /// </summary> public ReactiveCommand<string> NavigateCommand { get; } /// <summary> /// Initialize instance. /// </summary> /// <param name="navigationService"></param> public MainPageViewModel(INavigationService navigationService) { _navigationService = navigationService; NavigateCommand = new ReactiveCommand<string>(); NavigateCommand.Subscribe(Navigate); } /// <summary> /// Navigate next page. /// </summary> /// <param name="uri"></param> private void Navigate(string uri) { _navigationService.NavigateAsync(uri); } } } ``` Change to show alert if Secrets.cs is not edited
```c# using System; using Prism.Mvvm; using Prism.Navigation; using Prism.Services; using Reactive.Bindings; namespace BlueMonkey.ViewModels { /// <summary> /// ViewModel for MainPage. /// </summary> public class MainPageViewModel : BindableBase { /// <summary> /// NavigationService /// </summary> private readonly INavigationService _navigationService; /// <summary> /// The page dialog service. /// </summary> private readonly IPageDialogService _pageDialogService; /// <summary> /// Command of navigate next pages. /// </summary> public ReactiveCommand<string> NavigateCommand { get; } /// <summary> /// Initialize instance. /// </summary> /// <param name="navigationService"></param> /// <param name="pageDialogService"></param> public MainPageViewModel(INavigationService navigationService, IPageDialogService pageDialogService) { _navigationService = navigationService; _pageDialogService = pageDialogService; NavigateCommand = new ReactiveCommand<string>(); NavigateCommand.Subscribe(Navigate); } /// <summary> /// Navigate next page. /// </summary> /// <param name="uri"></param> private async void Navigate(string uri) { if (Secrets.ServerUri.Contains("your")) { await _pageDialogService.DisplayAlertAsync( "Invalid Server Uri", "You should write actual ServerUri and ConnectionString to Secrets.cs", "Close"); return; } await _navigationService.NavigateAsync(uri); } } } ```
36644811-bf20-45aa-a406-9ee88dfb8906
{ "language": "C#" }
```c# using System; using System.Linq; using System.Collections.Generic; using Realms; using System.IO; namespace Tasky.Shared { /// <summary> /// TaskDatabase uses ADO.NET to create the [Items] table and create,read,update,delete data /// </summary> public class TodoDatabase { private Realm realm; public TodoDatabase () { realm = Realm.GetInstance(); } public TodoItem CreateTodoItem() { var result = realm.CreateObject<TodoItem>(); result.ID = Guid.NewGuid().ToString(); return result; } public Transaction BeginTransaction() { return realm.BeginWrite(); } public IEnumerable<TodoItem> GetItems () { return realm.All<TodoItem>().ToList(); } public TodoItem GetItem (string id) { return realm.All<TodoItem>().single(i => i.ID == id); } public void SaveItem (TodoItem item) { // Nothing to see here... } public string DeleteItem(string id) { realm.Remove(GetItem(id)); return id; } } } ``` Fix typo in Tasky GetItem
```c# using System; using System.Linq; using System.Collections.Generic; using Realms; using System.IO; namespace Tasky.Shared { /// <summary> /// TaskDatabase uses ADO.NET to create the [Items] table and create,read,update,delete data /// </summary> public class TodoDatabase { private Realm realm; public TodoDatabase () { realm = Realm.GetInstance(); } public TodoItem CreateTodoItem() { var result = realm.CreateObject<TodoItem>(); result.ID = Guid.NewGuid().ToString(); return result; } public Transaction BeginTransaction() { return realm.BeginWrite(); } public IEnumerable<TodoItem> GetItems () { return realm.All<TodoItem>().ToList(); } public TodoItem GetItem (string id) { return realm.All<TodoItem>().Single(i => i.ID == id); } public void SaveItem (TodoItem item) { // Nothing to see here... } public string DeleteItem(string id) { realm.Remove(GetItem(id)); return id; } } } ```
1513eb8a-edc1-4289-b612-faca17057236
{ "language": "C#" }
```c# //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool // Changes to this file will be lost if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Collections.Generic; using System.Linq; using System.Text; public abstract class Component { private Vector2D position { get; set; } } ``` Use newly created vector object
```c# //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool // Changes to this file will be lost if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Collections.Generic; using System.Linq; using System.Text; public abstract class Component { private Vector position { get; set; } } ```
6a6ba08a-4288-40e4-9779-12da30c32e3f
{ "language": "C#" }
```c# using System; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace ZendeskApi_v2.Models.Targets { public class BaseTarget { [JsonProperty("id")] public long? Id { get; set; } [JsonProperty("title")] public string Title { get; set; } [JsonProperty("type")] public virtual string Type { get; } [JsonProperty("active")] public bool Active { get; set; } [JsonProperty("created_at")] [JsonConverter(typeof(IsoDateTimeConverter))] public DateTimeOffset? CreatedAt { get; set; } } }``` Test fix for appveyor CS0840
```c# using System; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace ZendeskApi_v2.Models.Targets { public class BaseTarget { [JsonProperty("id")] public long? Id { get; set; } [JsonProperty("title")] public string Title { get; set; } [JsonProperty("type")] public virtual string Type { get; private set; } [JsonProperty("active")] public bool Active { get; set; } [JsonProperty("created_at")] [JsonConverter(typeof(IsoDateTimeConverter))] public DateTimeOffset? CreatedAt { get; set; } } }```
6514f98b-3f18-482a-877c-90204db19138
{ "language": "C#" }
```c# using System; using System.Drawing; using MonoMac.Foundation; using MonoMac.AppKit; using MonoMac.ObjCRuntime; using NLog; using Radish.Support; using System.IO; namespace Radish { public partial class AppDelegate : NSApplicationDelegate { private static Logger logger = LogManager.GetCurrentClassLogger(); MainWindowController controller; public AppDelegate() { } public override void FinishedLaunching(NSObject notification) { var urlList = new NSFileManager().GetUrls(NSSearchPathDirectory.LibraryDirectory, NSSearchPathDomain.User); Preferences.Load(Path.Combine( urlList[0].Path, "Preferences", "com.rangic.Radish.json")); if (controller == null) { controller = new MainWindowController(); controller.Window.MakeKeyAndOrderFront(this); } } public override bool OpenFile(NSApplication sender, string filename) { logger.Info("OpenFile '{0}'", filename); if (controller == null) { controller = new MainWindowController(); controller.Window.MakeKeyAndOrderFront(this); } return controller.OpenFolderOrFile(filename); } } } ``` Fix issue of file opened via Finder doesn't always display.
```c# using System; using System.Drawing; using MonoMac.Foundation; using MonoMac.AppKit; using MonoMac.ObjCRuntime; using NLog; using Radish.Support; using System.IO; namespace Radish { public partial class AppDelegate : NSApplicationDelegate { private static Logger logger = LogManager.GetCurrentClassLogger(); private MainWindowController controller; private string filename; public AppDelegate() { } public override void FinishedLaunching(NSObject notification) { var urlList = new NSFileManager().GetUrls(NSSearchPathDirectory.LibraryDirectory, NSSearchPathDomain.User); Preferences.Load(Path.Combine( urlList[0].Path, "Preferences", "com.rangic.Radish.json")); controller = new MainWindowController(); controller.Window.MakeKeyAndOrderFront(this); if (filename != null) { controller.OpenFolderOrFile(filename); } } public override bool OpenFile(NSApplication sender, string filename) { if (controller == null) { this.filename = filename; logger.Info("OpenFile '{0}'", filename); return true; } return controller.OpenFolderOrFile(filename); } } } ```
48a1c8ed-f869-46e7-9b18-87225c879275
{ "language": "C#" }
```c# using System.Xml.Serialization; namespace DevelopmentInProgress.DipState { public enum DipStateActionType { [XmlEnum("1")] Entry, [XmlEnum("2")] Exit } } ``` Add action type for status
```c# using System.Xml.Serialization; namespace DevelopmentInProgress.DipState { public enum DipStateActionType { [XmlEnum("1")] Status, [XmlEnum("2")] Entry, [XmlEnum("3")] Exit } } ```
a4fad133-4535-4bfa-845e-e0d921d302de
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Moq; using NuGet.Common; using NuGet.Extensions.Nuspec; using NUnit.Framework; namespace NuGet.Extensions.Tests.Nuspec { [TestFixture] public class NuspecBuilderTests { [Test] public void AssemblyNameReplacesNullDescription() { var console = new Mock<IConsole>(); const string anyAssemblyName = "any.assembly.name"; var nullDataSource = new Mock<INuspecDataSource>().Object; var nuspecBuilder = new NuspecBuilder(anyAssemblyName); nuspecBuilder.SetMetadata(nullDataSource, new List<ManifestDependency>()); nuspecBuilder.Save(console.Object); var nuspecContents = File.ReadAllText(nuspecBuilder.FilePath); Assert.That(nuspecContents, Contains.Substring("<description>" + anyAssemblyName + "</description>")); } } } ``` Test target framework written as expected (characterise current lack of validation)
```c# using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Moq; using NuGet.Common; using NuGet.Extensions.Nuspec; using NuGet.Extensions.Tests.MSBuild; using NUnit.Framework; namespace NuGet.Extensions.Tests.Nuspec { [TestFixture] public class NuspecBuilderTests { [Test] public void AssemblyNameReplacesNullDescription() { var console = new Mock<IConsole>(); const string anyAssemblyName = "any.assembly.name"; var nullDataSource = new Mock<INuspecDataSource>().Object; var nuspecBuilder = new NuspecBuilder(anyAssemblyName); nuspecBuilder.SetMetadata(nullDataSource, new List<ManifestDependency>()); nuspecBuilder.Save(console.Object); var nuspecContents = File.ReadAllText(nuspecBuilder.FilePath); Assert.That(nuspecContents, Contains.Substring("<description>" + anyAssemblyName + "</description>")); ConsoleMock.AssertConsoleHasNoErrorsOrWarnings(console); } [TestCase("net40")] [TestCase("net35")] [TestCase("notARealTargetFramework", Description = "Characterisation: There is no validation on the target framework")] public void TargetFrameworkAppearsVerbatimInOutput(string targetFramework) { var console = new Mock<IConsole>(); var nuspecBuilder = new NuspecBuilder("anyAssemblyName"); var anyDependencies = new List<ManifestDependency>{new ManifestDependency {Id="anyDependency", Version = "0.0.0.0"}}; nuspecBuilder.SetDependencies(anyDependencies, targetFramework); nuspecBuilder.Save(console.Object); var nuspecContents = File.ReadAllText(nuspecBuilder.FilePath); var expectedAssemblyGroupStartTag = string.Format("<group targetFramework=\"{0}\">", targetFramework); Assert.That(nuspecContents, Contains.Substring(expectedAssemblyGroupStartTag)); ConsoleMock.AssertConsoleHasNoErrorsOrWarnings(console); } } } ```
b4d07ed7-e3f9-47c9-9b96-4f5dfece75cb
{ "language": "C#" }
```c# using System; using System.Linq; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; namespace Telegram.Bot.Tests.Integ.Framework { internal static class Extensions { public static User GetUser(this Update update) { switch (update.Type) { case UpdateType.Message: return update.Message.From; case UpdateType.InlineQuery: return update.InlineQuery.From; case UpdateType.CallbackQuery: return update.CallbackQuery.From; case UpdateType.PreCheckoutQuery: return update.PreCheckoutQuery.From; case UpdateType.ShippingQuery: return update.ShippingQuery.From; case UpdateType.ChosenInlineResult: return update.ChosenInlineResult.From; default: throw new ArgumentException("Unsupported update type {0}.", update.Type.ToString()); } } public static string GetTesterMentions(this UpdateReceiver updateReceiver) { return string.Join(", ", updateReceiver.AllowedUsernames.Select(username => '@' + username) ); } } } ``` Fix bug in fixture with unescaped underscore in username
```c# using System; using System.Linq; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; namespace Telegram.Bot.Tests.Integ.Framework { internal static class Extensions { public static User GetUser(this Update update) { switch (update.Type) { case UpdateType.Message: return update.Message.From; case UpdateType.InlineQuery: return update.InlineQuery.From; case UpdateType.CallbackQuery: return update.CallbackQuery.From; case UpdateType.PreCheckoutQuery: return update.PreCheckoutQuery.From; case UpdateType.ShippingQuery: return update.ShippingQuery.From; case UpdateType.ChosenInlineResult: return update.ChosenInlineResult.From; default: throw new ArgumentException("Unsupported update type {0}.", update.Type.ToString()); } } public static string GetTesterMentions(this UpdateReceiver updateReceiver) { return string.Join(", ", updateReceiver.AllowedUsernames.Select(username => $"@{username}".Replace("_", "\\_")) ); } } } ```
0f1fb1a0-925f-4dd4-a3f8-d668c6f09a15
{ "language": "C#" }
```c# using UnityEngine; using UnityEngine.Rendering; using UnityEngine.Networking; public static class UnityUtils { public static bool IsAnyKeyUp(KeyCode[] keys) { foreach (KeyCode key in keys) { if (Input.GetKeyUp(key)) return true; } return false; } public static bool IsAnyKeyDown(KeyCode[] keys) { foreach (KeyCode key in keys) { if (Input.GetKeyDown(key)) return true; } return false; } public static bool IsAnyKey(KeyCode[] keys) { foreach (KeyCode key in keys) { if (Input.GetKey(key)) return true; } return false; } public static bool IsHeadless() { return SystemInfo.graphicsDeviceType == GraphicsDeviceType.Null; } public static bool TryGetByNetId<T>(NetworkInstanceId targetNetId, out T output) where T : Component { output = null; GameObject foundObject = ClientScene.FindLocalObject(targetNetId); if (foundObject == null) return false; output = foundObject.GetComponent<T>(); if (output == null) return false; return true; } } ``` Improve network game object detection codes
```c# using UnityEngine; using UnityEngine.Rendering; using UnityEngine.Networking; public static class UnityUtils { public static bool IsAnyKeyUp(KeyCode[] keys) { foreach (KeyCode key in keys) { if (Input.GetKeyUp(key)) return true; } return false; } public static bool IsAnyKeyDown(KeyCode[] keys) { foreach (KeyCode key in keys) { if (Input.GetKeyDown(key)) return true; } return false; } public static bool IsAnyKey(KeyCode[] keys) { foreach (KeyCode key in keys) { if (Input.GetKey(key)) return true; } return false; } public static bool IsHeadless() { return SystemInfo.graphicsDeviceType == GraphicsDeviceType.Null; } public static bool TryGetGameObjectByNetId(NetworkInstanceId targetNetId, out GameObject output) { output = null; if (NetworkServer.active) output = NetworkServer.FindLocalObject(targetNetId); else output = ClientScene.FindLocalObject(targetNetId); if (output == null) return false; return true; } public static bool TryGetComponentByNetId<T>(NetworkInstanceId targetNetId, out T output) where T : Component { output = null; GameObject foundObject = null; if (TryGetGameObjectByNetId(targetNetId, out foundObject)) { output = foundObject.GetComponent<T>(); if (output == null) return false; return true; } return false; } } ```
227ff12b-4dae-4ce4-a3ab-28976c7d3a09
{ "language": "C#" }
```c# using System; using System.Diagnostics; using System.Threading; using System.Web.Routing; using SignalR.Hosting.AspNet.Routing; using SignalR.Samples.App_Start; using SignalR.Samples.Hubs.DemoHub; [assembly: WebActivator.PreApplicationStartMethod(typeof(Startup), "Start")] namespace SignalR.Samples.App_Start { public class Startup { public static void Start() { ThreadPool.QueueUserWorkItem(_ => { var connection = Global.Connections.GetConnection<Streaming.Streaming>(); var demoClients = Global.Connections.GetClients<DemoHub>(); while (true) { try { connection.Broadcast(DateTime.Now.ToString()); demoClients.fromArbitraryCode(DateTime.Now.ToString()); } catch (Exception ex) { Trace.TraceError("SignalR error thrown in Streaming broadcast: {0}", ex); } Thread.Sleep(2000); } }); RouteTable.Routes.MapConnection<Raw.Raw>("raw", "raw/{*operation}"); RouteTable.Routes.MapConnection<Streaming.Streaming>("streaming", "streaming/{*operation}"); } } }``` Change samples to use PostApplicationStart instead of pre.
```c# using System; using System.Diagnostics; using System.Threading; using System.Web.Routing; using SignalR.Hosting.AspNet.Routing; using SignalR.Samples.App_Start; using SignalR.Samples.Hubs.DemoHub; [assembly: WebActivator.PostApplicationStartMethod(typeof(Startup), "Start")] namespace SignalR.Samples.App_Start { public class Startup { public static void Start() { ThreadPool.QueueUserWorkItem(_ => { var connection = Global.Connections.GetConnection<Streaming.Streaming>(); var demoClients = Global.Connections.GetClients<DemoHub>(); while (true) { try { connection.Broadcast(DateTime.Now.ToString()); demoClients.fromArbitraryCode(DateTime.Now.ToString()); } catch (Exception ex) { Trace.TraceError("SignalR error thrown in Streaming broadcast: {0}", ex); } Thread.Sleep(2000); } }); RouteTable.Routes.MapConnection<Raw.Raw>("raw", "raw/{*operation}"); RouteTable.Routes.MapConnection<Streaming.Streaming>("streaming", "streaming/{*operation}"); } } }```
1b94d9a6-a9eb-4869-8ed7-e022e1350fdf
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace JLChnToZ.LuckyPlayer { public class DestinyTuner<T> { static DestinyTuner<T> defaultInstance; public static DestinyTuner<T> Default { get { if(defaultInstance == null) defaultInstance = new DestinyTuner<T>(); return defaultInstance; } } double fineTuneOnSuccess; public double FineTuneOnSuccess { get { return fineTuneOnSuccess; } set { if(value < 0 || value > 1) throw new ArgumentOutOfRangeException("Value must be between 0 and 1"); fineTuneOnSuccess = value; } } public DestinyTuner() { fineTuneOnSuccess = -0.0001; } public DestinyTuner(double fineTuneOnSuccess) { FineTuneOnSuccess = fineTuneOnSuccess; } protected internal virtual void TuneDestinyOnSuccess(LuckyController<T> luckyControl) { luckyControl.fineTune *= 1 + fineTuneOnSuccess; } } } ``` Remove range constraint in destiny tuner
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace JLChnToZ.LuckyPlayer { public class DestinyTuner<T> { static DestinyTuner<T> defaultInstance; public static DestinyTuner<T> Default { get { if(defaultInstance == null) defaultInstance = new DestinyTuner<T>(); return defaultInstance; } } double fineTuneOnSuccess; public double FineTuneOnSuccess { get { return fineTuneOnSuccess; } set { fineTuneOnSuccess = value; } } public DestinyTuner() { fineTuneOnSuccess = -0.0001; } public DestinyTuner(double fineTuneOnSuccess) { FineTuneOnSuccess = fineTuneOnSuccess; } protected internal virtual void TuneDestinyOnSuccess(LuckyController<T> luckyControl) { luckyControl.fineTune *= 1 + fineTuneOnSuccess; } } } ```
164cb3e9-7456-4972-9689-cdbaf833fdac
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using UnityEngine; using CNTK; using UnityEngine.Events; using System.Threading; using UnityEngine.Assertions; namespace UnityCNTK { /// <summary> /// the non-generic base class for all model /// only meant to be used for model management and GUI scripting, not in-game /// </summary> public class _Model : MonoBehaviour{ public UnityEvent OnModelLoaded; public string relativeModelPath; public Function function; private bool _isReady = false; public bool isReady { get; protected set; } /// <summary> /// Load the model automatically on start /// </summary> public bool LoadOnStart = true; protected Thread thread; public virtual void LoadModel() { Assert.IsNotNull(relativeModelPath); var absolutePath = System.IO.Path.Combine(Environment.CurrentDirectory, relativeModelPath); Thread loadThread = new Thread(() => { Debug.Log("Started thread"); try { function = Function.Load(absolutePath, CNTKManager.device); } catch (Exception e) { Debug.LogError(e); } if (OnModelLoaded != null) OnModelLoaded.Invoke(); isReady = true; Debug.Log("Model Loaded"); }); loadThread.Start(); } public void UnloadModel() { if (function != null) { function.Dispose(); } } } } ``` Make model to text asset so it can be loaded just like everything else
```c# using System; using System.Collections.Generic; using UnityEngine; using CNTK; using UnityEngine.Events; using System.Threading; using UnityEngine.Assertions; namespace UnityCNTK { /// <summary> /// the non-generic base class for all model /// only meant to be used for model management and GUI scripting, not in-game /// </summary> public class _Model : MonoBehaviour{ public UnityEvent OnModelLoaded; public TextAsset rawModel; public Function function; private bool _isReady = false; public bool isReady { get; protected set; } /// <summary> /// Load the model automatically on start /// </summary> public bool LoadOnStart = true; protected Thread thread; public virtual void LoadModel() { Assert.IsNotNull(rawModel); Debug.Log("Started thread"); try { function = Function.Load(rawModel.bytes, CNTKManager.device); } catch (Exception e) { Debug.LogError(e); } if (OnModelLoaded != null) OnModelLoaded.Invoke(); isReady = true; Debug.Log("Model Loaded : " +rawModel.name); } public void UnloadModel() { if (function != null) { function.Dispose(); } } } } ```
359b595b-bbe5-485f-8513-f66164f2b113
{ "language": "C#" }
```c# public class BuildConfig { private const string Version = "0.3.0"; public readonly string SrcDir = "./src/"; public readonly string OutDir = "./build/"; public string Target { get; private set; } public string SemVer { get; private set; } public string BuildProfile { get; private set; } public bool IsTeamCityBuild { get; private set; } public static BuildConfig Create( ICakeContext context, BuildSystem buildSystem) { if (context == null) throw new ArgumentNullException("context"); var target = context.Argument("target", "Default"); var branch = context.Argument("branch", string.Empty); var branchIsRelease = branch.ToLower() == "release"; var buildRevision = context.Argument("buildrevision", "0"); return new BuildConfig { Target = target, SemVer = Version + (branchIsRelease ? string.Empty : "-b" + buildRevision), BuildProfile = context.Argument("configuration", "Release"), IsTeamCityBuild = buildSystem.TeamCity.IsRunningOnTeamCity }; } }``` Build script, no dep on branch for now
```c# public class BuildConfig { private const string Version = "0.4.0"; private const bool IsPreRelease = true; public readonly string SrcDir = "./src/"; public readonly string OutDir = "./build/"; public string Target { get; private set; } public string SemVer { get; private set; } public string BuildProfile { get; private set; } public bool IsTeamCityBuild { get; private set; } public static BuildConfig Create( ICakeContext context, BuildSystem buildSystem) { if (context == null) throw new ArgumentNullException("context"); var target = context.Argument("target", "Default"); var buildRevision = context.Argument("buildrevision", "0"); return new BuildConfig { Target = target, SemVer = Version + (IsPreRelease ? buildRevision : "-b" + buildRevision), BuildProfile = context.Argument("configuration", "Release"), IsTeamCityBuild = buildSystem.TeamCity.IsRunningOnTeamCity }; } }```
2967b7a2-988b-4a74-83dd-de509b34aadf
{ "language": "C#" }
```c# // 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.Audio.Track; using osu.Framework.Graphics; using osu.Framework.Graphics.Shapes; using osu.Game.Beatmaps.ControlPoints; using osu.Game.Graphics.Containers; using osuTK.Graphics; namespace osu.Game.Rulesets.Osu.Skinning.Default { public class KiaiFlash : BeatSyncedContainer { private const double fade_length = 80; private const float flash_opacity = 0.25f; public KiaiFlash() { EarlyActivationMilliseconds = 80; Blending = BlendingParameters.Additive; Child = new Box { RelativeSizeAxes = Axes.Both, Colour = Color4.White, Alpha = 0f, }; } protected override void OnNewBeat(int beatIndex, TimingControlPoint timingPoint, EffectControlPoint effectPoint, ChannelAmplitudes amplitudes) { if (!effectPoint.KiaiMode) return; Child .FadeTo(flash_opacity, EarlyActivationMilliseconds, Easing.OutQuint) .Then() .FadeOut(timingPoint.BeatLength - fade_length, Easing.OutSine); } } } ``` Fix crash on super high bpm kiai sections
```c# // 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; using osu.Framework.Audio.Track; using osu.Framework.Graphics; using osu.Framework.Graphics.Shapes; using osu.Game.Beatmaps.ControlPoints; using osu.Game.Graphics.Containers; using osuTK.Graphics; namespace osu.Game.Rulesets.Osu.Skinning.Default { public class KiaiFlash : BeatSyncedContainer { private const double fade_length = 80; private const float flash_opacity = 0.25f; public KiaiFlash() { EarlyActivationMilliseconds = 80; Blending = BlendingParameters.Additive; Child = new Box { RelativeSizeAxes = Axes.Both, Colour = Color4.White, Alpha = 0f, }; } protected override void OnNewBeat(int beatIndex, TimingControlPoint timingPoint, EffectControlPoint effectPoint, ChannelAmplitudes amplitudes) { if (!effectPoint.KiaiMode) return; Child .FadeTo(flash_opacity, EarlyActivationMilliseconds, Easing.OutQuint) .Then() .FadeOut(Math.Max(0, timingPoint.BeatLength - fade_length), Easing.OutSine); } } } ```
ac86dbfb-32f6-4ae6-8158-c1d96450b339
{ "language": "C#" }
```c# using System.Collections.Generic; using System.Net.Mail; namespace StressMeasurementSystem.Models { public class Patient { #region Structs public struct Name { public string Prefix { get; set; } public string First { get; set; } public string Middle { get; set; } public string Last { get; set; } public string Suffix { get; set; } } public struct Organization { public string Company { get; set; } public string JobTitle { get; set; } } public struct PhoneNumber { public enum Type {Mobile, Home, Work, Main, WorkFax, HomeFax, Pager, Other} public string Number { get; set; } public Type T { get; set; } } public struct Email { public enum Type {Home, Work, Other} public MailAddress Address { get; set; } public Type T { get; set; } } #endregion #region Fields private Name _name; private uint _age; private Organization _organization; private List<PhoneNumber> _phoneNumbers; private List<Email> _emails; #endregion #region Constructors public Patient(Name name, uint age, Organization organization, List<PhoneNumber> phoneNumbers, List<Email> emails) { _name = name; _age = age; _organization = organization; _phoneNumbers = phoneNumbers; _emails = emails; } #endregion } } ``` Add whitespace to type enum definitions
```c# using System.Collections.Generic; using System.Net.Mail; namespace StressMeasurementSystem.Models { public class Patient { #region Structs public struct Name { public string Prefix { get; set; } public string First { get; set; } public string Middle { get; set; } public string Last { get; set; } public string Suffix { get; set; } } public struct Organization { public string Company { get; set; } public string JobTitle { get; set; } } public struct PhoneNumber { public enum Type { Mobile, Home, Work, Main, WorkFax, HomeFax, Pager, Other } public string Number { get; set; } public Type T { get; set; } } public struct Email { public enum Type { Home, Work, Other } public MailAddress Address { get; set; } public Type T { get; set; } } #endregion #region Fields private Name _name; private uint _age; private Organization _organization; private List<PhoneNumber> _phoneNumbers; private List<Email> _emails; #endregion #region Constructors public Patient(Name name, uint age, Organization organization, List<PhoneNumber> phoneNumbers, List<Email> emails) { _name = name; _age = age; _organization = organization; _phoneNumbers = phoneNumbers; _emails = emails; } #endregion } } ```
a334d7fe-0d91-4f9e-ba1e-18f18cd1f643
{ "language": "C#" }
```c# //Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>. //Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System; namespace osu.Framework.Graphics.Transformations { public interface ITransform { double Duration { get; } bool IsAlive { get; } double StartTime { get; set; } double EndTime { get; set; } void Apply(Drawable d); ITransform Clone(); ITransform CloneReverse(); void Reverse(); void Loop(double delay, int loopCount = 0); } }``` Fix incorrect default value in interface.
```c# //Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>. //Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System; namespace osu.Framework.Graphics.Transformations { public interface ITransform { double Duration { get; } bool IsAlive { get; } double StartTime { get; set; } double EndTime { get; set; } void Apply(Drawable d); ITransform Clone(); ITransform CloneReverse(); void Reverse(); void Loop(double delay, int loopCount = -1); } }```
673611e9-70fc-4141-907b-3604c9c949d4
{ "language": "C#" }
```c# namespace CommonDomain.Core { using System.Globalization; internal static class ExtensionMethods { public static string FormatWith(this string format, params object[] args) { return string.Format(CultureInfo.InvariantCulture, format ?? string.Empty, args); } public static void ThrowHandlerNotFound(this IAggregate aggregate, object eventMessage) { string exceptionMessage = "Aggregate of type '{0}' raised an event of type '{1}' but not handler could be found to handle the message." .FormatWith(aggregate.GetType().Name, eventMessage.GetType().Name); throw new HandlerForDomainEventNotFoundException(exceptionMessage); } } }``` Fix typo in exception message
```c# namespace CommonDomain.Core { using System.Globalization; internal static class ExtensionMethods { public static string FormatWith(this string format, params object[] args) { return string.Format(CultureInfo.InvariantCulture, format ?? string.Empty, args); } public static void ThrowHandlerNotFound(this IAggregate aggregate, object eventMessage) { string exceptionMessage = "Aggregate of type '{0}' raised an event of type '{1}' but no handler could be found to handle the message." .FormatWith(aggregate.GetType().Name, eventMessage.GetType().Name); throw new HandlerForDomainEventNotFoundException(exceptionMessage); } } }```
8866888a-4376-44ab-a062-f0d663237e87
{ "language": "C#" }
```c# using System; using System.IO; using System.Linq; using System.Reflection; namespace PCSBingMapKeyManager { class Program { private const string NewKeySwitch = "/a:"; static void Main(string[] args) { if (args.Length > 1 || args.Any() && !args[0].StartsWith(NewKeySwitch)) { Usage(); return; } var manager = new BingMapKeyManager(); if (!args.Any()) { var key = manager.GetAsync().Result; if (string.IsNullOrEmpty(key)) { Console.WriteLine("No bing map key set"); } else { Console.WriteLine($"Bing map key = {key}"); } Console.WriteLine($"\nHint: Use {NewKeySwitch}<key> to set or update the key"); } else { var key = args[0].Substring(NewKeySwitch.Length); if (manager.SetAsync(key).Result) { Console.WriteLine($"Bing map key set as '{key}'"); } } } private static void Usage() { var entry = Path.GetFileName(Assembly.GetEntryAssembly().CodeBase); Console.WriteLine($"Usage: {entry} [{NewKeySwitch}<new key>]"); } } } ``` Change the switch to set/update key to "/newkey:"
```c# using System; using System.IO; using System.Linq; using System.Reflection; namespace PCSBingMapKeyManager { class Program { private const string NewKeySwitch = "/newkey:"; static void Main(string[] args) { if (args.Length > 1 || args.Any() && !args[0].StartsWith(NewKeySwitch)) { Usage(); return; } var manager = new BingMapKeyManager(); if (!args.Any()) { var key = manager.GetAsync().Result; if (string.IsNullOrEmpty(key)) { Console.WriteLine("No bing map key set"); } else { Console.WriteLine($"Bing map key = {key}"); } Console.WriteLine($"\nHint: Use {NewKeySwitch}<key> to set or update the key"); } else { var key = args[0].Substring(NewKeySwitch.Length); if (manager.SetAsync(key).Result) { Console.WriteLine($"Bing map key set as '{key}'"); } } } private static void Usage() { var entry = Path.GetFileName(Assembly.GetEntryAssembly().CodeBase); Console.WriteLine($"Usage: {entry} [{NewKeySwitch}<new key>]"); } } } ```
16121589-c640-40be-916c-26efa7c880c4
{ "language": "C#" }
```c# using NMaier.sdlna.Server; namespace NMaier.sdlna.FileMediaServer.Comparers { class TitleComparer : IItemComparer { public virtual string Description { get { return "Sort alphabetically"; } } public virtual string Name { get { return "title"; } } public virtual int Compare(IMediaItem x, IMediaItem y) { return x.Title.ToLower().CompareTo(y.Title.ToLower()); } } }``` Use NaturalStringComparer to compare titles
```c# using System; using System.Collections; using NMaier.sdlna.Server; using NMaier.sdlna.Util; namespace NMaier.sdlna.FileMediaServer.Comparers { class TitleComparer : IItemComparer, IComparer { private static StringComparer comp = new NaturalStringComparer(); public virtual string Description { get { return "Sort alphabetically"; } } public virtual string Name { get { return "title"; } } public virtual int Compare(IMediaItem x, IMediaItem y) { return comp.Compare(x.Title, y.Title); } public int Compare(object x, object y) { return comp.Compare(x, y); } } }```
eefea407-bbce-4a26-9f29-03ae66768e48
{ "language": "C#" }
```c# // // EnumerableExtensions.cs // // Author: // Roman M. Yagodin <roman.yagodin@gmail.com> // // Copyright (c) 2016 Roman M. Yagodin // // This program 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. // // This program 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/>. using System.Collections.Generic; using System.Linq; namespace R7.University.ModelExtensions { public static class EnumerableExtensions { public static bool IsNullOrEmpty (this IEnumerable<object> enumerable) { return enumerable == null || !enumerable.Any (); } } } ``` Make IEnumerable.IsNullOrEmpty extension method generic
```c# // // EnumerableExtensions.cs // // Author: // Roman M. Yagodin <roman.yagodin@gmail.com> // // Copyright (c) 2016 Roman M. Yagodin // // This program 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. // // This program 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/>. using System.Collections.Generic; using System.Linq; namespace R7.University.ModelExtensions { public static class EnumerableExtensions { // TODO: Move to the base library public static bool IsNullOrEmpty<T> (this IEnumerable<T> enumerable) { return enumerable == null || !enumerable.Any (); } } } ```
3a598556-1765-4c59-98c3-e13c6662d388
{ "language": "C#" }
```c# using MarkdownSnippets; using Xunit; public class DocoUpdater { [Fact] public void Run() { GitHubMarkdownProcessor.RunForFilePath(); } }``` Update MarkdownSnippets API to use new DirectoryMarkdownProcessor
```c# using MarkdownSnippets; using Xunit; public class DocoUpdater { [Fact] public void Run() { DirectoryMarkdownProcessor.RunForFilePath(); } }```
f0be8e0b-83ba-4749-a9ff-4e1dc7fef9e5
{ "language": "C#" }
```c# using Bartender.Tests.Context; using Moq; using Xunit; namespace Bartender.Tests { public class AsyncCommandDispatcherTests : DispatcherTests { [Fact] public async void ShouldHandleCommandOnce_WhenCallDispatchAsyncMethod() { await AsyncCommandDispatcher.DispatchAsync<Command, Result>(Command); MockedAsyncCommandHandler.Verify(x => x.HandleAsync(It.IsAny<Command>()), Times.Once); } [Fact] public async void ShouldHandleCommandOnce_WhenCallDispatchAsyncMethodWithoutResult() { await AsyncCommandDispatcher.DispatchAsync<Command>(Command); MockedAsyncCommandWithoutResultHandler.Verify(x => x.HandleAsync(It.IsAny<Command>()), Times.Once); } } }``` Return result when dispatch a command
```c# using Bartender.Tests.Context; using Moq; using Shouldly; using Xunit; namespace Bartender.Tests { public class AsyncCommandDispatcherTests : DispatcherTests { [Fact] public async void ShouldHandleCommandOnce_WhenCallDispatchAsyncMethod() { await AsyncCommandDispatcher.DispatchAsync<Command, Result>(Command); MockedAsyncCommandHandler.Verify(x => x.HandleAsync(It.IsAny<Command>()), Times.Once); } [Fact] public async void ShouldHandleCommandOnce_WhenCallDispatchAsyncMethodWithoutResult() { await AsyncCommandDispatcher.DispatchAsync<Command>(Command); MockedAsyncCommandWithoutResultHandler.Verify(x => x.HandleAsync(It.IsAny<Command>()), Times.Once); } [Fact] public async void ShouldReturnResult_WhenCallDispatchMethod() { var result = await AsyncCommandDispatcher.DispatchAsync<Command, Result>(Command); result.ShouldBeSameAs(Result); } } }```
9acc589b-b5bf-4f74-b2db-a3dd2fcf8dae
{ "language": "C#" }
```c# using System; using System.IO; using System.Reflection; namespace Blueprint41.Modeller.Schemas { public abstract class DatastoreModelComparer { static public DatastoreModelComparer Instance { get { return instance.Value; } } static private Lazy<DatastoreModelComparer> instance = new Lazy<DatastoreModelComparer>(delegate() { string dll = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Blueprint41.Modeller.Compare.dll"); if (!File.Exists(dll)) return null; Assembly a = Assembly.LoadFile(dll); Type t = a.GetType("Blueprint41.Modeller.Schemas.DatastoreModelComparerImpl"); return (DatastoreModelComparer)Activator.CreateInstance(t); }, true); public abstract void GenerateUpgradeScript(modeller model, string storagePath); } } ``` Load comparer assembly from bytes
```c# using System; using System.IO; using System.Linq; using System.Reflection; namespace Blueprint41.Modeller.Schemas { public abstract class DatastoreModelComparer { public static DatastoreModelComparer Instance { get { return instance.Value; } } private static Lazy<DatastoreModelComparer> instance = new Lazy<DatastoreModelComparer>(delegate () { string dll = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Blueprint41.Modeller.Compare.dll"); if (!File.Exists(dll)) return null; byte[] assembly = File.ReadAllBytes(dll); Assembly asm = Assembly.Load(assembly); Type type = asm.GetTypes().First(x => x.Name == "DatastoreModelComparerImpl"); return (DatastoreModelComparer)Activator.CreateInstance(type); }, true); public abstract void GenerateUpgradeScript(modeller model, string storagePath); } } ```
48c53bad-1a9c-4782-a3e3-8f4ffdcae98b
{ "language": "C#" }
```c# using System.Xml.Linq; var target = Argument<string>("target", "Default"); var configuration = Argument<string>("configuration", "Release"); var projectName = "WeakEvent"; var libraryProject = $"./{projectName}/{projectName}.csproj"; var testProject = $"./{projectName}.Tests/{projectName}.Tests.csproj"; var outDir = $"./{projectName}/bin/{configuration}"; Task("Clean") .Does(() => { CleanDirectory(outDir); }); Task("Restore").Does(DotNetCoreRestore); Task("Build") .IsDependentOn("Clean") .IsDependentOn("Restore") .Does(() => { DotNetCoreBuild(".", new DotNetCoreBuildSettings { Configuration = configuration }); }); Task("Test") .IsDependentOn("Build") .Does(() => { DotNetCoreTest(testProject, new DotNetCoreTestSettings { Configuration = configuration }); }); Task("Pack") .IsDependentOn("Test") .Does(() => { DotNetCorePack(libraryProject, new DotNetCorePackSettings { Configuration = configuration }); }); Task("Push") .IsDependentOn("Pack") .Does(() => { var doc = XDocument.Load(libraryProject); string version = doc.Root.Elements("PropertyGroup").Elements("Version").First().Value; string package = $"{projectName}/bin/{configuration}/{projectName}.{version}.nupkg"; NuGetPush(package, new NuGetPushSettings()); }); Task("Default") .IsDependentOn("Pack"); RunTarget(target); ``` Use MSBuild for Build and Pack
```c# using System.Xml.Linq; var target = Argument<string>("target", "Default"); var configuration = Argument<string>("configuration", "Release"); var projectName = "WeakEvent"; var solution = $"{projectName}.sln"; var libraryProject = $"./{projectName}/{projectName}.csproj"; var testProject = $"./{projectName}.Tests/{projectName}.Tests.csproj"; var outDir = $"./{projectName}/bin/{configuration}"; Task("Clean") .Does(() => { CleanDirectory(outDir); }); Task("Restore") .Does(() => RunMSBuildTarget(solution, "Restore")); Task("Build") .IsDependentOn("Clean") .IsDependentOn("Restore") .Does(() => RunMSBuildTarget(solution, "Build")); Task("Test") .IsDependentOn("Build") .Does(() => { DotNetCoreTest(testProject, new DotNetCoreTestSettings { Configuration = configuration }); }); Task("Pack") .IsDependentOn("Test") .Does(() => RunMSBuildTarget(libraryProject, "Pack")); Task("Push") .IsDependentOn("Pack") .Does(() => { var doc = XDocument.Load(libraryProject); string version = doc.Root.Elements("PropertyGroup").Elements("Version").First().Value; string package = $"{projectName}/bin/{configuration}/{projectName}.{version}.nupkg"; NuGetPush(package, new NuGetPushSettings()); }); Task("Default") .IsDependentOn("Pack"); void RunMSBuildTarget(string projectOrSolution, string target) { MSBuild(projectOrSolution, new MSBuildSettings { Targets = { target }, Configuration = configuration }); } RunTarget(target); ```
c7b0d9b9-9b6b-46e1-aa06-6a13e91a157e
{ "language": "C#" }
```c# // 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.Framework.Bindables; using osu.Framework.Configuration; using osu.Framework.Platform; namespace osu.Framework.Tests.Visual.Platform { public class TestSceneAllowSuspension : FrameworkTestScene { private Bindable<bool> allowSuspension; [BackgroundDependencyLoader] private void load(GameHost host) { allowSuspension = host.AllowScreenSuspension.GetBoundCopy(); } protected override void LoadComplete() { base.LoadComplete(); AddToggleStep("Toggle Suspension", b => { allowSuspension.Value = b; } ); } } } ``` Fix formatting / usings in test scene
```c# // 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.Framework.Bindables; using osu.Framework.Platform; namespace osu.Framework.Tests.Visual.Platform { public class TestSceneAllowSuspension : FrameworkTestScene { private Bindable<bool> allowSuspension; [BackgroundDependencyLoader] private void load(GameHost host) { allowSuspension = host.AllowScreenSuspension.GetBoundCopy(); } protected override void LoadComplete() { base.LoadComplete(); AddToggleStep("Toggle Suspension", b => allowSuspension.Value = b); } } } ```
bc61014c-2dd1-4c51-ae38-aa243cace3c3
{ "language": "C#" }
```c# namespace Interapp.Services.Common { public class FilterModel { public string OrderBy { get; set; } public string Order { get; set; } public int Page { get; set; } public int PageSize { get; set; } public string Filter { get; set; } } } ``` Set default values for filter model
```c# namespace Interapp.Services.Common { public class FilterModel { public FilterModel() { this.Page = 1; this.PageSize = 10; } public string OrderBy { get; set; } public string Order { get; set; } public int Page { get; set; } public int PageSize { get; set; } public string Filter { get; set; } } } ```
8d425a5a-82c1-414e-9771-7965041b4466
{ "language": "C#" }
```c# #tool "nuget:?package=xunit.runners&version=1.9.2" var config = Argument("configuration", "Release"); var runEnvironment = Argument("runenv", "local"); var buildDir = Directory("./Titan/bin/") + Directory(config); var testDir = Directory("./TitanTest/bin/") + Directory(config); Task("Clean") .Does(() => { CleanDirectory(buildDir); }); Task("Restore-NuGet-Packages") .IsDependentOn("Clean") .Does(() => { NuGetRestore("./Titan.sln"); }); Task("Build") .IsDependentOn("Restore-NuGet-Packages") .Does(() => { if(IsRunningOnWindows()) { // Use MSBuild MSBuild("./Titan.sln", settings => settings.SetConfiguration(config)); } else { // Use XBuild XBuild("./Titan.sln", settings => settings.SetConfiguration(config)); } }); Task("Run-Unit-Tests") .IsDependentOn("Build") .Does(() => { XUnit(GetFiles("./TitanTest/bin/" + config + "/TitanTest.dll"), new XUnitSettings() { OutputDirectory = "./TitanTest/bin/" + config + "/results" }); }); if(runEnvironment.ToLower() == "ci") { Task("Default").IsDependentOn("Run-Unit-Tests"); } else { Task("Default").IsDependentOn("Build"); } RunTarget("Default"); ``` Use XUnit v2 runner in Cake instead of XUnit v1
```c# #tool "nuget:?package=xunit.runner.console" var config = Argument("configuration", "Release"); var runEnvironment = Argument("runenv", "local"); var buildDir = Directory("./Titan/bin/") + Directory(config); var testDir = Directory("./TitanTest/bin/") + Directory(config); Task("Clean") .Does(() => { CleanDirectory(buildDir); }); Task("Restore-NuGet-Packages") .IsDependentOn("Clean") .Does(() => { NuGetRestore("./Titan.sln"); }); Task("Build") .IsDependentOn("Restore-NuGet-Packages") .Does(() => { if(IsRunningOnWindows()) { // Use MSBuild MSBuild("./Titan.sln", settings => settings.SetConfiguration(config)); } else { // Use XBuild XBuild("./Titan.sln", settings => settings.SetConfiguration(config)); } }); Task("Run-Unit-Tests") .IsDependentOn("Build") .Does(() => { XUnit2(GetFiles("./TitanTest/bin/" + config + "/Titan*.dll"), new XUnit2Settings() { Parallelism = ParallelismOption.All, OutputDirectory = "./TitanTest/bin/" + config + "/results" }); }); if(runEnvironment.ToLower() == "ci") { Task("Default").IsDependentOn("Run-Unit-Tests"); } else { Task("Default").IsDependentOn("Build"); } RunTarget("Default"); ```
69170f54-85bf-4093-b3db-cd0cbf4fb303
{ "language": "C#" }
```c# using System; using System.Threading; using NUnit.Framework; namespace Atata.WebDriverExtras.Tests { [TestFixture] [Parallelizable(ParallelScope.None)] public class SafeWaitTests { private SafeWait<object> wait; [SetUp] public void SetUp() { wait = new SafeWait<object>(new object()) { Timeout = TimeSpan.FromSeconds(.3), PollingInterval = TimeSpan.FromSeconds(.05) }; } [Test] public void SafeWait_Success_Immediate() { using (StopwatchAsserter.Within(0, .01)) wait.Until(_ => { return true; }); } [Test] public void SafeWait_Timeout() { using (StopwatchAsserter.Within(.3, .01)) wait.Until(_ => { return false; }); } [Test] public void SafeWait_PollingInterval() { using (StopwatchAsserter.Within(.3, .2)) wait.Until(_ => { Thread.Sleep(TimeSpan.FromSeconds(.1)); return false; }); } [Test] public void SafeWait_PollingInterval_GreaterThanTimeout() { wait.PollingInterval = TimeSpan.FromSeconds(1); using (StopwatchAsserter.Within(.3, .015)) wait.Until(_ => { return false; }); } } } ``` Increase toleranceSeconds in SafeWait_Timeout test
```c# using System; using System.Threading; using NUnit.Framework; namespace Atata.WebDriverExtras.Tests { [TestFixture] [Parallelizable(ParallelScope.None)] public class SafeWaitTests { private SafeWait<object> wait; [SetUp] public void SetUp() { wait = new SafeWait<object>(new object()) { Timeout = TimeSpan.FromSeconds(.3), PollingInterval = TimeSpan.FromSeconds(.05) }; } [Test] public void SafeWait_Success_Immediate() { using (StopwatchAsserter.Within(0, .01)) wait.Until(_ => { return true; }); } [Test] public void SafeWait_Timeout() { using (StopwatchAsserter.Within(.3, .015)) wait.Until(_ => { return false; }); } [Test] public void SafeWait_PollingInterval() { using (StopwatchAsserter.Within(.3, .2)) wait.Until(_ => { Thread.Sleep(TimeSpan.FromSeconds(.1)); return false; }); } [Test] public void SafeWait_PollingInterval_GreaterThanTimeout() { wait.PollingInterval = TimeSpan.FromSeconds(1); using (StopwatchAsserter.Within(.3, .015)) wait.Until(_ => { return false; }); } } } ```
133ff214-eb6b-4367-859a-6c0ccc679b37
{ "language": "C#" }
```c# #region Copyright // Copyright 2016 SnapMD, Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion namespace SnapMD.ConnectedCare.ApiModels { /// <summary> /// Represents patient details for administrator patient lists. /// </summary> public class PatientAccountInfo { public int PatientId { get; set; } public int? UserId { get; set; } public string ProfileImagePath { get; set; } public string FullName { get; set; } public string Phone { get; set; } public bool IsAuthorized { get; set; } public PatientAccountStatus Status { get; set; } public string Email { get; set; } } } ``` Add IsDependent and GuardianId to patient profile
```c# #region Copyright // Copyright 2016 SnapMD, Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion namespace SnapMD.ConnectedCare.ApiModels { /// <summary> /// Represents patient details for administrator patient lists. /// </summary> public class PatientAccountInfo { public int PatientId { get; set; } public int? UserId { get; set; } public string ProfileImagePath { get; set; } public string FullName { get; set; } public string Phone { get; set; } public bool IsAuthorized { get; set; } public PatientAccountStatus Status { get; set; } public string IsDependent { get; set; } public int? GuardianId { get; set; } public string Email { get; set; } } } ```
bdda7fd3-dfd0-4c41-bb50-d50a8817daaa
{ "language": "C#" }
```c# using osu.Framework.Graphics.Containers; using osu.Framework.Graphics; using osu.Framework.Input; using OpenTK; using osu.Framework; using osu.Framework.Allocation; namespace osu.Game.Graphics.Containers { class ParallaxContainer : Container { public float ParallaxAmount = 0.02f; public override bool Contains(Vector2 screenSpacePos) => true; public ParallaxContainer() { RelativeSizeAxes = Axes.Both; AddInternal(content = new Container { RelativeSizeAxes = Axes.Both, Anchor = Anchor.Centre, Origin = Anchor.Centre }); } private Container content; protected override Container<Drawable> Content => content; protected override bool OnMouseMove(InputState state) { content.Position = (state.Mouse.Position - DrawSize / 2) * ParallaxAmount; return base.OnMouseMove(state); } protected override void Update() { base.Update(); content.Scale = new Vector2(1 + ParallaxAmount); } } } ``` Make parallax container work with global mouse state (so it ignores bounds checks).
```c# using osu.Framework.Graphics.Containers; using osu.Framework.Graphics; using osu.Framework.Input; using OpenTK; using osu.Framework; using osu.Framework.Allocation; namespace osu.Game.Graphics.Containers { class ParallaxContainer : Container { public float ParallaxAmount = 0.02f; public override bool Contains(Vector2 screenSpacePos) => true; public ParallaxContainer() { RelativeSizeAxes = Axes.Both; AddInternal(content = new Container { RelativeSizeAxes = Axes.Both, Anchor = Anchor.Centre, Origin = Anchor.Centre }); } private Container content; private InputManager input; protected override Container<Drawable> Content => content; [BackgroundDependencyLoader] private void load(UserInputManager input) { this.input = input; } protected override void Update() { base.Update(); content.Position = (input.CurrentState.Mouse.Position - DrawSize / 2) * ParallaxAmount; content.Scale = new Vector2(1 + ParallaxAmount); } } } ```
937dff38-1396-44d0-aaaf-a5d4549e2618
{ "language": "C#" }
```c# // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System.ComponentModel; namespace osu.Game.Screens.Edit.Screens { public enum EditorScreenMode { [Description("compose")] Compose, [Description("design")] Design, [Description("timing")] Timing, [Description("song")] SongSetup } } ``` Reorder screen tab control items
```c# // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System.ComponentModel; namespace osu.Game.Screens.Edit.Screens { public enum EditorScreenMode { [Description("setup")] SongSetup, [Description("compose")] Compose, [Description("design")] Design, [Description("timing")] Timing, } } ```
c8d94c30-1833-4629-9d10-4950575412b8
{ "language": "C#" }
```c# using System.Collections.Generic; using System.Linq; using Glimpse.Core2.Extensibility; using Glimpse.Core2.Framework; using Glimpse.Core2.ResourceResult; namespace Glimpse.Core2.Resource { public class Metadata : IResource { internal const string InternalName = "metadata.js"; private const int CacheDuration = 12960000; //150 days public string Name { get { return InternalName; } } public IEnumerable<string> ParameterKeys { get { return new[] { ResourceParameterKey.VersionNumber }; } } public IResourceResult Execute(IResourceContext context) { var metadata = context.PersistanceStore.GetMetadata(); if (metadata == null) return new StatusCodeResourceResult(404); return new JsonResourceResult(metadata, "console.log", CacheDuration, CacheSetting.Public); } } }``` Update metadata resource to use callback instead of console.log
```c# using System.Collections.Generic; using System.Linq; using Glimpse.Core2.Extensibility; using Glimpse.Core2.Framework; using Glimpse.Core2.ResourceResult; namespace Glimpse.Core2.Resource { public class Metadata : IResource { internal const string InternalName = "metadata.js"; private const int CacheDuration = 12960000; //150 days public string Name { get { return InternalName; } } public IEnumerable<string> ParameterKeys { get { return new[] { ResourceParameterKey.VersionNumber, ResourceParameterKey.Callback }; } } public IResourceResult Execute(IResourceContext context) { var metadata = context.PersistanceStore.GetMetadata(); if (metadata == null) return new StatusCodeResourceResult(404); return new JsonResourceResult(metadata, context.Parameters[ResourceParameterKey.Callback], CacheDuration, CacheSetting.Public); } } }```
d921985d-44cc-489e-a782-b7217234a059
{ "language": "C#" }
```c# using System; using DesktopWidgets.Classes; namespace DesktopWidgets.Widgets.CountdownClock { public class Settings : WidgetClockSettingsBase { public DateTime EndDateTime { get; } = DateTime.Now; } }``` Fix "Countdown" widget "EndDateTime" read only
```c# using System; using DesktopWidgets.Classes; namespace DesktopWidgets.Widgets.CountdownClock { public class Settings : WidgetClockSettingsBase { public DateTime EndDateTime { get; set; } = DateTime.Now; } }```
44a02fe2-d11b-4ecc-a697-3cf19f25ee0e
{ "language": "C#" }
```c# using System; using System.Data; using System.IO; namespace Tests.Daterpillar.Helper { public static class ConnectionFactory { public static IDbConnection CreateMySQLConnection(string database = null) { var connStr = new MySql.Data.MySqlClient.MySqlConnectionStringBuilder(""); if (!string.IsNullOrEmpty(database)) connStr.Database = database; return new MySql.Data.MySqlClient.MySqlConnection(connStr.ConnectionString); } public static IDbConnection CreateMSSQLConnection(string database = null) { var connStr = new System.Data.SqlClient.SqlConnectionStringBuilder(""); if (!string.IsNullOrEmpty(database)) connStr.Add("database", database); return new System.Data.SqlClient.SqlConnection(connStr.ConnectionString); } public static IDbConnection CreateSQLiteConnection(string filePath = "") { if (!File.Exists(filePath)) { filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "daterpillar-test.db3"); System.Data.SQLite.SQLiteConnection.CreateFile(filePath); } var connStr = new System.Data.SQLite.SQLiteConnectionStringBuilder() { DataSource = filePath }; return new System.Data.SQLite.SQLiteConnection(connStr.ConnectionString); } } }``` Add default database names to connectionfactory.cs
```c# using System; using System.Data; using System.IO; namespace Tests.Daterpillar.Helper { public static class ConnectionFactory { public static IDbConnection CreateSQLiteConnection(string filePath = "") { if (!File.Exists(filePath)) { filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "daterpillar-test.db3"); System.Data.SQLite.SQLiteConnection.CreateFile(filePath); } var connStr = new System.Data.SQLite.SQLiteConnectionStringBuilder() { DataSource = filePath }; return new System.Data.SQLite.SQLiteConnection(connStr.ConnectionString); } public static IDbConnection CreateMySQLConnection(string database = "daterpillar") { var connStr = new MySql.Data.MySqlClient.MySqlConnectionStringBuilder(ConnectionString.GetMySQLServerConnectionString()); if (!string.IsNullOrEmpty(database)) connStr.Database = database; return new MySql.Data.MySqlClient.MySqlConnection(connStr.ConnectionString); } public static IDbConnection CreateMSSQLConnection(string database = "daterpillar") { var connStr = new System.Data.SqlClient.SqlConnectionStringBuilder(ConnectionString.GetSQLServerConnectionString()); if (!string.IsNullOrEmpty(database)) connStr.Add("database", database); return new System.Data.SqlClient.SqlConnection(connStr.ConnectionString); } } }```
5a60b11e-7d88-4b53-93c9-19a6e676e38a
{ "language": "C#" }
```c# // 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 NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Testing; using osu.Game.Audio; using osu.Game.Beatmaps; using osu.Game.IO.Archives; using osu.Game.Tests.Resources; using osu.Game.Tests.Visual; namespace osu.Game.Tests.Skins { [HeadlessTest] public class TestSceneBeatmapSkinResources : OsuTestScene { [Resolved] private BeatmapManager beatmaps { get; set; } private WorkingBeatmap beatmap; [BackgroundDependencyLoader] private void load() { var imported = beatmaps.Import(new ZipArchiveReader(TestResources.OpenResource("Archives/ogg-beatmap.osz"))).Result; beatmap = beatmaps.GetWorkingBeatmap(imported.Beatmaps[0]); } [Test] public void TestRetrieveOggSample() => AddAssert("sample is non-null", () => beatmap.Skin.GetSample(new SampleInfo("sample")) != null); [Test] public void TestRetrieveOggTrack() => AddAssert("track is non-null", () => MusicController.CurrentTrack.IsDummyDevice == false); } } ``` Fix test scene using local beatmap
```c# // 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 NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Testing; using osu.Game.Audio; using osu.Game.Beatmaps; using osu.Game.IO.Archives; using osu.Game.Tests.Resources; using osu.Game.Tests.Visual; namespace osu.Game.Tests.Skins { [HeadlessTest] public class TestSceneBeatmapSkinResources : OsuTestScene { [Resolved] private BeatmapManager beatmaps { get; set; } [BackgroundDependencyLoader] private void load() { var imported = beatmaps.Import(new ZipArchiveReader(TestResources.OpenResource("Archives/ogg-beatmap.osz"))).Result; Beatmap.Value = beatmaps.GetWorkingBeatmap(imported.Beatmaps[0]); } [Test] public void TestRetrieveOggSample() => AddAssert("sample is non-null", () => Beatmap.Value.Skin.GetSample(new SampleInfo("sample")) != null); [Test] public void TestRetrieveOggTrack() => AddAssert("track is non-null", () => MusicController.CurrentTrack.IsDummyDevice == false); } } ```
ac2fdba0-0909-472a-92f2-a32dc03589db
{ "language": "C#" }
```c# // 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.Platform; using osu.Framework.Testing; namespace osu.Game.Configuration { [ExcludeFromDynamicCompile] public class DevelopmentOsuConfigManager : OsuConfigManager { protected override string Filename => base.Filename.Replace(".ini", ".dev.ini"); public DevelopmentOsuConfigManager(Storage storage) : base(storage) { } } } ``` Fix potential crash in tests when attempting to lookup key bindings in cases the lookup is not available
```c# // 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.Platform; using osu.Framework.Testing; namespace osu.Game.Configuration { [ExcludeFromDynamicCompile] public class DevelopmentOsuConfigManager : OsuConfigManager { protected override string Filename => base.Filename.Replace(".ini", ".dev.ini"); public DevelopmentOsuConfigManager(Storage storage) : base(storage) { LookupKeyBindings = _ => "unknown"; LookupSkinName = _ => "unknown"; } } } ```
493aed94-2560-4441-92e2-8b8d14ae94cd
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Common.Log; using CompetitionPlatform.Data.AzureRepositories.Log; using Quartz; using Quartz.Impl; namespace CompetitionPlatform.ScheduledJobs { public static class JobScheduler { public static async void Start(string connectionString, ILog log) { var schedFact = new StdSchedulerFactory(); var sched = await schedFact.GetScheduler(); await sched.Start(); var job = JobBuilder.Create<ProjectStatusIpdaterJob>() .WithIdentity("myJob", "group1") .Build(); var trigger = TriggerBuilder.Create() .WithIdentity("myTrigger", "group1") .WithSimpleSchedule(x => x .WithIntervalInSeconds(50) .RepeatForever()) .Build(); job.JobDataMap["connectionString"] = connectionString; job.JobDataMap["log"] = log; await sched.ScheduleJob(job, trigger); } } } ``` Change StatusUpdater job to run every hour.
```c# using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Common.Log; using CompetitionPlatform.Data.AzureRepositories.Log; using Quartz; using Quartz.Impl; namespace CompetitionPlatform.ScheduledJobs { public static class JobScheduler { public static async void Start(string connectionString, ILog log) { var schedFact = new StdSchedulerFactory(); var sched = await schedFact.GetScheduler(); await sched.Start(); var job = JobBuilder.Create<ProjectStatusIpdaterJob>() .WithIdentity("myJob", "group1") .Build(); var trigger = TriggerBuilder.Create() .WithIdentity("myTrigger", "group1") .WithSimpleSchedule(x => x .WithIntervalInHours(1) .RepeatForever()) .Build(); job.JobDataMap["connectionString"] = connectionString; job.JobDataMap["log"] = log; await sched.ScheduleJob(job, trigger); } } } ```
df63a623-3e12-4791-b0ee-ae6fba9c2bfa
{ "language": "C#" }
```c# using RealEstateAgencyFranchise.Database; using Starcounter; namespace RealEstateAgencyFranchise { partial class CorporationJson : Json { static CorporationJson() { DefaultTemplate.Offices.ElementType.InstanceType = typeof(AgencyOfficeJson); } void Handle(Input.SaveTrigger action) { Transaction.Commit(); } void Handle(Input.NewOfficeTrigger action) { new Office() { Corporation = this.Data as Corporation, Address = new Address(), Trend = 0, Name = this.NewOfficeName }; } } } ``` Fix new office name clearing after adding
```c# using RealEstateAgencyFranchise.Database; using Starcounter; namespace RealEstateAgencyFranchise { partial class CorporationJson : Json { static CorporationJson() { DefaultTemplate.Offices.ElementType.InstanceType = typeof(AgencyOfficeJson); } void Handle(Input.SaveTrigger action) { Transaction.Commit(); } void Handle(Input.NewOfficeTrigger action) { new Office() { Corporation = this.Data as Corporation, Address = new Address(), Trend = 0, Name = this.NewOfficeName }; this.NewOfficeName = ""; } } } ```
e6bee11b-9c51-4e70-a49e-250672a69af2
{ "language": "C#" }
```c# using System; namespace Silverpop.Client { public class TransactClientException : Exception { public TransactClientException() { } public TransactClientException(string message) : base(message) { } public TransactClientException(string message, Exception innerException) : base(message, innerException) { } } }``` Apply SerializableAttribute to custom exception
```c# using System; namespace Silverpop.Client { [Serializable] public class TransactClientException : Exception { public TransactClientException() { } public TransactClientException(string message) : base(message) { } public TransactClientException(string message, Exception innerException) : base(message, innerException) { } } }```
c99b9f6e-9d58-4cd5-9d2a-7bdd24fc4aa5
{ "language": "C#" }
```c# using System; using System.Diagnostics; using Dependencies.ClrPh; namespace Dependencies { namespace Test { class Program { static void Main(string[] args) { // always the first call to make Phlib.InitializePhLib(); // Redirect debug log to the console Debug.Listeners.Add(new TextWriterTraceListener(Console.Out)); Debug.AutoFlush = true; BinaryCache.Instance.Load(); foreach ( var peFilePath in args ) { PE Pe = BinaryCache.LoadPe(peFilePath); } BinaryCache.Instance.Unload(); } } } } ``` Use NDes.options for binarycache test executable
```c# using System; using System.Diagnostics; using System.Collections.Generic; using Dependencies.ClrPh; using NDesk.Options; namespace Dependencies { namespace Test { class Program { static void ShowHelp(OptionSet p) { Console.WriteLine("Usage: binarycache [options] <FILES_TO_LOAD>"); Console.WriteLine(); Console.WriteLine("Options:"); p.WriteOptionDescriptions(Console.Out); } static void Main(string[] args) { bool is_verbose = false; bool show_help = false; OptionSet opts = new OptionSet() { { "v|verbose", "redirect debug traces to console", v => is_verbose = v != null }, { "h|help", "show this message and exit", v => show_help = v != null }, }; List<string> eps = opts.Parse(args); if (show_help) { ShowHelp(opts); return; } if (is_verbose) { // Redirect debug log to the console Debug.Listeners.Add(new TextWriterTraceListener(Console.Out)); Debug.AutoFlush = true; } // always the first call to make Phlib.InitializePhLib(); BinaryCache.Instance.Load(); foreach ( var peFilePath in eps) { PE Pe = BinaryCache.LoadPe(peFilePath); Console.WriteLine("Loaded PE file : {0:s}", Pe.Filepath); } BinaryCache.Instance.Unload(); } } } } ```
2db39feb-f57c-4f56-9385-5320a21e70a7
{ "language": "C#" }
```c# using System.Collections.Generic; using CuttingEdge.Conditions; namespace ZimmerBot.Core { public class Request { public enum EventEnum { Welcome } public string Input { get; set; } public Dictionary<string, string> State { get; set; } public string SessionId { get; set; } public string UserId { get; set; } public string RuleId { get; set; } public string RuleLabel { get; set; } public EventEnum? EventType { get; set; } public string BotId { get; set; } public Request() : this("default", "default") { } public Request(string sessionId, string userId) { Condition.Requires(sessionId, nameof(sessionId)).IsNotNullOrEmpty(); Condition.Requires(userId, nameof(userId)).IsNotNullOrEmpty(); SessionId = sessionId; UserId = userId; } public Request(Request src, string input) { Input = input; State = src.State; SessionId = src.SessionId; UserId = src.UserId; State = src.State; RuleId = src.RuleId; RuleLabel = src.RuleLabel; } } } ``` Make sure multi-line output works when invoked with <<...>> output templates.
```c# using System.Collections.Generic; using CuttingEdge.Conditions; namespace ZimmerBot.Core { public class Request { public enum EventEnum { Welcome } public string Input { get; set; } public Dictionary<string, string> State { get; set; } public string SessionId { get; set; } public string UserId { get; set; } public string RuleId { get; set; } public string RuleLabel { get; set; } public EventEnum? EventType { get; set; } public string BotId { get; set; } public Request() : this("default", "default") { } public Request(string sessionId, string userId) { Condition.Requires(sessionId, nameof(sessionId)).IsNotNullOrEmpty(); Condition.Requires(userId, nameof(userId)).IsNotNullOrEmpty(); SessionId = sessionId; UserId = userId; } public Request(Request src, string input) { Input = input; State = src.State; SessionId = src.SessionId; UserId = src.UserId; RuleId = src.RuleId; RuleLabel = src.RuleLabel; EventType = src.EventType; BotId = src.BotId; } } } ```
6ecf7a69-4ae5-42b2-aeb1-7f01478c186c
{ "language": "C#" }
```c# WoWUnit unit = ObjectManager.GetNearestWoWUnit(ObjectManager.GetWoWUnitByEntry(questObjective.Entry, questObjective.IsDead), questObjective.IgnoreNotSelectable, questObjective.IgnoreBlackList, questObjective.AllowPlayerControlled); if (unit.IsValid && unit.Position.DistanceTo(questObjective.Position) <=8) { MovementManager.Face(unit); Interact.InteractWith(unit.GetBaseAddress); nManager.Wow.Helpers.Fight.StartFight(unit.Guid); } else { List<Point> liste = new List<Point>(); liste.Add(ObjectManager.Me.Position); liste.Add(questObjective.Position); MovementManager.Go(liste); } ``` Fix : Un-Stealth rogues for this quest otherwise the mobs arent aggroed.
```c# WoWUnit unit = ObjectManager.GetNearestWoWUnit(ObjectManager.GetWoWUnitByEntry(questObjective.Entry, questObjective.IsDead), questObjective.IgnoreNotSelectable, questObjective.IgnoreBlackList, questObjective.AllowPlayerControlled); ObjectManager.Me.UnitAura(115191).TryCancel(); //Remove Stealth from rogue if (unit.IsValid && unit.Position.DistanceTo(questObjective.Position) <=8) { MovementManager.Face(unit); Interact.InteractWith(unit.GetBaseAddress); nManager.Wow.Helpers.Fight.StartFight(unit.Guid); } else { List<Point> liste = new List<Point>(); liste.Add(ObjectManager.Me.Position); liste.Add(questObjective.Position); MovementManager.Go(liste); } ```