Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Refactor the arrange part of the test
using Cafe.Tab; using Edument.CQRS; using Events.Cafe; using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using WebFrontend; namespace CafeTests { [TestFixture] public class AddingEventHandlers { [Test] public void ShouldAddEventHandlers() { // Arrange Guid testId = Guid.NewGuid(); var command = new OpenTab() { Id = testId, TableNumber = 5, Waiter = "Bob" }; var expectedEvent = new TabOpened() { Id = testId, TableNumber = 5, Waiter = "Bob" }; ISubscribeTo<TabOpened> handler = new EventHandler(); // Act Domain.Setup(); Domain.Dispatcher.AddSubscriberFor<TabOpened>(handler); Domain.Dispatcher.SendCommand(command); // Assert Assert.AreEqual(expectedEvent.Id, (handler as EventHandler).Actual.Id); } public class EventHandler : ISubscribeTo<TabOpened> { public TabOpened Actual { get; private set; } public void Handle(TabOpened e) { Actual = e; } } } }
using Cafe.Tab; using Edument.CQRS; using Events.Cafe; using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using WebFrontend; namespace CafeTests { [TestFixture] public class AddingEventHandlers { private static void Arrange(out OpenTab command, out TabOpened expectedEvent, out ISubscribeTo<TabOpened> handler) { // Arrange Guid testId = Guid.NewGuid(); command = new OpenTab() { Id = testId, TableNumber = 5, Waiter = "Bob" }; expectedEvent = new TabOpened() { Id = testId, TableNumber = 5, Waiter = "Bob" }; handler = new EventHandler(); } [Test] public void ShouldAddEventHandlers() { ISubscribeTo<TabOpened> handler; OpenTab command; TabOpened expectedEvent; Arrange(out command, out expectedEvent, out handler); // Act Domain.Setup(); Domain.Dispatcher.AddSubscriberFor<TabOpened>(handler); Domain.Dispatcher.SendCommand(command); // Assert Assert.AreEqual(expectedEvent.Id, (handler as EventHandler).Actual.Id); } public class EventHandler : ISubscribeTo<TabOpened> { public TabOpened Actual { get; private set; } public void Handle(TabOpened e) { Actual = e; } } } }
Create negative test for getting values from nested environments
using Xunit; using Squirrel; using Squirrel.Nodes; namespace Tests { public class EnvironmentTests { private static readonly string TestVariableName = "x"; private static readonly INode TestVariableValue = new IntegerNode(1); [Fact] public void TestGetValueFromCurrentEnvironment() { var environment = new Environment(); environment.Put(TestVariableName, TestVariableValue); Assert.Equal(TestVariableValue, environment.Get(TestVariableName)); } [Fact] public void TestGetValueFromParentEnvironment() { var parentEnvironment = new Environment(); var childEnvironment = new Environment(parentEnvironment); parentEnvironment.Put(TestVariableName, TestVariableValue); Assert.Equal(TestVariableValue, childEnvironment.Get(TestVariableName)); } [Fact] public void TestGetValueFromGrandparentEnvironment() { var grandparentEnvironment = new Environment(); var parentEnvironment = new Environment(grandparentEnvironment); var childEnvironment = new Environment(parentEnvironment); grandparentEnvironment.Put(TestVariableName, TestVariableValue); Assert.Equal(TestVariableValue, childEnvironment.Get(TestVariableName)); } } }
using Xunit; using Squirrel; using Squirrel.Nodes; namespace Tests { public class EnvironmentTests { private static readonly string TestVariableName = "x"; private static readonly INode TestVariableValue = new IntegerNode(1); [Fact] public void TestCanGetValueFromCurrentEnvironment() { var environment = new Environment(); environment.Put(TestVariableName, TestVariableValue); Assert.Equal(TestVariableValue, environment.Get(TestVariableName)); } [Fact] public void TestCanGetValueFromParentEnvironment() { var parentEnvironment = new Environment(); var childEnvironment = new Environment(parentEnvironment); parentEnvironment.Put(TestVariableName, TestVariableValue); Assert.Equal(TestVariableValue, childEnvironment.Get(TestVariableName)); } [Fact] public void TestCanGetValueFromGrandparentEnvironment() { var grandparentEnvironment = new Environment(); var parentEnvironment = new Environment(grandparentEnvironment); var childEnvironment = new Environment(parentEnvironment); grandparentEnvironment.Put(TestVariableName, TestVariableValue); Assert.Equal(TestVariableValue, childEnvironment.Get(TestVariableName)); } [Fact] public void TestCannotGetValueFromChildEnvironment() { var parentEnvironment = new Environment(); var childEnvironment = new Environment(parentEnvironment); childEnvironment.Put(TestVariableName, TestVariableValue); Assert.NotEqual(TestVariableValue, parentEnvironment.Get(TestVariableName)); } } }
Reset stopwatch on Start instead of Pause
using MongoDB.Bson.Serialization.Attributes; using System.Diagnostics; namespace ChessVariantsTraining.Models.Variant960 { public class Clock { Stopwatch stopwatch; [BsonElement("secondsLeftAfterLatestMove")] public double SecondsLeftAfterLatestMove { get; set; } [BsonElement("increment")] public int Increment { get; set; } public Clock() { stopwatch = new Stopwatch(); } public Clock(TimeControl tc) : this() { Increment = tc.Increment; SecondsLeftAfterLatestMove = tc.InitialSeconds; } public void Start() { stopwatch.Start(); } public void Pause() { stopwatch.Stop(); stopwatch.Reset(); } public void AddIncrement() { SecondsLeftAfterLatestMove += Increment; } public void MoveMade() { Pause(); AddIncrement(); SecondsLeftAfterLatestMove = GetSecondsLeft(); } public double GetSecondsLeft() { return SecondsLeftAfterLatestMove - stopwatch.Elapsed.TotalSeconds; } } }
using MongoDB.Bson.Serialization.Attributes; using System.Diagnostics; namespace ChessVariantsTraining.Models.Variant960 { public class Clock { Stopwatch stopwatch; [BsonElement("secondsLeftAfterLatestMove")] public double SecondsLeftAfterLatestMove { get; set; } [BsonElement("increment")] public int Increment { get; set; } public Clock() { stopwatch = new Stopwatch(); } public Clock(TimeControl tc) : this() { Increment = tc.Increment; SecondsLeftAfterLatestMove = tc.InitialSeconds; } public void Start() { stopwatch.Reset(); stopwatch.Start(); } public void Pause() { stopwatch.Stop(); } public void AddIncrement() { SecondsLeftAfterLatestMove += Increment; } public void MoveMade() { Pause(); AddIncrement(); SecondsLeftAfterLatestMove = GetSecondsLeft(); } public double GetSecondsLeft() { return SecondsLeftAfterLatestMove - stopwatch.Elapsed.TotalSeconds; } } }
Add VariableParser to the main parser
using NBi.GenbiL.Action; using Sprache; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NBi.GenbiL.Parser { class Action { public readonly static Parser<IAction> Parser = ( from sentence in Case.Parser.Or(Setting.Parser.Or(Suite.Parser.Or(Template.Parser))) from terminator in Grammar.Terminator.AtLeastOnce() select sentence ); } }
using NBi.GenbiL.Action; using Sprache; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NBi.GenbiL.Parser { class Action { public readonly static Parser<IAction> Parser = ( from sentence in Case.Parser.Or(Setting.Parser.Or(Suite.Parser.Or(Template.Parser.Or(Variable.Parser)))) from terminator in Grammar.Terminator.AtLeastOnce() select sentence ); } }
Fix a http request issues.
using System; using System.IO; using System.Net; using System.Text; using Wox.Plugin; namespace Wox.Infrastructure.Http { public class HttpRequest { public static string Get(string url, string encoding = "UTF8") { return Get(url, encoding, HttpProxy.Instance); } private static string Get(string url, string encoding, IHttpProxy proxy) { if (string.IsNullOrEmpty(url)) return string.Empty; HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; request.Method = "GET"; request.Timeout = 10 * 1000; if (proxy != null && proxy.Enabled && !string.IsNullOrEmpty(proxy.Server)) { if (string.IsNullOrEmpty(proxy.UserName) || string.IsNullOrEmpty(proxy.Password)) { request.Proxy = new WebProxy(proxy.Server, proxy.Port); } else { request.Proxy = new WebProxy(proxy.Server, proxy.Port) { Credentials = new NetworkCredential(proxy.UserName, proxy.Password) }; } } try { HttpWebResponse response = request.GetResponse() as HttpWebResponse; if (response != null) { Stream stream = response.GetResponseStream(); if (stream != null) { using (StreamReader reader = new StreamReader(stream, Encoding.GetEncoding(encoding))) { return reader.ReadToEnd(); } } } } catch (Exception e) { return string.Empty; } return string.Empty; } } }
using System; using System.IO; using System.Net; using System.Text; using Wox.Plugin; namespace Wox.Infrastructure.Http { public class HttpRequest { public static string Get(string url, string encoding = "UTF-8") { return Get(url, encoding, HttpProxy.Instance); } private static string Get(string url, string encoding, IHttpProxy proxy) { if (string.IsNullOrEmpty(url)) return string.Empty; HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; request.Method = "GET"; request.Timeout = 10 * 1000; if (proxy != null && proxy.Enabled && !string.IsNullOrEmpty(proxy.Server)) { if (string.IsNullOrEmpty(proxy.UserName) || string.IsNullOrEmpty(proxy.Password)) { request.Proxy = new WebProxy(proxy.Server, proxy.Port); } else { request.Proxy = new WebProxy(proxy.Server, proxy.Port) { Credentials = new NetworkCredential(proxy.UserName, proxy.Password) }; } } try { HttpWebResponse response = request.GetResponse() as HttpWebResponse; if (response != null) { Stream stream = response.GetResponseStream(); if (stream != null) { using (StreamReader reader = new StreamReader(stream, Encoding.GetEncoding(encoding))) { return reader.ReadToEnd(); } } } } catch (Exception e) { return string.Empty; } return string.Empty; } } }
Add trace to check effective bug
using Microsoft.SqlServer.Management.Smo; using System; using System.Collections.Generic; using System.Data.SqlClient; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NBi.Core.Batch.SqlServer { class BatchRunCommand : IDecorationCommandImplementation { private readonly string connectionString; private readonly string fullPath; public BatchRunCommand(IBatchRunCommand command, SqlConnection connection) { this.connectionString = connection.ConnectionString; this.fullPath = command.FullPath; } public void Execute() { if (!File.Exists(fullPath)) throw new ExternalDependencyNotFoundException(fullPath); var script = File.ReadAllText(fullPath); var server = new Server(); server.ConnectionContext.ConnectionString = connectionString; server.ConnectionContext.ExecuteNonQuery(script); } } }
using Microsoft.SqlServer.Management.Smo; using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NBi.Core.Batch.SqlServer { class BatchRunCommand : IDecorationCommandImplementation { private readonly string connectionString; private readonly string fullPath; public BatchRunCommand(IBatchRunCommand command, SqlConnection connection) { this.connectionString = connection.ConnectionString; this.fullPath = command.FullPath; } public void Execute() { if (!File.Exists(fullPath)) throw new ExternalDependencyNotFoundException(fullPath); var script = File.ReadAllText(fullPath); Trace.WriteLineIf(NBiTraceSwitch.TraceVerbose, script); var server = new Server(); server.ConnectionContext.ConnectionString = connectionString; server.ConnectionContext.ExecuteNonQuery(script); } } }
Fix songselect blur potentially never being applied
// 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.Graphics; using osu.Framework.Graphics.Transforms; using osu.Game.Graphics.Backgrounds; using osuTK; namespace osu.Game.Screens { public abstract class BlurrableBackgroundScreen : BackgroundScreen { protected Background Background; protected Vector2 BlurTarget; public TransformSequence<Background> BlurTo(Vector2 sigma, double duration, Easing easing = Easing.None) => Background?.BlurTo(BlurTarget = sigma, duration, easing); } }
// 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.Graphics; using osu.Framework.Graphics.Transforms; using osu.Game.Graphics.Backgrounds; using osuTK; namespace osu.Game.Screens { public abstract class BlurrableBackgroundScreen : BackgroundScreen { protected Background Background; protected Vector2 BlurTarget; public TransformSequence<Background> BlurTo(Vector2 sigma, double duration, Easing easing = Easing.None) { BlurTarget = sigma; return Background?.BlurTo(BlurTarget, duration, easing); } } }
Reformat code in metdata provider
using System; using DbLocalizationProvider.Internal; namespace DbLocalizationProvider.DataAnnotations { internal class ModelMetadataLocalizationHelper { internal static string GetTranslation(string resourceKey) { var result = resourceKey; if(!ConfigurationContext.Current.EnableLocalization()) { return result; } var localizedDisplayName = LocalizationProvider.Current.GetString(resourceKey); result = localizedDisplayName; if(!ConfigurationContext.Current.ModelMetadataProviders.EnableLegacyMode()) return result; // for the legacy purposes - we need to look for this resource value as resource translation // once again - this will make sure that existing XPath resources are still working if(localizedDisplayName.StartsWith("/")) { result = LocalizationProvider.Current.GetString(localizedDisplayName); } //If other data annotations exists execept for [Display], an exception is thrown when displayname is "" //It should be null to avoid exception as ModelMetadata.GetDisplayName only checks for null and not String.Empty if (string.IsNullOrWhiteSpace(localizedDisplayName)) { return null; } return result; } internal static string GetTranslation(Type containerType, string propertyName) { var resourceKey = ResourceKeyBuilder.BuildResourceKey(containerType, propertyName); return GetTranslation(resourceKey); } } }
using System; using DbLocalizationProvider.Internal; namespace DbLocalizationProvider.DataAnnotations { internal class ModelMetadataLocalizationHelper { internal static string GetTranslation(string resourceKey) { var result = resourceKey; if(!ConfigurationContext.Current.EnableLocalization()) return result; var localizedDisplayName = LocalizationProvider.Current.GetString(resourceKey); result = localizedDisplayName; if(!ConfigurationContext.Current.ModelMetadataProviders.EnableLegacyMode()) return result; // for the legacy purposes - we need to look for this resource value as resource translation // once again - this will make sure that existing XPath resources are still working if(localizedDisplayName.StartsWith("/")) result = LocalizationProvider.Current.GetString(localizedDisplayName); // If other data annotations exists execept for [Display], an exception is thrown when displayname is "" // It should be null to avoid exception as ModelMetadata.GetDisplayName only checks for null and not String.Empty return string.IsNullOrWhiteSpace(localizedDisplayName) ? null : result; } internal static string GetTranslation(Type containerType, string propertyName) { var resourceKey = ResourceKeyBuilder.BuildResourceKey(containerType, propertyName); return GetTranslation(resourceKey); } } }
Make the delegate test more challenging
using System; public delegate int IntMap(int x); public static class Program { private static int Apply(IntMap f, int x) { return f(x); } private static int Square(int x) { return x * x; } public static void Main() { Console.WriteLine(Apply(Square, 10)); } }
using System; public delegate T2 Map<T1, T2>(T1 x); public static class Program { private static int Apply(Map<int, int> f, int x) { return f(x); } private static int Square(int x) { return x * x; } public static void Main() { Console.WriteLine(Apply(Square, 10)); } }
Update company name and copyright.
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("postalcodefinder")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("postalcodefinder")] [assembly: AssemblyCopyright("Copyright © Microsoft 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("6a604569-bbd4-4f13-b308-ff3969ff7549")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
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("postalcodefinder")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Experian")] [assembly: AssemblyProduct("postalcodefinder")] [assembly: AssemblyCopyright("Copyright © Experian 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("6a604569-bbd4-4f13-b308-ff3969ff7549")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
Print in reversed order method
namespace LinkedListInOrderInsertion { using System; using System.Collections.Generic; public class LinkedList { private Element Head = null; private Element Iterator = new Element(); internal void Add(int value) { Element insertedElement = new Element { Value = value }; if (Head == null) { Head = insertedElement; Iterator.Next = Head; } else { Element current = Head; if(current.Value > insertedElement.Value) { Head = insertedElement; Head.Next = current; Iterator.Next = Head; return; } while(current.Next != null) { if(current.Next.Value > insertedElement.Value) { insertedElement.Next = current.Next; current.Next = insertedElement; return; } current = current.Next; } current.Next = insertedElement; } } internal int Last() { Element current = Head; while (current.Next != null) { current = current.Next; } return current.Value; } internal IEnumerable<Element> Next() { if(Iterator.Next != null) { yield return Iterator.Next; } } } }
namespace LinkedListInOrderInsertion { using System; using System.Collections.Generic; public class LinkedList { private Element Head = null; private Element Iterator = new Element(); internal void Add(int value) { Element insertedElement = new Element { Value = value }; if (Head == null) { Head = insertedElement; Iterator.Next = Head; } else { Element current = Head; if(current.Value > insertedElement.Value) { Head = insertedElement; Head.Next = current; Iterator.Next = Head; return; } while(current.Next != null) { if(current.Next.Value > insertedElement.Value) { insertedElement.Next = current.Next; current.Next = insertedElement; return; } current = current.Next; } current.Next = insertedElement; } } internal int Last() { Element current = Head; while (current.Next != null) { current = current.Next; } return current.Value; } internal void PrintInReversedOrder(Element startElement) { if (startElement == null) { return; } PrintInReversedOrder(startElement.Next); Console.WriteLine(startElement.Value); } internal IEnumerable<Element> Next() { if(Iterator.Next != null) { yield return Iterator.Next; } } } }
Add extension methods to run guaranteed synchronous disposal
// 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; namespace osu.Framework.Graphics { /// <summary> /// Holds extension methods for <see cref="Drawable"/>. /// </summary> public static class DrawableExtensions { /// <summary> /// Adjusts specified properties of a <see cref="Drawable"/>. /// </summary> /// <param name="drawable">The <see cref="Drawable"/> whose properties should be adjusted.</param> /// <param name="adjustment">The adjustment function.</param> /// <returns>The given <see cref="Drawable"/>.</returns> public static T With<T>(this T drawable, Action<T> adjustment) where T : Drawable { adjustment?.Invoke(drawable); return drawable; } } }
// 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.Development; using osu.Framework.Graphics.Containers; namespace osu.Framework.Graphics { /// <summary> /// Holds extension methods for <see cref="Drawable"/>. /// </summary> public static class DrawableExtensions { /// <summary> /// Adjusts specified properties of a <see cref="Drawable"/>. /// </summary> /// <param name="drawable">The <see cref="Drawable"/> whose properties should be adjusted.</param> /// <param name="adjustment">The adjustment function.</param> /// <returns>The given <see cref="Drawable"/>.</returns> public static T With<T>(this T drawable, Action<T> adjustment) where T : Drawable { adjustment?.Invoke(drawable); return drawable; } /// <summary> /// Forces removal of this drawable from its parent, followed by immediate synchronous disposal. /// </summary> /// <remarks> /// This is intended as a temporary solution for the fact that there is no way to easily dispose /// a component in a way that is guaranteed to be synchronously run on the update thread. /// /// Eventually components will have a better method for unloading. /// </remarks> /// <param name="drawable">The <see cref="Drawable"/> to be disposed.</param> public static void RemoveAndDisposeImmediately(this Drawable drawable) { ThreadSafety.EnsureUpdateThread(); switch (drawable.Parent) { case Container cont: cont.Remove(drawable); break; case CompositeDrawable comp: comp.RemoveInternal(drawable); break; } drawable.Dispose(); } } }
Add english as well as german
// WhistTest.cs // <copyright file="WhistTest.cs"> This code is protected under the MIT License. </copyright> using System; using CardGames.Whist; namespace ConsoleTesting { /// <summary> /// The whist test class /// </summary> public class WhistTest : IGameTest { /// <summary> /// Run the test /// </summary> public void RunTest() { Whist whist = new Whist(); ConsolePlayer p1 = new ConsolePlayer(); ConsolePlayer p2 = new ConsolePlayer(); ConsolePlayer p3 = new ConsolePlayer(); whist.AddPlayer(p1); whist.AddPlayer(p2); whist.AddPlayer(p3); whist.Start(); } public void RunWithAi() { Console.WriteLine("Es gibt kein AI"); Console.WriteLine("There is no AI") } } }
// WhistTest.cs // <copyright file="WhistTest.cs"> This code is protected under the MIT License. </copyright> using System; using CardGames.Whist; namespace ConsoleTesting { /// <summary> /// The whist test class /// </summary> public class WhistTest : IGameTest { /// <summary> /// Run the test /// </summary> public void RunTest() { Whist whist = new Whist(); ConsolePlayer p1 = new ConsolePlayer(); ConsolePlayer p2 = new ConsolePlayer(); ConsolePlayer p3 = new ConsolePlayer(); whist.AddPlayer(p1); whist.AddPlayer(p2); whist.AddPlayer(p3); whist.Start(); } public void RunWithAi() { Console.WriteLine("Es gibt kein AI"); Console.WriteLine("There is no AI"); } } }
Update sentry to send data necessary for linking events with users
using System; using System.Collections.Generic; using osu_StreamCompanion.Code.Helpers; using Sentry; using StreamCompanionTypes.Enums; using StreamCompanionTypes.Interfaces.Services; namespace osu_StreamCompanion.Code.Core.Loggers { public class SentryLogger : IContextAwareLogger { public static string SentryDsn = "https://3187b2a91f23411ab7ec5f85ad7d80b8@sentry.pioo.space/2"; public static SentryClient SentryClient { get; } = new SentryClient(new SentryOptions { Dsn = SentryDsn, Release = Program.ScVersion }); public static Dictionary<string, string> ContextData { get; } = new Dictionary<string, string>(); private object _lockingObject = new object(); public void Log(object logMessage, LogLevel logLevel, params string[] vals) { if (logLevel == LogLevel.Critical && logMessage is Exception exception && !(exception is NonLoggableException)) { var sentryEvent = new SentryEvent(exception); lock (_lockingObject) { foreach (var contextKeyValue in ContextData) { sentryEvent.SetExtra(contextKeyValue.Key, contextKeyValue.Value); } SentryClient.CaptureEvent(sentryEvent); } } } public void SetContextData(string key, string value) { lock (_lockingObject) ContextData[key] = value; } } }
using System; using System.Collections.Generic; using osu_StreamCompanion.Code.Helpers; using Sentry; using StreamCompanionTypes.Enums; using StreamCompanionTypes.Interfaces.Services; namespace osu_StreamCompanion.Code.Core.Loggers { public class SentryLogger : IContextAwareLogger { public static string SentryDsn = "https://3187b2a91f23411ab7ec5f85ad7d80b8@sentry.pioo.space/2"; public static SentryClient SentryClient { get; } = new SentryClient(new SentryOptions { Dsn = SentryDsn, Release = Program.ScVersion, SendDefaultPii = true, BeforeSend = BeforeSend }); private static SentryEvent? BeforeSend(SentryEvent arg) { arg.User.IpAddress = null; return arg; } public static Dictionary<string, string> ContextData { get; } = new Dictionary<string, string>(); private object _lockingObject = new object(); public void Log(object logMessage, LogLevel logLevel, params string[] vals) { if (logLevel == LogLevel.Critical && logMessage is Exception exception && !(exception is NonLoggableException)) { var sentryEvent = new SentryEvent(exception); lock (_lockingObject) { foreach (var contextKeyValue in ContextData) { sentryEvent.SetExtra(contextKeyValue.Key, contextKeyValue.Value); } SentryClient.CaptureEvent(sentryEvent); } } } public void SetContextData(string key, string value) { lock (_lockingObject) ContextData[key] = value; } } }
Make internals visible to the testing project
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("Slack.Webhooks")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Slack.Webhooks")] [assembly: AssemblyCopyright("")] [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("98c19dcd-28da-4ebf-8e81-c9e051d65625")] // 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.1.8.*")] [assembly: AssemblyFileVersion("0.1.8.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Slack.Webhooks")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Slack.Webhooks")] [assembly: AssemblyCopyright("")] [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("98c19dcd-28da-4ebf-8e81-c9e051d65625")] // 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.1.8.*")] [assembly: AssemblyFileVersion("0.1.8.0")] [assembly: InternalsVisibleTo("Slack.Webhooks.Tests")]
Add IsLocked to audit for account locked message
using System.Collections.Generic; using SFA.DAS.Audit.Types; namespace SFA.DAS.EmployerUsers.Domain.Auditing { public class AccountLockedAuditMessage : EmployerUsersAuditMessage { public AccountLockedAuditMessage(User user) { Category = "ACCOUNT_LOCKED"; Description = $"User {user.Email} (id: {user.Id}) has exceeded the limit of failed logins and the account has been locked"; AffectedEntity = new Entity { Type = "User", Id = user.Id }; ChangedProperties = new List<PropertyUpdate> { PropertyUpdate.FromInt(nameof(user.FailedLoginAttempts), user.FailedLoginAttempts) }; } } }
using System.Collections.Generic; using SFA.DAS.Audit.Types; namespace SFA.DAS.EmployerUsers.Domain.Auditing { public class AccountLockedAuditMessage : EmployerUsersAuditMessage { public AccountLockedAuditMessage(User user) { Category = "ACCOUNT_LOCKED"; Description = $"User {user.Email} (id: {user.Id}) has exceeded the limit of failed logins and the account has been locked"; AffectedEntity = new Entity { Type = "User", Id = user.Id }; ChangedProperties = new List<PropertyUpdate> { PropertyUpdate.FromInt(nameof(user.FailedLoginAttempts), user.FailedLoginAttempts), PropertyUpdate.FromBool(nameof(user.IsLocked), user.IsLocked) }; } } }
Change date format to iso format
using System; using FluentMigrator.Runner.Generators.Generic; namespace FluentMigrator.Runner.Generators.Jet { public class JetQuoter : GenericQuoter { public override string OpenQuote { get { return "["; } } public override string CloseQuote { get { return "]"; } } public override string CloseQuoteEscapeString { get { return string.Empty; } } public override string OpenQuoteEscapeString { get { return string.Empty; } } public override string FormatDateTime(DateTime value) { return ValueQuote + (value).ToString("MM/dd/yyyy HH:mm:ss") + ValueQuote; } } }
using System; using FluentMigrator.Runner.Generators.Generic; namespace FluentMigrator.Runner.Generators.Jet { public class JetQuoter : GenericQuoter { public override string OpenQuote { get { return "["; } } public override string CloseQuote { get { return "]"; } } public override string CloseQuoteEscapeString { get { return string.Empty; } } public override string OpenQuoteEscapeString { get { return string.Empty; } } public override string FormatDateTime(DateTime value) { return ValueQuote + (value).ToString("YYYY-MM-DD HH:mm:ss") + ValueQuote; } } }
Support API Key authentication using header
using System.Data.Entity; using System.Linq; using System.Security.Claims; using System.Text.Encodings.Web; using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using SupportManager.DAL; namespace SupportManager.Web.Infrastructure.ApiKey { public class ApiKeyAuthenticationHandler : AuthenticationHandler<ApiKeyAuthenticationOptions> { private readonly SupportManagerContext db; public ApiKeyAuthenticationHandler(SupportManagerContext db, IOptionsMonitor<ApiKeyAuthenticationOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock) { this.db = db; } protected override async Task<AuthenticateResult> HandleAuthenticateAsync() { if (Request.Query["apikey"].Count != 1) return AuthenticateResult.Fail("Invalid request"); var key = Request.Query["apikey"][0]; var user = await db.ApiKeys.Where(apiKey => apiKey.Value == key).Select(apiKey => apiKey.User) .SingleOrDefaultAsync(); if (user == null) return AuthenticateResult.Fail("Invalid API Key"); var claims = new[] {new Claim(ClaimTypes.Name, user.Login)}; var identity = new ClaimsIdentity(claims, Scheme.Name); var principal = new ClaimsPrincipal(identity); var ticket = new AuthenticationTicket(principal, Scheme.Name); return AuthenticateResult.Success(ticket); } } }
using System.Data.Entity; using System.Linq; using System.Security.Claims; using System.Text.Encodings.Web; using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using SupportManager.DAL; namespace SupportManager.Web.Infrastructure.ApiKey { public class ApiKeyAuthenticationHandler : AuthenticationHandler<ApiKeyAuthenticationOptions> { private readonly SupportManagerContext db; public ApiKeyAuthenticationHandler(SupportManagerContext db, IOptionsMonitor<ApiKeyAuthenticationOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock) { this.db = db; } protected override async Task<AuthenticateResult> HandleAuthenticateAsync() { string key; if (Request.Headers["X-API-Key"].Count == 1) key = Request.Headers["X-API-Key"][0]; else if (Request.Query["apikey"].Count == 1) key = Request.Query["apikey"][0]; else return AuthenticateResult.Fail("Invalid request"); var user = await db.ApiKeys.Where(apiKey => apiKey.Value == key).Select(apiKey => apiKey.User) .SingleOrDefaultAsync(); if (user == null) return AuthenticateResult.Fail("Invalid API Key"); var claims = new[] {new Claim(ClaimTypes.Name, user.Login)}; var identity = new ClaimsIdentity(claims, Scheme.Name); var principal = new ClaimsPrincipal(identity); var ticket = new AuthenticationTicket(principal, Scheme.Name); return AuthenticateResult.Success(ticket); } } }
Remove var keyword in tests
using Newtonsoft.Json; using Telegram.Bot.Requests; using Xunit; namespace Telegram.Bot.Tests.Unit.Serialization { public class MethodNameTests { [Fact(DisplayName = "Should serialize method name in webhook responses")] public void Should_Serialize_MethodName_In_Webhook_Responses() { var sendMessageRequest = new SendMessageRequest(1, "text") { IsWebhookResponse = true }; var request = JsonConvert.SerializeObject(sendMessageRequest); Assert.Contains(@"""method"":""sendMessage""", request); } [Fact(DisplayName = "Should not serialize method name in webhook responses")] public void Should_Not_Serialize_MethodName_In_Webhook_Responses() { var sendMessageRequest = new SendMessageRequest(1, "text") { IsWebhookResponse = false }; var request = JsonConvert.SerializeObject(sendMessageRequest); Assert.DoesNotContain(@"""method"":""sendMessage""", request); } } }
using Newtonsoft.Json; using Telegram.Bot.Requests; using Xunit; namespace Telegram.Bot.Tests.Unit.Serialization { public class MethodNameTests { [Fact(DisplayName = "Should serialize method name in webhook responses")] public void Should_Serialize_MethodName_In_Webhook_Responses() { SendMessageRequest sendMessageRequest = new SendMessageRequest(1, "text") { IsWebhookResponse = true }; var request = JsonConvert.SerializeObject(sendMessageRequest); Assert.Contains(@"""method"":""sendMessage""", request); } [Fact(DisplayName = "Should not serialize method name in webhook responses")] public void Should_Not_Serialize_MethodName_In_Webhook_Responses() { SendMessageRequest sendMessageRequest = new SendMessageRequest(1, "text") { IsWebhookResponse = false }; var request = JsonConvert.SerializeObject(sendMessageRequest); Assert.DoesNotContain(@"""method"":""sendMessage""", request); } } }
Fix buggy type lookup when Type.FindType fails
using System; using System.Reflection; namespace FullSerializer.Internal { /// <summary> /// Provides APIs for looking up types based on their name. /// </summary> internal static class fsTypeLookup { public static Type GetType(string typeName) { //-- // see // http://answers.unity3d.com/questions/206665/typegettypestring-does-not-work-in-unity.html // Try Type.GetType() first. This will work with types defined by the Mono runtime, in // the same assembly as the caller, etc. var type = Type.GetType(typeName); // If it worked, then we're done here if (type != null) return type; // If the TypeName is a full name, then we can try loading the defining assembly // directly if (typeName.Contains(".")) { // Get the name of the assembly (Assumption is that we are using fully-qualified // type names) var assemblyName = typeName.Substring(0, typeName.IndexOf('.')); // Attempt to load the indicated Assembly var assembly = Assembly.Load(assemblyName); if (assembly == null) return null; // Ask that assembly to return the proper Type type = assembly.GetType(typeName); if (type != null) return type; } // If we still haven't found the proper type, we can enumerate all of the loaded // assemblies and see if any of them define the type var currentAssembly = Assembly.GetExecutingAssembly(); var referencedAssemblies = currentAssembly.GetReferencedAssemblies(); foreach (var assemblyName in referencedAssemblies) { // Load the referenced assembly var assembly = Assembly.Load(assemblyName); if (assembly != null) { // See if that assembly defines the named type type = assembly.GetType(typeName); if (type != null) return type; } } // The type just couldn't be found... return null; } } }
using System; using System.Reflection; namespace FullSerializer.Internal { /// <summary> /// Provides APIs for looking up types based on their name. /// </summary> internal static class fsTypeLookup { /// <summary> /// Attempts to lookup the given type. Returns null if the type lookup fails. /// </summary> public static Type GetType(string typeName) { Type type = null; // Try a direct type lookup type = Type.GetType(typeName); if (type != null) { return type; } // If we still haven't found the proper type, we can enumerate all of the loaded // assemblies and see if any of them define the type foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) { // See if that assembly defines the named type type = assembly.GetType(typeName); if (type != null) { return type; } } return null; } } }
Verify that "to-project" is a valid queue name
using Lokad.Cqrs.Build.Engine; using NUnit.Framework; namespace Lokad.Cqrs { [TestFixture] public sealed class MiscTests { // ReSharper disable InconsistentNaming [Test] public void Azure_queues_regex_is_valid() { Assert.IsTrue(AzureEngineModule.QueueName.IsMatch("some-queue")); Assert.IsFalse(AzureEngineModule.QueueName.IsMatch("-some-queue")); } } }
using Lokad.Cqrs.Build.Engine; using NUnit.Framework; namespace Lokad.Cqrs { [TestFixture] public sealed class MiscTests { // ReSharper disable InconsistentNaming [Test] public void Azure_queues_regex_is_valid() { Assert.IsTrue(AzureEngineModule.QueueName.IsMatch("some-queue")); Assert.IsTrue(AzureEngineModule.QueueName.IsMatch("to-watchtower")); Assert.IsFalse(AzureEngineModule.QueueName.IsMatch("-some-queue")); } } }
Test names changed to Should notation
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using OpcMock; namespace OpcMockTests { [TestClass] public class ProtocolComparerTests { private const int EQUALITY = 0; [TestMethod] public void Protocols_With_The_Same_Name_Are_Equal() { ProtocolComparer pc = new ProtocolComparer(); OpcMockProtocol omp1 = new OpcMockProtocol("omp1"); OpcMockProtocol compare1 = new OpcMockProtocol("omp1"); Assert.AreEqual(EQUALITY, pc.Compare(omp1, compare1)); } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using OpcMock; namespace OpcMockTests { [TestClass] public class ProtocolComparerTests { private const int EQUALITY = 0; [TestMethod] public void ProtocolsWithTheSameNameShould_Be_Equal() { ProtocolComparer pc = new ProtocolComparer(); OpcMockProtocol omp1 = new OpcMockProtocol("omp1"); OpcMockProtocol compare1 = new OpcMockProtocol("omp1"); Assert.AreEqual(EQUALITY, pc.Compare(omp1, compare1)); } } }
Update types on Message Bus definition
using System; namespace Glimpse { public interface IMessageBus { IObservable<T> Listen<T>(); IObservable<T> ListenIncludeLatest<T>(); void SendMessage(object message); } }
using System; namespace Glimpse { public interface IMessageBus { IObservable<T> Listen<T>() where T : IMessage; IObservable<T> ListenIncludeLatest<T>() where T : IMessage; void SendMessage(IMessage message); } }
Change so that the minimum hash length is 6 characters and not 10
using SFA.DAS.EmployerApprenticeshipsService.Domain.Interfaces; using HashidsNet; namespace SFA.DAS.EmployerApprenticeshipsService.Infrastructure.Services { public class HashingService : IHashingService { public string HashValue(long id) { var hashIds = new Hashids("SFA: digital apprenticeship service",10, "46789BCDFGHJKLMNPRSTVWXY"); return hashIds.EncodeLong(id); } } }
using SFA.DAS.EmployerApprenticeshipsService.Domain.Interfaces; using HashidsNet; namespace SFA.DAS.EmployerApprenticeshipsService.Infrastructure.Services { public class HashingService : IHashingService { public string HashValue(long id) { var hashIds = new Hashids("SFA: digital apprenticeship service",6, "46789BCDFGHJKLMNPRSTVWXY"); return hashIds.EncodeLong(id); } } }
Print source and destination addresses on ICMPv6 packets
using TAP; using System; using System.Net; public class TAPCfgTest { private static void Main(string[] args) { EthernetDevice dev = new EthernetDevice(); dev.Start("Device name"); Console.WriteLine("Got device name: {0}", dev.DeviceName); dev.MTU = 1280; dev.SetAddress(IPAddress.Parse("192.168.1.1"), 16); dev.SetAddress(IPAddress.Parse("fc00::1"), 64); dev.Enabled = true; while (true) { EthernetFrame frame = dev.Read(); if (frame == null) break; if (frame.EtherType == EtherType.IPv6) { IPv6Packet packet = new IPv6Packet(frame.Payload); if (packet.NextHeader == ProtocolType.ICMPv6) { ICMPv6Type type = (ICMPv6Type) packet.Payload[0]; Console.WriteLine("Got ICMPv6 packet type {0}", type); Console.WriteLine("Data: {0}", BitConverter.ToString(packet.Payload)); } } Console.WriteLine("Read Ethernet frame of type {0}", frame.EtherType); Console.WriteLine("Source address: {0}", BitConverter.ToString(frame.SourceAddress)); Console.WriteLine("Destination address: {0}", BitConverter.ToString(frame.DestinationAddress)); } } }
using TAP; using System; using System.Net; public class TAPCfgTest { private static void Main(string[] args) { EthernetDevice dev = new EthernetDevice(); dev.Start("Device name"); Console.WriteLine("Got device name: {0}", dev.DeviceName); dev.MTU = 1280; dev.SetAddress(IPAddress.Parse("192.168.1.1"), 16); dev.SetAddress(IPAddress.Parse("fc00::1"), 64); dev.Enabled = true; while (true) { EthernetFrame frame = dev.Read(); if (frame == null) break; if (frame.EtherType == EtherType.IPv6) { IPv6Packet packet = new IPv6Packet(frame.Payload); if (packet.NextHeader == ProtocolType.ICMPv6) { ICMPv6Type type = (ICMPv6Type) packet.Payload[0]; Console.WriteLine("Got ICMPv6 packet type {0}", type); Console.WriteLine("Src: {0}", packet.Source); Console.WriteLine("Dst: {0}", packet.Destination); Console.WriteLine("Data: {0}", BitConverter.ToString(packet.Payload)); } } Console.WriteLine("Read Ethernet frame of type {0}", frame.EtherType); Console.WriteLine("Source address: {0}", BitConverter.ToString(frame.SourceAddress)); Console.WriteLine("Destination address: {0}", BitConverter.ToString(frame.DestinationAddress)); } } }
Add alwaysShowDecimals param to FormatAccuracy
// 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. namespace osu.Game.Utils { public static class FormatUtils { /// <summary> /// Turns the provided accuracy into a percentage with 2 decimal places. /// Omits all decimal places when <paramref name="accuracy"/> equals 1d. /// </summary> /// <param name="accuracy">The accuracy to be formatted</param> /// <returns>formatted accuracy in percentage</returns> public static string FormatAccuracy(this double accuracy) => accuracy == 1 ? "100%" : $"{accuracy:0.00%}"; /// <summary> /// Turns the provided accuracy into a percentage with 2 decimal places. /// Omits all decimal places when <paramref name="accuracy"/> equals 100m. /// </summary> /// <param name="accuracy">The accuracy to be formatted</param> /// <returns>formatted accuracy in percentage</returns> public static string FormatAccuracy(this decimal accuracy) => accuracy == 100 ? "100%" : $"{accuracy:0.00}%"; } }
// 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. namespace osu.Game.Utils { public static class FormatUtils { /// <summary> /// Turns the provided accuracy into a percentage with 2 decimal places. /// </summary> /// <param name="accuracy">The accuracy to be formatted</param> /// <param name="alwaysShowDecimals">Whether to show decimal places if <paramref name="accuracy"/> equals 1d</param> /// <returns>formatted accuracy in percentage</returns> public static string FormatAccuracy(this double accuracy, bool alwaysShowDecimals = false) => accuracy == 1 && !alwaysShowDecimals ? "100%" : $"{accuracy:0.00%}"; /// <summary> /// Turns the provided accuracy into a percentage with 2 decimal places. /// </summary> /// <param name="accuracy">The accuracy to be formatted</param> /// <param name="alwaysShowDecimals">Whether to show decimal places if <paramref name="accuracy"/> equals 100m</param> /// <returns>formatted accuracy in percentage</returns> public static string FormatAccuracy(this decimal accuracy, bool alwaysShowDecimals = false) => accuracy == 100 && !alwaysShowDecimals ? "100%" : $"{accuracy:0.00}%"; } }
Use DotNetCoreBuild in Cake script.
////////////////////////////////////////////////////////////////////// // ARGUMENTS ////////////////////////////////////////////////////////////////////// var target = Argument("target", "Default"); var configuration = Argument("configuration", "Release"); ////////////////////////////////////////////////////////////////////// // TASKS ////////////////////////////////////////////////////////////////////// Task("Restore-NuGet-Packages") .Does(() => { NuGetRestore("SimpSim.NET.sln"); }); Task("Build") .IsDependentOn("Restore-NuGet-Packages") .Does(() => { MSBuild("SimpSim.NET.sln", settings => settings.SetConfiguration(configuration)); }); Task("Run-Unit-Tests") .IsDependentOn("Build") .Does(() => { DotNetCoreTest("./SimpSim.NET.Tests/SimpSim.NET.Tests.csproj"); DotNetCoreTest("./SimpSim.NET.Presentation.Tests/SimpSim.NET.Presentation.Tests.csproj"); }); ////////////////////////////////////////////////////////////////////// // TASK TARGETS ////////////////////////////////////////////////////////////////////// Task("Default") .IsDependentOn("Run-Unit-Tests"); ////////////////////////////////////////////////////////////////////// // EXECUTION ////////////////////////////////////////////////////////////////////// RunTarget(target);
////////////////////////////////////////////////////////////////////// // ARGUMENTS ////////////////////////////////////////////////////////////////////// var target = Argument("target", "Default"); var configuration = Argument("configuration", "Release"); ////////////////////////////////////////////////////////////////////// // TASKS ////////////////////////////////////////////////////////////////////// Task("Build") .Does(() => { DotNetCoreBuild("SimpSim.NET.sln", new DotNetCoreBuildSettings{Configuration = configuration}); }); Task("Run-Unit-Tests") .IsDependentOn("Build") .Does(() => { DotNetCoreTest(); }); ////////////////////////////////////////////////////////////////////// // TASK TARGETS ////////////////////////////////////////////////////////////////////// Task("Default") .IsDependentOn("Run-Unit-Tests"); ////////////////////////////////////////////////////////////////////// // EXECUTION ////////////////////////////////////////////////////////////////////// RunTarget(target);
Add method for querying active entities
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ECS { public class EntityComponentSystem { private EntityManager entityManager; private SystemManager systemManager; public EntityComponentSystem() { entityManager = new EntityManager(); systemManager = new SystemManager(); systemManager.context = this; } public Entity CreateEntity() { return entityManager.CreateEntity(); } public void AddSystem(System system, int priority = 0) { systemManager.SetSystem(system, priority); } public void Update(float deltaTime) { foreach (var systems in systemManager.SystemsByPriority()) { entityManager.ProcessQueues(); foreach (var system in systems) { system.processAll(entityManager.GetEntitiesForAspect(system.Aspect), deltaTime); } } systemManager.ProcessQueues(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ECS { public class EntityComponentSystem { private EntityManager entityManager; private SystemManager systemManager; public EntityComponentSystem() { entityManager = new EntityManager(); systemManager = new SystemManager(); systemManager.context = this; } public Entity CreateEntity() { return entityManager.CreateEntity(); } public void AddSystem(System system, int priority = 0) { systemManager.SetSystem(system, priority); } // TODO: Is this needed and is this right place for this method? public IEnumerable<Entity> QueryActiveEntities(Aspect aspect) { return entityManager.GetEntitiesForAspect(aspect); } public void Update(float deltaTime) { foreach (var systems in systemManager.SystemsByPriority()) { entityManager.ProcessQueues(); foreach (var system in systems) { system.processAll(entityManager.GetEntitiesForAspect(system.Aspect), deltaTime); } } systemManager.ProcessQueues(); } } }
Change remote app version to v0.1
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="AssemblyInfo.cs" company="Starboard"> // Copyright © 2011 All Rights Reserved // </copyright> // <summary> // AssemblyInfo.cs // </summary> // -------------------------------------------------------------------------------------------------------------------- using System.Reflection; using System.Runtime.InteropServices; using System.Windows; // 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("starboard-remote")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("starboard-remote")] [assembly: AssemblyCopyright("Copyright © Microsoft 2011")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="AssemblyInfo.cs" company="Starboard"> // Copyright © 2011 All Rights Reserved // </copyright> // <summary> // AssemblyInfo.cs // </summary> // -------------------------------------------------------------------------------------------------------------------- using System.Reflection; using System.Runtime.InteropServices; using System.Windows; // 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("starboard-remote")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Ascend")] [assembly: AssemblyProduct("starboard-remote")] [assembly: AssemblyCopyright("Copyright © Ascend 2011")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)] [assembly: AssemblyVersion("0.1.0.0")] [assembly: AssemblyFileVersion("0.1.0.0")]
Implement scanning assemblies for function types
using System; using System.Collections.Generic; using Manisero.DSLExecutor.Parser.SampleDSL.Parsing.Tokens; namespace Manisero.DSLExecutor.Parser.SampleDSL.ExpressionGeneration.FunctionExpressionGeneration.FunctionTypeResolvers { public class TypeSamplesAndSuffixConventionBasedFunctionTypeResolver : IFunctionTypeResolver { private readonly IEnumerable<Type> _functionTypeSamples; private readonly Lazy<IDictionary<string, Type>> _functionNameToTypeMap; public TypeSamplesAndSuffixConventionBasedFunctionTypeResolver(IEnumerable<Type> functionTypeSamples) { _functionTypeSamples = functionTypeSamples; _functionNameToTypeMap = new Lazy<IDictionary<string, Type>>(InitializeFunctionNameToTypeMap); } public Type Resolve(FunctionCall functionCall) { Type result; return !_functionNameToTypeMap.Value.TryGetValue(functionCall.FunctionName, out result) ? null : result; } private IDictionary<string, Type> InitializeFunctionNameToTypeMap() { var result = new Dictionary<string, Type>(); foreach (var functionTypeSample in _functionTypeSamples) { // TODO: Scan sample's assembly for function types // TODO: Fill result with type names without "Function" suffix } return result; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Manisero.DSLExecutor.Domain.FunctionsDomain; using Manisero.DSLExecutor.Extensions; using Manisero.DSLExecutor.Parser.SampleDSL.Parsing.Tokens; namespace Manisero.DSLExecutor.Parser.SampleDSL.ExpressionGeneration.FunctionExpressionGeneration.FunctionTypeResolvers { public class TypeSamplesAndSuffixConventionBasedFunctionTypeResolver : IFunctionTypeResolver { private readonly IEnumerable<Type> _functionTypeSamples; private readonly Lazy<IDictionary<string, Type>> _functionNameToTypeMap; public TypeSamplesAndSuffixConventionBasedFunctionTypeResolver(IEnumerable<Type> functionTypeSamples) { _functionTypeSamples = functionTypeSamples; _functionNameToTypeMap = new Lazy<IDictionary<string, Type>>(InitializeFunctionNameToTypeMap); } public Type Resolve(FunctionCall functionCall) { Type result; return !_functionNameToTypeMap.Value.TryGetValue(functionCall.FunctionName, out result) ? null : result; } private IDictionary<string, Type> InitializeFunctionNameToTypeMap() { var result = new Dictionary<string, Type>(); var assembliesToScan = _functionTypeSamples.Select(x => x.Assembly).Distinct(); var typesToScan = assembliesToScan.SelectMany(x => x.GetTypes()); foreach (var type in typesToScan) { var functionDefinitionImplementation = type.GetGenericInterfaceDefinitionImplementation(typeof(IFunction<>)); if (functionDefinitionImplementation == null) { continue; } // TODO: Fill result with type names without "Function" suffix } return result; } } }
Add missing copyright header text.
using Microsoft.MixedReality.Toolkit.Physics; using UnityEngine; namespace Microsoft.MixedReality.Toolkit.Input { /// <summary> /// The default implementation of IMixedRealityRaycastProvider. /// </summary> public class DefaultRaycastProvider : BaseDataProvider, IMixedRealityRaycastProvider { public DefaultRaycastProvider( IMixedRealityServiceRegistrar registrar, IMixedRealityInputSystem inputSystem, MixedRealityInputSystemProfile profile) : base(registrar, inputSystem, null, DefaultPriority, profile) { } /// <inheritdoc /> public bool Raycast(RayStep step, LayerMask[] prioritizedLayerMasks, out MixedRealityRaycastHit hitInfo) { var result = MixedRealityRaycaster.RaycastSimplePhysicsStep(step, step.Length, prioritizedLayerMasks, out RaycastHit physicsHit); hitInfo = new MixedRealityRaycastHit(physicsHit); return result; } /// <inheritdoc /> public bool SphereCast(RayStep step, float radius, LayerMask[] prioritizedLayerMasks, out MixedRealityRaycastHit hitInfo) { var result = MixedRealityRaycaster.RaycastSpherePhysicsStep(step, radius, step.Length, prioritizedLayerMasks, out RaycastHit physicsHit); hitInfo = new MixedRealityRaycastHit(physicsHit); return result; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using Microsoft.MixedReality.Toolkit.Physics; using UnityEngine; namespace Microsoft.MixedReality.Toolkit.Input { /// <summary> /// The default implementation of IMixedRealityRaycastProvider. /// </summary> public class DefaultRaycastProvider : BaseDataProvider, IMixedRealityRaycastProvider { public DefaultRaycastProvider( IMixedRealityServiceRegistrar registrar, IMixedRealityInputSystem inputSystem, MixedRealityInputSystemProfile profile) : base(registrar, inputSystem, null, DefaultPriority, profile) { } /// <inheritdoc /> public bool Raycast(RayStep step, LayerMask[] prioritizedLayerMasks, out MixedRealityRaycastHit hitInfo) { var result = MixedRealityRaycaster.RaycastSimplePhysicsStep(step, step.Length, prioritizedLayerMasks, out RaycastHit physicsHit); hitInfo = new MixedRealityRaycastHit(physicsHit); return result; } /// <inheritdoc /> public bool SphereCast(RayStep step, float radius, LayerMask[] prioritizedLayerMasks, out MixedRealityRaycastHit hitInfo) { var result = MixedRealityRaycaster.RaycastSpherePhysicsStep(step, radius, step.Length, prioritizedLayerMasks, out RaycastHit physicsHit); hitInfo = new MixedRealityRaycastHit(physicsHit); return result; } } }
Save trip before dismissing summary.
using System; using UIKit; namespace MyTrips.iOS { public partial class TripSummaryViewController : UIViewController { public ViewModel.CurrentTripViewModel ViewModel { get; set; } public TripSummaryViewController(IntPtr handle) : base(handle) { } public override void ViewDidLoad() { lblDateTime.Text = $"{DateTime.Now.ToString("M")} {DateTime.Now.ToString("t")}"; lblDistance.Text = $"{ViewModel.Distance} {ViewModel.DistanceUnits.ToLower()}"; lblDuration.Text = ViewModel.ElapsedTime; lblFuelConsumed.Text = $"{ViewModel.FuelConsumption} {ViewModel.FuelConsumptionUnits.ToLower()}"; lblDistance.Alpha = 0; lblDuration.Alpha = 0; lblTopSpeed.Alpha = 0; lblFuelConsumed.Alpha = 0; } public override void ViewDidAppear(bool animated) { base.ViewDidAppear(animated); lblDistance.FadeIn(0.4, 0.1f); lblDuration.FadeIn(0.4, 0.2f); lblTopSpeed.FadeIn(0.4, 0.3f); lblFuelConsumed.FadeIn(0.4, 0.4f); } async partial void BtnClose_TouchUpInside(UIButton sender) { await DismissViewControllerAsync(true); await ViewModel.SaveRecordingTripAsync(); } } }
using System; using UIKit; namespace MyTrips.iOS { public partial class TripSummaryViewController : UIViewController { public ViewModel.CurrentTripViewModel ViewModel { get; set; } public TripSummaryViewController(IntPtr handle) : base(handle) { } public override void ViewDidLoad() { lblDateTime.Text = $"{DateTime.Now.ToString("M")} {DateTime.Now.ToString("t")}"; lblDistance.Text = $"{ViewModel.Distance} {ViewModel.DistanceUnits.ToLower()}"; lblDuration.Text = ViewModel.ElapsedTime; lblFuelConsumed.Text = $"{ViewModel.FuelConsumption} {ViewModel.FuelConsumptionUnits.ToLower()}"; lblDistance.Alpha = 0; lblDuration.Alpha = 0; lblTopSpeed.Alpha = 0; lblFuelConsumed.Alpha = 0; } public override void ViewDidAppear(bool animated) { base.ViewDidAppear(animated); lblDistance.FadeIn(0.4, 0.1f); lblDuration.FadeIn(0.4, 0.2f); lblTopSpeed.FadeIn(0.4, 0.3f); lblFuelConsumed.FadeIn(0.4, 0.4f); } async partial void BtnClose_TouchUpInside(UIButton sender) { await ViewModel.SaveRecordingTripAsync(); await DismissViewControllerAsync(true); } } }
Test for migrations up to date.
using FluentAssertions; using MergableMigrations.EF6; using MergableMigrations.Specification.Implementation; using System; using System.Linq; using Xunit; namespace Mathematicians.UnitTests { public class SqlGeneratorTests { [Fact] public void CanGenerateSql() { var migrations = new Migrations(); var migrationHistory = new MigrationHistory(); var sqlGenerator = new SqlGenerator(migrations, migrationHistory); var sql = sqlGenerator.Generate(); sql.Length.Should().Be(3); sql[0].Should().Be("CREATE DATABASE [Mathematicians]"); sql[1].Should().Be("CREATE TABLE [Mathematicians].[dbo].[Mathematician]"); sql[2].Should().Be("CREATE TABLE [Mathematicians].[dbo].[Contribution]"); } } }
using FluentAssertions; using MergableMigrations.EF6; using MergableMigrations.Specification; using MergableMigrations.Specification.Implementation; using System; using System.Linq; using Xunit; namespace Mathematicians.UnitTests { public class SqlGeneratorTests { [Fact] public void CanGenerateSql() { var migrations = new Migrations(); var migrationHistory = new MigrationHistory(); var sqlGenerator = new SqlGenerator(migrations, migrationHistory); var sql = sqlGenerator.Generate(); sql.Length.Should().Be(3); sql[0].Should().Be("CREATE DATABASE [Mathematicians]"); sql[1].Should().Be("CREATE TABLE [Mathematicians].[dbo].[Mathematician]"); sql[2].Should().Be("CREATE TABLE [Mathematicians].[dbo].[Contribution]"); } [Fact] public void GeneratesNoSqlWhenUpToDate() { var migrations = new Migrations(); var migrationHistory = GivenCompleteMigrationHistory(migrations); var sqlGenerator = new SqlGenerator(migrations, migrationHistory); var sql = sqlGenerator.Generate(); sql.Length.Should().Be(0); } private MigrationHistory GivenCompleteMigrationHistory(Migrations migrations) { var model = new ModelSpecification(); migrations.AddMigrations(model); return model.MigrationHistory; } } }
Change random to avoid identical seed
using System; using System.Threading; namespace Criteo.Profiling.Tracing.Utils { /// <summary> /// Thread-safe random long generator. /// /// See "Correct way to use Random in multithread application" /// http://stackoverflow.com/questions/19270507/correct-way-to-use-random-in-multithread-application /// </summary> internal static class RandomUtils { private static int seed = Environment.TickCount; private static readonly ThreadLocal<Random> rand = new ThreadLocal<Random>(() => new Random(Interlocked.Increment(ref seed))); public static long NextLong() { return (long)((rand.Value.NextDouble() * 2.0 - 1.0) * long.MaxValue); } } }
using System; using System.Threading; namespace Criteo.Profiling.Tracing.Utils { /// <summary> /// Thread-safe random long generator. /// /// See "Correct way to use Random in multithread application" /// http://stackoverflow.com/questions/19270507/correct-way-to-use-random-in-multithread-application /// </summary> internal static class RandomUtils { private static int _seed = Guid.NewGuid().GetHashCode(); private static readonly ThreadLocal<Random> LocalRandom = new ThreadLocal<Random>(() => new Random(Interlocked.Increment(ref _seed))); public static long NextLong() { var buffer = new byte[8]; LocalRandom.Value.NextBytes(buffer); return BitConverter.ToInt64(buffer, 0); } } }
Allow output directory to be specified as a second parameter.
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; namespace NuPack { public class PackageAuthoring { private static readonly HashSet<string> _exclude = new HashSet<string>(new[] { ".nupack", ".nuspec" }, StringComparer.OrdinalIgnoreCase); public static void Main(string[] args) { // Review: Need to use a command-line parsing library instead of parsing it this way. string executable = Path.GetFileName(Environment.GetCommandLineArgs().First()); string Usage = String.Format(CultureInfo.InvariantCulture, "Usage: {0} <manifest-file>", executable); if (!args.Any()) { Console.Error.WriteLine(Usage); return; } try { // Parse the arguments. The last argument is the content to be added to the package var manifestFile = args.First(); PackageBuilder builder = PackageBuilder.ReadFrom(manifestFile); builder.Created = DateTime.Now; builder.Modified = DateTime.Now; var outputFile = String.Join(".", builder.Id, builder.Version, "nupack"); // Remove the output file or the package spec might try to include it (which is default behavior) builder.Files.RemoveAll(file => _exclude.Contains(Path.GetExtension(file.Path))); using (Stream stream = File.Create(outputFile)) { builder.Save(stream); } Console.WriteLine("{0} created successfully", outputFile); } catch (Exception exception) { Console.Error.WriteLine(exception.Message); } } } }
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; namespace NuPack { public class PackageAuthoring { private static readonly HashSet<string> _exclude = new HashSet<string>(new[] { ".nupack", ".nuspec" }, StringComparer.OrdinalIgnoreCase); public static void Main(string[] args) { // Review: Need to use a command-line parsing library instead of parsing it this way. string executable = Path.GetFileName(Environment.GetCommandLineArgs().First()); string Usage = String.Format(CultureInfo.InvariantCulture, "Usage: {0} <manifest-file>", executable); if (!args.Any()) { Console.Error.WriteLine(Usage); return; } try { var manifestFile = args.First(); string outputDirectory = args.Length > 1 ? args[1] : Directory.GetCurrentDirectory(); PackageBuilder builder = PackageBuilder.ReadFrom(manifestFile); builder.Created = DateTime.Now; builder.Modified = DateTime.Now; var outputFile = String.Join(".", builder.Id, builder.Version, "nupack"); // Remove the output file or the package spec might try to include it (which is default behavior) builder.Files.RemoveAll(file => _exclude.Contains(Path.GetExtension(file.Path))); string outputPath = Path.Combine(outputDirectory, outputFile); using (Stream stream = File.Create(outputPath)) { builder.Save(stream); } Console.WriteLine("{0} created successfully", outputPath); } catch (Exception exception) { Console.Error.WriteLine(exception.Message); } } } }
Make the queue into a list
// 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 System.Collections.Generic; using System.Threading.Tasks; using osu.Framework.Statistics; namespace osu.Framework.Allocation { /// <summary> /// A queue which batches object disposal on threadpool threads. /// </summary> internal static class AsyncDisposalQueue { private static readonly GlobalStatistic<string> last_disposal = GlobalStatistics.Get<string>("Drawable", "Last disposal"); private static readonly Queue<IDisposable> disposal_queue = new Queue<IDisposable>(); private static Task runTask; public static void Enqueue(IDisposable disposable) { lock (disposal_queue) disposal_queue.Enqueue(disposable); if (runTask?.Status < TaskStatus.Running) return; runTask = Task.Run(() => { IDisposable[] itemsToDispose; lock (disposal_queue) { itemsToDispose = disposal_queue.ToArray(); disposal_queue.Clear(); } foreach (var item in itemsToDispose) { last_disposal.Value = item.ToString(); item.Dispose(); } }); } } }
// 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 System.Collections.Generic; using System.Threading.Tasks; using osu.Framework.Statistics; namespace osu.Framework.Allocation { /// <summary> /// A queue which batches object disposal on threadpool threads. /// </summary> internal static class AsyncDisposalQueue { private static readonly GlobalStatistic<string> last_disposal = GlobalStatistics.Get<string>("Drawable", "Last disposal"); private static readonly List<IDisposable> disposal_queue = new List<IDisposable>(); private static Task runTask; public static void Enqueue(IDisposable disposable) { lock (disposal_queue) disposal_queue.Add(disposable); if (runTask?.Status < TaskStatus.Running) return; runTask = Task.Run(() => { IDisposable[] itemsToDispose; lock (disposal_queue) { itemsToDispose = disposal_queue.ToArray(); disposal_queue.Clear(); } foreach (var item in itemsToDispose) { last_disposal.Value = item.ToString(); item.Dispose(); } }); } } }
Make performance counter tests more stable
using System.Diagnostics; using FluentAssertions; using Xunit; namespace Okanshi.Test { public class PerformanceCounterTest { [Fact] public void Performance_counter_without_instance_name() { var performanceCounter = new PerformanceCounter("Memory", "Available Bytes"); var monitor = new PerformanceCounterMonitor(MonitorConfig.Build("Test"), PerformanceCounterConfig.Build("Memory", "Available Bytes")); monitor.GetValue() .Should() .BeGreaterThan(0) .And.BeApproximately(performanceCounter.NextValue(), 500000, "Because memory usage can change between the two values"); } [Fact] public void Performance_counter_with_instance_name() { var performanceCounter = new PerformanceCounter("Process", "Private Bytes", Process.GetCurrentProcess().ProcessName); var monitor = new PerformanceCounterMonitor(MonitorConfig.Build("Test"), PerformanceCounterConfig.Build("Process", "Private Bytes", Process.GetCurrentProcess().ProcessName)); monitor.GetValue() .Should() .BeGreaterThan(0) .And.BeApproximately(performanceCounter.NextValue(), 500000, "Because memory usage can change between the two values"); } } }
using System.Diagnostics; using FluentAssertions; using Xunit; namespace Okanshi.Test { public class PerformanceCounterTest { [Fact] public void Performance_counter_without_instance_name() { var performanceCounter = new PerformanceCounter("Memory", "Available Bytes"); var monitor = new PerformanceCounterMonitor(MonitorConfig.Build("Test"), PerformanceCounterConfig.Build("Memory", "Available Bytes")); monitor.GetValue() .Should() .BeGreaterThan(0) .And.BeApproximately(performanceCounter.NextValue(), 1000000, "Because memory usage can change between the two values"); } [Fact] public void Performance_counter_with_instance_name() { var performanceCounter = new PerformanceCounter("Process", "Private Bytes", Process.GetCurrentProcess().ProcessName); var monitor = new PerformanceCounterMonitor(MonitorConfig.Build("Test"), PerformanceCounterConfig.Build("Process", "Private Bytes", Process.GetCurrentProcess().ProcessName)); monitor.GetValue() .Should() .BeGreaterThan(0) .And.BeApproximately(performanceCounter.NextValue(), 1000000, "Because memory usage can change between the two values"); } } }
Fix wrong property mapping in SearchShard
using System.Collections.Generic; using Nest.Domain; using Newtonsoft.Json; using System.Linq.Expressions; using System; using System.Linq; namespace Nest { [JsonObject(MemberSerialization.OptIn)] public interface ISearchShardsResponse : IResponse { [JsonProperty("shards")] IEnumerable<IEnumerable<SearchShard>> Shards { get; } [JsonProperty("nodes")] IDictionary<string, SearchNode> Nodes { get; } } public class SearchShardsResponse : BaseResponse, ISearchShardsResponse { public IEnumerable<IEnumerable<SearchShard>> Shards { get; internal set; } public IDictionary<string, SearchNode> Nodes { get; internal set; } } [JsonObject(MemberSerialization.OptIn)] public class SearchNode { [JsonProperty("name")] public string Name { get; set; } [JsonProperty("transport_address")] public string TransportAddress { get; set; } } [JsonObject(MemberSerialization.OptIn)] public class SearchShard { [JsonProperty("name")] public string State { get; set;} [JsonProperty("primary")] public bool Primary { get; set;} [JsonProperty("node")] public string Node { get; set;} [JsonProperty("relocating_node")] public string RelocatingNode { get; set;} [JsonProperty("shard")] public int Shard { get; set;} [JsonProperty("index")] public string Index { get; set;} } }
using Nest.Domain; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; namespace Nest { [JsonObject(MemberSerialization.OptIn)] public interface ISearchShardsResponse : IResponse { [JsonProperty("shards")] IEnumerable<IEnumerable<SearchShard>> Shards { get; } [JsonProperty("nodes")] IDictionary<string, SearchNode> Nodes { get; } } public class SearchShardsResponse : BaseResponse, ISearchShardsResponse { public IEnumerable<IEnumerable<SearchShard>> Shards { get; internal set; } public IDictionary<string, SearchNode> Nodes { get; internal set; } } [JsonObject(MemberSerialization.OptIn)] public class SearchNode { [JsonProperty("name")] public string Name { get; set; } [JsonProperty("transport_address")] public string TransportAddress { get; set; } } [JsonObject(MemberSerialization.OptIn)] public class SearchShard { [JsonProperty("state")] public string State { get; set; } [JsonProperty("primary")] public bool Primary { get; set; } [JsonProperty("node")] public string Node { get; set; } [JsonProperty("relocating_node")] public string RelocatingNode { get; set; } [JsonProperty("shard")] public int Shard { get; set; } [JsonProperty("index")] public string Index { get; set; } } }
Remove usage of obsolete IApplicationRegistration
using System.Collections.Generic; using Glimpse.Core.Extensibility; using Nancy.Bootstrapper; namespace Glimpse.Nancy { public class GlimpseRegistrations : IApplicationRegistrations { public GlimpseRegistrations() { AppDomainAssemblyTypeScanner.AddAssembliesToScan(typeof(Glimpse.Core.Tab.Timeline).Assembly); } public IEnumerable<CollectionTypeRegistration> CollectionTypeRegistrations { get { var tabs = AppDomainAssemblyTypeScanner.TypesOf<ITab>(); var inspectors = AppDomainAssemblyTypeScanner.TypesOf<IInspector>(); return new[] { new CollectionTypeRegistration(typeof(ITab), tabs), new CollectionTypeRegistration(typeof(IInspector), inspectors) }; } } public IEnumerable<InstanceRegistration> InstanceRegistrations { get { return null; } } public IEnumerable<TypeRegistration> TypeRegistrations { get { return null; } } } }
using System.Collections.Generic; using Glimpse.Core.Extensibility; using Nancy.Bootstrapper; namespace Glimpse.Nancy { public class GlimpseRegistrations : IRegistrations { public GlimpseRegistrations() { AppDomainAssemblyTypeScanner.AddAssembliesToScan(typeof(Glimpse.Core.Tab.Timeline).Assembly); } public IEnumerable<CollectionTypeRegistration> CollectionTypeRegistrations { get { var tabs = AppDomainAssemblyTypeScanner.TypesOf<ITab>(); var inspectors = AppDomainAssemblyTypeScanner.TypesOf<IInspector>(); return new[] { new CollectionTypeRegistration(typeof(ITab), tabs), new CollectionTypeRegistration(typeof(IInspector), inspectors) }; } } public IEnumerable<InstanceRegistration> InstanceRegistrations { get { return null; } } public IEnumerable<TypeRegistration> TypeRegistrations { get { return null; } } } }
Test to check tinyioc is internal
using System; using System.Linq; using FluentAssertions; using NSaga; using Xunit; namespace Tests { public class NamespaceTests { [Fact] public void NSaga_Contains_Only_One_Namespace() { //Arrange var assembly = typeof(ISagaMediator).Assembly; // Act var namespaces = assembly.GetTypes() .Where(t => t.IsPublic) .Select(t => t.Namespace) .Distinct() .ToList(); // Assert var names = String.Join(", ", namespaces); namespaces.Should().HaveCount(1, $"Should only contain 'NSaga' namespace, but found '{names}'"); } [Fact] public void PetaPoco_Stays_Internal() { //Arrange var petapocoTypes = typeof(SqlSagaRepository).Assembly .GetTypes() .Where(t => !String.IsNullOrEmpty(t.Namespace)) .Where(t => t.Namespace.StartsWith("PetaPoco", StringComparison.OrdinalIgnoreCase)) .Where(t => t.IsPublic) .ToList(); petapocoTypes.Should().BeEmpty(); } } }
using System; using System.Linq; using FluentAssertions; using NSaga; using Xunit; namespace Tests { public class NamespaceTests { [Fact] public void NSaga_Contains_Only_One_Namespace() { //Arrange var assembly = typeof(ISagaMediator).Assembly; // Act var namespaces = assembly.GetTypes() .Where(t => t.IsPublic) .Select(t => t.Namespace) .Distinct() .ToList(); // Assert var names = String.Join(", ", namespaces); namespaces.Should().HaveCount(1, $"Should only contain 'NSaga' namespace, but found '{names}'"); } [Fact] public void PetaPoco_Stays_Internal() { //Arrange var petapocoTypes = typeof(SqlSagaRepository).Assembly .GetTypes() .Where(t => !String.IsNullOrEmpty(t.Namespace)) .Where(t => t.Namespace.StartsWith("PetaPoco", StringComparison.OrdinalIgnoreCase)) .Where(t => t.IsPublic) .ToList(); petapocoTypes.Should().BeEmpty(); } [Fact] public void TinyIoc_Stays_Internal() { typeof(TinyIoCContainer).IsPublic.Should().BeFalse(); } } }
Add license and disclaimer to About panel
@{ var version = ""; var versionName = Yio.Data.Constants.VersionConstant.Codename.ToString(); if(Yio.Data.Constants.VersionConstant.Patch == 0) { version = Yio.Data.Constants.VersionConstant.Release.ToString(); } else { version = Yio.Data.Constants.VersionConstant.Release.ToString() + "." + Yio.Data.Constants.VersionConstant.Patch.ToString(); } } <div class="panel" id="about-panel"> <div class="panel-inner"> <div class="panel-close"> <a href="#" id="about-panel-close"><i class="fa fa-fw fa-times"></i></a> </div> <h1>About</h1> <p> <strong>Curl your paw round your dick, and get clicking!</strong> </p> <p> Filled with furry (and more) porn, stripped from many sources &mdash; tumblr, e621, 4chan, 8chan, etc. &mdash; Yiff.co is the never-ending full-width stream of NSFW images. Built by <a href="https://zyr.io">Zyrio</a>. </p> <p> Running on version <strong>@version '@(versionName)'</strong> </p> </div> </div>
@{ var version = ""; var versionName = Yio.Data.Constants.VersionConstant.Codename.ToString(); if(Yio.Data.Constants.VersionConstant.Patch == 0) { version = Yio.Data.Constants.VersionConstant.Release.ToString(); } else { version = Yio.Data.Constants.VersionConstant.Release.ToString() + "." + Yio.Data.Constants.VersionConstant.Patch.ToString(); } } <div class="panel" id="about-panel"> <div class="panel-inner"> <div class="panel-close"> <a href="#" id="about-panel-close"><i class="fa fa-fw fa-times"></i></a> </div> <h1>About</h1> <p> <strong>Curl your paw round your dick, and get clicking!</strong> </p> <p> Filled with furry (and more) porn, stripped from many sources &mdash; tumblr, e621, 4chan, 8chan, etc. &mdash; Yiff.co is the never-ending full-width stream of NSFW images. </p> <p> Built by <a href="https://zyr.io">Zyrio</a>. Licensed under the MIT license, with code available on <a href="https://git.zyr.io/zyrio/yio">Zyrio Git</a>. All copyrights belong to their respectful owner, and Yiff.co does not claim ownership over any of them, nor does Yiff.co generate any money. </p> <p> Running on version <strong>@version '@(versionName)'</strong> </p> </div> </div>
Fix data collection cmdlets to not require login
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // 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.Management.Automation; using Microsoft.Azure.Commands.Profile.Models; using Microsoft.Azure.Commands.ResourceManager.Common; using System.Security.Permissions; namespace Microsoft.Azure.Commands.Profile { [Cmdlet(VerbsLifecycle.Enable, "AzureRmDataCollection")] [Alias("Enable-AzureDataCollection")] public class EnableAzureRmDataCollectionCommand : AzureRMCmdlet { protected override void ProcessRecord() { SetDataCollectionProfile(true); } protected void SetDataCollectionProfile(bool enable) { var profile = GetDataCollectionProfile(); profile.EnableAzureDataCollection = enable; SaveDataCollectionProfile(); } } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // 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.Management.Automation; using Microsoft.Azure.Commands.Profile.Models; using Microsoft.Azure.Commands.ResourceManager.Common; using System.Security.Permissions; namespace Microsoft.Azure.Commands.Profile { [Cmdlet(VerbsLifecycle.Enable, "AzureRmDataCollection")] [Alias("Enable-AzureDataCollection")] public class EnableAzureRmDataCollectionCommand : AzureRMCmdlet { protected override void BeginProcessing() { // do not call begin processing there is no context needed for this cmdlet } protected override void ProcessRecord() { SetDataCollectionProfile(true); } protected void SetDataCollectionProfile(bool enable) { var profile = GetDataCollectionProfile(); profile.EnableAzureDataCollection = enable; SaveDataCollectionProfile(); } } }
Change "single tap" mod acronym to not conflict with "strict tracking"
// 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 System.Linq; namespace osu.Game.Rulesets.Osu.Mods { public class OsuModSingleTap : InputBlockingMod { public override string Name => @"Single Tap"; public override string Acronym => @"ST"; public override string Description => @"You must only use one key!"; public override Type[] IncompatibleMods => base.IncompatibleMods.Concat(new[] { typeof(OsuModAlternate) }).ToArray(); protected override bool CheckValidNewAction(OsuAction action) => LastAcceptedAction == null || LastAcceptedAction == action; } }
// 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 System.Linq; namespace osu.Game.Rulesets.Osu.Mods { public class OsuModSingleTap : InputBlockingMod { public override string Name => @"Single Tap"; public override string Acronym => @"SG"; public override string Description => @"You must only use one key!"; public override Type[] IncompatibleMods => base.IncompatibleMods.Concat(new[] { typeof(OsuModAlternate) }).ToArray(); protected override bool CheckValidNewAction(OsuAction action) => LastAcceptedAction == null || LastAcceptedAction == action; } }
Make map pool layout more correct
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System.Linq; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Tournament.Components; using osu.Game.Tournament.Screens.Ladder.Components; namespace osu.Game.Tournament.Tests { public class TestCaseMapPool : LadderTestCase { [BackgroundDependencyLoader] private void load() { var round = Ladder.Groupings.First(g => g.Name == "Finals"); Add(new MapPoolScreen(round)); } } public class MapPoolScreen : CompositeDrawable { public MapPoolScreen(TournamentGrouping round) { FillFlowContainer maps; InternalChildren = new Drawable[] { maps = new FillFlowContainer { Direction = FillDirection.Full, RelativeSizeAxes = Axes.Both, }, }; foreach (var b in round.Beatmaps) maps.Add(new TournamentBeatmapPanel(b.BeatmapInfo)); } } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System.Linq; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Screens; using osu.Game.Tournament.Components; using osu.Game.Tournament.Screens.Ladder.Components; using OpenTK; namespace osu.Game.Tournament.Tests { public class TestCaseMapPool : LadderTestCase { [BackgroundDependencyLoader] private void load() { var round = Ladder.Groupings.First(g => g.Name == "Finals"); Add(new MapPoolScreen(round)); } } public class MapPoolScreen : OsuScreen { public MapPoolScreen(TournamentGrouping round) { FillFlowContainer maps; InternalChildren = new Drawable[] { maps = new FillFlowContainer { Spacing = new Vector2(20), Padding = new MarginPadding(50), Direction = FillDirection.Full, RelativeSizeAxes = Axes.Both, }, }; foreach (var b in round.Beatmaps) maps.Add(new TournamentBeatmapPanel(b.BeatmapInfo) { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, }); } } }
Add support for named argument parsing.
using System; using System.Dynamic; namespace BobTheBuilder { public class NamedArgumentsDynamicBuilder<T> : DynamicObject, IDynamicBuilder<T> where T : class { private readonly IDynamicBuilder<T> wrappedBuilder; private readonly IArgumentStore argumentStore; internal NamedArgumentsDynamicBuilder(IDynamicBuilder<T> wrappedBuilder, IArgumentStore argumentStore) { if (wrappedBuilder == null) { throw new ArgumentNullException("wrappedBuilder"); } if (argumentStore == null) { throw new ArgumentNullException("argumentStore"); } this.wrappedBuilder = wrappedBuilder; this.argumentStore = argumentStore; } public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { return wrappedBuilder.TryInvokeMember(binder, args, out result); } public T Build() { return wrappedBuilder.Build(); } } }
using System; using System.Dynamic; using System.Linq; namespace BobTheBuilder { public class NamedArgumentsDynamicBuilder<T> : DynamicObject, IDynamicBuilder<T> where T : class { private readonly IDynamicBuilder<T> wrappedBuilder; private readonly IArgumentStore argumentStore; internal NamedArgumentsDynamicBuilder(IDynamicBuilder<T> wrappedBuilder, IArgumentStore argumentStore) { if (wrappedBuilder == null) { throw new ArgumentNullException("wrappedBuilder"); } if (argumentStore == null) { throw new ArgumentNullException("argumentStore"); } this.wrappedBuilder = wrappedBuilder; this.argumentStore = argumentStore; } public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { if (binder.Name == "With") { ParseNamedArgumentValues(binder.CallInfo, args); } return wrappedBuilder.TryInvokeMember(binder, args, out result); } private void ParseNamedArgumentValues(CallInfo callInfo, object[] args) { var argumentName = callInfo.ArgumentNames.First(); argumentName = argumentName.First().ToString().ToUpper() + argumentName.Substring(1); argumentStore.SetMemberNameAndValue(argumentName, args.First()); } public T Build() { return wrappedBuilder.Build(); } } }
Enable stopwatch extension methods for .NET Core
// Copyright 2014 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. #if !PCL using System.Diagnostics; using JetBrains.Annotations; using NodaTime.Utility; namespace NodaTime.Extensions { /// <summary> /// Extension methods for <see cref="Stopwatch"/>. /// </summary> public static class StopwatchExtensions { /// <summary> /// Returns the elapsed time of <paramref name="stopwatch"/> as a <see cref="Duration"/>. /// </summary> /// <param name="stopwatch">The <c>Stopwatch</c> to obtain the elapsed time from.</param> /// <returns>The elapsed time of <paramref name="stopwatch"/> as a <c>Duration</c>.</returns> public static Duration ElapsedDuration([NotNull] this Stopwatch stopwatch) { Preconditions.CheckNotNull(stopwatch, nameof(stopwatch)); return stopwatch.Elapsed.ToDuration(); } } } #endif
// Copyright 2014 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using System.Diagnostics; using JetBrains.Annotations; using NodaTime.Utility; namespace NodaTime.Extensions { /// <summary> /// Extension methods for <see cref="Stopwatch"/>. /// </summary> public static class StopwatchExtensions { /// <summary> /// Returns the elapsed time of <paramref name="stopwatch"/> as a <see cref="Duration"/>. /// </summary> /// <param name="stopwatch">The <c>Stopwatch</c> to obtain the elapsed time from.</param> /// <returns>The elapsed time of <paramref name="stopwatch"/> as a <c>Duration</c>.</returns> public static Duration ElapsedDuration([NotNull] this Stopwatch stopwatch) { Preconditions.CheckNotNull(stopwatch, nameof(stopwatch)); return stopwatch.Elapsed.ToDuration(); } } }
Add group by yellow cards count
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using RedCard.API.Contexts; // For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860 namespace RedCard.API.Controllers { [Route("api/[controller]")] public class StatsController : Controller { public StatsController(ApplicationDbContext dbContext) { _dbContext = dbContext; } readonly ApplicationDbContext _dbContext; [HttpGet] public IActionResult RedCardCountForCountry() { var redCardCount = _dbContext.Players .GroupBy(player => player.Country) .Select(grouping => new { country = grouping.Key, redCardCount = grouping.Sum(player => player.RedCards) }) .ToArray(); return new ObjectResult(new { redCardCountForCountry = redCardCount }); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using RedCard.API.Contexts; using RedCard.API.Models; // For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860 namespace RedCard.API.Controllers { [Route("api/[controller]")] public class StatsController : Controller { public StatsController(ApplicationDbContext dbContext) { _dbContext = dbContext; } readonly ApplicationDbContext _dbContext; [Route("redcards")] [HttpGet] public IActionResult RedCardCountForCountry() { Func<IGrouping<string, Player>, object> getRedCardsForCountry = (grouping) => new { country = grouping.Key, redCardCount = grouping.Sum(player => player.RedCards) }; var redCardCount = _CardsForCountry(getRedCardsForCountry); return new ObjectResult(new { redCardCountForCountry = redCardCount }); } [Route("yellowcards")] [HttpGet] public IActionResult YellowCardCountForCountry() { Func<IGrouping<string, Player>, object> getYellowCardsForCountry = (grouping) => new { country = grouping.Key, yellowCardCount = grouping.Sum(player => player.YellowCards) }; var yellowCardCount = _CardsForCountry(getYellowCardsForCountry); return new ObjectResult(new { yellowCardCountForCountry = yellowCardCount }); } IEnumerable<object> _CardsForCountry(Func<IGrouping<string, Player>, object> getInfo) { return _dbContext.Players .GroupBy(player => player.Country) .Select(getInfo) .ToArray(); } } }
Allow coroutines of 0 sec delay
using System; using System.Collections; using UnityEngine; namespace LunaClient.Utilities { public class CoroutineUtil { public static void StartDelayedRoutine(string routineName, Action action, float delayInSec) { Client.Singleton.StartCoroutine(DelaySeconds(routineName, action, delayInSec)); } private static IEnumerator DelaySeconds(string routineName, Action action, float delayInSec) { yield return new WaitForSeconds(delayInSec); try { action(); } catch (Exception e) { LunaLog.LogError($"Error in delayed coroutine: {routineName}. Details {e}"); } } } }
using System; using System.Collections; using UnityEngine; namespace LunaClient.Utilities { public class CoroutineUtil { public static void StartDelayedRoutine(string routineName, Action action, float delayInSec) { Client.Singleton.StartCoroutine(DelaySeconds(routineName, action, delayInSec)); } private static IEnumerator DelaySeconds(string routineName, Action action, float delayInSec) { if (delayInSec > 0) yield return new WaitForSeconds(delayInSec); try { action(); } catch (Exception e) { LunaLog.LogError($"Error in delayed coroutine: {routineName}. Details {e}"); } } } }
Add check for content type when parsing in client. Fallback to Json if Protobuf is not available
using System; using System.Net.Http.Headers; using System.Threading.Tasks; using Infrastructure.Model; using Microsoft.AspNetCore.Mvc; namespace Web.Controllers { public class HomeController : Controller { [HttpGet] public async Task<string> Index() { var client = new System.Net.Http.HttpClient { BaseAddress = new Uri("http://localhost:5002") }; client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-protobuf")); var response = await client.GetAsync("api/home"); if (response.IsSuccessStatusCode) { using(var stream = await response.Content.ReadAsStreamAsync()) { var model = ProtoBuf.Serializer.Deserialize<ProtobufModelDto>(stream); return $"{model.Name}, {model.StringValue}, {model.Id}"; } } return "Failed"; } } }
using System; using System.Net.Http.Headers; using System.Threading.Tasks; using Infrastructure.Model; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; namespace Web.Controllers { public class HomeController : Controller { [HttpGet] public async Task<string> Index() { var client = new System.Net.Http.HttpClient { BaseAddress = new Uri("http://localhost:5002") }; client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-protobuf")); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var response = await client.GetAsync("api/home"); if (response.IsSuccessStatusCode) { using(var stream = await response.Content.ReadAsStreamAsync()) { ProtobufModelDto model = null; if (response.Content.Headers.ContentType.MediaType == "application/x-protobuf") { model = ProtoBuf.Serializer.Deserialize<ProtobufModelDto>(stream); return $"{model.Name}, {model.StringValue}, {model.Id}"; } var content = await response.Content.ReadAsStringAsync(); model = JsonConvert.DeserializeObject<ProtobufModelDto>(content); return $"{model.Name}, {model.StringValue}, {model.Id}"; } } return "Failed"; } } }
Disable warnings about obsoletion since the point is testing the obsolete stuff still works
using System; using System.IO; using System.Runtime.CompilerServices; using ExpressionToCodeLib; using Xunit; //requires binary serialization, which is omitted in older .net cores - but those are out of support: https://docs.microsoft.com/en-us/lifecycle/products/microsoft-net-and-net-core namespace ExpressionToCodeTest { public class ExceptionsSerialization { [MethodImpl(MethodImplOptions.NoInlining)] static void IntentionallyFailingMethod() => PAssert.That(() => false); [Fact] public void PAssertExceptionIsSerializable() => AssertMethodFailsWithSerializableException(IntentionallyFailingMethod); static void AssertMethodFailsWithSerializableException(Action intentionallyFailingMethod) { var original = Assert.ThrowsAny<Exception>(intentionallyFailingMethod); var formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); var ms = new MemoryStream(); formatter.Serialize(ms, original); var deserialized = formatter.Deserialize(new MemoryStream(ms.ToArray())); Assert.Equal(original.ToString(), deserialized.ToString()); } } }
using System; using System.IO; using System.Runtime.CompilerServices; using ExpressionToCodeLib; using Xunit; //requires binary serialization, which is omitted in older .net cores - but those are out of support: https://docs.microsoft.com/en-us/lifecycle/products/microsoft-net-and-net-core namespace ExpressionToCodeTest { public class ExceptionsSerialization { [MethodImpl(MethodImplOptions.NoInlining)] static void IntentionallyFailingMethod() => PAssert.That(() => false); [Fact] public void PAssertExceptionIsSerializable() => AssertMethodFailsWithSerializableException(IntentionallyFailingMethod); #pragma warning disable SYSLIB0011 // BinaryFormatter is Obsolete static void AssertMethodFailsWithSerializableException(Action intentionallyFailingMethod) { var original = Assert.ThrowsAny<Exception>(intentionallyFailingMethod); var formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); var ms = new MemoryStream(); formatter.Serialize(ms, original); var deserialized = formatter.Deserialize(new MemoryStream(ms.ToArray())); Assert.Equal(original.ToString(), deserialized.ToString()); } #pragma warning restore SYSLIB0011 } }
Add intermediate comments to help explain what to do
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using FizzWare.NBuilder; using IntermediatorBotSample.Models; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Bot.Schema; using Newtonsoft.Json; namespace IntermediatorBotSample.Controllers.Api { [Route("api/[controller]")] public class ConversationsController : Controller { [HttpGet] public IEnumerable<Conversation> Get() { return Builder<Conversation>.CreateListOfSize(2) .All() .With(o => o.ConversationInformation = Builder<ConversationInformation>.CreateNew().Build()) .With(o => o.ConversationReference = Builder<ConversationReference>.CreateNew().Build()) .With(o => o.UserInformation = Builder<UserInformation>.CreateNew().Build()) .Build() .ToList(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using FizzWare.NBuilder; using IntermediatorBotSample.Models; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Bot.Schema; using Newtonsoft.Json; namespace IntermediatorBotSample.Controllers.Api { [Route("api/[controller]")] public class ConversationsController : Controller { [HttpGet] public IEnumerable<Conversation> Get(int convId, int top) { var channels = new[] { "facebook", "skype", "skype for business", "directline" }; var random = new RandomGenerator(); return Builder<Conversation>.CreateListOfSize(5) .All() .With(o => o.ConversationInformation = Builder<ConversationInformation>.CreateNew() .With(ci => ci.MessagesCount = random.Next(2, 30)) .With(ci => ci.SentimentScore = random.Next(0.0d, 1.0d)) .Build()) .With(o => o.ConversationReference = Builder<ConversationReference>.CreateNew() .With(cr => cr.ChannelId = channels[random.Next(0, channels.Count())]) .Build()) .With(o => o.UserInformation = Builder<UserInformation>.CreateNew() .Build()) .Build() .ToList(); } //TODO: Retrieve ALL the conversation //TOOD: Forward conersation //TODO: DELETE Conversation = immediate kill by conversationId } }
Use different sounds for minigun's missed enemy effect.
//------------------------------------------------------------------------------ // Revenge Of The Cats: Ethernet // Copyright (C) 2008, mEthLab Interactive //------------------------------------------------------------------------------ datablock AudioProfile(MinigunProjectileImpactSound) { filename = "share/sounds/rotc/impact1.wav"; description = AudioDefault3D; preload = true; }; datablock AudioProfile(MinigunProjectileFlybySound) { filename = "share/sounds/rotc/flyby1.wav"; description = AudioCloseLooping3D; preload = true; }; datablock AudioProfile(MinigunProjectileMissedEnemySound) { filename = "share/sounds/rotc/flyby1.wav"; description = AudioClose3D; preload = true; };
//------------------------------------------------------------------------------ // Revenge Of The Cats: Ethernet // Copyright (C) 2008, mEthLab Interactive //------------------------------------------------------------------------------ datablock AudioProfile(MinigunProjectileImpactSound) { filename = "share/sounds/rotc/impact1.wav"; description = AudioDefault3D; preload = true; }; datablock AudioProfile(MinigunProjectileFlybySound) { filename = "share/sounds/rotc/flyby1.wav"; description = AudioCloseLooping3D; preload = true; }; datablock AudioProfile(MinigunProjectileMissedEnemySound) { filename = "share/sounds/rotc/ricochet1-1.wav"; alternate[0] = "share/sounds/rotc/ricochet1-1.wav"; alternate[1] = "share/sounds/rotc/ricochet1-2.wav"; alternate[2] = "share/sounds/rotc/ricochet1-3.wav"; alternate[3] = "share/sounds/rotc/ricochet1-4.wav"; alternate[4] = "share/sounds/rotc/ricochet1-5.wav"; alternate[5] = "share/sounds/rotc/ricochet1-6.wav"; description = AudioClose3D; preload = true; };
Move client handling into a separate method.
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; namespace EchoServer { class Program { static void Main(string[] args) { Task main = MainAsync(args); main.Wait(); } static async Task MainAsync(string[] args) { Console.WriteLine("Starting server"); CancellationToken cancellationToken = new CancellationTokenSource().Token; TcpListener listener = new TcpListener(IPAddress.IPv6Loopback, 8080); listener.Start(); TcpClient client = await listener.AcceptTcpClientAsync(); client.ReceiveTimeout = 30; NetworkStream stream = client.GetStream(); StreamWriter writer = new StreamWriter(stream, Encoding.ASCII) { AutoFlush = true }; StreamReader reader = new StreamReader(stream, Encoding.ASCII); while (true) { string line = await reader.ReadLineAsync(); Console.WriteLine($"Received {line}"); await writer.WriteLineAsync(line); if (cancellationToken.IsCancellationRequested) break; } listener.Stop(); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; namespace EchoServer { class Program { static void Main(string[] args) { Task main = MainAsync(args); main.Wait(); } static async Task MainAsync(string[] args) { Console.WriteLine("Starting server"); TcpListener server = new TcpListener(IPAddress.IPv6Loopback, 8080); Console.WriteLine("Starting listener"); server.Start(); while (true) { TcpClient client = await server.AcceptTcpClientAsync(); Task.Factory.StartNew(() => HandleConnection(client)); } server.Stop(); } static async Task HandleConnection(TcpClient client) { Console.WriteLine($"New connection from {client.Client.RemoteEndPoint}"); client.ReceiveTimeout = 30; client.SendTimeout = 30; NetworkStream stream = client.GetStream(); StreamWriter writer = new StreamWriter(stream, Encoding.ASCII) { AutoFlush = true }; StreamReader reader = new StreamReader(stream, Encoding.ASCII); string line = await reader.ReadLineAsync(); Console.WriteLine($"Received {line}"); await writer.WriteLineAsync(line); } } }
Clean up the diagnostic in FieldToProperty pass.
using System.Linq; using CppSharp.AST; using CppSharp.Generators; namespace CppSharp.Passes { public class FieldToPropertyPass : TranslationUnitPass { public override bool VisitClassDecl(Class @class) { if (@class.CompleteDeclaration != null) return VisitClassDecl(@class.CompleteDeclaration as Class); return base.VisitClassDecl(@class); } public override bool VisitFieldDecl(Field field) { if (!VisitDeclaration(field)) return false; var @class = field.Namespace as Class; if (@class == null) return false; if (ASTUtils.CheckIgnoreField(field)) return false; // Check if we already have a synthetized property. var existingProp = @class.Properties.FirstOrDefault(property => property.Field == field); if (existingProp != null) return false; field.GenerationKind = GenerationKind.Internal; var prop = new Property { Name = field.Name, Namespace = field.Namespace, QualifiedType = field.QualifiedType, Access = field.Access, Field = field }; // do not rename value-class fields because they would be // generated as fields later on even though they are wrapped by properties; // that is, in turn, because it's cleaner to write // the struct marshalling logic just for properties if (!prop.IsInRefTypeAndBackedByValueClassField()) field.Name = Generator.GeneratedIdentifier(field.Name); @class.Properties.Add(prop); Diagnostics.Debug("Property created from field: {0}::{1}", @class.Name, field.Name); return false; } } }
using System.Linq; using CppSharp.AST; using CppSharp.Generators; namespace CppSharp.Passes { public class FieldToPropertyPass : TranslationUnitPass { public override bool VisitClassDecl(Class @class) { if (@class.CompleteDeclaration != null) return VisitClassDecl(@class.CompleteDeclaration as Class); return base.VisitClassDecl(@class); } public override bool VisitFieldDecl(Field field) { if (!VisitDeclaration(field)) return false; var @class = field.Namespace as Class; if (@class == null) return false; if (ASTUtils.CheckIgnoreField(field)) return false; // Check if we already have a synthetized property. var existingProp = @class.Properties.FirstOrDefault(property => property.Field == field); if (existingProp != null) return false; field.GenerationKind = GenerationKind.Internal; var prop = new Property { Name = field.Name, Namespace = field.Namespace, QualifiedType = field.QualifiedType, Access = field.Access, Field = field }; // do not rename value-class fields because they would be // generated as fields later on even though they are wrapped by properties; // that is, in turn, because it's cleaner to write // the struct marshalling logic just for properties if (!prop.IsInRefTypeAndBackedByValueClassField()) field.Name = Generator.GeneratedIdentifier(field.Name); @class.Properties.Add(prop); Diagnostics.Debug($"Property created from field: {field.QualifiedName}"); return false; } } }
Mark evil test as ignore, again
 using System; using NUnit.Framework; namespace HttpMock.Unit.Tests { [TestFixture] public class HttpFactoryTests { [Test] public void ShouldBeAbleToHostAtSameAddressIfPreviousWasDisposed() { var serverFactory = new HttpServerFactory(); var uri = new Uri(String.Format("http://localhost:{0}", PortHelper.FindLocalAvailablePortForTesting())); IHttpServer server1, server2 = null; server1 = serverFactory.Get(uri).WithNewContext(uri.AbsoluteUri); try { server1.Start(); server1.Dispose(); server1 = null; server2 = serverFactory.Get(uri).WithNewContext(uri.AbsoluteUri); Assert.DoesNotThrow(server2.Start); } finally { if (server1 != null) { server1.Dispose(); } if (server2 != null) { server2.Dispose(); } } } } }
 using System; using NUnit.Framework; namespace HttpMock.Unit.Tests { [TestFixture] public class HttpFactoryTests { [Test] [Ignore ("Makes the test suite flaky (???)")] public void ShouldBeAbleToHostAtSameAddressIfPreviousWasDisposed() { var serverFactory = new HttpServerFactory(); var uri = new Uri(String.Format("http://localhost:{0}", PortHelper.FindLocalAvailablePortForTesting())); IHttpServer server1, server2 = null; server1 = serverFactory.Get(uri).WithNewContext(uri.AbsoluteUri); try { server1.Start(); server1.Dispose(); server1 = null; server2 = serverFactory.Get(uri).WithNewContext(uri.AbsoluteUri); Assert.DoesNotThrow(server2.Start); } finally { if (server1 != null) { server1.Dispose(); } if (server2 != null) { server2.Dispose(); } } } } }
Make sure distance is clamped to sane values
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using osu.Game.Rulesets.Osu.Difficulty.Preprocessing; namespace osu.Game.Rulesets.Osu.Difficulty.Skills { /// <summary> /// Represents the skill required to press keys with regards to keeping up with the speed at which objects need to be hit. /// </summary> public class Speed : Skill { protected override double SkillMultiplier => 1400; protected override double StrainDecayBase => 0.3; protected override double StrainValueOf(OsuDifficultyHitObject current) { double distance = current.TravelDistance + current.JumpDistance; return (0.95 + Math.Pow(distance / SINGLE_SPACING_THRESHOLD, 4)) / current.StrainTime; } } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using osu.Game.Rulesets.Osu.Difficulty.Preprocessing; namespace osu.Game.Rulesets.Osu.Difficulty.Skills { /// <summary> /// Represents the skill required to press keys with regards to keeping up with the speed at which objects need to be hit. /// </summary> public class Speed : Skill { protected override double SkillMultiplier => 1400; protected override double StrainDecayBase => 0.3; protected override double StrainValueOf(OsuDifficultyHitObject current) { double distance = Math.Min(SINGLE_SPACING_THRESHOLD, current.TravelDistance + current.JumpDistance); return (0.95 + Math.Pow(distance / SINGLE_SPACING_THRESHOLD, 4)) / current.StrainTime; } } }
Fix for GetTestCases not returning current folder
using Qart.Core.DataStore; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Qart.Testing { public class TestSystem { public IDataStore DataStorage { get; private set; } public TestSystem(IDataStore dataStorage) { DataStorage = dataStorage; } public TestCase GetTestCase(string id) { return new TestCase(id, this); } public IEnumerable<TestCase> GetTestCases() { return DataStorage.GetAllGroups().Where(_ => DataStorage.Contains(Path.Combine(_, ".test"))).Select(_ => new TestCase(_, this)); } } }
using Qart.Core.DataStore; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Qart.Testing { public class TestSystem { public IDataStore DataStorage { get; private set; } public TestSystem(IDataStore dataStorage) { DataStorage = dataStorage; } public TestCase GetTestCase(string id) { return new TestCase(id, this); } public IEnumerable<TestCase> GetTestCases() { return DataStorage.GetAllGroups().Concat(new[]{"."}).Where(_ => DataStorage.Contains(Path.Combine(_, ".test"))).Select(_ => new TestCase(_, this)); } } }
Refactor virtual judge user table schema
using System; using System.ComponentModel.DataAnnotations; namespace JoyOI.OnlineJudge.Models { public class VirtualJudgeUser { /// <summary> /// Gets or sets the identifier. /// </summary> /// <value>The identifier.</value> public Guid Id { get; set; } /// <summary> /// Gets or sets the username. /// </summary> /// <value>The username.</value> [MaxLength(32)] public string Username { get; set; } /// <summary> /// Gets or sets the password. /// </summary> /// <value>The password.</value> [MaxLength(64)] public string Password { get; set; } /// <summary> /// Gets or sets a value indicating whether this <see cref="T:JoyOI.OnlineJudge.Models.VirtualJudgeUser"/> is in use. /// </summary> /// <value><c>true</c> if is in use; otherwise, <c>false</c>.</value> public bool IsInUse { get; set; } /// <summary> /// Gets or sets the source. /// </summary> /// <value>The source of this user.</value> public ProblemSource Source { get; set; } } }
using System; using System.ComponentModel.DataAnnotations; namespace JoyOI.OnlineJudge.Models { public class VirtualJudgeUser { /// <summary> /// Gets or sets the identifier. /// </summary> /// <value>The identifier.</value> public Guid Id { get; set; } /// <summary> /// Gets or sets the username. /// </summary> /// <value>The username.</value> [MaxLength(32)] public string Username { get; set; } /// <summary> /// Gets or sets the password. /// </summary> /// <value>The password.</value> [MaxLength(64)] public string Password { get; set; } /// <summary> /// Gets or sets the locker id. /// </summary> /// <value>The locker id.</value> public Guid? LockerId { get; set; } /// <summary> /// Gets or sets the source. /// </summary> /// <value>The source of this user.</value> public ProblemSource Source { get; set; } } }
Use LargeTextureStore for online retrievals
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using osu.Framework.Allocation; using osu.Framework.Graphics.Sprites; using osu.Framework.Graphics.Textures; namespace osu.Game.Beatmaps.Drawables { public class BeatmapSetCover : Sprite { private readonly BeatmapSetInfo set; private readonly BeatmapSetCoverType type; public BeatmapSetCover(BeatmapSetInfo set, BeatmapSetCoverType type = BeatmapSetCoverType.Cover) { if (set == null) throw new ArgumentNullException(nameof(set)); this.set = set; this.type = type; } [BackgroundDependencyLoader] private void load(TextureStore textures) { string resource = null; switch (type) { case BeatmapSetCoverType.Cover: resource = set.OnlineInfo.Covers.Cover; break; case BeatmapSetCoverType.Card: resource = set.OnlineInfo.Covers.Card; break; case BeatmapSetCoverType.List: resource = set.OnlineInfo.Covers.List; break; } if (resource != null) Texture = textures.Get(resource); } } public enum BeatmapSetCoverType { Cover, Card, List, } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using osu.Framework.Allocation; using osu.Framework.Graphics.Sprites; using osu.Framework.Graphics.Textures; namespace osu.Game.Beatmaps.Drawables { public class BeatmapSetCover : Sprite { private readonly BeatmapSetInfo set; private readonly BeatmapSetCoverType type; public BeatmapSetCover(BeatmapSetInfo set, BeatmapSetCoverType type = BeatmapSetCoverType.Cover) { if (set == null) throw new ArgumentNullException(nameof(set)); this.set = set; this.type = type; } [BackgroundDependencyLoader] private void load(LargeTextureStore textures) { string resource = null; switch (type) { case BeatmapSetCoverType.Cover: resource = set.OnlineInfo.Covers.Cover; break; case BeatmapSetCoverType.Card: resource = set.OnlineInfo.Covers.Card; break; case BeatmapSetCoverType.List: resource = set.OnlineInfo.Covers.List; break; } if (resource != null) Texture = textures.Get(resource); } } public enum BeatmapSetCoverType { Cover, Card, List, } }
Use registered types for Out of Band handlers in packet handling type finder
// Original Work Copyright (c) Ethan Moffat 2014-2016 // This file is subject to the GPL v2 License // For additional details, see the LICENSE file using System.Collections.Generic; namespace EOLib.Net.Handlers { public class PacketHandlingTypeFinder : IPacketHandlingTypeFinder { private readonly List<FamilyActionPair> _inBandPackets; private readonly List<FamilyActionPair> _outOfBandPackets; public PacketHandlingTypeFinder() { _inBandPackets = new List<FamilyActionPair> { new FamilyActionPair(PacketFamily.Init, PacketAction.Init), new FamilyActionPair(PacketFamily.Account, PacketAction.Reply), new FamilyActionPair(PacketFamily.Character, PacketAction.Reply), new FamilyActionPair(PacketFamily.Login, PacketAction.Reply) }; _outOfBandPackets = new List<FamilyActionPair> { new FamilyActionPair(PacketFamily.Connection, PacketAction.Player) }; } public PacketHandlingType FindHandlingType(PacketFamily family, PacketAction action) { var fap = new FamilyActionPair(family, action); if (_inBandPackets.Contains(fap)) return PacketHandlingType.InBand; if (_outOfBandPackets.Contains(fap)) return PacketHandlingType.OutOfBand; return PacketHandlingType.NotHandled; } } }
// Original Work Copyright (c) Ethan Moffat 2014-2016 // This file is subject to the GPL v2 License // For additional details, see the LICENSE file using System.Collections.Generic; using System.Linq; namespace EOLib.Net.Handlers { public class PacketHandlingTypeFinder : IPacketHandlingTypeFinder { private readonly List<FamilyActionPair> _inBandPackets; private readonly List<FamilyActionPair> _outOfBandPackets; public PacketHandlingTypeFinder(IEnumerable<IPacketHandler> outOfBandHandlers) { _inBandPackets = new List<FamilyActionPair> { new FamilyActionPair(PacketFamily.Init, PacketAction.Init), new FamilyActionPair(PacketFamily.Account, PacketAction.Reply), new FamilyActionPair(PacketFamily.Character, PacketAction.Reply), new FamilyActionPair(PacketFamily.Login, PacketAction.Reply) }; _outOfBandPackets = outOfBandHandlers.Select(x => new FamilyActionPair(x.Family, x.Action)).ToList(); } public PacketHandlingType FindHandlingType(PacketFamily family, PacketAction action) { var fap = new FamilyActionPair(family, action); if (_inBandPackets.Contains(fap)) return PacketHandlingType.InBand; if (_outOfBandPackets.Contains(fap)) return PacketHandlingType.OutOfBand; return PacketHandlingType.NotHandled; } } }
Fix latest chain properties, simplify WordCount property and make it deduce the order from the passed initial chain.
using System; using System.Collections.Generic; namespace Chainey { internal class SentenceConstruct { internal int WordCount { get { return Forwards.Count + Backwards.Count - order; } } internal string Sentence { get { var sen = new List<string>(Backwards); sen.RemoveRange(0, order); sen.Reverse(); sen.AddRange(Forwards); return string.Join(" ", sen); } } internal string LatestForwardChain { get { int start = Forwards.Count - order; return string.Join(" ", Forwards, start, order); } } internal string LatestBackwardChain { get { int start = Backwards.Count - order; return string.Join(" ", Backwards, start, order); } } List<string> Forwards; List<string> Backwards; readonly int order; internal SentenceConstruct(string initialChain, int order) { string[] split = initialChain.Split(' '); Forwards = new List<string>(split); Backwards = new List<string>(split); Backwards.Reverse(); this.order = order; } internal void Append(string word) { Forwards.Add(word); } internal void Prepend(string word) { Backwards.Add(word); } } }
using System; using System.Collections.Generic; namespace Chainey { internal class SentenceConstruct { internal int WordCount { get; private set; } internal string Sentence { get { var sen = new List<string>(Backwards); sen.RemoveRange(0, order); sen.Reverse(); sen.AddRange(Forwards); return string.Join(" ", sen); } } internal string LatestForwardChain { get { var chain = new string[order]; int start = Forwards.Count - order; Forwards.CopyTo(start, chain, 0, order); return string.Join(" ", Forwards, start, order); } } internal string LatestBackwardChain { get { var chain = new string[order]; int start = Backwards.Count - order; Backwards.CopyTo(start, chain, 0, order); return string.Join(" ", Backwards, start, order); } } List<string> Forwards; List<string> Backwards; readonly int order; internal SentenceConstruct(string initialChain) { string[] split = initialChain.Split(' '); Forwards = new List<string>(split); Backwards = new List<string>(split); Backwards.Reverse(); WordCount = split.Length; order = split.Length; } internal void Append(string word) { Forwards.Add(word); WordCount++; } internal void Prepend(string word) { Backwards.Add(word); WordCount++; } } }
Update Nuget version of package to 1.1.0.10-rc
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("KeyPay")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("KeyPay")] [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("93365e33-3b92-4ea6-ab42-ffecbc504138")] // 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: AssemblyInformationalVersion("1.1.0.10-rc")] [assembly: AssemblyFileVersion("1.0.0.0")]
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("KeyPay")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("KeyPay")] [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("93365e33-3b92-4ea6-ab42-ffecbc504138")] // 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: AssemblyInformationalVersion("1.1.0.10-rc2")] [assembly: AssemblyFileVersion("1.0.0.0")]
Refactor - UserMessage instead of attribute
using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using NUnit.Migrator.Model; namespace NUnit.Migrator.CodeActions { internal class AssertUserMessageDecorator : AssertExceptionBlockDecorator { private readonly ExceptionExpectancyAtAttributeLevel _attribute; public AssertUserMessageDecorator(IAssertExceptionBlockCreator blockCreator, ExceptionExpectancyAtAttributeLevel attribute) : base(blockCreator) { _attribute = attribute; } public override BlockSyntax Create(MethodDeclarationSyntax method, TypeSyntax assertedType) { var body = base.Create(method, assertedType); if (!TryFindAssertThrowsInvocation(body, out InvocationExpressionSyntax invocation)) return body; var userMessageArgument = SyntaxFactory.Argument( SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.ParseToken($"\"{_attribute.UserMessage}\""))); // TODO: no need for full attribute, msg only var decoratedInvocationArgumentList = invocation.ArgumentList.AddArguments(userMessageArgument); return body.ReplaceNode(invocation.ArgumentList, decoratedInvocationArgumentList); } private static bool TryFindAssertThrowsInvocation(BlockSyntax block, out InvocationExpressionSyntax invocation) { invocation = null; if (block.Statements.Count == 0) return false; invocation = (block.Statements.First() as ExpressionStatementSyntax)? .Expression as InvocationExpressionSyntax; return invocation != null; } } }
using System; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using NUnit.Migrator.Model; namespace NUnit.Migrator.CodeActions { internal class AssertUserMessageDecorator : AssertExceptionBlockDecorator { private readonly string _userMessage; public AssertUserMessageDecorator(IAssertExceptionBlockCreator blockCreator, ExceptionExpectancyAtAttributeLevel attribute) : base(blockCreator) { if (attribute == null) throw new ArgumentNullException(nameof(attribute)); _userMessage = attribute.UserMessage; } public override BlockSyntax Create(MethodDeclarationSyntax method, TypeSyntax assertedType) { var body = base.Create(method, assertedType); if (!TryFindAssertThrowsInvocation(body, out InvocationExpressionSyntax invocation)) return body; var userMessageArgument = SyntaxFactory.Argument( SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.ParseToken($"\"{_userMessage}\""))); var decoratedInvocationArgumentList = invocation.ArgumentList.AddArguments(userMessageArgument); return body.ReplaceNode(invocation.ArgumentList, decoratedInvocationArgumentList); } private static bool TryFindAssertThrowsInvocation(BlockSyntax block, out InvocationExpressionSyntax invocation) { invocation = null; if (block.Statements.Count == 0) return false; invocation = (block.Statements.First() as ExpressionStatementSyntax)? .Expression as InvocationExpressionSyntax; return invocation != null; } } }
Remove caching of invoked expressions as it is hard to do and adds little benefit
 using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Linq; namespace MFlow.Core.Internal { /// <summary> /// An expression builder /// </summary> class ExpressionBuilder<T> : IExpressionBuilder<T> { static IDictionary<object, object> _expressions= new Dictionary<object, object>(); static IDictionary<InvokeCacheKey, object> _compilations = new Dictionary<InvokeCacheKey, object>(); /// <summary> /// Compiles the expression /// </summary> public Func<T, C> Compile<C>(Expression<Func<T, C>> expression) { if(_expressions.ContainsKey(expression)) return (Func<T, C>)_expressions[expression]; var compiled = expression.Compile(); _expressions.Add(expression, compiled); return compiled; } /// <summary> /// Invokes the expression /// </summary> public C Invoke<C>(Func<T, C> compiled, T target) { return compiled.Invoke(target); } } class InvokeCacheKey { public object Target{get;set;} public object Func{get;set;} } }
 using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Linq; namespace MFlow.Core.Internal { /// <summary> /// An expression builder /// </summary> class ExpressionBuilder<T> : IExpressionBuilder<T> { static IDictionary<object, object> _expressions= new Dictionary<object, object>(); static IDictionary<InvokeCacheKey, object> _compilations = new Dictionary<InvokeCacheKey, object>(); /// <summary> /// Compiles the expression /// </summary> public Func<T, C> Compile<C>(Expression<Func<T, C>> expression) { if(_expressions.ContainsKey(expression)) return (Func<T, C>)_expressions[expression]; var compiled = expression.Compile(); _expressions.Add(expression, compiled); return compiled; } /// <summary> /// Invokes the expression /// </summary> public C Invoke<C>(Func<T, C> compiled, T target) { return compiled.Invoke(target); } } }
Add missing ctor field initializations
using SSMScripter.Integration; using System; using System.Data; namespace SSMScripter.Scripter.Smo { public class SmoObjectMetadata { public SmoObjectType Type { get; protected set; } public string Schema { get; protected set; } public string Name { get; protected set; } public string ParentSchema { get; protected set; } public string ParentName { get; protected set; } public bool? AnsiNullsStatus { get; set; } public bool? QuotedIdentifierStatus { get; set; } public SmoObjectMetadata(SmoObjectType type, string schema, string name, string parentSchema, string parentName) { Schema = schema; Name = name; } } }
using SSMScripter.Integration; using System; using System.Data; namespace SSMScripter.Scripter.Smo { public class SmoObjectMetadata { public SmoObjectType Type { get; protected set; } public string Schema { get; protected set; } public string Name { get; protected set; } public string ParentSchema { get; protected set; } public string ParentName { get; protected set; } public bool? AnsiNullsStatus { get; set; } public bool? QuotedIdentifierStatus { get; set; } public SmoObjectMetadata(SmoObjectType type, string schema, string name, string parentSchema, string parentName) { Type = type; Schema = schema; Name = name; ParentSchema = parentSchema; ParentName = parentName; } } }
Change div class and change the position of button back
@model SpaceBlog.Models.CommentViewModel @{ ViewBag.Title = "Edit"; } <h2>Edit</h2> @using (Html.BeginForm()) { @Html.AntiForgeryToken() <div class="form-horizontal"> <h4>Comment</h4> <hr /> @Html.ValidationSummary(true, "", new { @class = "text-danger" }) @Html.HiddenFor(m => m.Id) @Html.HiddenFor(m => m.ArticleId) @Html.HiddenFor(m => m.AuthorId) <div class="form-group"> @Html.LabelFor(model => model.Content, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.Content, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Content, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="Save" class="btn btn-default" /> </div> </div> </div> } <div> @Html.ActionLink("Back to List", "Index") </div> @section Scripts { @Scripts.Render("~/bundles/jqueryval") }
@model SpaceBlog.Models.CommentViewModel @{ ViewBag.Title = "Edit"; ViewBag.Message = "Comment"; } @using (Html.BeginForm()) { @Html.AntiForgeryToken() <div class="container"> <h2>@ViewBag.Title</h2> <h4>@ViewBag.Message</h4> <hr /> @Html.ValidationSummary(true, "", new { @class = "text-danger" }) @Html.HiddenFor(m => m.Id) @Html.HiddenFor(m => m.ArticleId) @Html.HiddenFor(m => m.AuthorId) <div class="form-group"> @Html.LabelFor(model => model.Content, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.Content, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Content, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10" style="margin-top: 10px"> <input type="submit" value="Save" class="btn btn-success" /> @Html.ActionLink("Back", "Index", new { @id = ""}, new { @class = "btn btn-primary" }) </div> </div> </div> } @section Scripts { @Scripts.Render("~/bundles/jqueryval") }
Change assertion to support multiple issues in test
using System.Threading.Tasks; using Xunit; using YouTrackSharp.Issues; using YouTrackSharp.Tests.Infrastructure; namespace YouTrackSharp.Tests.Integration.Issues { public partial class IssuesServiceTests { public class GetIssuesInProject { [Fact] public async Task Valid_Connection_Returns_Issues() { // Arrange var connection = Connections.Demo1Token; var service = new IssuesService(connection); // Act var result = await service.GetIssuesInProject("DP1", filter: "assignee:me"); // Assert Assert.NotNull(result); Assert.Collection(result, issue => Assert.Equal("DP1", ((dynamic)issue).ProjectShortName)); } [Fact] public async Task Invalid_Connection_Throws_UnauthorizedConnectionException() { // Arrange var service = new IssuesService(Connections.UnauthorizedConnection); // Act & Assert await Assert.ThrowsAsync<UnauthorizedConnectionException>( async () => await service.GetIssuesInProject("DP1")); } } } }
using System.Threading.Tasks; using Xunit; using YouTrackSharp.Issues; using YouTrackSharp.Tests.Infrastructure; namespace YouTrackSharp.Tests.Integration.Issues { public partial class IssuesServiceTests { public class GetIssuesInProject { [Fact] public async Task Valid_Connection_Returns_Issues() { // Arrange var connection = Connections.Demo1Token; var service = new IssuesService(connection); // Act var result = await service.GetIssuesInProject("DP1", filter: "assignee:me"); // Assert Assert.NotNull(result); foreach (dynamic issue in result) { Assert.Equal("DP1", issue.ProjectShortName); } } [Fact] public async Task Invalid_Connection_Throws_UnauthorizedConnectionException() { // Arrange var service = new IssuesService(Connections.UnauthorizedConnection); // Act & Assert await Assert.ThrowsAsync<UnauthorizedConnectionException>( async () => await service.GetIssuesInProject("DP1")); } } } }
Update aspnet middleware extension message to allow shouldRun to be passed in
 using Microsoft.AspNet.Builder; using System; namespace Glimpse.Host.Web.AspNet { public static class GlimpseExtension { /// <summary> /// Adds a middleware that allows GLimpse to be registered into the system. /// </summary> /// <param name="app"></param> /// <returns></returns> public static IApplicationBuilder UseGlimpse(this IApplicationBuilder app) { return app.Use(next => new GlimpseMiddleware(next, app.ApplicationServices).Invoke); } } }
 using Glimpse.Web; using Microsoft.AspNet.Builder; using System; namespace Glimpse.Host.Web.AspNet { public static class GlimpseExtension { /// <summary> /// Adds a middleware that allows GLimpse to be registered into the system. /// </summary> /// <param name="app"></param> /// <returns></returns> public static IApplicationBuilder UseGlimpse(this IApplicationBuilder app) { return app.Use(next => new GlimpseMiddleware(next, app.ApplicationServices).Invoke); } public static IApplicationBuilder UseGlimpse(this IApplicationBuilder app, Func<IHttpContext, bool> shouldRun) { return app.Use(next => new GlimpseMiddleware(next, app.ApplicationServices, shouldRun).Invoke); } } }
Make internals in MSTest2 visible for JustMock dll in lite version
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("MigrateMSTest")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MigrateMSTest")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("12629109-a1aa-4abb-852a-087dd15205f3")] // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("MigrateMSTest")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MigrateMSTest")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("12629109-a1aa-4abb-852a-087dd15205f3")] // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] #if LITE_EDITION [assembly: InternalsVisibleTo("Telerik.JustMock")] #endif
Rephrase culture-neutral number format helper so that it can successfully compile against both the full .NET Framework and .NET Core.
namespace Fixie.Tests { using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text.RegularExpressions; using System.Threading; using Fixie.Execution; public static class TestExtensions { const BindingFlags InstanceMethods = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; public static MethodInfo GetInstanceMethod(this Type type, string methodName) { return type.GetMethod(methodName, InstanceMethods); } public static IReadOnlyList<MethodInfo> GetInstanceMethods(this Type type) { return type.GetMethods(InstanceMethods); } public static IEnumerable<string> Lines(this RedirectedConsole console) { return console.Output.Lines(); } public static IEnumerable<string> Lines(this string multiline) { var lines = multiline.Split(new[] { Environment.NewLine }, StringSplitOptions.None).ToList(); while (lines.Count > 0 && lines[lines.Count-1] == "") lines.RemoveAt(lines.Count-1); return lines; } public static string CleanStackTraceLineNumbers(this string stackTrace) { //Avoid brittle assertion introduced by stack trace line numbers. return Regex.Replace(stackTrace, @":line \d+", ":line #"); } public static string CleanDuration(this string output) { //Avoid brittle assertion introduced by test duration. var decimalSeparator = Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator; return Regex.Replace(output, @"took [\d" + Regex.Escape(decimalSeparator) + @"]+ seconds", @"took 1.23 seconds"); } } }
namespace Fixie.Tests { using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; using System.Text.RegularExpressions; using Fixie.Execution; public static class TestExtensions { const BindingFlags InstanceMethods = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; public static MethodInfo GetInstanceMethod(this Type type, string methodName) { return type.GetMethod(methodName, InstanceMethods); } public static IReadOnlyList<MethodInfo> GetInstanceMethods(this Type type) { return type.GetMethods(InstanceMethods); } public static IEnumerable<string> Lines(this RedirectedConsole console) { return console.Output.Lines(); } public static IEnumerable<string> Lines(this string multiline) { var lines = multiline.Split(new[] { Environment.NewLine }, StringSplitOptions.None).ToList(); while (lines.Count > 0 && lines[lines.Count-1] == "") lines.RemoveAt(lines.Count-1); return lines; } public static string CleanStackTraceLineNumbers(this string stackTrace) { //Avoid brittle assertion introduced by stack trace line numbers. return Regex.Replace(stackTrace, @":line \d+", ":line #"); } public static string CleanDuration(this string output) { //Avoid brittle assertion introduced by test duration. var decimalSeparator = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator; return Regex.Replace(output, @"took [\d" + Regex.Escape(decimalSeparator) + @"]+ seconds", @"took 1.23 seconds"); } } }
Implement the option to start the app when logging into Windows
using MultiMiner.Engine.Configuration; using System; using System.IO; namespace MultiMiner.Win { public class ApplicationConfiguration { public ApplicationConfiguration() { this.StartupMiningDelay = 45; } public bool LaunchOnWindowsLogin { get; set; } public bool StartMiningOnStartup { get; set; } public int StartupMiningDelay { get; set; } public bool RestartCrashedMiners { get; set; } private static string AppDataPath() { string rootPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); return Path.Combine(rootPath, "MultiMiner"); } private static string DeviceConfigurationsFileName() { return Path.Combine(AppDataPath(), "ApplicationConfiguration.xml"); } public void SaveApplicationConfiguration() { ConfigurationReaderWriter.WriteConfiguration(this, DeviceConfigurationsFileName()); } public void LoadApplicationConfiguration() { ApplicationConfiguration tmp = ConfigurationReaderWriter.ReadConfiguration<ApplicationConfiguration>(DeviceConfigurationsFileName()); this.LaunchOnWindowsLogin = tmp.LaunchOnWindowsLogin; this.StartMiningOnStartup = tmp.StartMiningOnStartup; this.StartupMiningDelay = tmp.StartupMiningDelay; this.RestartCrashedMiners = tmp.RestartCrashedMiners; } } }
using Microsoft.Win32; using MultiMiner.Engine.Configuration; using System; using System.IO; using System.Windows.Forms; namespace MultiMiner.Win { public class ApplicationConfiguration { public ApplicationConfiguration() { this.StartupMiningDelay = 45; } public bool LaunchOnWindowsLogin { get; set; } public bool StartMiningOnStartup { get; set; } public int StartupMiningDelay { get; set; } public bool RestartCrashedMiners { get; set; } private static string AppDataPath() { string rootPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); return Path.Combine(rootPath, "MultiMiner"); } private static string DeviceConfigurationsFileName() { return Path.Combine(AppDataPath(), "ApplicationConfiguration.xml"); } public void SaveApplicationConfiguration() { ConfigurationReaderWriter.WriteConfiguration(this, DeviceConfigurationsFileName()); ApplyLaunchOnWindowsStartup(); } private void ApplyLaunchOnWindowsStartup() { RegistryKey registrykey = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true); if (LaunchOnWindowsLogin) registrykey.SetValue("MultiMiner", Application.ExecutablePath); else registrykey.DeleteValue("MultiMiner", false); } public void LoadApplicationConfiguration() { ApplicationConfiguration tmp = ConfigurationReaderWriter.ReadConfiguration<ApplicationConfiguration>(DeviceConfigurationsFileName()); this.LaunchOnWindowsLogin = tmp.LaunchOnWindowsLogin; this.StartMiningOnStartup = tmp.StartMiningOnStartup; this.StartupMiningDelay = tmp.StartupMiningDelay; this.RestartCrashedMiners = tmp.RestartCrashedMiners; } } }
Add non-args constructor for serialization.
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Battlezeppelins.Models { public class GameTable { public const int TABLE_ROWS = 10; public const int TABLE_COLS = 10; public Game.Role role { get; private set; } public List<OpenPoint> openPoints { get; private set; } public List<Zeppelin> zeppelins { get; private set; } public GameTable(Game.Role role) { this.role = role; this.openPoints = new List<OpenPoint>(); this.zeppelins = new List<Zeppelin>(); } public void removeZeppelins() { zeppelins = null; } public bool AddZeppelin(Zeppelin newZeppelin) { foreach (Zeppelin zeppelin in this.zeppelins) { // No multiple zeppelins of the same type if (zeppelin.type == newZeppelin.type) return false; // No colliding zeppelins if (zeppelin.collides(newZeppelin)) return false; } if (newZeppelin.x < 0 || newZeppelin.x + newZeppelin.getWidth()-1 > TABLE_COLS - 1 || newZeppelin.y < 0 || newZeppelin.y + newZeppelin.getHeight()-1 > TABLE_ROWS - 1) { return false; } this.zeppelins.Add(newZeppelin); return true; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Battlezeppelins.Models { public class GameTable { public const int TABLE_ROWS = 10; public const int TABLE_COLS = 10; public Game.Role role { get; private set; } public List<OpenPoint> openPoints { get; private set; } public List<Zeppelin> zeppelins { get; private set; } public GameTable() { } public GameTable(Game.Role role) { this.role = role; this.openPoints = new List<OpenPoint>(); this.zeppelins = new List<Zeppelin>(); } public void removeZeppelins() { zeppelins = null; } public bool AddZeppelin(Zeppelin newZeppelin) { foreach (Zeppelin zeppelin in this.zeppelins) { // No multiple zeppelins of the same type if (zeppelin.type == newZeppelin.type) return false; // No colliding zeppelins if (zeppelin.collides(newZeppelin)) return false; } if (newZeppelin.x < 0 || newZeppelin.x + newZeppelin.getWidth()-1 > TABLE_COLS - 1 || newZeppelin.y < 0 || newZeppelin.y + newZeppelin.getHeight()-1 > TABLE_ROWS - 1) { return false; } this.zeppelins.Add(newZeppelin); return true; } } }
Create a non-null functionality wrapper in the required test.
namespace NBench.VisualStudio.TestAdapter.Tests.Unit.NBenchTestDiscoverer.NBenchTestDiscoverer { using JustBehave; using NBench.VisualStudio.TestAdapter; using NBench.VisualStudio.TestAdapter.Helpers; using Ploeh.AutoFixture; using Ploeh.AutoFixture.AutoNSubstitute; using Xunit; public class WhenTheNBenchFunctionalityWrapperIsNotNull : XBehaviourTest<NBenchTestDiscoverer> { private INBenchFunctionalityWrapper functionalitywrapper; protected override NBenchTestDiscoverer CreateSystemUnderTest() { return new NBenchTestDiscoverer(this.functionalitywrapper); } protected override void CustomizeAutoFixture(IFixture fixture) { fixture.Customize(new AutoNSubstituteCustomization()); } protected override void Given() { this.functionalitywrapper = null; } protected override void When() { } [Fact] public void TheNBenchTestDiscovererIsNotNull() { Assert.NotNull(this.SystemUnderTest); } } }
namespace NBench.VisualStudio.TestAdapter.Tests.Unit.NBenchTestDiscoverer.NBenchTestDiscoverer { using JustBehave; using NBench.VisualStudio.TestAdapter; using NBench.VisualStudio.TestAdapter.Helpers; using Ploeh.AutoFixture; using Ploeh.AutoFixture.AutoNSubstitute; using Xunit; public class WhenTheNBenchFunctionalityWrapperIsNotNull : XBehaviourTest<NBenchTestDiscoverer> { private INBenchFunctionalityWrapper functionalitywrapper; protected override NBenchTestDiscoverer CreateSystemUnderTest() { return new NBenchTestDiscoverer(this.functionalitywrapper); } protected override void CustomizeAutoFixture(IFixture fixture) { fixture.Customize(new AutoNSubstituteCustomization()); } protected override void Given() { this.functionalitywrapper = this.Fixture.Create<INBenchFunctionalityWrapper>(); } protected override void When() { } [Fact] public void TheNBenchTestDiscovererIsNotNull() { Assert.NotNull(this.SystemUnderTest); } } }
Add several methods for Windows: IsAdmin
using System; using System.Diagnostics; using System.Reflection; namespace FonctionsUtiles.Fred.Csharp { public class FunctionsWindows { public static bool IsInWinPath(string substring) { bool result = false; string winPath = Environment.GetEnvironmentVariable("Path", EnvironmentVariableTarget.Machine); if (winPath != null) result = winPath.Contains(substring); return result; } public static string DisplayTitle() { Assembly assembly = Assembly.GetExecutingAssembly(); FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(assembly.Location); return $@"V{fvi.FileMajorPart}.{fvi.FileMinorPart}.{fvi.FileBuildPart}.{fvi.FilePrivatePart}"; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Security.Principal; namespace FonctionsUtiles.Fred.Csharp { public class FunctionsWindows { public static bool IsInWinPath(string substring) { bool result = false; string winPath = Environment.GetEnvironmentVariable("Path", EnvironmentVariableTarget.Machine); if (winPath != null) result = winPath.Contains(substring); return result; } public static string DisplayTitle() { Assembly assembly = Assembly.GetExecutingAssembly(); FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(assembly.Location); return $@"V{fvi.FileMajorPart}.{fvi.FileMinorPart}.{fvi.FileBuildPart}.{fvi.FilePrivatePart}"; } public static bool IsAdministrator() { WindowsIdentity identity = WindowsIdentity.GetCurrent(); WindowsPrincipal principal = new WindowsPrincipal(identity); return principal.IsInRole(WindowsBuiltInRole.Administrator); } public static bool IsAdmin() { return new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator); } public static IEnumerable<Process> GetAllProcesses() { Process[] processlist = Process.GetProcesses(); return processlist.ToList(); } public static bool IsProcessRunningById(Process process) { try { Process.GetProcessById(process.Id); } catch (InvalidOperationException) { return false; } catch (ArgumentException) { return false; } return true; } public static bool IsProcessRunningByName(string processName) { try { Process.GetProcessesByName(processName); } catch (InvalidOperationException) { return false; } catch (ArgumentException) { return false; } return true; } public static Process GetProcessByName(string processName) { Process result = new Process(); foreach (Process process in GetAllProcesses()) { if (process.ProcessName == processName) { result = process; break; } } return result; } } }
Add additional tests for EnumMatchToBooleanConverter
using System.Globalization; using System.Reflection; using FluentAssertions; using Microsoft.Office.Interop.Outlook; using Moq; using NUnit.Framework; using OutlookMatters.Core.Settings; namespace Test.OutlookMatters.Core.Settings { [TestFixture] public class EnumMatchToBooleanConverterTest { [Test] [TestCase(MattermostVersion.ApiVersionOne, MattermostVersion.ApiVersionOne, true)] [TestCase(MattermostVersion.ApiVersionOne, MattermostVersion.ApiVersionThree, false)] [TestCase(null, MattermostVersion.ApiVersionThree, false)] [TestCase(MattermostVersion.ApiVersionOne, null, false)] public void Convert_ConvertsToExpectedResult(object parameter, object value, bool expectedResult) { var classUnderTest = new EnumMatchToBooleanConverter(); var result = classUnderTest.Convert(value, typeof (bool), parameter, It.IsAny<CultureInfo>()); Assert.That(result, Is.EqualTo(expectedResult)); } } }
using System.Globalization; using System.Reflection; using FluentAssertions; using Microsoft.Office.Interop.Outlook; using Moq; using NUnit.Framework; using OutlookMatters.Core.Settings; namespace Test.OutlookMatters.Core.Settings { [TestFixture] public class EnumMatchToBooleanConverterTest { [Test] [TestCase(MattermostVersion.ApiVersionOne, MattermostVersion.ApiVersionOne, true)] [TestCase(MattermostVersion.ApiVersionOne, MattermostVersion.ApiVersionThree, false)] [TestCase(null, MattermostVersion.ApiVersionThree, false)] [TestCase(MattermostVersion.ApiVersionOne, null, false)] public void Convert_ConvertsToExpectedResult(object parameter, object value, bool expectedResult) { var classUnderTest = new EnumMatchToBooleanConverter(); var result = classUnderTest.Convert(value, typeof (bool), parameter, It.IsAny<CultureInfo>()); Assert.That(result, Is.EqualTo(expectedResult)); } [Test] [TestCase(true, "ApiVersionOne", MattermostVersion.ApiVersionOne)] [TestCase(false, "ApiVersionOne", null)] [TestCase(true, null, null)] [TestCase(null, "ApiVersionOne", null)] public void ConvertBack_ConvertsToExpectedResult(object value, object parameter, object expectedResult) { var classUnderTest = new EnumMatchToBooleanConverter(); var result = classUnderTest.ConvertBack(value, typeof(MattermostVersion), parameter, It.IsAny<CultureInfo>()); Assert.That(result, Is.EqualTo(expectedResult)); } } }
Reset Chutes & Ladders demos to run demo 1 by default
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ChutesAndLadders.GamePlay; using ChutesAndLadders.Entities; using System.Diagnostics; namespace Chute { class Program { static void Main(string[] args) { var board = new GameBoard(); #region Demo 1 // board.Demo1a_GreedyAlgorithm(); #endregion #region Demo 2 // board.Demo2a_RulesEngine(); // board.Demo2b_ImprovedLinear(); #endregion #region Demo 3 // Only do demo 3b unless there is time left over // board.Demo3a_GeneticAnalysis(); // board.Demo3b_GeneticEvolution(); // board.Demo3c_GeneticSuperiority(); #endregion #region Demo 4 // board.Demo4a_ShortestPath(); #endregion #region Supplemental Demos // board.SupplementalDemo_SingleGame(); // board.SupplementalDemo_Player1Advantage(); board.GameActionOutput_SmallSample(); #endregion } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ChutesAndLadders.GamePlay; using ChutesAndLadders.Entities; using System.Diagnostics; namespace Chute { class Program { static void Main(string[] args) { var board = new GameBoard(); #region Demo 1 board.Demo1a_GreedyAlgorithm(); #endregion #region Demo 2 // board.Demo2a_RulesEngine(); // board.Demo2b_ImprovedLinear(); #endregion #region Demo 3 // Only do demo 3b unless there is time left over // board.Demo3a_GeneticAnalysis(); // board.Demo3b_GeneticEvolution(); // board.Demo3c_GeneticSuperiority(); #endregion #region Demo 4 // board.Demo4a_ShortestPath(); #endregion #region Supplemental Demos // board.SupplementalDemo_SingleGame(); // board.SupplementalDemo_Player1Advantage(); // board.GameActionOutput_SmallSample(); #endregion } } }
Simplify property name for LineItemMembershipSubject
using LtiLibrary.Core.Common; using Newtonsoft.Json; namespace LtiLibrary.Core.Outcomes.v2 { /// <summary> /// A LineItemContainer defines the endpoint to which clients POST new LineItem resources /// and from which they GET the list of LineItems associated with a a given learning context. /// </summary> public class LineItemContainer : JsonLdObject { public LineItemContainer() { Type = LtiConstants.LineItemContainerType; } /// <summary> /// Optional indication of which resource is the subject for the members of the container. /// </summary> [JsonProperty("membershipSubject")] public LineItemMembershipSubject LineItemMembershipSubject { get; set; } } }
using LtiLibrary.Core.Common; using Newtonsoft.Json; namespace LtiLibrary.Core.Outcomes.v2 { /// <summary> /// A LineItemContainer defines the endpoint to which clients POST new LineItem resources /// and from which they GET the list of LineItems associated with a a given learning context. /// </summary> public class LineItemContainer : JsonLdObject { public LineItemContainer() { Type = LtiConstants.LineItemContainerType; } /// <summary> /// Optional indication of which resource is the subject for the members of the container. /// </summary> [JsonProperty("membershipSubject")] public LineItemMembershipSubject MembershipSubject { get; set; } } }
Fix wrong property mapping in SearchShard
using System.Collections.Generic; using Nest.Domain; using Newtonsoft.Json; using System.Linq.Expressions; using System; using System.Linq; namespace Nest { [JsonObject(MemberSerialization.OptIn)] public interface ISearchShardsResponse : IResponse { [JsonProperty("shards")] IEnumerable<IEnumerable<SearchShard>> Shards { get; } [JsonProperty("nodes")] IDictionary<string, SearchNode> Nodes { get; } } public class SearchShardsResponse : BaseResponse, ISearchShardsResponse { public IEnumerable<IEnumerable<SearchShard>> Shards { get; internal set; } public IDictionary<string, SearchNode> Nodes { get; internal set; } } [JsonObject(MemberSerialization.OptIn)] public class SearchNode { [JsonProperty("name")] public string Name { get; set; } [JsonProperty("transport_address")] public string TransportAddress { get; set; } } [JsonObject(MemberSerialization.OptIn)] public class SearchShard { [JsonProperty("name")] public string State { get; set;} [JsonProperty("primary")] public bool Primary { get; set;} [JsonProperty("node")] public string Node { get; set;} [JsonProperty("relocating_node")] public string RelocatingNode { get; set;} [JsonProperty("shard")] public int Shard { get; set;} [JsonProperty("index")] public string Index { get; set;} } }
using Nest.Domain; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; namespace Nest { [JsonObject(MemberSerialization.OptIn)] public interface ISearchShardsResponse : IResponse { [JsonProperty("shards")] IEnumerable<IEnumerable<SearchShard>> Shards { get; } [JsonProperty("nodes")] IDictionary<string, SearchNode> Nodes { get; } } public class SearchShardsResponse : BaseResponse, ISearchShardsResponse { public IEnumerable<IEnumerable<SearchShard>> Shards { get; internal set; } public IDictionary<string, SearchNode> Nodes { get; internal set; } } [JsonObject(MemberSerialization.OptIn)] public class SearchNode { [JsonProperty("name")] public string Name { get; set; } [JsonProperty("transport_address")] public string TransportAddress { get; set; } } [JsonObject(MemberSerialization.OptIn)] public class SearchShard { [JsonProperty("state")] public string State { get; set; } [JsonProperty("primary")] public bool Primary { get; set; } [JsonProperty("node")] public string Node { get; set; } [JsonProperty("relocating_node")] public string RelocatingNode { get; set; } [JsonProperty("shard")] public int Shard { get; set; } [JsonProperty("index")] public string Index { get; set; } } }
Clarify behaviour on non-Windows systems
using HotChocolate.Types; using Snowflake.Framework.Remoting.GraphQL.Model.Filesystem; using Snowflake.Framework.Remoting.GraphQL.Model.Filesystem.Contextual; using Snowflake.Framework.Remoting.GraphQL.Schema; using Snowflake.Services; using System; using System.Collections.Generic; using System.IO; using System.Text; namespace Snowflake.Support.GraphQLFrameworkQueries.Queries.Filesystem { public class FilesystemQueries : ObjectTypeExtension { protected override void Configure(IObjectTypeDescriptor descriptor) { descriptor.Name("Query"); descriptor.Field("filesystem") .Argument("directoryPath", a => a.Type<OSDirectoryPathType>().Description("The path to explore.")) .Resolver(context => { var path = context.Argument<DirectoryInfo>("directoryPath"); if (path == null) return DriveInfo.GetDrives(); if (path.Exists) return path; return null; }) .Type<OSDirectoryContentsInterface>() .Description("Provides normalized OS-dependent filesystem access." + "Returns null if the specified path does not exist."); } } }
using HotChocolate.Types; using Microsoft.DotNet.PlatformAbstractions; using Snowflake.Framework.Remoting.GraphQL.Model.Filesystem; using Snowflake.Framework.Remoting.GraphQL.Model.Filesystem.Contextual; using Snowflake.Framework.Remoting.GraphQL.Schema; using Snowflake.Services; using System; using System.Collections.Generic; using System.IO; using System.Runtime.InteropServices; using System.Text; namespace Snowflake.Support.GraphQLFrameworkQueries.Queries.Filesystem { public class FilesystemQueries : ObjectTypeExtension { protected override void Configure(IObjectTypeDescriptor descriptor) { descriptor.Name("Query"); descriptor.Field("filesystem") .Argument("directoryPath", a => a.Type<OSDirectoryPathType>() .Description("The path to explore. If this is null, returns a listing of drives on Windows, " + "or the root directory on a Unix-like system.")) .Resolver(context => { var path = context.Argument<DirectoryInfo>("directoryPath"); if (path == null && RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) return DriveInfo.GetDrives(); if (path == null && (RuntimeInformation.IsOSPlatform(OSPlatform.OSX) || RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) || RuntimeInformation.IsOSPlatform(OSPlatform.FreeBSD)) return new DirectoryInfo("/"); if (path?.Exists ?? false) return path; return null; }) .Type<OSDirectoryContentsInterface>() .Description("Provides normalized OS-dependent filesystem access." + "Returns null if the specified path does not exist."); } } }
Increase assembly version to 1.2.0
using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle("Tiny-JSON")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("Robert Gering")] [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.1.2")] // 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("")]
using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle("Tiny-JSON")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("Robert Gering")] [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.2.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("")]
Change try remove key pair method semantics
using System.Collections.Concurrent; using System.Collections.Generic; namespace Utility.Extensions { public static class ConcurrentDictionaryExtensions { public static bool TryRemove<TKey, TValue>(this ConcurrentDictionary<TKey, TValue> dictionary, TKey key) { TValue value; return dictionary.TryRemove(key, out value); } /// <remarks> /// This is a hack but is atomic at time of writing! Unlikely to change but a unit test exists to test it as best it can (not 100%!) /// </remarks> public static bool TryRemove<TKey, TValue>(this ConcurrentDictionary<TKey, TValue> dictionary, TKey key, TValue value) { ICollection<KeyValuePair<TKey, TValue>> collection = dictionary; return collection.Remove(new KeyValuePair<TKey, TValue>(key, value)); } } }
using System.Collections.Concurrent; using System.Collections.Generic; namespace Utility.Extensions { public static class ConcurrentDictionaryExtensions { public static bool TryRemove<TKey, TValue>(this ConcurrentDictionary<TKey, TValue> dictionary, TKey key) { TValue value; return dictionary.TryRemove(key, out value); } /// <remarks> /// HACK: is atomic at time of writing! Unlikely to change but a unit test exists to test it as best it can. /// </remarks> public static bool TryRemove<TKey, TValue>(this ICollection<KeyValuePair<TKey, TValue>> collection, TKey key, TValue value) { return collection.Remove(new KeyValuePair<TKey, TValue>(key, value)); } } }
Use the in-memory database for testing the home controller
using IdeaWeb.Controllers; using Microsoft.AspNetCore.Mvc; using NUnit.Framework; namespace IdeaWeb.Test { [TestFixture] public class HomeControllerTests { HomeController _controller; [SetUp] public void SetUp() { _controller = new HomeController(); } [Test] public void IndexReturnsIdeasView() { IActionResult result = _controller.Index(); Assert.That(result, Is.Not.Null); } } }
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using IdeaWeb.Controllers; using IdeaWeb.Data; using IdeaWeb.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using NUnit.Framework; namespace IdeaWeb.Test { [TestFixture] public class HomeControllerTests { const int NUM_IDEAS = 10; HomeController _controller; [SetUp] public void SetUp() { // Create unique database names based on the test id var options = new DbContextOptionsBuilder<IdeaContext>() .UseInMemoryDatabase(TestContext.CurrentContext.Test.ID) .Options; // Seed the in-memory database using (var context = new IdeaContext(options)) { for(int i = 1; i <= NUM_IDEAS; i++) { context.Add(new Idea { Name = $"Idea name {i}", Description = $"Description {i}", Rating = i % 3 + 1 }); } context.SaveChanges(); } // Use a clean copy of the context within the tests _controller = new HomeController(new IdeaContext(options)); } [Test] public async Task IndexReturnsListOfIdeas() { ViewResult result = await _controller.Index() as ViewResult; Assert.That(result?.Model, Is.Not.Null); Assert.That(result.Model, Has.Count.EqualTo(NUM_IDEAS)); IEnumerable<Idea> ideas = result.Model as IEnumerable<Idea>; Idea idea = ideas?.FirstOrDefault(); Assert.That(idea, Is.Not.Null); Assert.That(idea.Name, Is.EqualTo("Idea name 1")); Assert.That(idea.Description, Does.Contain("1")); Assert.That(idea.Rating, Is.EqualTo(2)); } } }
Adjust initial size to look nicer
namespace DependencyInjection.Console { internal class PatternApp { private readonly PatternWriter _patternWriter; private readonly PatternGenerator _patternGenerator; public PatternApp(bool useColours) { _patternWriter = new PatternWriter(useColours); _patternGenerator = new PatternGenerator(); } public void Run() { var pattern = _patternGenerator.Generate(10, 10); _patternWriter.Write(pattern); } } }
namespace DependencyInjection.Console { internal class PatternApp { private readonly PatternWriter _patternWriter; private readonly PatternGenerator _patternGenerator; public PatternApp(bool useColours) { _patternWriter = new PatternWriter(useColours); _patternGenerator = new PatternGenerator(); } public void Run() { var pattern = _patternGenerator.Generate(25, 15); _patternWriter.Write(pattern); } } }
Split test into two separate tests
using Xunit; namespace EmotionAPI.Tests { public class EmotionAPIClientTests : EmotionAPITestsBase { [Fact] public void Can_Create_EmotionAPIClient_Controller() { var controller = new EmotionAPIClient(mockOcpApimSubscriptionKey); Assert.NotNull(controller); Assert.NotEmpty(controller.OcpApimSubscriptionKey); } } }
using Xunit; namespace EmotionAPI.Tests { public class EmotionAPIClientTests : EmotionAPITestsBase { [Fact] public void Can_Create_EmotionAPIClient_Class() { var sut = new EmotionAPIClient(mockOcpApimSubscriptionKey); Assert.NotNull(sut); } [Fact] public void OcpApimSubscriptionKey_Is_Being_Set() { var sut = new EmotionAPIClient(mockOcpApimSubscriptionKey); Assert.NotEmpty(sut.OcpApimSubscriptionKey); } } }
Add keyboard shortcut to open dev tools (Ctrl+Shift+I)
using System.Windows.Forms; using CefSharp; namespace TweetDuck.Core.Handling{ class KeyboardHandlerBase : IKeyboardHandler{ protected virtual bool HandleRawKey(IWebBrowser browserControl, IBrowser browser, Keys key, CefEventFlags modifiers){ return false; } bool IKeyboardHandler.OnPreKeyEvent(IWebBrowser browserControl, IBrowser browser, KeyType type, int windowsKeyCode, int nativeKeyCode, CefEventFlags modifiers, bool isSystemKey, ref bool isKeyboardShortcut){ if (type == KeyType.RawKeyDown && !browser.FocusedFrame.Url.StartsWith("chrome-devtools://")){ return HandleRawKey(browserControl, browser, (Keys)windowsKeyCode, modifiers); } return false; } bool IKeyboardHandler.OnKeyEvent(IWebBrowser browserControl, IBrowser browser, KeyType type, int windowsKeyCode, int nativeKeyCode, CefEventFlags modifiers, bool isSystemKey){ return false; } } }
using System.Windows.Forms; using CefSharp; using TweetDuck.Core.Controls; using TweetDuck.Core.Other; using TweetDuck.Core.Utils; namespace TweetDuck.Core.Handling{ class KeyboardHandlerBase : IKeyboardHandler{ protected virtual bool HandleRawKey(IWebBrowser browserControl, IBrowser browser, Keys key, CefEventFlags modifiers){ if (modifiers == (CefEventFlags.ControlDown | CefEventFlags.ShiftDown) && key == Keys.I){ if (BrowserUtils.HasDevTools){ browser.ShowDevTools(); } else{ browserControl.AsControl().InvokeSafe(() => { string extraMessage; if (Program.IsPortable){ extraMessage = "Please download the portable installer, select the folder with your current installation of TweetDuck Portable, and tick 'Install dev tools' during the installation process."; } else{ extraMessage = "Please download the installer, and tick 'Install dev tools' during the installation process. The installer will automatically find and update your current installation of TweetDuck."; } FormMessage.Information("Dev Tools", "You do not have dev tools installed. "+extraMessage, FormMessage.OK); }); } return true; } return false; } bool IKeyboardHandler.OnPreKeyEvent(IWebBrowser browserControl, IBrowser browser, KeyType type, int windowsKeyCode, int nativeKeyCode, CefEventFlags modifiers, bool isSystemKey, ref bool isKeyboardShortcut){ if (type == KeyType.RawKeyDown && !browser.FocusedFrame.Url.StartsWith("chrome-devtools://")){ return HandleRawKey(browserControl, browser, (Keys)windowsKeyCode, modifiers); } return false; } bool IKeyboardHandler.OnKeyEvent(IWebBrowser browserControl, IBrowser browser, KeyType type, int windowsKeyCode, int nativeKeyCode, CefEventFlags modifiers, bool isSystemKey){ return false; } } }
Fix pages slug to not be case sensitive when used in url
using System; using System.Web.Mvc; using Orchard.Localization; using Orchard.ContentManagement; using Orchard.Pages.Services; using Orchard.Pages.ViewModels; using Orchard.Security; namespace Orchard.Pages.Controllers { [ValidateInput(false)] public class PageController : Controller, IUpdateModel { private readonly IPageService _pageService; private readonly ISlugConstraint _slugConstraint; public PageController( IOrchardServices services, IPageService pageService, ISlugConstraint slugConstraint) { Services = services; _pageService = pageService; _slugConstraint = slugConstraint; T = NullLocalizer.Instance; } public IOrchardServices Services { get; set; } private Localizer T { get; set; } public ActionResult Item(string slug) { if (!Services.Authorizer.Authorize(StandardPermissions.AccessFrontEnd, T("Couldn't view page"))) return new HttpUnauthorizedResult(); if (slug == null) { throw new ArgumentNullException("slug"); } //var correctedSlug = _slugConstraint.LookupPublishedSlug(pageSlug); var page = _pageService.Get(slug); var model = new PageViewModel { Page = Services.ContentManager.BuildDisplayModel(page, "Detail") }; return View(model); } bool IUpdateModel.TryUpdateModel<TModel>(TModel model, string prefix, string[] includeProperties, string[] excludeProperties) { return TryUpdateModel(model, prefix, includeProperties, excludeProperties); } void IUpdateModel.AddModelError(string key, LocalizedString errorMessage) { ModelState.AddModelError(key, errorMessage.ToString()); } } }
using System; using System.Web.Mvc; using Orchard.Localization; using Orchard.ContentManagement; using Orchard.Mvc.Results; using Orchard.Pages.Services; using Orchard.Pages.ViewModels; using Orchard.Security; namespace Orchard.Pages.Controllers { [ValidateInput(false)] public class PageController : Controller { private readonly IPageService _pageService; private readonly ISlugConstraint _slugConstraint; public PageController(IOrchardServices services, IPageService pageService, ISlugConstraint slugConstraint) { Services = services; _pageService = pageService; _slugConstraint = slugConstraint; T = NullLocalizer.Instance; } public IOrchardServices Services { get; set; } private Localizer T { get; set; } public ActionResult Item(string slug) { if (!Services.Authorizer.Authorize(StandardPermissions.AccessFrontEnd, T("Couldn't view page"))) return new HttpUnauthorizedResult(); var correctedSlug = _slugConstraint.LookupPublishedSlug(slug); if (correctedSlug == null) return new NotFoundResult(); var page = _pageService.Get(correctedSlug); if (page == null) return new NotFoundResult(); var model = new PageViewModel { Page = Services.ContentManager.BuildDisplayModel(page, "Detail") }; return View(model); } } }
Fix case of zero rate calculating a zero true gameplay rate
// 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; namespace osu.Game.Screens.Play { public static class GameplayClockExtensions { /// <summary> /// The rate of gameplay when playback is at 100%. /// This excludes any seeking / user adjustments. /// </summary> public static double GetTrueGameplayRate(this IGameplayClock clock) { // To handle rewind, we still want to maintain the same direction as the underlying clock. double rate = Math.Sign(clock.Rate); return rate * clock.GameplayAdjustments.AggregateFrequency.Value * clock.GameplayAdjustments.AggregateTempo.Value; } } }
// 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; namespace osu.Game.Screens.Play { public static class GameplayClockExtensions { /// <summary> /// The rate of gameplay when playback is at 100%. /// This excludes any seeking / user adjustments. /// </summary> public static double GetTrueGameplayRate(this IGameplayClock clock) { // To handle rewind, we still want to maintain the same direction as the underlying clock. double rate = clock.Rate == 0 ? 1 : Math.Sign(clock.Rate); return rate * clock.GameplayAdjustments.AggregateFrequency.Value * clock.GameplayAdjustments.AggregateTempo.Value; } } }
Allow to use input event arguments in the event handlers
using OpenTK.Input; namespace MonoHaven.Input { public abstract class InputEvent { private readonly KeyModifiers mods; protected InputEvent() { mods = GetCurrentKeyModifiers(); } public bool Handled { get; set; } public KeyModifiers Modifiers { get { return mods; } } private static KeyModifiers GetCurrentKeyModifiers() { var mods = (KeyModifiers)0; var keyboardState = Keyboard.GetState(); if (keyboardState.IsKeyDown(Key.LShift) || keyboardState.IsKeyDown(Key.RShift)) mods |= KeyModifiers.Shift; if (keyboardState.IsKeyDown(Key.LAlt) || keyboardState.IsKeyDown(Key.RAlt)) mods |= KeyModifiers.Alt; if (keyboardState.IsKeyDown(Key.ControlLeft) || keyboardState.IsKeyDown(Key.ControlRight)) mods |= KeyModifiers.Control; return mods; } } }
using System; using OpenTK.Input; namespace MonoHaven.Input { public abstract class InputEvent : EventArgs { private readonly KeyModifiers mods; protected InputEvent() { mods = GetCurrentKeyModifiers(); } public bool Handled { get; set; } public KeyModifiers Modifiers { get { return mods; } } private static KeyModifiers GetCurrentKeyModifiers() { var mods = (KeyModifiers)0; var keyboardState = Keyboard.GetState(); if (keyboardState.IsKeyDown(Key.LShift) || keyboardState.IsKeyDown(Key.RShift)) mods |= KeyModifiers.Shift; if (keyboardState.IsKeyDown(Key.LAlt) || keyboardState.IsKeyDown(Key.RAlt)) mods |= KeyModifiers.Alt; if (keyboardState.IsKeyDown(Key.ControlLeft) || keyboardState.IsKeyDown(Key.ControlRight)) mods |= KeyModifiers.Control; return mods; } } }
Add vscode to git ignore
using SlugityLib.Configuration; namespace SlugityLib.Tests { public class CustomSlugityConfig : ISlugityConfig { public CustomSlugityConfig() { TextCase = TextCase.LowerCase; StripStopWords = false; MaxLength = 30; StringSeparator = ' '; ReplacementCharacters = new CharacterReplacement(); } public TextCase TextCase { get; set; } public char StringSeparator { get; set; } public int? MaxLength { get; set; } public CharacterReplacement ReplacementCharacters { get; set; } public bool StripStopWords { get; set; } } }
namespace SlugityLib.Tests { public class CustomSlugityConfig : ISlugityConfig { public CustomSlugityConfig() { TextCase = TextCase.LowerCase; StripStopWords = false; MaxLength = 30; StringSeparator = ' '; ReplacementCharacters = new CharacterReplacement(); } public TextCase TextCase { get; set; } public char StringSeparator { get; set; } public int? MaxLength { get; set; } public CharacterReplacement ReplacementCharacters { get; set; } public bool StripStopWords { get; set; } } }
Fix error dialog close button not working
<div class="panel" id="error-panel"> <div class="panel-inner"> <div class="panel-close"> <a href="#" id="about-panel-close"><i class="fa fa-fw fa-times"></i></a> </div> <h1 id="error-title">Error!</h1> <p id="error-message"> Oh no! </p> </div> </div>
<div class="panel" id="error-panel"> <div class="panel-inner"> <div class="panel-close"> <a href="#" id="error-panel-close"><i class="fa fa-fw fa-times"></i></a> </div> <h1 id="error-title">Error!</h1> <p id="error-message"> <img src="http://i.imgur.com/ne6uoFj.png" style="margin-bottom: 10px; width: 100%;"/><br /> Uh, I can explain... </p> </div> </div>
Remove filter (default will work)
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using System.Web; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class ChristianHoejsager : IFilterMyBlogPosts, IAmACommunityMember { public string FirstName => "Christian"; public string LastName => "Hoejsager"; public string ShortBioOrTagLine => "Systems Administrator, author of scriptingchris.tech and automation enthusiast"; public string StateOrRegion => "Denmark"; public string EmailAddress => "christian@scriptingchris.tech"; public string TwitterHandle => "_ScriptingChris"; public string GitHubHandle => "ScriptingChris"; public string GravatarHash => "d406f408c17d8a42f431cd6f90b007b1"; public GeoPosition Position => new GeoPosition(55.709830, 9.536208); public Uri WebSite => new Uri("https://scriptingchris.tech/"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://scriptingchris.tech/feed"); } } public bool Filter(SyndicationItem item) { return item.Categories?.Any(c => c.Name.ToLowerInvariant().Contains("powershell")) ?? false; } public string FeedLanguageCode => "en"; } }
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using System.Web; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class ChristianHoejsager : IAmACommunityMember { public string FirstName => "Christian"; public string LastName => "Hoejsager"; public string ShortBioOrTagLine => "Systems Administrator, author of scriptingchris.tech and automation enthusiast"; public string StateOrRegion => "Denmark"; public string EmailAddress => "christian@scriptingchris.tech"; public string TwitterHandle => "_ScriptingChris"; public string GitHubHandle => "ScriptingChris"; public string GravatarHash => "d406f408c17d8a42f431cd6f90b007b1"; public GeoPosition Position => new GeoPosition(55.709830, 9.536208); public Uri WebSite => new Uri("https://scriptingchris.tech/"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://scriptingchris.tech/feed"); } } public string FeedLanguageCode => "en"; } }
Refactor to a thread-safe queue.
using System.Collections.Generic; using System.Linq; namespace SharpRaven.Utilities { public class CircularBuffer<T> { private readonly int size; private readonly Queue<T> queue; public CircularBuffer(int size = 100) { this.size = size; queue = new Queue<T>(); } public List<T> ToList() { return queue.ToList(); } public void Clear() { queue.Clear(); } public void Add(T item) { if (queue.Count >= size) queue.Dequeue(); queue.Enqueue(item); } public bool IsEmpty() { return queue.Count <= 0; } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; namespace SharpRaven.Utilities { public class CircularBuffer<T> { private readonly int size; private ConcurrentQueue<T> queue; public CircularBuffer(int size = 100) { this.size = size; queue = new ConcurrentQueue<T>(); } public List<T> ToList() { var listReturn = this.queue.ToList(); return listReturn.Skip(Math.Max(0, listReturn.Count - size)).ToList(); } public void Clear() { queue = new ConcurrentQueue<T>(); } public void Add(T item) { if (queue.Count >= size) { T result; this.queue.TryDequeue(out result); } queue.Enqueue(item); } public bool IsEmpty() { return queue.Count <= 0; } } }
Move using-statements within namespace declaration.
using System; using Nancy.Helpers; namespace Nancy.ViewEngines.Razor { /// <summary> /// An html string that is encoded. /// </summary> public class EncodedHtmlString : IHtmlString { /// <summary> /// Represents the empty <see cref="EncodedHtmlString"/>. This field is readonly. /// </summary> public static readonly EncodedHtmlString Empty = new EncodedHtmlString(string.Empty); private readonly Lazy<string> encoderFactory; /// <summary> /// Initializes a new instance of the <see cref="EncodedHtmlString"/> class. /// </summary> /// <param name="value">The value.</param> public EncodedHtmlString(string value) { encoderFactory = new Lazy<string>(() => HttpUtility.HtmlEncode(value)); } /// <summary> /// Returns an HTML-encoded string. /// </summary> /// <returns>An HTML-encoded string.</returns> public string ToHtmlString() { return encoderFactory.Value; } public static implicit operator EncodedHtmlString(string value) { return new EncodedHtmlString(value); } } }
namespace Nancy.ViewEngines.Razor { using System; using Nancy.Helpers; /// <summary> /// An html string that is encoded. /// </summary> public class EncodedHtmlString : IHtmlString { /// <summary> /// Represents the empty <see cref="EncodedHtmlString"/>. This field is readonly. /// </summary> public static readonly EncodedHtmlString Empty = new EncodedHtmlString(string.Empty); private readonly string encodedValue; /// <summary> /// Initializes a new instance of the <see cref="EncodedHtmlString"/> class. /// </summary> /// <param name="value">The encoded value.</param> public EncodedHtmlString(string value) { encodedValue = HttpUtility.HtmlEncode(value); } /// <summary> /// Returns an HTML-encoded string. /// </summary> /// <returns>An HTML-encoded string.</returns> public string ToHtmlString() { return encodedValue; } public static implicit operator EncodedHtmlString(string value) { return new EncodedHtmlString(value); } } }
Add case for locked files
using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading.Tasks; using Vipr.Core; namespace Vipr { internal static class FileWriter { public static async void WriteAsync(IEnumerable<TextFile> textFilesToWrite, string outputDirectoryPath = null) { if (!string.IsNullOrWhiteSpace(outputDirectoryPath) && !Directory.Exists(outputDirectoryPath)) Directory.CreateDirectory(outputDirectoryPath); var fileTasks = new List<Task>(); foreach (var file in textFilesToWrite) { var filePath = file.RelativePath; if (!string.IsNullOrWhiteSpace(outputDirectoryPath)) filePath = Path.Combine(outputDirectoryPath, filePath); if (!String.IsNullOrWhiteSpace(Environment.CurrentDirectory) && !Path.IsPathRooted(filePath)) filePath = Path.Combine(Environment.CurrentDirectory, filePath); if (!Directory.Exists(Path.GetDirectoryName(filePath))) Directory.CreateDirectory(Path.GetDirectoryName(filePath)); fileTasks.Add(WriteToDisk(filePath, file.Contents)); } await Task.WhenAll(fileTasks); } public static async Task WriteToDisk(string filePath, string output) { StreamWriter sw = new StreamWriter(filePath, false, Encoding.UTF8); await sw.WriteAsync(output); sw.Close(); } } }
using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading; using System.Threading.Tasks; using Vipr.Core; namespace Vipr { internal static class FileWriter { public static async void WriteAsync(IEnumerable<TextFile> textFilesToWrite, string outputDirectoryPath = null) { if (!string.IsNullOrWhiteSpace(outputDirectoryPath) && !Directory.Exists(outputDirectoryPath)) Directory.CreateDirectory(outputDirectoryPath); var fileTasks = new List<Task>(); foreach (var file in textFilesToWrite) { var filePath = file.RelativePath; if (!string.IsNullOrWhiteSpace(outputDirectoryPath)) filePath = Path.Combine(outputDirectoryPath, filePath); if (!String.IsNullOrWhiteSpace(Environment.CurrentDirectory) && !Path.IsPathRooted(filePath)) filePath = Path.Combine(Environment.CurrentDirectory, filePath); if (!Directory.Exists(Path.GetDirectoryName(filePath))) Directory.CreateDirectory(Path.GetDirectoryName(filePath)); fileTasks.Add(WriteToDisk(filePath, file.Contents)); } await Task.WhenAll(fileTasks); } /** * Write the file to disk. If the file is locked for editing, * sleep until available */ public static async Task WriteToDisk(string filePath, string output) { for (int tries = 0; tries < 10; tries++) { StreamWriter sw = null; try { using (sw = new StreamWriter(filePath, false, Encoding.UTF8)) { await sw.WriteAsync(output); break; } } // If the file is currently locked for editing, sleep // This shouldn't be hit if the generator is running correctly, // however, files are currently being overwritten several times catch (IOException) { Thread.Sleep(5); } } } } }
Tweak benchmarks, still don't trust the results.
namespace Gu.Analyzers.Benchmarks.Benchmarks { using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using BenchmarkDotNet.Attributes; using Microsoft.CodeAnalysis.Diagnostics; public abstract class Analyzer { private readonly CompilationWithAnalyzers compilation; protected Analyzer(DiagnosticAnalyzer analyzer) { var project = Factory.CreateProject(analyzer); this.compilation = project.GetCompilationAsync(CancellationToken.None) .Result .WithAnalyzers( ImmutableArray.Create(analyzer), project.AnalyzerOptions, CancellationToken.None); } [Benchmark] public async Task<object> GetAnalyzerDiagnosticsAsync() { return await this.compilation.GetAnalyzerDiagnosticsAsync(CancellationToken.None) .ConfigureAwait(false); } } }
namespace Gu.Analyzers.Benchmarks.Benchmarks { using System.Collections.Immutable; using System.Threading; using BenchmarkDotNet.Attributes; using Microsoft.CodeAnalysis.Diagnostics; public abstract class Analyzer { private readonly CompilationWithAnalyzers compilation; protected Analyzer(DiagnosticAnalyzer analyzer) { var project = Factory.CreateProject(analyzer); this.compilation = project.GetCompilationAsync(CancellationToken.None) .Result .WithAnalyzers( ImmutableArray.Create(analyzer), project.AnalyzerOptions, CancellationToken.None); } [Benchmark] public object GetAnalyzerDiagnosticsAsync() { return this.compilation.GetAnalyzerDiagnosticsAsync(CancellationToken.None).Result; } } }
Fix files encoding to UTF-8
namespace InfinniPlatform.Sdk.Hosting { /// <summary> /// . /// </summary> public interface IHostAddressParser { /// <summary> /// , . /// </summary> /// <param name="hostNameOrAddress"> .</param> /// <returns> <c>true</c>, ; <c>false</c>.</returns> bool IsLocalAddress(string hostNameOrAddress); /// <summary> /// , . /// </summary> /// <param name="hostNameOrAddress"> .</param> /// <param name="normalizedAddress"> .</param> /// <returns> <c>true</c>, ; <c>false</c>.</returns> bool IsLocalAddress(string hostNameOrAddress, out string normalizedAddress); } }
namespace InfinniPlatform.Sdk.Hosting { /// <summary> /// Интерфейс для разбора адресов узлов. /// </summary> public interface IHostAddressParser { /// <summary> /// Определяет, является ли адрес локальным. /// </summary> /// <param name="hostNameOrAddress">Имя узла или его адрес.</param> /// <returns>Возвращает <c>true</c>, если адрес является локальным; иначе возвращает <c>false</c>.</returns> bool IsLocalAddress(string hostNameOrAddress); /// <summary> /// Определяет, является ли адрес локальным. /// </summary> /// <param name="hostNameOrAddress">Имя узла или его адрес.</param> /// <param name="normalizedAddress">Нормализованный адрес узла.</param> /// <returns>Возвращает <c>true</c>, если адрес является локальным; иначе возвращает <c>false</c>.</returns> bool IsLocalAddress(string hostNameOrAddress, out string normalizedAddress); } }
Change LineNumber to nullable so it does not get serialized unless set
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; namespace Mindscape.Raygun4Net { public class RaygunBreadcrumb { public string Message { get; set; } public string Category { get; set; } public RaygunBreadcrumbs.Level Level { get; set; } = RaygunBreadcrumbs.Level.Info; public IDictionary CustomData { get; set; } public string ClassName { get; set; } public string MethodName { get; set; } public int LineNumber { get; set; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; namespace Mindscape.Raygun4Net { public class RaygunBreadcrumb { public string Message { get; set; } public string Category { get; set; } public RaygunBreadcrumbs.Level Level { get; set; } = RaygunBreadcrumbs.Level.Info; public IDictionary CustomData { get; set; } public string ClassName { get; set; } public string MethodName { get; set; } public int? LineNumber { get; set; } } }
Add help message to !alarmclock
using System.Collections; using System.Reflection; using Assets.Scripts.Props; using UnityEngine; public class AlarmClockHoldableHandler : HoldableHandler { public AlarmClockHoldableHandler(KMHoldableCommander commander, FloatingHoldable holdable, IRCConnection connection, CoroutineCanceller canceller) : base(commander, holdable, connection, canceller) { clock = Holdable.GetComponentInChildren<AlarmClock>(); } protected override IEnumerator RespondToCommandInternal(string command) { if ((TwitchPlaySettings.data.AllowSnoozeOnly && (!(bool) _alarmClockOnField.GetValue(clock)))) yield break; yield return null; yield return DoInteractionClick(clock.SnoozeButton); } static AlarmClockHoldableHandler() { _alarmClockOnField = typeof(AlarmClock).GetField("isOn", BindingFlags.NonPublic | BindingFlags.Instance); } private static FieldInfo _alarmClockOnField = null; private AlarmClock clock; }
using System.Collections; using System.Reflection; using Assets.Scripts.Props; using UnityEngine; public class AlarmClockHoldableHandler : HoldableHandler { public AlarmClockHoldableHandler(KMHoldableCommander commander, FloatingHoldable holdable, IRCConnection connection, CoroutineCanceller canceller) : base(commander, holdable, connection, canceller) { clock = Holdable.GetComponentInChildren<AlarmClock>(); HelpMessage = "Snooze the alarm clock with !{0} snooze"; HelpMessage += TwitchPlaySettings.data.AllowSnoozeOnly ? " (Current Twitch play settings forbids turning the Alarm clock back on.)" : " Alarm clock may also be turned back on with !{0} snooze"; } protected override IEnumerator RespondToCommandInternal(string command) { if ((TwitchPlaySettings.data.AllowSnoozeOnly && (!(bool) _alarmClockOnField.GetValue(clock)))) yield break; yield return null; yield return DoInteractionClick(clock.SnoozeButton); } static AlarmClockHoldableHandler() { _alarmClockOnField = typeof(AlarmClock).GetField("isOn", BindingFlags.NonPublic | BindingFlags.Instance); } private static FieldInfo _alarmClockOnField = null; private AlarmClock clock; }
Use Enum.Parse overload available in PCL
using System; namespace EvilDICOM.Core.Helpers { public class EnumHelper { public static T StringToEnum<T>(string name) { return (T) Enum.Parse(typeof (T), name); } } }
using System; namespace EvilDICOM.Core.Helpers { public class EnumHelper { public static T StringToEnum<T>(string name) { return (T) Enum.Parse(typeof (T), name, false); } } }
Tag release with updated version number.
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace MonoGameUtils.UI.GameComponents { /// <summary> /// Represents a rectangular button that can be clicked in a game. /// </summary> public class Button : DrawableGameComponent { public SpriteFont Font { get; set; } public Color TextColor { get; set; } public string Text { get; set; } public Rectangle Bounds { get; set; } public Color BackgroundColor { get; set; } private Texture2D ButtonTexture; private readonly SpriteBatch spriteBatch; public Button(Game game, SpriteFont font, Color textColor, string text, Rectangle bounds, Color backgroundColor, SpriteBatch spriteBatch) : base(game) { this.Font = font; this.TextColor = textColor; this.Text = text; this.Bounds = bounds; this.BackgroundColor = backgroundColor; this.spriteBatch = spriteBatch; } protected override void LoadContent() { this.ButtonTexture = new Texture2D(Game.GraphicsDevice, 1, 1); this.ButtonTexture.SetData<Color>(new Color[] { Color.White }); } public override void Draw(GameTime gameTime) { // Draw the button background. spriteBatch.Draw(ButtonTexture, Bounds, BackgroundColor); // Draw the button text. spriteBatch.DrawString(Font, Text, new Vector2(Bounds.X + 5, Bounds.Y + 5), TextColor); base.Draw(gameTime); } } }
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace MonoGameUtils.UI.GameComponents { /// <summary> /// Represents a rectangular button that can be clicked in a game. /// </summary> public class Button : DrawableGameComponent { public SpriteFont Font { get; set; } public Color TextColor { get; set; } public string Text { get; set; } public Rectangle Bounds { get; set; } public Color BackgroundColor { get; set; } private Texture2D ButtonTexture; private readonly SpriteBatch spriteBatch; public Button(Game game, SpriteFont font, Color textColor, string text, Rectangle bounds, Color backgroundColor, SpriteBatch spriteBatch) : base(game) { this.Font = font; this.TextColor = textColor; this.Text = text; this.Bounds = bounds; this.BackgroundColor = backgroundColor; this.spriteBatch = spriteBatch; } protected override void LoadContent() { this.ButtonTexture = new Texture2D(Game.GraphicsDevice, 1, 1); this.ButtonTexture.SetData<Color>(new Color[] { Color.White }); } public override void Draw(GameTime gameTime) { // Draw the button background. spriteBatch.Draw(ButtonTexture, Bounds, BackgroundColor); // Draw the button text. spriteBatch.DrawString(Font, Text, new Vector2(Bounds.X + 5, Bounds.Y + 5), TextColor); base.Draw(gameTime); } } }