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

namespace Oberon0.Compiler.Expressions.Operations
{
    using JetBrains.Annotations;

    using Oberon0.Compiler.Definitions;
    using Oberon0.Compiler.Expressions.Constant;
    using Oberon0.Compiler.Expressions.Operations.Internal;
    using Oberon0.Compiler.Types;

    [ArithmeticOperation(OberonGrammarLexer.OR, BaseTypes.Bool, BaseTypes.Bool, BaseTypes.Bool)]
    [ArithmeticOperation(OberonGrammarLexer.AND, BaseTypes.Bool, BaseTypes.Bool, BaseTypes.Bool)]
    [UsedImplicitly]
    internal class OpRelOp2 : BinaryOperation
    {
        protected override Expression BinaryOperate(BinaryExpression bin, Block block, IArithmeticOpMetadata operationParameters)
        {
            if (bin.LeftHandSide.IsConst && bin.RightHandSide.IsConst)
            {
                var left = (ConstantExpression)bin.LeftHandSide;
                var right = (ConstantExpression)bin.RightHandSide;
                bool res = false;
                switch (operationParameters.Operation)
                {
                    case OberonGrammarLexer.AND:
                        res = left.ToBool() & right.ToBool();
                        break;
                    case OberonGrammarLexer.OR:
                        res = left.ToBool() || right.ToBool();
                        break;
                }

                return new ConstantBoolExpression(res);
            }

            return bin; // expression remains the same
        }
    }
}

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

namespace Oberon0.Compiler.Expressions.Operations
{
    using JetBrains.Annotations;

    using Oberon0.Compiler.Definitions;
    using Oberon0.Compiler.Expressions.Constant;
    using Oberon0.Compiler.Expressions.Operations.Internal;
    using Oberon0.Compiler.Types;

    [ArithmeticOperation(OberonGrammarLexer.OR, BaseTypes.Bool, BaseTypes.Bool, BaseTypes.Bool)]
    [ArithmeticOperation(OberonGrammarLexer.AND, BaseTypes.Bool, BaseTypes.Bool, BaseTypes.Bool)]
    [UsedImplicitly]
    internal class OpRelOp2 : BinaryOperation
    {
        protected override Expression BinaryOperate(BinaryExpression bin, Block block, IArithmeticOpMetadata operationParameters)
        {
            if (bin.LeftHandSide.IsConst && bin.RightHandSide.IsConst)
            {
                var left = (ConstantExpression)bin.LeftHandSide;
                var right = (ConstantExpression)bin.RightHandSide;
                bool res = false;
                switch (operationParameters.Operation)
                {
                    case OberonGrammarLexer.AND:
                        res = left.ToBool() && right.ToBool();
                        break;
                    case OberonGrammarLexer.OR:
                        res = left.ToBool() || right.ToBool();
                        break;
                }

                return new ConstantBoolExpression(res);
            }

            return bin; // expression remains the same
        }
    }
}

Use && instead of & to perform AND operation


using System.Linq;
using System.Web;
using CommonMark;
using JetBrains.Annotations;
using JoinRpg.DataModel;
using JoinRpg.Helpers.Web;

namespace JoinRpg.Web.Helpers
{
  public static class MarkDownHelper
  {
    /// <summary>
    /// Converts markdown to HtmlString with all sanitization
    /// </summary>
    [CanBeNull]
    public static HtmlString ToHtmlString([CanBeNull] this MarkdownString markdownString)
    {
      return markdownString?.Contents == null ? null : markdownString.RenderMarkDownToHtmlUnsafe().SanitizeHtml();
    }

    public static string ToPlainText([CanBeNull] this MarkdownString markdownString)
    {
      if (markdownString?.Contents == null)
      {
        return null;
      }
      return markdownString.RenderMarkDownToHtmlUnsafe().RemoveHtml();
    }

    private static UnSafeHtml RenderMarkDownToHtmlUnsafe(this MarkdownString markdownString)
    {
      var settings = CommonMarkSettings.Default.Clone();
      settings.RenderSoftLineBreaksAsLineBreaks = true;
      return CommonMarkConverter.Convert(markdownString.Contents, settings);
    }

    public static MarkdownString TakeWords(this MarkdownString markdownString, int words)
    {
      if (markdownString?.Contents == null)
      {
        return null;
      }
      var w = words;
      var idx = markdownString.Contents.TakeWhile(c => (w -= char.IsWhiteSpace(c) ? 1 : 0) > 0 && c != '\n').Count();
      var mdContents = markdownString.Contents.Substring(0, idx);
      return new MarkdownString(mdContents);
    }
  }
}

using System.Linq;
using System.Web;
using CommonMark;
using JetBrains.Annotations;
using JoinRpg.DataModel;
using JoinRpg.Helpers.Web;

namespace JoinRpg.Web.Helpers
{
  public static class MarkDownHelper
  {
    /// <summary>
    /// Converts markdown to HtmlString with all sanitization
    /// </summary>
    [CanBeNull]
    public static HtmlString ToHtmlString([CanBeNull] this MarkdownString markdownString)
    {
      return markdownString?.Contents == null ? null : markdownString.RenderMarkDownToHtmlUnsafe().SanitizeHtml();
    }

    public static string ToPlainText([CanBeNull] this MarkdownString markdownString)
    {
      if (markdownString?.Contents == null)
      {
        return null;
      }
      return markdownString.RenderMarkDownToHtmlUnsafe().RemoveHtml().Trim();
    }

    private static UnSafeHtml RenderMarkDownToHtmlUnsafe(this MarkdownString markdownString)
    {
      var settings = CommonMarkSettings.Default.Clone();
      settings.RenderSoftLineBreaksAsLineBreaks = true;
      return CommonMarkConverter.Convert(markdownString.Contents, settings);
    }

    public static MarkdownString TakeWords(this MarkdownString markdownString, int words)
    {
      if (markdownString?.Contents == null)
      {
        return null;
      }
      var w = words;
      var idx = markdownString.Contents.TakeWhile(c => (w -= char.IsWhiteSpace(c) ? 1 : 0) > 0 && c != '\n').Count();
      var mdContents = markdownString.Contents.Substring(0, idx);
      return new MarkdownString(mdContents);
    }
  }
}

Fix plots can't edit bug

Fix plots can't edit bug


using System;
using System.Linq;
using EloWeb.Models;
using NUnit.Framework;
using System.Collections.Generic;

namespace EloWeb.Tests.UnitTests
{
    class PlayersTests
    {
        [Test]
        public void CanParsePlayerDescriptionText()
        {
            InitialiseTestPlayers();
            InitialiseTestGames();

            var player = Players.PlayerByName("Richard");

            Assert.AreEqual("Richard", player.Name);
            Assert.AreEqual(1000, player.Rating);
        }

        [Test]
        public void CanGetPlayerTotalGamesWon()
        {
            InitialiseTestPlayers();
            InitialiseTestGames();

            var player = Players.PlayerByName("Frank");

            Assert.AreEqual(2, player.GamesWon);
        }

        [Test]
        public void CanGetPlayerTotalGamesLost()
        {
            InitialiseTestPlayers();
            InitialiseTestGames();

            var player = Players.PlayerByName("Frank");

            Assert.AreEqual(1, player.GamesLost);
        }

        private void InitialiseTestPlayers()
        {
            Players.Initialise(new List<String>() { "Peter", "Frank", "Richard" });
        }

        private void InitialiseTestGames()
        {
            Games.Initialise(new List<String>() { "Peter beat Frank", "Frank beat Peter", "Frank beat Peter" });
        }
    }
}

using System;
using System.Linq;
using EloWeb.Models;
using NUnit.Framework;
using System.Collections.Generic;

namespace EloWeb.Tests.UnitTests
{
    class PlayersTests
    {
        [TestFixtureSetUp]
        public void TestSetup()
        {
            InitialiseTestPlayers();
            InitialiseTestGames();
        }

        [Test]
        public void CanParsePlayerDescriptionText()
        {
            var player = Players.PlayerByName("Richard");

            Assert.AreEqual("Richard", player.Name);
            Assert.AreEqual(1000, player.Rating);
        }

        [Test]
        public void CanGetPlayerTotalGamesWon()
        {
            var player = Players.PlayerByName("Frank");

            Assert.AreEqual(2, player.GamesWon);
        }

        [Test]
        public void CanGetPlayerTotalGamesLost()
        {
            var player = Players.PlayerByName("Frank");

            Assert.AreEqual(1, player.GamesLost);
        }

        private void InitialiseTestPlayers()
        {
            Players.Initialise(new List<String>() { "Peter", "Frank", "Richard" });
        }

        private void InitialiseTestGames()
        {
            Games.Initialise(new List<String>() { "Peter beat Frank", "Frank beat Peter", "Frank beat Peter" });
        }
    }
}

Refactor tests to have initialise method


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

namespace NHotkey.Wpf
{
    class WeakReferenceCollection<T> : IEnumerable<T>
        where T : class
    {
        private readonly List<WeakReference> _references = new List<WeakReference>();

        public IEnumerator<T> GetEnumerator()
        {
            foreach (var reference in _references)
            {
                var target = reference.Target;
                if (target != null)
                    yield return (T) target;
            }
            Trim();
        }

        public void Add(T item)
        {
            _references.Add(new WeakReference(item));
        }

        public void Remove(T item)
        {
            _references.RemoveAll(r => (r.Target ?? item) == item);
        }

        public void Trim()
        {
            _references.RemoveAll(r => !r.IsAlive);
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }
}

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

namespace NHotkey.Wpf
{
    class WeakReferenceCollection<T> : IEnumerable<T>
        where T : class
    {
        private readonly List<WeakReference> _references = new List<WeakReference>();

        public IEnumerator<T> GetEnumerator()
        {
            var references = _references.ToList();
            foreach (var reference in references)
            {
                var target = reference.Target;
                if (target != null)
                    yield return (T) target;
            }
            Trim();
        }

        public void Add(T item)
        {
            _references.Add(new WeakReference(item));
        }

        public void Remove(T item)
        {
            _references.RemoveAll(r => (r.Target ?? item) == item);
        }

        public void Trim()
        {
            _references.RemoveAll(r => !r.IsAlive);
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }
}

Copy list before iterating to prevent modifications during iteration


namespace Umbraco.Web.UI
{
    /// <summary>
    /// This is used for anything that is assigned to an app
    /// </summary>
    /// <remarks>
    /// Currently things that need to be assigned to an app in order for user security to work are:
    /// dialogs, ITasks, editors
    /// </remarks>
    public interface IAssignedApp
    {
        /// <summary>
        /// Returns the app alias that this element belongs to
        /// </summary>
        string AssignedApp { get; }
    }
}

namespace Umbraco.Web.UI
{
    /// <summary>
    /// This is used for anything that is assigned to an app
    /// </summary>
    /// <remarks>
    /// Currently things that need to be assigned to an app in order for user security to work are:
    /// LegacyDialogTask
    /// </remarks>
    public interface IAssignedApp
    {
        /// <summary>
        /// Returns the app alias that this element belongs to
        /// </summary>
        string AssignedApp { get; }
    }
}

Update comment about this Interface usage - maybe we can remove this later on


using System;
using System.IO;
using System.Text;
using Xunit.Abstractions;

namespace Foundatio.Tests.Utility {
    public class TestOutputWriter : TextWriter {
        private readonly ITestOutputHelper _output;

        public TestOutputWriter(ITestOutputHelper output) {
            _output = output;
        }

        public override Encoding Encoding {
            get { return Encoding.UTF8; }
        }

        public override void WriteLine(string value) {
            _output.WriteLine(value);
        }

        public override void WriteLine() {
            _output.WriteLine(String.Empty);
        }
    }
}

using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using Xunit.Abstractions;

namespace Foundatio.Tests.Utility {
    public class TestOutputWriter : TextWriter {
        private readonly ITestOutputHelper _output;

        public TestOutputWriter(ITestOutputHelper output) {
            _output = output;
        }

        public override Encoding Encoding {
            get { return Encoding.UTF8; }
        }

        public override void WriteLine(string value) {
            try {
                _output.WriteLine(value);
            } catch (Exception ex) {
                Trace.WriteLine(ex);
            }
        }

        public override void WriteLine() {
            WriteLine(String.Empty);
        }
    }
}

Fix issue where test writer was writing when nothing was listening.


using System.Collections.Generic;
using NUnit.Framework;
using UnityEngine;
using Voxelgon.ShipEditor;

namespace Voxelgon.Tests {
    public class WallTests {

        [Test]
        public void WallCannotHaveDuplicateVertices() {
            //Arrange
            var editor = new ShipEditor.ShipEditor();
            var wall = new Wall(editor);
            var nodes = new List<Vector3>();
            nodes.Add(new Vector3(5, 8, 3));

            //Act
            wall.UpdateVertices(nodes, ShipEditor.ShipEditor.BuildMode.Polygon);

            //Assert
            Assert.That(wall.ValidVertex(new Vector3(5, 8, 3)), Is.False);
        }

    }
}

using System.Collections.Generic;
using NUnit.Framework;
using UnityEngine;
using Voxelgon.ShipEditor;

namespace Voxelgon.ShipEditor.Tests {
    public class WallTests {

        [Test]
        public void WallCannotHaveDuplicateVertices() {
            //Arrange
            var editor = new ShipEditor();
            var wall = new Wall(editor);
            var nodes = new List<Vector3>();
            nodes.Add(new Vector3(5, 8, 3));

            //Act
            wall.UpdateVertices(nodes, ShipEditor.BuildMode.Polygon);

            //Assert
            Assert.That(wall.ValidVertex(new Vector3(5, 8, 3)), Is.False);
        }

    }
}

Move Shipeditor tests to the Voxelgon.Shipeditor.Tests namespace


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

namespace NTwitch.Rest
{
    public class TwitchRestClientConfig
    {
        public string BaseUrl { get; set; } = "https://api.twitch.tv/kraken/";
    }
}

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

namespace NTwitch.Rest
{
    public class TwitchRestClientConfig
    {
        public string BaseUrl { get; set; } = "https://api.twitch.tv/kraken/";
        public LogLevel LogLevel { get; set; } = LogLevel.Errors;
    }
}

Add LogLevel option to restclient config


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

using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics.Containers;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Osu.Beatmaps;
using osu.Game.Screens.Edit;
using osu.Game.Screens.Edit.Setup;

namespace osu.Game.Tests.Visual.Editing
{
    [TestFixture]
    public class TestSceneSetupScreen : EditorClockTestScene
    {
        [Cached(typeof(EditorBeatmap))]
        [Cached(typeof(IBeatSnapProvider))]
        private readonly EditorBeatmap editorBeatmap;

        public TestSceneSetupScreen()
        {
            editorBeatmap = new EditorBeatmap(new OsuBeatmap());
        }

        [BackgroundDependencyLoader]
        private void load()
        {
            Beatmap.Value = CreateWorkingBeatmap(editorBeatmap.PlayableBeatmap);

            Child = new SetupScreen
            {
                State = { Value = Visibility.Visible },
            };
        }
    }
}

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

using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics.Containers;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Catch;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Mania;
using osu.Game.Rulesets.Osu;
using osu.Game.Rulesets.Osu.Beatmaps;
using osu.Game.Rulesets.Taiko;
using osu.Game.Screens.Edit;
using osu.Game.Screens.Edit.Setup;

namespace osu.Game.Tests.Visual.Editing
{
    [TestFixture]
    public class TestSceneSetupScreen : EditorClockTestScene
    {
        [Cached(typeof(EditorBeatmap))]
        [Cached(typeof(IBeatSnapProvider))]
        private readonly EditorBeatmap editorBeatmap;

        public TestSceneSetupScreen()
        {
            editorBeatmap = new EditorBeatmap(new OsuBeatmap());
        }

        [Test]
        public void TestOsu() => runForRuleset(new OsuRuleset().RulesetInfo);

        [Test]
        public void TestTaiko() => runForRuleset(new TaikoRuleset().RulesetInfo);

        [Test]
        public void TestCatch() => runForRuleset(new CatchRuleset().RulesetInfo);

        [Test]
        public void TestMania() => runForRuleset(new ManiaRuleset().RulesetInfo);

        private void runForRuleset(RulesetInfo rulesetInfo)
        {
            AddStep("create screen", () =>
            {
                editorBeatmap.BeatmapInfo.Ruleset = rulesetInfo;

                Beatmap.Value = CreateWorkingBeatmap(editorBeatmap.PlayableBeatmap);

                Child = new SetupScreen
                {
                    State = { Value = Visibility.Visible },
                };
            });
        }
    }
}

Add test coverage for per-ruleset setup screens


namespace TheCollection.Business {

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

    public interface ISearchRepository<T> where T : class {

        Task<IEnumerable<T>> SearchAsync(string searchterm, int top = 0);
    }
}

namespace TheCollection.Business {

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

    public interface ISearchRepository<T> where T : class {

        Task<IEnumerable<T>> SearchAsync(string searchterm, int top = 0);

        Task<long> SearchRowCountAsync(string searchterm);
    }
}

Add missing function to interface

Add missing function to interface


@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

  <input type="text" id="msg" />
  Send message

Messages :

Prepend debug messages in the web chat example.


@{
    ViewBag.Title = "GAMES";
}

GAMES:

list all games here!!!

Check if appharbour will trigger a build


using System;
using FG5eXmlToPDF;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace FG5eXmlToPdf.Tests
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void ReadWriteTest()
        {
            var currentDirectory = System.IO.Directory.GetCurrentDirectory();
            var character = FG5eXml.LoadCharacter($@"{currentDirectory}\rita.xml");
            FG5ePdf.Write(
                character,
                $@"{currentDirectory}\out.pdf");
        }
    }
}

using System;
using System.Linq;
using FG5eXmlToPDF;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace FG5eXmlToPdf.Tests
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void ReadWriteTest()
        {
            var currentDirectory = System.IO.Directory.GetCurrentDirectory();
            var character = FG5eXml.LoadCharacter($@"{currentDirectory}\rita.xml");
            var charName = character.Properities.FirstOrDefault((x) => x.Name == "Name")?.Value;
            var level = character.Properities.FirstOrDefault((x) => x.Name == "LevelTotal")?.Value;
            FG5ePdf.Write(
                character,
                $@"{currentDirectory}\{charName} ({level}).pdf");
        }
    }
}

Test file output using char name and total level.


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

namespace TvShowReminderWorker
{
    class Program
    {
        static void Main(string[] args)
        {
        }
    }
}

using System;

namespace TvShowReminderWorker
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("I am the web job, I ran at {0}", DateTime.Now);
        }
    }
}

Add text for debug purposes to see if the job has been running


using System;
using System.IO;
using System.Reflection;
using DanTup.DartAnalysis.Json;
namespace DanTup.DartAnalysis.Tests
{
	public abstract class Tests
	{
		protected string SdkFolder
		{
			// Hijack ENV-reading property
			get { return DanTup.DartVS.DartAnalysisService.SdkPath; }
		}

		string CodebaseRoot = Path.GetFullPath(new Uri(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase), @"..\..\..\")).AbsolutePath); // up out of debug, bin, Tests

		protected string ServerScript { get { return Path.Combine(CodebaseRoot, "Dart\\AnalysisServer.dart"); } }
		protected string SampleDartProject { get { return Path.Combine(CodebaseRoot, "DanTup.DartAnalysis.Tests.SampleDartProject"); } }
		protected string HelloWorldFile { get { return SampleDartProject + @"\hello_world.dart"; } }
		protected string SingleTypeErrorFile { get { return SampleDartProject + @"\single_type_error.dart"; } }

		protected DartAnalysisService CreateTestService()
		{
			var service = new DartAnalysisService(SdkFolder, ServerScript);

			service.SetServerSubscriptions(new[] { ServerService.Status }).Wait();

			return service;
		}
	}
}

using System;
using System.IO;
using System.Reactive.Linq;
using System.Reflection;
using DanTup.DartAnalysis.Json;
namespace DanTup.DartAnalysis.Tests
{
	public abstract class Tests
	{
		protected string SdkFolder
		{
			// Hijack ENV-reading property
			get { return DanTup.DartVS.DartAnalysisService.SdkPath; }
		}

		string CodebaseRoot = Path.GetFullPath(new Uri(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase), @"..\..\..\")).AbsolutePath); // up out of debug, bin, Tests

		protected string ServerScript { get { return Path.Combine(CodebaseRoot, "Dart\\AnalysisServer.dart"); } }
		protected string SampleDartProject { get { return Path.Combine(CodebaseRoot, "DanTup.DartAnalysis.Tests.SampleDartProject"); } }
		protected string HelloWorldFile { get { return SampleDartProject + @"\hello_world.dart"; } }
		protected string SingleTypeErrorFile { get { return SampleDartProject + @"\single_type_error.dart"; } }

		protected DartAnalysisService CreateTestService()
		{
			var service = new DartAnalysisService(SdkFolder, ServerScript);

			service.SetServerSubscriptions(new[] { ServerService.Status }).Wait();

			return service;
		}
	}

	public static class TestExtensions
	{
		public static void WaitForAnalysis(this DartAnalysisService service)
		{
			service
				.ServerStatusNotification
				.FirstAsync(n => n.Analysis.Analyzing == false)
				.Wait();
		}
	}
}

Add test extension for easier waiting for analysis completion.


using System;
using System.Linq;
using Microsoft.VisualStudio.ExtensionsExplorer;

namespace NuGet.Dialog.Providers {

    internal class PackagesSearchNode : PackagesTreeNodeBase {

        private string _searchText;
        private readonly PackagesTreeNodeBase _baseNode;

        public PackagesTreeNodeBase BaseNode {
            get {
                return _baseNode;
            }
        }

        public PackagesSearchNode(PackagesProviderBase provider, IVsExtensionsTreeNode parent, PackagesTreeNodeBase baseNode, string searchText) :
            base(parent, provider) {

            if (baseNode == null) {
                throw new ArgumentNullException("baseNode");
            }

            _searchText = searchText;
            _baseNode = baseNode;

            // Mark this node as a SearchResults node to assist navigation in ExtensionsExplorer
            IsSearchResultsNode = true;
        }

        public override string Name {
            get {
                return Resources.Dialog_RootNodeSearch;
            }
        }

        public void SetSearchText(string newSearchText) {
            if (newSearchText == null) {
                throw new ArgumentNullException("newSearchText");
            }

            if (_searchText != newSearchText) {
                _searchText = newSearchText;

                if (IsSelected) {
                    ResetQuery();
                    Refresh();
                }
            }
        }

        public override IQueryable<IPackage> GetPackages() {
            return _baseNode.GetPackages().Find(_searchText);
        }
    }
}

using System;
using System.Linq;
using Microsoft.VisualStudio.ExtensionsExplorer;

namespace NuGet.Dialog.Providers {

    internal class PackagesSearchNode : PackagesTreeNodeBase {

        private string _searchText;
        private readonly PackagesTreeNodeBase _baseNode;

        public PackagesTreeNodeBase BaseNode {
            get {
                return _baseNode;
            }
        }

        public PackagesSearchNode(PackagesProviderBase provider, IVsExtensionsTreeNode parent, PackagesTreeNodeBase baseNode, string searchText) :
            base(parent, provider) {

            if (baseNode == null) {
                throw new ArgumentNullException("baseNode");
            }

            _searchText = searchText;
            _baseNode = baseNode;

            // Mark this node as a SearchResults node to assist navigation in ExtensionsExplorer
            IsSearchResultsNode = true;
        }

        public override string Name {
            get {
                return Resources.Dialog_RootNodeSearch;
            }
        }

        public void SetSearchText(string newSearchText) {
            if (newSearchText == null) {
                throw new ArgumentNullException("newSearchText");
            }

            if (_searchText != newSearchText) {
                _searchText = newSearchText;

                if (IsSelected) {
                    ResetQuery();
                    LoadPage(1);
                }
            }
        }

        public override IQueryable<IPackage> GetPackages() {
            return _baseNode.GetPackages().Find(_searchText);
        }
    }
}

Reset page number to 1 when perform a new search.
Work items: 569

--HG--
branch : 1.1


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

namespace Establishment {

    public class StringEstablisher : BaseClassEstablisher<string> {

        public bool IsNullOrEmpty(string value) {
            if (!string.IsNullOrEmpty(value)) {
                return HandleFailure(new ArgumentException("string value must be null or empty"));
            }

            return true;
        }

        public bool IsNotNullOrEmpty(string value) {
            if (string.IsNullOrEmpty(value)) {
                return HandleFailure(new ArgumentException("string value must not be null or empty"));
            }

            return true;
        }

    }

}

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

namespace Establishment {

    public class StringEstablisher : BaseClassEstablisher<string> {

        public bool IsNullOrEmpty(string value) {
            if (!string.IsNullOrEmpty(value)) {
                return HandleFailure(new ArgumentException("string value must be null or empty"));
            }

            return true;
        }

        public bool IsNotNullOrEmpty(string value) {
            if (string.IsNullOrEmpty(value)) {
                return HandleFailure(new ArgumentException("string value must not be null or empty"));
            }

            return true;
        }

        public bool IsEmpty(string value) {
            if (value != string.Empty) {
                return HandleFailure(new ArgumentException("string value must be empty"));
            }

            return true;
        }

        public bool IsNotEmpty(string value) {
            if (value == string.Empty) {
                return HandleFailure(new ArgumentException("string value must not be empty"));
            }

            return true;
        }

    }

}

Add additional comparison methods for string establisher


// 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.Game.Beatmaps;
using osu.Game.Rulesets.Catch.Objects;
using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Scoring;
using osu.Game.Rulesets.UI;

namespace osu.Game.Rulesets.Catch.Scoring
{
    public class CatchScoreProcessor : ScoreProcessor<CatchHitObject>
    {
        public CatchScoreProcessor(DrawableRuleset<CatchHitObject> drawableRuleset)
            : base(drawableRuleset)
        {
        }

        private float hpDrainRate;

        protected override void ApplyBeatmap(Beatmap<CatchHitObject> beatmap)
        {
            base.ApplyBeatmap(beatmap);

            hpDrainRate = beatmap.BeatmapInfo.BaseDifficulty.DrainRate;
        }

        protected override double HpFactorFor(Judgement judgement, HitResult result)
        {
            switch (result)
            {
                case HitResult.Miss when judgement.IsBonus:
                    return 0;
                case HitResult.Miss:
                    return hpDrainRate;
                default:
                    return 10 - hpDrainRate; // Award less HP as drain rate is increased
            }
        }

        public override HitWindows CreateHitWindows() => new CatchHitWindows();
    }
}

// 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.Game.Beatmaps;
using osu.Game.Rulesets.Catch.Objects;
using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Scoring;
using osu.Game.Rulesets.UI;

namespace osu.Game.Rulesets.Catch.Scoring
{
    public class CatchScoreProcessor : ScoreProcessor<CatchHitObject>
    {
        public CatchScoreProcessor(DrawableRuleset<CatchHitObject> drawableRuleset)
            : base(drawableRuleset)
        {
        }

        private float hpDrainRate;

        protected override void ApplyBeatmap(Beatmap<CatchHitObject> beatmap)
        {
            base.ApplyBeatmap(beatmap);

            hpDrainRate = beatmap.BeatmapInfo.BaseDifficulty.DrainRate;
        }

        protected override double HpFactorFor(Judgement judgement, HitResult result)
        {
            switch (result)
            {
                case HitResult.Miss when judgement.IsBonus:
                    return 0;
                case HitResult.Miss:
                    return hpDrainRate;
                default:
                    return 10.2 - hpDrainRate; // Award less HP as drain rate is increased
            }
        }

        public override HitWindows CreateHitWindows() => new CatchHitWindows();
    }
}

Make catch provide some HP at DrainRate=10


using System;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;

namespace Gelf.Extensions.Logging
{
    public class GelfLoggerOptions
    {
        public GelfLoggerOptions()
        {
            Filter = (name, level) => level > LogLevel;
        }

        /// <summary>
        /// GELF server host.
        /// </summary>
        public string Host { get; set; }

        /// <summary>
        /// GELF server port.
        /// </summary>
        public int Port { get; set; } = 12201;

        /// <summary>
        /// Log source name mapped to the GELF host field.
        /// </summary>
        public string LogSource { get; set; }

        /// <summary>
        /// Enable GZip message compression.
        /// </summary>
        public bool Compress { get; set; } = true;

        /// <summary>
        /// The message size in bytes under which messages will not be compressed.
        /// </summary>
        public int CompressionThreshold { get; set; } = 512;

        /// <summary>
        /// Function used to filter log events based on logger name and level. Uses <see cref="LogLevel"/> by default.
        /// </summary>
        public Func<string, LogLevel, bool> Filter { get; set; }

        /// <summary>
        /// The defualt log level.
        /// </summary>
        public LogLevel LogLevel { get; set; } = LogLevel.Information;

        /// <summary>
        /// Additional fields that will be attached to all log messages.
        /// </summary>
        public Dictionary<string, string> AdditionalFields { get; } = new Dictionary<string, string>();
    }
}

using System;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;

namespace Gelf.Extensions.Logging
{
    public class GelfLoggerOptions
    {
        public GelfLoggerOptions()
        {
            Filter = (name, level) => level >= LogLevel;
        }

        /// <summary>
        /// GELF server host.
        /// </summary>
        public string Host { get; set; }

        /// <summary>
        /// GELF server port.
        /// </summary>
        public int Port { get; set; } = 12201;

        /// <summary>
        /// Log source name mapped to the GELF host field.
        /// </summary>
        public string LogSource { get; set; }

        /// <summary>
        /// Enable GZip message compression.
        /// </summary>
        public bool Compress { get; set; } = true;

        /// <summary>
        /// The message size in bytes under which messages will not be compressed.
        /// </summary>
        public int CompressionThreshold { get; set; } = 512;

        /// <summary>
        /// Function used to filter log events based on logger name and level. Uses <see cref="LogLevel"/> by default.
        /// </summary>
        public Func<string, LogLevel, bool> Filter { get; set; }

        /// <summary>
        /// The defualt log level.
        /// </summary>
        public LogLevel LogLevel { get; set; } = LogLevel.Information;

        /// <summary>
        /// Additional fields that will be attached to all log messages.
        /// </summary>
        public Dictionary<string, string> AdditionalFields { get; } = new Dictionary<string, string>();
    }
}

Fix default log level filter

Fix default log level filter


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

namespace DataGenExtensions
{
	public static class ObjectExtensions
	{

	}
}

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

namespace DataGenExtensions
{
	public static class ObjectExtensions
	{
		public static bool IsNull(this object objectInstance)
		{
			return objectInstance == null;
		}

		public static bool IsNotNull(this object objectInstance)
		{
			return !objectInstance.IsNull();
		}
	}
}

Add object's IsNull & IsNotNull extentions


using Slicer.Utils.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Slicer.Utils.Validators
{
    // Validates data extraction queries
    public class DataExtractionQueryValidator
    {
        Dictionary<string, dynamic> Query;
        public DataExtractionQueryValidator(Dictionary<string, dynamic> query)
        {
            this.Query = query;
        }

        // Validate data extraction query, if the query is valid will return true
        public bool Validator()
        {
            if (this.Query.ContainsKey("limit"))
            {
                var limitValue = (int) this.Query["limit"];
                if (limitValue > 100)
                {
                    throw new InvalidQueryException("The field 'limit' has a value max of 100.");
                }
            }
            if (this.Query.ContainsKey("fields"))
            {
                var fields = this.Query["fields"];
                if (fields.Count > 10)
                {
                    throw new InvalidQueryException("The key 'fields' in data extraction result must have up to 10 fields.");
                }
            }
            return true;
        }
    }
}

using Slicer.Utils.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Slicer.Utils.Validators
{
    // Validates data extraction queries
    public class DataExtractionQueryValidator
    {
        Dictionary<string, dynamic> Query;
        public DataExtractionQueryValidator(Dictionary<string, dynamic> query)
        {
            this.Query = query;
        }

        // Validate data extraction query, if the query is valid will return true
        public bool Validator()
        {
            if (this.Query.ContainsKey("fields"))
            {
                var fields = this.Query["fields"];
                if (fields.Count > 10)
                {
                    throw new InvalidQueryException("The key 'fields' in data extraction result must have up to 10 fields.");
                }
            }
            return true;
        }
    }
}

Remove limit check on data extraction queries


namespace Tabster.Core.Plugins
{
    public interface ITabsterPlugin
    {
        string Name { get; }
        string Description { get; }
        string Author { get; }
        string Version { get; }
        string[] PluginClasses { get; }
    }
}

using System;

namespace Tabster.Core.Plugins
{
    public interface ITabsterPlugin
    {
        string Name { get; }
        string Description { get; }
        string Author { get; }
        string Version { get; }
        Type[] Types { get; }
    }
}

Use types instead of fully qualified names.


using UnityEngine;

public class Application : MonoBehaviour
{
    public ModelContainer Model;
    public ControllerContainer Controller;
    public ViewContainer View;
}

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;

public class Application : MonoBehaviour
{
    public ModelContainer Model;
    public ControllerContainer Controller;
    public ViewContainer View;

    private Dictionary<string, UnityEvent> eventDictionary = new Dictionary<string, UnityEvent>();

    /// <summary>
    /// Add listener to a given event.
    /// </summary>
    /// <param name="eventName">Name of the event.</param>
    /// <param name="listener">Callback function.</param>
    public void AddEventListener(string eventName, UnityAction listener)
    {
        UnityEvent e;
        if (eventDictionary.TryGetValue(eventName, out e))
        {
            e.AddListener(listener);
        }
        else
        {
            e = new UnityEvent();
            e.AddListener(listener);
            eventDictionary.Add(eventName, e);
        }
    }

    /// <summary>
    /// Remove listener from a given event.
    /// </summary>
    /// <param name="eventName">Name of the event.</param>
    /// <param name="listener">Callback function.</param>
    public void RemoveEventListener(string eventName, UnityAction listener)
    {
        UnityEvent e;
        if (eventDictionary.TryGetValue(eventName, out e))
        {
            e.RemoveListener(listener);
        }
    }

    /// <summary>
    /// Triggers all registered callbacks of a given event.
    /// </summary>
    public void TriggerEvent(string eventName)
    {
        UnityEvent e;
        if (eventDictionary.TryGetValue(eventName, out e))
        {
            e.Invoke();
        }
    }
}

Add possibility to register events on App, like we do on HTML DOM

Methods are:
App.AddEventListener(eventName, listener);
App.RemoveEventListener(eventName, listener);
App.TriggerEvent(eventName);


using System.Collections;
using System.Collections.Generic;
using LiteNetLib;

namespace LiteNetLibHighLevel
{
    public class LiteNetLibPlayer
    {
        public LiteNetLibGameManager Manager { get; protected set; }
        public NetPeer Peer { get; protected set; }
        public long ConnectId { get { return Peer.ConnectId; } }
        public readonly Dictionary<uint, LiteNetLibIdentity> SpawnedObjects = new Dictionary<uint, LiteNetLibIdentity>();

        public LiteNetLibPlayer(LiteNetLibGameManager manager, NetPeer peer)
        {
            Manager = manager;
            Peer = peer;
        }

        internal void DestoryAllObjects()
        {
            foreach (var spawnedObject in SpawnedObjects)
                Manager.Assets.NetworkDestroy(spawnedObject.Key);
        }
    }
}

using System.Collections;
using System.Collections.Generic;
using LiteNetLib;

namespace LiteNetLibHighLevel
{
    public class LiteNetLibPlayer
    {
        public LiteNetLibGameManager Manager { get; protected set; }
        public NetPeer Peer { get; protected set; }
        public long ConnectId { get { return Peer.ConnectId; } }
        internal readonly Dictionary<uint, LiteNetLibIdentity> SpawnedObjects = new Dictionary<uint, LiteNetLibIdentity>();

        public LiteNetLibPlayer(LiteNetLibGameManager manager, NetPeer peer)
        {
            Manager = manager;
            Peer = peer;
        }

        internal void DestoryAllObjects()
        {
            var objectIds = new List<uint>(SpawnedObjects.Keys);
            foreach (var objectId in objectIds)
                Manager.Assets.NetworkDestroy(objectId);
        }
    }
}

Fix out of sync bugs

Fix out of sync bugs


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

namespace ZocBuild.Database.Errors
{
    public class MismatchedSchemaError : BuildErrorBase
    {
        public MismatchedSchemaError(string objectName, string expected, string actual)
        {
            ActualSchemaName = actual;
            ExpectedSchemaName = expected;
            ObjectName = objectName;
        }

        public string ActualSchemaName { get; private set; }
        public string ExpectedSchemaName { get; private set; }
        public string ObjectName { get; private set; }

        public override string ErrorType
        {
            get { return "Mismatched Schema"; }
        }

        public override string GetMessage()
        {
            return string.Format("Cannot use script of schema {2} for {1} when expecting schema {0}.", ObjectName, ExpectedSchemaName, ActualSchemaName);
        }

        public override BuildItem.BuildStatusType Status
        {
            get { return BuildItem.BuildStatusType.ScriptError; }
        }
    }
}

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

namespace ZocBuild.Database.Errors
{
    public class MismatchedSchemaError : BuildErrorBase
    {
        public MismatchedSchemaError(string objectName, string expected, string actual)
        {
            ActualSchemaName = actual;
            ExpectedSchemaName = expected;
            ObjectName = objectName;
        }

        public string ActualSchemaName { get; private set; }
        public string ExpectedSchemaName { get; private set; }
        public string ObjectName { get; private set; }

        public override string ErrorType
        {
            get { return "Mismatched Schema"; }
        }

        public override string GetMessage()
        {
            return string.Format("Cannot use script of schema {2} for {0} when expecting schema {1}.", ObjectName, ExpectedSchemaName, ActualSchemaName);
        }

        public override BuildItem.BuildStatusType Status
        {
            get { return BuildItem.BuildStatusType.ScriptError; }
        }
    }
}

Fix string format in error message

Fix string format in error message


using System.Web;
using Microsoft.Web.Infrastructure;

namespace BoC.Web
{
    public class ApplicationStarterHttpModule : IHttpModule
	{
        private static object lockObject = new object();
		private static bool startWasCalled = false;

		public static void StartApplication()
		{
			if (startWasCalled || Initializer.Executed)
				return;

			try
			{
				lock (lockObject)
				{
					if (startWasCalled)
						return;
					Initializer.Execute();
					startWasCalled = true;
				}
			}
			catch
			{
				InfrastructureHelper.UnloadAppDomain();
				throw;
			}
		}

		public void Init(HttpApplication context)
		{
            context.BeginRequest += (sender, args) => StartApplication();
            if (!startWasCalled)
			{
				try
				{
					context.Application.Lock();
					StartApplication();
				}
				finally
				{
					context.Application.UnLock();
				}
			}
		}

		public void Dispose()
		{
		}
	}
}

using System;
using System.Configuration;
using System.Web;
using System.Web.Configuration;
using Microsoft.Web.Infrastructure;

namespace BoC.Web
{
    public class ApplicationStarterHttpModule : IHttpModule
	{
        private static object lockObject = new object();
		private static bool startWasCalled = false;

        public static volatile bool Disabled = false;

		public static void StartApplication()
		{
			if (Disabled || startWasCalled || Initializer.Executed)
				return;
			try
			{
				lock (lockObject)
				{
				    var disabled = WebConfigurationManager.AppSettings["BoC.Web.DisableAutoStart"];
				    if ("true".Equals(disabled, StringComparison.InvariantCultureIgnoreCase))
				    {
				        Disabled = true;
				        return;
				    }

					if (startWasCalled)
						return;

					Initializer.Execute();
					startWasCalled = true;
				}
			}
			catch
			{
				InfrastructureHelper.UnloadAppDomain();
				throw;
			}
		}

		public void Init(HttpApplication context)
		{
		    if (Disabled)
		        return;

            context.BeginRequest += (sender, args) => StartApplication();
            if (!Disabled && !startWasCalled)
			{
				try
				{
					context.Application.Lock();
					StartApplication();
				}
				finally
				{
					context.Application.UnLock();
				}
			}
		}

		public void Dispose()
		{
		}
	}
}

Allow to disable the application-starter


using Android.App;
using Android.Widget;
using Android.OS;

namespace TwitterMonkey
{
  [Activity (Label = "TwitterMonkey", MainLauncher = true, Icon = "@drawable/icon")]
  public class MainActivity : Activity
  {
    int count = 1;

    protected override void OnCreate (Bundle bundle)
    {
      base.OnCreate (bundle);

      // Set our view from the "main" layout resource
      SetContentView (Resource.Layout.Main);

      // Get our button from the layout resource,
      // and attach an event to it
      Button button = FindViewById<Button> (Resource.Id.myButton);

      button.Click += delegate {
        button.Text = string.Format ("{0} clicks!", count++);

      };
    }
  }
}

using System;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using Android.App;
using Android.OS;
using Android.Widget;
using TwitterMonkey.Portable;

namespace TwitterMonkey {
  [Activity(Label = "TwitterMonkey", MainLauncher = true, Icon = "@drawable/icon")]
  public class MainActivity : Activity {
    protected override void OnCreate (Bundle bundle) {
      base.OnCreate(bundle);

      // Set our view from the "main" layout resource
      SetContentView(Resource.Layout.Main);

      // Get our button from the layout resource,
      // and attach an event to it
      Button button = FindViewById<Button>(Resource.Id.myButton);

      button.Click += async (sender, e) => {
        var textView    = FindViewById<TextView>(Resource.Id.textView1);
        var jsonString  = await fetchJsonAsync(new Uri ("http://goo.gl/pJwOUS"));
        var tweets      = TweetConverter.ConvertAll(jsonString);
        foreach (Tweet t in tweets) {
          textView.Text += t.Message + "\n";
        }
      };
    }

    private async Task<string> fetchJsonAsync (Uri uri) {
      HttpWebRequest request = new HttpWebRequest(uri);
      var resp = await request.GetResponseAsync();
      StreamReader reader = new StreamReader (resp.GetResponseStream());
      return await reader.ReadToEndAsync();
    }
  }
}

Add simple mechanism to fetch JSON and display it


using System;

using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Xamarin.Forms;

namespace BluetoothLE.Example.Droid
{
	[Activity(Label = "BluetoothLE.Example.Droid", Icon = "@drawable/icon", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
	public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity
	{
		protected override void OnCreate(Bundle bundle)
		{
			base.OnCreate(bundle);

			DependencyService.Register<IAdapter, Adapter>();

			global::Xamarin.Forms.Forms.Init(this, bundle);

			LoadApplication(new App());
		}
	}
}

using System;

using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Xamarin.Forms;

namespace BluetoothLE.Example.Droid
{
	[Activity(Label = "BluetoothLE.Example.Droid", Icon = "@drawable/icon", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
	public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity
	{
		protected override void OnCreate(Bundle bundle)
		{
			base.OnCreate(bundle);

			DependencyService.Register<BluetoothLE.Core.IAdapter, BluetoothLE.Droid.Adapter>();

			global::Xamarin.Forms.Forms.Init(this, bundle);

			LoadApplication(new App());
		}
	}
}

Update IAdapter registration in Droid example project


// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE

using System;
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.ControlPoints;

namespace osu.Game.Rulesets.Osu.Objects
{
    public class RepeatPoint : OsuHitObject
    {
        public int RepeatIndex { get; set; }
        public double SpanDuration { get; set; }

        protected override void ApplyDefaultsToSelf(ControlPointInfo controlPointInfo, BeatmapDifficulty difficulty)
        {
            base.ApplyDefaultsToSelf(controlPointInfo, difficulty);

            // We want to show the first RepeatPoint as the TimePreempt dictates but on short (and possibly fast) sliders
            // we may need to cut down this time on following RepeatPoints to only show up to two RepeatPoints at any given time.
            if (RepeatIndex > 0)
                TimePreempt = Math.Min(SpanDuration * 2, TimePreempt);
        }
    }
}

// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE

using System;
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.ControlPoints;

namespace osu.Game.Rulesets.Osu.Objects
{
    public class RepeatPoint : OsuHitObject
    {
        public int RepeatIndex { get; set; }
        public double SpanDuration { get; set; }

        protected override void ApplyDefaultsToSelf(ControlPointInfo controlPointInfo, BeatmapDifficulty difficulty)
        {
            base.ApplyDefaultsToSelf(controlPointInfo, difficulty);

            // Out preempt should be one span early to give the user ample warning.
            TimePreempt += SpanDuration;

            // We want to show the first RepeatPoint as the TimePreempt dictates but on short (and possibly fast) sliders
            // we may need to cut down this time on following RepeatPoints to only show up to two RepeatPoints at any given time.
            if (RepeatIndex > 0)
                TimePreempt = Math.Min(SpanDuration * 2, TimePreempt);
        }
    }
}

Fix slider repeat points appearing far too late


//
//  ReadRegisters.cs
//
//  Author:
//       Benito Palacios Sánchez <benito356@gmail.com>
//
//  Copyright (c) 2015 Benito Palacios Sánchez
//
//  This program is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with this program.  If not, see <http://www.gnu.org/licenses/>.
using System;

namespace NitroDebugger.RSP.Packets
{
	public class ReadRegisters : CommandPacket
	{
		public ReadRegisters()
			: base('g')
		{
		}

		protected override string PackArguments()
		{
			return "";
		}
	}
}

//
//  ReadRegisters.cs
//
//  Author:
//       Benito Palacios Sánchez <benito356@gmail.com>
//
//  Copyright (c) 2015 Benito Palacios Sánchez
//
//  This program is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with this program.  If not, see <http://www.gnu.org/licenses/>.
using System;

namespace NitroDebugger.RSP.Packets
{
	public class ReadRegisters : CommandPacket
	{
		public ReadRegisters()
			: base("g")
		{
		}

		protected override string PackArguments()
		{
			return "";
		}
	}
}

Fix typo that don't compile.

Fix typo that don't compile.

Why chars are not implicit casted to string?


namespace Octokit
{
    public interface IActivitiesClient
    {
        IEventsClient Event { get; }
    }
}

namespace Octokit
{
    public interface IActivitiesClient
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Event")]
        IEventsClient Event { get; }
    }
}

Apply naming suppression to allow build to build.


namespace Espera.Network
{
    public enum PushAction
    {
        UpdateAccessPermission = 0,
        UpdateCurrentPlaylist = 1,
        UpdatePlaybackState = 2,
        UpdateRemainingVotes = 3
    }
}

namespace Espera.Network
{
    public enum PushAction
    {
        UpdateAccessPermission = 0,
        UpdateCurrentPlaylist = 1,
        UpdatePlaybackState = 2,
        UpdateRemainingVotes = 3,
        UpdateCurrentPlaybackTime = 4
    }
}

Add a playback time push message

Add a playback time push message


using System;

namespace Mios.Localization.Localizers {
	public class NullLocalizer {
		public static LocalizedString Instance(string key, params object[] args) {
			return new LocalizedString(String.Format(key,args), null);
		}
	}
}

using System;
using System.Linq;

namespace Mios.Localization.Localizers {
	public class NullLocalizer {
		public static LocalizedString Instance(string key, params object[] args) {
      var parameters = args.Any()
        ? "["+String.Join(",",args.Select(t=>(t??String.Empty).ToString()).ToArray())+"]"
        : String.Empty;
			return new LocalizedString(key+parameters, null);
		}
	}
}

Fix exception when dumping a null parameter


namespace Nancy.Linker.Tests
{
  using System.Runtime.InteropServices;
  using Testing;
  using Xunit;

  public class ResourceLinkerTests
  {
    private Browser app;

    public class TestModule : NancyModule
    {
      public static ResourceLinker linker;

      public TestModule(ResourceLinker linker)
      {
        TestModule.linker = linker;
        Get["foo", "/foo"] = _ => 200;
        Get["bar", "/bar/{id}"] = _ => 200;
      }
    }

    public ResourceLinkerTests()
    {
      app = new Browser(with => with.Module<TestModule>(), defaults: to => to.HostName("localhost"));
    }

    [Fact]
    public void Link_generated_is_correct_when_base_uri_has_trailing_slash()
    {
      var uriString = TestModule.linker.BuildAbsoluteUri(app.Get("/foo").Context, "foo",  new {});

      Assert.Equal("http://localhost/foo", uriString.ToString());
    }

    [Fact]
    public void Link_generated_is_correct_with_bound_parameter()
    {
      var uriString = TestModule.linker.BuildAbsoluteUri(app.Get("/foo").Context, "bar", new {id = 123 });

      Assert.Equal("http://localhost/bar/123", uriString.ToString());
    }

    [Fact]
    public void Argument_exception_is_thrown_if_parameter_from_template_cannot_be_bound()
    {
    }
  }
}

namespace Nancy.Linker.Tests
{
  using System;
  using System.Runtime.InteropServices;
  using Testing;
  using Xunit;

  public class ResourceLinker_Should
  {
    private Browser app;

    public class TestModule : NancyModule
    {
      public static ResourceLinker linker;

      public TestModule(ResourceLinker linker)
      {
        TestModule.linker = linker;
        Get["foo", "/foo"] = _ => 200;
        Get["bar", "/bar/{id}"] = _ => 200;
      }
    }

    public ResourceLinker_Should()
    {
      app = new Browser(with => with.Module<TestModule>(), defaults: to => to.HostName("localhost"));
    }

    [Fact]
    public void generate_absolute_uri_correctly_when_route_has_no_params()
    {
      var uriString = TestModule.linker.BuildAbsoluteUri(app.Get("/foo").Context, "foo",  new {});

      Assert.Equal("http://localhost/foo", uriString.ToString());
    }

    [Fact]
    public void generate_absolute_uri_correctly_when_route_has_params()
    {
      var uriString = TestModule.linker.BuildAbsoluteUri(app.Get("/foo").Context, "bar", new {id = 123 });

      Assert.Equal("http://localhost/bar/123", uriString.ToString());
    }

    [Fact]
    public void throw_if_parameter_from_template_cannot_be_bound()
    {
      Assert.Throws<ArgumentException>(() =>
        TestModule.linker.BuildAbsoluteUri(app.Get("/foo").Context, "bar", new { })
      );
    }
  }
}

Change naming in test and add one

Change naming in test and add one


using NBi.Core.Transformation.Transformer.Native;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NBi.Core.Transformation.Transformer
{
    public class NativeTransformationFactory
    {
        public INativeTransformation Instantiate(string code)
        {
            var textInfo = CultureInfo.InvariantCulture.TextInfo;

            var parameters = code.Replace("(", ",")
                .Replace(")", ",")
                .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                .ToList().Skip(1).Select(x => x.Trim()).ToArray();

            var classToken = code.Contains("(") ? code.Replace(" ", "").Substring(0, code.IndexOf('(')) : code;
            var className = textInfo.ToTitleCase(classToken.Trim().Replace("-", " ")).Replace(" ", "").Replace("Datetime", "DateTime");

            var clazz = AppDomain.CurrentDomain.GetAssemblies()
                       .SelectMany(t => t.GetTypes())
                       .Where(
                                t => t.IsClass
                                && t.IsAbstract == false
                                && t.Name == className
                                && t.GetInterface("INativeTransformation") != null)
                       .SingleOrDefault();

            if (clazz == null)
                throw new NotImplementedTransformationException(className);

            return (INativeTransformation)Activator.CreateInstance(clazz, parameters);
        }
    }
}

using NBi.Core.Transformation.Transformer.Native;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NBi.Core.Transformation.Transformer
{
    public class NativeTransformationFactory
    {
        public INativeTransformation Instantiate(string code)
        {
            var textInfo = CultureInfo.InvariantCulture.TextInfo;

            var parameters = code.Replace("(", ",")
                .Replace(")", ",")
                .Replace(" ", "")
                .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                .ToList().Skip(1).Select(x => x.Trim()).ToArray();

            var classToken = code.Contains("(") ? code.Replace(" ", "").Substring(0, code.IndexOf('(') - 1) : code;
            var className = textInfo.ToTitleCase(classToken.Trim().Replace("-", " ")).Replace(" ", "").Replace("Datetime", "DateTime");

            var clazz = AppDomain.CurrentDomain.GetAssemblies()
                       .SelectMany(t => t.GetTypes())
                       .Where(
                                t => t.IsClass
                                && t.IsAbstract == false
                                && t.Name == className
                                && t.GetInterface("INativeTransformation") != null)
                       .SingleOrDefault();

            if (clazz == null)
                throw new NotImplementedTransformationException(className);

            return (INativeTransformation)Activator.CreateInstance(clazz, parameters);
        }
    }
}

Fix bugs that native functions with parameters are not instantiable due to parsing mistakes


using umbraco;
using Umbraco.Core.IO;
using Umbraco.Web.Composing;
using Umbraco.Web.Models.Trees;
using Umbraco.Web.Mvc;
using Umbraco.Web.WebApi.Filters;
using Constants = Umbraco.Core.Constants;

namespace Umbraco.Web.Trees
{
    /// <summary>
    /// Tree for displaying partial views in the settings app
    /// </summary>
    [Tree(Constants.Applications.Settings, Constants.Trees.PartialViews, null, sortOrder: 7)]
    [UmbracoTreeAuthorize(Constants.Trees.PartialViews)]
    [PluginController("UmbracoTrees")]
    [CoreTree(TreeGroup = Constants.Trees.Groups.Templating)]
    public class PartialViewsTreeController : FileSystemTreeController
    {
        protected override IFileSystem FileSystem => Current.FileSystems.PartialViewsFileSystem;

        private static readonly string[] ExtensionsStatic = {"cshtml"};

        protected override string[] Extensions => ExtensionsStatic;

        protected override string FileIcon => "icon-article";

        protected override void OnRenderFolderNode(ref TreeNode treeNode)
        {
            //TODO: This isn't the best way to ensure a noop process for clicking a node but it works for now.
            treeNode.AdditionalData["jsClickCallback"] = "javascript:void(0);";
            treeNode.Icon = "icon-article";
        }
    }
}

using umbraco;
using Umbraco.Core.IO;
using Umbraco.Web.Composing;
using Umbraco.Web.Models.Trees;
using Umbraco.Web.Mvc;
using Umbraco.Web.WebApi.Filters;
using Constants = Umbraco.Core.Constants;

namespace Umbraco.Web.Trees
{
    /// <summary>
    /// Tree for displaying partial views in the settings app
    /// </summary>
    [Tree(Constants.Applications.Settings, Constants.Trees.PartialViews, null, sortOrder: 7)]
    [UmbracoTreeAuthorize(Constants.Trees.PartialViews)]
    [PluginController("UmbracoTrees")]
    [CoreTree(TreeGroup = Constants.Trees.Groups.Templating)]
    public class PartialViewsTreeController : FileSystemTreeController
    {
        protected override IFileSystem FileSystem => Current.FileSystems.PartialViewsFileSystem;

        private static readonly string[] ExtensionsStatic = {"cshtml"};

        protected override string[] Extensions => ExtensionsStatic;

        protected override string FileIcon => "icon-article";

        protected override void OnRenderFolderNode(ref TreeNode treeNode)
        {
            //TODO: This isn't the best way to ensure a noop process for clicking a node but it works for now.
            treeNode.AdditionalData["jsClickCallback"] = "javascript:void(0);";
            treeNode.Icon = "icon-folder";
        }
    }
}

Fix PartialView Tree Controller to display a folder icon as opposed to an article icon for nested folders - looks odd/broken to me otherwise


using System.Collections.Generic;
using Elders.Cronus.Discoveries;
using Microsoft.Extensions.DependencyInjection;
using RabbitMQ.Client;

namespace Elders.Cronus.Transport.RabbitMQ
{
    public class RabbitMqPublisherDiscovery : DiscoveryBasedOnExecutingDirAssemblies<IPublisher<IMessage>>
    {
        protected override DiscoveryResult<IPublisher<IMessage>> DiscoverFromAssemblies(DiscoveryContext context)
        {
            return new DiscoveryResult<IPublisher<IMessage>>(GetModels());
        }

        IEnumerable<DiscoveredModel> GetModels()
        {
            yield return new DiscoveredModel(typeof(RabbitMqSettings), typeof(RabbitMqSettings), ServiceLifetime.Singleton);
            yield return new DiscoveredModel(typeof(IConnectionFactory), typeof(RabbitMqConnectionFactory), ServiceLifetime.Singleton);
            yield return new DiscoveredModel(typeof(IPublisher<>), typeof(RabbitMqPublisher<>), ServiceLifetime.Singleton);
        }
    }
}

using System.Collections.Generic;
using Elders.Cronus.Discoveries;
using Microsoft.Extensions.DependencyInjection;
using RabbitMQ.Client;

namespace Elders.Cronus.Transport.RabbitMQ
{
    public class RabbitMqPublisherDiscovery : DiscoveryBasedOnExecutingDirAssemblies<IPublisher<IMessage>>
    {
        protected override DiscoveryResult<IPublisher<IMessage>> DiscoverFromAssemblies(DiscoveryContext context)
        {
            return new DiscoveryResult<IPublisher<IMessage>>(GetModels());
        }

        IEnumerable<DiscoveredModel> GetModels()
        {
            yield return new DiscoveredModel(typeof(RabbitMqSettings), typeof(RabbitMqSettings), ServiceLifetime.Singleton);
            yield return new DiscoveredModel(typeof(IConnectionFactory), typeof(RabbitMqConnectionFactory), ServiceLifetime.Singleton);

            var publisherModel = new DiscoveredModel(typeof(IPublisher<>), typeof(RabbitMqPublisher<>), ServiceLifetime.Singleton);
            publisherModel.CanOverrideDefaults = true;
            yield return publisherModel;
        }
    }
}

Mark IPublisher<> descriptor as overrider


using Newtonsoft.Json;

namespace TicketTimer.Core.Infrastructure
{
    public class JsonWorkItemStore : WorkItemStore
    {
        private readonly FileStore _fileStore;
        private const string FileName = "timer.state";
        private TimerState _state;

        public JsonWorkItemStore(FileStore fileStore)
        {
            _fileStore = fileStore;
            Load();
        }

        public void AddToArchive(WorkItem workItem)
        {
            GetState().WorkItemArchive.Add(workItem);
            Save();
        }

        public TimerState GetState()
        {
            if (_state == null)
            {
                Load();
            }
            return _state;
        }

        public void Save()
        {
            var json = JsonConvert.SerializeObject(_state);
            _fileStore.WriteFile(json, FileName);
        }

        private void Load()
        {
            var json = _fileStore.ReadFile(FileName);
            if (!string.IsNullOrEmpty(json))
            {
                _state = JsonConvert.DeserializeObject<TimerState>(json);
            }
            else
            {
                _state = new TimerState();
            }
        }

        public void SetCurrent(WorkItem workItem)
        {
            GetState().CurrentWorkItem = workItem;
            Save();
        }

        public void ClearArchive()
        {
            GetState().WorkItemArchive.Clear();
            Save();
        }
    }
}

using Newtonsoft.Json;

namespace TicketTimer.Core.Infrastructure
{
    public class JsonWorkItemStore : WorkItemStore
    {
        private readonly FileStore _fileStore;
        private const string FileName = "timer.state";
        private TimerState _state;

        public JsonWorkItemStore(FileStore fileStore)
        {
            _fileStore = fileStore;
            Load();
        }

        public void AddToArchive(WorkItem workItem)
        {
            GetState().WorkItemArchive.Add(workItem);
            Save();
        }

        public TimerState GetState()
        {
            if (_state == null)
            {
                Load();
            }
            return _state;
        }

        public void Save()
        {
            var json = JsonConvert.SerializeObject(_state, Formatting.Indented);
            _fileStore.WriteFile(json, FileName);
        }

        private void Load()
        {
            var json = _fileStore.ReadFile(FileName);
            if (!string.IsNullOrEmpty(json))
            {
                _state = JsonConvert.DeserializeObject<TimerState>(json);
            }
            else
            {
                _state = new TimerState();
            }
        }

        public void SetCurrent(WorkItem workItem)
        {
            GetState().CurrentWorkItem = workItem;
            Save();
        }

        public void ClearArchive()
        {
            GetState().WorkItemArchive.Clear();
            Save();
        }
    }
}

[master] Write JSON as prettified string to file for better readability.


using System.Reflection;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("CakeMail.RestClient")]
[assembly: AssemblyDescription("CakeMail.RestClient is a .NET wrapper for the CakeMail API")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jeremie Desautels")]
[assembly: AssemblyProduct("CakeMail.RestClient")]
[assembly: AssemblyCopyright("Copyright Jeremie Desautels © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0-alpha01")]

using System.Reflection;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("CakeMail.RestClient")]
[assembly: AssemblyDescription("CakeMail.RestClient is a .NET wrapper for the CakeMail API")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jeremie Desautels")]
[assembly: AssemblyProduct("CakeMail.RestClient")]
[assembly: AssemblyCopyright("Copyright Jeremie Desautels © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0-beta01")]

Increase assembly version to 'beta01'

Increase assembly version to 'beta01'


using Rainbow.Model;

namespace Rainbow.Diff.Fields
{
	public class DefaultComparison : IFieldComparer
	{
		public bool CanCompare(IItemFieldValue field1, IItemFieldValue field2)
		{
			return field1 != null && field2 != null;
		}

		public bool AreEqual(IItemFieldValue field1, IItemFieldValue field2)
		{
			if (field1.Value == null || field2.Value == null) return false;

			if (field1.BlobId.HasValue && field2.BlobId.HasValue) return field1.BlobId.Value.Equals(field2.BlobId.Value);

			return field1.Value.Equals(field2.Value);
		}
	}
}

using Rainbow.Model;

namespace Rainbow.Diff.Fields
{
	public class DefaultComparison : IFieldComparer
	{
		public bool CanCompare(IItemFieldValue field1, IItemFieldValue field2)
		{
			return field1 != null && field2 != null;
		}

		public bool AreEqual(IItemFieldValue field1, IItemFieldValue field2)
		{
			if (field1.BlobId.HasValue && field2.BlobId.HasValue) return field1.BlobId.Value.Equals(field2.BlobId.Value);

			var field1Value = field1.Value;
			var field2Value = field2.Value;

			if (field1Value == null || field2Value == null) return false;

			return field1Value.Equals(field2Value);
		}
	}
}

Improve comparison order to avoid reading blob values by mistake


namespace Simple.Web.Behaviors.Implementations
{
    using MediaTypeHandling;
    using Behaviors;
    using Http;

    /// <summary>
    /// This type supports the framework directly and should not be used from your code.
    /// </summary>
    public static class SetInput
    {
        /// <summary>
        /// This method supports the framework directly and should not be used from your code
        /// </summary>
        /// <typeparam name="T">The input model type.</typeparam>
        /// <param name="handler">The handler.</param>
        /// <param name="context">The context.</param>
        public static void Impl<T>(IInput<T> handler, IContext context)
        {
        	if (context.Request.InputStream.Length == 0) return;

            var mediaTypeHandlerTable = new MediaTypeHandlerTable();
            var mediaTypeHandler = mediaTypeHandlerTable.GetMediaTypeHandler(context.Request.GetContentType());
            handler.Input = (T)mediaTypeHandler.Read(context.Request.InputStream, typeof(T));
        }
    }
}

namespace Simple.Web.Behaviors.Implementations
{
    using MediaTypeHandling;
    using Behaviors;
    using Http;

    /// <summary>
    /// This type supports the framework directly and should not be used from your code.
    /// </summary>
    public static class SetInput
    {
        /// <summary>
        /// This method supports the framework directly and should not be used from your code
        /// </summary>
        /// <typeparam name="T">The input model type.</typeparam>
        /// <param name="handler">The handler.</param>
        /// <param name="context">The context.</param>
        public static void Impl<T>(IInput<T> handler, IContext context)
        {
            if (context.Request.InputStream.CanSeek && context.Request.InputStream.Length == 0)
            {
                return;
            }

            var mediaTypeHandlerTable = new MediaTypeHandlerTable();
            var mediaTypeHandler = mediaTypeHandlerTable.GetMediaTypeHandler(context.Request.GetContentType());
            handler.Input = (T)mediaTypeHandler.Read(context.Request.InputStream, typeof(T));
        }
    }
}

Check InputStream on when seekable.

Check InputStream on when seekable.


namespace Application.Business.Models
{
    using System.ComponentModel.DataAnnotations;

    public class ResetPasswordFromMailModel
    {
        [Required]
        [DataType(DataType.EmailAddress)]
        [Display(Name = "Email")]
        public string Email { get; set; }

        [Required]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }

        [Required]
        [DataType(DataType.Password)]
        [Display(Name = "Confirm password")]
        [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
        public string ConfirmPassword { get; set; }

        [Required]
        [Display(Name = "Token")]
        public string Token { get; set; }
    }
}

namespace Application.Business.Models
{
    using System.ComponentModel.DataAnnotations;

    public class ResetPasswordFromMailModel
    {
        [Required]
        [DataType(DataType.EmailAddress)]
        [Display(Name = "Email")]
        public string Email { get; set; }

        [Required]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }

        [Required]
        [DataType(DataType.Password)]
        [Display(Name = "Confirm password")]
        [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
        public string ConfirmPassword { get; set; }

        [Display(Name = "Token")]
        public string Token { get; set; }
    }
}

Fix bug with require token field in register page


// Copyright (c) Martin Costello, 2015. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.

namespace MartinCostello.AdventOfCode.Puzzles.Y2016
{
    using Xunit;

    /// <summary>
    /// A class containing tests for the <see cref="Day16"/> class. This class cannot be inherited.
    /// </summary>
    public static class Day16Tests
    {
        [Theory]
        [InlineData("110010110100", 12, "100")]
        [InlineData("10000", 20, "01100")]
        public static void Y2016_Day16_GetDiskChecksum_Returns_Correct_Solution(string initial, int size, string expected)
        {
            // Act
            string actual = Day16.GetDiskChecksum(initial, size);

            // Assert
            Assert.Equal(expected, actual);
        }

        [Fact]
        public static void Y2016_Day16_Solve_Returns_Correct_Solution()
        {
            // Arrange
            string[] args = new[] { "10010000000110000", "272" };

            // Act
            var puzzle = PuzzleTestHelpers.SolvePuzzle<Day16>(args);

            // Assert
            Assert.Equal("10010110010011110", puzzle.Checksum);
        }
    }
}

// Copyright (c) Martin Costello, 2015. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.

namespace MartinCostello.AdventOfCode.Puzzles.Y2016
{
    using Xunit;

    /// <summary>
    /// A class containing tests for the <see cref="Day16"/> class. This class cannot be inherited.
    /// </summary>
    public static class Day16Tests
    {
        [Theory]
        [InlineData("110010110100", 12, "100")]
        [InlineData("10000", 20, "01100")]
        public static void Y2016_Day16_GetDiskChecksum_Returns_Correct_Solution(string initial, int size, string expected)
        {
            // Act
            string actual = Day16.GetDiskChecksum(initial, size);

            // Assert
            Assert.Equal(expected, actual);
        }

        [Theory]
        [InlineData("272", "10010110010011110")]
        [InlineData("35651584", "01101011101100011")]
        public static void Y2016_Day16_Solve_Returns_Correct_Solution(string size, string expected)
        {
            // Arrange
            string[] args = new[] { "10010000000110000", size };

            // Act
            var puzzle = PuzzleTestHelpers.SolvePuzzle<Day16>(args);

            // Assert
            Assert.Equal(expected, puzzle.Checksum);
        }
    }
}

Solve day 16 part 2

Solve day 16 part 2

Extend the tests to solve part 2 of the puzzle for day 16.


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

#nullable enable

using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Sprites;
using osu.Game.Graphics;
using osu.Game.Graphics.UserInterface;
using osuTK;

namespace osu.Game.Overlays.Chat.ChannelList
{
    public class ChannelListItemCloseButton : OsuAnimatedButton
    {
        [BackgroundDependencyLoader]
        private void load(OsuColour osuColour)
        {
            Alpha = 0f;
            Size = new Vector2(20);
            Add(new SpriteIcon
            {
                Anchor = Anchor.Centre,
                Origin = Anchor.Centre,
                Scale = new Vector2(0.75f),
                Icon = FontAwesome.Solid.TimesCircle,
                RelativeSizeAxes = Axes.Both,
                Colour = osuColour.Red1,
            });
        }
    }
}

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

#nullable enable

using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Input.Events;
using osu.Game.Graphics;
using osu.Game.Graphics.Containers;
using osuTK;
using osuTK.Graphics;

namespace osu.Game.Overlays.Chat.ChannelList
{
    public class ChannelListItemCloseButton : OsuClickableContainer
    {
        private SpriteIcon icon = null!;

        private Color4 normalColour;
        private Color4 hoveredColour;

        [BackgroundDependencyLoader]
        private void load(OsuColour osuColour)
        {
            normalColour = osuColour.Red2;
            hoveredColour = Color4.White;

            Alpha = 0f;
            Size = new Vector2(20);
            Add(icon = new SpriteIcon
            {
                Anchor = Anchor.Centre,
                Origin = Anchor.Centre,
                Scale = new Vector2(0.75f),
                Icon = FontAwesome.Solid.TimesCircle,
                RelativeSizeAxes = Axes.Both,
                Colour = normalColour,
            });
        }

        // Transforms matching OsuAnimatedButton
        protected override bool OnHover(HoverEvent e)
        {
            icon.FadeColour(hoveredColour, 300, Easing.OutQuint);
            return base.OnHover(e);
        }

        protected override void OnHoverLost(HoverLostEvent e)
        {
            icon.FadeColour(normalColour, 300, Easing.OutQuint);
            base.OnHoverLost(e);
        }

        protected override bool OnMouseDown(MouseDownEvent e)
        {
            icon.ScaleTo(0.75f, 2000, Easing.OutQuint);
            return base.OnMouseDown(e);
        }

        protected override void OnMouseUp(MouseUpEvent e)
        {
            icon.ScaleTo(1, 1000, Easing.OutElastic);
            base.OnMouseUp(e);
        }
    }
}

Remove box surrounding close button

Remove box surrounding close button


// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE

using System.Linq;
using SQLite.Net.Attributes;

namespace osu.Game.Database
{
    public class BeatmapMetadata
    {
        [PrimaryKey, AutoIncrement]
        public int ID { get; set; }

        public int? OnlineBeatmapSetID { get; set; }

        public string Title { get; set; }
        public string TitleUnicode { get; set; }
        public string Artist { get; set; }
        public string ArtistUnicode { get; set; }
        public string Author { get; set; }
        public string Source { get; set; }
        public string Tags { get; set; }
        public int PreviewTime { get; set; }
        public string AudioFile { get; set; }
        public string BackgroundFile { get; set; }

        public string[] SearchableTerms => new[]
        {
            Artist,
            ArtistUnicode,
            Title,
            TitleUnicode,
            Source,
            Tags
        }.Where(s => !string.IsNullOrEmpty(s)).ToArray();
    }
}

// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE

using System.Linq;
using SQLite.Net.Attributes;

namespace osu.Game.Database
{
    public class BeatmapMetadata
    {
        [PrimaryKey, AutoIncrement]
        public int ID { get; set; }

        public int? OnlineBeatmapSetID { get; set; }

        public string Title { get; set; }
        public string TitleUnicode { get; set; }
        public string Artist { get; set; }
        public string ArtistUnicode { get; set; }
        public string Author { get; set; }
        public string Source { get; set; }
        public string Tags { get; set; }
        public int PreviewTime { get; set; }
        public string AudioFile { get; set; }
        public string BackgroundFile { get; set; }

        public string[] SearchableTerms => new[]
        {
            Author,
            Artist,
            ArtistUnicode,
            Title,
            TitleUnicode,
            Source,
            Tags
        }.Where(s => !string.IsNullOrEmpty(s)).ToArray();
    }
}

Add support for searching beatmap author at song select

Resolves #792


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using SIL.Windows.Forms.Widgets.BetterGrid;

namespace Glyssen.Controls
{
	//DataGridView with Enter moving to right (instead of down)
	public class DataGridViewOverrideEnter : BetterGrid
	{
		public DataGridViewOverrideEnter()
		{
			AllowUserToAddRows = true;
			MultiSelect = true;
		}

		protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
		{
			if (keyData == Keys.Enter)
			{
				MoveToNextField();
				return true;
			}

			return base.ProcessCmdKey(ref msg, keyData);
		}

		public void MoveToNextField()
		{
			int nextColumn, nextRow;

			if (CurrentCell.ColumnIndex + 1 < ColumnCount)
			{
				nextColumn = CurrentCell.ColumnIndex + 1;
				nextRow = CurrentCell.RowIndex;
			}
			else
			{
				nextColumn = 0;
				nextRow = CurrentCell.RowIndex + 1;
			}

			CurrentCell = Rows[nextRow].Cells[nextColumn];
		}

		private void InitializeComponent()
		{
			((System.ComponentModel.ISupportInitialize)(this)).BeginInit();
			this.SuspendLayout();
			((System.ComponentModel.ISupportInitialize)(this)).EndInit();
			this.ResumeLayout(false);

		}
	}
}

using System.Windows.Forms;
using SIL.Windows.Forms.Widgets.BetterGrid;

namespace Glyssen.Controls
{
	/// <summary>
	/// DataGridView with Enter moving to right (instead of down)
	/// </summary>
	public class DataGridViewOverrideEnter : BetterGrid
	{
		public DataGridViewOverrideEnter()
		{
			AllowUserToAddRows = true;
			MultiSelect = true;
		}

		protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
		{
			if (keyData == Keys.Enter)
			{
				MoveToNextField();
				return true;
			}

			return base.ProcessCmdKey(ref msg, keyData);
		}

		public void MoveToNextField()
		{
			int nextColumn, nextRow;

			if (CurrentCell.ColumnIndex + 1 < ColumnCount)
			{
				nextColumn = CurrentCell.ColumnIndex + 1;
				nextRow = CurrentCell.RowIndex;
			}
			else if (CurrentCell.RowIndex + 1 < RowCount)
			{
				nextColumn = 0;
				nextRow = CurrentCell.RowIndex + 1;
			}
			else
			{
				return;
			}

			CurrentCell = Rows[nextRow].Cells[nextColumn];
		}
	}
}

Fix bug when hitting Enter on last row (PG-234)


using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SpecialPower : MonoBehaviour {

    public float manaCost;
    public float coolDownDuration;
    public string button;
    public bool isBomb = false; //tmp

    [HideInInspector]
    public float mana;
    public float maxMana;

    public float coolDownTimer = 0;
    private ISpecialPower power;

    void Start () {
        power = GetComponent<ISpecialPower>();
        if(!isBomb) {
            maxMana = transform.parent.GetComponent<Player>().maxMana; //tmp
        }
        mana = maxMana;
        NotifyUI();
    }

	// Update is called once per frame
	void Update () {
        coolDownTimer -= Time.deltaTime;

        if(Input.GetButtonDown(button)) {
            if (coolDownTimer < 0 && mana >= manaCost) {
                power.Activate();
                coolDownTimer = coolDownDuration;
                mana -= manaCost;
                NotifyUI();
            }
            else {
                SoundManager.instance.PlaySound(GenericSoundsEnum.ERROR);
            }
        }
	}

    private void NotifyUI() {
        if (isBomb) {
            BombUI.instance.OnUsePower(this);
        }
        else {
            PowerUI.instance.OnUsePower(this);
        }
    }
}

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SpecialPower : MonoBehaviour {

    public float manaCost;
    public float coolDownDuration;
    public string button;
    public bool isBomb = false; //tmp

    [HideInInspector]
    public float mana;
    public float maxMana;

    public float coolDownTimer = 0;
    private ISpecialPower power;

    void Start () {
        power = GetComponent<ISpecialPower>();
        if(!isBomb) {
            maxMana = transform.parent.GetComponent<Player>().maxMana; //tmp
        }
        mana = maxMana;
        NotifyUI();
        enabled = false;
        EventDispatcher.AddEventListener(Events.GAME_LOADED, OnLoaded);
    }

    void OnDestroy() {
        EventDispatcher.RemoveEventListener(Events.GAME_LOADED, OnLoaded);
    }

    private void OnLoaded(object useless) {
        enabled = true;
    }

    // Update is called once per frame
    void Update () {
        coolDownTimer -= Time.deltaTime;

        if(Input.GetButtonDown(button)) {
            if (coolDownTimer < 0 && mana >= manaCost) {
                power.Activate();
                coolDownTimer = coolDownDuration;
                mana -= manaCost;
                NotifyUI();
            }
            else {
                SoundManager.instance.PlaySound(GenericSoundsEnum.ERROR);
            }
        }
	}

    private void NotifyUI() {
        if (isBomb) {
            BombUI.instance.OnUsePower(this);
        }
        else {
            PowerUI.instance.OnUsePower(this);
        }
    }
}

Fix press space to start game launch bomb


// Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE

using System;
using osu.Framework.Graphics.Containers;
using System.Linq;

namespace osu.Framework.Graphics.Performance
{
    class PerformanceOverlay : FlowContainer, IStateful<FrameStatisticsMode>
    {
        private FrameStatisticsMode state;

        public FrameStatisticsMode State
        {
            get
            {
                return state;
            }

            set
            {
                if (state == value) return;

                state = value;

                switch (state)
                {
                    case FrameStatisticsMode.None:
                        FadeOut(100);
                        break;
                    case FrameStatisticsMode.Minimal:
                    case FrameStatisticsMode.Full:
                        FadeIn(100);
                        foreach (FrameStatisticsDisplay d in Children.Cast<FrameStatisticsDisplay>())
                            d.State = state;
                        break;
                }
            }
        }

        public override void Load(BaseGame game)
        {
            base.Load(game);

            Add(new FrameStatisticsDisplay(@"Input", game.Host.InputMonitor));
            Add(new FrameStatisticsDisplay(@"Update", game.Host.UpdateMonitor));
            Add(new FrameStatisticsDisplay(@"Draw", game.Host.DrawMonitor));

            Direction = FlowDirection.VerticalOnly;
        }
    }

    public enum FrameStatisticsMode
    {
        None,
        Minimal,
        Full
    }
}

// Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE

using System;
using osu.Framework.Graphics.Containers;
using System.Linq;

namespace osu.Framework.Graphics.Performance
{
    class PerformanceOverlay : FlowContainer, IStateful<FrameStatisticsMode>
    {
        private FrameStatisticsMode state;

        public FrameStatisticsMode State
        {
            get
            {
                return state;
            }

            set
            {
                if (state == value) return;

                state = value;

                switch (state)
                {
                    case FrameStatisticsMode.None:
                        FadeOut(100);
                        break;
                    case FrameStatisticsMode.Minimal:
                    case FrameStatisticsMode.Full:
                        FadeIn(100);
                        break;
                }

                foreach (FrameStatisticsDisplay d in Children.Cast<FrameStatisticsDisplay>())
                    d.State = state;
            }
        }

        public override void Load(BaseGame game)
        {
            base.Load(game);

            Add(new FrameStatisticsDisplay(@"Input", game.Host.InputMonitor));
            Add(new FrameStatisticsDisplay(@"Update", game.Host.UpdateMonitor));
            Add(new FrameStatisticsDisplay(@"Draw", game.Host.DrawMonitor));

            Direction = FlowDirection.VerticalOnly;
        }
    }

    public enum FrameStatisticsMode
    {
        None,
        Minimal,
        Full
    }
}

Fix overlay hide animation playing at the wrong point in time.


using AutoMapper;
using Castle.MicroKernel.Registration;
using Castle.MicroKernel.SubSystems.Configuration;
using Castle.Windsor;

namespace Snittlistan.Installers
{
	public class AutoMapperInstaller : IWindsorInstaller
	{
		public void Install(IWindsorContainer container, IConfigurationStore store)
		{
			container.Register(FindProfiles().LifestyleSingleton());
		}

		private static BasedOnDescriptor FindProfiles()
		{
			return AllTypes
				.FromThisAssembly()
				.BasedOn<Profile>();
		}
	}
}

using AutoMapper;
using Castle.MicroKernel.Registration;
using Castle.MicroKernel.SubSystems.Configuration;
using Castle.Windsor;

namespace Snittlistan.Installers
{
	public class AutoMapperInstaller : IWindsorInstaller
	{
		public void Install(IWindsorContainer container, IConfigurationStore store)
		{
			container.Register(FindProfiles().LifestyleSingleton().WithServiceFromInterface(typeof(Profile)));
		}

		private static BasedOnDescriptor FindProfiles()
		{
			return AllTypes
				.FromThisAssembly()
				.BasedOn<Profile>();
		}
	}
}

Correct installation of AutoMapper profiles


#region License

/*
    Copyright [2011] [Jeffrey Cameron]

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

#endregion

using System;
using System.ComponentModel;

namespace PicklesDoc.Pickles
{
    public enum DocumentationFormat
    {
        [Description("HTML")]
        Html,

        [Description("Microsoft Word OpenXML (.docx)")]
        Word,

        [Description("Darwin Information Typing Architecture (DITA)")]
        Dita,

        [Description("Javascript Object Notation (JSON)")]
        JSON,

        [Description("Microsoft Excel OpenXML (.xlsx)")]
        Excel,
        DHtml
    }
}

#region License

/*
    Copyright [2011] [Jeffrey Cameron]

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

#endregion

using System;
using System.ComponentModel;

namespace PicklesDoc.Pickles
{
    public enum DocumentationFormat
    {
        [Description("HTML")]
        Html,

        [Description("Microsoft Word OpenXML (.docx)")]
        Word,

        [Description("Darwin Information Typing Architecture (DITA)")]
        Dita,

        [Description("Javascript Object Notation (JSON)")]
        JSON,

        [Description("Microsoft Excel OpenXML (.xlsx)")]
        Excel,

        [Description("HTML w/search")]
        DHtml
    }
}

Add annotation to DHtml enum

Add annotation to DHtml enum

So it will provide a bit more context


using System;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            new GrammarParser(null);
        }
    }
}

using System;

[assembly: CLSCompliant(true)]

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            new GrammarParser(null);
        }
    }
}

Clean up warnings where preparing AntlrGeneratedFiles test project