using System;
using System.Linq;
using System.Net;
using Google.Protobuf.Reflection;
using KillrVideo.Host.Config;

namespace KillrVideo.Protobuf.ServiceDiscovery
{
    /// <summary>
    /// Service discovery implementation that just points all service clients to the host/port where they
    /// have been configured to run locally.
    /// </summary>
    public class LocalServiceDiscovery : IFindGrpcServices
    {
        private readonly IHostConfiguration _hostConfig;
        private readonly Lazy<ServiceLocation> _localServicesIp;

        public LocalServiceDiscovery(IHostConfiguration hostConfig)
        {
            if (hostConfig == null) throw new ArgumentNullException(nameof(hostConfig));
            _hostConfig = hostConfig;
            _localServicesIp = new Lazy<ServiceLocation>(GetLocalGrpcServer);
        }

        public ServiceLocation Find(ServiceDescriptor service)
        {
            return _localServicesIp.Value;
        }

        private ServiceLocation GetLocalGrpcServer()
        {
            // Get the host/port configuration for the Grpc Server
            string host = _hostConfig.GetRequiredConfigurationValue(GrpcServerTask.HostConfigKey);
            string portVal = _hostConfig.GetRequiredConfigurationValue(GrpcServerTask.HostPortKey);
            int port = int.Parse(portVal);

            return new ServiceLocation(host, port);
        }
    }
}

using System;
using Google.Protobuf.Reflection;
using KillrVideo.Host.Config;

namespace KillrVideo.Protobuf.ServiceDiscovery
{
    /// <summary>
    /// Service discovery implementation that just points all service clients to 'localhost' and the port
    /// where they have been configured to run locally.
    /// </summary>
    public class LocalServiceDiscovery : IFindGrpcServices
    {
        private readonly IHostConfiguration _hostConfig;
        private readonly Lazy<ServiceLocation> _localServicesIp;

        public LocalServiceDiscovery(IHostConfiguration hostConfig)
        {
            if (hostConfig == null) throw new ArgumentNullException(nameof(hostConfig));
            _hostConfig = hostConfig;
            _localServicesIp = new Lazy<ServiceLocation>(GetLocalGrpcServer);
        }

        public ServiceLocation Find(ServiceDescriptor service)
        {
            return _localServicesIp.Value;
        }

        private ServiceLocation GetLocalGrpcServer()
        {
            // Get the host/port configuration for the Grpc Server
            string host = "localhost";
            string portVal = _hostConfig.GetRequiredConfigurationValue(GrpcServerTask.HostPortKey);
            int port = int.Parse(portVal);

            return new ServiceLocation(host, port);
        }
    }
}

Fix local service discovery now that services are listening on 0.0.0.0


using System.Reflection;
using System.Windows;

namespace Arkivverket.Arkade.UI.Views
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            Title = string.Format(UI.Resources.UI.General_WindowTitle, typeof(App).Assembly.GetName().Version);
        }
    }
}

using System.Reflection;
using System.Windows;

namespace Arkivverket.Arkade.UI.Views
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            Title = string.Format(UI.Resources.UI.General_WindowTitle, "0.3.0"); // Todo - get correct application version from assembly
        }
    }
}

Set correct version number in main window


using System.Collections.Generic;

namespace Microsoft.Build.Logging.StructuredLogger
{
    public class ParentedNode : BaseNode
    {
        public TreeNode Parent { get; set; }

        public IEnumerable<ParentedNode> GetParentChain()
        {
            var chain = new List<ParentedNode>();
            ParentedNode current = this;
            while (current.Parent != null)
            {
                chain.Add(current);
                current = current.Parent;
            }

            chain.Reverse();
            return chain;
        }

        public T GetNearestParent<T>() where T : ParentedNode
        {
            ParentedNode current = this;
            while (current.Parent != null)
            {
                current = current.Parent;
                if (current is T)
                {
                    return (T)current;
                }
            }

            return null;
        }
    }
}

using System.Collections.Generic;

namespace Microsoft.Build.Logging.StructuredLogger
{
    public class ParentedNode : BaseNode
    {
        private TreeNode parent;
        public TreeNode Parent
        {
            get => parent;
            set
            {
#if DEBUG
                if (parent != null)
                {
                    throw new System.InvalidOperationException("A node is being reparented");
                }
#endif

                parent = value;
            }
        }

        public IEnumerable<ParentedNode> GetParentChain()
        {
            var chain = new List<ParentedNode>();
            ParentedNode current = this;
            while (current.Parent != null)
            {
                chain.Add(current);
                current = current.Parent;
            }

            chain.Reverse();
            return chain;
        }

        public T GetNearestParent<T>() where T : ParentedNode
        {
            ParentedNode current = this;
            while (current.Parent != null)
            {
                current = current.Parent;
                if (current is T)
                {
                    return (T)current;
                }
            }

            return null;
        }
    }
}

Add a debug assert when a node is being reparented.

A tree node should only be parented once.


using CareerHub.Client.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CareerHub.Client.API.Integrations.Workflows {
    internal class WorkflowProgressApi : IWorkflowProgressApi {

        private const string ApiBase = "api/integrations/v1/workflows/progress";
        private readonly OAuthHttpClient client = null;

        public WorkflowProgressApi(string baseUrl, string accessToken) {
            client = new OAuthHttpClient(baseUrl, ApiBase, accessToken);
		}

        public Task<IEnumerable<ProgressModel>> Get(int id) {
            return client.GetResource<IEnumerable<ProgressModel>>(id.ToString());
        }
    }
}

using CareerHub.Client.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CareerHub.Client.API.Integrations.Workflows {
    internal class WorkflowProgressApi : IWorkflowProgressApi {

        private const string ApiBase = "api/integrations/v1/workflows";
        private readonly OAuthHttpClient client = null;

        public WorkflowProgressApi(string baseUrl, string accessToken) {
            client = new OAuthHttpClient(baseUrl, ApiBase, accessToken);
		}

        public Task<IEnumerable<ProgressModel>> Get(int workflowId) {
            string resource = GetResource(workflowId);
            return client.GetResource<IEnumerable<ProgressModel>>(resource);
        }

        private string GetResource(int workflowId, string resource = "") {
            return String.Format("{0}/progress/{1}", workflowId, resource);
        }
    }
}

Update api to match new URL

Update api to match new URL


using Autofac;
using Bit.Model.Events;
using Plugin.Connectivity.Abstractions;
using Prism;
using Prism.Autofac;
using Prism.Events;
using Prism.Ioc;
using Xamarin.Forms;

namespace Bit
{
    public abstract class BitApplication : PrismApplication
    {
        protected BitApplication(IPlatformInitializer platformInitializer = null)
            : base(platformInitializer)
        {
            MainPage = new ContentPage { };
        }

        protected override void OnInitialized()
        {
            IConnectivity connectivity = Container.Resolve<IConnectivity>();

            IEventAggregator eventAggregator = Container.Resolve<IEventAggregator>();

            connectivity.ConnectivityChanged += (sender, e) =>
            {
                eventAggregator.GetEvent<ConnectivityChangedEvent>()
                    .Publish(new ConnectivityChangedEvent { IsConnected = e.IsConnected });
            };
        }

        protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {
            containerRegistry.GetBuilder().Register<IContainerProvider>(c => Container).SingleInstance().PreserveExistingDefaults();
        }
    }
}

using Autofac;
using Bit.Model.Events;
using Plugin.Connectivity.Abstractions;
using Prism;
using Prism.Autofac;
using Prism.Events;
using Prism.Ioc;
using Xamarin.Forms;

namespace Bit
{
    public abstract class BitApplication : PrismApplication
    {
        protected BitApplication(IPlatformInitializer platformInitializer = null)
            : base(platformInitializer)
        {
            if (MainPage == null)
                MainPage = new ContentPage { Title = "DefaultPage" };
        }

        protected override void OnInitialized()
        {
            IConnectivity connectivity = Container.Resolve<IConnectivity>();

            IEventAggregator eventAggregator = Container.Resolve<IEventAggregator>();

            connectivity.ConnectivityChanged += (sender, e) =>
            {
                eventAggregator.GetEvent<ConnectivityChangedEvent>()
                    .Publish(new ConnectivityChangedEvent { IsConnected = e.IsConnected });
            };
        }

        protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {
            containerRegistry.GetBuilder().Register<IContainerProvider>(c => Container).SingleInstance().PreserveExistingDefaults();
        }
    }
}

Set main page of bit application of cs client if no main page is provided (Due error/delay in initialization)


using static System.Console;

public class Counter
{
    public Counter() { }

    public int Count;

    public Counter Increment()
    {
        Count++;
        return this;
    }
}

public static class Program
{
    public static readonly Counter printCounter = new Counter();

    public static void Main()
    {
        WriteLine(printCounter.Increment().Coutn);
        WriteLine(printCounter.Inrement().Count);
        WriteLine(printCoutner.Increment().Count);
    }
}

using static System.Console;

public class Counter
{
    public Counter() { }

    public int Count;

    public Counter Increment()
    {
        Count++;
        return this;
    }

    public Counter Decrement<T>()
    {
        Count--;
        return this;
    }
}

public static class Program
{
    public static readonly Counter printCounter = new Counter();

    public static void Main()
    {
        WriteLine(printCounter.Increment().Coutn);
        WriteLine(printCounter.Inrement().Count);
        WriteLine(printCoutner.Increment().Count);
        WriteLine(printCounter.Dcrement<int>().Count);
    }
}

Expand the misspelled member name test

Expand the misspelled member name test


namespace JetBrains.TeamCity.NuGet.Tests
{
  public static class NuGetConstants
  {
    public const string DefaultFeedUrl_v1 = "https://go.microsoft.com/fwlink/?LinkID=206669";
    public const string DefaultFeedUrl_v2 = "https://go.microsoft.com/fwlink/?LinkID=230477";
    public const string NuGetDevFeed = "https://dotnet.myget.org/F/nuget-build/api/v2/";
  }
}

namespace JetBrains.TeamCity.NuGet.Tests
{
  public static class NuGetConstants
  {
    public const string DefaultFeedUrl_v1 = "https://packages.nuget.org/v1/FeedService.svc/";
    public const string DefaultFeedUrl_v2 = "https://www.nuget.org/api/v2/";
    public const string NuGetDevFeed = "https://dotnet.myget.org/F/nuget-build/api/v2/";
  }
}

Use direct nuget public feed URLs

Use direct nuget public feed URLs


namespace Bakery.Cqrs
{
	using SimpleInjector;
	using System;
	using System.Linq;
	using System.Threading.Tasks;

	public class SimpleInjectorDispatcher
		: IDispatcher
	{
		private readonly Container container;

		public SimpleInjectorDispatcher(Container container)
		{
			if (container == null)
				throw new ArgumentNullException(nameof(container));

			this.container = container;
		}

		public async Task CommandAsync<TCommand>(TCommand command)
			where TCommand : ICommand
		{
			if (command == null)
				throw new ArgumentNullException(nameof(command));

			var handlers = container.GetAllInstances<ICommandHandler<TCommand>>().ToArray();

			if (!handlers.Any())
				throw new NoRegistrationFoundException(typeof(TCommand));

			foreach (var handler in handlers)
				await handler.HandleAsync(command);
		}

		public async Task<TResult> QueryAsync<TResult>(IQuery<TResult> query)
		{
			if (query == null)
				throw new ArgumentNullException(nameof(query));

			var handlerType = typeof(IQueryHandler<,>).MakeGenericType(query.GetType(), typeof(TResult));
			var handlers = container.GetAllInstances(handlerType);

			if (!handlers.Any())
				throw new NoRegistrationFoundException(query.GetType());

			if (handlers.Multiple())
				throw new MultipleRegistrationsFoundException(query.GetType());

			dynamic handler = handlers.Single();

			return await handler.HandleAsync(query as dynamic);
		}
	}
}

namespace Bakery.Cqrs
{
	using SimpleInjector;
	using System;
	using System.Linq;
	using System.Threading.Tasks;

	public class SimpleInjectorDispatcher
		: IDispatcher
	{
		private readonly Container container;

		public SimpleInjectorDispatcher(Container container)
		{
			if (container == null)
				throw new ArgumentNullException(nameof(container));

			this.container = container;
		}

		public async Task CommandAsync<TCommand>(TCommand command)
			where TCommand : ICommand
		{
			if (command == null)
				throw new ArgumentNullException(nameof(command));

			var handlers = container.GetAllInstances<ICommandHandler<TCommand>>().ToArray();

			if (!handlers.Any())
				throw new NoRegistrationFoundException(typeof(TCommand));

			foreach (var handler in handlers)
				await handler.HandleAsync(command);
		}

		public async Task<TResult> QueryAsync<TResult>(IQuery<TResult> query)
		{
			if (query == null)
				throw new ArgumentNullException(nameof(query));

			var handlerType = typeof(IQueryHandler<,>).MakeGenericType(query.GetType(), typeof(TResult));
			var handlers = container.GetAllInstances(handlerType).ToArray();

			if (!handlers.Any())
				throw new NoRegistrationFoundException(query.GetType());

			if (handlers.Multiple())
				throw new MultipleRegistrationsFoundException(query.GetType());

			dynamic handler = handlers.Single();

			return await handler.HandleAsync(query as dynamic);
		}
	}
}

Convert candidates to an array.

Convert candidates to an array.


using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;

namespace PixelPet {
	/// <summary>
	/// PixelPet workbench instance.
	/// </summary>
	public class Workbench {
		public IList<Color> Palette { get; }
		public Bitmap Bitmap { get; private set; }
		public Graphics Graphics { get; private set; }
		public MemoryStream Stream { get; private set; }

		public Workbench() {
			this.Palette = new List<Color>();
			ClearBitmap(8, 8);
			this.Stream = new MemoryStream();
		}

		public void ClearBitmap(int width, int height) {
			Bitmap bmp = null;
			try {
				bmp = new Bitmap(width, height, PixelFormat.Format32bppArgb);
				SetBitmap(bmp);
			} finally {
				if (bmp != null) {
					bmp.Dispose();
				}
			}
			this.Graphics.Clear(Color.Transparent);
			this.Graphics.Flush();
		}

		public void SetBitmap(Bitmap bmp) {
			if (this.Graphics != null) {
				this.Graphics.Dispose();
			}
			if (this.Bitmap != null) {
				this.Bitmap.Dispose();
			}
			this.Bitmap = bmp;
			this.Graphics = Graphics.FromImage(this.Bitmap);
		}
	}
}

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;

namespace PixelPet {
	/// <summary>
	/// PixelPet workbench instance.
	/// </summary>
	public class Workbench {
		public IList<Color> Palette { get; }
		public Bitmap Bitmap { get; private set; }
		public Graphics Graphics { get; private set; }
		public MemoryStream Stream { get; private set; }

		public Workbench() {
			this.Palette = new List<Color>();
			ClearBitmap(8, 8);
			this.Stream = new MemoryStream();
		}

		public void ClearBitmap(int width, int height) {
			this.Bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb);
			this.Graphics = Graphics.FromImage(this.Bitmap);

			this.Graphics.Clear(Color.Transparent);
			this.Graphics.Flush();
		}

		public void SetBitmap(Bitmap bmp) {
			if (this.Graphics != null) {
				this.Graphics.Dispose();
			}
			if (this.Bitmap != null) {
				this.Bitmap.Dispose();
			}
			this.Bitmap = bmp;
			this.Graphics = Graphics.FromImage(this.Bitmap);
		}
	}
}

Fix Clear-Bitmap being completely broken now, oops.


using DeJson;
using System.Collections.Generic;
using System;
using System.IO;
using UnityEngine;

namespace HappyFunTimes
{
    public class HFTWebFileLoader
    {
        // TODO: Put this in one place
        static private string HFT_WEB_PATH = "HappyFunTimesAutoGeneratedDoNotEdit/";
        static private string HFT_WEB_DIR = "HappyFunTimesAutoGeneratedDoNotEdit/__dir__";

        static public void LoadFiles(HFTWebFileDB db)
        {
            TextAsset dirTxt = Resources.Load(HFT_WEB_DIR, typeof(TextAsset)) as TextAsset;
            if (dirTxt == null)
            {
                Debug.LogError("could not load: " + HFT_WEB_DIR);
                return;
            }

            Deserializer deserializer = new Deserializer();
            string[] files = deserializer.Deserialize<string[] >(dirTxt.text);

            foreach (string file in files)
            {
                string path = HFT_WEB_PATH + file;
                TextAsset asset = Resources.Load(path) as TextAsset;
                if (asset == null)
                {
                    Debug.LogError("Could not load: " + path);
                }
                else
                {
                    db.AddFile(file, asset.bytes);
                }
            }

        }
    }

}  // namespace HappyFunTimes

using DeJson;
using System.Collections.Generic;
using System;
using System.IO;
using UnityEngine;

namespace HappyFunTimes
{
    public class HFTWebFileLoader
    {
        // TODO: Put this in one place
        static private string HFT_WEB_PATH = "HappyFunTimesAutoGeneratedDoNotEdit/";
        static private string HFT_WEB_DIR = "HappyFunTimesAutoGeneratedDoNotEdit/__dir__";

        static public void LoadFiles(HFTWebFileDB db)
        {
            TextAsset dirTxt = Resources.Load<TextAsset>(HFT_WEB_DIR);
            if (dirTxt == null)
            {
                Debug.LogError("could not load: " + HFT_WEB_DIR);
                return;
            }

            Deserializer deserializer = new Deserializer();
            string[] files = deserializer.Deserialize<string[] >(dirTxt.text);

            foreach (string file in files)
            {
                string path = HFT_WEB_PATH + file;
                TextAsset asset = Resources.Load(path) as TextAsset;
                if (asset == null)
                {
                    Debug.LogError("Could not load: " + path);
                }
                else
                {
                    db.AddFile(file, asset.bytes);
                }
            }

        }
    }

}  // namespace HappyFunTimes

Use templated version of Resources.Load

Use templated version of Resources.Load


using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.Specialized;
using MonoTorrent.BEncoding;
using System.Net;

namespace MonoTorrent.Tracker
{
    public abstract class RequestParameters : EventArgs
    {
        protected internal static readonly string FailureKey = "failure reason";
        protected internal static readonly string WarningKey = "warning"; //FIXME: Check this, i know it's wrong!

        private IPAddress remoteAddress;
        private NameValueCollection parameters;
        private BEncodedDictionary response;

        public abstract bool IsValid { get; }

        public NameValueCollection Parameters
        {
            get { return parameters; }
        }

        public BEncodedDictionary Response
        {
            get { return response; }
        }

        public IPAddress RemoteAddress
        {
            get { return remoteAddress; }
            protected set { remoteAddress = value; }
        }

        protected RequestParameters(NameValueCollection parameters, IPAddress address)
        {
            this.parameters = parameters;
            remoteAddress = address;
            response = new BEncodedDictionary();
        }
    }
}

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.Specialized;
using MonoTorrent.BEncoding;
using System.Net;

namespace MonoTorrent.Tracker
{
    public abstract class RequestParameters : EventArgs
    {
        protected internal static readonly string FailureKey = "failure reason";
        protected internal static readonly string WarningKey = "warning message";

        private IPAddress remoteAddress;
        private NameValueCollection parameters;
        private BEncodedDictionary response;

        public abstract bool IsValid { get; }

        public NameValueCollection Parameters
        {
            get { return parameters; }
        }

        public BEncodedDictionary Response
        {
            get { return response; }
        }

        public IPAddress RemoteAddress
        {
            get { return remoteAddress; }
            protected set { remoteAddress = value; }
        }

        protected RequestParameters(NameValueCollection parameters, IPAddress address)
        {
            this.parameters = parameters;
            remoteAddress = address;
            response = new BEncodedDictionary();
        }
    }
}

Use the correct string for the warning key. (patch by olivier)

svn path=/trunk/bitsharp/; revision=143085


using System.Collections.Generic;
using StockportContentApi.Model;
using StockportContentApi.Utils;
using System.Linq;
using System.Threading.Tasks;

namespace StockportContentApi.Services
{
    public interface IHealthcheckService
    {
        Task<Healthcheck> Get();
    }

    public class HealthcheckService : IHealthcheckService
    {
        private readonly string _appVersion;
        private readonly string _sha;
        private readonly IFileWrapper _fileWrapper;
        private readonly string _environment;
        private readonly ICache _cacheWrapper;

        public HealthcheckService(string appVersionPath, string shaPath, IFileWrapper fileWrapper, string environment, ICache cacheWrapper)
        {
            _fileWrapper = fileWrapper;
            _appVersion = GetFirstFileLineOrDefault(appVersionPath, "dev");
            _sha = GetFirstFileLineOrDefault(shaPath, string.Empty);
            _environment = environment;
            _cacheWrapper = cacheWrapper;
        }

        private string GetFirstFileLineOrDefault(string filePath, string defaultValue)
        {
            if (_fileWrapper.Exists(filePath))
            {
                var firstLine = _fileWrapper.ReadAllLines(filePath).FirstOrDefault();
                if (!string.IsNullOrEmpty(firstLine))
                    return firstLine;
            }
            return defaultValue;
        }

        public async Task<Healthcheck> Get()
        {
            // Commented out because it was breaking prod.
            //var keys = await _cacheWrapper.GetKeys();
            return new Healthcheck(_appVersion, _sha, _environment, new List<RedisValueData>());
        }
    }
}

using System.Collections.Generic;
using StockportContentApi.Model;
using StockportContentApi.Utils;
using System.Linq;
using System.Threading.Tasks;

namespace StockportContentApi.Services
{
    public interface IHealthcheckService
    {
        Task<Healthcheck> Get();
    }

    public class HealthcheckService : IHealthcheckService
    {
        private readonly string _appVersion;
        private readonly string _sha;
        private readonly IFileWrapper _fileWrapper;
        private readonly string _environment;
        private readonly ICache _cacheWrapper;

        public HealthcheckService(string appVersionPath, string shaPath, IFileWrapper fileWrapper, string environment, ICache cacheWrapper)
        {
            _fileWrapper = fileWrapper;
            _appVersion = GetFirstFileLineOrDefault(appVersionPath, "dev");
            _sha = GetFirstFileLineOrDefault(shaPath, string.Empty);
            _environment = environment;
            _cacheWrapper = cacheWrapper;
        }

        private string GetFirstFileLineOrDefault(string filePath, string defaultValue)
        {
            if (_fileWrapper.Exists(filePath))
            {
                var firstLine = _fileWrapper.ReadAllLines(filePath).FirstOrDefault();
                if (!string.IsNullOrEmpty(firstLine))
                    return firstLine.Trim();
            }
            return defaultValue.Trim();
        }

        public async Task<Healthcheck> Get()
        {
            // Commented out because it was breaking prod.
            //var keys = await _cacheWrapper.GetKeys();
            return new Healthcheck(_appVersion, _sha, _environment, new List<RedisValueData>());
        }
    }
}

Remove whitespace around app version

fix(Healthcheck): Remove whitespace around app version


// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.IO;

namespace Microsoft.CodeAnalysis.RulesetToEditorconfig
{
    internal static class Program
    {
        public static int Main(string[] args)
        {
            if (args.Length < 1 || args.Length > 2)
            {
                ShowUsage();
                return 1;
            }

            var rulesetFilePath = args[0];
            var editorconfigFilePath = args.Length == 2 ?
                args[1] :
                Path.Combine(Environment.CurrentDirectory, ".editorconfig");
            try
            {
                Converter.GenerateEditorconfig(rulesetFilePath, editorconfigFilePath);
            }
            catch (IOException ex)
            {
                Console.WriteLine(ex.Message);
                return 2;
            }

            Console.WriteLine($"Successfully converted to '{editorconfigFilePath}'");
            return 0;

            static void ShowUsage()
            {
                Console.WriteLine("Usage: RulesetToEditorconfigConverter.exe <%ruleset_file%> [<%path_to_editorconfig%>]");
                return;
            }
        }
    }
}

// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.IO;

namespace Microsoft.CodeAnalysis.RulesetToEditorconfig
{
    internal static class Program
    {
        public static int Main(string[] args)
        {
            if (args.Length is < 1 or > 2)
            {
                ShowUsage();
                return 1;
            }

            var rulesetFilePath = args[0];
            var editorconfigFilePath = args.Length == 2 ?
                args[1] :
                Path.Combine(Environment.CurrentDirectory, ".editorconfig");
            try
            {
                Converter.GenerateEditorconfig(rulesetFilePath, editorconfigFilePath);
            }
            catch (IOException ex)
            {
                Console.WriteLine(ex.Message);
                return 2;
            }

            Console.WriteLine($"Successfully converted to '{editorconfigFilePath}'");
            return 0;

            static void ShowUsage()
            {
                Console.WriteLine("Usage: RulesetToEditorconfigConverter.exe <%ruleset_file%> [<%path_to_editorconfig%>]");
                return;
            }
        }
    }
}

Fix for one more IDE0078

Fix for one more IDE0078


// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

namespace Microsoft.CodeAnalysis.Internal.Log
{
    internal sealed class StatisticLogAggregator : AbstractLogAggregator<StatisticLogAggregator.StatisticCounter>
    {
        protected override StatisticCounter CreateCounter()
        {
            return new StatisticCounter();
        }

        public void AddDataPoint(object key, int value)
        {
            var counter = GetCounter(key);
            counter.AddDataPoint(value);
        }

        public StatisticResult GetStaticticResult(object key)
        {
            if (TryGetCounter(key, out var counter))
            {
                return counter.GetStatisticResult();
            }

            return default;
        }

        internal sealed class StatisticCounter
        {
            private int _count;
            private int _maximum;
            private int _mininum;

            private int _total;

            public void AddDataPoint(int value)
            {
                if (_count == 0 || value > _maximum)
                {
                    _maximum = value;
                }

                if (_count == 0 || value < _mininum)
                {
                    _mininum = value;
                }

                _count++;
                _total += value;
            }

            public StatisticResult GetStatisticResult()
            {
                if (_count == 0)
                {
                    return default;
                }
                else
                {
                    return new StatisticResult(_maximum, _mininum, median: null, mean: _total / _count, range: _maximum - _mininum, mode: null, count: _count);
                }
            }
        }
    }
}

// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

namespace Microsoft.CodeAnalysis.Internal.Log
{
    internal sealed class StatisticLogAggregator : AbstractLogAggregator<StatisticLogAggregator.StatisticCounter>
    {
        protected override StatisticCounter CreateCounter()
        {
            return new StatisticCounter();
        }

        public void AddDataPoint(object key, int value)
        {
            var counter = GetCounter(key);
            counter.AddDataPoint(value);
        }

        public StatisticResult GetStaticticResult(object key)
        {
            if (TryGetCounter(key, out var counter))
            {
                return counter.GetStatisticResult();
            }

            return default;
        }

        internal sealed class StatisticCounter
        {
            private readonly object _lock = new object();
            private int _count;
            private int _maximum;
            private int _mininum;

            private int _total;

            public void AddDataPoint(int value)
            {
                lock (_lock)
                {
                    if (_count == 0 || value > _maximum)
                    {
                        _maximum = value;
                    }

                    if (_count == 0 || value < _mininum)
                    {
                        _mininum = value;
                    }

                    _count++;
                    _total += value;
                }
            }

            public StatisticResult GetStatisticResult()
            {
                if (_count == 0)
                {
                    return default;
                }
                else
                {
                    return new StatisticResult(_maximum, _mininum, median: null, mean: _total / _count, range: _maximum - _mininum, mode: null, count: _count);
                }
            }
        }
    }
}

Add a lock for StatisticCounter

Add a lock for StatisticCounter


using System;
using System.Collections.Generic;

namespace OneDrive
{
    public class ThumbnailRetrievalOptions : RetrievalOptions
    {
        /// <summary>
        /// List of thumbnail size names to return
        /// </summary>
        public string[] SelectThumbnailNames { get; set; }

        /// <summary>
        /// Retrieve the default thumbnails for an item
        /// </summary>
        public static ThumbnailRetrievalOptions Default { get { return new ThumbnailRetrievalOptions(); } }

        /// <summary>
        /// Returns a string like "select=small,medium" that can be used in an expand parameter value
        /// </summary>
        /// <returns></returns>
        public override IEnumerable<ODataOption> ToOptions()
        {
            List<ODataOption> options = new List<ODataOption>();

            SelectOData thumbnailSelect = null;
            if (SelectThumbnailNames != null && SelectThumbnailNames.Length > 0)
                thumbnailSelect = new SelectOData { FieldNames = SelectThumbnailNames };

            options.Add(new ExpandOData
            {
                PropertyToExpand = ApiConstants.ThumbnailsRelationshipName,
                Select = thumbnailSelect
            });

            return EmptyCollection;
        }
    }
}

using System;
using System.Collections.Generic;

namespace OneDrive
{
    public class ThumbnailRetrievalOptions : RetrievalOptions
    {

        /// <summary>
        /// List of thumbnail size names to return
        /// </summary>
        public string[] SelectThumbnailNames { get; set; }

        /// <summary>
        /// Retrieve the default thumbnails for an item
        /// </summary>
        public static ThumbnailRetrievalOptions Default { get { return new ThumbnailRetrievalOptions(); } }

        /// <summary>
        /// Returns a string like "select=small,medium" that can be used in an expand parameter value
        /// </summary>
        /// <returns></returns>
        public override IEnumerable<ODataOption> ToOptions()
        {
            List<ODataOption> options = new List<ODataOption>();

            SelectOData thumbnailSelect = null;
            if (SelectThumbnailNames != null && SelectThumbnailNames.Length > 0)
            {
                thumbnailSelect = new SelectOData { FieldNames = SelectThumbnailNames };
                options.Add(thumbnailSelect);
            }

            return options;
        }
    }

    public static class ThumbnailSize
    {
        public const string Small = "small";
        public const string Medium = "medium";
        public const string Large = "large";
        public const string SmallSquare = "smallSquare";
        public const string MediumSquare = "mediumSquare";
        public const string LargeSquare = "largeSquare";

        public static string CustomSize(int width, int height, bool cropped)
        {
            return string.Format("c{0}x{1}{2}", width, height, cropped ? "_Crop" : "");
        }

    }
}

Fix thumbnail retrieval options to actually work


using System;

using InfinniPlatform.Sdk.Types;

using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.Serializers;

namespace InfinniPlatform.DocumentStorage.MongoDB
{
    /// <summary>
    /// Реализует логику сериализации и десериализации <see cref="Time"/> для MongoDB.
    /// </summary>
    internal sealed class MongoTimeBsonSerializer : SerializerBase<Time>
    {
        public static readonly MongoTimeBsonSerializer Default = new MongoTimeBsonSerializer();

        public override Time Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
        {
            var reader = context.Reader;

            var currentBsonType = reader.GetCurrentBsonType();

            long totalSeconds;

            switch (currentBsonType)
            {
                case BsonType.Double:
                    totalSeconds = (long)reader.ReadDouble();
                    break;
                case BsonType.Int64:
                    totalSeconds = reader.ReadInt64();
                    break;
                case BsonType.Int32:
                    totalSeconds = reader.ReadInt32();
                    break;
                default:
                    throw new FormatException($"Cannot deserialize a '{BsonUtils.GetFriendlyTypeName(typeof(Time))}' from BsonType '{currentBsonType}'.");
            }

            return new Time(totalSeconds);
        }

        public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, Time value)
        {
            var writer = context.Writer;

            writer.WriteDouble(value.TotalSeconds);
        }
    }
}

using System;

using InfinniPlatform.Sdk.Types;

using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.Serializers;

namespace InfinniPlatform.DocumentStorage.MongoDB
{
    /// <summary>
    /// Реализует логику сериализации и десериализации <see cref="Time"/> для MongoDB.
    /// </summary>
    internal sealed class MongoTimeBsonSerializer : SerializerBase<Time>
    {
        public static readonly MongoTimeBsonSerializer Default = new MongoTimeBsonSerializer();

        public override Time Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
        {
            var reader = context.Reader;

            var currentBsonType = reader.GetCurrentBsonType();

            double totalSeconds;

            switch (currentBsonType)
            {
                case BsonType.Double:
                    totalSeconds = reader.ReadDouble();
                    break;
                case BsonType.Int64:
                    totalSeconds = reader.ReadInt64();
                    break;
                case BsonType.Int32:
                    totalSeconds = reader.ReadInt32();
                    break;
                default:
                    throw new FormatException($"Cannot deserialize a '{BsonUtils.GetFriendlyTypeName(typeof(Time))}' from BsonType '{currentBsonType}'.");
            }

            return new Time(totalSeconds);
        }

        public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, Time value)
        {
            var writer = context.Writer;

            writer.WriteDouble(value.TotalSeconds);
        }
    }
}

Add BsonSerializer for Date and Time

MC-4171: Add BsonSerializer for Date and Time


using System;
using System.Text;

namespace ExtensionBlocks
{
    public class Beef001a : BeefBase
    {
        public Beef001a(byte[] rawBytes)
            : base(rawBytes)
        {
            if (Signature != 0xbeef001a)
            {
                throw new Exception($"Signature mismatch! Should be Beef001a but is {Signature}");
            }

            var len = 0;
            var index = 10;

            while ((rawBytes[index + len] != 0x0 || rawBytes[index + len + 1] != 0x0))
            {
                len += 1;
            }

            var uname = Encoding.Unicode.GetString(rawBytes, index, len + 1);

            FileDocumentTypeString = uname;

            index += len + 3; // move past string and end of string marker

            //is index 24?

            //TODO get shell item list

            Message =
                "Unsupported Extension block. Please report to Report to saericzimmerman@gmail.com to get it added!";

            VersionOffset = BitConverter.ToInt16(rawBytes, index);
        }

        public string FileDocumentTypeString { get; }

        public override string ToString()
        {
            var sb = new StringBuilder();

            sb.AppendLine(base.ToString());

            sb.AppendLine();

            sb.AppendLine($"File Document Type String: {FileDocumentTypeString}");

            return sb.ToString();
        }
    }
}

using System;
using System.Text;

namespace ExtensionBlocks
{
    public class Beef001a : BeefBase
    {
        public Beef001a(byte[] rawBytes)
            : base(rawBytes)
        {
            if (Signature != 0xbeef001a)
            {
                throw new Exception($"Signature mismatch! Should be Beef001a but is {Signature}");
            }

            var len = 0;
            var index = 10;

            while ((rawBytes[index + len] != 0x0 || rawBytes[index + len + 1] != 0x0))
            {
                len += 1;
            }

            var uname = Encoding.Unicode.GetString(rawBytes, index, len + 1);

            FileDocumentTypeString = uname;

            index += len + 3; // move past string and end of string marker

            //is index 24?

            //TODO get shell item list

            if (index != 38)
            {
                Message =
                    "Unsupported Extension block. Please report to Report to saericzimmerman@gmail.com to get it added!";
            }

            VersionOffset = BitConverter.ToInt16(rawBytes, index);
        }

        public string FileDocumentTypeString { get; }

        public override string ToString()
        {
            var sb = new StringBuilder();

            sb.AppendLine(base.ToString());

            sb.AppendLine();

            sb.AppendLine($"File Document Type String: {FileDocumentTypeString}");

            return sb.ToString();
        }
    }
}

Tweak beef001a to suppress Message when no additional shell items are present


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

using System;
using osu.Framework.Platform;
using osu.Framework.Testing;

namespace osu.Game.Tests.Visual
{
    public abstract class OsuTestCase : TestCase
    {
        public override void RunTest()
        {
            using (var host = new HeadlessGameHost(AppDomain.CurrentDomain.FriendlyName.Replace(' ', '-'), realtime: false))
                host.Run(new OsuTestCaseTestRunner(this));
        }

        public class OsuTestCaseTestRunner : OsuGameBase
        {
            private readonly OsuTestCase testCase;

            public OsuTestCaseTestRunner(OsuTestCase testCase)
            {
                this.testCase = testCase;
            }

            protected override void LoadComplete()
            {
                base.LoadComplete();
                Add(new TestCaseTestRunner.TestRunner(testCase));
            }
        }
    }
}

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

using System;
using osu.Framework.Platform;
using osu.Framework.Testing;

namespace osu.Game.Tests.Visual
{
    public abstract class OsuTestCase : TestCase
    {
        public override void RunTest()
        {
            Storage storage;
            using (var host = new HeadlessGameHost($"test-{Guid.NewGuid()}", realtime: false))
            {
                storage = host.Storage;
                host.Run(new OsuTestCaseTestRunner(this));
            }

            // clean up after each run
            storage.DeleteDirectory(string.Empty);
        }

        public class OsuTestCaseTestRunner : OsuGameBase
        {
            private readonly OsuTestCase testCase;

            public OsuTestCaseTestRunner(OsuTestCase testCase)
            {
                this.testCase = testCase;
            }

            protected override void LoadComplete()
            {
                base.LoadComplete();
                Add(new TestCaseTestRunner.TestRunner(testCase));
            }
        }
    }
}

Fix test case runs not being correctly isolated on mono


using System;
using System.Linq;
using Avalonia;

namespace ControlCatalog.NetCore
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Contains("--fbdev"))
                AppBuilder.Configure<App>()
                    .InitializeWithLinuxFramebuffer(tl => tl.Content = new MainView());
            else
                AppBuilder.Configure<App>()
                    .UsePlatformDetect()
                    .Start<MainWindow>();
        }
    }
}

using System;
using System.Linq;
using Avalonia;

namespace ControlCatalog.NetCore
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Contains("--fbdev")) AppBuilder.Configure<App>().InitializeWithLinuxFramebuffer(tl =>
            {
                tl.Content = new MainView();
                System.Threading.ThreadPool.QueueUserWorkItem(_ => ConsoleSilencer());
            });
            else
                AppBuilder.Configure<App>()
                    .UsePlatformDetect()
                    .Start<MainWindow>();
        }

        static void ConsoleSilencer()
        {
            Console.CursorVisible = false;
            while (true)
                Console.ReadKey();
        }
    }
}

Handle console input in fbdev mode

Handle console input in fbdev mode


using System;
using Glimpse.Core.Extensibility;
using Glimpse.Core.Resource;
using Moq;
using Xunit;

namespace Glimpse.Test.Core.Resource
{
    public class ConfigurationShould
    {
        [Fact]
        public void ReturnProperName()
        {
            var name = "glimpse_config";

            var resource = new ConfigurationResource();

            Assert.Equal(name, ConfigurationResource.InternalName);
            Assert.Equal(name, resource.Name);
        }

        [Fact]
        public void ReturnNoParameterKeys()
        {
            var resource = new ConfigurationResource();
            Assert.Empty(resource.Parameters);
        }

        [Fact]
        public void Execute()
        {
            var contextMock = new Mock<IResourceContext>();

            var resource = new ConfigurationResource();

            Assert.NotNull(resource.Execute(contextMock.Object));
        }
    }
}

using System;
using Glimpse.Core.Extensibility;
using Glimpse.Core.Framework;
using Glimpse.Core.Resource;
using Glimpse.Core.ResourceResult;
using Moq;
using Xunit;

namespace Glimpse.Test.Core.Resource
{
    public class ConfigurationShould
    {
        [Fact]
        public void ReturnProperName()
        {
            var name = "glimpse_config";

            var resource = new ConfigurationResource();

            Assert.Equal(name, ConfigurationResource.InternalName);
            Assert.Equal(name, resource.Name);
        }

        [Fact]
        public void ReturnNoParameterKeys()
        {
            var resource = new ConfigurationResource();
            Assert.Empty(resource.Parameters);
        }

        [Fact]
        public void NotSupportNonPrivilegedExecution()
        {
            var resource = new PopupResource();
            var contextMock = new Mock<IResourceContext>();

            Assert.Throws<NotSupportedException>(() => resource.Execute(contextMock.Object));
        }

        [Fact(Skip = "Need to build out correct test here")]
        public void Execute()
        {
            var contextMock = new Mock<IResourceContext>();
            var configMock = new Mock<IGlimpseConfiguration>();

            var resource = new ConfigurationResource();

            var result = resource.Execute(contextMock.Object, configMock.Object);
            var htmlResourceResult = result as HtmlResourceResult;

            Assert.NotNull(result);
        }
    }
}

Fix broken build because of failing test


using System.Collections.Generic;

using Android.App;
using Android.Content;

namespace Plugin.FirebasePushNotification
{
    [BroadcastReceiver]
    public class PushNotificationActionReceiver : BroadcastReceiver
    {
        public override void OnReceive(Context context, Intent intent)
        {
            IDictionary<string, object> parameters = new Dictionary<string, object>();
            var extras = intent.Extras;

            if (extras != null && !extras.IsEmpty)
            {
                foreach (var key in extras.KeySet())
                {
                    parameters.Add(key, $"{extras.Get(key)}");
                    System.Diagnostics.Debug.WriteLine(key, $"{extras.Get(key)}");
                }
            }
            FirebasePushNotificationManager.RegisterAction(parameters);

            var manager = context.GetSystemService(Context.NotificationService) as NotificationManager;
            var notificationId = extras.GetInt(DefaultPushNotificationHandler.ActionNotificationIdKey, -1);
            if (notificationId != -1)
            {
                var notificationTag = extras.GetString(DefaultPushNotificationHandler.ActionNotificationTagKey, string.Empty);

                if (notificationTag == null)
                {
                    manager.Cancel(notificationId);
                }
                else
                {
                    manager.Cancel(notificationTag, notificationId);
                }
            }
        }
    }
}

using System.Collections.Generic;

using Android.App;
using Android.Content;

namespace Plugin.FirebasePushNotification
{
    [BroadcastReceiver(Enabled = true, Exported = false)]
    public class PushNotificationActionReceiver : BroadcastReceiver
    {
        public override void OnReceive(Context context, Intent intent)
        {
            IDictionary<string, object> parameters = new Dictionary<string, object>();
            var extras = intent.Extras;

            if (extras != null && !extras.IsEmpty)
            {
                foreach (var key in extras.KeySet())
                {
                    parameters.Add(key, $"{extras.Get(key)}");
                    System.Diagnostics.Debug.WriteLine(key, $"{extras.Get(key)}");
                }
            }
            FirebasePushNotificationManager.RegisterAction(parameters);

            var manager = context.GetSystemService(Context.NotificationService) as NotificationManager;
            var notificationId = extras.GetInt(DefaultPushNotificationHandler.ActionNotificationIdKey, -1);
            if (notificationId != -1)
            {
                var notificationTag = extras.GetString(DefaultPushNotificationHandler.ActionNotificationTagKey, string.Empty);

                if (notificationTag == null)
                {
                    manager.Cancel(notificationId);
                }
                else
                {
                    manager.Cancel(notificationTag, notificationId);
                }
            }
        }
    }
}

Add Enabled = true, Exported = false

Add Enabled = true, Exported = false


using System;
using System.Threading;
using Microsoft.SPOT;

namespace AgentIntervals
{
    public delegate void HeartBeatEventHandler(object sender, EventArgs e);

    public class HeartBeat
    {
        private Timer _timer;
        private int _period;

        public event HeartBeatEventHandler OnHeartBeat;

        public HeartBeat(int period)
        {
            _period = period;
        }

        private void TimerCallback(object state)
        {
            if (OnHeartBeat != null)
            {
                OnHeartBeat(this, new EventArgs());
            }
        }

        public void Start()
        {
            Start(0);
        }

        public void Start(int delay)
        {
            if (_timer != null) return;

            _timer = new Timer(TimerCallback, null, delay, _period);
        }

        public void Stop()
        {
            if (_timer == null) return;

            _timer.Dispose();
            _timer = null;
        }

        public bool Toggle()
        {
            return Toggle(0);
        }

        public bool Toggle(int delay)
        {
            bool started;
            if (_timer == null)
            {
                Start(delay);
                started = true;
            }
            else
            {
                Stop();
                started = false;
            }
            return started;
        }

        public void Reset()
        {
            Reset(0);
        }

        public void Reset(int delay)
        {
            Stop();
            Start(delay);
        }

        public void ChangePeriod(int newPeriod)
        {
            _period = newPeriod;
        }
    }
}

using System;
using System.Threading;
using Microsoft.SPOT;

namespace AgentIntervals
{
    public delegate void HeartBeatEventHandler(object sender, EventArgs e);

    public class HeartBeat
    {
        private Timer _timer;
        private int _period;

        public event HeartBeatEventHandler OnHeartBeat;

        public HeartBeat(int period)
        {
            _period = period;
        }

        private void TimerCallback(object state)
        {
            if (OnHeartBeat != null)
            {
                OnHeartBeat(this, new EventArgs());
            }
        }

        public void Start()
        {
            Start(0);
        }

        public void Start(int delay)
        {
            if (_timer != null) return;

            _timer = new Timer(TimerCallback, null, delay, _period);
        }

        public void Stop()
        {
            if (_timer == null) return;

            _timer.Dispose();
            _timer = null;
        }

        public bool Toggle()
        {
            return Toggle(0);
        }

        public bool Toggle(int delay)
        {
            bool started;
            if (_timer == null)
            {
                Start(delay);
                started = true;
            }
            else
            {
                Stop();
                started = false;
            }
            return started;
        }

        public void Reset()
        {
            Reset(0);
        }

        public void Reset(int delay)
        {
            Stop();
            Start(delay);
        }

        public void ChangePeriod(int newPeriod)
        {
            _period = newPeriod;

            if (_timer != null)
            {
                Reset();
            }
        }
    }
}

Reset timer if period is changed while it is running.


using AppKit;
using Foundation;

namespace Skia.OSX.Demo
{
	[Register ("AppDelegate")]
	public partial class AppDelegate : NSApplicationDelegate
	{
		public AppDelegate ()
		{
		}

		public override void DidFinishLaunching (NSNotification notification)
		{
			// Insert code here to initialize your application
		}

		public override void WillTerminate (NSNotification notification)
		{
			// Insert code here to tear down your application
		}
	}
}

using AppKit;
using Foundation;

namespace Skia.OSX.Demo
{
	[Register ("AppDelegate")]
	public partial class AppDelegate : NSApplicationDelegate
	{
		public AppDelegate ()
		{
		}

		public override void DidFinishLaunching (NSNotification notification)
		{
			// Insert code here to initialize your application
		}

		public override void WillTerminate (NSNotification notification)
		{
			// Insert code here to tear down your application
		}

		public override bool ApplicationShouldTerminateAfterLastWindowClosed (NSApplication sender)
		{
			return true;
		}
	}
}

Quit the Mac app after the window is closed


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

using osu.Game.Rulesets.Mods;

namespace osu.Game.Rulesets.Taiko.Mods
{
    public class TaikoModEasy : ModEasy
    {
        public override string Description => @"Beats move slower, less accuracy required, and three lives!";
    }
}

// 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 Humanizer;
using osu.Framework.Bindables;
using osu.Framework.Graphics.Sprites;
using osu.Game.Beatmaps;
using osu.Game.Configuration;
using osu.Game.Graphics;
using osu.Game.Rulesets.Mods;

namespace osu.Game.Rulesets.Taiko.Mods
{
    public class TaikoModEasy : Mod, IApplicableToDifficulty, IApplicableFailOverride
    {
        public override string Name => "Easy";
        public override string Acronym => "EZ";
        public override string Description => @"Beats move slower, less accuracy required";
        public override IconUsage? Icon => OsuIcon.ModEasy;
        public override ModType Type => ModType.DifficultyReduction;
        public override double ScoreMultiplier => 0.5;
        public override bool Ranked => true;
        public override Type[] IncompatibleMods => new[] { typeof(ModHardRock), typeof(ModDifficultyAdjust) };

        public void ReadFromDifficulty(BeatmapDifficulty difficulty)
        {
        }

        public void ApplyToDifficulty(BeatmapDifficulty difficulty)
        {
            const float ratio = 0.5f;
            difficulty.CircleSize *= ratio;
            difficulty.ApproachRate *= ratio;
            difficulty.DrainRate *= ratio;
            difficulty.OverallDifficulty *= ratio;
        }

        public bool PerformFail() => true;

        public bool RestartOnFail => false;

    }
}

Make EZ mod able to fail in Taiko

Make EZ mod able to fail in Taiko


using NUnit.Framework;
using System;
using System.Linq.Expressions;
using TestStack.FluentMVCTesting.Internal;

namespace TestStack.FluentMVCTesting.Tests.Internal
{
    [TestFixture]
    public class ExpressionInspectorShould
    {
        [Test]
        public void Correctly_parse_equality_comparison_with_string_operands()
        {
            Expression<Func<string, bool>> func = text => text == "any";
            ExpressionInspector sut = new ExpressionInspector();
            var actual = sut.Inspect(func);
            Assert.AreEqual("text => text == \"any\"", actual);
        }

        [Test]
        public void Correctly_parse_equality_comparison_with_int_operands()
        {
            Expression<Func<int, bool>> func = number => number == 5;
            ExpressionInspector sut = new ExpressionInspector();
            var actual = sut.Inspect(func);
            Assert.AreEqual("number => number == 5", actual);
        }

        [Test]
        public void Correctly_parse_inequality_comparison_with_int_operands()
        {
            Expression<Func<int, bool>> func = number => number != 5;
            ExpressionInspector sut = new ExpressionInspector();
            var actual = sut.Inspect(func);
            Assert.AreEqual("number => number != 5", actual);
        }
    }
}

using NUnit.Framework;
using System;
using System.Linq.Expressions;
using TestStack.FluentMVCTesting.Internal;

namespace TestStack.FluentMVCTesting.Tests.Internal
{
    [TestFixture]
    public class ExpressionInspectorShould
    {
        [Test]
        public void Correctly_parse_equality_comparison_with_string_operands()
        {
            Expression<Func<string, bool>> func = text => text == "any";
            ExpressionInspector sut = new ExpressionInspector();
            var actual = sut.Inspect(func);
            Assert.AreEqual("text => text == \"any\"", actual);
        }

        [Test]
        public void Correctly_parse_equality_comparison_with_int_operands()
        {
            Expression<Func<int, bool>> func = number => number == 5;
            ExpressionInspector sut = new ExpressionInspector();
            var actual = sut.Inspect(func);
            Assert.AreEqual("number => number == 5", actual);
        }

        [Test]
        public void Correctly_parse_inequality_comparison_with_int_operands()
        {
            Expression<Func<int, bool>> func = number => number != 5;
            ExpressionInspector sut = new ExpressionInspector();
            var actual = sut.Inspect(func);
            Assert.AreEqual("number => number != 5", actual);
        }

        [Test]
        public void Correctly_parse_equality_comparison_with_captured_constant_operand()
        {
            const int Number = 5;
            Expression<Func<int, bool>> func = number => number == Number;
            ExpressionInspector sut = new ExpressionInspector();
            var actual = sut.Inspect(func);
            Assert.AreEqual("number => number == " + Number, actual);
        }
    }
}

Support for parsing equality operator with constant operand.


using System.Threading.Tasks;
using NSubstitute;
using Ploeh.AutoFixture;
using Ploeh.AutoFixture.Xunit;
using TeamCityApi.Domain;
using TeamCityApi.Locators;
using TeamCityApi.Tests.Helpers;
using TeamCityApi.Tests.Scenarios;
using TeamCityApi.UseCases;
using Xunit;
using Xunit.Extensions;

namespace TeamCityApi.Tests.UseCases
{
    public class CloneRootBuildConfigUseCaseTests
    {
        [Theory]
        [AutoNSubstituteData]
        public void Should_clone_root_build_config(
            int buildId,
            string newNameSyntax,
            ITeamCityClient client,
            IFixture fixture)
        {
            var sourceBuildId = buildId.ToString();
            var scenario = new SingleBuildScenario(fixture, client, sourceBuildId);
            var sut = new CloneRootBuildConfigUseCase(client);

            sut.Execute(sourceBuildId, newNameSyntax).Wait();

            var newBuildConfigName = scenario.BuildConfig.Name + Consts.SuffixSeparator + newNameSyntax;
            client.BuildConfigs.Received()
                .CopyBuildConfiguration(scenario.Project.Id, newBuildConfigName, scenario.BuildConfig.Id, Arg.Any<bool>(), Arg.Any<bool>());
        }
    }
}

using System.Threading.Tasks;
using NSubstitute;
using Ploeh.AutoFixture;
using Ploeh.AutoFixture.Xunit;
using TeamCityApi.Domain;
using TeamCityApi.Locators;
using TeamCityApi.Tests.Helpers;
using TeamCityApi.Tests.Scenarios;
using TeamCityApi.UseCases;
using Xunit;
using Xunit.Extensions;

namespace TeamCityApi.Tests.UseCases
{
    public class CloneRootBuildConfigUseCaseTests
    {
        [Theory]
        [AutoNSubstituteData]
        public void Should_clone_root_build_config(
            int buildId,
            string newNameSyntax,
            ITeamCityClient client,
            IFixture fixture)
        {
            var sourceBuildId = buildId.ToString();
            var scenario = new SingleBuildScenario(fixture, client, sourceBuildId);
            var sut = new CloneRootBuildConfigUseCase(client);

            sut.Execute(sourceBuildId, newNameSyntax).Wait();

            var newBuildConfigName = scenario.BuildConfig.Name + Consts.SuffixSeparator + newNameSyntax;
            client.BuildConfigs.Received(1)
                .CopyBuildConfiguration(scenario.Project.Id, newBuildConfigName, scenario.BuildConfig.Id, Arg.Any<bool>(), Arg.Any<bool>());
        }
    }
}

Make clone root build config test more strict

By expecting only single call to API made


@using System.Configuration;
@{
    ViewBag.Title = "Login";
}

<div id="root" style="width: 320px; margin: 40px auto; padding: 10px; border-style: dashed; border-width: 1px;">
    embeded area
</div>
@Html.AntiForgeryToken()
<script src="https://cdn.auth0.com/js/lock-8.2.2.min.js"></script>
<script>

    var lock = new Auth0Lock('@ConfigurationManager.AppSettings["auth0:ClientId"]', '@ConfigurationManager.AppSettings["auth0:Domain"]');

    var xsrf = document.getElementsByName("__RequestVerificationToken")[0].value;

    lock.show({
        container: 'root',
        callbackURL: window.location.origin + '/signin-auth0',
        responseType: 'code',
        authParams: {
            scope: 'openid profile',
            state: 'xsrf=' + xsrf + '&ru=' + '@ViewBag.ReturnUrl'
        }
    });
</script>

@using System.Configuration;
@{
    ViewBag.Title = "Login";
}

<div id="root" style="width: 320px; margin: 40px auto; padding: 10px; border-style: dashed; border-width: 1px;">
    embeded area
</div>
@Html.AntiForgeryToken()
<script src="https://cdn.auth0.com/js/lock-9.0.js"></script>
<script>

    var lock = new Auth0Lock('@ConfigurationManager.AppSettings["auth0:ClientId"]', '@ConfigurationManager.AppSettings["auth0:Domain"]');

    var xsrf = document.getElementsByName("__RequestVerificationToken")[0].value;

    lock.show({
        container: 'root',
        callbackURL: window.location.origin + '/signin-auth0',
        responseType: 'code',
        authParams: {
            scope: 'openid profile',
            state: 'xsrf=' + xsrf + '&ru=' + '@ViewBag.ReturnUrl'
        }
    });
</script>

Update lock version to 9.0

Update lock version to 9.0


using Umbraco.Core;
using Umbraco.Core.PropertyEditors;

namespace Umbraco.Web.PropertyEditors
{
    [PropertyEditor(Constants.PropertyEditors.TextboxMultipleAlias, "Textarea", "textarea", IsParameterEditor = true)]
    public class TextAreaPropertyEditor : PropertyEditor
    {
    }
}

using Umbraco.Core;
using Umbraco.Core.PropertyEditors;

namespace Umbraco.Web.PropertyEditors
{
    [PropertyEditor(Constants.PropertyEditors.TextboxMultipleAlias, "Textarea", "textarea", IsParameterEditor = true, ValueType = "TEXT")]
    public class TextAreaPropertyEditor : PropertyEditor
    {
    }
}

Set value type for Textarea to "TEXT".

Set value type for Textarea to "TEXT".

This should fix http://issues.umbraco.org/issue/U4-5063


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

using UnityEngine;

namespace HoloToolkit.Unity
{
    public static class EditorUtils
    {
        /// <summary>
        /// Deletes all objects in the scene
        /// </summary>
        public static void ClearScene()
        {
            foreach (var gameObject in Object.FindObjectsOfType<GameObject>())
            {
                //only destroy root objects
                if (gameObject.transform.parent == null)
                {
                    Object.DestroyImmediate(gameObject);
                }
            }
        }
    }
}

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

using System.Linq;
using UnityEngine;

namespace HoloToolkit.Unity
{
    public static class EditorUtils
    {
        /// <summary>
        /// Deletes all objects in the scene
        /// </summary>
        public static void ClearScene()
        {
            foreach (var transform in Object.FindObjectsOfType<Transform>().Select(t => t.root).Distinct().ToList())
            {
                Object.DestroyImmediate(transform.gameObject);
            }
        }
    }
}

Rework clear scene method by collecting all roots


namespace dotless.Core.Parser.Functions
{
    using System.Linq;
    using Infrastructure;
    using Infrastructure.Nodes;
    using Tree;
    using Utils;

    public class RgbaFunction : Function
    {
        protected override Node Evaluate(Env env)
        {
            if (Arguments.Count == 2)
            {
                var color = Guard.ExpectNode<Color>(Arguments[0], this, Location);
                var number = Guard.ExpectNode<Number>(Arguments[1], this, Location);

                return new Color(color.RGB, number.Value);
            }

            Guard.ExpectNumArguments(4, Arguments.Count, this, Location);
            var args = Guard.ExpectAllNodes<Number>(Arguments, this, Location);

            var values = args.Select(n => n.Value).ToList();
            var rgb = values.Take(3).ToArray();
            var alpha = values[3];

            return new Color(rgb, alpha);
        }
    }
}

namespace dotless.Core.Parser.Functions
{
    using System.Linq;
    using Infrastructure;
    using Infrastructure.Nodes;
    using Tree;
    using Utils;

    public class RgbaFunction : Function
    {
        protected override Node Evaluate(Env env)
        {
            if (Arguments.Count == 2)
            {
                var color = Guard.ExpectNode<Color>(Arguments[0], this, Location);
                var number = Guard.ExpectNode<Number>(Arguments[1], this, Location);

                return new Color(color.RGB, number.Value);
            }

            Guard.ExpectNumArguments(4, Arguments.Count, this, Location);
            var args = Guard.ExpectAllNodes<Number>(Arguments, this, Location);

            var rgb = args.Take(3).Select(n => n.ToNumber(255.0)).ToArray();
            var alpha = args[3].ToNumber(1.0);

            return new Color(rgb, alpha);
        }
    }
}

Fix percent conversion to color.

Fix percent conversion to color.


//------------------------------------------------------------------------------
// <copyright file="SharedAssemblyInfo.cs" company="Microsoft">
//    Copyright (c) Microsoft Corporation
// </copyright>
// <summary>
//      Assembly global configuration.
// </summary>
//------------------------------------------------------------------------------

using System;
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;

[assembly: AssemblyVersion("0.9.0.0")]
[assembly: AssemblyFileVersion("0.9.0.0")]

[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Microsoft Azure Storage")]
[assembly: AssemblyCopyright("Copyright © 2018 Microsoft Corp.")]
[assembly: AssemblyTrademark("Microsoft ® is a registered trademark of Microsoft Corporation.")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components.  If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

[assembly: NeutralResourcesLanguageAttribute("en-US")]

[assembly: CLSCompliant(false)]

//------------------------------------------------------------------------------
// <copyright file="SharedAssemblyInfo.cs" company="Microsoft">
//    Copyright (c) Microsoft Corporation
// </copyright>
// <summary>
//      Assembly global configuration.
// </summary>
//------------------------------------------------------------------------------

using System;
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;

[assembly: AssemblyVersion("0.8.1.0")]
[assembly: AssemblyFileVersion("0.8.1.0")]

[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Microsoft Azure Storage")]
[assembly: AssemblyCopyright("Copyright © 2018 Microsoft Corp.")]
[assembly: AssemblyTrademark("Microsoft ® is a registered trademark of Microsoft Corporation.")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components.  If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

[assembly: NeutralResourcesLanguageAttribute("en-US")]

[assembly: CLSCompliant(false)]

Update DMLib version to 0.8.1.0

Update DMLib version to 0.8.1.0


@model SFA.DAS.EmployerAccounts.Web.OrchestratorResponse<SFA.DAS.EmployerAccounts.Web.ViewModels.AccountDashboardViewModel>

@{
    ViewBag.Title = "Home";
    ViewBag.PageID = "page-company-homepage";
}

Your employer account

@Model.Data.Account.Name

                @Html.Action("Row1Panel1", new { model = Model.Data })
                @Html.Action("Row1Panel2", new { model = Model.Data })

                @Html.Action("Row2Panel1", new { model = Model.Data })
                @Html.Action("Row2Panel2", new { model = Model.Data })

@model SFA.DAS.EmployerAccounts.Web.OrchestratorResponse<SFA.DAS.EmployerAccounts.Web.ViewModels.AccountDashboardViewModel>

@{
    ViewBag.Title = "Home";
    ViewBag.PageID = "page-company-homepage";
}

Your employer account

@Model.Data.Account.Name

                @Html.Action("Row1Panel1", new { model = Model.Data })
                @Html.Action("Row2Panel1", new { model = Model.Data })

                @Html.Action("Row1Panel2", new { model = Model.Data })
                @Html.Action("Row2Panel2", new { model = Model.Data })

Update css classes to new styles

[CON-477] Update css classes to new styles


using System;
using System.Linq;

namespace CefSharp.Example
{
    public static class CefExample
    {
        public const string DefaultUrl = "custom://cefsharp/BindingTest.html";

        // Use when debugging the actual SubProcess, to make breakpoints etc. inside that project work.
        private const bool debuggingSubProcess = true;

        public static void Init()
        {
            var settings = new CefSettings();
            settings.RemoteDebuggingPort = 8088;
            //settings.CefCommandLineArgs.Add("renderer-process-limit", "1");
            //settings.CefCommandLineArgs.Add("renderer-startup-dialog", "renderer-startup-dialog");
            settings.LogSeverity = LogSeverity.Verbose;

            if (debuggingSubProcess)
            {
                var architecture = Environment.Is64BitProcess ? "x64" : "x86";
                settings.BrowserSubprocessPath = "..\\..\\..\\..\\CefSharp.BrowserSubprocess\\bin\\" + architecture + "\\Debug\\CefSharp.BrowserSubprocess.exe";
            }

            settings.RegisterScheme(new CefCustomScheme
            {
                SchemeName = CefSharpSchemeHandlerFactory.SchemeName,
                SchemeHandlerFactory = new CefSharpSchemeHandlerFactory()
            });

            if (!Cef.Initialize(settings))
            {
                if (Environment.GetCommandLineArgs().Contains("--type=renderer"))
                {
                    Environment.Exit(0);
                }
                else
                {
                    return;
                }
            }
        }
    }
}

using System;
using System.Diagnostics;
using System.Linq;

namespace CefSharp.Example
{
    public static class CefExample
    {
        public const string DefaultUrl = "custom://cefsharp/BindingTest.html";

        // Use when debugging the actual SubProcess, to make breakpoints etc. inside that project work.
        private static readonly bool DebuggingSubProcess = Debugger.IsAttached;

        public static void Init()
        {
            var settings = new CefSettings();
            settings.RemoteDebuggingPort = 8088;
            //settings.CefCommandLineArgs.Add("renderer-process-limit", "1");
            //settings.CefCommandLineArgs.Add("renderer-startup-dialog", "renderer-startup-dialog");
            settings.LogSeverity = LogSeverity.Verbose;

            if (DebuggingSubProcess)
            {
                var architecture = Environment.Is64BitProcess ? "x64" : "x86";
                settings.BrowserSubprocessPath = "..\\..\\..\\..\\CefSharp.BrowserSubprocess\\bin\\" + architecture + "\\Debug\\CefSharp.BrowserSubprocess.exe";
            }

            settings.RegisterScheme(new CefCustomScheme
            {
                SchemeName = CefSharpSchemeHandlerFactory.SchemeName,
                SchemeHandlerFactory = new CefSharpSchemeHandlerFactory()
            });

            if (!Cef.Initialize(settings))
            {
                if (Environment.GetCommandLineArgs().Contains("--type=renderer"))
                {
                    Environment.Exit(0);
                }
                else
                {
                    return;
                }
            }
        }
    }
}

Set DebuggingSubProcess = Debugger.IsAttached rather than a hard coded value


using System;
using System.IO;
using System.Text;

namespace Eleven41.Helpers
{
	public static class JsonHelper
	{
		public static string Serialize<T>(T obj)
		{
			return ServiceStack.Text.JsonSerializer.SerializeToString(obj, typeof(T));
		}

		public static void SerializeToStream<T>(T obj, Stream stream)
		{
			ServiceStack.Text.JsonSerializer.SerializeToStream(obj, stream);
		}

		public static T Deserialize<T>(string json)
		{
			return ServiceStack.Text.JsonSerializer.DeserializeFromString<T>(json);
		}

		public static T DeserializeFromStream<T>(Stream stream)
		{
			return ServiceStack.Text.JsonSerializer.DeserializeFromStream<T>(stream);
		}
	}
}

using System;
using System.IO;
using System.Text;
using ServiceStack.Text;

namespace Eleven41.Helpers
{
	public static class JsonHelper
	{
		public static string Serialize<T>(T obj)
		{
			return JsonSerializer.SerializeToString(obj, typeof(T));
		}

		public static string SerializeAndFormat<T>(T obj)
		{
			return obj.SerializeAndFormat();
		}

		public static void SerializeToStream<T>(T obj, Stream stream)
		{
			JsonSerializer.SerializeToStream(obj, stream);
		}

		public static T Deserialize<T>(string json)
		{
			return JsonSerializer.DeserializeFromString<T>(json);
		}

		public static T DeserializeFromStream<T>(Stream stream)
		{
			return JsonSerializer.DeserializeFromStream<T>(stream);
		}
	}
}

Add a formated Json serialization option


#if DECOMPILE

namespace UELib.Core
{
	public partial class UConst : UField
	{
		/// <summary>
		/// Decompiles this object into a text format of:
		///
		/// const NAME = VALUE;
		/// </summary>
		/// <returns></returns>
		public override string Decompile()
		{
			return "const " + Name + " = " + Value + ";";
		}
	}
}
#endif

#if DECOMPILE

namespace UELib.Core
{
	public partial class UConst : UField
	{
		/// <summary>
		/// Decompiles this object into a text format of:
		///
		/// const NAME = VALUE;
		/// </summary>
		/// <returns></returns>
		public override string Decompile()
		{
			return "const " + Name + " = " + Value.Trim() + ";";
		}
	}
}
#endif

Trim the output of constants.

[Fix]: Trim the output of constants.


    <input type="button" onclick="acceptChallenge()" value="Accept" />
    <input type="button" onclick="rejectChallenge()" value="Reject" />

Fix challenge div displaying in Chrome.

Fix challenge div displaying in Chrome.


using Microsoft.AspNetCore.Identity;

namespace DragonSpark.Application.Security.Identity;

public readonly record struct Login<T>(ExternalLoginInfo Information, T User);

using Microsoft.AspNetCore.Identity;

namespace DragonSpark.Application.Security.Identity;

public sealed record Login<T>(ExternalLoginInfo Information, T User);

Upgrade to allocation as it is used a bit


using System;
using NUnit.Framework;

namespace Plivo.Test
{
    [TestFixture]
    public class TestSignature
    {
        [Test]
        public void TestSignatureV2Pass()
        {
            string url = "https://answer.url";
            string nonce = "12345";
            string signature = "ehV3IKhLysWBxC1sy8INm0qGoQYdYsHwuoKjsX7FsXc=";
            string authToken = "my_auth_token";

            Assert.Equals(Utilities.XPlivoSignatureV2.VerifySignature(url, nonce, signature, authToken), true);
        }

        [Test]
        public void TestSignatureV2Fail()
        {
            string url = "https://answer.url";
            string nonce = "12345";
            string signature = "ehV3IKhLysWBxC1sy8INm0qGoQYdYsHwuoKjsX7FsXc=";
            string authToken = "my_auth_tokens";

            Assert.Equals(Utilities.XPlivoSignatureV2.VerifySignature(url, nonce, signature, authToken), false);
        }
    }
}

using System;
using NUnit.Framework;

namespace Plivo.Test
{
    [TestFixture]
    public class TestSignature
    {
        [Test]
        public void TestSignatureV2Pass()
        {
            string url = "https://answer.url";
            string nonce = "12345";
            string signature = "ehV3IKhLysWBxC1sy8INm0qGoQYdYsHwuoKjsX7FsXc=";
            string authToken = "my_auth_token";

            Assert.True(Utilities.XPlivoSignatureV2.VerifySignature(url, nonce, signature, authToken));
        }

        [Test]
        public void TestSignatureV2Fail()
        {
            string url = "https://answer.url";
            string nonce = "12345";
            string signature = "ehV3IKhLysWBxC1sy8INm0qGoQYdYsHwuoKjsX7FsXc=";
            string authToken = "my_auth_tokens";

            Assert.False(Utilities.XPlivoSignatureV2.VerifySignature(url, nonce, signature, authToken));
        }
    }
}

Fix failing tests on Travis

Fix failing tests on Travis


using Silphid.Extensions;
using UnityEngine;

namespace Silphid.Showzup.ListLayouts
{
    public class HorizontalListLayout : ListLayout
    {
        public float HorizontalSpacing;
        public float ItemWidth;

        protected float ItemOffsetX => ItemWidth + HorizontalSpacing;

        public override Rect GetItemRect(int index, Vector2 viewportSize) =>
            new Rect(
                FirstItemPosition + new Vector2(ItemOffsetX * index, 0),
                new Vector2(ItemWidth, viewportSize.y - (Padding.top + Padding.bottom)));

        public override Vector2 GetContainerSize(int count, Vector2 viewportSize) =>
            new Vector2(
                Padding.left + ItemWidth * count + HorizontalSpacing * (count - 1).AtLeast(0) + Padding.right,
                viewportSize.y);

        public override IndexRange GetVisibleIndexRange(Rect rect) =>
            new IndexRange(
                ((rect.xMin - FirstItemPosition.x) / ItemOffsetX).FloorInt(),
                ((rect.xMax - FirstItemPosition.x) / ItemOffsetX).FloorInt() + 1);
    }
}

using Silphid.Extensions;
using UnityEngine;

namespace Silphid.Showzup.ListLayouts
{
    public class HorizontalListLayout : ListLayout
    {
        public float HorizontalSpacing;
        public float ItemWidth;

        protected float ItemOffsetX => ItemWidth + HorizontalSpacing;
        private Rect VisibleRect = new Rect();

        public override Rect GetItemRect(int index, Vector2 viewportSize) =>
            new Rect(
                FirstItemPosition + new Vector2(ItemOffsetX * index, 0),
                new Vector2(ItemWidth, viewportSize.y - (Padding.top + Padding.bottom)));

        public override Vector2 GetContainerSize(int count, Vector2 viewportSize) =>
            new Vector2(
                Padding.left + ItemWidth * count + HorizontalSpacing * (count - 1).AtLeast(0) + Padding.right,
                viewportSize.y);

        public override IndexRange GetVisibleIndexRange(Rect visibleRect)
        {
            VisibleRect.Set(visibleRect.x*-1, visibleRect.y, visibleRect.width, visibleRect.height);
            return new IndexRange(
                ((VisibleRect.xMin - FirstItemPosition.x) / ItemOffsetX).FloorInt(),
                ((VisibleRect.xMax - FirstItemPosition.x) / ItemOffsetX).FloorInt() + 1);
        }
    }
}

Fix horizontal scroll for Virtual list

Fix horizontal scroll for Virtual list


using System;
using System.Linq;
using Microsoft.OpenApi.Models;
using Newtonsoft.Json.Serialization;

namespace Swashbuckle.AspNetCore.SwaggerGen
{
    public class PolymorphicSchemaGenerator : ChainableSchemaGenerator
    {
        public PolymorphicSchemaGenerator(
            SchemaGeneratorOptions options,
            ISchemaGenerator rootGenerator,
            IContractResolver contractResolver)
            : base(options, rootGenerator, contractResolver)
        { }

        protected override bool CanGenerateSchemaFor(Type type)
        {
            var subTypes = Options.SubTypesResolver(type);
            return subTypes.Any();
        }

        protected override OpenApiSchema GenerateSchemaFor(Type type, SchemaRepository schemaRepository)
        {
            var subTypes = Options.SubTypesResolver(type);

            return new OpenApiSchema
            {
                OneOf = subTypes
                    .Select(subType => RootGenerator.GenerateSchema(subType, schemaRepository))
                    .ToList()
            };
        }
    }
}

using System;
using System.Linq;
using Microsoft.OpenApi.Models;
using Newtonsoft.Json.Serialization;

namespace Swashbuckle.AspNetCore.SwaggerGen
{
    public class PolymorphicSchemaGenerator : ChainableSchemaGenerator
    {
        public PolymorphicSchemaGenerator(
            SchemaGeneratorOptions options,
            ISchemaGenerator rootGenerator,
            IContractResolver contractResolver)
            : base(options, rootGenerator, contractResolver)
        { }

        protected override bool CanGenerateSchemaFor(Type type)
        {
            return (Options.GeneratePolymorphicSchemas && Options.SubTypesResolver(type).Any());
        }

        protected override OpenApiSchema GenerateSchemaFor(Type type, SchemaRepository schemaRepository)
        {
            var subTypes = Options.SubTypesResolver(type);

            return new OpenApiSchema
            {
                OneOf = subTypes
                    .Select(subType => RootGenerator.GenerateSchema(subType, schemaRepository))
                    .ToList()
            };
        }
    }
}

Make polymorphic schema generation opt-in


using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using LtiLibrary.NetCore.Common;
using LtiLibrary.NetCore.Extensions;

namespace LtiLibrary.NetCore.Profiles
{
    public static class ToolConsumerProfileClient
    {
        /// <summary>
        /// Get a ToolConsumerProfile from the service endpoint.
        /// </summary>
        /// <param name="serviceUrl">The full URL of the ToolConsumerProfile service.</param>
        /// <returns>A <see cref="ToolConsumerProfileResponse"/> which includes both the HTTP status code
        /// and the <see cref="ToolConsumerProfile"/> if the HTTP status is a success code.</returns>
        public static async Task<ToolConsumerProfileResponse> GetToolConsumerProfileAsync(string serviceUrl)
        {
            var profileResponse = new ToolConsumerProfileResponse();
            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(LtiConstants.ToolConsumerProfileMediaType));

                var response = await client.GetAsync(serviceUrl);
                profileResponse.StatusCode = response.StatusCode;
                if (response.IsSuccessStatusCode)
                {
                    profileResponse.ToolConsumerProfile = await response.Content.ReadJsonAsObjectAsync<ToolConsumerProfile>();
                }
            }
            return profileResponse;
        }
    }
}

using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using LtiLibrary.NetCore.Common;
using LtiLibrary.NetCore.Extensions;

namespace LtiLibrary.NetCore.Profiles
{
    public static class ToolConsumerProfileClient
    {
        /// <summary>
        /// Get a ToolConsumerProfile from the service endpoint.
        /// </summary>
        /// <param name="client">The HttpClient to use for the request.</param>
        /// <param name="serviceUrl">The full URL of the ToolConsumerProfile service.</param>
        /// <returns>A <see cref="ToolConsumerProfileResponse"/> which includes both the HTTP status code
        /// and the <see cref="ToolConsumerProfile"/> if the HTTP status is a success code.</returns>
        public static async Task<ToolConsumerProfileResponse> GetToolConsumerProfileAsync(HttpClient client, string serviceUrl)
        {
            var profileResponse = new ToolConsumerProfileResponse();
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(LtiConstants.ToolConsumerProfileMediaType));

            using (var response = await client.GetAsync(serviceUrl))
            {
                profileResponse.StatusCode = response.StatusCode;
                if (response.IsSuccessStatusCode)
                {
                    profileResponse.ToolConsumerProfile =
                        await response.Content.ReadJsonAsObjectAsync<ToolConsumerProfile>();
                    profileResponse.ContentType = response.Content.Headers.ContentType.MediaType;
                }
                return profileResponse;
            }
        }
    }
}

Add HttpClient to GetToolConsumerProfileAsync convenience method to make it easier to call from an integration test.


using UnityEngine.Events;

[System.Serializable]
public class LiteNetLibLoadSceneEvent : UnityEvent<string, bool, float>
{

	// Use this for initialization
	void Start () {

	}

	// Update is called once per frame
	void Update () {

	}
}

using UnityEngine.Events;

[System.Serializable]
public class LiteNetLibLoadSceneEvent : UnityEvent<string, bool, float>
{
}

Remove unused functions (that generate by unity :p)


using UnityEngine;

[CreateAssetMenu (menuName = "AI/Actions/Enemy_Attack")]
public class Action_Attack : Action {

	public override void Init(StateController controller) {
		return;
	}

	public override void Act(StateController controller) {

	}
}

using UnityEngine;

[CreateAssetMenu (menuName = "AI/Actions/Enemy_Attack")]
public class Action_Attack : Action {
	[SerializeField] float staminaRequired = 2f;
	[SerializeField] float attackDelay     = 1f;
	[SerializeField] float attackDuration  = 1f;
	[SerializeField] float attackDamage    = 1f;
	[SerializeField] float attackRange     = 2f;

	float timer;

	public override void Init(StateController controller) {
		Debug.Log("ATTACK STATAE");
		timer = attackDelay;
		return;
	}

	public override void Act(StateController controller) {
		attackRoutine(controller as Enemy_StateController);
	}

	private void attackRoutine(Enemy_StateController controller) {
		Vector3 targetPosition = controller.chaseTarget.transform.position;
		float distanceFromTarget = getDistanceFromTarget(targetPosition, controller);
		bool hasStamina = controller.characterStatus.stamina.isEnough(staminaRequired);

		if(hasStamina) {
			if(timer >= attackDelay) {
				timer = attackDelay;
				controller.characterStatus.stamina.decrease(staminaRequired);
				performAttack(controller, attackDamage, attackDuration);
				timer = 0f;
			} else {
				timer += Time.deltaTime;
			}
		} else {
			timer = attackDelay;
		}
	}

	private void performAttack(Enemy_StateController controller, float attackDamage, float attackDuration) {
		controller.anim.SetTrigger("AttackState");
		controller.attackHandler.damage = attackDamage;
		controller.attackHandler.duration = attackDuration;
		controller.attackHandler.hitBox.enabled = true;
	}

	private float getDistanceFromTarget(Vector3 targetPosition, Enemy_StateController controller) {
		Vector3 originPosition = controller.eyes.position;
		Vector3 originToTargetVector = targetPosition - originPosition;
		float distanceFromTarget = originToTargetVector.magnitude;

		return distanceFromTarget;
	}
}

Rewrite Action Attack erased by mistake

Rewrite Action Attack erased by mistake


using System.Collections.ObjectModel;
using System.Linq;
using SOVND.Lib.Models;

namespace SOVND.Client.Util
{
    public class ChannelDirectory
    {
        public ObservableCollection<Channel> channels = new ObservableCollection<Channel>();

        public bool AddChannel(Channel channel)
        {
            if (channels.Where(x => x.Name == channel.Name).Count() > 0)
                return false;

            channels.Add(channel);
            return true;
        }
    }
}

using System.Collections.ObjectModel;
using System.Linq;
using SOVND.Lib.Models;

namespace SOVND.Client.Util
{
    public class ChannelDirectory
    {
        private readonly SyncHolder _sync;
        public ObservableCollection<Channel> channels = new ObservableCollection<Channel>();

        public ChannelDirectory(SyncHolder sync)
        {
            _sync = sync;
        }

        public bool AddChannel(Channel channel)
        {
            if (channels.Where(x => x.Name == channel.Name).Count() > 0)
                return false;

            if (_sync.sync != null)
                _sync.sync.Send((x) => channels.Add(channel), null);
            else
                channels.Add(channel);
            return true;
        }
    }
}

Fix crash when items are added from non-WPF main thread


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

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

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

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

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

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

Rename previously unknown GAF field

Rename previously unknown GAF field


using System;
using Xunit;

namespace Cascara.Tests
{
    public class AssertExtension : Assert
    {
        public static T ThrowsWithMessage<T>(Func<object> testCode, string message)
            where T : Exception
        {
            var ex = Assert.Throws<T>(testCode);
            Assert.Equal(ex.Message, message);

            return ex;
        }
    }
}

using System;
using Xunit;

namespace Cascara.Tests
{
    public class AssertExtension : Assert
    {
        public static T ThrowsWithMessage<T>(Func<object> testCode, string message)
            where T : Exception
        {
            var ex = Assert.Throws<T>(testCode);
            Assert.Equal(ex.Message, message);

            return ex;
        }

        public static T ThrowsWithMessage<T>(Func<object> testCode, string fmt, params object[] args)
            where T : Exception
        {
            string message = string.Format(fmt, args);

            var ex = Assert.Throws<T>(testCode);
            Assert.Equal(ex.Message, message);

            return ex;
        }
    }
}

Add ThrowsWithMessage() overload with format string


using System;
using Moq;
using Xunit;
using Should;

namespace Foggle
{
	public class EnableByHostnameTests
	{
		[Fact]
		public void IsEnabled_ClassMarkedWithFoggleByHostName_TrysToGetListOfHostname()
		{
			var mockConfig = new Mock<IConfigWrapper>();

			Feature.configurationWrapper = mockConfig.Object;
			Feature.IsEnabled<TestFeature>().ShouldBeFalse();

			mockConfig.Verify(x => x.GetApplicationSetting(It.Is<string>(s => s.EndsWith("Hostnames"))));
		}

		[Fact]
		public void IsEnabled_ClassMarkedWithFoggleByHostName_GetsCurrentHostname()
		{
			var mockConfig = new Mock<IConfigWrapper>();

			Feature.configurationWrapper = mockConfig.Object;
			Feature.IsEnabled<TestFeature>();

			mockConfig.Verify(x => x.GetCurrentHostname(), Times.Once);
		}

		[Fact]
		public void IsEnabledByHostName_HostnameInList_ReturnsTrue()
		{
			var mockConfig = new Mock<IConfigWrapper>();

			Feature.configurationWrapper = mockConfig.Object;
			Feature.IsEnabled<TestFeature>();

			mockConfig.Verify(x => x.GetCurrentHostname(), Times.Once);
		}

		[FoggleByHostname]
		class TestFeature : FoggleFeature
		{

		}
	}
}

using System;
using Moq;
using Xunit;
using Should;

namespace Foggle
{
	public class EnableByHostnameTests
	{
		[Fact]
		public void IsEnabled_ClassMarkedWithFoggleByHostName_TrysToGetListOfHostname()
		{
			var mockConfig = new Mock<IConfigWrapper>();

			Feature.configurationWrapper = mockConfig.Object;
			Feature.IsEnabled<TestHostnameFeature>().ShouldBeFalse();

			mockConfig.Verify(x => x.GetApplicationSetting(It.Is<string>(s => s.EndsWith("Hostnames"))));
		}

		[Fact]
		public void IsEnabled_ClassMarkedWithFoggleByHostName_GetsCurrentHostname()
		{
			var mockConfig = new Mock<IConfigWrapper>();

			Feature.configurationWrapper = mockConfig.Object;
			Feature.IsEnabled<TestHostnameFeature>();

			mockConfig.Verify(x => x.GetCurrentHostname(), Times.Once);
		}

		[Fact]
		public void IsEnabledByHostName_HostnameInList_ReturnsTrue()
		{
			var mockConfig = new Mock<IConfigWrapper>();

			Feature.configurationWrapper = mockConfig.Object;
			Feature.IsEnabled<TestHostnameFeature>();

			mockConfig.Verify(x => x.GetCurrentHostname(), Times.Once);
		}

		[FoggleByHostname]
		class TestHostnameFeature : FoggleFeature
		{

		}
	}
}

Rename test feature class for hostname tests


using MacroDiagnostics;
using MacroExceptions;
using MacroGuards;

namespace
produce
{

public class
NuGitModule : Module
{

public override void
Attach(ProduceRepository repository, Graph graph)
{
    Guard.NotNull(repository, nameof(repository));
    Guard.NotNull(graph, nameof(graph));

    var nugitRestore = graph.Command("nugit-restore", _ => Restore(repository));
    graph.Dependency(nugitRestore, graph.Command("restore"));

    var nugitUpdate = graph.Command("nugit-update", _ => Update(repository));
    graph.Dependency(nugitUpdate, graph.Command("update"));
}

static void
Restore(ProduceRepository repository)
{
    if (ProcessExtensions.Execute(true, true, repository.Path, "cmd", "/c", "nugit", "restore") != 0)
        throw new UserException("nugit failed");
}

static void
Update(ProduceRepository repository)
{
    if (ProcessExtensions.Execute(true, true, repository.Path, "cmd", "/c", "nugit", "update") != 0)
        throw new UserException("nugit failed");
}

}
}

using MacroDiagnostics;
using MacroExceptions;
using MacroGuards;

namespace
produce
{

public class
NuGitModule : Module
{

public override void
Attach(ProduceRepository repository, Graph graph)
{
    Guard.NotNull(repository, nameof(repository));
    Guard.NotNull(graph, nameof(graph));

    var nugitRestore = graph.Command("nugit-restore", _ => Restore(repository));
    graph.Dependency(nugitRestore, graph.Command("restore"));

    var nugitUpdate = graph.Command("nugit-update", _ => Update(repository));
    graph.Dependency(nugitUpdate, graph.Command("update"));
}

static void
Restore(ProduceRepository repository)
{
    using (LogicalOperation.Start("Restoring NuGit dependencies"))
        if (ProcessExtensions.Execute(true, true, repository.Path, "cmd", "/c", "nugit", "restore") != 0)
            throw new UserException("nugit failed");
}

static void
Update(ProduceRepository repository)
{
    using (LogicalOperation.Start("Updating NuGit dependencies"))
        if (ProcessExtensions.Execute(true, true, repository.Path, "cmd", "/c", "nugit", "update") != 0)
            throw new UserException("nugit failed");
}

}
}

Add logical operations to NuGit operations