using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;

namespace SimpleReport.Model.Replacers
{
    /// <summary>
    /// Used to replace xml code and remove styling from rtf text
    /// </summary>
    public class ValueReplacer : IValueReplacer
    {
        public string Replace(string inputstring)
        {
            var value = IsRtf(inputstring) ? RtfToText(inputstring) : inputstring;
            value = XmlTextEncoder.Encode(value);
            return value;
        }
        private static bool IsRtf(string text)
        {
            return text.TrimStart().StartsWith("{\\rtf1", StringComparison.Ordinal);
        }
        private static string RtfToText(string text)
        {
            try
            {
                var rtBox = new System.Windows.Forms.RichTextBox {Rtf = text};
                text = rtBox.Text;
            } catch (Exception ex)
            {
               // do nothing, just return faulty rtf
            }

            return text;
        }
    }
}

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;

namespace SimpleReport.Model.Replacers
{
    /// <summary>
    /// Used to replace xml code and remove styling from rtf text
    /// </summary>
    public class ValueReplacer : IValueReplacer
    {
        public string Replace(string inputstring)
        {
            var value = IsRtf(inputstring) ? RtfToText(inputstring) : inputstring;
            return value;
        }
        private static bool IsRtf(string text)
        {
            return text.TrimStart().StartsWith("{\\rtf1", StringComparison.Ordinal);
        }
        private static string RtfToText(string text)
        {
            try
            {
                var rtBox = new System.Windows.Forms.RichTextBox {Rtf = text};
                text = rtBox.Text;
            } catch (Exception ex)
            {
               // do nothing, just return faulty rtf
            }

            return text;
        }
    }
}

Remove xml encoding in reports.

[8182] Remove xml encoding in reports.


using System;
using System.Web;
using System.Web.Hosting;
using System.Configuration;

namespace NuGet.Server.Infrastructure
{
    public class PackageUtility
    {

        internal static string PackagePhysicalPath;
        private static string DefaultPackagePhysicalPath = HostingEnvironment.MapPath("~/Packages");

        static PackageUtility()
        {
            string packagePath = ConfigurationManager.AppSettings["NuGetPackagePath"];
            if (string.IsNullOrEmpty(packagePath))
            {
                PackagePhysicalPath = DefaultPackagePhysicalPath;
            }
            else
            {
                PackagePhysicalPath = packagePath;
            }
        }

        public static Uri GetPackageUrl(string path, Uri baseUri)
        {
            return new Uri(baseUri, GetPackageDownloadUrl(path));
        }

        private static string GetPackageDownloadUrl(string path)
        {
            return VirtualPathUtility.ToAbsolute("~/Packages/" + path);
        }
    }
}

using System;
using System.Web;
using System.Web.Hosting;
using System.Configuration;
using System.IO;

namespace NuGet.Server.Infrastructure
{
    public class PackageUtility
    {

        internal static string PackagePhysicalPath;
        private static string DefaultPackagePhysicalPath = HostingEnvironment.MapPath("~/Packages");

        static PackageUtility()
        {
            string packagePath = ConfigurationManager.AppSettings["NuGetPackagePath"];
            if (string.IsNullOrEmpty(packagePath))
            {
                PackagePhysicalPath = DefaultPackagePhysicalPath;
            }
            else
            {
                if (Path.IsPathRooted(packagePath))
                {
                    PackagePhysicalPath = packagePath;
                }
                else
                {
                    PackagePhysicalPath = HostingEnvironment.MapPath(packagePath);
                }
            }
        }

        public static Uri GetPackageUrl(string path, Uri baseUri)
        {
            return new Uri(baseUri, GetPackageDownloadUrl(path));
        }

        private static string GetPackageDownloadUrl(string path)
        {
            return VirtualPathUtility.ToAbsolute("~/Packages/" + path);
        }
    }
}

Check if the specified path is a physical or a virtual path


using static System.Console;

namespace ConsoleApp
{
    class Program
    {
        private static void Main()
        {
            var connectionString = @"Server=.\SQLEXPRESS;Database=LearnORM;Trusted_Connection=True;";
            var schemaName = "dbo";
            var tableName = "Book";

            var columnsProvider = new ColumnsProvider(connectionString);
            var columns = columnsProvider.GetColumnsAsync(schemaName, tableName).GetAwaiter().GetResult();

            new Table(tableName, columns).OutputMigrationCode(Out);
        }
    }
}

using static System.Console;

namespace ConsoleApp
{
    class Program
    {
        private static void Main(string[] args)
        {
            if (args.Length != 3)
            {
                WriteLine("Usage: schema2fm.exe connectionstring schema table");
                return;
            }

            var connectionString = args[0];//@"Server=.\SQLEXPRESS;Database=LearnORM;Trusted_Connection=True;";
            var schemaName = args[1];//"dbo";
            var tableName = args[2];//"Book";

            var columnsProvider = new ColumnsProvider(connectionString);
            var columns = columnsProvider.GetColumnsAsync(schemaName, tableName).GetAwaiter().GetResult();

            new Table(tableName, columns).OutputMigrationCode(Out);
        }
    }
}

Read parameters from command line arguments


#region License
//
// Copyright (c) 2013, Kooboo team
//
// Licensed under the BSD License
// See the file LICENSE.txt for details.
//
#endregion
using Kooboo.CMS.Sites.Extension.ModuleArea;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Kooboo.CMS.Sites.Extension;
using Kooboo.CMS.ModuleArea.Areas.SampleModule.Models;
namespace Kooboo.CMS.ModuleArea.Areas.Empty
{
    [Kooboo.CMS.Common.Runtime.Dependency.Dependency(typeof(IModuleAction), Key = SampleAreaRegistration.ModuleName)]
    public class ModuleAction : IModuleAction
    {
        public void OnExcluded(Sites.Models.Site site)
        {
            // Add code here that will be executed when the module was excluded to the site.
        }

        public void OnIncluded(Sites.Models.Site site)
        {
            // Add code here that will be executed when the module was included to the site.
        }

        public void OnInstalling(ControllerContext controllerContext)
        {
            var moduleInfo = ModuleInfo.Get(SampleAreaRegistration.ModuleName);
            var installModel = new InstallModel();
            Kooboo.CMS.Sites.Extension.PagePluginHelper.BindModel<InstallModel>(installModel, controllerContext);

            moduleInfo.DefaultSettings.CustomSettings["DatabaseServer"] = installModel.DatabaseServer;
            moduleInfo.DefaultSettings.CustomSettings["UserName"] = installModel.UserName;
            moduleInfo.DefaultSettings.CustomSettings["Password"] = installModel.Password;
            ModuleInfo.Save(moduleInfo);

            // Add code here that will be executed when the module installing.
        }

        public void OnUninstalling(ControllerContext controllerContext)
        {
            // Add code here that will be executed when the module uninstalling.
        }
    }
}

#region License
//
// Copyright (c) 2013, Kooboo team
//
// Licensed under the BSD License
// See the file LICENSE.txt for details.
//
#endregion
using Kooboo.CMS.Sites.Extension.ModuleArea;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Kooboo.CMS.Sites.Extension;
using Kooboo.CMS.ModuleArea.Areas.SampleModule.Models;
namespace Kooboo.CMS.ModuleArea.Areas.Empty
{
    [Kooboo.CMS.Common.Runtime.Dependency.Dependency(typeof(IModuleAction), Key = ModuleAreaRegistration.ModuleName)]
    public class ModuleAction : IModuleAction
    {
        public void OnExcluded(Sites.Models.Site site)
        {
            // Add code here that will be executed when the module was excluded to the site.
        }

        public void OnIncluded(Sites.Models.Site site)
        {
            // Add code here that will be executed when the module was included to the site.
        }

        public void OnInstalling(ControllerContext controllerContext)
        {
            // Add code here that will be executed when the module installing.
        }

        public void OnUninstalling(ControllerContext controllerContext)
        {
            // Add code here that will be executed when the module uninstalling.
        }
    }
}

Update the Empty module template.

Update the Empty module template.


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

namespace DigitalOcean.Structs
{
        public class Droplet
        {
            public int id { get; set; }
            public string name { get; set; }
            public int image_id { get; set; }
            public int size_id { get; set; }
            public int region_id { get; set; }
            public bool backups_active { get; set; }
            public string ip_address { get; set; }
            public object private_ip_address { get; set; }
            public bool locked { get; set; }
            public string status { get; set; }
            public string created_at { get; set; }
        }

        public class Droplets
        {
            public string status { get; set; }
            public List<Droplet> droplets { get; set; }
        }
}

using System.Collections.Generic;

namespace DigitalOcean.Structs
{
    public class Droplet
    {
        public int id { get; set; }
        public int image_id { get; set; }
        public string name { get; set; }
        public int region_id { get; set; }
        public int size_id { get; set; }
        public bool backups_active { get; set; }
        public List<object> backups { get; set; } //extended
        public List<object> snapshots { get; set; } //extended
        public string ip_address { get; set; }
        public object private_ip_address { get; set; }
        public bool locked { get; set; }
        public string status { get; set; }
        public string created_at { get; set; }
    }

    public class Droplets
    {
        public string status { get; set; }
        public List<Droplet> droplets { get; set; }
    }
}

Make way for the extended information which can be requested using the Show Droplet request.


using MyDocs.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Windows.Storage;
using Logic = MyDocs.Common.Model.Logic;

namespace JsonNetDal
{
    public class SubDocument
    {
        public string Title { get; set; }

        public string File { get; set; }

        public List<string> Photos { get; set; }

        public SubDocument() { }

        public SubDocument(string title, string file, IEnumerable<string> photos)
        {
            Title = title;
            File = file;
            Photos = photos.ToList();
        }

        public static SubDocument FromLogic(Logic.SubDocument subDocument)
        {
            return new SubDocument(subDocument.Title, subDocument.File.GetUri().AbsoluteUri, subDocument.Photos.Select(p => p.File.GetUri().AbsoluteUri));
        }

        public async Task<Logic.SubDocument> ToLogic()
        {
            var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri(File));
            var photoTasks =
                Photos
                .Select(p => new Uri(p))
                .Select(StorageFile.GetFileFromApplicationUriAsync)
                .Select(x => x.AsTask());
            var photos = await Task.WhenAll(photoTasks);
            return new Logic.SubDocument(file, photos.Select(p => new Logic.Photo(p)));
        }
    }
}

using MyDocs.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Windows.Storage;
using Logic = MyDocs.Common.Model.Logic;

namespace JsonNetDal
{
    public class SubDocument
    {
        public string Title { get; set; }

        public Uri File { get; set; }

        public List<Uri> Photos { get; set; }

        public SubDocument() { }

        public SubDocument(string title, Uri file, IEnumerable<Uri> photos)
        {
            Title = title;
            File = file;
            Photos = photos.ToList();
        }

        public static SubDocument FromLogic(Logic.SubDocument subDocument)
        {
            return new SubDocument(subDocument.Title, subDocument.File.GetUri(), subDocument.Photos.Select(p => p.File.GetUri()));
        }

        public async Task<Logic.SubDocument> ToLogic()
        {
            var file = await StorageFile.GetFileFromApplicationUriAsync(File);
            var photoTasks =
                Photos
                .Select(StorageFile.GetFileFromApplicationUriAsync)
                .Select(x => x.AsTask());
            var photos = await Task.WhenAll(photoTasks);
            return new Logic.SubDocument(file, photos.Select(p => new Logic.Photo(p)));
        }
    }
}

Use Uri's for subdocument file and photos


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

namespace Cronus.Core.Eventing
{
    /// <summary>
    /// Represents an in memory event messaging destribution
    /// </summary>
    public class InMemoryEventBus : AbstractEventBus
    {
        /// <summary>
        /// Publishes the given event to all registered event handlers
        /// </summary>
        /// <param name="event">An event instance</param>
        public override bool Publish(IEvent @event)
        {
            onPublishEvent(@event);
            foreach (var handleMethod in handlers[@event.GetType()])
            {
                var result = handleMethod(@event);
                if (result == false)
                    return result;
            }
            onEventPublished(@event);
            return true;
        }

        public override Task<bool> PublishAsync(IEvent @event)
        {
            return Threading.RunAsync(() => Publish(@event));
        }
    }
}

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

namespace Cronus.Core.Eventing
{
    /// <summary>
    /// Represents an in memory event messaging destribution
    /// </summary>
    public class InMemoryEventBus : AbstractEventBus
    {
        /// <summary>
        /// Publishes the given event to all registered event handlers
        /// </summary>
        /// <param name="event">An event instance</param>
        public override bool Publish(IEvent @event)
        {
            onPublishEvent(@event);
            List<Func<IEvent, bool>> eventHandlers;
            if (handlers.TryGetValue(@event.GetType(), out eventHandlers))
            {
                foreach (var handleMethod in eventHandlers)
                {
                    var result = handleMethod(@event);
                    if (result == false)
                        return result;
                }
            }
            onEventPublished(@event);
            return true;
        }

        public override Task<bool> PublishAsync(IEvent @event)
        {
            return Threading.RunAsync(() => Publish(@event));
        }
    }
}

Fix major bug when getting event handlers


using Gigobyte.Daterpillar.Arguments;
using Gigobyte.Daterpillar.Commands;
using System;

namespace Gigobyte.Daterpillar
{
    public class Program
    {
        internal static void Main(string[] args)
        {
            InitializeWindow();

            start:
            var options = new Options();
            if (args.Length > 0)
            {
                CommandLine.Parser.Default.ParseArguments(args, options,
                    onVerbCommand: (verb, arg) =>
                    {
                        ICommand command = new CommandFactory().CrateInstance(verb);
                        try { _exitCode = command.Execute(arg); }
                        catch (Exception ex)
                        {
                            _exitCode = ExitCode.UnhandledException;
                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.WriteLine(ex);
                        }
                    });
            }
            else
            {
                Console.WriteLine(options.GetHelp());
                args = Console.ReadLine().Split(new char[] { ' ', '\t', '\n' });
                goto start;
            }
            Environment.Exit(_exitCode);
        }

        #region Private Members

        private static int _exitCode;

        private static void InitializeWindow()
        {
            Console.Title = $"{nameof(Daterpillar)} CLI";
        }

        #endregion Private Members
    }
}

using Gigobyte.Daterpillar.Arguments;
using Gigobyte.Daterpillar.Commands;
using System;

namespace Gigobyte.Daterpillar
{
    public class Program
    {
        internal static void Main(string[] args)
        {
            InitializeWindow();

            do
            {
                var commandLineOptions = new Options();
                if (args.Length > 0)
                {
                    CommandLine.Parser.Default.ParseArguments(args, commandLineOptions,
                        onVerbCommand: (verb, arg) =>
                        {
                            ICommand command = new CommandFactory().CrateInstance(verb);
                            try { _exitCode = command.Execute(arg); }
                            catch (Exception ex)
                            {
                                _exitCode = ExitCode.UnhandledException;
                                Console.ForegroundColor = ConsoleColor.Red;
                                Console.WriteLine(ex);
                            }
                            finally { Console.ResetColor(); }
                        }); break;
                }
                else
                {
                    Console.WriteLine(commandLineOptions.GetHelp());
                    args = Console.ReadLine().Split(new char[] { ' ', '\t', '\n' });
                }
            } while (true);
            Environment.Exit(_exitCode);
        }

        #region Private Members

        private static int _exitCode;

        private static void InitializeWindow()
        {
            Console.Title = $"{nameof(Daterpillar)} CLI";
        }

        #endregion Private Members
    }
}

Remove goto statements from command line program


#if NET45
using System;
using Microsoft.Owin.Hosting;

namespace MvcSample
{
    public class Program
    {
        const string baseUrl = "http://localhost:9001/";

        public static void Main()
        {
            using (WebApp.Start<Startup>(new StartOptions(baseUrl)))
            {
                Console.WriteLine("Listening at {0}", baseUrl);
                Console.WriteLine("Press any key to exit");
                Console.ReadKey();
            }
        }
    }
}
#endif

using System;
#if NET45
using Microsoft.Owin.Hosting;
#endif

namespace MvcSample
{
    public class Program
    {
        const string baseUrl = "http://localhost:9001/";

        public static void Main()
        {
#if NET45
            using (WebApp.Start<Startup>(new StartOptions(baseUrl)))
            {
                Console.WriteLine("Listening at {0}", baseUrl);
                Console.WriteLine("Press any key to exit");
                Console.ReadKey();
            }
#else
            Console.WriteLine("Hello World");
#endif
        }
    }
}

Print hello world for k10 project.

Print hello world for k10 project.


using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Azure.WebJobs;

namespace TaskWebJob
{
    // To learn more about Microsoft Azure WebJobs SDK, please see http://go.microsoft.com/fwlink/?LinkID=320976
    class Program
    {
        // Please set the following connection strings in app.config for this WebJob to run:
        // AzureWebJobsDashboard and AzureWebJobsStorage
        static void Main()
        {
            using (var host = new JobHost())
            {
                host.Call(typeof(Functions).GetMethod(nameof(Functions.RecordTimeAndSleep)), new { startTime = DateTime.UtcNow });
            }
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Azure.WebJobs;

namespace TaskWebJob
{
    // To learn more about Microsoft Azure WebJobs SDK, please see http://go.microsoft.com/fwlink/?LinkID=320976
    class Program
    {
        // Please set the following connection strings in app.config for this WebJob to run:
        // AzureWebJobsDashboard and AzureWebJobsStorage
        static void Main()
        {
            using (var host = new JobHost())
            {
                host.Call(typeof(Functions).GetMethod(nameof(Functions.RecordTimeAndSleep)), new { startTime = DateTime.UtcNow });
            }
        }
    }

    public static class PrimeNumbers
    {
        public static IEnumerable<long> GetPrimeNumbers(long minValue, long maxValue) =>
            new[]
            {
                new
                {
                    primes = new List<long>(),
                    min = Math.Max(minValue, 2),
                    max = Math.Max(maxValue, 0),
                    root_max = maxValue >= 0 ? (long)Math.Sqrt(maxValue) : 0,
                }
            }
                .SelectMany(_ => Enumerable2.Range2(2, Math.Min(_.root_max, _.min - 1))
                    .Concat(Enumerable2.Range2(_.min, _.max))
                    .Select(i => new { _.primes, i, root_i = (long)Math.Sqrt(i) }))
                .Where(_ => _.primes
                    .TakeWhile(p => p <= _.root_i)
                    .All(p => _.i % p != 0))
                .Do(_ => _.primes.Add(_.i))
                .Select(_ => _.i)
                .SkipWhile(i => i < minValue);
    }

    public static class Enumerable2
    {
        public static IEnumerable<long> Range2(long minValue, long maxValue)
        {
            for (var i = minValue; i <= maxValue; i++)
            {
                yield return i;
            }
        }

        public static IEnumerable<TSource> Do<TSource>(this IEnumerable<TSource> source, Action<TSource> action)
        {
            if (source == null) throw new ArgumentNullException("source");
            if (action == null) throw new ArgumentNullException("action");

            foreach (var item in source)
            {
                action(item);
                yield return item;
            }
        }
    }
}

Add classes for prime numbers

Add classes for prime numbers


/*
  ----------------------------------------------------------------------
  Numenta Platform for Intelligent Computing (NuPIC)
  Copyright (C) 2015, Numenta, Inc.  Unless you have an agreement
  with Numenta, Inc., for a separate license for this software code, the
  following terms and conditions apply:

  This program is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License version 3 as
  published by the Free Software Foundation.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  See the GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program.  If not, see http://www.gnu.org/licenses.

  http://numenta.org/licenses/
  ----------------------------------------------------------------------
*/
using UnityEngine;
using System.Collections;

public class CarCollisions : MonoBehaviour {

	void OnCollisionEnter(Collision collision) {
		if (collision.gameObject.tag == "Boundary") {
			Application.LoadLevel(Application.loadedLevel);
		}
		else if (collision.gameObject.tag == "Finish") {
			Application.LoadLevel(Application.loadedLevel + 1);
		}
	}

}

/*
  ----------------------------------------------------------------------
  Numenta Platform for Intelligent Computing (NuPIC)
  Copyright (C) 2015, Numenta, Inc.  Unless you have an agreement
  with Numenta, Inc., for a separate license for this software code, the
  following terms and conditions apply:

  This program is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License version 3 as
  published by the Free Software Foundation.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  See the GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program.  If not, see http://www.gnu.org/licenses.

  http://numenta.org/licenses/
  ----------------------------------------------------------------------
*/
using UnityEngine;
using System.Collections;

public class CarCollisions : MonoBehaviour {

	void OnCollisionEnter(Collision collision) {
		if (collision.gameObject.tag == "Boundary") {
      API.instance.Reset();
      Application.LoadLevel(Application.loadedLevel);
    }
    else if (collision.gameObject.tag == "Finish") {
      API.instance.Reset();
      Application.LoadLevel(Application.loadedLevel + 1);
    }
  }

}

Add resets when reloading level

Add resets when reloading level


using NBi.Core.ResultSet;
using System;
using System.Globalization;
using System.Linq;

namespace NBi.Core.Scalar.Comparer
{
    public class ToleranceFactory
    {

        public static Tolerance Instantiate(IColumnDefinition columnDefinition)
        {
            if (columnDefinition.Role != ColumnRole.Value)
                throw new ArgumentException("The ColumnDefinition must have have a role defined as 'Value' and is defined as 'Key'", "columnDefinition");

            return Instantiate(columnDefinition.Type, columnDefinition.Tolerance);
        }

        public static Tolerance Instantiate(ColumnType type, string value)
        {
            if (string.IsNullOrEmpty(value) || string.IsNullOrWhiteSpace(value))
                return null;

            Tolerance tolerance=null;
            switch (type)
            {
                case ColumnType.Text:
                    tolerance = new TextToleranceFactory().Instantiate(value);
                    break;
                case ColumnType.Numeric:
                    tolerance = new NumericToleranceFactory().Instantiate(value);
                    break;
                case ColumnType.DateTime:
                    tolerance = new DateTimeToleranceFactory().Instantiate(value);
                    break;
                case ColumnType.Boolean:
                    break;
                default:
                    break;
            }

            return tolerance;
        }

        public static Tolerance None(ColumnType type)
        {
            Tolerance tolerance = null;
            switch (type)
            {
                case ColumnType.Text:
                    tolerance = TextSingleMethodTolerance.None;
                    break;
                case ColumnType.Numeric:
                    tolerance = NumericAbsoluteTolerance.None;
                    break;
                case ColumnType.DateTime:
                    tolerance = DateTimeTolerance.None;
                    break;
                case ColumnType.Boolean:
                    break;
                default:
                    break;
            }

            return tolerance;
        }

    }
}

using NBi.Core.ResultSet;
using System;
using System.Globalization;
using System.Linq;

namespace NBi.Core.Scalar.Comparer
{
    public class ToleranceFactory
    {

        public static Tolerance Instantiate(IColumnDefinition columnDefinition)
        {
            if (string.IsNullOrEmpty(columnDefinition.Tolerance) || string.IsNullOrWhiteSpace(columnDefinition.Tolerance))
                return null;

            if (columnDefinition.Role != ColumnRole.Value)
                throw new ArgumentException("The ColumnDefinition must have have a role defined as 'Value' and is defined as 'Key'", "columnDefinition");

            return Instantiate(columnDefinition.Type, columnDefinition.Tolerance);
        }

        public static Tolerance Instantiate(ColumnType type, string value)
        {

            Tolerance tolerance=null;
            switch (type)
            {
                case ColumnType.Text:
                    tolerance = new TextToleranceFactory().Instantiate(value);
                    break;
                case ColumnType.Numeric:
                    tolerance = new NumericToleranceFactory().Instantiate(value);
                    break;
                case ColumnType.DateTime:
                    tolerance = new DateTimeToleranceFactory().Instantiate(value);
                    break;
                case ColumnType.Boolean:
                    break;
                default:
                    break;
            }

            return tolerance;
        }

        public static Tolerance None(ColumnType type)
        {
            Tolerance tolerance = null;
            switch (type)
            {
                case ColumnType.Text:
                    tolerance = TextSingleMethodTolerance.None;
                    break;
                case ColumnType.Numeric:
                    tolerance = NumericAbsoluteTolerance.None;
                    break;
                case ColumnType.DateTime:
                    tolerance = DateTimeTolerance.None;
                    break;
                case ColumnType.Boolean:
                    break;
                default:
                    break;
            }

            return tolerance;
        }

    }
}

Fix huge bug related to instantiation of tolerance


using System;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.Primitives;

using ActiproSoftware.Text.Implementation;

using NQuery.Language.Services.BraceMatching;

namespace NQuery.Language.ActiproWpf
{
    public sealed class NQueryLanguage : SyntaxLanguage, IDisposable
    {
        private readonly CompositionContainer _compositionContainer;

        public NQueryLanguage()
            : this(GetDefaultCatalog())
        {
        }

        public NQueryLanguage(ComposablePartCatalog catalog)
            : base("NQuery")
        {
            _compositionContainer = new CompositionContainer(catalog);
            _compositionContainer.SatisfyImportsOnce(this);

            var serviceProviders = _compositionContainer.GetExportedValues<ILanguageServiceRegistrar>();
            foreach (var serviceProvider in serviceProviders)
                serviceProvider.RegisterServices(this);
        }

        private static ComposablePartCatalog GetDefaultCatalog()
        {
            var servicesAssembly = new AssemblyCatalog(typeof (IBraceMatchingService).Assembly);
            var thisAssembly = new AssemblyCatalog(typeof (NQueryLanguage).Assembly);
            return new AggregateCatalog(servicesAssembly, thisAssembly);
        }

        public void Dispose()
        {
            _compositionContainer.Dispose();
        }
    }
}

using System;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.Primitives;

using ActiproSoftware.Text.Implementation;

using NQuery.Language.Services.BraceMatching;
using NQuery.Language.Wpf;

namespace NQuery.Language.ActiproWpf
{
    public sealed class NQueryLanguage : SyntaxLanguage, IDisposable
    {
        private readonly CompositionContainer _compositionContainer;

        public NQueryLanguage()
            : this(GetDefaultCatalog())
        {
        }

        public NQueryLanguage(ComposablePartCatalog catalog)
            : base("NQuery")
        {
            _compositionContainer = new CompositionContainer(catalog);
            _compositionContainer.SatisfyImportsOnce(this);

            var serviceProviders = _compositionContainer.GetExportedValues<ILanguageServiceRegistrar>();
            foreach (var serviceProvider in serviceProviders)
                serviceProvider.RegisterServices(this);
        }

        private static ComposablePartCatalog GetDefaultCatalog()
        {
            var servicesAssembly = new AssemblyCatalog(typeof (IBraceMatchingService).Assembly);
            var wpfAssembly = new AssemblyCatalog(typeof(INQueryGlyphService).Assembly);
            var thisAssembly = new AssemblyCatalog(typeof (NQueryLanguage).Assembly);
            return new AggregateCatalog(servicesAssembly, wpfAssembly, thisAssembly);
        }

        public void Dispose()
        {
            _compositionContainer.Dispose();
        }
    }
}

Fix Actipro language to construct the correct set of language services


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

using osu.Framework.Graphics;
using osu.Game.Graphics.UserInterface;

namespace osu.Game.Overlays.Settings
{
    public class SettingsTextBox : SettingsItem<string>
    {
        protected override Drawable CreateControl() => new OsuTextBox
        {
            Margin = new MarginPadding { Top = 5 },
            RelativeSizeAxes = Axes.X,
        };
    }
}

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

using osu.Framework.Graphics;
using osu.Game.Graphics.UserInterface;

namespace osu.Game.Overlays.Settings
{
    public class SettingsTextBox : SettingsItem<string>
    {
        protected override Drawable CreateControl() => new OsuTextBox
        {
            Margin = new MarginPadding { Top = 5 },
            RelativeSizeAxes = Axes.X,
            CommitOnFocusLost = true,
        };
    }
}

Make settings textboxes commit on focus lost


namespace NuGetPe
{
    public static class NuGetConstants
    {
        public static readonly string DefaultFeedUrl = "http://www.nuget.org/api/v2/";
        public static readonly string V2LegacyFeedUrl = "https://nuget.org/api/v2/";
        public static readonly string PluginFeedUrl = "http://www.myget.org/F/npe/";

        public const string V2LegacyNuGetPublishFeed = "https://nuget.org";
        public const string NuGetPublishFeed = "https://www.nuget.org";
    }
}

namespace NuGetPe
{
    public static class NuGetConstants
    {
        public static readonly string DefaultFeedUrl = "https://www.nuget.org/api/v2/";
        public static readonly string V2LegacyFeedUrl = "https://nuget.org/api/v2/";
        public static readonly string PluginFeedUrl = "http://www.myget.org/F/npe/";

        public const string V2LegacyNuGetPublishFeed = "https://nuget.org";
        public const string NuGetPublishFeed = "https://www.nuget.org";
    }
}

Update nuget url to https

Update nuget url to https


/* © 2017 Ivan Pointer
MIT License: https://github.com/ivanpointer/NuLog/blob/master/LICENSE
Source on GitHub: https://github.com/ivanpointer/NuLog */

using NuLog.LogEvents;
using System;
using System.Threading.Tasks;

namespace NuLog.Targets
{
    public class ConsoleTarget : LayoutTargetBase
    {
        public override void Write(LogEvent logEvent)
        {
            var message = Layout.Format(logEvent);
            Console.Write(message);
        }
    }
}

/* © 2017 Ivan Pointer
MIT License: https://github.com/ivanpointer/NuLog/blob/master/LICENSE
Source on GitHub: https://github.com/ivanpointer/NuLog */

using NuLog.LogEvents;
using System;

namespace NuLog.Targets
{
    public class ConsoleTarget : LayoutTargetBase
    {
        public override void Write(LogEvent logEvent)
        {
            var message = Layout.Format(logEvent);
            Console.Write(message);
        }
    }
}

Remove reference to unused "Tasks".

Remove reference to unused "Tasks".


// <copyright file="QtCreatorBuilder.cs" company="Mark Final">
//  Opus package
// </copyright>
// <summary>QtCreator package</summary>
// <author>Mark Final</author>
[assembly: Opus.Core.DeclareBuilder("QtCreator", typeof(QtCreatorBuilder.QtCreatorBuilder))]

// Automatically generated by Opus v0.20
namespace QtCreatorBuilder
{
    public sealed partial class QtCreatorBuilder : Opus.Core.IBuilder
    {
        public static string GetProFilePath(Opus.Core.DependencyNode node)
        {
            //string proFileDirectory = System.IO.Path.Combine(node.GetModuleBuildDirectory(), "QMake");
            string proFileDirectory = node.GetModuleBuildDirectory();
            string proFilePath = System.IO.Path.Combine(proFileDirectory, System.String.Format("{0}_{1}.pro", node.UniqueModuleName, node.Target));
            Opus.Core.Log.MessageAll("ProFile : '{0}'", proFilePath);
            return proFilePath;
        }

        public static string GetQtConfiguration(Opus.Core.Target target)
        {
            if (target.Configuration != Opus.Core.EConfiguration.Debug && target.Configuration != Opus.Core.EConfiguration.Optimized)
            {
                throw new Opus.Core.Exception("QtCreator only supports debug and optimized configurations");
            }
            string QtCreatorConfiguration = (target.Configuration == Opus.Core.EConfiguration.Debug) ? "debug" : "release";
            return QtCreatorConfiguration;
        }
    }
}

// <copyright file="QtCreatorBuilder.cs" company="Mark Final">
//  Opus package
// </copyright>
// <summary>QtCreator package</summary>
// <author>Mark Final</author>
[assembly: Opus.Core.DeclareBuilder("QtCreator", typeof(QtCreatorBuilder.QtCreatorBuilder))]

// Automatically generated by Opus v0.20
namespace QtCreatorBuilder
{
    public sealed partial class QtCreatorBuilder : Opus.Core.IBuilder
    {
        public static string GetProFilePath(Opus.Core.DependencyNode node)
        {
            //string proFileDirectory = System.IO.Path.Combine(node.GetModuleBuildDirectory(), "QMake");
            string proFileDirectory = node.GetModuleBuildDirectory();
            //string proFilePath = System.IO.Path.Combine(proFileDirectory, System.String.Format("{0}_{1}.pro", node.UniqueModuleName, node.Target));
            string proFilePath = System.IO.Path.Combine(proFileDirectory, System.String.Format("{0}.pro", node.ModuleName));
            Opus.Core.Log.MessageAll("ProFile : '{0}'", proFilePath);
            return proFilePath;
        }

        public static string GetQtConfiguration(Opus.Core.Target target)
        {
            if (target.Configuration != Opus.Core.EConfiguration.Debug && target.Configuration != Opus.Core.EConfiguration.Optimized)
            {
                throw new Opus.Core.Exception("QtCreator only supports debug and optimized configurations");
            }
            string QtCreatorConfiguration = (target.Configuration == Opus.Core.EConfiguration.Debug) ? "debug" : "release";
            return QtCreatorConfiguration;
        }
    }
}

Simplify the .pro file names

[qtcreator] Simplify the .pro file names


using System.Web.Mvc;
using Autofac;
using Autofac.Integration.Mvc;
using Zk.Models;
using Zk.Services;
using Zk.Repositories;

namespace Zk
{
    public static class IocConfig
    {
        public static void RegisterDependencies()
        {
            var builder = new ContainerBuilder();
            builder.RegisterControllers(typeof(MvcApplication).Assembly);

            builder.RegisterType<ZkContext>()
                .As<IZkContext>()
                .InstancePerRequest();

            builder.RegisterType<Repository>();
            builder.RegisterType<AuthenticationService>();
            builder.RegisterType<UserService>()
                .Keyed<IUserService>(AuthenticatedStatus.Anonymous);
            builder.RegisterType<UserService>()
                .Keyed<IUserService>(AuthenticatedStatus.Authenticated);
            builder.RegisterType<PasswordRecoveryService>();
            builder.RegisterType<CalendarService>();
            builder.RegisterType<FarmingActionService>();
            builder.RegisterType<CropProvider>();

            var container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }
    }
}

using System.Web.Mvc;
using Autofac;
using Autofac.Integration.Mvc;
using Zk.Models;
using Zk.Services;
using Zk.Repositories;

namespace Zk
{
    public static class IocConfig
    {
        public static void RegisterDependencies()
        {
            var builder = new ContainerBuilder();
            builder.RegisterControllers(typeof(MvcApplication).Assembly);

            builder.RegisterType<ZkContext>()
                .As<IZkContext>()
                .InstancePerRequest();

            builder.RegisterType<Repository>()
                .InstancePerRequest();
            builder.RegisterType<AuthenticationService>()
                .InstancePerRequest();

            builder.RegisterType<UserService>()
                .Keyed<IUserService>(AuthenticatedStatus.Anonymous);
            builder.RegisterType<UserService>()
                .Keyed<IUserService>(AuthenticatedStatus.Authenticated);

            builder.RegisterType<PasswordRecoveryService>()
                .InstancePerRequest();
            builder.RegisterType<CalendarService>()
                .InstancePerRequest();
            builder.RegisterType<FarmingActionService>()
                .InstancePerRequest();
            builder.RegisterType<CropProvider>()
                .InstancePerRequest();;

            var container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }
    }
}

Add instanceperrequest lifetime scope to all services


using System;

namespace DAQ.Environment
{
    public class PHBonesawFileSystem : DAQ.Environment.FileSystem
    {
        public PHBonesawFileSystem()
        {
            Paths.Add("MOTMasterDataPath", "C:\\Users\\cafmot\\Box\\CaF MOT\\MOTData\\MOTMasterData\\");
            Paths.Add("scriptListPath", "C:\\ControlPrograms\\EDMSuite\\MoleculeMOTMasterScripts");
            Paths.Add("daqDLLPath", "C:\\ControlPrograms\\EDMSuite\\DAQ\\bin\\CaF\\daq.dll");
            Paths.Add("MOTMasterExePath", "C:\\ControlPrograms\\EDMSuite\\MOTMaster\\bin\\CaF\\");
            Paths.Add("ExternalFilesPath", "C:\\Users\\cafmot\\Documents\\Temp Camera Images\\");
            Paths.Add("HardwareClassPath", "C:\\ControlPrograms\\EDMSuite\\DAQ\\MoleculeMOTHardware.cs");

            DataSearchPaths.Add(Paths["scanMasterDataPath"]);

            SortDataByDate = false;
        }
    }
}

using System;

namespace DAQ.Environment
{
    public class PHBonesawFileSystem : DAQ.Environment.FileSystem
    {
        public PHBonesawFileSystem()
        {
            Paths.Add("MOTMasterDataPath", "C:\\Users\\cafmot\\Box Sync\\CaF MOT\\MOTData\\MOTMasterData\\");
            Paths.Add("scriptListPath", "C:\\ControlPrograms\\EDMSuite\\MoleculeMOTMasterScripts");
            Paths.Add("daqDLLPath", "C:\\ControlPrograms\\EDMSuite\\DAQ\\bin\\CaF\\daq.dll");
            Paths.Add("MOTMasterExePath", "C:\\ControlPrograms\\EDMSuite\\MOTMaster\\bin\\CaF\\");
            Paths.Add("ExternalFilesPath", "C:\\Users\\cafmot\\Documents\\Temp Camera Images\\");
            Paths.Add("HardwareClassPath", "C:\\ControlPrograms\\EDMSuite\\DAQ\\MoleculeMOTHardware.cs");

            DataSearchPaths.Add(Paths["scanMasterDataPath"]);

            SortDataByDate = false;
        }
    }
}

Change CaF file system paths

Change CaF file system paths

- We've moved back to using Box sync (instead of Box drive) on lab
computer so file paths have changed


// 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.Composition;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Shell.Interop;

namespace Microsoft.VisualStudio.LanguageServices.Telemetry
{
    [ExportWorkspaceService(typeof(IProjectTypeLookupService), ServiceLayer.Host), Shared]
    internal class ProjectTypeLookupService : IProjectTypeLookupService
    {
        public string GetProjectType(Workspace workspace, ProjectId projectId)
        {
            if (workspace == null || projectId == null)
            {
                return string.Empty;
            }

            var vsWorkspace = workspace as VisualStudioWorkspace;

            var aggregatableProject = vsWorkspace.GetHierarchy(projectId) as IVsAggregatableProject;
            if (aggregatableProject == null)
            {
                return string.Empty;
            }

            if (ErrorHandler.Succeeded(aggregatableProject.GetAggregateProjectTypeGuids(out var projectType)))
            {
                return projectType;
            }

            return projectType ?? string.Empty;
        }
    }
}

// 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.Composition;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Shell.Interop;

namespace Microsoft.VisualStudio.LanguageServices.Telemetry
{
    [ExportWorkspaceService(typeof(IProjectTypeLookupService), ServiceLayer.Host), Shared]
    internal class ProjectTypeLookupService : IProjectTypeLookupService
    {
        public string GetProjectType(Workspace workspace, ProjectId projectId)
        {
            if (!(workspace is VisualStudioWorkspace vsWorkspace) || projectId == null)
            {
                return string.Empty;
            }

            var aggregatableProject = vsWorkspace.GetHierarchy(projectId) as IVsAggregatableProject;
            if (aggregatableProject == null)
            {
                return string.Empty;
            }

            if (ErrorHandler.Succeeded(aggregatableProject.GetAggregateProjectTypeGuids(out var projectType)))
            {
                return projectType;
            }

            return projectType ?? string.Empty;
        }
    }
}

Fix incorrect assumption that a workspace is a Visual Studio workspace

Fixes #27128


@model dynamic
@using Umbraco.Web.Templates

@if (Model.value != null)
{
    var url = Model.value.image;
    if(Model.editor.config != null && Model.editor.config.size != null){
        url += "?width=" + Model.editor.config.size.width;
        url += "&height=" + Model.editor.config.size.height;

        if(Model.value.focalPoint != null){
            url += "&center=" + Model.value.focalPoint.top +"," + Model.value.focalPoint.left;
            url += "&mode=crop";
        }
    }

    if (Model.value.caption != null)
    {

@Model.value.caption

    }
}

@model dynamic
@using Umbraco.Web.Templates

@if (Model.value != null)
{
    var url = Model.value.image;
    if(Model.editor.config != null && Model.editor.config.size != null){
        url += "?width=" + Model.editor.config.size.width;
        url += "&height=" + Model.editor.config.size.height;

        if(Model.value.focalPoint != null){
            url += "&center=" + Model.value.focalPoint.top +"," + Model.value.focalPoint.left;
            url += "&mode=crop";
        }
    }

    var altText = Model.value.altText ?? String.Empty;

    if (Model.value.caption != null)
    {

@Model.value.caption

    }
}

Fix for U4-10821, render alt text attribute from grid image editor, or empty string if null (for screen readers)


using System;
using Sancho.DOM.XamarinForms;
using Sancho.XAMLParser;
using TabletDesigner.Helpers;
using Xamarin.Forms;

namespace TabletDesigner
{
    public interface ILogAccess
    {
        void Clear();
        string Log { get; }
    }

    public partial class TabletDesignerPage : ContentPage
    {
        ILogAccess logAccess;

        public TabletDesignerPage()
        {
            InitializeComponent();
            logAccess = DependencyService.Get<ILogAccess>();
        }

        protected override void OnAppearing()
        {
            base.OnAppearing();
            editor.Text = Settings.Xaml;
        }

        void Handle_TextChanged(object sender, Xamarin.Forms.TextChangedEventArgs e)
        {
            try
            {
                Settings.Xaml = editor.Text;

                logAccess.Clear();
                var parser = new Parser();
                var rootNode = parser.Parse(e.NewTextValue);

                rootNode = new ContentNodeProcessor().Process(rootNode);
                rootNode = new ExpandedPropertiesProcessor().Process(rootNode);

                var view = new XamlDOMCreator().CreateNode(rootNode) as View;
                Root.Content = view;

                LoggerOutput.Text = logAccess.Log;
                LoggerOutput.TextColor = Color.White;
            }
            catch (Exception ex)
            {
                LoggerOutput.Text = ex.ToString();
                LoggerOutput.TextColor = Color.FromHex("#FF3030");
            }
        }
    }
}

using System;
using Sancho.DOM.XamarinForms;
using Sancho.XAMLParser;
using TabletDesigner.Helpers;
using Xamarin.Forms;

namespace TabletDesigner
{
    public interface ILogAccess
    {
        void Clear();
        string Log { get; }
    }

    public partial class TabletDesignerPage : ContentPage
    {
        ILogAccess logAccess;

        public TabletDesignerPage()
        {
            InitializeComponent();
            logAccess = DependencyService.Get<ILogAccess>();
        }

        protected override void OnAppearing()
        {
            base.OnAppearing();
            editor.Text = Settings.Xaml;
        }

        void Handle_TextChanged(object sender, Xamarin.Forms.TextChangedEventArgs e)
        {
            try
            {
                Settings.Xaml = editor.Text;

                logAccess.Clear();
                var parser = new Parser();
                var rootNode = parser.Parse(e.NewTextValue);

                rootNode = new ContentNodeProcessor().Process(rootNode);
                rootNode = new ExpandedPropertiesProcessor().Process(rootNode);

                var dom = new XamlDOMCreator().CreateNode(rootNode);
                if (dom is View)
                    Root.Content = (View)dom;
                else if (dom is ContentPage)
                    Root.Content = ((ContentPage)dom).Content;

                LoggerOutput.Text = logAccess.Log;
                LoggerOutput.TextColor = Color.White;
            }
            catch (Exception ex)
            {
                LoggerOutput.Text = ex.ToString();
                LoggerOutput.TextColor = Color.FromHex("#FF3030");
            }
        }
    }
}

Handle content pages as well

Handle content pages as well


using System;
using System.Collections.Generic;
using ICSharpCode.Decompiler;
using ICSharpCode.Decompiler.Ast.Transforms;
using ICSharpCode.NRefactory.CSharp;

namespace JSIL {
    public class DeclarationHoister : ContextTrackingVisitor<object> {
        public readonly BlockStatement Output;
        public VariableDeclarationStatement Statement = null;
        public readonly HashSet<string> HoistedNames = new HashSet<string>();

        public DeclarationHoister (DecompilerContext context, BlockStatement output)
            : base(context) {

            Output = output;
        }

        public override object VisitVariableDeclarationStatement (VariableDeclarationStatement variableDeclarationStatement, object data) {
            if (Statement == null) {
                Statement = new VariableDeclarationStatement();
                Output.Add(Statement);
            }

            foreach (var variable in variableDeclarationStatement.Variables) {
                if (!HoistedNames.Contains(variable.Name)) {
                    Statement.Variables.Add(new VariableInitializer(
                        variable.Name
                    ));
                    HoistedNames.Add(variable.Name);
                }
            }

            var replacement = new BlockStatement();
            foreach (var variable in variableDeclarationStatement.Variables) {
                replacement.Add(new ExpressionStatement(new AssignmentExpression {
                    Left = new IdentifierExpression(variable.Name),
                    Right = variable.Initializer.Clone()
                }));
            }

            if (replacement.Statements.Count == 1) {
                var firstChild = replacement.FirstChild;
                firstChild.Remove();
                variableDeclarationStatement.ReplaceWith(firstChild);
            } else if (replacement.Statements.Count > 1) {
                variableDeclarationStatement.ReplaceWith(replacement);
            }

            return null;
        }
    }
}

using System;
using System.Collections.Generic;
using ICSharpCode.Decompiler;
using ICSharpCode.Decompiler.Ast.Transforms;
using ICSharpCode.NRefactory.CSharp;

namespace JSIL {
    public class DeclarationHoister : ContextTrackingVisitor<object> {
        public readonly BlockStatement Output;
        public VariableDeclarationStatement Statement = null;
        public readonly HashSet<string> HoistedNames = new HashSet<string>();

        public DeclarationHoister (DecompilerContext context, BlockStatement output)
            : base(context) {

            Output = output;
        }

        public override object VisitVariableDeclarationStatement (VariableDeclarationStatement variableDeclarationStatement, object data) {
            if (Statement == null) {
                Statement = new VariableDeclarationStatement();
                Output.Add(Statement);
            }

            foreach (var variable in variableDeclarationStatement.Variables) {
                if (!HoistedNames.Contains(variable.Name)) {
                    Statement.Variables.Add(new VariableInitializer(
                        variable.Name
                    ));
                    HoistedNames.Add(variable.Name);
                }
            }

            var replacement = new BlockStatement();
            foreach (var variable in variableDeclarationStatement.Variables) {
                if (variable.IsNull)
                    continue;
                if (variable.Initializer.IsNull)
                    continue;

                replacement.Add(new ExpressionStatement(new AssignmentExpression {
                    Left = new IdentifierExpression(variable.Name),
                    Right = variable.Initializer.Clone()
                }));
            }

            if (replacement.Statements.Count == 1) {
                var firstChild = replacement.FirstChild;
                firstChild.Remove();
                variableDeclarationStatement.ReplaceWith(firstChild);
            } else if (replacement.Statements.Count > 1) {
                variableDeclarationStatement.ReplaceWith(replacement);
            } else {
                variableDeclarationStatement.Remove();
            }

            return null;
        }
    }
}

Fix hoisting of null initializers

Fix hoisting of null initializers


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

namespace Avalonia.Data.Core
{
    internal abstract class SettableNode : ExpressionNode
    {
        public bool SetTargetValue(object value, BindingPriority priority)
        {
            if (ShouldNotSet(value))
            {
                return true;
            }
            return SetTargetValueCore(value, priority);
        }

        private bool ShouldNotSet(object value)
        {
            if (PropertyType == null)
            {
                return false;
            }
            if (PropertyType.IsValueType)
            {
                return LastValue?.Target.Equals(value) ?? false;
            }
            return LastValue != null && Object.ReferenceEquals(LastValue?.Target, value);
        }

        protected abstract bool SetTargetValueCore(object value, BindingPriority priority);

        public abstract Type PropertyType { get; }
    }
}

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

namespace Avalonia.Data.Core
{
    internal abstract class SettableNode : ExpressionNode
    {
        public bool SetTargetValue(object value, BindingPriority priority)
        {
            if (ShouldNotSet(value))
            {
                return true;
            }
            return SetTargetValueCore(value, priority);
        }

        private bool ShouldNotSet(object value)
        {
            if (PropertyType == null)
            {
                return false;
            }
            if (PropertyType.IsValueType)
            {
                return LastValue?.Target != null && LastValue.Target.Equals(value);
            }
            return LastValue != null && Object.ReferenceEquals(LastValue?.Target, value);
        }

        protected abstract bool SetTargetValueCore(object value, BindingPriority priority);

        public abstract Type PropertyType { get; }
    }
}

Fix codepath where the property is a value type but the weakreference has been collected.


using System;
using System.Threading.Tasks;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Serilog;

namespace FilterLists.SharedKernel.Logging
{
    public static class HostRunner
    {
        public static async Task TryRunWithLoggingAsync(this IHost host, Func<Task>? runPreHostAsync = default)
        {
            _ = host ?? throw new ArgumentNullException(nameof(host));

            InitializeLogger(host);

            try
            {
                if (runPreHostAsync != null)
                {
                    Log.Information("Initializing pre-host");
                    await runPreHostAsync();
                }

                Log.Information("Initializing host");
                await host.RunAsync();
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Host terminated unexpectedly");
                throw;
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }

        private static void InitializeLogger(IHost host)
        {
            var hostEnvironment = host.Services.GetRequiredService<IHostEnvironment>();
            Log.Logger = ConfigurationBuilder.BaseLoggerConfiguration
                .ReadFrom.Configuration(host.Services.GetRequiredService<IConfiguration>())
                .Enrich.WithProperty("Application", hostEnvironment.ApplicationName)
                .Enrich.WithProperty("Environment", hostEnvironment.EnvironmentName)
                .WriteTo.Conditional(
                    _ => !hostEnvironment.IsProduction(),
                    sc => sc.Console().WriteTo.Debug())
                .WriteTo.Conditional(
                    _ => hostEnvironment.IsProduction(),
                    sc => sc.ApplicationInsights(
                        host.Services.GetRequiredService<TelemetryConfiguration>(),
                        TelemetryConverter.Traces))
                .CreateLogger();
        }
    }
}

using System;
using System.Threading.Tasks;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Serilog;

namespace FilterLists.SharedKernel.Logging
{
    public static class HostRunner
    {
        public static async Task TryRunWithLoggingAsync(this IHost host, Func<Task>? runPreHostAsync = default)
        {
            _ = host ?? throw new ArgumentNullException(nameof(host));

            Log.Logger = ConfigurationBuilder.BaseLoggerConfiguration
                .WriteTo.Conditional(
                    _ => host.Services.GetService<IHostEnvironment>().IsProduction(),
                    c => c.ApplicationInsights(
                        TelemetryConfiguration.CreateDefault(),
                        TelemetryConverter.Traces))
                .CreateLogger();

            try
            {
                if (runPreHostAsync != null)
                {
                    Log.Information("Initializing pre-host");
                    await runPreHostAsync();
                }

                Log.Information("Initializing host");
                await host.RunAsync();
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Host terminated unexpectedly");
                throw;
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }
    }
}

Revert "fix(logging): 🐛 try yet another AppInsights config"

This reverts commit a313ce949202d3cc6263b8ff7136a34cf99715de.


using System;
using System.Xml;

namespace FluentNHibernate.Mapping
{
    public class ImportPart : IMappingPart
    {
        private readonly Cache<string, string> attributes = new Cache<string, string>();
        private readonly Type importType;

        public ImportPart(Type importType)
        {
            this.importType = importType;
        }

        public void SetAttribute(string name, string value)
        {
            attributes.Store(name, value);
        }

        public void SetAttributes(Attributes attrs)
        {
            foreach (var key in attrs.Keys)
            {
                SetAttribute(key, attrs[key]);
            }
        }

        public void Write(XmlElement classElement, IMappingVisitor visitor)
        {
            var importElement = classElement.AddElement("import")
                .WithAtt("class", importType.AssemblyQualifiedName);

            attributes.ForEachPair((name, value) => importElement.WithAtt(name, value));
        }

        public void As(string alternativeName)
        {
            SetAttribute("rename", alternativeName);
        }

        public int Level
        {
            get { return 1; }
        }

        public PartPosition Position
        {
            get { return PartPosition.First; }
        }
    }
}

using System;
using System.Xml;

namespace FluentNHibernate.Mapping
{
    public class ImportPart : IMappingPart
    {
        private readonly Cache<string, string> attributes = new Cache<string, string>();
        private readonly Type importType;

        public ImportPart(Type importType)
        {
            this.importType = importType;
        }

        public void SetAttribute(string name, string value)
        {
            attributes.Store(name, value);
        }

        public void SetAttributes(Attributes attrs)
        {
            foreach (var key in attrs.Keys)
            {
                SetAttribute(key, attrs[key]);
            }
        }

        public void Write(XmlElement classElement, IMappingVisitor visitor)
        {
            var importElement = classElement.AddElement("import")
                .WithAtt("class", importType.AssemblyQualifiedName)
                .WithAtt("xmlns", "urn:nhibernate-mapping-2.2");

            attributes.ForEachPair((name, value) => importElement.WithAtt(name, value));
        }

        public void As(string alternativeName)
        {
            SetAttribute("rename", alternativeName);
        }

        public int Level
        {
            get { return 1; }
        }

        public PartPosition Position
        {
            get { return PartPosition.First; }
        }
    }
}

Fix import tag to have correct namespace

git-svn-id: a161142445158cf41e00e2afdd70bb78aded5464@138 48f0ce17-cc52-0410-af8c-857c09b6549b


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using Microsoft.Xaml.Behaviors;

namespace Monitorian.Core.Views.Behaviors
{
	public class FocusElementAction : TriggerAction<DependencyObject>
	{
		public UIElement TargetElement
		{
			get { return (UIElement)GetValue(TargetElementProperty); }
			set { SetValue(TargetElementProperty, value); }
		}
		public static readonly DependencyProperty TargetElementProperty =
			DependencyProperty.Register(
				"TargetElement",
				typeof(UIElement),
				typeof(FocusElementAction),
				new PropertyMetadata(null));

		protected override void Invoke(object parameter)
		{
			if ((TargetElement is null) || !TargetElement.Focusable || TargetElement.IsFocused)
				return;

			TargetElement.Focus();
		}
	}
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using Microsoft.Xaml.Behaviors;

namespace Monitorian.Core.Views.Behaviors
{
	public class FocusElementAction : TriggerAction<DependencyObject>
	{
		public UIElement TargetElement
		{
			get { return (UIElement)GetValue(TargetElementProperty); }
			set { SetValue(TargetElementProperty, value); }
		}
		public static readonly DependencyProperty TargetElementProperty =
			DependencyProperty.Register(
				"TargetElement",
				typeof(UIElement),
				typeof(FocusElementAction),
				new PropertyMetadata(default(UIElement)));

		protected override void Invoke(object parameter)
		{
			if ((TargetElement is null) || !TargetElement.Focusable || TargetElement.IsFocused)
				return;

			TargetElement.Focus();
		}
	}
}

Modify PropertyMetadata for correct overloading


#if !NO_UNITY
using System;
using UnityEngine;
using UnityEngine.Events;

namespace FullSerializer {
    partial class fsConverterRegistrar {
        public static Internal.Converters.UnityEvent_Converter Register_UnityEvent_Converter;
    }
}

namespace FullSerializer.Internal.Converters {
    // The standard FS reflection converter has started causing Unity to crash when processing
    // UnityEvent. We can send the serialization through JsonUtility which appears to work correctly
    // instead.
    //
    // We have to support legacy serialization formats so importing works as expected.
    public class UnityEvent_Converter : fsConverter {
        public override bool CanProcess(Type type) {
            return typeof(UnityEvent).Resolve().IsAssignableFrom(type) && type.IsGenericType == false;
        }

        public override bool RequestCycleSupport(Type storageType) {
            return false;
        }

        public override fsResult TryDeserialize(fsData data, ref object instance, Type storageType) {
            Type objectType = (Type)instance;

            fsResult result = fsResult.Success;
            instance = JsonUtility.FromJson(fsJsonPrinter.CompressedJson(data), objectType);
            return result;
        }

        public override fsResult TrySerialize(object instance, out fsData serialized, Type storageType) {
            fsResult result = fsResult.Success;
            serialized = fsJsonParser.Parse(JsonUtility.ToJson(instance));
            return result;
        }
    }
}
#endif

#if !NO_UNITY
using System;
using UnityEngine;
using UnityEngine.Events;

namespace FullSerializer {
    partial class fsConverterRegistrar {
        // Disable the converter for the time being. Unity's JsonUtility API cannot be called from
        // within a C# ISerializationCallbackReceiver callback.

        // public static Internal.Converters.UnityEvent_Converter Register_UnityEvent_Converter;
    }
}

namespace FullSerializer.Internal.Converters {
    // The standard FS reflection converter has started causing Unity to crash when processing
    // UnityEvent. We can send the serialization through JsonUtility which appears to work correctly
    // instead.
    //
    // We have to support legacy serialization formats so importing works as expected.
    public class UnityEvent_Converter : fsConverter {
        public override bool CanProcess(Type type) {
            return typeof(UnityEvent).Resolve().IsAssignableFrom(type) && type.IsGenericType == false;
        }

        public override bool RequestCycleSupport(Type storageType) {
            return false;
        }

        public override fsResult TryDeserialize(fsData data, ref object instance, Type storageType) {
            Type objectType = (Type)instance;

            fsResult result = fsResult.Success;
            instance = JsonUtility.FromJson(fsJsonPrinter.CompressedJson(data), objectType);
            return result;
        }

        public override fsResult TrySerialize(object instance, out fsData serialized, Type storageType) {
            fsResult result = fsResult.Success;
            serialized = fsJsonParser.Parse(JsonUtility.ToJson(instance));
            return result;
        }
    }
}
#endif

Disable UnityEvent workaround since it is broken in Full Inspector


using System.Collections.Generic;
using Newtonsoft.Json;
using SurveyMonkey.Enums;

namespace SurveyMonkey.Containers
{
    [JsonConverter(typeof(TolerantJsonConverter))]
    public class Recipient : IPageableContainer
    {
        public long? Id { get; set; }
        public long? SurveyId { get; set; }
        internal string Href { get; set; }
        public string Email { get; set; }
        public RecipientSurveyResponseStatus? SurveyResponseStatus { get; set; }
        public MessageStatus? MailStatus { get; set; }
        public Dictionary<string, string> CustomFields { get; set; }
        public string SurveyLink { get; set; }
        public string RemoveLink { get; set; }
        public Dictionary<string, string> ExtraFields { get; set; }
    }
}

using System.Collections.Generic;
using Newtonsoft.Json;
using SurveyMonkey.Enums;

namespace SurveyMonkey.Containers
{
    [JsonConverter(typeof(TolerantJsonConverter))]
    public class Recipient : IPageableContainer
    {
        public long? Id { get; set; }
        public long? SurveyId { get; set; }
        internal string Href { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        public RecipientSurveyResponseStatus? SurveyResponseStatus { get; set; }
        public MessageStatus? MailStatus { get; set; }
        public Dictionary<string, string> CustomFields { get; set; }
        public string SurveyLink { get; set; }
        public string RemoveLink { get; set; }
        public Dictionary<string, string> ExtraFields { get; set; }
    }
}

Include first & last names for recipients


using System;
using System.Diagnostics;
using System.IO;
using DspAdpcm.Encode.Adpcm;
using DspAdpcm.Encode.Adpcm.Formats;
using DspAdpcm.Encode.Pcm;
using DspAdpcm.Encode.Pcm.Formats;

namespace DspAdpcm.Cli
{
    public static class DspAdpcmCli
    {
        public static int Main(string[] args)
        {
            if (args.Length < 2)
            {
                Console.WriteLine("Usage: dspenc <wavin> <dspout>\n");
                return 0;
            }

            IPcmStream wave;

            try
            {
                using (var file = new FileStream(args[0], FileMode.Open))
                {
                    wave = new Wave(file).AudioStream;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return -1;
            }

            Stopwatch watch = new Stopwatch();
            watch.Start();

            IAdpcmStream adpcm = Encode.Adpcm.Encode.PcmToAdpcm(wave);

            watch.Stop();
            Console.WriteLine($"DONE! {adpcm.NumSamples} samples processed\n");
            Console.WriteLine($"Time elapsed: {watch.Elapsed.TotalSeconds}");
            Console.WriteLine($"Processed {(adpcm.NumSamples / watch.Elapsed.TotalMilliseconds):N} samples per milisecond.");

            var dsp = new Dsp(adpcm);

            using (var stream = File.Open(args[1], FileMode.Create))
                foreach (var b in dsp.GetFile())
                    stream.WriteByte(b);

            return 0;
        }
    }
}

using System;
using System.Diagnostics;
using System.IO;
using DspAdpcm.Encode.Adpcm;
using DspAdpcm.Encode.Adpcm.Formats;
using DspAdpcm.Encode.Pcm;
using DspAdpcm.Encode.Pcm.Formats;

namespace DspAdpcm.Cli
{
    public static class DspAdpcmCli
    {
        public static int Main(string[] args)
        {
            if (args.Length < 2)
            {
                Console.WriteLine("Usage: dspadpcm <wavIn> <brstmOut>\n");
                return 0;
            }

            IPcmStream wave;

            try
            {
                using (var file = new FileStream(args[0], FileMode.Open))
                {
                    wave = new Wave(file).AudioStream;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return -1;
            }

            Stopwatch watch = new Stopwatch();
            watch.Start();

            IAdpcmStream adpcm = Encode.Adpcm.Encode.PcmToAdpcmParallel(wave);

            watch.Stop();
            Console.WriteLine($"DONE! {adpcm.NumSamples} samples processed\n");
            Console.WriteLine($"Time elapsed: {watch.Elapsed.TotalSeconds}");
            Console.WriteLine($"Processed {(adpcm.NumSamples / watch.Elapsed.TotalMilliseconds):N} samples per milisecond.");

            var brstm = new Brstm(adpcm);

            using (var stream = File.Open(args[1], FileMode.Create))
                foreach (var b in brstm.GetFile())
                    stream.WriteByte(b);

            return 0;
        }
    }
}

CLI: Make brstm instead of dsp. Encode adpcm channels in parallel


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

namespace SkypeSharp {
    /// <summary>
    ///     Class representing a Skype CHAT object
    /// </summary>
    public class Chat : SkypeObject {
        /// <summary>
        ///     List of users in this chat
        /// </summary>
        public IEnumerable<User> Users {
            get {
                string[] usernames = GetProperty("MEMBERS").Split(' ');
                return usernames.Select(u => new User(Skype, u));
            }
        }

        /// <summary>
        ///     List of chatmembers, useful for changing roles
        ///     Skype broke this so it probably doesn't work
        /// </summary>
        public IEnumerable<ChatMember> ChatMembers {
            get {
                string[] members = GetProperty("MEMBEROBJECTS").Split(' ');
                return members.Select(m => new ChatMember(Skype, m));
            }
        }

        public Chat(Skype skype, string id) : base(skype, id, "CHAT") {}

        /// <summary>
        ///     Send a message to this chat
        /// </summary>
        /// <param name="text">Text to send</param>
        public void Send(string text) {
            Skype.Send("CHATMESSAGE " + ID + " " + text);
        }
    }
}

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

namespace SkypeSharp {
    /// <summary>
    ///     Class representing a Skype CHAT object
    /// </summary>
    public class Chat : SkypeObject {
        /// <summary>
        ///     List of users in this chat
        /// </summary>
        public IEnumerable<User> Users {
            get {
                string[] usernames = GetProperty("MEMBERS").Split(' ');
                return usernames.Select(u => new User(Skype, u));
            }
        }

        /// <summary>
        ///     List of chatmembers, useful for changing roles
        ///     Skype broke this so it probably doesn't work
        /// </summary>
        public IEnumerable<ChatMember> ChatMembers {
            get {
                string[] members = GetProperty("MEMBEROBJECTS").Split(' ');
                return members.Select(m => new ChatMember(Skype, m));
            }
        }

        public Chat(Skype skype, string id) : base(skype, id, "CHAT") {}

        /// <summary>
        ///     Send a message to this chat
        /// </summary>
        /// <param name="text">Text to send</param>
        public void Send(string text) {
            Skype.Send("CHATMESSAGE " + ID + " " + text);
        }

        /// <summary>
        ///     Uses xdotool to attempt to send skype a message
        /// </summary>
        /// <param name="text"></param>
        public void SendRaw(string text) {
            Skype.Send("OPEN CHAT " + ID);

            Process p = new Process();
            p.StartInfo.FileName = "/usr/bin/xdotool";
            p.StartInfo.Arguments = String.Format("search --name skype type \"{0}\"", text.Replace("\"", "\\\""));
            p.Start();
            p.WaitForExit();

            p.StartInfo.Arguments = "search --name skype key ctrl+shift+Return";
            p.Start();
            p.WaitForExit();
        }
    }
}

Add raw message sending, requires xdotool


using System;

namespace SeleniumExtension.SauceLabs
{
    public class SauceDriverKeys
    {
        public static string SAUCELABS_USERNAME
        {
            get
            {
                var userName = Environment.GetEnvironmentVariable("SAUCELABS_USERNAME", EnvironmentVariableTarget.User);
                if(string.IsNullOrEmpty(userName))
                    throw new Exception("Missing environment variable, name: SAUCELABS_USERNAME");
                return userName;
            }
        }

        public static string SAUCELABS_ACCESSKEY
        {
            get
            {
                var userName = Environment.GetEnvironmentVariable("SAUCELABS_ACCESSKEY", EnvironmentVariableTarget.User);
                if (string.IsNullOrEmpty(userName))
                    throw new Exception("Missing environment variable, name: SAUCELABS_ACCESSKEY");
                return userName;
            }
        }
    }
}

using System;

namespace SeleniumExtension.SauceLabs
{
    public class SauceDriverKeys
    {
        public static string SAUCELABS_USERNAME
        {
            get
            {
                var userName = Environment.GetEnvironmentVariable("SAUCELABS_USERNAME");
                if(string.IsNullOrEmpty(userName))
                    throw new Exception("Missing environment variable, name: SAUCELABS_USERNAME");
                return userName;
            }
        }

        public static string SAUCELABS_ACCESSKEY
        {
            get
            {
                var userName = Environment.GetEnvironmentVariable("SAUCELABS_ACCESSKEY");
                if (string.IsNullOrEmpty(userName))
                    throw new Exception("Missing environment variable, name: SAUCELABS_ACCESSKEY");
                return userName;
            }
        }
    }
}

Change the target to get working on build server


namespace Metrics.Integrations.Linters
{
    using System;
    using System.IO;
    using System.Text;

    // TODO: Improve logging.
    public class LogManager : IDisposable
    {
        public StringBuilder LogWriter { get; }
        private bool saved = false;

        public LogManager()
        {
            LogWriter = new StringBuilder();
        }

        public void Log(string format, params object[] args)
        {
            LogWriter.AppendLine(string.Format(format, args));
        }

        public void Trace(string message, params object[] args)
        {
            Log("TRACE: " + message + " {0}", string.Join(" ", args));
        }

        public void Error(string message, params object[] args)
        {
            Log("ERROR: " + message + " {0}", string.Join(" ", args));
            System.Console.Error.WriteLine(string.Format(message + " {0}", string.Join(" ", args)));
        }

        public void Save(string fileName)
        {
            saved = true;
            File.WriteAllText(fileName, LogWriter.ToString());
        }

        public void Dispose()
        {
            if (!saved)
            {
                System.Console.Write(LogWriter.ToString());
            }
        }
    }
}

namespace Metrics.Integrations.Linters
{
    using System;
    using System.IO;
    using System.Text;

    // TODO: Improve logging.
    public class LogManager : IDisposable
    {
        public StringBuilder LogWriter { get; }
        private bool saved = false;
        private bool error = false;

        public LogManager()
        {
            LogWriter = new StringBuilder();
        }

        public void Log(string format, params object[] args)
        {
            LogWriter.AppendLine(string.Format(format, args));
        }

        public void Trace(string message, params object[] args)
        {
            Log("TRACE: " + message + " {0}", string.Join(" ", args));
        }

        public void Error(string message, params object[] args)
        {
            error = true;
            Log("ERROR: " + message + " {0}", string.Join(" ", args));
            System.Console.Error.WriteLine(string.Format(message + " {0}", string.Join(" ", args)));
        }

        public void Save(string fileName)
        {
            saved = true;
            File.WriteAllText(fileName, LogWriter.ToString());
        }

        public void Dispose()
        {
            if (!saved && error)
            {
                System.Console.Write(LogWriter.ToString());
            }
        }
    }
}

Write logs to console only in case of error


using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using KAGTools.Data;
using Newtonsoft.Json;

namespace KAGTools.Helpers
{
    public static class ApiHelper
    {
        private const string UrlPlayer = "https://api.kag2d.com/v1/player/{0}";
        private const string UrlServers = "https://api.kag2d.com/v1/game/thd/kag/servers";

        private static readonly HttpClient httpClient;

        static ApiHelper()
        {
            httpClient = new HttpClient();
        }

        public static async Task<ApiPlayerResults> GetPlayer(string username)
        {
            return await HttpGetApiResult<ApiPlayerResults>(string.Format(UrlPlayer, username));
        }

        public static async Task<ApiServerResults> GetServers(params ApiFilter[] filters)
        {
            string filterJson = "?filters=" + JsonConvert.SerializeObject(filters);
            return await HttpGetApiResult<ApiServerResults>(UrlServers + filterJson);
        }

        private static async Task<T> HttpGetApiResult<T>(string requestUri) where T : class
        {
            try
            {
                string data = await httpClient.GetStringAsync(requestUri);
                return data != null ? JsonConvert.DeserializeObject<T>(data) : null;
            }
            catch (HttpRequestException e)
            {
                MessageBox.Show(e.Message, "HTTP Request Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }

            return null;
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using KAGTools.Data;
using Newtonsoft.Json;

namespace KAGTools.Helpers
{
    public static class ApiHelper
    {
        private const string UrlPlayer = "https://api.kag2d.com/v1/player/{0}";
        private const string UrlServers = "https://api.kag2d.com/v1/game/thd/kag/servers";

        private static readonly HttpClient httpClient;

        static ApiHelper()
        {
            httpClient = new HttpClient();
        }

        public static async Task<ApiPlayerResults> GetPlayer(string username)
        {
            return await HttpGetApiResult<ApiPlayerResults>(string.Format(UrlPlayer, username));
        }

        public static async Task<ApiServerResults> GetServers(params ApiFilter[] filters)
        {
            string filterJson = "?filters=" + JsonConvert.SerializeObject(filters);
            return await HttpGetApiResult<ApiServerResults>(UrlServers + filterJson);
        }

        private static async Task<T> HttpGetApiResult<T>(string requestUri) where T : class
        {
            try
            {
                string data = await httpClient.GetStringAsync(requestUri);
                return data != null ? JsonConvert.DeserializeObject<T>(data) : null;
            }
            catch (HttpRequestException e)
            {
                MessageBox.Show(string.Format("{0}{2}{2}Request URL: {1}", e.Message, requestUri, Environment.NewLine), "HTTP Request Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }

            return null;
        }
    }
}

Include request URL in HTTP error message


using System;
using Gtk;

namespace gtksharp_clock
{
	class MainClass
	{
		public static void Main(string[] args)
		{
			Application.Init();
			MainWindow win = new MainWindow();
			win.Show();
			Application.Run();
		}
	}
}

using System;
using Gtk;

// http://www.mono-project.com/docs/gui/gtksharp/widgets/widget-colours/

namespace gtksharp_clock
{
	class MainClass
	{
		public static void Main(string[] args)
		{
			Application.Init();
			ClockWindow win = new ClockWindow ();
			win.Show();
			Application.Run();
		}
	}

	class ClockWindow : Window
	{
		public ClockWindow() : base("ClockWindow")
		{
			SetDefaultSize(250, 200);
			SetPosition(WindowPosition.Center);

			ClockFace cf = new ClockFace();

			Gdk.Color black = new Gdk.Color();
			Gdk.Color.Parse("black", ref black);
			Gdk.Color grey = new Gdk.Color();
			Gdk.Color.Parse("grey", ref grey);

			this.ModifyBg(StateType.Normal, grey);
			cf.ModifyBg(StateType.Normal, grey);

			this.ModifyFg(StateType.Normal, black);
			cf.ModifyFg(StateType.Normal, black);

			this.DeleteEvent += DeleteWindow;

			Add(cf);
			ShowAll();
		}

		static void DeleteWindow(object obj, DeleteEventArgs args)
		{
			Application.Quit();
		}
	}

	class ClockFace : DrawingArea
	{

		public ClockFace() : base()
		{
			this.SetSizeRequest(600, 600);
			this.ExposeEvent += OnExposed;
		}

		public void OnExposed(object o, ExposeEventArgs args)
		{

			Gdk.Color black = new Gdk.Color();
			Gdk.Color.Parse("black", ref black);

			this.ModifyFg(StateType.Normal, black);

			this.GdkWindow.DrawLine(this.Style.BaseGC(StateType.Normal), 0, 0, 400, 300);
		}
	}
}

Add clock Face and Window classes. Draw a line. Setting FG color is TODO.


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

namespace RabidWarren.Collections.Generic
{
    public static class Enumerable
    {
        public static Multimap<TKey, TElement> ToMultimap<TSource, TKey, TElement>(
            this IEnumerable<TSource> source,
            Func<TSource, TKey> keySelector,
            Func<TSource, TElement> elementSelector)
        {
            var map = new Multimap<TKey, TElement>();

            foreach (var entry in source)
            {
                map.Add(keySelector(entry), elementSelector(entry));
            }

            return map;
        }
    }
}

// -----------------------------------------------------------------------
//  <copyright file="Enumerable.cs" company="Ron Parker">
//   Copyright 2014 Ron Parker
//  </copyright>
//  <summary>
//   Provides an extension method for converting IEnumerables to Multimaps.
//  </summary>
// -----------------------------------------------------------------------

namespace RabidWarren.Collections.Generic
{
    using System;
    using System.Collections.Generic;

    /// <summary>
    /// Contains extension methods for <see cref="System.Collections.Generic.IEnumerable{TSource}"/>.
    /// </summary>
    public static class Enumerable
    {
        /// <summary>
        /// Converts the source to an <see cref="RabidWarren.Collections.Generic.Multimap{TSource, TKey, TValue}"/>.
        /// </summary>
        /// <returns>The <see cref="RabidWarren.Collections.Generic.Multimap{TSource, TKey, TValue}"/>.</returns>
        /// <param name="source">The source.</param>
        /// <param name="keySelector">The key selector.</param>
        /// <param name="valueSelector">The value selector.</param>
        /// <typeparam name="TSource">The source type.</typeparam>
        /// <typeparam name="TKey">The key type.</typeparam>
        /// <typeparam name="TValue">The the value type.</typeparam>
        public static Multimap<TKey, TValue> ToMultimap<TSource, TKey, TValue>(
            this IEnumerable<TSource> source,
            Func<TSource, TKey> keySelector,
            Func<TSource, TValue> valueSelector)
        {
            var map = new Multimap<TKey, TValue>();

            foreach (var entry in source)
            {
                map.Add(keySelector(entry), valueSelector(entry));
            }

            return map;
        }
    }
}

Document and clean up the binding code

Document and clean up the binding code


<!DOCTYPE html>

    <title>Vote On</title>
    <meta name="viewport" content="initial-scale=1">

    @Styles.Render("~/Bundles/StyleLib/AngularMaterial")
    @Styles.Render("~/Bundles/StyleLib/FontAwesome")
    @Styles.Render("~/Bundles/VotingStyle")

        <toolbar></toolbar>

    @Scripts.Render("~/Bundles/ScriptLib/JQuery");
    @Scripts.Render("~/Bundles/ScriptLib/JQuerySignalR");

    @Scripts.Render("~/Bundles/ScriptLib/Angular")
    @Scripts.Render("~/Bundles/ScriptLib/AngularAnimate")
    @Scripts.Render("~/Bundles/ScriptLib/AngularAria")
    @Scripts.Render("~/Bundles/ScriptLib/AngularMaterial")
    @Scripts.Render("~/Bundles/ScriptLib/AngularMessages")
    @Scripts.Render("~/Bundles/ScriptLib/AngularRoute")
    @Scripts.Render("~/Bundles/ScriptLib/AngularCharts")
    @Scripts.Render("~/Bundles/ScriptLib/AngularSignalR")

    @Scripts.Render("~/Bundles/ScriptLib/ngStorage")
    @Scripts.Render("~/Bundles/ScriptLib/moment")

    @Scripts.Render("~/Bundles/Script")

<!DOCTYPE html>

    <title>Vote On</title>
    <meta name="viewport" content="initial-scale=1">

    @Styles.Render("~/Bundles/StyleLib/AngularMaterial")
    @Styles.Render("~/Bundles/StyleLib/FontAwesome")
    @Styles.Render("~/Bundles/VotingStyle")

        <toolbar></toolbar>

    @Scripts.Render("~/Bundles/ScriptLib/JQuery")
    @Scripts.Render("~/Bundles/ScriptLib/JQuerySignalR")

    @Scripts.Render("~/Bundles/ScriptLib/Angular")
    @Scripts.Render("~/Bundles/ScriptLib/AngularAnimate")
    @Scripts.Render("~/Bundles/ScriptLib/AngularAria")
    @Scripts.Render("~/Bundles/ScriptLib/AngularMaterial")
    @Scripts.Render("~/Bundles/ScriptLib/AngularMessages")
    @Scripts.Render("~/Bundles/ScriptLib/AngularRoute")
    @Scripts.Render("~/Bundles/ScriptLib/AngularCharts")
    @Scripts.Render("~/Bundles/ScriptLib/AngularSignalR")

    @Scripts.Render("~/Bundles/ScriptLib/ngStorage")
    @Scripts.Render("~/Bundles/ScriptLib/moment")

    @Scripts.Render("~/Bundles/Script")

Remove semicolons from poll page

Remove semicolons from poll page


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

using System.Linq;
using osu.Game.Beatmaps;
using osu.Game.Configuration;
using osu.Game.Rulesets.Mods;

namespace osu.Game.Rulesets.Taiko.Mods
{
    public class TaikoModDifficultyAdjust : ModDifficultyAdjust
    {
        [SettingSource("Scroll Speed", "Adjust a beatmap's set scroll speed", LAST_SETTING_ORDER + 1, SettingControlType = typeof(DifficultyAdjustSettingsControl))]
        public DifficultyBindable ScrollSpeed { get; } = new DifficultyBindable
        {
            Precision = 0.05f,
            MinValue = 0.25f,
            MaxValue = 4,
            ReadCurrentFromDifficulty = _ => 1,
        };

        public override string SettingDescription
        {
            get
            {
                string scrollSpeed = ScrollSpeed.IsDefault ? string.Empty : $"Scroll x{ScrollSpeed.Value:N1}";

                return string.Join(", ", new[]
                {
                    base.SettingDescription,
                    scrollSpeed
                }.Where(s => !string.IsNullOrEmpty(s)));
            }
        }

        protected override void ApplySettings(BeatmapDifficulty difficulty)
        {
            base.ApplySettings(difficulty);

            if (ScrollSpeed.Value != null) difficulty.SliderMultiplier *= ScrollSpeed.Value.Value;
        }
    }
}

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

using System.Linq;
using osu.Game.Beatmaps;
using osu.Game.Configuration;
using osu.Game.Rulesets.Mods;

namespace osu.Game.Rulesets.Taiko.Mods
{
    public class TaikoModDifficultyAdjust : ModDifficultyAdjust
    {
        [SettingSource("Scroll Speed", "Adjust a beatmap's set scroll speed", LAST_SETTING_ORDER + 1, SettingControlType = typeof(DifficultyAdjustSettingsControl))]
        public DifficultyBindable ScrollSpeed { get; } = new DifficultyBindable
        {
            Precision = 0.05f,
            MinValue = 0.25f,
            MaxValue = 4,
            ReadCurrentFromDifficulty = _ => 1,
        };

        public override string SettingDescription
        {
            get
            {
                string scrollSpeed = ScrollSpeed.IsDefault ? string.Empty : $"Scroll x{ScrollSpeed.Value:N2}";

                return string.Join(", ", new[]
                {
                    base.SettingDescription,
                    scrollSpeed
                }.Where(s => !string.IsNullOrEmpty(s)));
            }
        }

        protected override void ApplySettings(BeatmapDifficulty difficulty)
        {
            base.ApplySettings(difficulty);

            if (ScrollSpeed.Value != null) difficulty.SliderMultiplier *= ScrollSpeed.Value.Value;
        }
    }
}

Fix taiko difficulty adjust scroll speed being shown with too low precision


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

using osu.Framework.Timing;
using osu.Framework.Configuration;

namespace osu.Game.Screens.Play.ReplaySettings
{
    public class PlaybackSettings : ReplayGroup
    {
        protected override string Title => @"playback";

        public IAdjustableClock AdjustableClock { set; get; }

        private readonly ReplaySliderBar<double> sliderbar;

        public PlaybackSettings()
        {
            Child = sliderbar = new ReplaySliderBar<double>
            {
                LabelText = "Playback speed",
                Bindable = new BindableDouble
                {
                    Default = 1,
                    MinValue = 0.5,
                    MaxValue = 2
                },
            };
        }

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

            if (AdjustableClock == null)
                return;

            var clockRate = AdjustableClock.Rate;
            sliderbar.Bindable.ValueChanged += rateMultiplier => AdjustableClock.Rate = clockRate * rateMultiplier;
        }
    }
}

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

using osu.Framework.Timing;
using osu.Framework.Configuration;

namespace osu.Game.Screens.Play.ReplaySettings
{
    public class PlaybackSettings : ReplayGroup
    {
        protected override string Title => @"playback";

        public IAdjustableClock AdjustableClock { set; get; }

        private readonly ReplaySliderBar<double> sliderbar;

        public PlaybackSettings()
        {
            Child = sliderbar = new ReplaySliderBar<double>
            {
                LabelText = "Playback speed",
                Bindable = new BindableDouble(1)
                {
                    Default = 1,
                    MinValue = 0.5,
                    MaxValue = 2
                },
            };
        }

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

            if (AdjustableClock == null)
                return;

            var clockRate = AdjustableClock.Rate;
            sliderbar.Bindable.ValueChanged += rateMultiplier => AdjustableClock.Rate = clockRate * rateMultiplier;
        }
    }
}

Add startup value for the slider

Add startup value for the slider


using System;
using Newtonsoft.Json;
using Stripe.Infrastructure;

namespace Stripe
{
    public class StripeStatusTransitions : StripeEntity
    {
        [JsonConverter(typeof(StripeDateTimeConverter))]
        [JsonProperty("canceled")]
        public DateTime? Canceled { get; set; }

        [JsonConverter(typeof(StripeDateTimeConverter))]
        [JsonProperty("fulfiled")]
        public DateTime? Fulfilled { get; set; }

        [JsonConverter(typeof(StripeDateTimeConverter))]
        [JsonProperty("paid")]
        public DateTime? Paid { get; set; }

        [JsonConverter(typeof(StripeDateTimeConverter))]
        [JsonProperty("returned")]
        public DateTime? Returned { get; set; }
    }
}

using System;
using Newtonsoft.Json;
using Stripe.Infrastructure;

namespace Stripe
{
    public class StripeStatusTransitions : StripeEntity
    {
        [JsonConverter(typeof(StripeDateTimeConverter))]
        [JsonProperty("canceled")]
        public DateTime? Canceled { get; set; }

        [JsonConverter(typeof(StripeDateTimeConverter))]
        [JsonProperty("fulfiled")]
        public DateTime? Fulfiled { get; set; }

        [JsonConverter(typeof(StripeDateTimeConverter))]
        [JsonProperty("paid")]
        public DateTime? Paid { get; set; }

        [JsonConverter(typeof(StripeDateTimeConverter))]
        [JsonProperty("returned")]
        public DateTime? Returned { get; set; }
    }
}

Change name of the property for the status transition to match the API too