/*
 * Copyright (c) Contributors, http://opensimulator.org/
 * See CONTRIBUTORS.TXT for a full list of copyright holders.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the OpenSimulator Project nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

using System;
using System.Reflection;
using System.Threading;
using NUnit.Framework;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Tests.Common;
using OpenSim.Tests.Common.Mock;

namespace OpenSim.Region.Framework.Scenes.Tests
{
    /// <summary>
    /// Spatial scene object tests (will eventually cover root and child part position, rotation properties, etc.)
    /// </summary>
    [TestFixture]
    public class SceneObjectSpatialTests
    {
        [Test]
        public void TestGetRootPartPosition()
        {
            TestHelpers.InMethod();

            Scene scene = SceneHelpers.SetupScene();
            UUID ownerId = TestHelpers.ParseTail(0x1);
            Vector3 partPosition = new Vector3(10, 20, 30);

            SceneObjectGroup so
                = SceneHelpers.CreateSceneObject(1, ownerId, "obj1", 0x10);
            so.AbsolutePosition = partPosition;
            scene.AddNewSceneObject(so, false);

            Assert.That(so.AbsolutePosition, Is.EqualTo(partPosition));
            Assert.That(so.RootPart.AbsolutePosition, Is.EqualTo(partPosition));
        }
    }
}

Add very basic TestGetRootPartPosition() test


namespace FakeItEasy.Tools
{
    using System;
    using System.Collections.Generic;
    using System.Globalization;
    using System.Text.RegularExpressions;
    using Octokit;

    public static class ReleaseHelpers
    {
        public static ICollection<int> GetIssueNumbersReferencedFromReleases(IEnumerable<Release> releases)
        {
            // Release bodies should contain references to fixed issues in the form
            // (#1234), or (#1234, #1235, #1236) if multiple issues apply to a topic.
            // It's hard (impossible?) to harvest values from a repeated capture group,
            // so grab everything between the ()s and split manually.
            var issuesReferencedFromRelease = new HashSet<int>();
            foreach (var release in releases)
            {
                foreach (Match match in Regex.Matches(release.Body, @"\((?<issueNumbers>#[0-9]+((, )#[0-9]+)*)\)"))
                {
                    var issueNumbers = match.Groups["issueNumbers"].Value;
                    foreach (var issueNumber in issueNumbers.Split(new[] { '#', ' ', ',' }, StringSplitOptions.RemoveEmptyEntries))
                    {
                        issuesReferencedFromRelease.Add(int.Parse(issueNumber, NumberStyles.Integer, NumberFormatInfo.InvariantInfo));
                    }
                }
            }

            return issuesReferencedFromRelease;
        }
    }
}

namespace FakeItEasy.Tools
{
    using System.Collections.Generic;
    using System.Globalization;
    using System.Text.RegularExpressions;
    using Octokit;

    public static class ReleaseHelpers
    {
        public static ICollection<int> GetIssueNumbersReferencedFromReleases(IEnumerable<Release> releases)
        {
            var issuesReferencedFromRelease = new HashSet<int>();
            foreach (var release in releases)
            {
                foreach (Match match in Regex.Matches(release.Body, @"\(\s*#(?<issueNumber>[0-9]+)(,\s*#(?<issueNumber>[0-9]+))*\s*\)"))
                {
                    foreach (Capture capture in match.Groups["issueNumber"].Captures)
                    {
                        issuesReferencedFromRelease.Add(int.Parse(capture.Value, NumberStyles.Integer, NumberFormatInfo.InvariantInfo));
                    }
                }
            }

            return issuesReferencedFromRelease;
        }
    }
}

Improve parsing of issues in release notes


using System;
using Xunit;

namespace NQuery.Tests.Evaluation
{
    public class EvaluationTest
    {
        protected void AssertProduces<T>(string text, T[] expected)
        {
            var expectedColumns = new[] { typeof(T) };
            var expectedRows = new object[expected.Length][];

            for (var i = 0; i < expected.Length; i++)
                expectedRows[i] = new object[] { expected[i] };

            AssertProduces(text, expectedColumns, expectedRows);
        }

        protected void AssertProduces<T1, T2>(string text, (T1, T2)[] expected)
        {
            var expectedColumns = new[] { typeof(T1), typeof(T2) };
            var expectedRows = new object[expected.Length][];

            for (var i = 0; i < expected.Length; i++)
                expectedRows[i] = new object[] { expected[i].Item1, expected[i].Item2 };

            AssertProduces(text, expectedColumns, expectedRows);
        }

        private void AssertProduces(string text, Type[] expectedColumns, object[][] expectedRows)
        {
            var dataContext = NorthwindDataContext.Instance;
            var query = Query.Create(dataContext, text);
            using (var data = query.ExecuteReader())
            {
                Assert.Equal(expectedColumns.Length, data.ColumnCount);

                for (var i = 0; i < expectedColumns.Length; i++)
                    Assert.Equal(expectedColumns[i], data.GetColumnType(i));

                var rowIndex = 0;

                while (data.Read())
                {
                    var expectedRow = expectedRows[rowIndex];

                    for (var columnIndex = 0; columnIndex < expectedColumns.Length; columnIndex++)
                        Assert.Equal(expectedRow[columnIndex], data[columnIndex]);

                    rowIndex++;
                }
            }
        }
    }
}

Add ability to run evaluation tests

Add ability to run evaluation tests

This allows to define the expected data as arrays of scalars or tuples and
then assert that the data matches.


using System;
using System.Collections.Generic;
using System.Text;
using SadConsole.Input;
using SadRogue.Primitives;

namespace SadConsole.Components
{
    /// <summary>
    /// Tints a surface when that surface would use the mouse. Helps debug which object is receiving mouse input as you move the mouse around.
    /// </summary>
    public class MouseTint : UpdateComponent
    {
        IScreenObject _previous;
        SadConsole.Input.Mouse _mouse;

        /// <inheritdoc/>
        public override void OnAdded(IScreenObject host)
        {
            _mouse = new SadConsole.Input.Mouse();
            _mouse.Update(TimeSpan.Zero);
        }

        /// <inheritdoc/>
        public override void Update(IScreenObject host, TimeSpan delta)
        {
            _mouse.Update(delta);

            // Build a list of all screen objects
            var screenObjects = new List<IScreenObject>();
            GetConsoles(GameHost.Instance.Screen, ref screenObjects);

            // Process top-most screen objects first.
            screenObjects.Reverse();

            for (int i = 0; i < screenObjects.Count; i++)
            {
                var state = new MouseScreenObjectState(screenObjects[i], _mouse);

                if (screenObjects[i].IsVisible && screenObjects[i].UseMouse && state.IsOnScreenObject)
                {
                    if (_previous != null && _previous != screenObjects[i])
                        if (_previous is IScreenSurface prevSurface)
                            prevSurface.Tint = Color.Transparent;

                    _previous = screenObjects[i];

                    if (_previous is IScreenSurface newSurface)
                        newSurface.Tint = Color.Purple.SetAlpha(128);

                    break;
                }
            }
        }

        private void GetConsoles(IScreenObject screen, ref List<IScreenObject> list)
        {
            if (!screen.IsVisible) return;

            if (screen.UseMouse)
                list.Add(screen);

            foreach (IScreenObject child in screen.Children)
                GetConsoles(child, ref list);
        }
    }
}

Add mouse tint debug component

[ext] Add mouse tint debug component


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

namespace A2BBAPI.Utils
{
    /// <summary>
    /// Class holding info for device linking.
    /// </summary>
    public class LinkHolder
    {
        #region Public properties
        /// <summary>
        /// The device to link.
        /// </summary>
        public Device Device { get; set; }

        /// <summary>
        /// The user username.
        /// </summary>
        public string Username { get; set; }

        /// <summary>
        /// The user password.
        /// </summary>
        public string Password { get; set; }

        /// <summary>
        /// The user subject id.
        /// </summary>
        public string Subject { get; set; }

        /// <summary>
        /// Whether the link has been actually estabilished or not.
        /// </summary>
        public bool IsEstabilished { get; set; }
        #endregion
    }
}

Add utils class which holds temporary linking info between user-device.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;

namespace ExpressionToCodeLib
{
    [Obsolete(
        "This class is *not* the base class of all assertion violation exceptions - don't rely on it!  It will be removed in version 2."
        ), Serializable]
    public class PAssertFailedException : Exception
    {
        public PAssertFailedException(string message)
            : base(message) { }

        public PAssertFailedException(string message, Exception inner)
            : base(message, inner) { }

        public PAssertFailedException(SerializationInfo info, StreamingContext context)
            : base(info, context) { }
    }
#pragma warning disable 618
    [Serializable]
    sealed class AssertFailedException : PAssertFailedException
#pragma warning restore 618
    {
        public AssertFailedException(string message)
            : base(message) { }

        public AssertFailedException(string message, Exception inner)
            : base(message, inner) { }

        public AssertFailedException(SerializationInfo info, StreamingContext context)
            : base(info, context) { }
    }

    namespace Internal
    {
        /// <summary>
        /// This class is not part of the public API: it's undocumented and minor version bumps may break compatiblity.
        /// </summary>
        public static class UnitTestingInternalsAccess
        {
            public static Exception CreateException(string msg) { return new AssertFailedException(msg); }
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;

namespace ExpressionToCodeLib
{
    [Serializable]
    sealed class AssertFailedException : Exception
    {
        public AssertFailedException(string message)
            : base(message) { }

        public AssertFailedException(string message, Exception inner)
            : base(message, inner) { }

        public AssertFailedException(SerializationInfo info, StreamingContext context)
            : base(info, context) { }
    }

    namespace Internal
    {
        /// <summary>
        /// This class is not part of the public API: it's undocumented and minor version bumps may break compatiblity.
        /// </summary>
        public static class UnitTestingInternalsAccess
        {
            public static Exception CreateException(string msg) { return new AssertFailedException(msg); }
        }
    }
}

Drop PAssertException from public api

Drop PAssertException from public api


using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Porthor.Models;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Xunit;

namespace Porthor.Tests
{
    public class ContentDefinitionTests
    {
        [Fact]
        public async Task Request_WithInvalidMediaType_ReturnsUnsupportedMediaType()
        {
            // Arrange
            var builder = new WebHostBuilder()
                .ConfigureServices(services =>
                {
                    services.AddPorthor(options =>
                    {
                        options.Content.ValidationEnabled = true;
                    });
                })
                .Configure(app =>
                {
                    var resource = new Resource
                    {
                        Method = HttpMethod.Post,
                        Path = "api/v5.1/data",
                        ContentDefinitions = new List<ContentDefinition>
                        {
                            new ContentDefinition{ MediaType = PorthorConstants.MediaType.Json }
                        },
                        EndpointUrl = $"http://example.org/api/v5.1/data"
                    };

                    app.UsePorthor(new[] { resource });
                });
            var server = new TestServer(builder);

            // Act
            var requestMessage = new HttpRequestMessage(HttpMethod.Post, "api/v5.1/data");
            requestMessage.Content = new StringContent("Request Body");
            var responseMessage = await server.CreateClient().SendAsync(requestMessage);

            // Assert
            Assert.Equal(HttpStatusCode.UnsupportedMediaType, responseMessage.StatusCode);
        }

        [Fact]
        public async Task Request_WithValidMediaType_ReturnsOk()
        {
            // Arrange
            var builder = new WebHostBuilder()
                .ConfigureServices(services =>
                {
                    services.AddPorthor(options =>
                    {
                        options.BackChannelMessageHandler = new TestMessageHandler
                        {
                            Sender = request =>
                            {
                                var response = new HttpResponseMessage(HttpStatusCode.OK);
                                return response;
                            }
                        };
                        options.Content.ValidationEnabled = true;
                    });
                })
                .Configure(app =>
                {
                    var resource = new Resource
                    {
                        Method = HttpMethod.Post,
                        Path = "api/v5.2/data",
                        ContentDefinitions = new List<ContentDefinition>
                        {
                            new ContentDefinition{ MediaType = PorthorConstants.MediaType.Json }
                        },
                        EndpointUrl = $"http://example.org/api/v5.2/data"
                    };

                    app.UsePorthor(new[] { resource });
                });
            var server = new TestServer(builder);

            // Act
            var requestMessage = new HttpRequestMessage(HttpMethod.Post, "api/v5.2/data");
            requestMessage.Content = new StringContent("{ \"name\": \"demo\" }", Encoding.UTF8, PorthorConstants.MediaType.Json);
            var responseMessage = await server.CreateClient().SendAsync(requestMessage);

            // Assert
            Assert.Equal(HttpStatusCode.OK, responseMessage.StatusCode);
        }
    }
}

Add content media type tests

Add content media type tests


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

namespace LBD2OBJ.Types
{
	class FixedPoint
	{
		public int IntegralPart { get; set; }
		public int DecimalPart { get; set; }

		public FixedPoint(byte[] data)
		{
			if (data.Length != 2) { throw new ArgumentException("data must be 2 bytes", "data"); }

			byte[] _data = new byte[2];
			data.CopyTo(_data, 0);

			var signMask = (byte)128;
			var integralMask = (byte)112;
			var firstPartOfDecimalMask = (byte)15;

			bool isNegative = (_data[0] & signMask) == 128;
			int integralPart = (_data[0] & integralMask) * (isNegative ? -1 : 1);
			int decimalPart = (_data[0] & firstPartOfDecimalMask);
			decimalPart <<= 8;
			decimalPart += data[1];

			IntegralPart = integralPart;
			DecimalPart = decimalPart;
		}
	}
}

Add class for fixed point data

Add class for fixed point data


using System.Drawing;
using JetBrains.Application.UI.Controls.JetPopupMenu;
using JetBrains.Diagnostics;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Feature.Services.Occurrences;
using JetBrains.ReSharper.Feature.Services.Presentation;
using JetBrains.ReSharper.Plugins.Unity.AsmDef.Psi.Caches;
using JetBrains.ReSharper.Plugins.Unity.AsmDef.Psi.DeclaredElements;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Resources.Shell;
using JetBrains.UI.Icons;
using JetBrains.UI.RichText;

namespace JetBrains.ReSharper.Plugins.Unity.AsmDef.Feature.Services.Occurrences
{
    // Used to present an occurrence. Surprisingly, used by (at least) Rider when double clicking on an element used as
    // a target in a find usage. All occurrences are added to a menu, presented but the menu will automatically click
    // a single entry. If there's no presenter, the element appears disabled, and can't be clicked.
    [OccurrencePresenter(Priority = 4.0)]
    public class AsmDefNameOccurrencePresenter : IOccurrencePresenter
    {
        public bool IsApplicable(IOccurrence occurrence) => occurrence is AsmDefNameOccurrence;

        public bool Present(IMenuItemDescriptor descriptor, IOccurrence occurrence,
                            OccurrencePresentationOptions options)
        {
            if (occurrence is not AsmDefNameOccurrence asmDefNameOccurrence)
                return false;

            var solution = occurrence.GetSolution().NotNull("occurrence.GetSolution() != null");
            var cache = solution.GetComponent<AsmDefNameCache>();

            descriptor.Text = asmDefNameOccurrence.Name;
            if (options.IconDisplayStyle != IconDisplayStyle.NoIcon)
                descriptor.Icon = GetIcon(solution, asmDefNameOccurrence, options);

            var fileName = cache.GetPathFor(asmDefNameOccurrence.Name);
            if (fileName != null && !fileName.IsEmpty)
            {
                var style = TextStyle.FromForeColor(SystemColors.GrayText);
                descriptor.ShortcutText = new RichText($" in {fileName.Name}", style);
                descriptor.TailGlyph = AsmDefDeclaredElementType.AsmDef.GetImage();
            }
            descriptor.Style = MenuItemStyle.Enabled;
            return true;
        }

        private static IconId GetIcon(ISolution solution,
                                      AsmDefNameOccurrence asmDefNameOccurrence,
                                      OccurrencePresentationOptions options)
        {
            var presentationService = asmDefNameOccurrence.SourceFile.GetPsiServices()
                .GetComponent<PsiSourceFilePresentationService>();
            switch (options.IconDisplayStyle)
            {
                case IconDisplayStyle.OccurrenceKind:
                    return OccurrencePresentationUtil.GetOccurrenceKindImage(asmDefNameOccurrence, solution).Icon;

                case IconDisplayStyle.File:
                    var iconId = presentationService.GetIconId(asmDefNameOccurrence.SourceFile);
                    if (iconId == null)
                    {
                        var projectFile = asmDefNameOccurrence.SourceFile.ToProjectFile();
                        if (projectFile != null)
                        {
                            iconId = Shell.Instance.GetComponent<ProjectModelElementPresentationService>()
                                .GetIcon(projectFile);
                        }
                    }

                    if (iconId == null)
                        iconId = AsmDefDeclaredElementType.AsmDef.GetImage();

                    return iconId;

                default:
                    return AsmDefDeclaredElementType.AsmDef.GetImage();
            }
        }
    }
}

Add presenter for asmdef occurrences

Add presenter for asmdef occurrences


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

namespace Recipe.Web
{
    public enum ResponseCategories
    {
        Unknown,
        Informational,
        Success,
        Redirected,
        ClientError,
        ServerError
    }

    public class ResponseStatusHandling
    {
        public static ResponseCategories CategorizeResponse(HttpWebResponse httpResponse)
        {
            int statusCode = (int) httpResponse.StatusCode;
            if (statusCode>=100&&statusCode<=199)
            {
                return ResponseCategories.Informational;
            }
            else if (statusCode >= 200 && statusCode <= 299)
            {
                return ResponseCategories.Success;
            }
            else if (statusCode >= 300 && statusCode <= 399)
            {
                return ResponseCategories.Redirected;
            }
            else if (statusCode >= 400 && statusCode <= 499)
            {
                return ResponseCategories.ClientError;
            }
            else if (statusCode >= 500 && statusCode <= 599)
            {
                return ResponseCategories.ServerError;
            }

            return ResponseCategories.Unknown;
        }
    }
}

Add web response status handling

Add web response status handling


using Glimpse.Core2.Extensibility;

namespace Glimpse.Core2.ClientScript
{
    public class Metadata:IDynamicClientScript
    {
        public ScriptOrder Order
        {
            get { return ScriptOrder.IncludeAfterClientInterfaceScript; }
        }

        public string GetResourceName()
        {
            return Resource.Metadata.InternalName;
        }
    }
}

using Glimpse.Core2.Extensibility;

namespace Glimpse.Core2.ClientScript
{
    public class Metadata:IDynamicClientScript
    {
        public ScriptOrder Order
        {
            get { return ScriptOrder.RequestMetadataScript; }
        }

        public string GetResourceName()
        {
            return Resource.Metadata.InternalName;
        }
    }
}

Switch over metadata to use its own script order reference


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

public class MainCamera : MonoBehaviour {

	public GameObject cursor;
	private IEnumerator currentMove;

	// Use this for initialization
	void Start () {

	}

	// Update is called once per frame
	void Update () {
		//this.transform.position.z = -10; //NO
	}

	public void scootTo(Vector3 endpos) {
		if (currentMove != null) {
			//if we're moving, fuck that
			StopCoroutine (currentMove);
		}
		Debug.Log ("Scoot TO:"); Debug.Log(endpos);
		currentMove = SmoothMove (this.transform.position, endpos, 5.0);
		StartCoroutine (currentMove);
	}

	IEnumerator SmoothMove(Vector3 startpos, Vector3 endpos, double seconds) {
		double t = 0.0;
		endpos.z = this.transform.position.z; //NEVER move forward or backward (Hack because we are in 2D)
		while ( t <= 1.0 ) {
			//Debug.Log ("t=" + t);
			t += Time.deltaTime/seconds;
			transform.position = Vector3.Lerp(startpos, endpos, Mathf.SmoothStep((float) 0.0, (float) 1.0, (float) t));
			//Debug.Log (transform.position);
			yield return null; //WHY
		}
	}
}

Add the ability to scoot the camera

Add the ability to scoot the camera


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

using System;
using System.Collections.Generic;
using System.Linq;
using osu.Game.Rulesets.Scoring;

namespace osu.Game.Screens.Ranking.Statistics
{
    /// <summary>
    /// Displays the unstable rate statistic for a given play.
    /// </summary>
    public class UnstableRate : SimpleStatisticItem<double>
    {
        /// <summary>
        /// Creates and computes an <see cref="UnstableRate"/> statistic.
        /// </summary>
        /// <param name="hitEvents">Sequence of <see cref="HitEvent"/>s to calculate the unstable rate based on.</param>
        public UnstableRate(IEnumerable<HitEvent> hitEvents)
            : base("Unstable Rate")
        {
            var timeOffsets = hitEvents.Select(ev => ev.TimeOffset).ToArray();
            Value = 10 * standardDeviation(timeOffsets);
        }

        private static double standardDeviation(double[] timeOffsets)
        {
            if (timeOffsets.Length == 0)
                return double.NaN;

            var mean = timeOffsets.Average();
            var squares = timeOffsets.Select(offset => Math.Pow(offset - mean, 2)).Sum();
            return Math.Sqrt(squares / timeOffsets.Length);
        }

        protected override string DisplayValue(double value) => double.IsNaN(value) ? "(not available)" : value.ToString("N2");
    }
}

Add component for unstable rate statistic


/*
 * Copyright (c) Contributors, http://opensimulator.org/
 * See CONTRIBUTORS.TXT for a full list of copyright holders.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the OpenSimulator Project nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
using NUnit.Framework;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using OpenSim.Tests.Common;
using OpenSim.Tests.Common.Mock;

namespace OpenSim.Region.Framework.Scenes.Tests
{
    [TestFixture]
    public class SceneManagerTests
    {
        [Test]
        public void TestClose()
        {
            TestHelpers.InMethod();

            SceneHelpers sh = new SceneHelpers();
            Scene scene = sh.SetupScene();

            sh.SceneManager.Close();
            Assert.That(scene.ShuttingDown, Is.True);
        }
    }
}

Add regression test for checking scene close when SceneManager is asked to close


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

using System.Threading.Tasks;
using NUnit.Framework;
using osu.Framework.IO.Stores;
using osu.Framework.Tests.Visual;

namespace osu.Framework.Tests.IO
{
    public class DllResourceStoreTest
    {
        [Test]
        public async Task TestSuccessfulAsyncLookup()
        {
            var resourceStore = new DllResourceStore(typeof(FrameworkTestScene).Assembly);

            byte[]? stream = await resourceStore.GetAsync("Resources.Tracks.sample-track.mp3");
            Assert.That(stream, Is.Not.Null);
        }

        [Test]
        public async Task TestFailedAsyncLookup()
        {
            var resourceStore = new DllResourceStore(typeof(FrameworkTestScene).Assembly);

            byte[]? stream = await resourceStore.GetAsync("Resources.Tracks.sample-track.mp5");
            Assert.That(stream, Is.Null);
        }
    }
}

Add test coverage for failing scenario

Add test coverage for failing scenario


using System;
using System.Threading.Tasks;
using ErgastApi.Client;
using ErgastApi.Client.Caching;
using ErgastApi.Requests;
using ErgastApi.Responses;
using FluentAssertions;
using NSubstitute;
using Xunit;

namespace ErgastApi.Tests.Client
{
    public class ErgastClientTests
    {
        private ErgastClient Client { get; }

        private IErgastCache Cache { get; set; }

        private IUrlBuilder UrlBuilder { get; set; }

        public ErgastClientTests()
        {
            Cache = Substitute.For<IErgastCache>();
            UrlBuilder = Substitute.For<IUrlBuilder>();

            Client = new ErgastClient
            {
                Cache = Cache,
                UrlBuilder = UrlBuilder
            };
        }

        [Theory]
        [AutoMockedData("invalid string")]
        [AutoMockedData("C:\\")]
        [AutoMockedData("C:")]
        [AutoMockedData("ftp://example.com")]
        [AutoMockedData("ftp://example.com/")]
        [AutoMockedData("C:\\example.txt")]
        [AutoMockedData("/example/api")]
        [AutoMockedData("example/api")]
        public void ApiRoot_Set_NonUrlShouldThrowArgumentException(string url)
        {
            Action act = () => Client.ApiRoot = url;
            act.ShouldThrow<ArgumentException>();
        }

        [Theory]
        [AutoMockedData("http://example.com")]
        [AutoMockedData("https://example.com")]
        public void ApiRoot_Set_ShouldAcceptHttpAndHttpsUrls(string url)
        {
            Client.ApiRoot = url;
            Client.ApiRoot.Should().Be(url);
        }

        [Theory]
        [AutoMockedData("http://example.com/api/")]
        [AutoMockedData("https://example.com/")]
        public void ApiRoot_Set_ShouldRemoveTrailingSlash(string url)
        {
            Client.ApiRoot = url;
            Client.ApiRoot.Should().Be(url.TrimEnd('/'));
        }

        [Theory]
        [AutoMockedData]
        public void GetResponseAsync_RequestWithRoundWithoutSeason_ThrowsInvalidOperationException(ErgastRequest<ErgastResponse> request)
        {
            // Arrange
            request.Season = null;
            request.Round = "1";

            // Act
            Func<Task> act = async () => await Client.GetResponseAsync(request);

            // Assert
            act.ShouldThrow<InvalidOperationException>();
        }

        [Theory]
        [AutoMockedData]
        public async Task GetResponseAsync_ReturnsCachedResponse(ErgastResponse expectedResponse)
        {
            Cache.Get<ErgastResponse>(null).ReturnsForAnyArgs(expectedResponse);

            var response = await Client.GetResponseAsync<ErgastResponse>(null);

            response.Should().Be(expectedResponse);
        }
    }
}

Add some tests for ErgastClient

Add some tests for ErgastClient


#region License
/* Copyright (c) 2017 Wes Hampson
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
#endregion

using System.Xml;
using System.Xml.Linq;

namespace WHampson.BFT
{
    internal static class XmlUtils
    {
        public static string BuildXmlErrorMsg(XObject o, string msgFmt, params object[] fmtArgs)
        {
            IXmlLineInfo lineInfo = o;
            string msg = string.Format(msgFmt, fmtArgs);
            if (!msg.EndsWith("."))
            {
                msg += ".";
            }

            msg += " " + string.Format(" Line {0}, position {1}.", lineInfo.LineNumber, lineInfo.LinePosition);

            return msg;
        }
    }
}

Add utility class for Xml-related tasks

Add utility class for Xml-related tasks


using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;

using Bonobo.Git.Server.Models;

using Microsoft.Practices.Unity;
using System.Web;
using Microsoft.Owin.Security.WsFederation;
using Microsoft.Owin.Security.Cookies;
using Owin;

namespace Bonobo.Git.Server.Security
{
    public abstract class AuthenticationProvider : IAuthenticationProvider
    {
        [Dependency]
        public IMembershipService MembershipService { get; set; }

        [Dependency]
        public IRoleProvider RoleProvider { get; set; }

        public abstract void Configure(IAppBuilder app);
        public abstract void SignIn(string username, string returnUrl);
        public abstract void SignOut();

        public IEnumerable<Claim> GetClaimsForUser(string username)
        {
            List<Claim> result = new List<Claim>();

            UserModel user = MembershipService.GetUser(username);

            result.Add(new Claim(ClaimTypes.Name, user.DisplayName));
            result.Add(new Claim(ClaimTypes.Upn, user.Name));
            result.Add(new Claim(ClaimTypes.Email, user.Email));
            result.Add(new Claim(ClaimTypes.Role, Definitions.Roles.Member));
            result.AddRange(RoleProvider.GetRolesForUser(user.Name).Select(x => new Claim(ClaimTypes.Role, x)));

            return result;
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;

using Bonobo.Git.Server.Models;

using Microsoft.Practices.Unity;

using Owin;

namespace Bonobo.Git.Server.Security
{
    public abstract class AuthenticationProvider : IAuthenticationProvider
    {
        [Dependency]
        public IMembershipService MembershipService { get; set; }

        [Dependency]
        public IRoleProvider RoleProvider { get; set; }

        public abstract void Configure(IAppBuilder app);
        public abstract void SignIn(string username, string returnUrl);
        public abstract void SignOut();

        public IEnumerable<Claim> GetClaimsForUser(string username)
        {
            List<Claim> result = null;

            UserModel user = MembershipService.GetUser(username.StripDomain());
            if (user != null)
            {
                result = new List<Claim>();
                result.Add(new Claim(ClaimTypes.Name, user.DisplayName));
                result.Add(new Claim(ClaimTypes.Upn, user.Name));
                result.Add(new Claim(ClaimTypes.Email, user.Email));
                result.Add(new Claim(ClaimTypes.Role, Definitions.Roles.Member));
                result.AddRange(RoleProvider.GetRolesForUser(user.Name).Select(x => new Claim(ClaimTypes.Role, x)));
            }

            return result;
        }
    }
}

Check for valid user before adding claims


using System; // require keep for Windows Universal App
using UnityEngine;

namespace UniRx.Triggers
{
    [DisallowMultipleComponent]
    public class ObservableJointTrigger : ObservableTriggerBase
    {
        Subject<float> onJointBreak;

        void OnJointBreak(float breakForce)
        {
            if (onJointBreak != null) onJointBreak.OnNext(breakForce);
        }

        public IObservable<float> OnJointBreakAsObservable()
        {
            return onJointBreak ?? (onJointBreak = new Subject<float>());
        }

        Subject<Joint2D> onJointBreak2D;

        void OnJointBreak2D(Joint2D brokenJoint)
        {
            if (onJointBreak2D != null) onJointBreak2D.OnNext(brokenJoint);
        }

        public IObservable<Joint2D> OnJointBreak2DAsObservable()
        {
            return onJointBreak2D ?? (onJointBreak2D = new Subject<Joint2D>());
        }

        protected override void RaiseOnCompletedOnDestroy()
        {
            if (onJointBreak != null)
            {
                onJointBreak.OnCompleted();
            }
            if (onJointBreak2D != null)
            {
                onJointBreak2D.OnCompleted();
            }
        }
    }
}

Add joint trigger (OnJointBreak() + OnJointBreak2D())

Issue #154


using System;

namespace mcThings.Extensions
{
    public static class ByteExtensions
    {
        public static byte ReadFirstNBits(this byte value, byte n)
        {
            if (n > 8)
                throw new ArgumentException($"{nameof(n)} cannot be greater than 8.", nameof(n));

            return (byte) (value >> (8 - n));
        }

        public static byte ReadLastNBits(this byte value, byte n)
        {
            if (n > 8)
                throw new ArgumentException($"{nameof(n)} cannot be greater than 8.", nameof(n));

            byte mask = (byte) ((1 << n) - 1);
            return (byte) (value & mask);
        }
    }
}

Add extensions to byte for getting a value from the first or last n bits of said byte.


using slang.AST;

namespace slang.Compilation
{
    public class CompilationUnit
    {
        public CompilationUnit (string sourceFilename, ProgramNode root)
        {
            SourceFile = sourceFilename;
            Root = root;
        }

        public string SourceFile { get; set; }

        public ProgramNode Root { get; set; }
    }
}

Add a compilation unit type that represents a parse tree from a specific file.


// Component.cs
// <copyright file="Component.cs"> This code is protected under the MIT License. </copyright>
using System.Collections.Generic;

namespace EnigmaUtilities.Components
{
    /// <summary>
    /// An abstract super class for each component in the enigma machine.
    /// </summary>
    public abstract class Component
    {
        /// <summary>
        /// Gets or sets a dictionary all letters and what they get encrypted to.
        /// </summary>
        protected Dictionary<char, char> EncryptionKeys { get; set; }

        /// <summary>
        /// Encrypts a letter with the current encryption keys.
        /// </summary>
        /// <param name="c"> The character to encrypt. </param>
        /// <returns> The encrypted character. </returns>
        public abstract char Encrypt(char c);
    }
}

Add a component super class

Add a component super class


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

using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Sprites;
using osu.Game.Rulesets.UI.Scrolling;

namespace osu.Game.Rulesets.Mania.Skinning
{
    public class LegacyHitExplosion : LegacyManiaColumnElement
    {
        private readonly IBindable<ScrollingDirection> direction = new Bindable<ScrollingDirection>();

        private Drawable explosion;

        [BackgroundDependencyLoader]
        private void load(IScrollingInfo scrollingInfo)
        {
            InternalChild = explosion = new Sprite
            {
            };

            direction.BindTo(scrollingInfo.Direction);
            direction.BindValueChanged(onDirectionChanged, true);

            // Todo: LightingN
            // Todo: LightingL
        }

        private void onDirectionChanged(ValueChangedEvent<ScrollingDirection> obj)
        {
            throw new System.NotImplementedException();
        }

        protected override void LoadComplete()
        {
            base.LoadComplete();

            lighting.FadeInFromZero(80)
                    .Then().FadeOut(120);
        }
    }
}

Add structure for legacy hit explosions

Add structure for legacy hit explosions


using DSharpPlus.EventArgs;
using ModCore.Entities;
using ModCore.Logic;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ModCore.Listeners
{
    public class UnbanTimerRemove
    {
        [AsyncListener(EventTypes.GuildBanRemoved)]
        public static async Task CommandError(ModCoreShard bot, GuildBanRemoveEventArgs e)
        {
            using (var db = bot.Database.CreateContext())
            {
                if (db.Timers.Any(x => x.ActionType == TimerActionType.Unmute && (ulong)x.UserId == e.Member.Id))
                {
                    db.Timers.Remove(db.Timers.First(x => (ulong)x.UserId == e.Member.Id && x.ActionType == TimerActionType.Unban));
                    await db.SaveChangesAsync();
                }
            }
        }
    }
}

Remove unban timer on actual unban event


namespace MediaFileParser.MediaTypes.MediaFile.Junk
{
    /// <summary>
    /// Junk String Extensions Class
    /// </summary>
    public static class JunkStringExtensions
    {
        /// <summary>
        /// Determines whether the beginning of this string instance matches a specified JunkString.
        /// </summary>
        /// <param name="str">The string to compare to.</param>
        /// <param name="startsWith">The JunkString to compare.</param>
        /// <returns>true if value matches the beginning of this string; otherwise, false.</returns>
        public static bool StartsWith(this string str, JunkString startsWith)
        {
            return str.StartsWith(startsWith.String);
        }

        /// <summary>
        /// Determines whether this instance and another specified JunkString object have the same value.
        /// </summary>
        /// <param name="str">The string to compare to.</param>
        /// <param name="obj">The JunkString to compare to this instance.</param>
        /// <returns>true if the value of the value parameter is the same as this instance; otherwise, false.</returns>
        public static bool EqualsJunk(this string str, JunkString obj)
        {
            return str.Equals(obj.String);
        }
    }
}

Move string extensions to own file

Move string extensions to own file


using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Unosquare.Swan.Components;
using Unosquare.Swan.Networking;

namespace Unosquare.Swan.Test
{
    [TestFixture]
    public class ComponentsRetryTest
    {
        private static int count = 0;

        [Test]
        public async Task RetryTest()
        {
            var retryCount = 4;
            await Retry.Do(FailFunction, TimeSpan.FromSeconds(1), retryCount);
            Assert.IsTrue(count == retryCount);
        }

        internal async Task FailFunction()
        {
            count++;
            var token = await JsonClient.GetString("http://accesscore.azurewebsites.net/api/token");
        }
    }
}

Add Retry Test(not done yet)

Add Retry Test(not done yet)


using System;
using System.Collections.Generic;
using System.Text;
using Xunit;

namespace SCPI.Tests
{
    public class AUTOSCALE_Tests
    {
        [Fact]
        public void ValidCommand()
        {
            // Arrange
            var cmd = new AUTOSCALE();
            var expected = ":AUToscale";

            // Act
            var actual = cmd.Command();

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

Add unit test for autoscale command

Add unit test for autoscale command


using NUnit.Framework;
using SimpleStack.Orm.Attributes;

namespace SimpleStack.Orm.Tests
{
    [TestFixture]
    public partial class ExpressionTests
    {
        public class ModeWithAutoIncrement
        {
            /// Gets or sets the identifier.
            /// <value>The identifier.</value>
            [AutoIncrement]
            [PrimaryKey]
            public int Id { get; set; }

            /// Gets or sets the name.
            /// <value>The name.</value>
            public string Name { get; set; }
        }

        public class ModeWithoutAutoIncrement
        {
            /// Gets or sets the identifier.
            /// <value>The identifier.</value>
            [PrimaryKey]
            public int Id { get; set; }

            /// Gets or sets the name.
            /// <value>The name.</value>
            public string Name { get; set; }
        }

        [Test]
        public void InsertAndRetrieveIdentity()
        {
            using (var conn = OpenDbConnection())
            {
                conn.CreateTable<ModeWithAutoIncrement>(true);

                var identity = conn.Insert(new ModeWithAutoIncrement{Name = "hello"});
                var identity2 = conn.Insert(new ModeWithAutoIncrement{Name = "hello"});

                Assert.NotNull(identity);
                Assert.False(identity == identity2);
            }
        }

        [Test]
        public void InsertWithoutAutoIncrementAndRetrieveIdentity()
        {
            using (var conn = OpenDbConnection())
            {
                conn.CreateTable<ModeWithoutAutoIncrement>(true);

                var identity = conn.Insert(new ModeWithoutAutoIncrement{Id=10, Name = "hello"});

                Assert.AreEqual(0,identity);
            }
        }

    }
}

Add Autonum and Identity retrieval Tests


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

namespace libgitface
{
	public static class LinqExtensions
	{
		class DelegateComparer<T, TCompare> : IEqualityComparer<T>
		{
			Func<T, TCompare> Selector;

			public DelegateComparer (Func<T, TCompare> selector) => Selector = selector;

			public bool Equals (T x, T y) => EqualityComparer<TCompare>.Default.Equals (Selector (x), Selector (y));

			public int GetHashCode (T obj) => EqualityComparer<TCompare>.Default.GetHashCode (Selector (obj));
		}

		public static IEnumerable<T> Distinct<T, TCompare> (this IEnumerable<T> self, Func<T, TCompare> selector)
		{
			var comparer = new DelegateComparer<T, TCompare> (selector);
			return self.Distinct (comparer);
		}
	}
}

Add a linq extension to Distinct objects using a Func


// Copyright 2017 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.

using NUnit.Framework;

namespace NodaTime.Demo
{
    public class DateIntervalDemo
    {
        [Test]
        public void Construction()
        {
            var calendar = CalendarSystem.Gregorian;
            LocalDate start = new LocalDate(2017, 1, 1, calendar);
            LocalDate end = new LocalDate(2017, 12, 31, calendar);

            DateInterval interval = Snippet.For(new DateInterval(start, end));

            Assert.AreEqual(365, interval.Length);
            Assert.AreEqual("[2017-01-01, 2017-12-31]", interval.ToString());
            Assert.AreEqual(start, interval.Start);
            Assert.AreEqual(end, interval.End);
            Assert.AreEqual(calendar, interval.Calendar);
        }

        [Test]
        public void Intersection()
        {
            DateInterval januaryToAugust = new DateInterval(
                new LocalDate(2017, 1, 1),
                new LocalDate(2017, 8, 31));

            DateInterval juneToNovember = new DateInterval(
                new LocalDate(2017, 6, 1),
                new LocalDate(2017, 11, 30));

            DateInterval juneToAugust = new DateInterval(
                new LocalDate(2017, 6, 1),
                new LocalDate(2017, 8, 31));

            var result = Snippet.For(januaryToAugust.Intersection(juneToNovember));
            Assert.AreEqual(juneToAugust, result);
        }

        [Test]
        public void Contains_LocalDate()
        {
            LocalDate start = new LocalDate(2017, 1, 1);
            LocalDate end = new LocalDate(2017, 12, 31);

            DateInterval interval = new DateInterval(start, end);

            var result = Snippet.For(interval.Contains(new LocalDate(2017, 12, 5)));
            Assert.AreEqual(true, result);
        }

        [Test]
        public void Contains_Interval()
        {
            LocalDate start = new LocalDate(2017, 1, 1);
            LocalDate end = new LocalDate(2017, 12, 31);

            DateInterval interval = new DateInterval(start, end);
            DateInterval june = new DateInterval(
                new LocalDate(2017, 6, 1),
                new LocalDate(2017, 6, 30));

            var result = Snippet.For(interval.Contains(june));
            Assert.AreEqual(true, result);
        }
    }
}

Add snippets for the DateInterval type

Add snippets for the DateInterval type


using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Xunit;

namespace Nether.Web.IntegrationTests
{
    public class SwaggerTests
    {
        [Fact]
        public async Task GET_Swagger_returns_200_OK()
        {
            var client = new HttpClient();

            var response = await client.GetAsync("http://localhost:5000/api/swagger/v0.1/swagger.json");

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
        }
    }
}

Add integration test to ensure SwaggerGen runs ok


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

namespace Pather.CSharp.PathElements
{
    public class EnumerableAccess : IPathElement
    {
        private string property;
        private int index;

        public EnumerableAccess(string property, int index)
        {
            this.property = property;
            this.index = index;
        }

        public object Apply(object target)
        {
            PropertyInfo p = target.GetType().GetProperty(property);
            if (p == null)
                throw new ArgumentException($"The property {property} could not be found.");

            var enumerable = p.GetValue(target) as IEnumerable;
            if (enumerable == null)
                throw new ArgumentException($"The property {property} is not an IEnumerable.");

            var enumerator = enumerable.GetEnumerator();
            for (var i = 0; i < index; i++) enumerator.MoveNext();

            var result = enumerator.Current;
            return result;
        }
    }
}

Add PathElement class for array like access


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

namespace FierceGalaxyInterface
{
    interface IGameFacade
    {
        IPlayerManager PlayerManager { get; }
    }
}

Add facade for the game (interface)

Add facade for the game (interface)


using System;

namespace MQTTnet.Extensions.ManagedClient
{
    public class ManagedMqttApplicationMessage : IEquatable<ManagedMqttApplicationMessage>
    {
        public Guid Id { get; set; } = Guid.NewGuid();

        public MqttApplicationMessage ApplicationMessage { get; set; }

        public bool Equals(ManagedMqttApplicationMessage other)
        {
            return Id.Equals(other.Id);
        }
    }
}

Revert "Changes to this file no longer needed"

This reverts commit 2c6c3ac6a4d070f6bbab48e2e9123f596bddad5a.


using System;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Xunit;
using Xunit.Abstractions;

namespace Moq.Proxy.Tests
{
    public class CompositionTests
    {
        ITestOutputHelper output;

        public CompositionTests(ITestOutputHelper output) => this.output = output;

        [Fact]
        public void CanGetProxyGenerationServices()
        {
            var host = ProxyGenerator.CreateHost();
            var workspace = new AdhocWorkspace(host);

            var services = workspace.Services.GetService<ICodeAnalysisServices>();

            var serviceTypes = typeof(ProxyGenerator).Assembly.GetTypes()
                .Select(x => new
                {
                    Type = x,
                    Export = x.GetCustomAttributes(typeof(ExportLanguageServiceAttribute), false)
                        .OfType<ExportLanguageServiceAttribute>().FirstOrDefault()
                })
                .Where(x => x.Export != null)
                .Select(x => new
                {
                    Key = Tuple.Create(x.Export.Language, x.Export.ServiceType, x.Export.Layer),
                    x.Type
                })
                .GroupBy(x => x.Key)
                .ToArray();

            foreach (var group in serviceTypes)
            {
                var instances = services.GetLanguageServices(group.Key.Item1, group.Key.Item2, group.Key.Item3).ToArray();

                Assert.Equal(group.Count(), instances.Length);
                output.WriteLine(group.Key.Item1 + ":" + group.Key.Item2.Substring(0, group.Key.Item2.IndexOf(",")) + ":" + group.Key.Item3 + "=" + instances.Length);
            }
        }
    }
}

Add test that ensures our exported components can be loaded


// 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.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();
        }
    }
}

Add test scene for setup screen

Add test scene for setup screen


// 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.Game.Beatmaps;

namespace osu.Game.Tests.NonVisual
{
    [TestFixture]
    public class BeatmapSetInfoEqualityTest
    {
        [Test]
        public void TestOnlineWithOnline()
        {
            var ourInfo = new BeatmapSetInfo { OnlineBeatmapSetID = 123 };
            var otherInfo = new BeatmapSetInfo { OnlineBeatmapSetID = 123 };

            Assert.AreEqual(ourInfo, otherInfo);
        }

        [Test]
        public void TestDatabasedWithDatabased()
        {
            var ourInfo = new BeatmapSetInfo { ID = 123 };
            var otherInfo = new BeatmapSetInfo { ID = 123 };

            Assert.AreEqual(ourInfo, otherInfo);
        }

        [Test]
        public void TestDatabasedWithOnline()
        {
            var ourInfo = new BeatmapSetInfo { ID = 123, OnlineBeatmapSetID = 12 };
            var otherInfo = new BeatmapSetInfo { OnlineBeatmapSetID = 12 };

            Assert.AreEqual(ourInfo, otherInfo);
        }

        [Test]
        public void TestCheckNullID()
        {
            var ourInfo = new BeatmapSetInfo { Status = BeatmapSetOnlineStatus.Loved };
            var otherInfo = new BeatmapSetInfo { Status = BeatmapSetOnlineStatus.Approved };

            Assert.AreNotEqual(ourInfo, otherInfo);
        }
    }
}

Add equality check test to ensure correct values


using Microsoft.ServiceFabric.Data;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ServiceFabric.Bond
{
    public class ByteArrayStateSerializer : IStateSerializer<byte[]>
    {
        public byte[] Read(BinaryReader binaryReader)
        {
            var count = binaryReader.ReadInt32();
            var bytes = binaryReader.ReadBytes(count);
            return bytes;
        }

        public byte[] Read(byte[] baseValue, BinaryReader binaryReader) => Read(binaryReader);

        public void Write(byte[] value, BinaryWriter binaryWriter)
        {
            binaryWriter.Write(value.Length);
            binaryWriter.Write(value, 0, value.Length);
        }

        public void Write(byte[] baseValue, byte[] targetValue, BinaryWriter binaryWriter) =>
            Write(targetValue, binaryWriter);
    }
}

Add in byte array serializer

Add in byte array serializer


// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

using System;

namespace Microsoft.R.Actions.Utility {
    public static class SupportedRVersionList {
        // TODO: this probably needs configuration file
        // or another dynamic source of supported versions.
        public const int MinMajorVersion = 3;
        public const int MinMinorVersion = 2;
        public const int MaxMajorVersion = 3;
        public const int MaxMinorVersion = 3;

        public static readonly Version MinVersion = new Version(MinMajorVersion, MinMinorVersion);
        public static readonly Version MaxVersion = new Version(MaxMajorVersion, MaxMinorVersion);

        public static bool IsCompatibleVersion(Version v) {
            var verMajorMinor = new Version(v.Major, v.Minor);
            return verMajorMinor >= MinVersion && verMajorMinor <= MaxVersion;
        }
    }
}

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

using System;

namespace Microsoft.R.Actions.Utility {
    public static class SupportedRVersionList {
        // TODO: this probably needs configuration file
        // or another dynamic source of supported versions.
        public const int MinMajorVersion = 3;
        public const int MinMinorVersion = 2;
        public const int MaxMajorVersion = 3;
        public const int MaxMinorVersion = 9;

        public static readonly Version MinVersion = new Version(MinMajorVersion, MinMinorVersion);
        public static readonly Version MaxVersion = new Version(MaxMajorVersion, MaxMinorVersion);

        public static bool IsCompatibleVersion(Version v) {
            var verMajorMinor = new Version(v.Major, v.Minor);
            return verMajorMinor >= MinVersion && verMajorMinor <= MaxVersion;
        }
    }
}

Increase R version cap to 3.9

Increase R version cap to 3.9


using Antlr4.Runtime;

namespace PythonParseTree
{
    public enum PythonVersion
    {
        Autodetect,
        Python2 = 2,
        Python3 = 3
    }

    public abstract class PythonBaseParser : Parser
    {
        public PythonVersion Version { get; set; }

        protected PythonBaseParser(ITokenStream input) : base(input)
        {
        }

        protected bool CheckVersion(int version) => Version == PythonVersion.Autodetect || version == (int) Version;

        protected void SetVersion(int requiredVersion) => Version = (PythonVersion) requiredVersion;
    }
}

Add PythonBaseParser with CheckVersion() and SetVersion() methods to check specific (Python 2 or 3) syntax


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

using NuGet;

namespace NuProj.Tests.Infrastructure
{
    public static class Scenario
    {
        public static async Task<IPackage> RestoreAndBuildSinglePackage(string scenarioName, IDictionary<string, string> properties = null)
        {
            var packages = await RestoreAndBuildPackages(scenarioName, properties);
            return packages.Single();
        }

        public static async Task<IReadOnlyCollection<IPackage>> RestoreAndBuildPackages(string scenarioName, IDictionary<string, string> properties = null)
        {
            var projectFullPath = Assets.GetScenarioSolutionPath(scenarioName);

            var projectDirectory = Path.GetDirectoryName(projectFullPath);
            await NuGetHelper.RestorePackagesAsync(projectDirectory);

            var result = await MSBuild.RebuildAsync(projectFullPath, properties);
            result.AssertSuccessfulBuild();

            return NuPkg.GetPackages(projectDirectory);
        }
    }
}

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

using NuGet;

namespace NuProj.Tests.Infrastructure
{
    public static class Scenario
    {
        public static async Task<IPackage> RestoreAndBuildSinglePackage(string scenarioName, string packageId = null, IDictionary<string, string> properties = null)
        {
            var packages = await RestoreAndBuildPackages(scenarioName, properties);
            return packageId == null
                    ? packages.Single()
                    : packages.Single(p => string.Equals(p.Id, packageId, StringComparison.OrdinalIgnoreCase));
        }

        public static async Task<IReadOnlyCollection<IPackage>> RestoreAndBuildPackages(string scenarioName, IDictionary<string, string> properties = null)
        {
            var projectFullPath = Assets.GetScenarioSolutionPath(scenarioName);

            var projectDirectory = Path.GetDirectoryName(projectFullPath);
            await NuGetHelper.RestorePackagesAsync(projectDirectory);

            var result = await MSBuild.RebuildAsync(projectFullPath, properties);
            result.AssertSuccessfulBuild();

            return NuPkg.GetPackages(projectDirectory);
        }
    }
}

Allow to specify which package to assert against


using ZobShop.ModelViewPresenter.Product.Details;

namespace ZobShop.ModelViewPresenter
{
    public interface IViewModelFactory
    {
        ProductDetailsViewModel CreateProductDetailsViewModel(string name, string category, decimal price, double volume, string maker);
    }
}

Add view model factory interface

Add view model factory interface


//
// ThreadSafe attribute
//
// Copyright 2012, Xamarin Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//

using System;

namespace MonoMac.ObjCRuntime {

	public class ThreadSafeAttribute : Attribute {

		public ThreadSafeAttribute ()
		{
		}
	}
}

Add [ThreadSafe] attribute so it can be used for documentation purpose (not just for bindings)


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AgateLib;
using AgateLib.DisplayLib;
using AgateLib.Geometry;
using AgateLib.WinForms;

namespace Tests.WinFormsTests
{
	class Converters : AgateApplication, IAgateTest
	{
		public string Name
		{
			get { return "Conversion Tests"; }
		}

		public string Category
		{
			get { return "WinForms"; }
		}

		public void Main(string[] args)
		{
			Run(args);
		}

		protected override void Initialize()
		{
			Surface surf = new Surface("attacke.png");

			System.Drawing.Bitmap bmp = surf.ToBitmap();

			bmp.Save("test.bmp", System.Drawing.Imaging.ImageFormat.Bmp);
		}
	}
}

Add test for winforms converters.

Add test for winforms converters.


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

namespace Oberon0.Generator.Msil.Tests.Statements
{
    using System.IO;

    using NUnit.Framework;

    using Oberon0.Compiler;
    using Oberon0.Compiler.Definitions;

    [TestFixture]
    public class StatementTests
    {
        [Test]
        public void RepeatTest()
        {
            string source = @"MODULE Test;
VAR
  i: INTEGER;

BEGIN
  i := 1;
  REPEAT
      WriteInt(i);
      WriteLn;
      i := i+1;
  UNTIL i > 5
END Test.";

            Module m = Oberon0Compiler.CompileString(source);

            CodeGenerator cg = new CodeGenerator(m);

            cg.Generate();
            StringBuilder sb = new StringBuilder();
            using (StringWriter w = new StringWriter(sb))
            {
                cg.DumpCode(w);
            }
            var code = sb.ToString();
            Assert.IsTrue(MsilTestHelper.CompileRunTest(code, null, out var outputData));
            Assert.AreEqual("1\n2\n3\n4\n5\n", outputData.NlFix());

        }
    }
}

Add generator test for REPEAT

Add generator test for REPEAT


/*
  Copyright © Iain McDonald 2010-2019

  This file is part of Decider.

  Unlike the Expression type which is wholly supported on its own, the MetaExpression relies
  on the values of other supporting variables. Thus, if those variables change, the bounds
  of the MetaExpression need to be re-evaluated.
*/
using System.Collections.Generic;

namespace Decider.Csp.BaseTypes
{
	public interface IMetaExpression<T>
	{
		IList<IVariable<T>> Support { get; }
	}
}

Fix Windows file format issues

Fix Windows file format issues


using System;
using MSBuildProjectTools.LanguageServer.XmlParser;

namespace MSBuildProjectTools.LanguageServer.Utilities
{
    /// <summary>
    ///     A quick-and-dirty calculator for text positions.
    /// </summary>
    /// <remarks>
    ///     This could easily be improved by also storing a character sub-total for each line.
    /// </remarks>
    public sealed class TextPositions
    {
        /// <summary>
        ///     The lengths of each line of the text.
        /// </summary>
        readonly int[] _lineLengths;

        /// <summary>
        ///     Create a new <see cref="TextPositions"/> for the specified text.
        /// </summary>
        /// <param name="text">
        ///     The text.
        /// </param>
        public TextPositions(string text)
        {
            if (text == null)
                throw new ArgumentNullException(nameof(text));

            string[] lines = text.Split(
                separator: new string[] { Environment.NewLine },
                options: StringSplitOptions.None
            );
            _lineLengths = new int[lines.Length];
            for (int lineIndex = 0; lineIndex < lines.Length; lineIndex++)
                _lineLengths[lineIndex] = lines[lineIndex].Length + Environment.NewLine.Length;
        }

        /// <summary>
        ///     Convert a <see cref="Position"/> to an absolute position within the text.
        /// </summary>
        /// <param name="line">
        ///     The target line (1-based).
        /// </param>
        /// <param name="column">
        ///     The target column (1-based).
        /// </param>
        /// <returns>
        ///     The equivalent absolute position within the text.
        /// </returns>
        public int GetAbsolutePosition(Position position)
        {
            if (position == null)
                throw new ArgumentNullException(nameof(position));

            position = position.ToOneBased();

            return GetAbsolutePosition(position.LineNumber, position.ColumnNumber);
        }

        /// <summary>
        ///     Convert line and column numbers to an absolute position within the text.
        /// </summary>
        /// <param name="line">
        ///     The target line (1-based).
        /// </param>
        /// <param name="column">
        ///     The target column (1-based).
        /// </param>
        /// <returns>
        ///     The equivalent absolute position within the text.
        /// </returns>
        public int GetAbsolutePosition(int line, int column)
        {
            // Indexes are 0-based.
            int targetLine = line - 1;
            int targetColumn = column - 1;

            if (targetLine >= _lineLengths.Length)
                throw new ArgumentOutOfRangeException(nameof(line), line, "Line is past the end of the text.");

            if (targetColumn >= _lineLengths[targetLine])
                throw new ArgumentOutOfRangeException(nameof(column), column, "Column is past the end of the line.");

            if (targetLine == 0)
                return targetColumn;

            // Position up to preceding line.
            int targetPosition = 0;
            for (int lineIndex = 0; lineIndex < targetLine; lineIndex++)
                targetPosition += _lineLengths[lineIndex];

            // And the final line.
            targetPosition += targetColumn;

            return targetPosition;
        }
    }
}

Implement calculation of absolute position in the document text, given a line and column number.


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

using System;
using NUnit.Framework;
using osu.Framework.Bindables;
using osu.Framework.Testing;
using osu.Game.Screens.OnlinePlay;
using osu.Game.Tests.Visual;

namespace osu.Game.Tests.NonVisual
{
    [HeadlessTest]
    public class OngoingOperationTrackerTest : OsuTestScene
    {
        private OngoingOperationTracker tracker;
        private IBindable<bool> operationInProgress;

        [SetUpSteps]
        public void SetUp()
        {
            AddStep("create tracker", () => Child = tracker = new OngoingOperationTracker());
            AddStep("bind to operation status", () => operationInProgress = tracker.InProgress.GetBoundCopy());
        }

        [Test]
        public void TestOperationTracking()
        {
            IDisposable firstOperation = null;
            IDisposable secondOperation = null;

            AddStep("begin first operation", () => firstOperation = tracker.BeginOperation());
            AddAssert("operation in progress", () => operationInProgress.Value);

            AddStep("cannot start another operation",
                () => Assert.Throws<InvalidOperationException>(() => tracker.BeginOperation()));

            AddStep("end first operation", () => firstOperation.Dispose());
            AddAssert("operation is ended", () => !operationInProgress.Value);

            AddStep("start second operation", () => secondOperation = tracker.BeginOperation());
            AddAssert("operation in progress", () => operationInProgress.Value);

            AddStep("dispose first operation again", () => firstOperation.Dispose());
            AddAssert("operation in progress", () => operationInProgress.Value);

            AddStep("dispose second operation", () => secondOperation.Dispose());
            AddAssert("operation is ended", () => !operationInProgress.Value);
        }

        [Test]
        public void TestOperationDisposalAfterTracker()
        {
            IDisposable operation = null;

            AddStep("begin operation", () => operation = tracker.BeginOperation());
            AddStep("dispose tracker", () => tracker.Expire());
            AddStep("end operation", () => operation.Dispose());
            AddAssert("operation is ended", () => !operationInProgress.Value);
        }
    }
}

Add coverage for operation tracker with failing tests


using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace WebApp
{
    /// <summary>
    /// Startup configuration example with user defined static file options
    /// To use this configuration, webpack static assets have to be built
    /// with public path set to /public/:
    /// unix:    export PUBLIC_PATH=/public/ && npm run build
    /// windows: set "PUBLIC_PATH=/public/" && npm run build
    /// </summary>
    public class StartupWithStaticFileOptions
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddWebpack(options =>
            {
                options.UseStaticFiles(opts => {
                    opts.RequestPath = "/public";
                    opts.OnPrepareResponse = responseContext =>
                        responseContext.Context.Response.Headers.Add(
                            key: "Cache-control",
                            value: "public,max-age=31536000"
                        );
                });
            });
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseWebpack();
            app.UseMvcWithDefaultRoute();
        }
    }
}

Add static file options startup sample

Add static file options startup sample


@*
// Copyright (c) 2010-2013 SharpDoc - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// -------------------------------------------------------------------------------
// Override this template to modify the generated html footer for all body
// -------------------------------------------------------------------------------
*@

@Param.Copyright

Documentation generated by SharpDoc

Update link to SharpaDoc on github

Update link to SharpaDoc on github


// ***********************************************************************
// Copyright (c) 2018 Charlie Poole, Rob Prouse
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************

#if ASYNC
using System.Threading.Tasks;

namespace NUnit.Framework
{
    // Make sure other tests are testing what we think they’re testing
    public static class AsyncExecutionApiAdapterTests
    {
        [TestCaseSource(typeof(AsyncExecutionApiAdapter), nameof(AsyncExecutionApiAdapter.All))]
        public static void ExecutesAsyncUserCode(AsyncExecutionApiAdapter adapter)
        {
            var didExecute = false;

            adapter.Execute(async () =>
            {
#if NET40
                await TaskEx.Yield();
#else
                await Task.Yield();
#endif
                didExecute = true;
            });

            Assert.That(didExecute);
        }
    }
}
#endif

Make sure async API tests are testing what we think they’re testing


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

namespace Schedutalk.Logic
{
    class HttpRequestor
    {
        public async Task<string> getHttpRequestAsString(Func<string, HttpRequestMessage> requestTask, string input)
        {
            HttpClient httpClient = new HttpClient();
            HttpRequestMessage request = requestTask(input);
            var response = httpClient.SendAsync(request);

            var result = await response.Result.Content.ReadAsStringAsync();
            return result;
        }

    }
}

Implement utlity for httprequest as string


namespace GeekLearning.Test.Integration.Environment
{
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Logging;
    using System;

    public class StartupConfigurationService : IStartupConfigurationService
    {
        public IServiceProvider ServiceProvider
        {
            get
            {
                throw new NotImplementedException();
            }
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { }

        public void ConfigureEnvironment(IHostingEnvironment env) { }

        public void ConfigureService(IServiceCollection services, IConfigurationRoot configuration) { }

        public void RegisterExternalStartupConfigured(Action callback)
        {
            throw new NotImplementedException();
        }
    }
}

Add empty Startup configuration service implementation


// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System.Reflection;

[assembly: AssemblyMetadata("Serviceable", "True")]

Add serviceable attribute to projects.

Add serviceable attribute to projects.

aspnet/DNX#1600


using System;

namespace Zyborg.Vault.Server.Util
{
    /// <summary>
    /// This attribute allows you to specify what type is used to configure
    /// the behavior of another type instance, such as a service provider.
    /// </summary>
    [AttributeUsage(AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
    public class ConfiguredByAttribute : Attribute
    {
        public ConfiguredByAttribute(Type type)
        {
            this.Type = type;
        }

        public Type Type
        { get; }
    }
}

Support meta-data to define config relationship between classes

This could become useful when doing code analysis and automated doc generation


// Copyright 2020 Google LLC
//
// 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
//
//     https://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.

// [START functions_http_integration_test]
using Google.Cloud.Functions.Invoker.Testing;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Xunit;

namespace HelloHttp.Tests
{
    public class FunctionIntegrationTest
    {
        [Fact]
        public async Task GetRequest_NoParameters()
        {
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "uri");
            string text = await ExecuteRequest(request);
            Assert.Equal("Hello world!", text);
        }

        [Fact]
        public async Task GetRequest_UrlParameters()
        {
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "uri?name=Cho");
            string text = await ExecuteRequest(request);
            Assert.Equal("Hello Cho!", text);
        }

        [Fact]
        public async Task PostRequest_BodyParameters()
        {
            string json = "{\"name\":\"Julie\"}";
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "uri")
            {
                Content = new StringContent(json)
            };
            string text = await ExecuteRequest(request);
            Assert.Equal("Hello Julie!", text);
        }

        /// <summary>
        /// Executes the given request in the function in an in-memory test server,
        /// validates that the response status code is 200, and returns the text of the
        /// response body. FunctionTestServer{T} is provided by the
        /// Google.Cloud.Functions.Invoker.Testing package.
        /// </summary>
        private static async Task<string> ExecuteRequest(HttpRequestMessage request)
        {
            using (var server = new FunctionTestServer<Function>())
            {
                using (HttpClient client = server.CreateClient())
                {
                    HttpResponseMessage response = await client.SendAsync(request);
                    Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                    return await response.Content.ReadAsStringAsync();
                }
            }
        }
    }
}
// [END functions_http_integration_test]

Add sample of an HTTP function integration test


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

using System;
using System.Collections.Generic;
using NUnit.Framework;
using osu.Framework.Graphics;
using osu.Game.Rulesets.Mania.Beatmaps;
using osu.Game.Rulesets.Mania.Objects;
using osu.Game.Rulesets.Mania.UI;

namespace osu.Game.Rulesets.Mania.Tests.Skinning
{
    public class TestSceneBarLine : ManiaSkinnableTestScene
    {
        [Test]
        public void TestMinor()
        {
            AddStep("Create barlines", () => recreate());
        }

        private void recreate(Func<IEnumerable<BarLine>>? createBarLines = null)
        {
            var stageDefinitions = new List<StageDefinition>
            {
                new StageDefinition { Columns = 4 },
            };

            SetContents(_ => new ManiaPlayfield(stageDefinitions).With(s =>
            {
                if (createBarLines != null)
                {
                    var barLines = createBarLines();

                    foreach (var b in barLines)
                        s.Add(b);

                    return;
                }

                for (int i = 0; i < 64; i++)
                {
                    s.Add(new BarLine
                    {
                        StartTime = Time.Current + i * 500,
                        Major = i % 4 == 0,
                    });
                }
            }));
        }
    }
}

Add test scene for visually adjusting mania `BarLine`s


// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#nullable enable

using System;
using Microsoft.CodeAnalysis.PooledObjects;

namespace Microsoft.CodeAnalysis.LanguageServer.Handler
{
    /// <summary>
    /// Helper type to allow command handlers to report data either in a streaming fashion (if a client supports that),
    /// or as an array of results.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    internal struct BufferedProgress<T> : IProgress<T>, IDisposable
    {
        /// <summary>
        /// The progress stream to report results to.  May be <see langword="null"/> for clients that do not support streaming.
        /// If <see langword="null"/> then <see cref="_buffer"/> will be non null and will contain all the produced values.
        /// </summary>
        private readonly IProgress<T[]>? _underlyingProgress;

        /// <summary>
        /// A buffer that results are held in if the client does not support streaming.  Values of this can be retrieved
        /// using <see cref="GetValues"/>.
        /// </summary>
        private readonly ArrayBuilder<T>? _buffer;

        public BufferedProgress(IProgress<T[]>? underlyingProgress)
        {
            _underlyingProgress = underlyingProgress;
            _buffer = underlyingProgress == null ? ArrayBuilder<T>.GetInstance() : null;
        }

        public void Dispose()
            => _buffer?.Free();

        /// <summary>
        /// Report a value either in a streaming or buffered fashion depending on what the client supports.
        /// </summary>
        public void Report(T value)
        {
            _underlyingProgress?.Report(new[] { value });
            _buffer?.Add(value);
        }

        /// <summary>
        /// Gets the set of buffered values.  Will return null if the client supports streaming.
        /// </summary>
        public T[]? GetValues()
            => _buffer?.ToArray();
    }

    internal static class BufferedProgress
    {
        public static BufferedProgress<T> Create<T>(IProgress<T[]>? progress)
            => new BufferedProgress<T>(progress);
    }
}

Add an abstraction for either reporting an array or results, or streaming them in LSP scenarios.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MassTransit.Tests.TextFixtures;
using MassTransit.TestFramework;
using MassTransit.BusConfigurators;
using NUnit.Framework;
using Magnum.TestFramework;
using Magnum;
using Magnum.Extensions;

namespace MassTransit.Tests.Subscriptions
{
    [TestFixture]
    public class when_multiple_subscribers_to_same_message
        : LoopbackLocalAndRemoteTestFixture
    {
        protected override void EstablishContext()
        {
            base.EstablishContext();

            RemoteBus.ShouldHaveSubscriptionFor<MyMessage>();

            LocalBus.Publish(new MyMessage());
        }

        private List<Tuple<string, MyMessage>> receivedMessages = new List<Tuple<string, MyMessage>>();

        protected override void ConfigureRemoteBus(ServiceBusConfigurator configurator)
        {
            base.ConfigureLocalBus(configurator);

            configurator.Subscribe(cf =>
            {
                cf.Handler<MyMessage>(message => receivedMessages.Add(new Tuple<string, MyMessage>("One", message)));
                cf.Handler<MyMessage>(message => receivedMessages.Add(new Tuple<string, MyMessage>("Two", message)));
            });
        }

        [Test]
        public void each_subscriber_should_only_receive_once()
        {

            ThreadUtil.Sleep(4.Seconds());

            var byReceiver = receivedMessages.GroupBy(r => r.Item1);
            byReceiver.All(g => g.Count() == 1).ShouldBeTrue();
        }

    }

    public class MyMessage
    {

    }

}

Test to repro multiple subscribers issue


using Microsoft.VisualStudio.TestTools.UnitTesting;
using ThScoreFileConverter.Models;
using ThScoreFileConverter.Properties;
using ThScoreFileConverter.ViewModels;

namespace ThScoreFileConverterTests.ViewModels
{
    [TestClass]
    public class AboutWindowViewModelTests
    {
        [TestMethod]
        public void TitleTest()
        {
            var window = new AboutWindowViewModel();
            Assert.AreEqual(Utils.GetLocalizedValues<string>(nameof(Resources.AboutWindowTitle)), window.Title);
        }

        [TestMethod]
        public void IconTest()
        {
            var window = new AboutWindowViewModel();
            Assert.IsNotNull(window.Icon);
        }

        [TestMethod]
        public void NameTest()
        {
            var window = new AboutWindowViewModel();
            Assert.AreEqual(nameof(ThScoreFileConverter), window.Name);
        }

        [TestMethod]
        public void VersionTest()
        {
            var window = new AboutWindowViewModel();
            StringAssert.StartsWith(window.Version, Utils.GetLocalizedValues<string>(nameof(Resources.VersionPrefix)));
        }

        [TestMethod]
        public void CopyrightTest()
        {
            var window = new AboutWindowViewModel();
            Assert.IsFalse(string.IsNullOrEmpty(window.Copyright));
        }

        [TestMethod]
        public void UriTest()
        {
            var window = new AboutWindowViewModel();
            Assert.AreEqual(Resources.ProjectUrl, window.Uri);
        }

        [TestMethod]
        public void OpenUriCommandTest()
        {
            var window = new AboutWindowViewModel();
            var command = window.OpenUriCommand;
            Assert.IsNotNull(command);
            Assert.IsTrue(command.CanExecute(Resources.ProjectUrl));
            command.Execute(Resources.ProjectUrl);
        }

        [TestMethod]
        public void CanCloseDialogTest()
        {
            var window = new AboutWindowViewModel();
            Assert.IsTrue(window.CanCloseDialog());
        }
    }
}

Add test cases for ViewModels.AboutWindowViewModel


using System;
using System.Diagnostics;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.EntityFrameworkCore.Migrations.Operations;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore.Storage.Internal;
using Microsoft.EntityFrameworkCore.TestUtilities;
using Microsoft.EntityFrameworkCore.TestUtilities.FakeProvider;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure.Internal;
using Xunit;
using Microsoft.EntityFrameworkCore.Internal;
using Moq;
using MySql.Data.MySqlClient;

namespace Pomelo.EntityFrameworkCore.MySql.Tests.Migrations
{
    public class MigrationSqlGeneratorMySql56Test : MigrationSqlGeneratorTestBase
    {
        protected override IMigrationsSqlGenerator SqlGenerator
        {
            get
            {
                // type mapper
                var typeMapper = new MySqlTypeMapper(new RelationalTypeMapperDependencies());

                // migrationsSqlGeneratorDependencies
                var commandBuilderFactory = new RelationalCommandBuilderFactory(
                    new FakeDiagnosticsLogger<DbLoggerCategory.Database.Command>(),
                    typeMapper);
                var migrationsSqlGeneratorDependencies = new MigrationsSqlGeneratorDependencies(
                    commandBuilderFactory,
                    new MySqlSqlGenerationHelper(new RelationalSqlGenerationHelperDependencies()),
                    typeMapper);

                var mySqlOptions = new Mock<IMySqlOptions>();
                mySqlOptions.SetupGet(opts => opts.ConnectionSettings).Returns(
                    new MySqlConnectionSettings(new MySqlConnectionStringBuilder(), new ServerVersion("5.6.2")));

                return new MySqlMigrationsSqlGenerator(
                    migrationsSqlGeneratorDependencies,
                    mySqlOptions.Object);
            }
        }

        private static FakeRelationalConnection CreateConnection(IDbContextOptions options = null)
            => new FakeRelationalConnection(options ?? CreateOptions());

        private static IDbContextOptions CreateOptions(RelationalOptionsExtension optionsExtension = null)
        {
            var optionsBuilder = new DbContextOptionsBuilder();

            ((IDbContextOptionsBuilderInfrastructure)optionsBuilder)
                .AddOrUpdateExtension(optionsExtension
                                      ?? new FakeRelationalOptionsExtension().WithConnectionString("test"));

            return optionsBuilder.Options;
        }

        public override void RenameIndexOperation_works()
        {
            base.RenameIndexOperation_works();

            Assert.Equal("ALTER TABLE `People` DROP INDEX `IX_People_Name`;" + EOL
                         + "ALTER TABLE `People` CREATE INDEX `IX_People_Better_Name`;" + EOL,
                Sql);
        }
    }
}

Add test suite with tests for MySQL 5.6

Add test suite with tests for MySQL 5.6

Right now it only overrides the Rename Index test to test that the
generator creates proper statements


// 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.Development;
using osu.Game.Configuration;

namespace osu.Game.Tests.Visual.Navigation
{
    [TestFixture]
    public class TestSceneStartupRuleset : OsuGameTestScene
    {
        protected override TestOsuGame CreateTestGame()
        {
            // Must be done in this function due to the RecycleLocalStorage call just before.
            var config = DebugUtils.IsDebugBuild
                ? new DevelopmentOsuConfigManager(LocalStorage)
                : new OsuConfigManager(LocalStorage);

            config.SetValue(OsuSetting.Ruleset, "mania");
            config.Save();

            return base.CreateTestGame();
        }

        [Test]
        public void TestRulesetConsumed()
        {
            AddUntilStep("ruleset correct", () => Game.Ruleset.Value.ShortName == "mania");
        }
    }
}

Add test coverage of startup ruleset being non-default


using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using NuGet;
using NuGetPackageExplorer.Types;

namespace PackageExplorerViewModel.Rules {
    [Export(typeof(IPackageRule))]
    internal class NonAssemblyReferenceName : IPackageRule {

        public string Name {
            get {
                return "Non-Assembly Reference Name";
            }
        }

        public IEnumerable<PackageIssue> Check(IPackage package) {
            return from reference in package.References
                   let file = reference.File
                   where !file.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) &&
                         !file.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)
                   select CreateIssue(file);
        }

        private static PackageIssue CreateIssue(string reference) {
            return new PackageIssue(
                PackageIssueLevel.Warning,
                "Non-assembly reference name",
                "The name '" + reference + "' in the Filtered Assembly References is not a valid assembly name. An assembly name must have extension as either .dll or .exe.",
                "Remove this assembly reference name.");
        }
    }
}

Add missing file in the previous commit.

--HG--
branch : 2.0


using System;
using System.Collections.Generic;

namespace BinaryKits.Utility.ZPLUtility.Elements
{
    /// <summary>
    /// Interleaved 2 of 5 Barcode
    /// </summary>
    public class ZPLBarCodeInterleaved2of5 : ZPLBarcode
    {
        public bool Mod10CheckDigit { get; private set; }

        public ZPLBarCodeInterleaved2of5(string content, int positionX, int positionY, int height = 100, string orientation = "N", bool printInterpretationLine = true, bool printInterpretationLineAboveCode = false, bool mod10CheckDigit = false)
            : base(content, positionX, positionY, height, orientation, printInterpretationLine, printInterpretationLineAboveCode)
        {
            if (!IsDigitsOnly(content))
            {
                throw new ArgumentException("Interleaved 2 of 5 Barcode allow only digits", nameof(content));
            }

            Mod10CheckDigit = mod10CheckDigit;
        }

        public override IEnumerable<string> Render(ZPLRenderOptions context)
        {
            var result = new List<string>();
            result.AddRange(Origin.Render(context));
            result.Add($"^B2{Orientation},{context.Scale(Height)},{(PrintInterpretationLine ? "Y" : "N")},{(PrintInterpretationLineAboveCode ? "Y" : "N")},{(Mod10CheckDigit ? "Y" : "N")}");
            result.Add($"^FD{Content}^FS");

            return result;
        }

        private bool IsDigitsOnly(string text)
        {
            foreach (char c in text)
            {
                if (c < '0' || c > '9')
                {
                    return false;
                }
            }

            return true;
        }
    }
}

Add Interleaved 2 of 5 Barcode

Add Interleaved 2 of 5 Barcode