using System.IO;
using System.Web;
using System.Web.Mvc;
using System.Net.Mail;

namespace SmartCam.Controllers
{
    public class SmartCamController : Controller
    {
        private static byte[] currentImage = new byte[0];

        [HttpPost]
        public string PostImage(HttpPostedFileBase file)
        {
            Stream fileStream = file.InputStream;
            using (MemoryStream ms = new MemoryStream())
            {
                fileStream.CopyTo(ms);
                currentImage = ms.GetBuffer();
            }
            return "Success";
        }

        [HttpGet]
        public FileResult GetPicture()
        {
            return new FileStreamResult(new MemoryStream(currentImage), "image/jpeg");
        }

        [HttpGet]
        public string SendNotification()
        {
            var fromAddress = new MailAddress(from, "From Name");
            var toAddress = new MailAddress(to, "To Name");
            const string fromPassword = ;
            const string subject = "SmartCam";
            const string body = "Motion Detected!";

            using (SmtpClient smtp = new SmtpClient
            {
                Host = "smtp.gmail.com",
                Port = 587,
                EnableSsl = true,
                DeliveryMethod = SmtpDeliveryMethod.Network,
                UseDefaultCredentials = false,
                Credentials = new System.Net.NetworkCredential(fromAddress.Address, fromPassword)
            })
            {
                using (var message = new MailMessage(fromAddress, toAddress)
                {
                    Subject = subject,
                    Body = body
                })
                {
                    smtp.Send(message);
                }
            }
            return "Success";
        }
    }
}

using System.IO;
using System.Web;
using System.Web.Mvc;
using System.Net.Mail;

namespace SmartCam.Controllers
{
    public class SmartCamController : Controller
    {
        private static byte[] currentImage = new byte[0];

        [HttpPost]
        public string PostImage(HttpPostedFileBase file)
        {
            Stream fileStream = file.InputStream;
            using (MemoryStream ms = new MemoryStream())
            {
                fileStream.CopyTo(ms);
                currentImage = ms.GetBuffer();
            }
            return "Success";
        }

        [HttpGet]
        public FileResult GetPicture()
        {
            return new FileStreamResult(new MemoryStream(currentImage), "image/jpeg");
        }

        [HttpGet]
        public ActionResult ShowFeed()
        {
            return View();
        }

        [HttpGet]
        public string SendNotification()
        {
            var fromAddress = new MailAddress(from, "From Name");
            var toAddress = new MailAddress(to, "To Name");
            const string fromPassword = ;
            const string subject = "SmartCam";
            const string body = "Motion Detected!";

            using (SmtpClient smtp = new SmtpClient
            {
                Host = "smtp.gmail.com",
                Port = 587,
                EnableSsl = true,
                DeliveryMethod = SmtpDeliveryMethod.Network,
                UseDefaultCredentials = false,
                Credentials = new System.Net.NetworkCredential(fromAddress.Address, fromPassword)
            })
            {
                using (var message = new MailMessage(fromAddress, toAddress)
                {
                    Subject = subject,
                    Body = body
                })
                {
                    smtp.Send(message);
                }
            }
            return "Success";
        }
    }
}

Add an endpoint for the view page

Add an endpoint for the view page


using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;

namespace XmlParserWpf
{
    public class FilesViewModel: ObservableCollection<FilesListItem>
    {
        public const int NoneSelection = -1;
        private int _selectedIndex = NoneSelection;

        public int SelectedIndex
        {
            get { return _selectedIndex; }
            set
            {
                if (_selectedIndex != value)
                {
                    _selectedIndex = value;
                    OnPropertyChanged(new PropertyChangedEventArgs("SelectedIndex"));
                    OnPropertyChanged(new PropertyChangedEventArgs("SelectedFile"));
                }
            }
        }

        public FilesListItem SelectedFile => (SelectedIndex != NoneSelection ? this[SelectedIndex] : null);

        public void AddAndSelect(FilesListItem item)
        {
            Add(item);
            SelectedIndex = IndexOf(item);
        }

        public bool HasFile(string path)
        {
            return this.Any(x => x.Path.Equals(path));
        }

        public void SelectIfExists(string path)
        {
            if (HasFile(path))
                SelectedIndex = IndexOf(this.First(x => x.Path.Equals(path)));
        }

        public void RemoveSelected()
        {
            if (SelectedIndex < 0)
                return;

            RemoveAt(SelectedIndex);

            if (Count == 0)
                SelectedIndex = NoneSelection;
        }
    }
}

using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;

namespace XmlParserWpf
{
    public class FilesViewModel: ObservableCollection<FilesListItem>
    {
        public const int NoneSelection = -1;
        private int _selectedIndex = NoneSelection;

        public int SelectedIndex
        {
            get { return _selectedIndex; }
            set
            {
                if (_selectedIndex != value)
                {
                    _selectedIndex = value;
                    OnPropertyChanged(new PropertyChangedEventArgs("SelectedIndex"));
                    OnPropertyChanged(new PropertyChangedEventArgs("SelectedFile"));
                }
            }
        }

        public FilesListItem SelectedFile => ((Count > 0) && (SelectedIndex != NoneSelection)) ? this[SelectedIndex] : null;

        public void AddAndSelect(FilesListItem item)
        {
            Add(item);
            SelectedIndex = IndexOf(item);
        }

        public bool HasFile(string path)
        {
            return this.Any(x => x.Path.Equals(path));
        }

        public void SelectIfExists(string path)
        {
            if (HasFile(path))
                SelectedIndex = IndexOf(this.First(x => x.Path.Equals(path)));
        }

        public void RemoveSelected()
        {
            if (SelectedIndex < 0)
                return;

            RemoveAt(SelectedIndex);

            if (Count == 0)
                SelectedIndex = NoneSelection;
        }
    }
}

Fix IndexOutOfBounds exception on application closing

* with empty files list when SelectedIndex = 0 SelectedFile = ?
* now SelectedFile = null


using MongoDB.Driver;
using MongoDB.Driver.Linq;
using Persistence.MongoDB;
using SO115App.Models.Servizi.Infrastruttura.GestioneTrasferimentiChiamate.CodiciChiamate;
using System.Collections.Generic;

namespace SO115App.Persistence.MongoDB.GestioneTrasferimentiChiamate.CodiciChiamate
{
    public class GetCodiciChiamate : IGetCodiciChiamate
    {
        private readonly DbContext _dbContext;
        public GetCodiciChiamate(DbContext dbContext) => _dbContext = dbContext;

        public List<string> Get(string CodSede)
        {
            return _dbContext.RichiestaAssistenzaCollection.AsQueryable()
                .Where(c => c.TestoStatoRichiesta == "C" && c.CodSOCompetente == CodSede)
                .Select(c => c.Codice)
                .ToList();
        }
    }
}

using MongoDB.Driver;
using MongoDB.Driver.Linq;
using Persistence.MongoDB;
using SO115App.API.Models.Classi.Organigramma;
using SO115App.API.Models.Classi.Soccorso;
using SO115App.Models.Servizi.Infrastruttura.GestioneTrasferimentiChiamate.CodiciChiamate;
using SO115App.Models.Servizi.Infrastruttura.SistemiEsterni.ServizioSede;
using System.Collections.Generic;
using System.Linq;

namespace SO115App.Persistence.MongoDB.GestioneTrasferimentiChiamate.CodiciChiamate
{
    public class GetCodiciChiamate : IGetCodiciChiamate
    {
        private readonly DbContext _dbContext;
        private readonly IGetAlberaturaUnitaOperative _getAlberaturaUnitaOperative;

        public GetCodiciChiamate(DbContext dbContext, IGetAlberaturaUnitaOperative getAlberaturaUnitaOperative)
        {
            _dbContext = dbContext;
            _getAlberaturaUnitaOperative = getAlberaturaUnitaOperative;
        }

        public List<string> Get(string CodSede)
        {
            var listaSediAlberate = _getAlberaturaUnitaOperative.ListaSediAlberata();

            var pinNodi = new List<PinNodo>();

            pinNodi.Add(new PinNodo(CodSede, true));

            foreach (var figlio in listaSediAlberate.GetSottoAlbero(pinNodi))
            {
                pinNodi.Add(new PinNodo(figlio.Codice, true));
            }

            var filtroSediCompetenti = Builders<RichiestaAssistenza>.Filter
                .In(richiesta => richiesta.CodSOCompetente, pinNodi.Select(uo => uo.Codice));

            var lista = _dbContext.RichiestaAssistenzaCollection.Find(filtroSediCompetenti).ToList();

            return lista.Where(c => c.TestoStatoRichiesta == "C")
                   .Select(c => c.Codice).ToList();
        }
    }
}

Fix gestione codici chiamata in Trasferimento Chiamata


// 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.ControlPoints;

namespace osu.Game.Beatmaps.Formats
{
    /// <summary>
    /// A <see cref="LegacyBeatmapDecoder"/> built for difficulty calculation of legacy <see cref="Beatmap"/>s
    /// <remarks>
    /// To use this, the decoder must be registered by the application through <see cref="LegacyDifficultyCalculatorBeatmapDecoder.Register"/>.
    /// Doing so will override any existing <see cref="Beatmap"/> decoders.
    /// </remarks>
    /// </summary>
    public class LegacyDifficultyCalculatorBeatmapDecoder : LegacyBeatmapDecoder
    {
        public LegacyDifficultyCalculatorBeatmapDecoder(int version = LATEST_VERSION)
            : base(version)
        {
            ApplyOffsets = false;
        }

        public new static void Register()
        {
            AddDecoder<Beatmap>(@"osu file format v", m => new LegacyDifficultyCalculatorBeatmapDecoder(int.Parse(m.Split('v').Last())));
        }

        protected override TimingControlPoint CreateTimingControlPoint()
            => new LegacyDifficultyCalculatorControlPoint();

        private class LegacyDifficultyCalculatorControlPoint : TimingControlPoint
        {
            public override double BeatLength { get; set; } = DEFAULT_BEAT_LENGTH;
        }
    }
}

// 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.ControlPoints;

namespace osu.Game.Beatmaps.Formats
{
    /// <summary>
    /// A <see cref="LegacyBeatmapDecoder"/> built for difficulty calculation of legacy <see cref="Beatmap"/>s
    /// <remarks>
    /// To use this, the decoder must be registered by the application through <see cref="LegacyDifficultyCalculatorBeatmapDecoder.Register"/>.
    /// Doing so will override any existing <see cref="Beatmap"/> decoders.
    /// </remarks>
    /// </summary>
    public class LegacyDifficultyCalculatorBeatmapDecoder : LegacyBeatmapDecoder
    {
        public LegacyDifficultyCalculatorBeatmapDecoder(int version = LATEST_VERSION)
            : base(version)
        {
            ApplyOffsets = false;
        }

        public new static void Register()
        {
            AddDecoder<Beatmap>(@"osu file format v", m => new LegacyDifficultyCalculatorBeatmapDecoder(int.Parse(m.Split('v').Last())));
            SetFallbackDecoder<Beatmap>(() => new LegacyDifficultyCalculatorBeatmapDecoder());
        }

        protected override TimingControlPoint CreateTimingControlPoint()
            => new LegacyDifficultyCalculatorControlPoint();

        private class LegacyDifficultyCalculatorControlPoint : TimingControlPoint
        {
            public override double BeatLength { get; set; } = DEFAULT_BEAT_LENGTH;
        }
    }
}

Add difficulty calculator beatmap decoder fallback


using System;
using HexWorld.Enums;

namespace HexWorld
{
    public class Tile
    {
        public TileTypes Type { get; set; }
        public bool IsWater { get; set; }
        public string Printable { get; set; }

        public Tile(TileTypes type)
        {
            ChangeTile(type);
        }

        public void ChangeTile(TileTypes type)
        {
            Type = type;
            switch (Type)
            {
                case TileTypes.Ocean:
                    IsWater = true;
//                    Printable = "▓▓▓";
                    Printable = "   ";
                    break;
                case TileTypes.Desert:
                    IsWater = false;
                    Printable = "░░░";
                    break;
                case TileTypes.Mountain:
                    IsWater = false;
                    Printable = "╔╬╗";
                    break;
                case TileTypes.Hill:
                    IsWater = false;
                    Printable = "▅▂▅";
                    break;
                case TileTypes.Grassland:
                    IsWater = false;
                    Printable = "▒▒▒";
                    break;
                case TileTypes.Steppe:
                    IsWater = false;
                    Printable = "░▒░";
                    break;
                case TileTypes.Tundra:
                    IsWater = false;
                    Printable = "***";
                    break;
                default:
                    throw new ArgumentException("Unknown Tile Type");
            }
        }

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

using System;
using HexWorld.Enums;

namespace HexWorld
{
    public class Tile
    {
        public TileTypes Type { get; set; }
        public bool IsWater { get; set; }
        public string Printable { get; set; }

        public Tile(TileTypes type)
        {
            ChangeTile(type);
        }

        public void ChangeTile(TileTypes type)
        {
            Type = type;
            switch (Type)
            {
                case TileTypes.Ocean:
                    IsWater = true;
//                    Printable = "▓▓▓";
                    Printable = "   ";
                    break;
                case TileTypes.Desert:
                    IsWater = false;
                    Printable = "░░░";
                    break;
                case TileTypes.Mountain:
                    IsWater = false;
                    Printable = "╔╬╗";
                    break;
                case TileTypes.Hill:
                    IsWater = false;
                    Printable = "▅▂▅";
                    break;
                case TileTypes.Grassland:
                    IsWater = false;
                    Printable = "▒▒▒";
                    break;
                case TileTypes.Steppe:
                    IsWater = false;
                    Printable = "░▒░";
                    break;
                case TileTypes.Tundra:
                    IsWater = false;
                    Printable = "***";
                    break;
                case TileTypes.Jungle:
                    IsWater = false;
                    Printable = "╫╫╫";
                    break;
                case TileTypes.Forest:
                    IsWater = false;
                    Printable = "┼┼┼";
                    break;
                case TileTypes.Swamp:
                    IsWater = false;
                    Printable = "▚▞▜";
                    break;
                default:
                    throw new ArgumentException("Unknown Tile Type");
            }
        }

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

Test data for last 3 tile types.

Test data for last 3 tile types.


namespace testproj
{
    using System;

    using JetBrains.dotMemoryUnit;

    using NUnit.Framework;

    [TestFixture]
    public class UnitTest1
    {
        [Test]
        public void TestMethod1()
        {
            dotMemory.Check(
                memory =>
                {
                    var str1 = "1";
                    var str2 = "2";
                    var str3 = "3";
                    Assert.LessOrEqual(2, memory.ObjectsCount);
                    Console.WriteLine(str1 + str2 + str3);
                });
        }
    }
}

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

    using JetBrains.dotMemoryUnit;

    using NUnit.Framework;

    [TestFixture]
    public class UnitTest1
    {
        [Test]
        public void TestMethod1()
        {
            var strs = new List<string>();
            var memoryCheckPoint = dotMemory.Check();
            strs.Add(GenStr());
            strs.Add(GenStr());
            strs.Add(GenStr());

            dotMemory.Check(
                memory =>
                {
                    var strCount = memory
                        .GetDifference(memoryCheckPoint)
                        .GetNewObjects()
                        .GetObjects(i => i.Type == typeof(string))
                        .ObjectsCount;

                    Assert.LessOrEqual(strCount, 2);
                });

            strs.Clear();
        }

        [Test]
        public void TestMethod2()
        {
            var strs = new List<string>();
            var memoryCheckPoint = dotMemory.Check();
            strs.Add(GenStr());
            strs.Add(GenStr());

            dotMemory.Check(
                memory =>
                {
                    var strCount = memory
                        .GetDifference(memoryCheckPoint)
                        .GetNewObjects()
                        .GetObjects(i => i.Type == typeof(string))
                        .ObjectsCount;

                    Assert.LessOrEqual(strCount, 2);
                });

            strs.Clear();
        }

        private static string GenStr()
        {
            return Guid.NewGuid().ToString();
        }
    }
}

Add broken test to testproj

Add broken test to testproj


using UnityEngine;
using UnityEngine.Networking;

public class PlayerState : NetworkBehaviour {

    [SyncVar]
    string fakingTheory;

    [SyncVar]
    int score;

    void Start()
    {
        fakingTheory = null;
        score = 0;
    }

    [Command]
    public void CmdSetFakingState(string newFakingTheory)
    {
        fakingTheory = newFakingTheory;
    }

    [Command]
    public void CmdAddScore(int value)
    {
        score += value;
    }

    public bool IsFaking()
    {
        return (fakingTheory != null);
    }

    void OnGUI()
    {
        if (!isLocalPlayer)
        {
            return;
        }
        GUI.BeginGroup(new Rect(Screen.width / 2 - 100, Screen.height - 100, 200, 200));
        GUILayout.Label("Score: " + score);
        if (IsFaking())
        {
            GUILayout.Label("Faking using " + fakingTheory);
        }
        GUI.EndGroup();
    }
}

using System;
using UnityEngine;
using UnityEngine.Networking;

public class PlayerState : NetworkBehaviour {

    [SyncVar]
    string fakingTheory;

    [SyncVar]
    int score;

    void Start()
    {
        fakingTheory = null;
        score = 0;
    }

    [Command]
    public void CmdSetFakingState(string newFakingTheory)
    {
        fakingTheory = newFakingTheory;
    }

    [Command]
    public void CmdAddScore(int value)
    {
        score += value;
    }

    public bool IsFaking()
    {
        return !String.IsNullOrEmpty(fakingTheory);
    }

    void OnGUI()
    {
        if (!isLocalPlayer)
        {
            return;
        }
        GUI.BeginGroup(new Rect(Screen.width / 2 - 100, Screen.height - 100, 200, 200));
        GUILayout.Label("Score: " + score);
        if (IsFaking())
        {
            GUILayout.Label("Faking using " + fakingTheory);
        }
        GUI.EndGroup();
    }
}

Fix the player score counter (IsFaking always returned true)


using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Windows.ApplicationModel.Background;
using Gitter.Services.Abstract;

namespace Gitter.Services.Concrete
{
    public class BackgroundTaskService : IBackgroundTaskService
    {
        public Dictionary<string, string> Tasks
        {
            get
            {
                return new Dictionary<string, string>
                {
                    {"NotificationsBackgroundTask", "Gitter.Tasks"}
                };
            }
        }

        public async Task RegisterTasksAsync()
        {
            foreach (var kvTask in Tasks)
            {
                if (BackgroundTaskRegistration.AllTasks.Any(task => task.Value.Name == kvTask.Key))
                    break;

                await RegisterTaskAsync(kvTask.Key, kvTask.Value);
            }
        }

        private async Task RegisterTaskAsync(string taskName, string taskNamespace)
        {
            var requestAccess = await BackgroundExecutionManager.RequestAccessAsync();

            if (requestAccess == BackgroundAccessStatus.AllowedWithAlwaysOnRealTimeConnectivity ||
                requestAccess == BackgroundAccessStatus.AllowedMayUseActiveRealTimeConnectivity)
            {
                var taskBuilder = new BackgroundTaskBuilder
                {
                    Name = taskName,
                    TaskEntryPoint = string.Format("{0}.{1}", taskNamespace, taskName)
                };

                // Set the condition trigger that feels right for you
                taskBuilder.SetTrigger(new TimeTrigger(15, false));

                taskBuilder.Register();
            }
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Windows.ApplicationModel.Background;
using Gitter.Services.Abstract;

namespace Gitter.Services.Concrete
{
    public class BackgroundTaskService : IBackgroundTaskService
    {
        public Dictionary<string, string> Tasks
        {
            get
            {
                return new Dictionary<string, string>
                {
                    {"NotificationsBackgroundTask", "Gitter.Tasks"}
                };
            }
        }

        public async Task RegisterTasksAsync()
        {
            foreach (var kvTask in Tasks)
            {
                if (BackgroundTaskRegistration.AllTasks.Any(task => task.Value.Name == kvTask.Key))
                    break;

                await RegisterTaskAsync(kvTask.Key, kvTask.Value);
            }
        }

        private async Task RegisterTaskAsync(string taskName, string taskNamespace)
        {
            var requestAccess = await BackgroundExecutionManager.RequestAccessAsync();

            if (requestAccess == BackgroundAccessStatus.AllowedWithAlwaysOnRealTimeConnectivity ||
                requestAccess == BackgroundAccessStatus.AllowedMayUseActiveRealTimeConnectivity)
            {
                var taskBuilder = new BackgroundTaskBuilder
                {
                    Name = taskName,
                    TaskEntryPoint = string.Format("{0}.{1}", taskNamespace, taskName)
                };

                // Set the condition trigger that feels right for you
                taskBuilder.SetTrigger(new TimeTrigger(15, false));

                taskBuilder.AddCondition(new SystemCondition(SystemConditionType.InternetAvailable));
                taskBuilder.AddCondition(new SystemCondition(SystemConditionType.UserNotPresent));

                taskBuilder.Register();
            }
        }
    }
}

Add conditions to background tasks

Add conditions to background tasks


using System;

namespace Mindscape.Raygun4Net
{
  public class RaygunSettings
  {
    private static RaygunSettings settings;
    private const string DefaultApiEndPoint = "https://api.raygun.io/entries";
    private const string DefaultPulseEndPoint = "https://api.raygun.io/events";

    public static RaygunSettings Settings
    {
      get
      {
        return settings ?? (settings = new RaygunSettings { ApiEndpoint = new Uri(DefaultApiEndPoint), PulseEndpoint = new Uri(DefaultPulseEndPoint) });
      }
    }

    public Uri ApiEndpoint { get; set; }

    public Uri PulseEndpoint{ get; set; }
  }
}

using System;

namespace Mindscape.Raygun4Net
{
  public class RaygunSettings
  {
    private static RaygunSettings settings;
    private const string DefaultApiEndPoint = "https://api.raygun.io/entries";
    private const string DefaultPulseEndPoint = "https://api.raygun.io/events";

    public static RaygunSettings Settings
    {
      get
      {
        return settings ?? (settings = new RaygunSettings { ApiEndpoint = new Uri(DefaultApiEndPoint), PulseEndpoint = new Uri(DefaultPulseEndPoint) });
      }
    }

    public Uri ApiEndpoint { get; set; }

    public Uri PulseEndpoint{ get; set; }

    public bool SetUnobservedTaskExceptionsAsObserved { get; set; }
  }
}

Add option to mark exceptions as observed


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

namespace MatterHackers.Agg.UI
{
    public class RootedObjectEventHandler
    {
        EventHandler InternalEvent;
        public void RegisterEvent(EventHandler functionToCallOnEvent, ref EventHandler functionThatWillBeCalledToUnregisterEvent)
        {
            InternalEvent += functionToCallOnEvent;
            functionThatWillBeCalledToUnregisterEvent += (sender, e) =>
            {
                InternalEvent -= functionToCallOnEvent;
            };
        }

        public void UnregisterEvent(EventHandler functionToCallOnEvent, ref EventHandler functionThatWillBeCalledToUnregisterEvent)
        {
            InternalEvent -= functionToCallOnEvent;
            // After we remove it it will still be removed again in the functionThatWillBeCalledToUnregisterEvent
            // But it is valid to attempt remove more than once.
        }

        public void CallEvents(Object sender, EventArgs e)
        {
            if (InternalEvent != null)
            {
                InternalEvent(this, e);
            }
        }
    }
}

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

namespace MatterHackers.Agg.UI
{
    public class RootedObjectEventHandler
    {
#if DEBUG
        private event EventHandler InternalEventForDebug;
        private List<EventHandler> DebugEventDelegates = new List<EventHandler>();

        private event EventHandler InternalEvent
        {
            //Wraps the PrivateClick event delegate so that we can track which events have been added and clear them if necessary
            add
            {
                InternalEventForDebug += value;
                DebugEventDelegates.Add(value);
            }

            remove
            {
                InternalEventForDebug -= value;
                DebugEventDelegates.Remove(value);
            }
        }
#else
        EventHandler InternalEvent;
#endif

        public void RegisterEvent(EventHandler functionToCallOnEvent, ref EventHandler functionThatWillBeCalledToUnregisterEvent)
        {
            InternalEvent += functionToCallOnEvent;
            functionThatWillBeCalledToUnregisterEvent += (sender, e) =>
            {
                InternalEvent -= functionToCallOnEvent;
            };
        }

        public void UnregisterEvent(EventHandler functionToCallOnEvent, ref EventHandler functionThatWillBeCalledToUnregisterEvent)
        {
            InternalEvent -= functionToCallOnEvent;
            // After we remove it it will still be removed again in the functionThatWillBeCalledToUnregisterEvent
            // But it is valid to attempt remove more than once.
        }

        public void CallEvents(Object sender, EventArgs e)
        {
#if DEBUG
            if (InternalEventForDebug != null)
            {
                InternalEventForDebug(this, e);
            }
#else
            if (InternalEvent != null)
            {
                InternalEvent(this, e);
            }
#endif
        }
    }
}

Put in some debugging code for looking at what functions have been added to the rooted event handler.


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

namespace GrienerTest
{

    public partial class PolygonClip
    {

#if false
        void insert(node *ins, node *first, node *last)
{
  node *aux=first;
  while(aux != last && aux->alpha < ins->alpha) aux = aux->next;
  ins->next = aux;
  ins->prev = aux->prev;
  ins->prev->next = ins;
  ins->next->prev = ins;
}
#endif
        void insert(Node ins,Node first,Node last)
        {
            Node aux = first;
            while (aux != last && aux.alpha < ins.alpha) aux = aux.next;
            ins.next = aux;
            ins.prev = aux.prev;
            ins.prev.next = ins;
            ins.next.prev = ins;
        }

    }
}

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

namespace GrienerTest
{

    public partial class PolygonClip
    {

#if false
        void insert(node *ins, node *first, node *last)
{
  node *aux=first;
  while(aux != last && aux->alpha < ins->alpha) aux = aux->next;
  ins->next = aux;
  ins->prev = aux->prev;
  ins->prev->next = ins;
  ins->next->prev = ins;
}
#endif
        void insert(Node ins,Node first,Node last)
        {
            Node aux = first;
            while (aux != last && aux.alpha < ins.alpha) aux = aux.next;
            ins.next = aux;
            ins.prev = aux.prev;
            /*
             * Feb 2017. Check against null pointer
             */
             if (ins.prev != null) {
                ins.prev.next = ins;
             }
             if (ins.next != null) {
                ins.next.prev = ins;
             }
        }

    }
}

Add in check for null pointers.

Add in check for null pointers.


@{
    ViewBag.Title = "Contact";
}

@ViewBag.Title.

@ViewBag.Message

<address>
    One Microsoft Way

    Redmond, WA 98052-6399

    P:
    425.555.0100
</address>

<address>
    Support:   Support@example.com

    Marketing: Marketing@example.com
    Pat: patrick.fulton@zirmed.com
    Dustin: dustin.crawford@zirmed.com
</address>

@{
    ViewBag.Title = "Contact";
}

@ViewBag.Title.

@ViewBag.Message

<address>
    One Microsoft Way

    Redmond, WA 98052-6399

    P:
    425.555.0100
</address>

<address>
    Support:   Support@example.com

    Marketing: Marketing@example.com
    Pat: patrick.fulton@zirmed.com
    Dustin: dustin.crawford@zirmed.com
    Nicolas: nick.wolf@zirmed.com
</address>

Add nick wolf contact info.

Add nick wolf contact info.


using System;
using Mono.TextEditor;
using ICSharpCode.NRefactory;

namespace JustEnoughVi
{
    public class ChangeInnerBlock : ChangeCommand
    {
        public ChangeInnerBlock(TextEditorData editor, char openingChar, char closingChar)
            : base(editor, TextObject.InnerBlock, openingChar, closingChar)
        {
        }

        protected override void Run()
        {
            CommandRange range = _selector();
            ChangeRange(range);
            if (range != CommandRange.Empty)
            {
                // Move caret inside if it is on on opening character and block is empty
                if (range.Length == 0 && Editor.Caret.Offset < range.Start)
                    Editor.Caret.Offset++;
                else
                {
                    // if block still has two newlines inside, then drop inside block and indent
                    int del1 = NewLine.GetDelimiterLength(Editor.Text[range.Start - 1], Editor.Text[range.Start]);
                    if (del1 > 0)
                    {
                        int del2Start = range.Start - 1 + del1;
                        int del2 = NewLine.GetDelimiterLength(Editor.Text[del2Start],
                                                              Editor.Text[del2Start + 1]);
                        if (del2 > 0)
                            IndentInsideBlock(range.Start);
                    }
                }
            }
        }

        private void IndentInsideBlock(int blockStart)
        {
            int end = blockStart;
            while (Char.IsWhiteSpace(Editor.Text[end]))
                end++;
            Editor.SetSelection(blockStart, end);
            Editor.DeleteSelectedText();
            MiscActions.InsertNewLine(Editor);
        }
    }
}

using System;
using Mono.TextEditor;
using ICSharpCode.NRefactory.Utils;
using ICSharpCode.NRefactory;

namespace JustEnoughVi
{
    public class ChangeInnerBlock : ChangeCommand
    {
        public ChangeInnerBlock(TextEditorData editor, char openingChar, char closingChar)
            : base(editor, TextObject.InnerBlock, openingChar, closingChar)
        {
        }

        protected override void Run()
        {
            CommandRange range = _selector();
            ChangeRange(range);
            if (range != CommandRange.Empty)
            {
                // Move caret inside if it is on on opening character and block is empty
                if (range.Length == 0 && Editor.Caret.Offset < range.Start)
                    Editor.Caret.Offset++;
                else
                {
                    // if block still has two newlines inside, then drop inside block and indent
                    int del1 = NewLine.GetDelimiterLength(Editor.Text[range.Start - 1], Editor.Text[range.Start]);
                    if (del1 > 0)
                    {
                        int del2Start = range.Start - 1 + del1;
                        int del2 = NewLine.GetDelimiterLength(Editor.Text[del2Start],
                                                              Editor.Text[del2Start + 1]);
                        if (del2 > 0)
                            IndentInsideBlock(range.Start - 2);
                    }
                }
            }
        }

        private void IndentInsideBlock(int openingChar)
        {
            string indentation = Editor.GetLineIndent(Editor.OffsetToLineNumber(openingChar));
            if (indentation != null && indentation.Length > 0)
                Editor.Insert(Editor.Caret.Offset, indentation);
            MiscActions.InsertTab(Editor);
        }
    }
}

Fix indentation when changing inside multiline block


using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("DynaShape")]
[assembly: AssemblyDescription("Open-source Dynamo plugin for constraint-based form finding, optimization and physics simulation")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DynaShape")]
[assembly: AssemblyCopyright("MIT License © 2017 Long Nguyen")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("157ad178-ee17-46e9-b6dc-c50eb9dcca60")]
[assembly: AssemblyVersion("0.3.1.2")]
[assembly: AssemblyFileVersion("0.3.1.2")]

using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("DynaShape")]
[assembly: AssemblyDescription("Open-source Dynamo plugin for constraint-based form finding, optimization and physics simulation")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DynaShape")]
[assembly: AssemblyCopyright("MIT License © 2017 Long Nguyen")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("157ad178-ee17-46e9-b6dc-c50eb9dcca60")]
[assembly: AssemblyVersion("0.3.2.0")]
[assembly: AssemblyFileVersion("0.3.2.0")]

Set AssemblyVersion number correctly to 0.3.2


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

namespace EvilDICOM.Core.IO.Writing
{
    public class DICOMBinaryWriter : IDisposable
    {
        private readonly BinaryWriter _writer;

        /// <summary>
        ///     Constructs a new writer from a file path.
        /// </summary>
        /// <param name="filePath">path to the file to be written</param>
        public DICOMBinaryWriter(string filePath)
        {
            _writer = new BinaryWriter(
                File.Open(filePath, FileMode.Create),
                Encoding.UTF8);
        }

        public DICOMBinaryWriter(Stream stream)
        {
            _writer = new BinaryWriter(stream, Encoding.UTF8);
        }

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

        public void Write(byte b)
        {
            _writer.Write(b);
        }

        public void Write(byte[] bytes)
        {
            _writer.Write(bytes);
        }

        public void Write(char[] chars)
        {
            _writer.Write(chars);
        }

        public void Write(string chars)
        {
            char[] asCharArray = chars.ToCharArray(0, chars.Length);
            Write(asCharArray);
        }

        public void WriteNullBytes(int numberToWrite)
        {
            for (int i = 0; i < numberToWrite; i++)
            {
                Write(0x00);
            }
        }
    }
}

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

namespace EvilDICOM.Core.IO.Writing
{
    public class DICOMBinaryWriter : IDisposable
    {
        private readonly BinaryWriter _writer;

        /// <summary>
        ///     Constructs a new writer from a file path.
        /// </summary>
        /// <param name="filePath">path to the file to be written</param>
        public DICOMBinaryWriter(string filePath)
        {
            _writer = new BinaryWriter(
                File.Open(filePath, FileMode.Create),
                Encoding.UTF8);
        }

        public DICOMBinaryWriter(Stream stream)
        {
            _writer = new BinaryWriter(stream, Encoding.UTF8);
        }

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

        public void Write(byte b)
        {
            _writer.Write(b);
        }

        public void Write(byte[] bytes)
        {
            _writer.Write(bytes);
        }

        public void Write(char[] chars)
        {
            _writer.Write(chars);
        }

        public void Write(string chars)
        {
            char[] asCharArray = chars.ToCharArray();
            Write(asCharArray);
        }

        public void WriteNullBytes(int numberToWrite)
        {
            for (int i = 0; i < numberToWrite; i++)
            {
                Write(0x00);
            }
        }
    }
}

Use portable ToCharArray overload yielding equivalent result


#tool "nuget:?package=GitVersion.CommandLine"
#addin "Cake.Yaml"

public class ContextInfo
{
    public string NugetVersion { get; set; }
    public string AssemblyVersion { get; set; }
    public GitVersion Git { get; set; }

    public string BuildVersion
    {
        get { return NugetVersion + "-" + Git.Sha; }
    }
}

ContextInfo _versionContext = null;
public ContextInfo VersionContext
{
    get
    {
        if(_versionContext == null)
            throw new Exception("The current context has not been read yet. Call ReadContext(FilePath) before accessing the property.");

        return _versionContext;
    }
}

public ContextInfo ReadContext(FilePath filepath)
{
    _versionContext = DeserializeYamlFromFile<ContextInfo>(filepath);
    _versionContext.Git = GitVersion();
    return _versionContext;
}

public void UpdateAppVeyorBuildVersionNumber()
{
    var increment = 0;
    while(increment < 10)
    {
        try
        {
            var version = VersionContext.BuildVersion;
            if(increment > 0)
                version += "-" + increment;

            AppVeyor.UpdateBuildVersion(version);
            break;
        }
        catch
        {
            increment++;
        }
    }
}

#tool "nuget:?package=GitVersion.CommandLine"
#addin "Cake.Yaml"

public class ContextInfo
{
    public string NugetVersion { get; set; }
    public string AssemblyVersion { get; set; }
    public GitVersion Git { get; set; }

    public string BuildVersion
    {
        get { return NugetVersion + "-" + Git.Sha; }
    }
}

ContextInfo _versionContext = null;
public ContextInfo VersionContext
{
    get
    {
        if(_versionContext == null)
            throw new Exception("The current context has not been read yet. Call ReadContext(FilePath) before accessing the property.");

        return _versionContext;
    }
}

public ContextInfo ReadContext(FilePath filepath)
{
    _versionContext = DeserializeYamlFromFile<ContextInfo>(filepath);
    try
    {
        _versionContext.Git = GitVersion();
    }
    catch
    {
        _versionContext.Git = new Cake.Common.Tools.GitVersion.GitVersion();
    }
    return _versionContext;
}

public void UpdateAppVeyorBuildVersionNumber()
{
    var increment = 0;
    while(increment < 10)
    {
        try
        {
            var version = VersionContext.BuildVersion;
            if(increment > 0)
                version += "-" + increment;

            AppVeyor.UpdateBuildVersion(version);
            break;
        }
        catch
        {
            increment++;
        }
    }
}

Allow to run build even if git repo informations are not available


using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Shapes;

class Program
{
    [STAThread]
    static void Main(string[] args)
    {
        var app = new Application();
        var window = new Window();
        window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
        window.WindowState = WindowState.Maximized;
        window.Title = "SystemColors";

        var content = new ListBox();

        foreach (var prop in typeof(SystemColors).GetProperties().Where(p => p.PropertyType == typeof(SolidColorBrush)))
        {
            var brush = prop.GetValue(null) as SolidColorBrush;
            var rect = new Rectangle() { Width = 100, Height = 20, Fill = brush };
            var panel = new StackPanel() { Orientation = Orientation.Horizontal };
            panel.Children.Add(new TextBlock() { Text = prop.Name, Width = 200 });
            panel.Children.Add(rect);
            panel.Children.Add(new TextBlock() { Text = brush.Color.ToString(), Margin = new Thickness(8, 0, 8, 0) });
            content.Items.Add(panel);
        }

        window.Content = content;

        app.Run(window);
    }
}

using System;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Shapes;

class Program
{
    [STAThread]
    static void Main(string[] args)
    {
        var app = new Application();
        var window = new Window();
        window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
        window.WindowState = WindowState.Maximized;
        window.Title = "SystemColors";

        var content = new ListBox();

        var sb = new StringBuilder();

        foreach (var prop in typeof(SystemColors).GetProperties().Where(p => p.PropertyType == typeof(SolidColorBrush)))
        {
            var brush = prop.GetValue(null) as SolidColorBrush;
            var rect = new Rectangle() { Width = 100, Height = 20, Fill = brush };
            var panel = new StackPanel() { Orientation = Orientation.Horizontal };
            panel.Children.Add(new TextBlock() { Text = prop.Name, Width = 200 });
            panel.Children.Add(rect);
            panel.Children.Add(new TextBlock() { Text = brush.Color.ToString(), Margin = new Thickness(8, 0, 8, 0) });
            content.Items.Add(panel);
        }

        foreach (var prop in typeof(Colors).GetProperties().Where(p => p.PropertyType == typeof(Color)))
        {
            var color = (Color)prop.GetValue(null);
            sb.AppendLine($"{color.R / 255.0}, {color.G / 255.0}, {color.B / 255.0},");
            //sb.AppendLine($"{color.ScR}, {color.ScG}, {color.ScB},");
        }

        // Clipboard.SetText(sb.ToString());

        window.Content = content;

        app.Run(window);
    }
}

Add some code to dump known colors

Add some code to dump known colors


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Antlr4.Runtime;
using Antlr4.Runtime.Misc;
using Antlr4.Runtime.Tree;

namespace Twee2Z.Analyzer
{
    public static class TweeAnalyzer
    {

        public static ObjectTree.Tree Parse(StreamReader input)
        {
            return Parse2(Lex(input));
        }

        public static ObjectTree.Tree Parse2(CommonTokenStream input)
        {

            System.Console.WriteLine("Parse twee file ...");
            Twee.StartContext startContext = new Twee(input).start();

            TweeVisitor visit = new TweeVisitor();
            visit.Visit(startContext);

            System.Console.WriteLine("Convert parse tree into object tree ...");
            return visit.Tree;
        }

        public static CommonTokenStream Lex(StreamReader input)
        {
            System.Console.WriteLine("Lex twee file ...");
            AntlrInputStream antlrStream = new AntlrInputStream(input.ReadToEnd());
            return new CommonTokenStream(new LEX(antlrStream));
        }
    }
}

Revert "Revert "auswertung von tags gebessert""

This reverts commit 59db5d111a7f8c11a188c031bc82bbfc114b70ce.


using System;
using System.Threading.Tasks;
using Eurofurence.App.Domain.Model.Abstractions;
using Eurofurence.App.Domain.Model.Sync;
using Eurofurence.App.Server.Services.Abstractions;

namespace Eurofurence.App.Server.Services.Storage
{
    public class StorageService<T> : IStorageService
    {
        private readonly IEntityStorageInfoRepository _entityStorageInfoRepository;
        private readonly string _entityType;

        public StorageService(IEntityStorageInfoRepository entityStorageInfoRepository, string entityType)
        {
            _entityStorageInfoRepository = entityStorageInfoRepository;
            _entityType = entityType;
        }

        public async Task TouchAsync()
        {
            var record = await GetEntityStorageRecordAsync();
            record.LastChangeDateTimeUtc = DateTime.UtcNow;
            await _entityStorageInfoRepository.ReplaceOneAsync(record);
        }

        public async Task ResetDeltaStartAsync()
        {
            var record = await GetEntityStorageRecordAsync();
            record.DeltaStartDateTimeUtc = DateTime.UtcNow;
            await _entityStorageInfoRepository.ReplaceOneAsync(record);
        }

        public Task<EntityStorageInfoRecord> GetStorageInfoAsync()
        {
            return GetEntityStorageRecordAsync();
        }

        private async Task<EntityStorageInfoRecord> GetEntityStorageRecordAsync()
        {
            var record = await _entityStorageInfoRepository.FindOneAsync(_entityType);

            if (record == null)
            {
                record = new EntityStorageInfoRecord {EntityType = _entityType};
                record.NewId();
                record.Touch();

                await _entityStorageInfoRepository.InsertOneAsync(record);
            }

            return record;
        }
    }
}

using System;
using System.Threading.Tasks;
using Eurofurence.App.Domain.Model.Abstractions;
using Eurofurence.App.Domain.Model.Sync;
using Eurofurence.App.Server.Services.Abstractions;

namespace Eurofurence.App.Server.Services.Storage
{
    public class StorageService<T> : IStorageService
    {
        private readonly IEntityStorageInfoRepository _entityStorageInfoRepository;
        private readonly string _entityType;

        public StorageService(IEntityStorageInfoRepository entityStorageInfoRepository, string entityType)
        {
            _entityStorageInfoRepository = entityStorageInfoRepository;
            _entityType = entityType;
        }

        public async Task TouchAsync()
        {
            var record = await GetEntityStorageRecordAsync();
            record.LastChangeDateTimeUtc = DateTime.UtcNow;
            await _entityStorageInfoRepository.ReplaceOneAsync(record);
        }

        public async Task ResetDeltaStartAsync()
        {
            var record = await GetEntityStorageRecordAsync();
            record.DeltaStartDateTimeUtc = DateTime.UtcNow;
            await _entityStorageInfoRepository.ReplaceOneAsync(record);
        }

        public Task<EntityStorageInfoRecord> GetStorageInfoAsync()
        {
            return GetEntityStorageRecordAsync();
        }

        private async Task<EntityStorageInfoRecord> GetEntityStorageRecordAsync()
        {
            var record = await _entityStorageInfoRepository.FindOneAsync(_entityType);

            if (record == null)
            {
                record = new EntityStorageInfoRecord
                {
                    EntityType = _entityType,
                    DeltaStartDateTimeUtc = DateTime.UtcNow
                };

                record.NewId();
                record.Touch();

                await _entityStorageInfoRepository.InsertOneAsync(record);
            }

            return record;
        }
    }
}

Fix to ensure Delta start time is reset when storage is re-created


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

namespace Vending.Core
{
    public class VendingMachine
    {
        private readonly List<Coin> _coins = new List<Coin>();
        private readonly List<Coin> _returnTray = new List<Coin>();
        private readonly List<string> _output = new List<string>();

        public IEnumerable<Coin> ReturnTray => _returnTray;
        public IEnumerable<string> Output => _output;

        public void Dispense(string sku)
        {
            _output.Add(sku);
        }

        public void Accept(Coin coin)
        {
            if (coin.Value() == 0)
            {
                _returnTray.Add(coin);
                return;
            }

            _coins.Add(coin);
        }

        public string GetDisplayText()
        {
            if (!_coins.Any())
            {
                return "INSERT COIN";
            }

            return $"{CurrentTotal():C}";
        }

        private decimal CurrentTotal()
        {
            var counts = new Dictionary<Coin, int>()
            {
                {Coin.Nickel, 0},
                {Coin.Dime, 0},
                {Coin.Quarter, 0}
            };

            foreach (var coin in _coins)
            {
                counts[coin]++;
            }

            decimal total = 0;
            foreach (var coinCount in counts)
            {
                total += (coinCount.Value * coinCount.Key.Value());
            }

            return ConvertCentsToDollars(total);
        }

        private static decimal ConvertCentsToDollars(decimal total)
        {
            return total / 100;
        }
    }
}

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

namespace Vending.Core
{
    public class VendingMachine
    {
        private readonly List<Coin> _coins = new List<Coin>();
        private readonly List<Coin> _returnTray = new List<Coin>();

        public IEnumerable<Coin> ReturnTray => _returnTray;

        public void Dispense(string soda)
        {
        }

        public void Accept(Coin coin)
        {
            if (coin.Value() == 0)
            {
                _returnTray.Add(coin);
                return;
            }

            _coins.Add(coin);
        }

        public string GetDisplayText()
        {
            if (!_coins.Any())
            {
                return "INSERT COIN";
            }

            return $"{CurrentTotal():C}";
        }

        private decimal CurrentTotal()
        {
            var counts = new Dictionary<Coin, int>()
            {
                {Coin.Nickel, 0},
                {Coin.Dime, 0},
                {Coin.Quarter, 0}
            };

            foreach (var coin in _coins)
            {
                counts[coin]++;
            }

            decimal total = 0;
            foreach (var coinCount in counts)
            {
                total += (coinCount.Value * coinCount.Key.Value());
            }

            return ConvertCentsToDollars(total);
        }

        private static decimal ConvertCentsToDollars(decimal total)
        {
            return total / 100;
        }
    }
}

Revert "Added place to output products"

Revert "Added place to output products"

This reverts commit a4d3db1b46a642857651273f1d717b12d91f182b.


using System;
using System.Globalization;
using System.Windows.Data;
using System.Windows.Media;

namespace MaterialDesignDemo.Converters
{
    public class BrushToHexConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null) return null;
            string lowerHexString(int i) => i.ToString("X").ToLower();
            var brush = (SolidColorBrush)value;
            var hex = lowerHexString(brush.Color.R) +
                      lowerHexString(brush.Color.G) +
                      lowerHexString(brush.Color.B);
            return "#" + hex;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}

using System;
using System.Globalization;
using System.Windows.Data;
using System.Windows.Media;

namespace MaterialDesignDemo.Converters
{
    public class BrushToHexConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null) return null;
            string lowerHexString(int i) => i.ToString("X2").ToLower();
            var brush = (SolidColorBrush)value;
            var hex = lowerHexString(brush.Color.R) +
                      lowerHexString(brush.Color.G) +
                      lowerHexString(brush.Color.B);
            return "#" + hex;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}

Fix display of color code

Fix display of color code

Fixes #1546


using System;

namespace RockLib.Messaging
{
    /// <summary>
    /// Defines an interface for receiving messages. To start receiving messages,
    /// set the value of the <see cref="MessageHandler"/> property.
    /// </summary>
    public interface IReceiver : IDisposable
    {
        /// <summary>
        /// Gets the name of this instance of <see cref="IReceiver"/>.
        /// </summary>
        string Name { get; }

        /// <summary>
        /// Gets or sets the message handler for this receiver. When set, the receiver is started
        /// and will invoke the value's <see cref="IMessageHandler.OnMessageReceived"/> method
        /// when messages are received.
        /// </summary>
        IMessageHandler MessageHandler { get; set; }

        /// <summary>
        /// Occurs when a connection is established.
        /// </summary>
        event EventHandler Connected;

        /// <summary>
        /// Occurs when a connection is lost.
        /// </summary>
        event EventHandler<DisconnectedEventArgs> Disconnected;
    }
}

using System;

namespace RockLib.Messaging
{
    /// <summary>
    /// Defines an interface for receiving messages. To start receiving messages,
    /// set the value of the <see cref="MessageHandler"/> property.
    /// </summary>
    public interface IReceiver : IDisposable
    {
        /// <summary>
        /// Gets the name of this instance of <see cref="IReceiver"/>.
        /// </summary>
        string Name { get; }

        /// <summary>
        /// Gets or sets the message handler for this receiver. When set, the receiver is started
        /// and will invoke the value's <see cref="IMessageHandler.OnMessageReceived"/> method
        /// when messages are received.
        /// </summary>
        /// <remarks>
        /// Implementions of this interface should not allow this property to be set to null or
        /// to be set more than once.
        /// </remarks>
        IMessageHandler MessageHandler { get; set; }

        /// <summary>
        /// Occurs when a connection is established.
        /// </summary>
        event EventHandler Connected;

        /// <summary>
        /// Occurs when a connection is lost.
        /// </summary>
        event EventHandler<DisconnectedEventArgs> Disconnected;
    }
}

Add remark to doc comment

Add remark to doc comment


using Citysim.Map;

namespace Citysim
{
    public class City
    {
        /// <summary>
        /// Amount of cash available.
        /// </summary>
        public int cash = 10000; // $10,000 starting cash

        /// <summary>
        /// The world. Needs generation.
        /// </summary>
        public World world = new World();
    }
}

using Citysim.Map;

namespace Citysim
{
    public class City
    {
        /// <summary>
        /// Amount of cash available.
        /// </summary>
        public int cash = 10000; // $10,000 starting cash

        /// <summary>
        /// MW (mega watts) of electricity available to the city.
        /// </summary>
        public int power = 0;

        /// <summary>
        /// ML (mega litres) of water available to the city.
        /// </summary>
        public int water = 0;

        /// <summary>
        /// The world. Needs generation.
        /// </summary>
        public World world = new World();
    }
}

Add city power and water variables.

Add city power and water variables.


// Copyright 2018 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE

using System;
using System.Linq;
using System.Reflection;

namespace Nuke.Common.Utilities
{
    public static class AssemblyExtensions
    {
        public static string GetInformationalText(this Assembly assembly)
        {
            return $"version {assembly.GetVersionText()} ({EnvironmentInfo.Platform}, {EnvironmentInfo.Framework})";
        }

        public static string GetVersionText(this Assembly assembly)
        {
            var informationalVersion = assembly.GetAssemblyInformationalVersion();
            var plusIndex = informationalVersion.IndexOf(value: '+');
            return plusIndex == -1 ? "LOCAL" : informationalVersion.Substring(startIndex: 0, length: plusIndex);
        }

        private static string GetAssemblyInformationalVersion(this Assembly assembly)
        {
            return assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion;
        }
    }
}

// Copyright 2018 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE

using System;
using System.Linq;
using System.Reflection;

namespace Nuke.Common.Utilities
{
    public static class AssemblyExtensions
    {
        public static string GetInformationalText(this Assembly assembly)
        {
            return $"version {assembly.GetVersionText()} ({EnvironmentInfo.Platform},{EnvironmentInfo.Framework})";
        }

        public static string GetVersionText(this Assembly assembly)
        {
            var informationalVersion = assembly.GetAssemblyInformationalVersion();
            var plusIndex = informationalVersion.IndexOf(value: '+');
            return plusIndex == -1 ? "LOCAL" : informationalVersion.Substring(startIndex: 0, length: plusIndex);
        }

        private static string GetAssemblyInformationalVersion(this Assembly assembly)
        {
            return assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion;
        }
    }
}

Remove whitespace in informational text

Remove whitespace in informational text


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

namespace Company.WebApplication1
{
    public class AzureAdB2COptions
    {
        public string ClientId { get; set; }
        public string AzureAdB2CInstance { get; set; }
        public string Tenant { get; set; }
        public string SignUpSignInPolicyId { get; set; }
        public string DefaultPolicy => SignUpSignInPolicyId;
        public string Authority => $"{AzureAdB2CInstance}/{Tenant}/{DefaultPolicy}/v2.0";
        public string Audience => ClientId;
    }
}

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

namespace Company.WebApplication1
{
    public class AzureAdB2COptions
    {
        public string ClientId { get; set; }
        public string AzureAdB2CInstance { get; set; }
        public string Domain { get; set; }
        public string SignUpSignInPolicyId { get; set; }
        public string DefaultPolicy => SignUpSignInPolicyId;
        public string Authority => $"{AzureAdB2CInstance}/{Domain}/{DefaultPolicy}/v2.0";
        public string Audience => ClientId;
    }
}

Rename Tenant to Domain in the web api template


// 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.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.LanguageServer.Protocol;
using Microsoft.VisualStudio.LanguageServices.LiveShare.CustomProtocol;
using Xunit;

namespace Microsoft.VisualStudio.LanguageServices.LiveShare.UnitTests
{
    public class ClassificationsHandlerTests : AbstractLiveShareRequestHandlerTests
    {
        [Fact]
        public async Task TestClassificationsAsync()
        {
            var markup =
@"class A
{
    void M()
    {
        {|classify:var|} i = 1;
    }
}";
            var (solution, ranges) = CreateTestSolution(markup);
            var classifyLocation = ranges["classify"].First();

            var results = await TestHandleAsync<ClassificationParams, ClassificationSpan[]>(solution, CreateClassificationParams(classifyLocation));
            AssertCollectionsEqual(new ClassificationSpan[] { CreateClassificationSpan("keyword", classifyLocation.Range) }, results, AssertClassificationsEqual);
        }

        private static void AssertClassificationsEqual(ClassificationSpan expected, ClassificationSpan actual)
        {
            Assert.Equal(expected.Classification, actual.Classification);
            Assert.Equal(expected.Range, actual.Range);
        }

        private static ClassificationSpan CreateClassificationSpan(string classification, Range range)
            => new ClassificationSpan()
            {
                Classification = classification,
                Range = range
            };

        private static ClassificationParams CreateClassificationParams(Location location)
            => new ClassificationParams()
            {
                Range = location.Range,
                TextDocument = CreateTextDocumentIdentifier(location.Uri)
            };
    }
}

// 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.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.LanguageServer.Protocol;
using Microsoft.VisualStudio.LanguageServices.LiveShare.CustomProtocol;
using Xunit;

namespace Microsoft.VisualStudio.LanguageServices.LiveShare.UnitTests
{
    public class ClassificationsHandlerTests : AbstractLiveShareRequestHandlerTests
    {
        [Fact]
        public async Task TestClassificationsAsync()
        {
            var markup =
@"class A
{
    void M()
    {
        {|classify:var|} i = 1;
    }
}";
            var (solution, ranges) = CreateTestSolution(markup);
            var classifyLocation = ranges["classify"].First();

            var results = await TestHandleAsync<ClassificationParams, object[]>(solution, CreateClassificationParams(classifyLocation));
            AssertCollectionsEqual(new ClassificationSpan[] { CreateClassificationSpan("keyword", classifyLocation.Range) }, results, AssertClassificationsEqual);
        }

        private static void AssertClassificationsEqual(ClassificationSpan expected, ClassificationSpan actual)
        {
            Assert.Equal(expected.Classification, actual.Classification);
            Assert.Equal(expected.Range, actual.Range);
        }

        private static ClassificationSpan CreateClassificationSpan(string classification, Range range)
            => new ClassificationSpan()
            {
                Classification = classification,
                Range = range
            };

        private static ClassificationParams CreateClassificationParams(Location location)
            => new ClassificationParams()
            {
                Range = location.Range,
                TextDocument = CreateTextDocumentIdentifier(location.Uri)
            };
    }
}

Fix classification test to use object type.


namespace Mappy
{
    using System;
    using System.Windows.Forms;
    using UI.Forms;

    public static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        public static void Main()
        {
            Application.ThreadException += Program.OnGuiUnhandedException;
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainForm());
        }

        private static void HandleUnhandledException(object o)
        {
            Exception e = o as Exception;
            if (e != null)
            {
                throw e;
            }
        }

        private static void OnGuiUnhandedException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            HandleUnhandledException(e.Exception);
        }
    }
}

namespace Mappy
{
    using System;
    using System.IO;
    using System.Windows.Forms;
    using UI.Forms;

    public static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        public static void Main()
        {
            RemoveOldVersionSettings();

            Application.ThreadException += Program.OnGuiUnhandedException;
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainForm());
        }

        private static void HandleUnhandledException(object o)
        {
            Exception e = o as Exception;
            if (e != null)
            {
                throw e;
            }
        }

        private static void OnGuiUnhandedException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            HandleUnhandledException(e.Exception);
        }

        private static void RemoveOldVersionSettings()
        {
            string appDir = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
            string oldDir = Path.Combine(appDir, @"Armoured_Fish");

            try
            {
                if (Directory.Exists(oldDir))
                {
                    Directory.Delete(oldDir, true);
                }
            }
            catch (IOException)
            {
                // we don't care if this fails
            }
        }
    }
}

Add code to remove all old settings

Add code to remove all old settings


using System.Collections.Generic;
using DotNetCore.CAP.Models;

namespace DotNetCore.CAP
{
    public abstract class CapTransactionBase : ICapTransaction
    {
        private readonly IDispatcher _dispatcher;

        private readonly IList<CapPublishedMessage> _bufferList;

        protected CapTransactionBase(IDispatcher dispatcher)
        {
            _dispatcher = dispatcher;
            _bufferList = new List<CapPublishedMessage>(1);
        }

        public bool AutoCommit { get; set; }

        public object DbTransaction { get; set; }

        protected internal virtual void AddToSent(CapPublishedMessage msg)
        {
            _bufferList.Add(msg);
        }

        protected void Flush()
        {
            foreach (var message in _bufferList)
            {
                _dispatcher.EnqueueToPublish(message);
            }
        }

        public abstract void Commit();

        public abstract void Rollback();

        public abstract void Dispose();
    }
}

using System.Collections.Generic;
using DotNetCore.CAP.Models;

namespace DotNetCore.CAP
{
    public abstract class CapTransactionBase : ICapTransaction
    {
        private readonly IDispatcher _dispatcher;

        private readonly IList<CapPublishedMessage> _bufferList;

        protected CapTransactionBase(IDispatcher dispatcher)
        {
            _dispatcher = dispatcher;
            _bufferList = new List<CapPublishedMessage>(1);
        }

        public bool AutoCommit { get; set; }

        public object DbTransaction { get; set; }

        protected internal virtual void AddToSent(CapPublishedMessage msg)
        {
            _bufferList.Add(msg);
        }

        protected virtual void Flush()
        {
            foreach (var message in _bufferList)
            {
                _dispatcher.EnqueueToPublish(message);
            }

            _bufferList.Clear();
        }

        public abstract void Commit();

        public abstract void Rollback();

        public abstract void Dispose();
    }
}

Fix flush unclaer data bugs.

Fix  flush unclaer data bugs.


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

using NUnit.Framework;

namespace osu.Framework.Tests.Audio
{
    [TestFixture]
    public class DevicelessAudioTest : AudioThreadTest
    {
        public override void SetUp()
        {
            base.SetUp();

            // lose all devices
            Manager.SimulateDeviceLoss();
        }

        [Test]
        public void TestPlayTrackWithoutDevices()
        {
            var track = Manager.Tracks.Get("Tracks.sample-track.mp3");

            // start track
            track.Restart();
            Assert.IsTrue(track.IsRunning);

            CheckTrackIsProgressing(track);

            // stop track
            track.Stop();

            WaitForOrAssert(() => !track.IsRunning, "Track did not stop", 1000);

            Assert.IsFalse(track.IsRunning);

            // seek track
            track.Seek(0);

            Assert.IsFalse(track.IsRunning);
            Assert.AreEqual(track.CurrentTime, 0);
        }
    }
}

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

using NUnit.Framework;

namespace osu.Framework.Tests.Audio
{
    [TestFixture]
    public class DevicelessAudioTest : AudioThreadTest
    {
        public override void SetUp()
        {
            base.SetUp();

            // lose all devices
            Manager.SimulateDeviceLoss();
        }

        [Test]
        public void TestPlayTrackWithoutDevices()
        {
            var track = Manager.Tracks.Get("Tracks.sample-track.mp3");

            // start track
            track.Restart();
            Assert.IsTrue(track.IsRunning);

            CheckTrackIsProgressing(track);

            // stop track
            track.Stop();

            WaitForOrAssert(() => !track.IsRunning, "Track did not stop", 1000);

            Assert.IsFalse(track.IsRunning);

            // seek track
            track.Seek(0);

            Assert.IsFalse(track.IsRunning);
            WaitForOrAssert(() => track.CurrentTime == 0, "Track did not seek correctly", 1000);
        }
    }
}

Fix one remaining case of incorrect audio testing


Welcome!

We are Sweet Water Revolver. This is our website. Please look around and check out our...

... showtimes.

Make the jumbotron inside a container.

Make the jumbotron inside a container.


using UnityEngine;
using System.Collections;

public class test : Skill
{
    private float duration = 10f;
    private float expiration;
    bool active;
    Player player;

    private int bonusStrength;
    protected override void Start()
    {
        base.Start();

        base.SetBaseValues(15, 16000, 150, "Ignite", SkillLevel.Level1);
        player = GetComponent<Player>();

    }
    protected override void Update()
    {
        base.Update();
        if(active && Time.time >= expiration)
        {
            active = false;
            player.transform.GetChild(0).GetComponent<DealDamage>().isMagic = false;
            player.SetStrength(player.GetStrength() - bonusStrength);

        }

    }

    public override void UseSkill(GameObject caller, GameObject target = null, object optionalParameters = null)
    {
        base.UseSkill(gameObject);
        expiration = Time.time + duration;
        active = true;
        player.transform.GetChild(0).GetComponent<DealDamage>().isMagic = true;
        bonusStrength = player.GetIntelligence() / 2;
        player.SetStrength(player.GetStrength() + bonusStrength);

    }
}

public class skilltesting : MonoBehaviour {

    float castInterval;

    private Skill testSkill;

	// Use this for initialization
	void Start () {
        gameObject.AddComponent<Fireball>();
        testSkill = GetComponent<Skill>();
	}

	// Update is called once per frame
	void Update () {
	    if(testSkill.GetCoolDownTimer() <= 0)
        {
            testSkill.UseSkill(gameObject);

        }
	}
}

using UnityEngine;
using System.Collections;

public class test : Skill
{
    private float duration = 10f;
    private float expiration;
    bool active;
    Player player;

    private int bonusStrength;
    protected override void Start()
    {
        base.Start();

        base.SetBaseValues(15, 16000, 150, "Ignite", SkillLevel.Level1);
        player = GetComponent<Player>();

    }
    protected override void Update()
    {
        base.Update();
        if(active && Time.time >= expiration)
        {
            active = false;
            player.transform.GetChild(0).GetComponent<DealDamage>().isMagic = false;
            player.SetStrength(player.GetStrength() - bonusStrength);

        }

    }

    public override void UseSkill(GameObject caller, GameObject target = null, object optionalParameters = null)
    {
        base.UseSkill(gameObject);
        expiration = Time.time + duration;
        active = true;
        player.transform.GetChild(0).GetComponent<DealDamage>().isMagic = true;
        bonusStrength = player.GetIntelligence() / 2;
        player.SetStrength(player.GetStrength() + bonusStrength);

    }
}

public class skilltesting : MonoBehaviour {

    float castInterval;

    private Skill testSkill;

	// Use this for initialization
	void Start () {
        gameObject.AddComponent<FireballSkill>();
        testSkill = GetComponent<Skill>();
	}

	// Update is called once per frame
	void Update () {
	    if(testSkill.GetCoolDownTimer() <= 0)
        {
            testSkill.UseSkill(gameObject);

        }
	}
}

Fix Error With Skill Test

Fix Error With Skill Test


using Xunit;

namespace Pioneer.Pagination.Tests
{
    /// <summary>
    /// Clamp Tests
    /// </summary>
    public class ClampTests
    {
        private readonly PaginatedMetaService _sut = new PaginatedMetaService();

        [Fact]
        public void LastPageDisplayed()
        {
            var result = _sut.GetMetaData(10, 11, 1);
            Assert.True(result.NextPage.PageNumber == 10, "Expected: Last Page ");
        }

        [Fact]
        public void FirstPageDisplayed()
        {
            var result = _sut.GetMetaData(10, 0, 1);
            Assert.True(result.NextPage.PageNumber == 1, "Expected: First Page ");
        }
    }
}

using Xunit;

namespace Pioneer.Pagination.Tests
{
    /// <summary>
    /// Clamp Tests
    /// </summary>
    public class ClampTests
    {
        private readonly PaginatedMetaService _sut = new PaginatedMetaService();

        [Fact]
        public void NextPageIsLastPageInCollectionWhenRequestedPageIsGreatedThenCollection()
        {
            var result = _sut.GetMetaData(10, 11, 1);
            Assert.True(result.NextPage.PageNumber == 10, "Expected: Last Page ");
        }

        [Fact]
        public void PreviousPageIsLastPageMinusOneInCollectionWhenRequestedPageIsGreatedThenCollection()
        {
            var result = _sut.GetMetaData(10, 11, 1);
            Assert.True(result.PreviousPage.PageNumber == 9, "Expected: Last Page ");
        }

        [Fact]
        public void PreviousPageIsFirstPageInCollectionWhenRequestedPageIsZero()
        {
            var result = _sut.GetMetaData(10, 0, 1);
            Assert.True(result.PreviousPage.PageNumber == 1, "Expected: First Page ");
        }

        [Fact]
        public void NextPageIsSecondPageInCollectionWhenRequestedPageIsZero()
        {
            var result = _sut.GetMetaData(10, 0, 1);
            Assert.True(result.NextPage.PageNumber == 2, "Expected: First Page ");
        }

        [Fact]
        public void PreviousPageIsFirstPageInCollectionWhenRequestedPageIsNegative()
        {
            var result = _sut.GetMetaData(10, -1, 1);
            Assert.True(result.PreviousPage.PageNumber == 1, "Expected: First Page ");
        }

        [Fact]
        public void NextPageIsSecondPageInCollectionWhenRequestedPageIsNegative()
        {
            var result = _sut.GetMetaData(10, -1, 1);
            Assert.True(result.NextPage.PageNumber == 2, "Expected: First Page ");
        }
    }
}

Add edge case unit tests

Add edge case unit tests


using TruckRouter.Models;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddTransient<IMazeSolver, MazeSolverBFS>();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
    app.UseDeveloperExceptionPage();
}

app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();

app.Run();

using TruckRouter.Models;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddTransient<IMazeSolver, MazeSolverBFS>();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
    app.UseDeveloperExceptionPage();
}
else
{
    app.UseHttpsRedirection();
    app.UseAuthorization();
}

app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();

app.Run();

Enable https redirection and authorization for non-dev envs only


namespace TraktApiSharp.Tests.Experimental.Requests.Users.OAuth
{
    using FluentAssertions;
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using TraktApiSharp.Experimental.Requests.Base.Put;
    using TraktApiSharp.Experimental.Requests.Users.OAuth;
    using TraktApiSharp.Objects.Get.Users.Lists;
    using TraktApiSharp.Objects.Post.Users;

    [TestClass]
    public class TraktUserCustomListUpdateRequestTests
    {
        [TestMethod, TestCategory("Requests"), TestCategory("Users")]
        public void TestTraktUserCustomListUpdateRequestIsNotAbstract()
        {
            typeof(TraktUserCustomListUpdateRequest).IsAbstract.Should().BeFalse();
        }

        [TestMethod, TestCategory("Requests"), TestCategory("Users")]
        public void TestTraktUserCustomListUpdateRequestIsSealed()
        {
            typeof(TraktUserCustomListUpdateRequest).IsSealed.Should().BeTrue();
        }

        [TestMethod, TestCategory("Requests"), TestCategory("Users")]
        public void TestTraktUserCustomListUpdateRequestIsSubclassOfATraktSingleItemPutByIdRequest()
        {
            typeof(TraktUserCustomListUpdateRequest).IsSubclassOf(typeof(ATraktSingleItemPutByIdRequest<TraktList, TraktUserCustomListPost>)).Should().BeTrue();
        }
    }
}

namespace TraktApiSharp.Tests.Experimental.Requests.Users.OAuth
{
    using FluentAssertions;
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using TraktApiSharp.Experimental.Requests.Base.Put;
    using TraktApiSharp.Experimental.Requests.Users.OAuth;
    using TraktApiSharp.Objects.Get.Users.Lists;
    using TraktApiSharp.Objects.Post.Users;
    using TraktApiSharp.Requests;

    [TestClass]
    public class TraktUserCustomListUpdateRequestTests
    {
        [TestMethod, TestCategory("Requests"), TestCategory("Users")]
        public void TestTraktUserCustomListUpdateRequestIsNotAbstract()
        {
            typeof(TraktUserCustomListUpdateRequest).IsAbstract.Should().BeFalse();
        }

        [TestMethod, TestCategory("Requests"), TestCategory("Users")]
        public void TestTraktUserCustomListUpdateRequestIsSealed()
        {
            typeof(TraktUserCustomListUpdateRequest).IsSealed.Should().BeTrue();
        }

        [TestMethod, TestCategory("Requests"), TestCategory("Users")]
        public void TestTraktUserCustomListUpdateRequestIsSubclassOfATraktSingleItemPutByIdRequest()
        {
            typeof(TraktUserCustomListUpdateRequest).IsSubclassOf(typeof(ATraktSingleItemPutByIdRequest<TraktList, TraktUserCustomListPost>)).Should().BeTrue();
        }

        [TestMethod, TestCategory("Requests"), TestCategory("Users")]
        public void TestTraktUserCustomListUpdateRequestHasAuthorizationRequired()
        {
            var request = new TraktUserCustomListUpdateRequest(null);
            request.AuthorizationRequirement.Should().Be(TraktAuthorizationRequirement.Required);
        }
    }
}

Add test for authorization requirement in TraktUserCustomListUpdateRequest


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

namespace Umbraco.Inception.Attributes
{
    [AttributeUsage(AttributeTargets.Property)]
    public class UmbracoTabAttribute : Attribute
    {
        public string Name { get; set; }
        public int SortOrder { get; set; }

        public UmbracoTabAttribute(string name, int sortOrder = 0)
        {
            Name = name;
            SortOrder = sortOrder;
        }
    }
}

using System;

namespace Umbraco.Inception.Attributes
{
    [AttributeUsage(AttributeTargets.Property)]
    public class UmbracoTabAttribute : Attribute
    {
        public string Name { get; set; }
        public int SortOrder { get; set; }

        public UmbracoTabAttribute(string name)
        {
            Name = name;
            SortOrder = 0;
        }
        public UmbracoTabAttribute(string name, int sortOrder = 0)
        {
            Name = name;
            SortOrder = sortOrder;
        }
    }
}

Add original constructor signature as there is Inception code which looks for it


using System.Linq;

namespace HundredDoors
{
	public static class HundredDoors
	{
		/// <summary>
		/// Solves the 100 Doors problem
		/// </summary>
		/// <returns>An array with 101 values, each representing a door (except 0). True = open</returns>
		public static bool[] Solve()
		{
			// Create our array with 101 values, all of them false. We'll only use 1~100 to simplify it
			bool[] doors = Enumerable.Repeat(false, 101).ToArray();

			// We'll pass 100 times, each pass we'll start at door #pass and increment by pass, toggling the current door
			for (int pass = 1; pass <= 100; pass++)
				for (int i = pass; i < doors.Length; i += pass)
					doors[i] = !doors[i];

			return doors;
		}
	}
}

using System.Linq;

namespace HundredDoors
{
	public static class HundredDoors
	{
		/// <summary>
		/// Solves the 100 Doors problem
		/// </summary>
		/// <returns>An array with 101 values, each representing a door (except 0). True = open</returns>
		public static bool[] Solve()
		{
			// Create our array with 101 values, all of them false. We'll only use 1~100 to simplify it
			bool[] doors = Enumerable.Repeat(false, 101).ToArray();

			// We'll pass 100 times, each pass we'll start at door #pass and increment by pass, toggling the current door
			for (int pass = 1; pass <= 100; pass++)
				for (int i = pass; i < doors.Length; i += pass)
					doors[i] = !doors[i];

			return doors; //final door count
		}
	}
}

Revert "Revert "Added "final door count" comment at return value.""

This reverts commit 4ed080e822168a87a0140fb8f0f28132bc0b6d96.


using Cake.Core;
using Cake.Core.Annotations;
using System;

namespace Cake.Docker
{
    partial class DockerAliases
    {
        /// <summary>
        /// Logs <paramref name="container"/> using default settings.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="container">The list of containers.</param>
        [CakeMethodAlias]
        public static void DockerLogs(this ICakeContext context, string container)
        {
            DockerLogs(context, new DockerContainerLogsSettings(), container);
        }

        /// <summary>
        /// Logs <paramref name="container"/> using the given <paramref name="settings"/>.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="container">The list of containers.</param>
        /// <param name="settings">The settings.</param>
        [CakeMethodAlias]
		public static void DockerLogs(this ICakeContext context, DockerContainerLogsSettings settings, string container)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (container == null)
            {
                throw new ArgumentNullException("container");
            }
            var runner = new GenericDockerRunner<DockerContainerLogsSettings>(context.FileSystem, context.Environment, context.ProcessRunner, context.Tools);
            runner.Run("start", settings ?? new DockerContainerLogsSettings(), new string[] { container });
        }
    }
}

using Cake.Core;
using Cake.Core.Annotations;
using System;
using System.Linq;
using System.Collections.Generic;

namespace Cake.Docker
{
    partial class DockerAliases
    {
        /// <summary>
        /// Logs <paramref name="container"/> using default settings.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="container">The list of containers.</param>
        [CakeMethodAlias]
        public static IEnumerable<string> DockerLogs(this ICakeContext context, string container)
        {
            return DockerLogs(context, new DockerContainerLogsSettings(), container);
        }

        /// <summary>
        /// Logs <paramref name="container"/> using the given <paramref name="settings"/>.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="container">The list of containers.</param>
        /// <param name="settings">The settings.</param>
        [CakeMethodAlias]
		public static IEnumerable<string> DockerLogs(this ICakeContext context, DockerContainerLogsSettings settings, string container)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (container == null)
            {
                throw new ArgumentNullException("container");
            }
            var runner = new GenericDockerRunner<DockerContainerLogsSettings>(context.FileSystem, context.Environment, context.ProcessRunner, context.Tools);
            return runner.RunWithResult("logs", settings ?? new DockerContainerLogsSettings(), r => r.ToArray(), new string[] { container });
        }
    }
}

Fix log command and return log lines

Fix log command and return log lines


using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Bonobo.Git.Server.Controllers;
using Bonobo.Git.Server.Test.Integration.Web;
using Bonobo.Git.Server.Test.IntegrationTests.Helpers;
using SpecsFor.Mvc;

namespace Bonobo.Git.Server.Test.IntegrationTests
{
    using OpenQA.Selenium.Support.UI;
    using OpenQA.Selenium;

    [TestClass]
    public class SharedLayoutTests : IntegrationTestBase
    {
        [TestMethod, TestCategory(TestCategories.WebIntegrationTest)]
        public void DropdownNavigationWorks()
        {
            var reponame = "A_Nice_Repo";
            var id1 = ITH.CreateRepositoryOnWebInterface(reponame);
            var id2 = ITH.CreateRepositoryOnWebInterface("other_name");

            app.NavigateTo<RepositoryController>(c => c.Detail(id2));

            var element = app.Browser.FindElementByCssSelector("select#Repositories");
            var dropdown = new SelectElement(element);
            dropdown.SelectByText(reponame);

            app.UrlMapsTo<RepositoryController>(c => c.Detail(id1));

            app.WaitForElementToBeVisible(By.CssSelector("select#Repositories"), TimeSpan.FromSeconds(10));
            dropdown = new SelectElement(app.Browser.FindElementByCssSelector("select#Repositories"));
            dropdown.SelectByText("other_name");

            app.UrlMapsTo<RepositoryController>(c => c.Detail(id2));
        }

    }
}

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Bonobo.Git.Server.Controllers;
using Bonobo.Git.Server.Test.Integration.Web;
using Bonobo.Git.Server.Test.IntegrationTests.Helpers;
using SpecsFor.Mvc;

namespace Bonobo.Git.Server.Test.IntegrationTests
{
    using OpenQA.Selenium.Support.UI;
    using OpenQA.Selenium;
    using System.Threading;

    [TestClass]
    public class SharedLayoutTests : IntegrationTestBase
    {
        [TestMethod, TestCategory(TestCategories.WebIntegrationTest)]
        public void DropdownNavigationWorks()
        {
            var reponame = ITH.MakeName();
            var otherreponame = ITH.MakeName(reponame + "_other");
            var repoId = ITH.CreateRepositoryOnWebInterface(reponame);
            var otherrepoId = ITH.CreateRepositoryOnWebInterface(otherreponame);

            app.NavigateTo<RepositoryController>(c => c.Detail(otherrepoId));

            var element = app.Browser.FindElementByCssSelector("select#Repositories");
            var dropdown = new SelectElement(element);
            dropdown.SelectByText(reponame);
            Thread.Sleep(2000);

            app.UrlMapsTo<RepositoryController>(c => c.Detail(repoId));

            app.WaitForElementToBeVisible(By.CssSelector("select#Repositories"), TimeSpan.FromSeconds(10));
            dropdown = new SelectElement(app.Browser.FindElementByCssSelector("select#Repositories"));
            dropdown.SelectByText(otherreponame);
            Thread.Sleep(2000);

            app.UrlMapsTo<RepositoryController>(c => c.Detail(otherrepoId));
        }

    }
}

Make DropdDownNavigationWorks more reliable and use new test methods.


using System;
using System.Linq;
using System.Linq.Expressions;
using FluentAssertions;

namespace PSql.Tests
{
    using static ScriptExecutor;

    internal static class StringExtensions
    {
        internal static void
            ShouldOutput(
                this string     script,
                params object[] expected
            )
        {
            if (script is null)
                throw new ArgumentNullException(nameof(script));
            if (expected is null)
                throw new ArgumentNullException(nameof(expected));

            var (objects, exception) = Execute(script);

            exception.Should().BeNull();

            objects.Should().HaveCount(expected.Length);

            objects
                .Select(o => o?.BaseObject)
                .Should().BeEquivalentTo(expected, x => x.IgnoringCyclicReferences());
        }

        internal static void
            ShouldThrow<T>(
                this string script,
                string      messagePart
            )
            where T : Exception
        {
            script.ShouldThrow<T>(
                e => e.Message.Contains(messagePart, StringComparison.OrdinalIgnoreCase)
            );
        }

        internal static void
            ShouldThrow<T>(
                this string                script,
                Expression<Func<T, bool>>? predicate = null
            )
            where T : Exception
        {
            if (script is null)
                throw new ArgumentNullException(nameof(script));

            var (_, exception) = Execute(script);

            exception.Should().NotBeNull().And.BeAssignableTo<T>();

            if (predicate is not null)
                exception.Should().Match<T>(predicate);
        }
    }
}

using System;
using System.Linq;
using System.Linq.Expressions;
using FluentAssertions;

namespace PSql.Tests
{
    using static ScriptExecutor;

    internal static class StringExtensions
    {
        internal static void
            ShouldOutput(
                this string     script,
                params object[] expected
            )
        {
            if (script is null)
                throw new ArgumentNullException(nameof(script));
            if (expected is null)
                throw new ArgumentNullException(nameof(expected));

            var (objects, exception) = Execute(script);

            exception.Should().BeNull();

            objects.Should().HaveCount(expected.Length);

            objects
                .Select(o => o?.BaseObject)
                .Should().BeEquivalentTo(expected, x => x.IgnoringCyclicReferences());
        }

        internal static void
            ShouldThrow<T>(this string script, string messagePart)
            where T : Exception
        {
            var exception = script.ShouldThrow<T>();

            exception.Message.Should().Contain(messagePart);
        }

        internal static T ShouldThrow<T>(this string script)
            where T : Exception
        {
            if (script is null)
                throw new ArgumentNullException(nameof(script));

            var (_, exception) = Execute(script);

            return exception
                .Should().NotBeNull()
                .And     .BeAssignableTo<T>()
                .Subject;
        }
    }
}

Rework exception asserts to improve failure messages.


using Microsoft.VisualStudio.TestTools.UnitTesting;
using Renci.SshNet.Security.Cryptography;
using Renci.SshNet.Tests.Common;
using System;

namespace Renci.SshNet.Tests.Classes
{
    /// <summary>
    /// Holds information about key size and cipher to use
    /// </summary>
    [TestClass]
    public class CipherInfoTest : TestBase
    {
        /// <summary>
        ///A test for CipherInfo Constructor
        ///</summary>
        [TestMethod()]
        public void CipherInfoConstructorTest()
        {
            int keySize = 0; // TODO: Initialize to an appropriate value
            Func<byte[], byte[], BlockCipher> cipher = null; // TODO: Initialize to an appropriate value
            CipherInfo target = new CipherInfo(keySize, cipher);
            Assert.Inconclusive("TODO: Implement code to verify target");
        }
    }
}

using Microsoft.VisualStudio.TestTools.UnitTesting;
using Renci.SshNet.Security.Cryptography;
using Renci.SshNet.Tests.Common;
using System;

namespace Renci.SshNet.Tests.Classes
{
    /// <summary>
    /// Holds information about key size and cipher to use
    /// </summary>
    [TestClass]
    public class CipherInfoTest : TestBase
    {
        /// <summary>
        ///A test for CipherInfo Constructor
        ///</summary>
        [TestMethod()]
        public void CipherInfoConstructorTest()
        {
            int keySize = 0; // TODO: Initialize to an appropriate value
            Func<byte[], byte[], Cipher> cipher = null; // TODO: Initialize to an appropriate value
            CipherInfo target = new CipherInfo(keySize, cipher);
            Assert.Inconclusive("TODO: Implement code to verify target");
        }
    }
}

Fix build when targeting .NET Framework 3.5 as Func only supports covariance on .NET Framework 4.0 and higher.


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

namespace Microsoft.CodeAnalysis
{
    /// <summary>
    /// Indicates that the implementing type can be serialized via <see cref="ToString"/>
    /// for diagnostic message purposes.
    /// </summary>
    /// <remarks>
    /// Not appropriate on types that require localization, since localization should
    /// happen after serialization.
    /// </remarks>
    internal interface IMessageSerializable
    {
    }
}

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

namespace Microsoft.CodeAnalysis
{
    /// <summary>
    /// Indicates that the implementing type can be serialized via <see cref="object.ToString"/>
    /// for diagnostic message purposes.
    /// </summary>
    /// <remarks>
    /// Not appropriate on types that require localization, since localization should
    /// happen after serialization.
    /// </remarks>
    internal interface IMessageSerializable
    {
    }
}

Fix a warning about a cref in an XML doc comment.

"ToString" by itself cannot be resolved to a symbol. We really meant "object.ToString". (changeset 1255357)