using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Oberon0.Compiler.Definitions;
using Oberon0.Compiler.Solver;

namespace Oberon0.Compiler.Expressions.Arithmetic
{
    [Export(typeof(ICalculatable))]
    class SubExpression: BinaryExpression, ICalculatable
    {
        public SubExpression()
        {
            Operator = TokenType.Sub;
        }

        public override Expression Calc(Block block)
        {
            if (this.BinaryConstChecker(block) == null)
            {
                return null;
            }
            // 1. Easy as int
            var lhi = (ConstantExpression)LeftHandSide;
            var rhi = (ConstantExpression)RightHandSide;
            if (rhi.BaseType == lhi.BaseType && lhi.BaseType == BaseType.IntType)
            {
                return new ConstantIntExpression(lhi.ToInt32() - rhi.ToInt32());
            }
            // at least one of them is double
            return new ConstantDoubleExpression(lhi.ToDouble() - lhi.ToDouble());
        }
    }
}

using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Oberon0.Compiler.Definitions;
using Oberon0.Compiler.Solver;

namespace Oberon0.Compiler.Expressions.Arithmetic
{
    [Export(typeof(ICalculatable))]
    class SubExpression: BinaryExpression, ICalculatable
    {
        public SubExpression()
        {
            Operator = TokenType.Sub;
        }

        public override Expression Calc(Block block)
        {
            if (this.BinaryConstChecker(block) == null)
            {
                return null;
            }
            // 1. Easy as int
            var leftHandSide = (ConstantExpression)LeftHandSide;
            var rightHandSide = (ConstantExpression)RightHandSide;
            if (rightHandSide.BaseType == leftHandSide.BaseType && leftHandSide.BaseType == BaseType.IntType)
            {
                return new ConstantIntExpression(leftHandSide.ToInt32() - rightHandSide.ToInt32());
            }
            // at least one of them is double
            return new ConstantDoubleExpression(leftHandSide.ToDouble() - rightHandSide.ToDouble());
        }
    }
}

Fix sonarqube markup that sub has lhs and rhs identical


// 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 BenchmarkDotNet.Attributes;
using osu.Framework.Bindables;

namespace osu.Framework.Benchmarks
{
    public class BenchmarkBindableInstantiation
    {
        [Benchmark(Baseline = true)]
        public Bindable<int> GetBoundCopyOld() => new BindableOld<int>().GetBoundCopy();

        [Benchmark]
        public Bindable<int> GetBoundCopy() => new Bindable<int>().GetBoundCopy();

        private class BindableOld<T> : Bindable<T>
        {
            public BindableOld(T defaultValue = default)
                : base(defaultValue)
            {
            }

            protected override Bindable<T> CreateInstance() => (BindableOld<T>)Activator.CreateInstance(GetType(), 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;
using BenchmarkDotNet.Attributes;
using osu.Framework.Bindables;

namespace osu.Framework.Benchmarks
{
    [MemoryDiagnoser]
    public class BenchmarkBindableInstantiation
    {
        [Benchmark]
        public Bindable<int> Instantiate() => new Bindable<int>();

        [Benchmark]
        public Bindable<int> GetBoundCopy() => new Bindable<int>().GetBoundCopy();

        [Benchmark(Baseline = true)]
        public Bindable<int> GetBoundCopyOld() => new BindableOld<int>().GetBoundCopy();

        private class BindableOld<T> : Bindable<T>
        {
            public BindableOld(T defaultValue = default)
                : base(defaultValue)
            {
            }

            protected override Bindable<T> CreateInstance() => (BindableOld<T>)Activator.CreateInstance(GetType(), Value);
        }
    }
}

Add basic bindable instantiation benchmark


// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Linq;
using Microsoft.DotNet.Cli;
using Microsoft.DotNet.Cli.CommandLine;
using Microsoft.DotNet.Cli.Utils;
using Microsoft.DotNet.InternalAbstractions;
using Microsoft.DotNet.Tools;

namespace Microsoft.DotNet.Tools.NuGet
{
    public class NuGetCommand
    {
        public static int Run(string[] args)
        {
            return Run(args, new NuGetCommandRunner());
        }

        public static int Run(string[] args, ICommandRunner nugetCommandRunner)
        {
            DebugHelper.HandleDebugSwitch(ref args);

            if (nugetCommandRunner == null)
            {
                throw new ArgumentNullException(nameof(nugetCommandRunner));
            }

            return nugetCommandRunner.Run(args);
        }

        private class NuGetCommandRunner : ICommandRunner
        {
            public int Run(string[] args)
            {
                var nugetApp = new NuGetForwardingApp(args);

                return nugetApp.Execute();
            }
        }
    }
}

// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Linq;
using Microsoft.DotNet.Cli;
using Microsoft.DotNet.Cli.CommandLine;
using Microsoft.DotNet.Cli.Utils;
using Microsoft.DotNet.InternalAbstractions;
using Microsoft.DotNet.Tools;

namespace Microsoft.DotNet.Tools.NuGet
{
    public class NuGetCommand
    {
        public static int Run(string[] args)
        {
            return Run(args, new NuGetCommandRunner());
        }

        public static int Run(string[] args, ICommandRunner nugetCommandRunner)
        {
            DebugHelper.HandleDebugSwitch(ref args);

            if (nugetCommandRunner == null)
            {
                throw new ArgumentNullException(nameof(nugetCommandRunner));
            }

            return nugetCommandRunner.Run(args);
        }

        private class NuGetCommandRunner : ICommandRunner
        {
            public int Run(string[] args)
            {
                var nugetApp = new NuGetForwardingApp(args);
                nugetApp.WithEnvironmentVariable("DOTNET_HOST_PATH", GetDotnetPath());
                return nugetApp.Execute();
            }
        }

        private static string GetDotnetPath()
        {
            return new Muxer().MuxerPath;
        }
    }
}

Add DOTNET_HOST_PATH for dotnet nuget commands


using UnityEditor;
using UnityEngine;

namespace GitHub.Unity
{
    public class PublishWindow : EditorWindow
    {
        private const string PublishTitle = "Publish this repository to GitHub";
        private string repoName = "";
        private string repoDescription = "";
        private bool togglePrivate = false;

        static void Init()
        {
            PublishWindow window = (PublishWindow)EditorWindow.GetWindow(typeof(PublishWindow));
            window.Show();
        }

        void OnGUI()
        {
            GUILayout.Label(PublishTitle, EditorStyles.boldLabel);

            GUILayout.Space(5);

            repoName = EditorGUILayout.TextField("Name", repoName);
            repoDescription = EditorGUILayout.TextField("Description", repoDescription);

            GUILayout.BeginHorizontal();
            {
                GUILayout.FlexibleSpace();
                togglePrivate = GUILayout.Toggle(togglePrivate, "Keep my code private");
            }
            GUILayout.EndHorizontal();

            GUILayout.Space(5);

            GUILayout.BeginHorizontal();
            {
                GUILayout.FlexibleSpace();
                GUILayout.Button("Create");
            }
            GUILayout.EndHorizontal();
        }
    }
}

using UnityEditor;
using UnityEngine;

namespace GitHub.Unity
{
    public class PublishWindow : EditorWindow
    {
        private const string PublishTitle = "Publish this repository to GitHub";
        private string repoName = "";
        private string repoDescription = "";
        private int selectedOrg = 0;
        private bool togglePrivate = false;

        private string[] orgs = { "donokuda", "github", "donokudallc", "another-org" };

        static void Init()
        {
            PublishWindow window = (PublishWindow)EditorWindow.GetWindow(typeof(PublishWindow));
            window.Show();
        }

        void OnGUI()
        {
            GUILayout.Label(PublishTitle, EditorStyles.boldLabel);

            GUILayout.Space(5);

            repoName = EditorGUILayout.TextField("Name", repoName);
            repoDescription = EditorGUILayout.TextField("Description", repoDescription);

            GUILayout.BeginHorizontal();
            {
                GUILayout.FlexibleSpace();
                togglePrivate = GUILayout.Toggle(togglePrivate, "Keep my code private");
            }
            GUILayout.EndHorizontal();
            selectedOrg = EditorGUILayout.Popup("Organization", 0, orgs);

            GUILayout.Space(5);

            GUILayout.BeginHorizontal();
            {
                GUILayout.FlexibleSpace();
                GUILayout.Button("Create");
            }
            GUILayout.EndHorizontal();
        }
    }
}

Add a dropdown for selecting organizations


// 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.Linq;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Testing;
using osu.Game.Tournament.Components;
using osu.Game.Tournament.Screens.Gameplay;
using osu.Game.Tournament.Screens.Gameplay.Components;

namespace osu.Game.Tournament.Tests.Screens
{
    public class TestSceneGameplayScreen : TournamentTestScene
    {
        [Cached]
        private TournamentMatchChatDisplay chat = new TournamentMatchChatDisplay { Width = 0.5f };

        [BackgroundDependencyLoader]
        private void load()
        {
            Add(new GameplayScreen());
            Add(chat);
        }

        [Test]
        public void TestWarmup()
        {
            checkScoreVisibility(false);

            toggleWarmup();
            checkScoreVisibility(true);

            toggleWarmup();
            checkScoreVisibility(false);
        }

        private void checkScoreVisibility(bool visible)
            => AddUntilStep($"scores {(visible ? "shown" : "hidden")}",
                () => this.ChildrenOfType<TeamScore>().All(score => score.Alpha == (visible ? 1 : 0)));

        private void toggleWarmup()
            => AddStep("toggle warmup", () => this.ChildrenOfType<TourneyButton>().First().TriggerClick());
    }
}

// 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.Linq;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Testing;
using osu.Game.Tournament.Components;
using osu.Game.Tournament.IPC;
using osu.Game.Tournament.Screens.Gameplay;
using osu.Game.Tournament.Screens.Gameplay.Components;

namespace osu.Game.Tournament.Tests.Screens
{
    public class TestSceneGameplayScreen : TournamentTestScene
    {
        [Cached]
        private TournamentMatchChatDisplay chat = new TournamentMatchChatDisplay { Width = 0.5f };

        [Test]
        public void TestStartupState([Values] TourneyState state)
        {
            AddStep("set state", () => IPCInfo.State.Value = state);
            createScreen();
        }

        [Test]
        public void TestWarmup()
        {
            createScreen();

            checkScoreVisibility(false);

            toggleWarmup();
            checkScoreVisibility(true);

            toggleWarmup();
            checkScoreVisibility(false);
        }

        private void createScreen()
        {
            AddStep("setup screen", () =>
            {
                Remove(chat);

                Children = new Drawable[]
                {
                    new GameplayScreen(),
                    chat,
                };
            });
        }

        private void checkScoreVisibility(bool visible)
            => AddUntilStep($"scores {(visible ? "shown" : "hidden")}",
                () => this.ChildrenOfType<TeamScore>().All(score => score.Alpha == (visible ? 1 : 0)));

        private void toggleWarmup()
            => AddStep("toggle warmup", () => this.ChildrenOfType<TourneyButton>().First().TriggerClick());
    }
}

Add failing test coverage for tournament startup states


using System;
using System.IO;
using System.Text;
using Calamari.Deployment;
using Calamari.Integration.FileSystem;
using Octostache;

namespace Calamari.Integration.Substitutions
{
    public class FileSubstituter : IFileSubstituter
    {
        readonly ICalamariFileSystem fileSystem;

        public FileSubstituter(ICalamariFileSystem fileSystem)
        {
            this.fileSystem = fileSystem;
        }

        public void PerformSubstitution(string sourceFile, VariableDictionary variables)
        {
            PerformSubstitution(sourceFile, variables, sourceFile);
        }

        public void PerformSubstitution(string sourceFile, VariableDictionary variables, string targetFile)
        {
            var source = fileSystem.ReadFile(sourceFile);
            var encoding = GetEncoding(sourceFile, variables);
            var result = variables.Evaluate(source);
            fileSystem.OverwriteFile(targetFile, result, encoding);
        }

        private Encoding GetEncoding(string sourceFile, VariableDictionary variables)
        {
            var requestedEncoding = variables.Get(SpecialVariables.Package.SubstituteInFilesOutputEncoding);
            if (requestedEncoding == null)
            {
                return fileSystem.GetFileEncoding(sourceFile);
            }

            try
            {
                return Encoding.GetEncoding(requestedEncoding);
            }
            catch (ArgumentException)
            {
                return Encoding.GetEncoding(sourceFile);
            }

        }
    }
}

using System;
using System.IO;
using System.Text;
using Calamari.Deployment;
using Calamari.Integration.FileSystem;
using Octostache;

namespace Calamari.Integration.Substitutions
{
    public class FileSubstituter : IFileSubstituter
    {
        readonly ICalamariFileSystem fileSystem;

        public FileSubstituter(ICalamariFileSystem fileSystem)
        {
            this.fileSystem = fileSystem;
        }

        public void PerformSubstitution(string sourceFile, VariableDictionary variables)
        {
            PerformSubstitution(sourceFile, variables, sourceFile);
        }

        public void PerformSubstitution(string sourceFile, VariableDictionary variables, string targetFile)
        {
            var source = fileSystem.ReadFile(sourceFile);
            var encoding = GetEncoding(sourceFile, variables);
            var result = variables.Evaluate(source);
            fileSystem.OverwriteFile(targetFile, result, encoding);
        }

        private Encoding GetEncoding(string sourceFile, VariableDictionary variables)
        {
            var requestedEncoding = variables.Get(SpecialVariables.Package.SubstituteInFilesOutputEncoding);
            if (requestedEncoding == null)
            {
                return fileSystem.GetFileEncoding(sourceFile);
            }

            try
            {
                return Encoding.GetEncoding(requestedEncoding);
            }
            catch (ArgumentException)
            {
                return fileSystem.GetFileEncoding(sourceFile);
            }

        }
    }
}

Use existing file encoding if provided override is invalid


using System;
using System.Collections.Generic;
using System.Linq;

using NQuery.Binding;

namespace NQuery.Optimization
{
    internal static class Condition
    {
        public static BoundExpression And(BoundExpression left, BoundExpression right)
        {
            if (left == null)
                return right;

            if (right == null)
                return left;

            var result = BinaryOperator.Resolve(BinaryOperatorKind.LogicalAnd, left.Type, right.Type);
            return new BoundBinaryExpression(left, result, right);
        }

        public static BoundExpression And(IEnumerable<BoundExpression> conditions)
        {
            return conditions.Aggregate<BoundExpression, BoundExpression>(null, (c, n) => c == null ? n : And(c, n));
        }

        public static IEnumerable<BoundExpression> SplitConjunctions(BoundExpression expression)
        {
            var stack = new Stack<BoundExpression>();
            stack.Push(expression);

            while (stack.Count > 0)
            {
                var current = stack.Pop();
                var binary = current as BoundBinaryExpression;
                if (binary != null && binary.OperatorKind == BinaryOperatorKind.LogicalAnd)
                {
                    stack.Push(binary.Left);
                    stack.Push(binary.Right);
                }
                else
                {
                    yield return binary;
                }
            }
        }

        public static bool DependsOnAny(this BoundExpression expression, IEnumerable<ValueSlot> valueSlots)
        {
            var finder = new ValueSlotDependencyFinder();
            finder.VisitExpression(expression);
            return finder.ValueSlots.Overlaps(valueSlots);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;

using NQuery.Binding;

namespace NQuery.Optimization
{
    internal static class Condition
    {
        public static BoundExpression And(BoundExpression left, BoundExpression right)
        {
            if (left == null)
                return right;

            if (right == null)
                return left;

            var result = BinaryOperator.Resolve(BinaryOperatorKind.LogicalAnd, left.Type, right.Type);
            return new BoundBinaryExpression(left, result, right);
        }

        public static BoundExpression And(IEnumerable<BoundExpression> conditions)
        {
            return conditions.Aggregate<BoundExpression, BoundExpression>(null, (c, n) => c == null ? n : And(c, n));
        }

        public static IEnumerable<BoundExpression> SplitConjunctions(BoundExpression expression)
        {
            var stack = new Stack<BoundExpression>();
            stack.Push(expression);

            while (stack.Count > 0)
            {
                var current = stack.Pop();
                var binary = current as BoundBinaryExpression;
                if (binary != null && binary.OperatorKind == BinaryOperatorKind.LogicalAnd)
                {
                    stack.Push(binary.Left);
                    stack.Push(binary.Right);
                }
                else
                {
                    yield return current;
                }
            }
        }

        public static bool DependsOnAny(this BoundExpression expression, IEnumerable<ValueSlot> valueSlots)
        {
            var finder = new ValueSlotDependencyFinder();
            finder.VisitExpression(expression);
            return finder.ValueSlots.Overlaps(valueSlots);
        }
    }
}

Fix bug when splitting conjunctions

Fix bug when splitting conjunctions


using Cirrious.CrossCore.Core;
using System;
using System.Threading.Tasks;

namespace codestuffers.MvvmCrossPlugins.UserInteraction
{
    /// <summary>
    /// Helper class that executes a task with a progress bar
    /// </summary>
    public class ProgressHelper
    {
        private readonly IMvxMainThreadDispatcher _dispatcher;

        public ProgressHelper(IMvxMainThreadDispatcher dispatcher)
        {
            _dispatcher = dispatcher;
        }

        /// <summary>
        /// Setup the execution of the task with a progress indicator
        /// </summary>
        /// <typeparam name="T">Type of task return value</typeparam>
        /// <param name="task">Task that is executing</param>
        /// <param name="onCompletion">Action that will be executed when the task is complete</param>
        /// <param name="startProgressAction">Action that will show the progress indicator</param>
        /// <param name="stopProgressAction">Action that will hide the progress indicator</param>
        public void SetupTask<T>(Task<T> task, Action<Task<T>> onCompletion, Action startProgressAction, Action stopProgressAction)
        {
            _dispatcher.RequestMainThreadAction(startProgressAction);

            task.ContinueWith(x =>
            {
                onCompletion(task);

                _dispatcher.RequestMainThreadAction(stopProgressAction);
            });
        }
    }
}

using Cirrious.CrossCore.Core;
using System;
using System.Threading.Tasks;

namespace codestuffers.MvvmCrossPlugins.UserInteraction
{
    /// <summary>
    /// Helper class that executes a task with a progress bar
    /// </summary>
    public class ProgressHelper
    {
        private readonly IMvxMainThreadDispatcher _dispatcher;
        private int _progressIndicatorCount;

        public ProgressHelper(IMvxMainThreadDispatcher dispatcher)
        {
            _dispatcher = dispatcher;
        }

        /// <summary>
        /// Setup the execution of the task with a progress indicator
        /// </summary>
        /// <typeparam name="T">Type of task return value</typeparam>
        /// <param name="task">Task that is executing</param>
        /// <param name="onCompletion">Action that will be executed when the task is complete</param>
        /// <param name="startProgressAction">Action that will show the progress indicator</param>
        /// <param name="stopProgressAction">Action that will hide the progress indicator</param>
        public void SetupTask<T>(Task<T> task, Action<Task<T>> onCompletion, Action startProgressAction, Action stopProgressAction)
        {
            _progressIndicatorCount++;
            _dispatcher.RequestMainThreadAction(startProgressAction);

            task.ContinueWith(x =>
            {
                onCompletion(task);

                if (--_progressIndicatorCount == 0)
                {
                    _dispatcher.RequestMainThreadAction(stopProgressAction);
                }
            });
        }
    }
}

Modify progress helper so that activity indicator stops after last call ends


#region

using System.Windows;
using SteamAccountSwitcher.Properties;

#endregion

namespace SteamAccountSwitcher
{
    /// <summary>
    ///     Interaction logic for Options.xaml
    /// </summary>
    public partial class Options : Window
    {
        public Options()
        {
            InitializeComponent();
        }

        private void btnOK_Click(object sender, RoutedEventArgs e)
        {
            Settings.Default.Save();
            DialogResult = true;
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            Settings.Default.Reload();
            DialogResult = true;
        }
    }
}

#region

using System.Windows;
using SteamAccountSwitcher.Properties;

#endregion

namespace SteamAccountSwitcher
{
    /// <summary>
    ///     Interaction logic for Options.xaml
    /// </summary>
    public partial class Options : Window
    {
        public Options()
        {
            InitializeComponent();
            Settings.Default.Save();
        }

        private void btnOK_Click(object sender, RoutedEventArgs e)
        {
            Settings.Default.Save();
            DialogResult = true;
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            Settings.Default.Reload();
            DialogResult = true;
        }
    }
}

Fix settings not saving when opening "Options"


using GeneratorAPI;
using NUnit.Framework;
using NUnit.Framework.Internal;

namespace Tests.GeneratorAPI {
    [TestFixture]
    internal class GeneratorTests {
        [SetUp]
        public void Initiate() {
            _generator = new Generator<Randomizer>(new Randomizer(Seed));
        }

        [TearDown]
        public void Dispose() {
            _generator = null;
        }

        private Generator<Randomizer> _generator;
        private const int Seed = 100;

        [Test(
            Author = "Robert",
            Description = "Checks that the result from Generate is not null"
        )]
        public void Test() {
            var result = _generator.Generate(randomizer => randomizer.GetString());
            Assert.IsNotNull(result);
        }

        [Test(
            Author = "Robert",
            Description = "Checks that provider is assigned in the constructor."
        )]
        public void Test_Provider_Is_not_Null() {
            Assert.IsNotNull(_generator);
        }
    }
}

using System;
using GeneratorAPI;
using NUnit.Framework;
using NUnit.Framework.Internal;

namespace Tests.GeneratorAPI {
    [TestFixture]
    internal class GeneratorTests {
        [SetUp]
        public void Initiate() {
            _generator = new Generator<Randomizer>(new Randomizer(Seed));
        }

        [TearDown]
        public void Dispose() {
            _generator = null;
        }

        private Generator<Randomizer> _generator;
        private const int Seed = 100;

        [Test(
            Author = "Robert",
            Description = "Check that constructor throws exception if argument is null"
        )]
        public void Constructor_Null_Argument() {
            Assert.Throws<ArgumentNullException>(() => new Generator<Randomizer>(null));
        }

        [Test(
            Author = "Robert",
            Description = "Checks that the result from Generate is not null"
        )]
        public void Generate_Does_Not_Return_With_Valid_Arg() {
            var result = _generator.Generate(randomizer => randomizer.GetString());
            Assert.IsNotNull(result);
        }

        [Test(
            Author = "Robert",
            Description = "Checks that an exception is thrown when generate argument is null"
        )]
        public void Generate_With_Null() {
            Assert.Throws<ArgumentNullException>(() => _generator.Generate<string>(randomizer => null));
        }

        [Test(
            Author = "Robert",
            Description = "Checks that provider is assigned in the constructor."
        )]
        public void Provider_Is_not_Null() {
            var result = _generator.Provider;
            Assert.IsNotNull(result);
        }
    }
}

Add tests for null checking

Add tests for null checking

Former-commit-id: 093d57674ed09329af065f5df3615d2d2c511f8f


using System.Collections.Generic;
using System.Linq;
using Glimpse.Server.Internal;
using Glimpse.Internal.Extensions;
using Microsoft.AspNet.Http;
using Microsoft.Extensions.OptionsModel;

namespace Glimpse.Server.Configuration
{
    public class DefaultMetadataProvider : IMetadataProvider
    {
        private readonly IResourceManager _resourceManager;
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly GlimpseServerOptions _serverOptions;
        private Metadata _metadata;

        public DefaultMetadataProvider(IResourceManager resourceManager, IHttpContextAccessor httpContextAccessor, IOptions<GlimpseServerOptions> serverOptions)
        {
            _resourceManager = resourceManager;
            _httpContextAccessor = httpContextAccessor;
            _serverOptions = serverOptions.Value;
        }

        public Metadata BuildInstance()
        {
            if (_metadata != null)
                return _metadata;

            var request = _httpContextAccessor.HttpContext.Request;
            var baseUrl = $"{request.Scheme}://{request.Host}/{_serverOptions.BasePath}/";
            IDictionary<string, string> resources = _resourceManager.RegisteredUris.ToDictionary(kvp => kvp.Key.KebabCase(), kvp => $"{baseUrl}{kvp.Key}/{kvp.Value}");

            if (_serverOptions.OverrideResources != null)
                _serverOptions.OverrideResources(resources);

            return new Metadata(resources);
        }
    }
}

using System.Collections.Generic;
using System.Linq;
using Glimpse.Server.Internal;
using Glimpse.Internal.Extensions;
using Microsoft.AspNet.Http;
using Microsoft.Extensions.OptionsModel;

namespace Glimpse.Server.Configuration
{
    public class DefaultMetadataProvider : IMetadataProvider
    {
        private readonly IResourceManager _resourceManager;
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly GlimpseServerOptions _serverOptions;
        private Metadata _metadata;

        public DefaultMetadataProvider(IResourceManager resourceManager, IHttpContextAccessor httpContextAccessor, IOptions<GlimpseServerOptions> serverOptions)
        {
            _resourceManager = resourceManager;
            _httpContextAccessor = httpContextAccessor;
            _serverOptions = serverOptions.Value;
        }

        public Metadata BuildInstance()
        {
            if (_metadata != null)
                return _metadata;

            var request = _httpContextAccessor.HttpContext.Request;
            var baseUrl = $"{request.Scheme}://{request.Host}/{_serverOptions.BasePath}/";
            var resources = _resourceManager.RegisteredUris.ToDictionary(kvp => kvp.Key.KebabCase(), kvp => $"{baseUrl}{kvp.Key}/{kvp.Value}");

            if (_serverOptions.OverrideResources != null)
                _serverOptions.OverrideResources(resources);

            _metadata = new Metadata(resources);

            return _metadata;
        }
    }
}

Make sure metadata is set before being returned


using Xunit;
using Unity.SolrNetCloudIntegration;
using Unity;

namespace SolrNet.Cloud.Tests
{
    public class UnityTests
    {
        private IUnityContainer Setup() {
            return new SolrNetContainerConfiguration().ConfigureContainer(
                new FakeProvider(),
                new UnityContainer());
        }

        [Fact]
        public void ShouldResolveBasicOperationsFromStartupContainer()
        {
            Assert.NotNull(
                Setup().Resolve<ISolrBasicOperations<FakeEntity>>());
        }

        [Fact]
        public void ShouldResolveBasicReadOnlyOperationsFromStartupContainer()
        {
            Assert.NotNull(
                Setup().Resolve<ISolrBasicReadOnlyOperations<FakeEntity>>());
        }

        [Fact]
        public void ShouldResolveOperationsFromStartupContainer() {
            Assert.NotNull(
                Setup().Resolve<ISolrOperations<FakeEntity>>());
        }

        [Fact]
        public void ShouldResolveReadOnlyOperationsFromStartupContainer()
        {
            Assert.NotNull(
                Setup().Resolve<ISolrReadOnlyOperations<FakeEntity>>());
        }
    }
}

using Xunit;
using Unity.SolrNetCloudIntegration;
using Unity;

namespace SolrNet.Cloud.Tests
{
    public class UnityTests
    {
        private IUnityContainer Setup() {
            return new SolrNetContainerConfiguration().ConfigureContainer(
                new FakeProvider(),
                new UnityContainer());
        }

        [Fact]
        public void ShouldResolveBasicOperationsFromStartupContainer()
        {
            Assert.NotNull(
                Setup().Resolve<ISolrBasicOperations<FakeEntity>>());
        }

        [Fact]
        public void ShouldResolveBasicReadOnlyOperationsFromStartupContainer()
        {
            Assert.NotNull(
                Setup().Resolve<ISolrBasicReadOnlyOperations<FakeEntity>>());
        }

        [Fact]
        public void ShouldResolveOperationsFromStartupContainer() {
            Assert.NotNull(
                Setup().Resolve<ISolrOperations<FakeEntity>>());
        }

        [Fact]
        public void ShouldResolveReadOnlyOperationsFromStartupContainer()
        {
            Assert.NotNull(
                Setup().Resolve<ISolrReadOnlyOperations<FakeEntity>>());
        }

        [Fact]
        public void ShouldResolveIOperations ()
        {
            using (var container = new UnityContainer())
            {
                var cont = new Unity.SolrNetCloudIntegration.SolrNetContainerConfiguration().ConfigureContainer(new FakeProvider(), container);
                var obj = cont.Resolve<ISolrOperations<Camera>>();

            }
        }

        public class Camera
        {
            [Attributes.SolrField("Name")]
            public string Name { get; set; }

            [Attributes.SolrField("UID")]
            public int UID { get; set; }

            [Attributes.SolrField("id")]
            public string Id { get; set; }
        }
    }
}

Add test trying to recreate the issue

Add test trying to recreate the issue


using System;
using System.Collections.Generic;
using System.Linq;
using VersionOne.SDK.APIClient;

namespace VersionOne.ServerConnector {
    // TODO extract interface and inject into VersionOneProcessor
    internal class EntityFactory {
        private readonly IMetaModel metaModel;
        private readonly IServices services;
        private readonly IEnumerable<AttributeInfo> attributesToQuery;

        internal EntityFactory(IMetaModel metaModel, IServices services, IEnumerable<AttributeInfo> attributesToQuery) {
            this.metaModel = metaModel;
            this.services = services;
            this.attributesToQuery = attributesToQuery;
        }

        internal Asset Create(string assetTypeName, IEnumerable<AttributeValue> attributeValues) {
            var assetType = metaModel.GetAssetType(assetTypeName);
            var asset = services.New(assetType, Oid.Null);

            foreach (var attributeValue in attributeValues) {
                if(attributeValue is SingleAttributeValue) {
                    asset.SetAttributeValue(assetType.GetAttributeDefinition(attributeValue.Name), ((SingleAttributeValue)attributeValue).Value);
                } else if(attributeValue is MultipleAttributeValue) {
                    var values = ((MultipleAttributeValue) attributeValue).Values;
                    var attributeDefinition = assetType.GetAttributeDefinition(attributeValue.Name);

                    foreach (var value in values) {
                        asset.AddAttributeValue(attributeDefinition, value);
                    }

                } else {
                    throw new NotSupportedException("Unknown Attribute Value type.");
                }
            }

            foreach (var attributeInfo in attributesToQuery.Where(attributeInfo => attributeInfo.Prefix == assetTypeName)) {
                asset.EnsureAttribute(assetType.GetAttributeDefinition(attributeInfo.Attr));
            }

            services.Save(asset);
            return asset;
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using VersionOne.SDK.APIClient;

namespace VersionOne.ServerConnector {
    // TODO extract interface and inject into VersionOneProcessor
    internal class EntityFactory {
        private readonly IServices services;
        private readonly IEnumerable<AttributeInfo> attributesToQuery;

        internal EntityFactory(IServices services, IEnumerable<AttributeInfo> attributesToQuery) {
            this.services = services;
            this.attributesToQuery = attributesToQuery;
        }

        internal Asset Create(string assetTypeName, IEnumerable<AttributeValue> attributeValues) {
            var assetType = services.Meta.GetAssetType(assetTypeName);
            var asset = services.New(assetType, Oid.Null);

            foreach (var attributeValue in attributeValues) {
                if(attributeValue is SingleAttributeValue) {
                    asset.SetAttributeValue(assetType.GetAttributeDefinition(attributeValue.Name), ((SingleAttributeValue)attributeValue).Value);
                } else if(attributeValue is MultipleAttributeValue) {
                    var values = ((MultipleAttributeValue) attributeValue).Values;
                    var attributeDefinition = assetType.GetAttributeDefinition(attributeValue.Name);

                    foreach (var value in values) {
                        asset.AddAttributeValue(attributeDefinition, value);
                    }

                } else {
                    throw new NotSupportedException("Unknown Attribute Value type.");
                }
            }

            foreach (var attributeInfo in attributesToQuery.Where(attributeInfo => attributeInfo.Prefix == assetTypeName)) {
                asset.EnsureAttribute(assetType.GetAttributeDefinition(attributeInfo.Attr));
            }

            services.Save(asset);
            return asset;
        }
    }
}

S-54454: Use the new 15.0 SDK to access meta via IServices


// <copyright file="AssemblyInfoCommon.cs" company="natsnudasoft">
// Copyright (c) Adrian John Dunstan. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>

using System.Reflection;
using System.Resources;

[assembly: NeutralResourcesLanguage("en-GB")]
[assembly: AssemblyCompany("natsnudasoft")]
[assembly: AssemblyCopyright("Copyright © Adrian John Dunstan 2016")]

// Version is generated on the build server.
[assembly: AssemblyVersion("0.1.0.0")]
[assembly: AssemblyFileVersion("0.1.0.0")]
[assembly: AssemblyInformationalVersion("0.1.0.0")]

// <copyright file="AssemblyInfoCommon.cs" company="natsnudasoft">
// Copyright (c) Adrian John Dunstan. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>

using System.Reflection;
using System.Resources;

[assembly: NeutralResourcesLanguage("en-GB")]
[assembly: AssemblyCompany("natsnudasoft")]
[assembly: AssemblyCopyright("Copyright © Adrian John Dunstan 2016")]

// Version is generated on the build server.
#pragma warning disable MEN002 // Line is too long
[assembly: AssemblyVersion("0.1.0.0")]
[assembly: AssemblyFileVersion("0.1.0.0")]
[assembly: AssemblyInformationalVersion("0.1.0.0")]
#pragma warning restore MEN002 // Line is too long

Resolve line too long message on build server


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Newtonsoft.Json;

namespace Battlezeppelins.Models
{
    public class ZeppelinType
    {
        public static readonly ZeppelinType MOTHER = new ZeppelinType("Mother", 5);
        public static readonly ZeppelinType LEET = new ZeppelinType("Leet", 3);
        public static readonly ZeppelinType NIBBLET = new ZeppelinType("Nibblet", 2);

        public static IEnumerable<ZeppelinType> Values
        {
            get
            {
                yield return MOTHER;
                yield return LEET;
                yield return NIBBLET;
            }
        }

        public static ZeppelinType getByName(string name) {
            foreach (ZeppelinType type in Values)
            {
                if (type.name == name) return type;
            }
            return null;
        }

        [JsonProperty]
        public string name { get; private set; }
        [JsonProperty]
        public int length { get; private set; }

        private ZeppelinType() { }

        ZeppelinType(string name, int length)
        {
            this.name = name;
            this.length = length;
        }

        public override string ToString()
        {
            return name;
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Newtonsoft.Json;

namespace Battlezeppelins.Models
{
    public class ZeppelinType
    {
        public static readonly ZeppelinType MOTHER = new ZeppelinType("Mother", 5);
        public static readonly ZeppelinType LEET = new ZeppelinType("Leet", 3);
        public static readonly ZeppelinType NIBBLET = new ZeppelinType("Nibblet", 2);

        public static IEnumerable<ZeppelinType> Values
        {
            get
            {
                yield return MOTHER;
                yield return LEET;
                yield return NIBBLET;
            }
        }

        public static ZeppelinType getByName(string name) {
            foreach (ZeppelinType type in Values)
            {
                if (type.name == name) return type;
            }
            return null;
        }

        [JsonProperty]
        public string name { get; private set; }
        [JsonProperty]
        public int length { get; private set; }

        private ZeppelinType() { }

        ZeppelinType(string name, int length)
        {
            this.name = name;
            this.length = length;
        }

        public override string ToString()
        {
            return name;
        }

        public override bool Equals(object zeppelin) {
            return this == (ZeppelinType)zeppelin;
        }

        public static bool operator==(ZeppelinType z1, ZeppelinType z2)
        {
            return z1.name == z2.name;
        }

        public static bool operator !=(ZeppelinType z1, ZeppelinType z2)
        {
            return z1.name != z2.name;
        }
    }
}

Fix 'no multiple zeppelins of the same type' constraint server side.


// Copyright © 2010-2014 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Windows.Forms;
using CefSharp.Internals;

namespace CefSharp.BrowserSubprocess
{
    public class Program
    {
        public static int Main(string[] args)
        {
            Kernel32.OutputDebugString("BrowserSubprocess starting up with command line: " + String.Join("\n", args));

            int result;

            //MessageBox.Show("Please attach debugger now", null, MessageBoxButtons.OK, MessageBoxIcon.Information);

            var commandLineArgs = new List<string>(args)
            {
                "--renderer-startup-dialog"
            };

            using (var subprocess = Create(commandLineArgs.ToArray()))
            {
                //if (subprocess is CefRenderProcess)
                //{
                //    MessageBox.Show("Please attach debugger now", null, MessageBoxButtons.OK, MessageBoxIcon.Information);
                //}

                result = subprocess.Run();
            }

            Kernel32.OutputDebugString("BrowserSubprocess shutting down.");
            return result;
        }

        public static CefSubProcess Create(IEnumerable<string> args)
        {
            const string typePrefix = "--type=";
            var typeArgument = args.SingleOrDefault(arg => arg.StartsWith(typePrefix));

            var type = typeArgument.Substring(typePrefix.Length);

            switch (type)
            {
                case "renderer":
                    return new CefRenderProcess(args);
                case "gpu-process":
                    return new CefGpuProcess(args);
                default:
                    return new CefSubProcess(args);
            }
        }
    }
}

// Copyright © 2010-2014 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using CefSharp.Internals;

namespace CefSharp.BrowserSubprocess
{
    public class Program
    {
        public static int Main(string[] args)
        {
            Kernel32.OutputDebugString("BrowserSubprocess starting up with command line: " + String.Join("\n", args));

            int result;

            using (var subprocess = Create(args))
            {
                //if (subprocess is CefRenderProcess)
                //{
                //    MessageBox.Show("Please attach debugger now", null, MessageBoxButtons.OK, MessageBoxIcon.Information);
                //}

                result = subprocess.Run();
            }

            Kernel32.OutputDebugString("BrowserSubprocess shutting down.");
            return result;
        }

        public static CefSubProcess Create(IEnumerable<string> args)
        {
            const string typePrefix = "--type=";
            var typeArgument = args.SingleOrDefault(arg => arg.StartsWith(typePrefix));

            var type = typeArgument.Substring(typePrefix.Length);

            switch (type)
            {
                case "renderer":
                    return new CefRenderProcess(args);
                case "gpu-process":
                    return new CefGpuProcess(args);
                default:
                    return new CefSubProcess(args);
            }
        }
    }
}

Revert to previous debugging method as change wasn't working correctly.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Luval.Common
{
    public class ConsoleArguments
    {
        private List<string> _args;

        public ConsoleArguments(IEnumerable<string> args)
        {
            _args = new List<string>(args);
        }

        public bool ContainsSwitch(string name)
        {
            return _args.Contains(name);
        }

        public string GetSwitchValue(string name)
        {
            if (!ContainsSwitch(name)) return null;
            var switchIndex = _args.IndexOf(name);
            if (_args.Count < switchIndex + 1) return null;
            return _args[switchIndex + 1];
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Luval.Common
{
    public class ConsoleArguments
    {
        private List<string> _args;

        public ConsoleArguments(IEnumerable<string> args)
        {
            _args = new List<string>(args);
        }

        public bool ContainsSwitch(string name)
        {
            return _args.Contains(name);
        }

        public string GetSwitchValue(string name)
        {
            if (!ContainsSwitch(name)) return null;
            var switchIndex = _args.IndexOf(name);
            if ((_args.Count - 1) < switchIndex + 1) return null;
            return _args[switchIndex + 1];
        }
    }
}

Fix a bug with the console arguments class


using System;
using System.IO;

namespace MultiMiner.Utility
{
    public static class ApplicationPaths
    {
        public static string AppDataPath()
        {
            string rootPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            return Path.Combine(rootPath, "MultiMiner");
        }
    }
}

using System;
using System.IO;

namespace MultiMiner.Utility
{
    public static class ApplicationPaths
    {
        public static string AppDataPath()
        {
            //if running in "portable" mode
            if (IsRunningInPortableMode())
            {
                //store files in the working directory rather than AppData
                return GetWorkingDirectory();
            }
            else
            {
                string rootPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
                return Path.Combine(rootPath, "MultiMiner");
            }
        }

        //simply check for a file named "portable" in the same folder
        private static bool IsRunningInPortableMode()
        {
            string assemblyDirectory = GetWorkingDirectory();
            string portableFile = Path.Combine(assemblyDirectory, "portable");
            return File.Exists(portableFile);
        }

        private static string GetWorkingDirectory()
        {
            string assemblyFilePath = System.Reflection.Assembly.GetExecutingAssembly().Location;
            return Path.GetDirectoryName(assemblyFilePath);
        }
    }
}

Support for running the app in a "portable" mode


using System.Collections.Generic;
using System.IO;
using Wox.Plugin.Program.Programs;

namespace Wox.Plugin.Program
{
    public class Settings
    {
        public List<ProgramSource> ProgramSources { get; set; } = new List<ProgramSource>();
        public List<DisabledProgramSource> DisabledProgramSources { get; set; } = new List<DisabledProgramSource>();
        public string[] ProgramSuffixes { get; set; } = {"bat", "appref-ms", "exe", "lnk"};

        public bool EnableStartMenuSource { get; set; } = true;

        public bool EnableRegistrySource { get; set; } = true;

        internal const char SuffixSeperator = ';';

        /// <summary>
        /// Contains user added folder location contents as well as all user disabled applications
        /// </summary>
        /// <remarks>
        /// <para>Win32 class applications sets UniqueIdentifier using their full path</para>
        /// <para>UWP class applications sets UniqueIdentifier using their Application User Model ID</para>
        /// </remarks>
        public class ProgramSource
        {
            private string name;

            public string Location { get; set; }
            public string Name { get => name ?? new DirectoryInfo(Location).Name; set => name = value; }
            public bool Enabled { get; set; } = true;
            public string UniqueIdentifier { get; set; }
        }

        public class DisabledProgramSource
        {
            private string name;

            public string Location { get; set; }
            public string Name { get => name ?? new DirectoryInfo(Location).Name; set => name = value; }
            public bool Enabled { get; set; } = true;
            public string UniqueIdentifier { get; set; }
        }
    }
}

using System.Collections.Generic;
using System.IO;
using Wox.Plugin.Program.Programs;

namespace Wox.Plugin.Program
{
    public class Settings
    {
        public List<ProgramSource> ProgramSources { get; set; } = new List<ProgramSource>();
        public List<DisabledProgramSource> DisabledProgramSources { get; set; } = new List<DisabledProgramSource>();
        public string[] ProgramSuffixes { get; set; } = {"bat", "appref-ms", "exe", "lnk"};

        public bool EnableStartMenuSource { get; set; } = true;

        public bool EnableRegistrySource { get; set; } = true;

        internal const char SuffixSeperator = ';';

        /// <summary>
        /// Contains user added folder location contents as well as all user disabled applications
        /// </summary>
        /// <remarks>
        /// <para>Win32 class applications sets UniqueIdentifier using their full path</para>
        /// <para>UWP class applications sets UniqueIdentifier using their Application User Model ID</para>
        /// </remarks>
        public class ProgramSource
        {
            private string name;

            public string Location { get; set; }
            public string Name { get => name ?? new DirectoryInfo(Location).Name; set => name = value; }
            public bool Enabled { get; set; } = true;
            public string UniqueIdentifier { get; set; }
        }

        public class DisabledProgramSource : ProgramSource { }
    }
}

Change DisabledProgramSource class to inherit ProgramSource


namespace TAUtil.Gaf.Structures
{
    using System.IO;

    internal struct GafFrameData
    {
        public ushort Width;
        public ushort Height;
        public ushort XPos;
        public ushort YPos;
        public byte TransparencyIndex;
        public bool Compressed;
        public ushort FramePointers;
        public uint Unknown2;
        public uint PtrFrameData;
        public uint Unknown3;

        public static void Read(BinaryReader b, ref GafFrameData e)
        {
            e.Width = b.ReadUInt16();
            e.Height = b.ReadUInt16();
            e.XPos = b.ReadUInt16();
            e.YPos = b.ReadUInt16();
            e.TransparencyIndex = b.ReadByte();
            e.Compressed = b.ReadBoolean();
            e.FramePointers = b.ReadUInt16();
            e.Unknown2 = b.ReadUInt32();
            e.PtrFrameData = b.ReadUInt32();
            e.Unknown3 = b.ReadUInt32();
        }
    }
}

namespace TAUtil.Gaf.Structures
{
    using System.IO;

    internal struct GafFrameData
    {
        public ushort Width;
        public ushort Height;
        public short XPos;
        public short YPos;
        public byte TransparencyIndex;
        public bool Compressed;
        public ushort FramePointers;
        public uint Unknown2;
        public uint PtrFrameData;
        public uint Unknown3;

        public static void Read(BinaryReader b, ref GafFrameData e)
        {
            e.Width = b.ReadUInt16();
            e.Height = b.ReadUInt16();
            e.XPos = b.ReadInt16();
            e.YPos = b.ReadInt16();
            e.TransparencyIndex = b.ReadByte();
            e.Compressed = b.ReadBoolean();
            e.FramePointers = b.ReadUInt16();
            e.Unknown2 = b.ReadUInt32();
            e.PtrFrameData = b.ReadUInt32();
            e.Unknown3 = b.ReadUInt32();
        }
    }
}

Allow negative GAF frame offsets

Allow negative GAF frame offsets


namespace TAUtil.Gdi.Bitmap
{
    using System.Drawing;
    using System.Drawing.Imaging;
    using System.IO;

    using TAUtil.Gdi.Palette;

    /// <summary>
    /// Serializes a 32-bit Bitmap instance into raw 8-bit indexed color data.
    /// The mapping from color to index is done according to the given
    /// reverse palette lookup.
    /// </summary>
    public class BitmapSerializer
    {
        private readonly IPalette palette;

        public BitmapSerializer(IPalette palette)
        {
            this.palette = palette;
        }

        public byte[] ToBytes(Bitmap bitmap)
        {
            int length = bitmap.Width * bitmap.Height;

            byte[] output = new byte[length];

            this.Serialize(new MemoryStream(output, true), bitmap);

            return output;
        }

        public void Serialize(Stream output, Bitmap bitmap)
        {
            Rectangle r = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
            BitmapData data = bitmap.LockBits(r, ImageLockMode.ReadOnly, bitmap.PixelFormat);

            int length = bitmap.Width * bitmap.Height;

            unsafe
            {
                int* pointer = (int*)data.Scan0;
                for (int i = 0; i < length; i++)
                {
                    Color c = Color.FromArgb(pointer[i]);
                    output.WriteByte((byte)this.palette.LookUp(c));
                }
            }

            bitmap.UnlockBits(data);
        }
    }
}

namespace TAUtil.Gdi.Bitmap
{
    using System.Drawing;
    using System.Drawing.Imaging;
    using System.IO;

    using TAUtil.Gdi.Palette;

    /// <summary>
    /// Serializes a 32-bit Bitmap instance into raw 8-bit indexed color data.
    /// The mapping from color to index is done according to the given
    /// reverse palette lookup.
    /// </summary>
    public class BitmapSerializer
    {
        private readonly IPalette palette;

        public BitmapSerializer(IPalette palette)
        {
            this.palette = palette;
        }

        public byte[] ToBytes(Bitmap bitmap)
        {
            int length = bitmap.Width * bitmap.Height;

            byte[] output = new byte[length];

            this.Serialize(new MemoryStream(output, true), bitmap);

            return output;
        }

        public void Serialize(Stream output, Bitmap bitmap)
        {
            Rectangle r = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
            BitmapData data = bitmap.LockBits(r, ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);

            int length = bitmap.Width * bitmap.Height;

            unsafe
            {
                int* pointer = (int*)data.Scan0;
                for (int i = 0; i < length; i++)
                {
                    Color c = Color.FromArgb(pointer[i]);
                    output.WriteByte((byte)this.palette.LookUp(c));
                }
            }

            bitmap.UnlockBits(data);
        }
    }
}

Fix bitmap serialization with indexed format bitmaps


// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using NUnit.Framework;
using osu.Framework.Graphics;
using osu.Game.Screens.Play.PlayerSettings;
using osu.Game.Tests.Visual.Ranking;

namespace osu.Game.Tests.Visual.Gameplay
{
    public class TestSceneBeatmapOffsetControl : OsuTestScene
    {
        [Test]
        public void TestDisplay()
        {
            Child = new PlayerSettingsGroup("Some settings")
            {
                Anchor = Anchor.Centre,
                Origin = Anchor.Centre,
                Children = new Drawable[]
                {
                    new BeatmapOffsetControl(TestSceneHitEventTimingDistributionGraph.CreateDistributedHitEvents(-4.5))
                }
            };
        }
    }
}

// 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.Linq;
using NUnit.Framework;
using osu.Framework.Graphics;
using osu.Framework.Testing;
using osu.Game.Overlays.Settings;
using osu.Game.Scoring;
using osu.Game.Screens.Play.PlayerSettings;
using osu.Game.Tests.Visual.Ranking;

namespace osu.Game.Tests.Visual.Gameplay
{
    public class TestSceneBeatmapOffsetControl : OsuTestScene
    {
        private BeatmapOffsetControl offsetControl;

        [SetUpSteps]
        public void SetUpSteps()
        {
            AddStep("Create control", () =>
            {
                Child = new PlayerSettingsGroup("Some settings")
                {
                    Anchor = Anchor.Centre,
                    Origin = Anchor.Centre,
                    Children = new Drawable[]
                    {
                        offsetControl = new BeatmapOffsetControl()
                    }
                };
            });
        }

        [Test]
        public void TestDisplay()
        {
            const double average_error = -4.5;

            AddAssert("Offset is neutral", () => offsetControl.Current.Value == 0);
            AddAssert("No calibration button", () => !offsetControl.ChildrenOfType<SettingsButton>().Any());
            AddStep("Set reference score", () =>
            {
                offsetControl.ReferenceScore.Value = new ScoreInfo
                {
                    HitEvents = TestSceneHitEventTimingDistributionGraph.CreateDistributedHitEvents(average_error)
                };
            });

            AddAssert("Has calibration button", () => offsetControl.ChildrenOfType<SettingsButton>().Any());
            AddStep("Press button", () => offsetControl.ChildrenOfType<SettingsButton>().Single().TriggerClick());
            AddAssert("Offset is adjusted", () => offsetControl.Current.Value == average_error);

            AddStep("Remove reference score", () => offsetControl.ReferenceScore.Value = null);
            AddAssert("No calibration button", () => !offsetControl.ChildrenOfType<SettingsButton>().Any());
        }
    }
}

Add full testing flow for `BeatmapOffsetControl`


using System.Diagnostics;
using System.Windows.Input;
using DesktopWidgets.Classes;
using DesktopWidgets.Helpers;
using DesktopWidgets.ViewModelBase;
using GalaSoft.MvvmLight.Command;

namespace DesktopWidgets.Widgets.Search
{
    public class ViewModel : WidgetViewModelBase
    {
        private string _searchText;

        public ViewModel(WidgetId id) : base(id)
        {
            Settings = id.GetSettings() as Settings;
            if (Settings == null)
                return;
            Go = new RelayCommand(GoExecute);
            OnKeyUp = new RelayCommand<KeyEventArgs>(OnKeyUpExecute);
        }

        public Settings Settings { get; }

        public ICommand Go { get; set; }
        public ICommand OnKeyUp { get; set; }

        public string SearchText
        {
            get { return _searchText; }
            set
            {
                if (_searchText != value)
                {
                    _searchText = value;
                    RaisePropertyChanged(nameof(SearchText));
                }
            }
        }

        private void GoExecute()
        {
            var searchText = SearchText;
            SearchText = string.Empty;
            Process.Start($"{Settings.BaseUrl}{searchText}");
        }

        private void OnKeyUpExecute(KeyEventArgs args)
        {
            if (args.Key == Key.Enter)
                GoExecute();
        }
    }
}

using System.Diagnostics;
using System.Windows;
using System.Windows.Input;
using DesktopWidgets.Classes;
using DesktopWidgets.Helpers;
using DesktopWidgets.ViewModelBase;
using GalaSoft.MvvmLight.Command;

namespace DesktopWidgets.Widgets.Search
{
    public class ViewModel : WidgetViewModelBase
    {
        private string _searchText;

        public ViewModel(WidgetId id) : base(id)
        {
            Settings = id.GetSettings() as Settings;
            if (Settings == null)
                return;
            Go = new RelayCommand(GoExecute);
            OnKeyUp = new RelayCommand<KeyEventArgs>(OnKeyUpExecute);
        }

        public Settings Settings { get; }

        public ICommand Go { get; set; }
        public ICommand OnKeyUp { get; set; }

        public string SearchText
        {
            get { return _searchText; }
            set
            {
                if (_searchText != value)
                {
                    _searchText = value;
                    RaisePropertyChanged(nameof(SearchText));
                }
            }
        }

        private void GoExecute()
        {
            if (string.IsNullOrWhiteSpace(Settings.BaseUrl))
            {
                Popup.Show("You must setup a base url first.", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                return;
            }
            var searchText = SearchText;
            SearchText = string.Empty;
            Process.Start($"{Settings.BaseUrl}{searchText}");
        }

        private void OnKeyUpExecute(KeyEventArgs args)
        {
            if (args.Key == Key.Enter)
                GoExecute();
        }
    }
}

Add "Search" widget no base url warning

Add "Search" widget no base url warning


using System;
using System.ComponentModel;
using Newtonsoft.Json;
using Sendgrid.Webhooks.Converters;

namespace Sendgrid.Webhooks.Service
{
    public class WebhookCategoryConverter : GenericListCreationJsonConverter<String>
    {
    }
}

using System;
using System.ComponentModel;
using Newtonsoft.Json;
using Sendgrid.Webhooks.Converters;

namespace Sendgrid.Webhooks.Service
{
    public class WebhookCategoryConverter : GenericListCreationJsonConverter<string>
    {
    }
}

Use string instead of String

Use string instead of String


// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using osu.Framework.Platform;
using osu.Framework.Platform.Linux;
using osu.Framework.Platform.MacOS;
using osu.Framework.Platform.Windows;
using System;

namespace osu.Framework
{
    public static class Host
    {
        public static DesktopGameHost GetSuitableHost(string gameName, bool bindIPC = false, bool portableInstallation = false)
        {
            switch (RuntimeInfo.OS)
            {
                case RuntimeInfo.Platform.macOS:
                    return new MacOSGameHost(gameName, bindIPC);

                case RuntimeInfo.Platform.Linux:
                    return new LinuxGameHost(gameName, bindIPC);

                case RuntimeInfo.Platform.Windows:
                    return new WindowsGameHost(gameName, bindIPC);

                default:
                    throw new InvalidOperationException($"Could not find a suitable host for the selected operating system ({Enum.GetName(typeof(RuntimeInfo.Platform), RuntimeInfo.OS)}).");
            }
        }
    }
}

// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using osu.Framework.Platform;
using osu.Framework.Platform.Linux;
using osu.Framework.Platform.MacOS;
using osu.Framework.Platform.Windows;
using System;

namespace osu.Framework
{
    public static class Host
    {
        public static DesktopGameHost GetSuitableHost(string gameName, bool bindIPC = false, bool portableInstallation = false)
        {
            switch (RuntimeInfo.OS)
            {
                case RuntimeInfo.Platform.macOS:
                    return new MacOSGameHost(gameName, bindIPC, portableInstallation);

                case RuntimeInfo.Platform.Linux:
                    return new LinuxGameHost(gameName, bindIPC, portableInstallation);

                case RuntimeInfo.Platform.Windows:
                    return new WindowsGameHost(gameName, bindIPC, portableInstallation);

                default:
                    throw new InvalidOperationException($"Could not find a suitable host for the selected operating system ({Enum.GetName(typeof(RuntimeInfo.Platform), RuntimeInfo.OS)}).");
            }
        }
    }
}

Add back incorrectly removed parameter

Add back incorrectly removed parameter


using CertiPay.PDF;
using Nancy;
using Nancy.TinyIoc;
using System;
using System.Configuration;

namespace CertiPay.Services.PDF
{
    public class Bootstrapper : DefaultNancyBootstrapper
    {
        private static String ABCPdfLicense
        {
            get { return ConfigurationManager.AppSettings["ABCPDF-License"]; }
        }

        protected override void ConfigureApplicationContainer(TinyIoCContainer container)
        {
            container.Register<IPDFService>(new PDFService(ABCPdfLicense));
        }
    }
}

using CertiPay.PDF;
using Nancy;
using Nancy.TinyIoc;
using System;
using System.Configuration;

namespace CertiPay.Services.PDF
{
    public class Bootstrapper : DefaultNancyBootstrapper
    {
        private static String ABCPdfLicense
        {
            get
            {
                // Check the environment variables for the license key

                String key = "ABCPDF-License";

                if (!String.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable(key, EnvironmentVariableTarget.User)))
                {
                    return Environment.GetEnvironmentVariable(key, EnvironmentVariableTarget.User);
                }

                return ConfigurationManager.AppSettings[key];
            }
        }

        protected override void ConfigureApplicationContainer(TinyIoCContainer container)
        {
            container.Register<IPDFService>(new PDFService(ABCPdfLicense));
        }
    }
}

Check the environment variable for the license key


// This file was auto-generated based on version 1.0.0 of the canonical data.

using Xunit;

public class PrimeFactorsTest
{
    [Fact]
    public void No_factors()
    {
        Assert.Empty(PrimeFactors.Factors(1));
    }

    [Fact]
    public void Prime_number()
    {
        Assert.Equal(new[] { 2 }, PrimeFactors.Factors(2));
    }

    [Fact]
    public void Square_of_a_prime()
    {
        Assert.Equal(new[] { 3, 3 }, PrimeFactors.Factors(9));
    }

    [Fact]
    public void Cube_of_a_prime()
    {
        Assert.Equal(new[] { 2, 2, 2 }, PrimeFactors.Factors(8));
    }

    [Fact]
    public void Product_of_primes_and_non_primes()
    {
        Assert.Equal(new[] { 2, 2, 3 }, PrimeFactors.Factors(12));
    }

    [Fact]
    public void Product_of_primes()
    {
        Assert.Equal(new[] { 5, 17, 23, 461 }, PrimeFactors.Factors(901255));
    }

    [Fact]
    public void Factors_include_a_large_prime()
    {
        Assert.Equal(new[] { 11, 9539, 894119 }, PrimeFactors.Factors(93819012551));
    }
}

// This file was auto-generated based on version 1.0.0 of the canonical data.

using Xunit;

public class PrimeFactorsTest
{
    [Fact]
    public void No_factors()
    {
        Assert.Empty(PrimeFactors.Factors(1));
    }

    [Fact(Skip = "Remove to run test")]
    public void Prime_number()
    {
        Assert.Equal(new[] { 2 }, PrimeFactors.Factors(2));
    }

    [Fact(Skip = "Remove to run test")]
    public void Square_of_a_prime()
    {
        Assert.Equal(new[] { 3, 3 }, PrimeFactors.Factors(9));
    }

    [Fact(Skip = "Remove to run test")]
    public void Cube_of_a_prime()
    {
        Assert.Equal(new[] { 2, 2, 2 }, PrimeFactors.Factors(8));
    }

    [Fact(Skip = "Remove to run test")]
    public void Product_of_primes_and_non_primes()
    {
        Assert.Equal(new[] { 2, 2, 3 }, PrimeFactors.Factors(12));
    }

    [Fact(Skip = "Remove to run test")]
    public void Product_of_primes()
    {
        Assert.Equal(new[] { 5, 17, 23, 461 }, PrimeFactors.Factors(901255));
    }

    [Fact(Skip = "Remove to run test")]
    public void Factors_include_a_large_prime()
    {
        Assert.Equal(new[] { 11, 9539, 894119 }, PrimeFactors.Factors(93819012551));
    }
}

Add skips to prime factors test suite

Add skips to prime factors test suite


using HolzShots.Net.Custom;
using Xunit;

namespace HolzShots.Core.Tests.Net.Custom
{
    public class CustomUploaderLoaderTests
    {
        [Theory]
        [FileStringContentData("Files/DirectUpload.net.hsjson")]
        [FileStringContentData("Files/FotosHochladen.hsjson")]
        public void ValidateTest(string content)
        {
            var parseResult = CustomUploader.TryParse(content, out var result);
            Assert.True(parseResult);
            Assert.NotNull(result);
            Assert.NotNull(result.CustomData);
            Assert.NotNull(result.CustomData.Info);
            Assert.NotNull(result.CustomData.Uploader);
            Assert.NotNull(result.CustomData.SchemaVersion);
        }
    }
}

using HolzShots.Net.Custom;
using Xunit;

namespace HolzShots.Core.Tests.Net.Custom
{
    public class CustomUploaderLoaderTests
    {
        [Theory]
        [FileStringContentData("Files/DirectUpload.net.hsjson")]
        [FileStringContentData("Files/FotosHochladen.hsjson")]
        public void ValidateTest(string content)
        {
            var parseResult = CustomUploader.TryParse(content, out var result);
            Assert.True(parseResult);
            Assert.NotNull(result);
            Assert.NotNull(result.CustomData);
            Assert.NotNull(result.CustomData.Info);
            Assert.NotNull(result.CustomData.Uploader);
            Assert.NotNull(result.CustomData.SchemaVersion);

            Assert.True(result.CustomData.Info.Version == new Semver.SemVersion(1, 0, 0));
        }
    }
}

Add Test for SemVer Parsing

Add Test for SemVer Parsing


// 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.Diagnostics;
using osu.Framework.Utils;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Scoring;

namespace osu.Game.Rulesets.Osu.Tests
{
    public class TestSceneShaking : TestSceneHitCircle
    {
        protected override TestDrawableHitCircle CreateDrawableHitCircle(HitCircle circle, bool auto)
        {
            var drawableHitObject = base.CreateDrawableHitCircle(circle, auto);

            Debug.Assert(drawableHitObject.HitObject.HitWindows != null);

            double delay = drawableHitObject.HitObject.StartTime - (drawableHitObject.HitObject.HitWindows.WindowFor(HitResult.Miss) + RNG.Next(0, 300)) - Time.Current;
            Scheduler.AddDelayed(() => drawableHitObject.TriggerJudgement(), delay);

            return drawableHitObject;
        }
    }
}

// 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.Collections.Generic;
using System.Diagnostics;
using osu.Framework.Threading;
using osu.Framework.Utils;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Scoring;

namespace osu.Game.Rulesets.Osu.Tests
{
    public class TestSceneShaking : TestSceneHitCircle
    {
        private readonly List<ScheduledDelegate> scheduledTasks = new List<ScheduledDelegate>();

        protected override IBeatmap CreateBeatmapForSkinProvider()
        {
            // best way to run cleanup before a new step is run
            foreach (var task in scheduledTasks)
                task.Cancel();

            scheduledTasks.Clear();

            return base.CreateBeatmapForSkinProvider();
        }

        protected override TestDrawableHitCircle CreateDrawableHitCircle(HitCircle circle, bool auto)
        {
            var drawableHitObject = base.CreateDrawableHitCircle(circle, auto);

            Debug.Assert(drawableHitObject.HitObject.HitWindows != null);

            double delay = drawableHitObject.HitObject.StartTime - (drawableHitObject.HitObject.HitWindows.WindowFor(HitResult.Miss) + RNG.Next(0, 300)) - Time.Current;
            scheduledTasks.Add(Scheduler.AddDelayed(() => drawableHitObject.TriggerJudgement(), delay));

            return drawableHitObject;
        }
    }
}

Fix scheduled tasks not being cleaned up between test steps


using System;
using System.Net.Sockets;
using System.Net;
using System.Threading;

namespace NDeproxy
{
    public static class SocketHelper
    {
        static readonly Logger log = new Logger("SocketHelper");

        public static Socket Server(int port, int listenQueue=5)
        {
            var s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            s.Bind(new IPEndPoint(IPAddress.Any, port));
            s.Listen(listenQueue);
            return s;
        }

        public static Socket Client(string remoteHost, int port)
        {
            var s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            s.Connect(remoteHost, port);
            return s;
        }

        public static int GetLocalPort(this Socket socket)
        {
            return ((IPEndPoint)socket.LocalEndPoint).Port;
        }

        public static int GetRemotePort(this Socket socket)
        {
            return ((IPEndPoint)socket.RemoteEndPoint).Port;
        }
    }
}

using System;
using System.Net.Sockets;
using System.Net;
using System.Threading;

namespace NDeproxy
{
    public static class SocketHelper
    {
        static readonly Logger log = new Logger("SocketHelper");

        public static Socket Server(int port, int listenQueue=5)
        {
            var s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            s.Bind(new IPEndPoint(IPAddress.Any, port));
            s.Listen(listenQueue);
            return s;
        }

        public static Socket Client(string remoteHost, int port, int timeout=Timeout.Infinite)
        {
            var s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            if (timeout == Timeout.Infinite)
            {
                s.Connect(remoteHost, port);
                return s;
            }
            else
            {
                var result = s.BeginConnect(remoteHost, port, (_result) => { s.EndConnect(_result); }, s);

                if (result.AsyncWaitHandle.WaitOne(timeout))
                {
                    return s;
                }
                else
                {
                    throw new SocketException((int)SocketError.TimedOut);
                }
            }
        }

        public static int GetLocalPort(this Socket socket)
        {
            return ((IPEndPoint)socket.LocalEndPoint).Port;
        }

        public static int GetRemotePort(this Socket socket)
        {
            return ((IPEndPoint)socket.RemoteEndPoint).Port;
        }
    }
}

Add an optional timeout for connection attempts.


// Copyright (c) Alexandre Mutel. All rights reserved.
// This file is licensed under the BSD-Clause 2 license.
// See the license.txt file in the project root for more information.

using System.Collections.Generic;

namespace Lunet.Core
{
    /// <summary>
    /// Manages the meta information associated to a site (from the `_meta` directory and `.lunet` directory)
    /// </summary>
    /// <seealso cref="ManagerBase" />
    public class MetaManager : ManagerBase
    {
        public const string MetaDirectoryName = "_meta";

        /// <summary>
        /// Initializes a new instance of the <see cref="MetaManager"/> class.
        /// </summary>
        /// <param name="site">The site.</param>
        public MetaManager(SiteObject site) : base(site)
        {
            Directory = Site.BaseDirectory.GetSubFolder(MetaDirectoryName);
            PrivateDirectory = Site.PrivateBaseDirectory.GetSubFolder(MetaDirectoryName);
        }

        public FolderInfo Directory { get; }

        public FolderInfo PrivateDirectory { get; }

        public IEnumerable<FolderInfo> Directories
        {
            get
            {
                yield return Directory;

                foreach (var theme in Site.Extends.CurrentList)
                {
                    yield return theme.Directory.GetSubFolder(MetaDirectoryName);
                }
            }
        }
    }
}

// Copyright (c) Alexandre Mutel. All rights reserved.
// This file is licensed under the BSD-Clause 2 license.
// See the license.txt file in the project root for more information.

using System.Collections.Generic;
using System.IO;
using System.Reflection;

namespace Lunet.Core
{
    /// <summary>
    /// Manages the meta information associated to a site (from the `_meta` directory and `.lunet` directory)
    /// </summary>
    /// <seealso cref="ManagerBase" />
    public class MetaManager : ManagerBase
    {
        public const string MetaDirectoryName = "_meta";

        /// <summary>
        /// Initializes a new instance of the <see cref="MetaManager"/> class.
        /// </summary>
        /// <param name="site">The site.</param>
        public MetaManager(SiteObject site) : base(site)
        {
            Directory = Site.BaseDirectory.GetSubFolder(MetaDirectoryName);
            PrivateDirectory = Site.PrivateBaseDirectory.GetSubFolder(MetaDirectoryName);
            BuiltinDirectory = Path.GetDirectoryName(typeof(MetaManager).GetTypeInfo().Assembly.Location);
        }

        public FolderInfo Directory { get; }

        public FolderInfo BuiltinDirectory { get; }

        public FolderInfo PrivateDirectory { get; }

        public IEnumerable<FolderInfo> Directories
        {
            get
            {
                yield return Directory;

                foreach (var theme in Site.Extends.CurrentList)
                {
                    yield return theme.Directory.GetSubFolder(MetaDirectoryName);
                }

                // Last one is the builtin directory
                yield return new DirectoryInfo(Path.Combine(BuiltinDirectory, MetaDirectoryName));
            }
        }
    }
}

Add support for builtins directory from the assembly folder/_meta


using System;
using System.IO;
using System.Collections.Generic;
using System.Threading.Tasks;

using Owin;

namespace Connect.Owin.Examples.Hello
{
    // OWIN application delegate
    using AppFunc = Func<IDictionary<string, object>, Task>;

    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.Use(new Func<AppFunc, AppFunc>(next => async env =>
                {
                    env["owin.ResponseStatusCode"] = 200;
                    ((IDictionary<string, string[]>)env["owin.ResponseHeaders"]).Add(
                        "Content-Type", new string[] { "text/html" });
                    StreamWriter w = new StreamWriter((Stream)env["owin.ResponseBody"]);
                    w.Write("Hello, from C#. Time on server is " + DateTime.Now.ToString());
                    await w.FlushAsync();
                }));
        }
    }
}

using System;
using System.IO;
using System.Collections.Generic;
using System.Threading.Tasks;

using Owin;

namespace Connect.Owin.Examples.Hello
{
    // OWIN application delegate
    using AppFunc = Func<IDictionary<string, object>, Task>;

    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.Use(new Func<AppFunc, AppFunc>(next => async env =>
                {
                    env["owin.ResponseStatusCode"] = 200;
                    ((IDictionary<string, string[]>)env["owin.ResponseHeaders"]).Add(
                        "Content-Length", new string[] { "53" });
                    ((IDictionary<string, string[]>)env["owin.ResponseHeaders"]).Add(
                        "Content-Type", new string[] { "text/html" });
                    StreamWriter w = new StreamWriter((Stream)env["owin.ResponseBody"]);
                    w.Write("Hello, from C#. Time on server is " + DateTime.Now.ToString());
                    await w.FlushAsync();
                }));
        }
    }
}

Set `Content-Length` in the `hello` sample


using System;
using System.Data;
using Dapper.FastCrud;

namespace Smooth.IoC.Dapper.Repository.UnitOfWork.Data
{
    public class UnitOfWork : DbTransaction, IUnitOfWork
    {
        public SqlDialect SqlDialect { get; set; }
        private readonly Guid _guid = Guid.NewGuid();

        public UnitOfWork(IDbFactory factory, ISession session, IsolationLevel isolationLevel = IsolationLevel.Serializable) : base(factory)
        {
            Transaction = session.BeginTransaction(isolationLevel);
        }

        protected bool Equals(UnitOfWork other)
        {
            return _guid.Equals(other._guid);
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            if (ReferenceEquals(this, obj)) return true;
            if (obj.GetType() != this.GetType()) return false;
            return Equals((UnitOfWork) obj);
        }

        public override int GetHashCode()
        {
            return _guid.GetHashCode();
        }

        public static bool operator ==(UnitOfWork left, UnitOfWork right)
        {
            return Equals(left, right);
        }

        public static bool operator !=(UnitOfWork left, UnitOfWork right)
        {
            return !Equals(left, right);
        }
    }
}

using System;
using System.Data;
using Dapper.FastCrud;

namespace Smooth.IoC.Dapper.Repository.UnitOfWork.Data
{
    public class UnitOfWork : DbTransaction, IUnitOfWork
    {
        public SqlDialect SqlDialect { get; set; }
        private readonly Guid _guid = Guid.NewGuid();

        public UnitOfWork(IDbFactory factory, ISession session,
            IsolationLevel isolationLevel = IsolationLevel.Serializable, bool sessionOnlyForThisUnitOfWork = false) : base(factory)
        {
            if (sessionOnlyForThisUnitOfWork)
            {
                Session = session;
            }
            Transaction = session.BeginTransaction(isolationLevel);
        }

        protected bool Equals(UnitOfWork other)
        {
            return _guid.Equals(other._guid);
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            if (ReferenceEquals(this, obj)) return true;
            if (obj.GetType() != this.GetType()) return false;
            return Equals((UnitOfWork) obj);
        }

        public override int GetHashCode()
        {
            return _guid.GetHashCode();
        }

        public static bool operator ==(UnitOfWork left, UnitOfWork right)
        {
            return Equals(left, right);
        }

        public static bool operator !=(UnitOfWork left, UnitOfWork right)
        {
            return !Equals(left, right);
        }
    }
}

Add boolean to figure out is the uow is made with the session


// Copyright © 2010-2014 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.

using System.ServiceModel;

namespace CefSharp.Internals
{
    [ServiceContract(CallbackContract = typeof(IRenderProcess), SessionMode = SessionMode.Required)]
    public interface IBrowserProcess
    {
        [OperationContract]
        BrowserProcessResponse CallMethod(long objectId, string name, object[] parameters);

        [OperationContract]
        BrowserProcessResponse GetProperty(long objectId, string name);

        [OperationContract]
        BrowserProcessResponse SetProperty(long objectId, string name, object value);

        [OperationContract]
        JavascriptRootObject GetRegisteredJavascriptObjects();

        [OperationContract]
        void Connect();
    }
}

// Copyright © 2010-2014 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.

using System.Collections.Generic;
using System.ServiceModel;

namespace CefSharp.Internals
{
    [ServiceContract(CallbackContract = typeof(IRenderProcess), SessionMode = SessionMode.Required)]
    [ServiceKnownType(typeof(object[]))]
    [ServiceKnownType(typeof(Dictionary<string, object>))]
    public interface IBrowserProcess
    {
        [OperationContract]
        BrowserProcessResponse CallMethod(long objectId, string name, object[] parameters);

        [OperationContract]
        BrowserProcessResponse GetProperty(long objectId, string name);

        [OperationContract]
        BrowserProcessResponse SetProperty(long objectId, string name, object value);

        [OperationContract]
        JavascriptRootObject GetRegisteredJavascriptObjects();

        [OperationContract]
        void Connect();
    }
}

Add service ServiceKnownTypes for object[] and Dictionary<string, object> so that basic arrays can be passed two and from functions


using System;
using engine.core;

namespace engine.rules
{
    public class PercentageDiscount : Rule
    {
        private readonly string m_ApplicableItemName;
        private readonly double m_Percentage;

        public PercentageDiscount(string applicableItemName, int percentage)
        {
            m_ApplicableItemName = applicableItemName;
            m_Percentage = percentage;
        }

        public override Basket Apply(Basket basket)
        {
            var discountedBasket = new Basket();

            foreach (var item in basket)
            {
                discountedBasket.Add(item);

                if (item.Name.Equals(m_ApplicableItemName) && !item.UsedInOffer)
                {
                    var discountToApply =  -(int) Math.Ceiling(item.Price * m_Percentage / 100);
                    discountedBasket.Add(string.Format("{0}:{1}% discount", m_ApplicableItemName, m_Percentage), discountToApply);
                }
            }

            return discountedBasket;
        }
    }
}

using System;
using engine.core;

namespace engine.rules
{
    public class PercentageDiscount : Rule
    {
        private readonly string m_ApplicableItemName;
        private readonly double m_Percentage;

        public PercentageDiscount(string applicableItemName, int percentage)
        {
            m_ApplicableItemName = applicableItemName;
            m_Percentage = percentage;
        }

        public override Basket Apply(Basket basket)
        {
            var discountedBasket = new Basket();

            foreach (var item in basket)
            {
                discountedBasket.Add(item);

                if (item.Name.Equals(m_ApplicableItemName) && !item.UsedInOffer)
                {
                    var discountToApply =  Math.Ceiling(item.Price * m_Percentage / 100);
                    discountedBasket.Add(string.Format("{0}:{1}% discount", m_ApplicableItemName, m_Percentage), (int) -discountToApply);
                }
            }

            return discountedBasket;
        }
    }
}

Tidy up sum a bit by moving where we cast and negate to the line below.


using WampSharp.Binding;
using WampSharp.V2.Binding;
using WampSharp.V2.Client;
using WampSharp.WebSocket4Net;

namespace WampSharp.V2
{
    public class DefaultWampChannelFactory : WampChannelFactory
    {
        public IWampChannel CreateChannel<TMessage>(string address,
                                                    string realm,
                                                    IWampTextBinding<TMessage> binding)
        {
            var connection =
                new WebSocket4NetTextConnection<TMessage>(address, binding);

            return this.CreateChannel(realm, connection, binding);
        }

        public IWampChannel CreateChannel<TMessage>(string address,
                                                    string realm,
                                                    IWampBinaryBinding<TMessage> binding)
        {
            var connection =
                new WebSocket4NetBinaryConnection<TMessage>(address, binding);

            return this.CreateChannel(realm, connection, binding);
        }

        public IWampChannel CreateJsonChannel(string address,
                                              string realm)
        {
            JTokenBinding binding = new JTokenBinding();

            return this.CreateChannel(address, realm, binding);
        }

        public IWampChannel CreateMsgpackChannel(string address,
                                                 string realm)
        {
            MessagePackObjectBinding binding = new MessagePackObjectBinding();

            return this.CreateChannel(address, realm, binding);
        }
    }
}

using WampSharp.Binding;
using WampSharp.V2.Binding;
using WampSharp.V2.Client;
using WampSharp.WebSocket4Net;

namespace WampSharp.V2
{
    public class DefaultWampChannelFactory : WampChannelFactory
    {
        private readonly MessagePackObjectBinding mMsgpackBinding = new MessagePackObjectBinding();
        private readonly JTokenBinding mJsonBinding = new JTokenBinding();

        public IWampChannel CreateChannel<TMessage>(string address,
                                                    string realm,
                                                    IWampTextBinding<TMessage> binding)
        {
            var connection =
                new WebSocket4NetTextConnection<TMessage>(address, binding);

            return this.CreateChannel(realm, connection, binding);
        }

        public IWampChannel CreateChannel<TMessage>(string address,
                                                    string realm,
                                                    IWampBinaryBinding<TMessage> binding)
        {
            var connection =
                new WebSocket4NetBinaryConnection<TMessage>(address, binding);

            return this.CreateChannel(realm, connection, binding);
        }

        public IWampChannel CreateJsonChannel(string address,
                                              string realm)
        {
            return this.CreateChannel(address, realm, mJsonBinding);
        }

        public IWampChannel CreateMsgpackChannel(string address,
                                                 string realm)
        {
            return this.CreateChannel(address, realm, mMsgpackBinding);
        }
    }
}

Use the same reference for all method calls


using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Lurchsoft.FileData;
using Lurchsoft.ParallelWorkshop.Ex10WaitHalfWay;
using NUnit.Framework;

namespace Lurchsoft.ParallelWorkshopTests.Ex10WaitHalfWay
{
    [TestFixture]
    public class LimitedModeCharacterCounterTests
    {
        [Test]
        public void GetCharCounts_ShouldSucceed_WhenSeveralInstancesRunConcurrently()
        {
            const int NumConcurrent = 10;
            ITextFile[] allFiles = EmbeddedFiles.AllFiles.ToArray();
            IEnumerable<ITextFile> textFiles = Enumerable.Range(0, NumConcurrent).Select(i => allFiles[i % allFiles.Length]);

            // To solve the exercise, you may need to pass additional synchronisation information to the constructor.
            var counters = textFiles.Select(textFile => new LimitedModeCharacterCounter(textFile)).ToArray();

            // When you've succeeded, try changing this to use AsParallel(). Does it still work? It didn't for me. Explain why!
            Task[] tasks = counters.Select(c => (Task)Task.Factory.StartNew(() => c.GetCharCounts())).ToArray();
            Task.WaitAll(tasks);
        }
    }
}

using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Lurchsoft.FileData;
using Lurchsoft.ParallelWorkshop.Ex10WaitHalfWay;
using NUnit.Framework;

namespace Lurchsoft.ParallelWorkshopTests.Ex10WaitHalfWay
{
    [TestFixture]
    public class LimitedModeCharacterCounterTests
    {
        [Test]
        public void GetCharCounts_ShouldSucceed_WhenSeveralInstancesRunConcurrently()
        {
            LimitedModeCharacterCounter[] counters = CreateCounters();
            Task[] tasks = counters.Select(c => (Task)Task.Factory.StartNew(() => c.GetCharCounts())).ToArray();
            Task.WaitAll(tasks);
        }

        [Test, Explicit("This will probably hang, once you make it use your Barrier-based solution. Can you work out why?")]
        public void GetCharCounts_UsingAsParallel()
        {
            LimitedModeCharacterCounter[] counters = CreateCounters();
            var results = counters.AsParallel().Select(c => c.GetCharCounts()).ToArray();
            Assert.That(results, Is.Not.Empty);
        }

        private static LimitedModeCharacterCounter[] CreateCounters()
        {
            const int NumConcurrent = 10;
            ITextFile[] allFiles = EmbeddedFiles.AllFiles.ToArray();
            IEnumerable<ITextFile> textFiles = Enumerable.Range(0, NumConcurrent).Select(i => allFiles[i % allFiles.Length]);

            // To solve the exercise, you may need to pass additional synchronisation information to the constructor.
            var counters = textFiles.Select(textFile => new LimitedModeCharacterCounter(textFile)).ToArray();
            return counters;
        }
    }
}

Add an Explicit test that tries to use AsParallel(). It will hang after the exercise is completed, if the solution is the same as mine.


using System;
using System.IO;
using System.Timers;

using StatoBot.Core;

namespace StatoBot.Analytics
{
    public class AnalyzerBot : TwitchBot
    {
        public ChatAnalyzer Analyzer;

        public AnalyzerBot(Credentials credentials, string channel) : base(credentials, channel)
        {
            Analyzer = new ChatAnalyzer();
            OnMessageReceived += AnalyzeMessage;
        }

        private void AnalyzeMessage(object sender, OnMessageReceivedEventArgs args)
        {
            Analyzer
                .AnalyzeAsync(args)
                .Start();
        }
    }
}

using System;
using System.IO;
using System.Timers;
using System.Threading.Tasks;

using StatoBot.Core;

namespace StatoBot.Analytics
{
    public class AnalyzerBot : TwitchBot
    {
        public ChatAnalyzer Analyzer;

        public AnalyzerBot(Credentials credentials, string channel) : base(credentials, channel)
        {
            Analyzer = new ChatAnalyzer();
            OnMessageReceived += AnalyzeMessage;
        }

        private void AnalyzeMessage(object sender, OnMessageReceivedEventArgs args)
        {
            Task.Run(() =>
                Analyzer
                    .AnalyzeAsync(args)
            );
        }
    }
}

Use Task.Run instead of .Start()

Use Task.Run instead of .Start()


// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using osu.Framework.Allocation;
using osu.Game.Rulesets.Catch.Objects;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.UI;
using osu.Game.Rulesets.UI.Scrolling;

namespace osu.Game.Rulesets.Catch.Edit.Blueprints
{
    public class CatchPlacementBlueprint<THitObject> : PlacementBlueprint
        where THitObject : CatchHitObject, new()
    {
        protected new THitObject HitObject => (THitObject)base.HitObject;

        protected ScrollingHitObjectContainer HitObjectContainer => (ScrollingHitObjectContainer)playfield.HitObjectContainer;

        [Resolved]
        private Playfield playfield { get; set; }

        public CatchPlacementBlueprint()
            : base(new THitObject())
        {
        }
    }
}

// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using osu.Framework.Allocation;
using osu.Game.Rulesets.Catch.Objects;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.UI;
using osu.Game.Rulesets.UI.Scrolling;
using osuTK;

namespace osu.Game.Rulesets.Catch.Edit.Blueprints
{
    public class CatchPlacementBlueprint<THitObject> : PlacementBlueprint
        where THitObject : CatchHitObject, new()
    {
        protected new THitObject HitObject => (THitObject)base.HitObject;

        protected ScrollingHitObjectContainer HitObjectContainer => (ScrollingHitObjectContainer)playfield.HitObjectContainer;

        [Resolved]
        private Playfield playfield { get; set; }

        public CatchPlacementBlueprint()
            : base(new THitObject())
        {
        }

        public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => true;
    }
}

Fix hit object placement not receiving input when outside playfield

The input area is vertical infinite, but horizontally restricted to the playfield due to `CatchPlayfield`'s `ReceivePositionalInputAt` override.