handling of corrupted cached species images

--- ARKBreedingStats/CreatureColored.cs
+++ ARKBreedingStats/CreatureColored.cs
@@ -5,14 +5,12 @@
 using System.Drawing.Imaging;
 using System.IO;
 using System.Linq;
-using System.Linq.Expressions;
-using System.Runtime.Remoting.Messaging;
 using System.Text;
 using ARKBreedingStats.Library;

 namespace ARKBreedingStats
 {
-    static class CreatureColored
+    internal static class CreatureColored
     {
         private const string Extension = ".png";
         private static readonly string ImgFolder = FileService.GetPath(FileService.ImageFolderName);
@@ -105,10 +103,32 @@
                 cacheFileExists = CreateAndSaveCacheSpeciesFile(colorIds, enabledColorRegions, speciesBackgroundFilePath, speciesColorMaskFilePath, cacheFilePath);
             }

-            if (onlyImage && !cacheFileExists) return null;
+            if (onlyImage && !cacheFileExists) return null; // creating the species file failed

             if (cacheFileExists && size == TemplateSize)
-                return new Bitmap(cacheFilePath);
+            {
+                try
+                {
+                    return new Bitmap(cacheFilePath);
+                }
+                catch
+                {
+                    // cached file corrupted, recreate
+                    if (CreateAndSaveCacheSpeciesFile(colorIds, enabledColorRegions, speciesBackgroundFilePath,
+                        speciesColorMaskFilePath, cacheFilePath))
+                    {
+                        try
+                        {
+                            return new Bitmap(cacheFilePath);
+                        }
+                        catch
+                        {
+                            // file is still invalid after recreation, ignore file
+                        }
+                    }
+                }
+                return null;
+            }

             Bitmap bm = new Bitmap(size, size);
             using (Graphics graph = Graphics.FromImage(bm))
@@ -121,8 +141,30 @@
                     graph.InterpolationMode = InterpolationMode.HighQualityBicubic;
                     graph.SmoothingMode = SmoothingMode.HighQuality;
                     graph.PixelOffsetMode = PixelOffsetMode.HighQuality;
-                    using (var cachedImgBmp = new Bitmap(cacheFilePath))
-                        graph.DrawImage(cachedImgBmp, 0, 0, size, size);
+                    try
+                    {
+                        using (var cachedImgBmp = new Bitmap(cacheFilePath))
+                            graph.DrawImage(cachedImgBmp, 0, 0, size, size);
+                    }
+                    catch
+                    {
+                        // cached file invalid, recreate
+                        if (CreateAndSaveCacheSpeciesFile(colorIds, enabledColorRegions, speciesBackgroundFilePath,
+                            speciesColorMaskFilePath, cacheFilePath))
+                        {
+                            try
+                            {
+                                using (var cachedImgBmp = new Bitmap(cacheFilePath))
+                                    graph.DrawImage(cachedImgBmp, 0, 0, size, size);
+                            }
+                            catch
+                            {
+                                // file is still invalid after recreation, ignore file
+                                bm.Dispose();
+                                return null;
+                            }
+                        }
+                    }
                 }
                 else
                 {
@@ -162,7 +204,9 @@
         private static bool CreateAndSaveCacheSpeciesFile(int[] colorIds, bool[] enabledColorRegions,
             string speciesBackgroundFilePath, string speciesColorMaskFilePath, string cacheFilePath, int outputSize = 256)
         {
-            if (!File.Exists(speciesBackgroundFilePath)) return false;
+            if (!File.Exists(speciesBackgroundFilePath)
+                || string.IsNullOrEmpty(cacheFilePath))
+                return false;

             using (Bitmap bmpBackground = new Bitmap(speciesBackgroundFilePath))
             using (Bitmap bmpColoredCreature = new Bitmap(bmpBackground.Width, bmpBackground.Height, PixelFormat.Format32bppArgb))
@@ -202,7 +246,7 @@
                         if (useColorRegions[c])
                         {
                             Color cl = CreatureColors.CreatureColor(colorIds[c]);
-                            rgb[c] = new byte[] { cl.R, cl.G, cl.B };
+                            rgb[c] = new[] { cl.R, cl.G, cl.B };
                         }
                     }
                     imageFine = ApplyColorsUnsafe(rgb, useColorRegions, speciesColorMaskFilePath, TemplateSize, bmpBackground, bmpColoredCreature);
@@ -211,6 +255,7 @@
                 if (imageFine)
                 {
                     string cacheFolder = Path.GetDirectoryName(cacheFilePath);
+                    if (string.IsNullOrEmpty(cacheFolder)) return false;
                     if (!Directory.Exists(cacheFolder))
                         Directory.CreateDirectory(cacheFolder);
                     if (outputSize == TemplateSize)


Fix SecretCache

Fix SecretCache

--- Akavache/WinRTEncryptedBlobCache.cs
+++ Akavache/WinRTEncryptedBlobCache.cs
@@ -19,7 +19,6 @@
             get { return _Current.Value; }
         }

-        readonly DataProtectionProvider dpapi = new DataProtectionProvider();
         protected EncryptedBlobCache(string cacheDirectory = null, IFilesystemProvider filesystemProvider = null, IScheduler scheduler = null)
             : base(cacheDirectory, filesystemProvider, scheduler)
         {
@@ -32,12 +31,24 @@

         protected override IObservable<byte[]> BeforeWriteToDiskFilter(byte[] data, IScheduler scheduler)
         {
+            if (data.Length == 0)
+            {
+                return Observable.Return(data);
+            }
+
+            var dpapi = new DataProtectionProvider("LOCAL=user");
             return dpapi.ProtectAsync(data.AsBuffer()).ToObservable()
                 .Select(x => x.ToArray());
         }

         protected override IObservable<byte[]> AfterReadFromDiskFilter(byte[] data, IScheduler scheduler)
         {
+            if (data.Length == 0)
+            {
+                return Observable.Return(data);
+            }
+
+            var dpapi = new DataProtectionProvider();
             return dpapi.UnprotectAsync(data.AsBuffer()).ToObservable()
                 .Select(x => x.ToArray());
         }


Move reroute logic above deserialization since it might not have the types...

--- Naos.MessageBus.Core/MessageDispatcher.cs
+++ Naos.MessageBus.Core/MessageDispatcher.cs
@@ -59,6 +59,17 @@
                 throw new DispatchException("Parcel must contain envelopes");
             }

+            // make sure the message was routed correctly (if not then reroute)
+            if (this.servicedChannels.SingleOrDefault(_ => _.Name == parcel.Envelopes.First().Channel.Name) == null)
+            {
+                var rerouteMessageSender = this.simpleInjectorContainer.GetInstance<ISendMessages>();
+
+                // any schedule should already be set and NOT reset...
+                rerouteMessageSender.Send(parcel, Schedules.None);
+
+                return;
+            }
+
             Func<string, string, string, Type> getTypeForLocalVersion = (typeNamespace, typeName, typeAssemblyQualifiedName) =>
                 {
                     var registeredHandlers =
@@ -113,22 +124,8 @@
                         return ret;
                     }).ToList();

-            var firstChannel = channeledMessages.First().Channel;
             var firstMessage = channeledMessages.First().Message;
             var remainingChanneledMessages = channeledMessages.Skip(1).ToList();
-
-            // make sure the message was routed correctly (if not then reroute)
-            if (!this.servicedChannels.Contains(firstChannel))
-            {
-                var rerouteMessageSender = this.simpleInjectorContainer.GetInstance<ISendMessages>();
-                var rerouteMessageSequence = new MessageSequence
-                {
-                    Id = parcel.Id,
-                    ChanneledMessages = channeledMessages
-                };
-
-                rerouteMessageSender.Send(rerouteMessageSequence);
-            }

             var messageType = firstMessage.GetType();
             var handlerType = typeof(IHandleMessages<>).MakeGenericType(messageType);


Tweak ArrayEqualByComparer

Tweak ArrayEqualByComparer

--- Gu.State/EqualBy/Comparers/ArrayEqualByComparer.cs
+++ Gu.State/EqualBy/Comparers/ArrayEqualByComparer.cs
@@ -1,59 +1,96 @@
 namespace Gu.State
 {
     using System;
+    using System.Reflection;

     /// <inheritdoc />
-    internal class ArrayEqualByComparer : EqualByComparer
+    internal static class ArrayEqualByComparer
     {
-        /// The default instance.
-        public static readonly ArrayEqualByComparer Default = new ArrayEqualByComparer();
-
-        private ArrayEqualByComparer()
-        {
-        }
-
-        /// <inheritdoc />
-        public override bool Equals(object x, object y, MemberSettings settings, ReferencePairCollection referencePairs)
-        {
-            if (TryGetEitherNullEquals(x, y, out var result))
-            {
-                return result;
-            }
-
-            return Equals((Array)x, (Array)y, settings, referencePairs);
-        }
-
         internal static bool TryGet(Type type, MemberSettings settings, out EqualByComparer comparer)
         {
             if (type.IsArray)
             {
-                comparer = Default;
-                return true;
+                switch (type.GetArrayRank())
+                {
+                    case 1:
+                        return IReadOnlyListEqualByComparer.TryGet(type, settings, out comparer);
+                    case 2:
+                        comparer = (EqualByComparer)typeof(Comparer2D<>).MakeGenericType(type.GetItemType())
+                                                                           .GetField(nameof(Comparer2D<int>.Default), BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static)
+                                                                           .GetValue(null);
+                        return true;
+                    default:
+                        comparer = Comparer.Default;
+                        return true;
+                }
             }

             comparer = null;
             return false;
         }

-        private static bool Equals(Array x, Array y, MemberSettings settings, ReferencePairCollection referencePairs)
+        private class Comparer2D<T> : EqualByComparer<T[,]>
         {
-            if (!Is.SameSize(x, y))
+            /// The default instance.
+            public static readonly Comparer2D<T> Default = new Comparer2D<T>();
+
+            private Comparer2D()
             {
-                return false;
             }

-            var comparer = settings.GetEqualByComparer(x.GetType().GetItemType());
-            var xe = x.GetEnumerator();
-            var ye = y.GetEnumerator();
-            while (xe.MoveNext() && ye.MoveNext())
+            public override bool Equals(T[,] xs, T[,] ys, MemberSettings settings, ReferencePairCollection referencePairs)
             {
-                if (!comparer.Equals(xe.Current, ye.Current, settings, referencePairs))
+                if (!Is.SameSize(xs, ys))
                 {
                     return false;
                 }
+
+                var comparer = settings.GetEqualByComparer(typeof(T));
+
+                for (var i = 0; i < xs.GetLength(0); i++)
+                {
+                    for (var j = 0; j < xs.GetLength(1); j++)
+                    {
+                        if (!comparer.Equals(i, j, settings, referencePairs))
+                        {
+                            return false;
+                        }
+                    }
+                }
+
+                return true;
+            }
+        }
+
+        private class Comparer : EqualByComparer<Array>
+        {
+            /// The default instance.
+            public static readonly Comparer Default = new Comparer();
+
+            private Comparer()
+            {
             }

-            return true;
+            public override bool Equals(Array x, Array y, MemberSettings settings, ReferencePairCollection referencePairs)
+            {
+                if (!Is.SameSize(x, y))
+                {
+                    return false;
+                }
+
+                var comparer = settings.GetEqualByComparer(x.GetType().GetItemType());
+                var xe = x.GetEnumerator();
+                var ye = y.GetEnumerator();
+                while (xe.MoveNext() && ye.MoveNext())
+                {
+                    if (!comparer.Equals(xe.Current, ye.Current, settings, referencePairs))
+                    {
+                        return false;
+                    }
+                }
+
+                return true;
+            }
         }
     }
-}+}


[UPDATE] Definition of String.Empty resolves #47

--- Core/Foundation/System/String.cs
+++ Core/Foundation/System/String.cs
@@ -13,6 +13,9 @@
     {
         public readonly int Length = 0;

+        [InlineConst]
+        public const string Empty = "";
+
         /// <summary>
         /// The String global object is a constructor for strings, or a sequence of characters.
         /// </summary>


Fix ListUserBestScores score info parsing

--- CotcSdk/HighLevel/GamerScores.cs
+++ CotcSdk/HighLevel/GamerScores.cs
@@ -98,7 +98,8 @@
 			return Common.RunInTask<Dictionary<string, Score>>(req, (response, task) => {
 				Dictionary<string, Score> scores = new Dictionary<string, Score>();
 				foreach (var pair in response.BodyJson.AsDictionary()) {
-					Score s = new Score(pair.Value);
+					Bundle scoreValue = Bundle.CreateObject("score", pair.Value);
+					Score s = new Score(scoreValue, pair.Value["rank"].AsInt());
 					s.GamerInfo = null;
 					scores[pair.Key] = s;
 				}


Remove accidently added using directives

--- DLL_Project/Defs/ModHelperDef.cs
+++ DLL_Project/Defs/ModHelperDef.cs
@@ -2,8 +2,7 @@
 using System.Collections.Generic;
 using System.Linq;
 using System.Reflection;
-using System.Text;
-using System.Threading;
+
 using Verse;

 namespace CommunityCoreLibrary


Added support for source rect on XNB replacements

--- Libraries/Revolution/Content/ContentManager.cs
+++ Libraries/Revolution/Content/ContentManager.cs
@@ -116,9 +116,19 @@
                 {
                     Log.Verbose("Trying to construct texture from scratch");
                     var originalData = new Color[originalTexture.Width * originalTexture.Height];
-                    var modData = new Color[obj.Width * obj.Height];
+                    Color[] modData;
                     originalTexture.GetData<Color>(originalData);
-                    obj.GetData<Color>(modData);
+
+                    if (item.Source == null)
+                    {
+                        modData = new Color[obj.Width * obj.Height];
+                        obj.GetData<Color>(modData);
+                    }
+                    else
+                    {
+                        modData = new Color[item.Source.Width * item.Source.Height];
+                        obj.GetData<Color>(0, item.Source, modData, 0, item.Source.Width * item.Source.Height);
+                    }

                     var newObject = new Texture2D(Game1.graphics.GraphicsDevice, originalTexture.Width, originalTexture.Height);
                     newObject.SetData<Color>(originalData);


Add SwitchExtruderStream to GCode export

--- MatterControlLib/Library/Export/GCodeExport.cs
+++ MatterControlLib/Library/Export/GCodeExport.cs
@@ -287,6 +287,11 @@
 			var queueStream = new QueuedCommandsStream(printer, gCodeBaseStream);
 			GCodeStream accumulatedStream = queueStream;

+			if (printer.Settings.GetValue<int>(SettingsKey.extruder_count) > 1)
+			{
+				accumulatedStream = new SwitchExtruderStream(printer, accumulatedStream);
+			}
+
 			accumulatedStream = new RelativeToAbsoluteStream(printer, accumulatedStream);

 			bool levelingEnabled = printer.Settings.GetValue<bool>(SettingsKey.print_leveling_enabled) && applyLeveling;


Ported some missing methods in ApiClient to net35

--- MediaBrowser.ApiInteraction.net35/ApiClient.cs
+++ MediaBrowser.ApiInteraction.net35/ApiClient.cs
@@ -2,10 +2,15 @@
 using MediaBrowser.Model.Configuration;
 using MediaBrowser.Model.Dto;
 using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Globalization;
 using MediaBrowser.Model.Logging;
+using MediaBrowser.Model.Notifications;
+using MediaBrowser.Model.Plugins;
 using MediaBrowser.Model.Querying;
+using MediaBrowser.Model.Search;
 using MediaBrowser.Model.Serialization;
 using MediaBrowser.Model.System;
+using MediaBrowser.Model.Tasks;
 using MediaBrowser.Model.Users;
 using MediaBrowser.Model.Web;
 using System;
@@ -196,6 +201,26 @@
         }

         /// <summary>
+        /// Gets the name of the item by.
+        /// </summary>
+        /// <param name="type">the plural type name ea. Artists, Genres, Studios</param>
+        /// <param name="query">The query.</param>
+        /// <param name="onSuccess">The on success.</param>
+        /// <param name="onError">The on error.</param>
+        /// <exception cref="System.ArgumentNullException">query</exception>
+        public void GetItemsByName(string type, ItemsByNameQuery query, Action<ItemsResult> onSuccess, Action<Exception> onError)
+        {
+            if (query == null)
+            {
+                throw new ArgumentNullException("query");
+            }
+
+            string url = base.GetItemByNameListUrl(type, query);
+
+            GetSerializedData(url, onSuccess, onError);
+        }
+
+        /// <summary>
         /// Gets the genres.
         /// </summary>
         /// <param name="query">The query.</param>
@@ -204,13 +229,73 @@
         /// <exception cref="System.ArgumentNullException">query</exception>
         public void GetGenres(ItemsByNameQuery query, Action<ItemsResult> onSuccess, Action<Exception> onError)
         {
+            GetItemsByName("Genres", query, onSuccess, onError);
+        }
+
+        /// <summary>
+        /// Gets the next up.
+        /// </summary>
+        /// <param name="query">The query.</param>
+        /// <param name="onSuccess">The on success.</param>
+        /// <param name="onError">The on error.</param>
+        /// <exception cref="System.ArgumentNullException">query</exception>
+        public void GetNextUp(NextUpQuery query, Action<ItemsResult> onSuccess, Action<Exception> onError)
+        {
             if (query == null)
             {
                 throw new ArgumentNullException("query");
             }

-            string url = base.GetItemByNameListUrl("Genres", query);
-
+            var dict = new QueryStringDictionary { };
+
+            if (query.Fields != null)
+            {
+                dict.Add("fields", query.Fields.Select(f => f.ToString()));
+            }
+
+            dict.AddIfNotNull("Limit", query.Limit);
+            dict.AddIfNotNull("StartIndex", query.StartIndex);
+            dict.Add("UserId", query.UserId);
+
+            var url = GetApiUrl("Shows/NextUp", dict);
+
+            GetSerializedData(url, onSuccess, onError);
+        }
+
+        /// <summary>
+        /// Gets people by query.
+        /// </summary>
+        /// <param name="query">The query.</param>
+        /// <param name="onSuccess">The on success.</param>
+        /// <param name="onError">The on error.</param>
+        public void GetPeople(PersonsQuery query, Action<ItemsResult> onSuccess, Action<Exception> onError)
+        {
+            var url = GetItemByNameListUrl("Persons", query);
+
+            if (query.PersonTypes != null && query.PersonTypes.Length > 0)
+            {
+                url += "&PersonTypes=" + string.Join(",", query.PersonTypes);
+            }
+
+            GetSerializedData(url, onSuccess, onError);
+        }
+
+        /// <summary>
+        /// Gets similar items.
+        /// </summary>
+        /// <param name="type">The type of item.</param>
+        /// <param name="query">The query.</param>
+        /// <param name="onSuccess">The on success.</param>
+        /// <param name="onError">The on error.</param>
+        /// <exception cref="System.ArgumentNullException">query</exception>
+        public void GetSimilarItems(string type, SimilarItemsQuery query, Action<ItemsResult> onSuccess, Action<Exception> onError)
+        {
+            if (query == null)
+            {
+                throw new ArgumentNullException("query");
+            }
+
+            var url = GetSimilarItemListUrl(query, type);
             GetSerializedData(url, onSuccess, onError);
         }

@@ -223,14 +308,7 @@
         /// <exception cref="System.ArgumentNullException">query</exception>
         public void GetStudios(ItemsByNameQuery query, Action<ItemsResult> onSuccess, Action<Exception> onError)
         {
-            if (query == null)
-            {
-                throw new ArgumentNullException("query");
-            }
-
-            string url = base.GetItemByNameListUrl("Studios", query);
-
-            GetSerializedData(url, onSuccess, onError);
+            GetItemsByName("Studios", query, onSuccess, onError);
         }

         /// <summary>
@@ -240,9 +318,7 @@
         /// <param name="onError">The on error.</param>
         public void GetServerConfiguration(Action<ServerConfiguration> onSuccess, Action<Exception> onError)
         {
-            var url = GetApiUrl("System/Configuration");
-
-            GetSerializedData(url, onSuccess, onError);
+            GetOperation("System/Configuration", onSuccess, onError);
         }

         /// <summary>
@@ -411,6 +487,276 @@
             _httpClient.Delete(url, x => onResponse(false));
         }

+        /// <summary>
+        /// Restarts the server.
+        /// </summary>
+        /// <param name="onSuccess">The on success.</param>
+        /// <param name="onError">The on error.</param>
+        public void RestartServer(Action<EmptyRequestResult> onSuccess, Action<Exception> onError)
+        {
+            var url = GetApiUrl("System/Restart");
+
+            Post(url, new QueryStringDictionary(), onSuccess, onError);
+        }
+
+        /// <summary>
+        /// Gets the installed plugins.
+        /// </summary>
+        /// <param name="onSuccess">The on success.</param>
+        /// <param name="onError">The on error.</param>
+        public void GetInstalledPlugins(Action<PluginInfo[]> onSuccess, Action<Exception> onError)
+        {
+            GetOperation("Plugins", onSuccess, onError);
+        }
+
+        /// <summary>
+        /// Gets the scheduled tasks.
+        /// </summary>
+        /// <param name="onSuccess">The on success.</param>
+        /// <param name="onError">The on error.</param>
+        public void GetScheduledTasks(Action<TaskInfo[]> onSuccess, Action<Exception> onError)
+        {
+            GetOperation("ScheduledTasks", onSuccess, onError);
+        }
+
+
+        /// <summary>
+        /// Gets the operation.
+        /// </summary>
+        /// <typeparam name="TResponse">The type of the response.</typeparam>
+        /// <param name="operation">The operation.</param>
+        /// <param name="onSuccess">The on success.</param>
+        /// <param name="onError">The on error.</param>
+        protected void GetOperation<TResponse>(string operation, Action<TResponse> onSuccess, Action<Exception> onError)
+        {
+            var url = GetApiUrl(operation);
+
+            GetSerializedData(url, onSuccess, onError);
+        }
+
+        /// <summary>
+        /// Gets the scheduled task.
+        /// </summary>
+        /// <param name="id">The identifier.</param>
+        /// <param name="onSuccess">The on success.</param>
+        /// <param name="onError">The on error.</param>
+        /// <exception cref="System.ArgumentNullException">id</exception>
+        public void GetScheduledTask(Guid id, Action<TaskInfo> onSuccess, Action<Exception> onError)
+        {
+            if (id == Guid.Empty)
+            {
+                throw new ArgumentNullException("id");
+            }
+
+            var url = GetApiUrl("ScheduledTasks/" + id);
+            GetSerializedData(url, onSuccess, onError);
+        }
+
+        /// <summary>
+        /// Gets the parental ratings.
+        /// </summary>
+        /// <param name="onSuccess">The on success.</param>
+        /// <param name="onError">The on error.</param>
+        public void GetParentalRatings(Action<List<ParentalRating>> onSuccess, Action<Exception> onError)
+        {
+            var url = GetApiUrl("Localization/ParentalRatings");
+            GetSerializedData(url, onSuccess, onError);
+        }
+
+        /// <summary>
+        /// Gets the local trailers.
+        /// </summary>
+        /// <param name="userId">The user identifier.</param>
+        /// <param name="itemId">The item identifier.</param>
+        /// <param name="onSuccess">The on success.</param>
+        /// <param name="onError">The on error.</param>
+        public void GetLocalTrailers(string userId, string itemId, Action<BaseItemDto[]> onSuccess, Action<Exception> onError)
+        {
+            GetExtras("LocalTrailers", userId, itemId, onSuccess, onError);
+        }
+
+        /// <summary>
+        /// Gets the special features.
+        /// </summary>
+        /// <param name="userId">The user identifier.</param>
+        /// <param name="itemId">The item identifier.</param>
+        /// <param name="onSuccess">The on success.</param>
+        /// <param name="onError">The on error.</param>
+        public void GetSpecialFeatures(string userId, string itemId, Action<BaseItemDto[]> onSuccess, Action<Exception> onError)
+        {
+            GetExtras("SpecialFeatures", userId, itemId, onSuccess, onError);
+        }
+
+        /// <summary>
+        /// Gets the extras.
+        /// </summary>
+        /// <param name="extraType">Type of the extra.</param>
+        /// <param name="userId">The user identifier.</param>
+        /// <param name="itemId">The item identifier.</param>
+        /// <param name="onSuccess">The on success.</param>
+        /// <param name="onError">The on error.</param>
+        /// <exception cref="System.ArgumentNullException">
+        /// userId
+        /// or
+        /// itemId
+        /// </exception>
+        private void GetExtras(string extraType, string userId, string itemId, Action<BaseItemDto[]> onSuccess, Action<Exception> onError)
+        {
+            if (string.IsNullOrEmpty(userId))
+            {
+                throw new ArgumentNullException("userId");
+            }
+            if (string.IsNullOrEmpty(itemId))
+            {
+                throw new ArgumentNullException("itemId");
+            }
+
+            var url = GetApiUrl("Users/" + userId + "/Items/" + itemId + "/" + extraType);
+            GetSerializedData(url, onSuccess, onError);
+        }
+
+        /// <summary>
+        /// Gets the cultures.
+        /// </summary>
+        /// <param name="onSuccess">The on success.</param>
+        /// <param name="onError">The on error.</param>
+        public void GetCultures(Action<CultureDto[]> onSuccess, Action<Exception> onError)
+        {
+            GetOperation("Localization/Cultures", onSuccess, onError);
+        }
+
+        /// <summary>
+        /// Gets the countries.
+        /// </summary>
+        /// <param name="onSuccess">The on success.</param>
+        /// <param name="onError">The on error.</param>
+        public void GetCountries(Action<CountryInfo[]> onSuccess, Action<Exception> onError)
+        {
+            GetOperation("Localization/Countries", onSuccess, onError);
+        }
+
+        /// <summary>
+        /// Gets the notifications summary.
+        /// </summary>
+        /// <param name="userId">The user identifier.</param>
+        /// <param name="onSuccess">The on success.</param>
+        /// <param name="onError">The on error.</param>
+        public void GetNotificationsSummary(string userId, Action<NotificationsSummary> onSuccess, Action<Exception> onError)
+        {
+            GetOperation("Notifications/" + userId + "/Summary", onSuccess, onError);
+        }
+
+        /// <summary>
+        /// Gets the notifications.
+        /// </summary>
+        /// <param name="query">The query.</param>
+        /// <param name="onSuccess">The on success.</param>
+        /// <param name="onError">The on error.</param>
+        public void GetNotifications(NotificationQuery query, Action<NotificationResult> onSuccess, Action<Exception> onError)
+        {
+            var dict = new QueryStringDictionary();
+            dict.AddIfNotNull("ItemIds", query.IsRead);
+            dict.AddIfNotNull("StartIndex", query.StartIndex);
+            dict.AddIfNotNull("Limit", query.Limit);
+
+            var url = GetApiUrl("Notifications/" + query.UserId, dict);
+            GetSerializedData(url, onSuccess, onError);
+        }
+
+        /// <summary>
+        /// Gets the search hints.
+        /// </summary>
+        /// <param name="userId">The user identifier.</param>
+        /// <param name="searchTerm">The search term.</param>
+        /// <param name="onSuccess">The on success.</param>
+        /// <param name="onError">The on error.</param>
+        /// <param name="startIndex">The start index.</param>
+        /// <param name="limit">The limit.</param>
+        /// <exception cref="System.ArgumentNullException">searchTerm</exception>
+        public void GetSearchHints(string userId, string searchTerm, Action<SearchHintResult> onSuccess, Action<Exception> onError, int? startIndex = null, int? limit = null)
+        {
+            if (string.IsNullOrEmpty(searchTerm))
+            {
+                throw new ArgumentNullException("searchTerm");
+            }
+
+            var queryString = new QueryStringDictionary();
+
+            queryString.Add("searchTerm", searchTerm);
+            queryString.AddIfNotNullOrEmpty("UserId", userId);
+            queryString.AddIfNotNull("startIndex", startIndex);
+            queryString.AddIfNotNull("limit", limit);
+
+            var url = GetApiUrl("Search/Hints", queryString);
+
+            GetSerializedData(url, onSuccess, onError);
+        }
+
+        /// <summary>
+        /// Marks the played.
+        /// </summary>
+        /// <param name="itemId">The item identifier.</param>
+        /// <param name="userId">The user identifier.</param>
+        /// <param name="datePlayed">The date played.</param>
+        /// <param name="onSuccess">The on success.</param>
+        /// <param name="onError">The on error.</param>
+        /// <exception cref="System.ArgumentNullException">
+        /// itemId
+        /// or
+        /// userId
+        /// </exception>
+        public void MarkPlayed(string itemId, string userId, DateTime? datePlayed, Action<UserItemDataDto> onSuccess, Action<Exception> onError)
+        {
+            if (string.IsNullOrEmpty(itemId))
+            {
+                throw new ArgumentNullException("itemId");
+            }
+            if (string.IsNullOrEmpty(userId))
+            {
+                throw new ArgumentNullException("userId");
+            }
+
+            var dict = new QueryStringDictionary();
+            //dict.AddIfNotNull("DatePlayed", datePlayed);
+            var url = GetApiUrl("Users/" + userId + "/PlayedItems/" + itemId, dict);
+
+            Post(url, new Dictionary<string, string>(), onSuccess, onError);
+        }
+
+        /// <summary>
+        /// Marks the unplayed.
+        /// </summary>
+        /// <param name="itemId">The item identifier.</param>
+        /// <param name="userId">The user identifier.</param>
+        /// <param name="onResponse">The on response.</param>
+        /// <exception cref="System.ArgumentNullException">
+        /// itemId
+        /// or
+        /// userId
+        /// </exception>
+        public void MarkUnplayed(string itemId, string userId, Action<bool> onResponse)
+        {
+            if (string.IsNullOrEmpty(itemId))
+            {
+                throw new ArgumentNullException("itemId");
+            }
+            if (string.IsNullOrEmpty(userId))
+            {
+                throw new ArgumentNullException("userId");
+            }
+
+            var url = GetApiUrl("Users/" + userId + "/PlayedItems/" + itemId);
+            _httpClient.Delete(url, x => onResponse(false)); // todo: response object
+        }
+
+        /// <summary>
+        /// Posts the specified URL.
+        /// </summary>
+        /// <typeparam name="T"></typeparam>
+        /// <param name="url">The URL.</param>
+        /// <param name="args">The arguments.</param>
+        /// <param name="onSuccess">The on success.</param>
+        /// <param name="onError">The on error.</param>
         public void Post<T>(string url, Dictionary<string, string> args, Action<T> onSuccess, Action<Exception> onError)
            where T : class
         {
@@ -438,6 +784,15 @@
             }, onError);
         }

+        /// <summary>
+        /// Posts the specified URL.
+        /// </summary>
+        /// <typeparam name="TInputType">The type of the input type.</typeparam>
+        /// <typeparam name="TOutputType">The type of the output type.</typeparam>
+        /// <param name="url">The URL.</param>
+        /// <param name="obj">The object.</param>
+        /// <param name="onSuccess">The on success.</param>
+        /// <param name="onError">The on error.</param>
         protected void Post<TInputType, TOutputType>(string url, TInputType obj, Action<TOutputType> onSuccess, Action<Exception> onError)
             where TOutputType : class
         {


Fix DB connection

Fix DB connection

--- MiniTrello.Infrastructure/ConfigureDatabase.cs
+++ MiniTrello.Infrastructure/ConfigureDatabase.cs
@@ -20,7 +20,7 @@
         public void Run()
         {
             MsSqlConfiguration databaseConfiguration = MsSqlConfiguration.MsSql2008.ShowSql().
-                ConnectionString(x => x.FromConnectionStringWithKey("MiniTrello.Local"));
+                ConnectionString(x => x.FromConnectionStringWithKey("MiniTrello.Remote"));

             container.Register(c => c.Resolve<ISessionFactory>().OpenSession()).As
                 <ISession>()


Check for a valid Coin configuration - null ref error

--- MultiMiner.Win/ViewModels/MainFormViewModel.cs
+++ MultiMiner.Win/ViewModels/MainFormViewModel.cs
@@ -148,7 +148,7 @@
         public void ApplyDeviceDetailsResponseModels(string coinSymbol, List<DeviceDetailsResponse> deviceDetailsList)
         {
             //for getting Proxy worker names
-            DeviceViewModel proxyDevice = Devices.SingleOrDefault(d => (d.Kind == DeviceKind.PXY) && d.Coin.Symbol.Equals(coinSymbol));
+            DeviceViewModel proxyDevice = Devices.SingleOrDefault(d => (d.Kind == DeviceKind.PXY) && (d.Coin != null) && d.Coin.Symbol.Equals(coinSymbol));

             if (proxyDevice != null)
             {


Request Url fix

Request Url fix

--- Titanium.Web.Proxy/RequestHandler.cs
+++ Titanium.Web.Proxy/RequestHandler.cs
@@ -5,6 +5,7 @@
 using System.Net.Security;
 using System.Net.Sockets;
 using System.Security.Authentication;
+using System.Text.RegularExpressions;
 using System.Threading.Tasks;
 using StreamExtended;
 using StreamExtended.Helpers;
@@ -15,7 +16,6 @@
 using Titanium.Web.Proxy.Helpers;
 using Titanium.Web.Proxy.Http;
 using Titanium.Web.Proxy.Models;
-using Titanium.Web.Proxy.Network;
 using Titanium.Web.Proxy.Network.Tcp;

 namespace Titanium.Web.Proxy
@@ -25,6 +25,8 @@
     /// </summary>
     partial class ProxyServer
     {
+        private static readonly Regex uriSchemeRegex = new Regex("^[a-z]*://", RegexOptions.IgnoreCase | RegexOptions.Compiled);
+
         private bool isWindowsAuthenticationEnabledAndSupported => EnableWinAuth && RunTime.IsWindows && !RunTime.IsRunningOnMono;

         /// <summary>
@@ -360,9 +362,22 @@
                     //Read the request headers in to unique and non-unique header collections
                     await HeaderParser.ReadHeaders(clientStreamReader, args.WebSession.Request.Headers);

-                    var httpRemoteUri = new Uri(httpsConnectHostname == null
-                        ? isTransparentEndPoint ? string.Concat("http://", args.WebSession.Request.Host, httpUrl) : httpUrl
-                        : string.Concat("https://", args.WebSession.Request.Host ?? httpsConnectHostname, httpUrl));
+                    Uri httpRemoteUri;
+                    if (uriSchemeRegex.IsMatch(httpUrl))
+                    {
+                        httpRemoteUri = new Uri(httpUrl);
+                    }
+                    else
+                    {
+                        string host = args.WebSession.Request.Host ?? httpsConnectHostname;
+                        string hostAndPath = host;
+                        if (httpUrl.StartsWith("/"))
+                        {
+                            hostAndPath += httpUrl;
+                        }
+
+                        httpRemoteUri = new Uri(string.Concat(httpsConnectHostname == null ? "http://" : "https://", hostAndPath));
+                    }

                     args.WebSession.Request.RequestUri = httpRemoteUri;
                     args.WebSession.Request.OriginalUrl = httpUrl;


Ajuste no mapeamento de rotas para evitar duplicidade

--- TopGearApi/App_Start/WebApiConfig.cs
+++ TopGearApi/App_Start/WebApiConfig.cs
@@ -13,6 +13,7 @@
             // Web API configuration and services

             // Web API routes
+            config.MapHttpAttributeRoutes();

             config.Routes.MapHttpRoute(
                 name: "ApiByAction",
@@ -20,11 +21,11 @@
                 defaults: new { action = "Get", id = RouteParameter.Optional }
             );

-            config.Routes.MapHttpRoute(
-                name: "DefaultApi",
-                routeTemplate: "api/{controller}/{id}",
-                defaults: new { action = "Get", id = RouteParameter.Optional }
-            );
+            //config.Routes.MapHttpRoute(
+            //    name: "DefaultApi",
+            //    routeTemplate: "api/{controller}/{id}",
+            //    defaults: new { action = "Get", id = RouteParameter.Optional }
+            //);

             config.Formatters.Clear();
             config.Formatters.Add(new JsonMediaTypeFormatter());


UriTemplates: Use .ToString() for unknown value types instead of throwing exception

--- TypedRest/UriTemplates/Expression.cs
+++ TypedRest/UriTemplates/Expression.cs
@@ -186,10 +186,7 @@

                     if (dictionaryValue == null)
                     {
-                        throw new UriTemplateException(
-                            string.Format(
-                                "Invalid value type of variable \"{0}\". Expected: string or IEnumerable<string> or IDictionary<string, string>.",
-                                value.GetType()));
+                        stringValue = value.ToString();
                     }
                     else if (dictionaryValue.Count == 0)
                     {


cleanup

cleanup

--- Anlab.Core/Services/SlothService.cs
+++ Anlab.Core/Services/SlothService.cs
@@ -35,15 +35,13 @@
         //TODO: Add validation?
         public async Task<SlothResponseModel> MoveMoney(Order order)
         {
-            //var config = appSettings.Value;
-            var config = _appSettings;
             var orderDetails = order.GetOrderDetails();
-            var token = config.SlothApiKey;
-            var url = config.SlothApiUrl;
-            var creditAccount = new AccountModel(config.AnlabAccount);
+            var token = _appSettings.SlothApiKey;
+            var url = _appSettings.SlothApiUrl;
+            var creditAccount = new AccountModel(_appSettings.AnlabAccount);
             var debitAccount = new AccountModel(orderDetails.Payment.Account);

-            var objectCode = config.ObjectCode;
+            var objectCode = _appSettings.ObjectCode;

             var model = new TransactionViewModel();
             model.MerchantTrackingNumber = order.Id.ToString();


Don't show duplicate on results page if they have not paid yet.

--- Anlab.Mvc/Views/Results/Link.cshtml
+++ Anlab.Mvc/Views/Results/Link.cshtml
@@ -37,18 +37,19 @@

              Download

+        @if (User.Identity.IsAuthenticated)
+         {
+             <form asp-action="Copy" asp-controller="Order" method="post" autocomplete="off">
+                 <input type="hidden" name="id" value="@Model.OrderReviewModel.Order.ShareIdentifier" />
+                 <button type="submit" class="btn btn-primary" aria-hidden="true"> Duplicate</button>
+             </form>
+         }
+         else
+         {
+             <button id="sign-in" class="btn btn-primary" aria-hidden="true"> Duplicate</button>
+         }
     }
-    @if (User.Identity.IsAuthenticated)
-    {
-        <form asp-action="Copy" asp-controller="Order" method="post" autocomplete="off">
-            <input type="hidden" name="id" value="@Model.OrderReviewModel.Order.ShareIdentifier" />
-            <button type="submit" class="btn btn-primary" aria-hidden="true"> Duplicate</button>
-        </form>
-    }
-    else
-    {
-        <button id="sign-in" class="btn btn-primary" aria-hidden="true"> Duplicate</button>
-    }
+

 }


增加速度限制

增加速度限制

--- JitterPhysics/Assets/TrueSync/Unity/TSRigidBody.cs
+++ JitterPhysics/Assets/TrueSync/Unity/TSRigidBody.cs
@@ -13,6 +13,12 @@

         public enum InterpolateMode { None, Interpolate, Extrapolate };

+        [SerializeField]
+        /// <summary>
+        /// The max angular velocity.
+        /// </summary>
+        private FP MaxAngularVelocity;
+
         [FormerlySerializedAs("mass")]
         [SerializeField]
         private FP _mass = 1;
@@ -321,16 +327,34 @@
             }
         }

+        /// <summary>
+        /// 缓存上一次的velocity
+        /// </summary>
+        private TSVector previousAngularVelocity = TSVector.zero;
+
         /**
         *  @brief AngularVelocity of the body.
         **/
         public TSVector angularVelocity {
             get {
+
                 return tsCollider.Body.TSAngularVelocity;
             }

             set {
-                tsCollider.Body.TSAngularVelocity = value;
+//                tsCollider.Body.TSAngularVelocity = value;
+//                return;
+
+                //如果传入的velocity的值大于设定的值，则将设置为上一次设置的值。
+                if(value.magnitude > MaxAngularVelocity)
+                {
+                    tsCollider.Body.TSAngularVelocity = previousAngularVelocity;
+                }else
+                {//否则将传入的值设置上
+                    tsCollider.Body.TSAngularVelocity = value;
+                }
+                //缓存设置的值，为下次准备。
+                previousAngularVelocity = tsCollider.Body.TSAngularVelocity;
             }
         }


Added test for arg null check on package manager

--HG--
extra : rebase_source : c9bc648ca8308ceb233a54b1f2dfbfe4ea0e3d7b

--- NuPack.Test/PackageManagerTest.cs
+++ NuPack.Test/PackageManagerTest.cs
@@ -9,6 +9,15 @@
     [TestClass]
     public class PackageManagerTest {
         [TestMethod]
+        public void CtorThrowsIfDependenciesAreNull() {
+            // Act & Assert
+            ExceptionAssert.ThrowsArgNull(() => new PackageManager(null, new DefaultPackagePathResolver("foo"), new MockProjectSystem(), new MockPackageRepository()), "sourceRepository");
+            ExceptionAssert.ThrowsArgNull(() => new PackageManager(new MockPackageRepository(), null, new MockProjectSystem(), new MockPackageRepository()), "pathResolver");
+            ExceptionAssert.ThrowsArgNull(() => new PackageManager(new MockPackageRepository(), new DefaultPackagePathResolver("foo"), null, new MockPackageRepository()), "fileSystem");
+            ExceptionAssert.ThrowsArgNull(() => new PackageManager(new MockPackageRepository(), new DefaultPackagePathResolver("foo"), new MockProjectSystem(), null), "localRepository");
+        }
+
+        [TestMethod]
         public void InstallingPackageWithUnknownDependencyAndIgnoreDepencenciesInstallsPackageWithoutDependencies() {
             // Arrange
             var localRepository = new MockPackageRepository();


bugfix

bugfix

--- LatencyCollectorService/LatencyCollectorService.cs
+++ LatencyCollectorService/LatencyCollectorService.cs
@@ -38,10 +38,20 @@
 		{
 			lock (_sync)
 			{
-				_terminated = true;
-				_thread.Interrupt();
-				_thread.Join();
-				_thread = null;
+				try
+				{
+					_terminated = true;
+					_thread.Abort();
+
+					StopWorkerDomain();
+
+					_thread.Join();
+					_thread = null;
+				}
+				catch (Exception exc)
+				{
+					WriteEventLog(exc.ToString(), EventLogEntryType.Warning);
+				}
 			}
 		}

@@ -57,29 +67,20 @@
 						if (_appDomain == null)
 							StartWorkerDomain(Const.WorkerAssemblyPath);
 					}
-					catch (ThreadInterruptedException)
+					catch (ThreadAbortException)
 					{
 						break;
 					}
 					catch (Exception exc)
 					{
-						WriteEventLog(exc.ToString());
+						WriteEventLog(exc.ToString(), EventLogEntryType.Warning);
 					}

 					Thread.Sleep(AutoUpdateCheckPeriod);
 				}
 			}
-			catch (ThreadInterruptedException)
+			catch (ThreadAbortException)
 			{
-			}
-
-			try
-			{
-				StopWorkerDomain();
-			}
-			catch (Exception exc)
-			{
-				WriteEventLog(exc.ToString());
 			}
 		}

@@ -150,14 +151,14 @@
 			return appDomain;
 		}

-		public void WriteEventLog(string message)
+		public void WriteEventLog(string message, EventLogEntryType type = EventLogEntryType.Information)
 		{
 			Trace.WriteLine(message);

 			try
 			{
 				var appId = this.ServiceName;
-				EventLog.WriteEntry(appId, message, EventLogEntryType.Information);
+				EventLog.WriteEntry(appId, message, type);
 			}
 			catch (Exception exc)
 			{


Added unit test for parsing ENVELOPEs with routed mailboxes

--- UnitTests/Net/Imap/ImapUtilsTests.cs
+++ UnitTests/Net/Imap/ImapUtilsTests.cs
@@ -398,6 +398,34 @@
 		}

 		[Test]
+		public void TestParseEnvelopeWithRoutedMailboxes ()
+		{
+			const string text = "(\"Mon, 13 Jul 2015 21:15:32 -0400\" \"Test message\" ((\"Example From\" \"@route1,@route2\" \"from\" \"example.com\")) ((\"Example Sender\" NIL \"sender\" \"example.com\")) ((\"Example Reply-To\" NIL \"reply-to\" \"example.com\")) ((NIL NIL \"boys\" NIL)(NIL NIL \"aaron\" \"MISSING_DOMAIN\")(NIL NIL \"jeff\" \"MISSING_DOMAIN\")(NIL NIL \"zach\" \"MISSING_DOMAIN\")(NIL NIL NIL NIL)(NIL NIL \"girls\" NIL)(NIL NIL \"alice\" \"MISSING_DOMAIN\")(NIL NIL \"hailey\" \"MISSING_DOMAIN\")(NIL NIL \"jenny\" \"MISSING_DOMAIN\")(NIL NIL NIL NIL)) NIL NIL NIL \"<MV4F9T0FLVT4.2CZLZPO4HZ8B3@Jeffreys-MacBook-Air.local>\")";
+
+			using (var memory = new MemoryStream (Encoding.ASCII.GetBytes (text), false)) {
+				using (var tokenizer = new ImapStream (memory, null, new NullProtocolLogger ())) {
+					using (var engine = new ImapEngine (null)) {
+						Envelope envelope;
+
+						engine.SetStream (tokenizer);
+
+						try {
+							envelope = ImapUtils.ParseEnvelopeAsync (engine, false, CancellationToken.None).GetAwaiter ().GetResult ();
+						} catch (Exception ex) {
+							Assert.Fail ("Parsing ENVELOPE failed: {0}", ex);
+							return;
+						}
+
+						Assert.AreEqual ("\"Example Sender\" <sender@example.com>", envelope.Sender.ToString ());
+						Assert.AreEqual ("\"Example From\" <@route1,@route2:from@example.com>", envelope.From.ToString ());
+						Assert.AreEqual ("\"Example Reply-To\" <reply-to@example.com>", envelope.ReplyTo.ToString ());
+						Assert.AreEqual ("boys: aaron, jeff, zach;, girls: alice, hailey, jenny;", envelope.To.ToString ());
+					}
+				}
+			}
+		}
+
+		[Test]
 		public void TestParseDovcotEnvelopeWithGroupAddresses ()
 		{
 			const string text = "(\"Mon, 13 Jul 2015 21:15:32 -0400\" \"Test message\" ((\"Example From\" NIL \"from\" \"example.com\")) ((\"Example Sender\" NIL \"sender\" \"example.com\")) ((\"Example Reply-To\" NIL \"reply-to\" \"example.com\")) ((NIL NIL \"boys\" NIL)(NIL NIL \"aaron\" \"MISSING_DOMAIN\")(NIL NIL \"jeff\" \"MISSING_DOMAIN\")(NIL NIL \"zach\" \"MISSING_DOMAIN\")(NIL NIL NIL NIL)(NIL NIL \"girls\" NIL)(NIL NIL \"alice\" \"MISSING_DOMAIN\")(NIL NIL \"hailey\" \"MISSING_DOMAIN\")(NIL NIL \"jenny\" \"MISSING_DOMAIN\")(NIL NIL NIL NIL)) NIL NIL NIL \"<MV4F9T0FLVT4.2CZLZPO4HZ8B3@Jeffreys-MacBook-Air.local>\")";


Correction affichage vitesse, calcul acceleration douteux

--- Assets/Systems/MonitorTextSystem.cs
+++ Assets/Systems/MonitorTextSystem.cs
@@ -30,10 +30,11 @@

 			m.frameCount += 1;

-
-
-			float speed = Vector3.Distance (m.target.transform.position, m.lastPosition) / Time.deltaTime * 3.6f;
-			float g = Time.deltaTime * (speed - m.lastSpeed) * 3.6f * 9.81f * 2f;
+			float speed = m.lastSpeed;
+			if (Vector3.Distance (m.target.transform.position, m.lastPosition) > 0) {
+				speed = Vector3.Distance (m.target.transform.position, m.lastPosition) * 3.6f / Time.deltaTime;
+			}
+			float g = Time.deltaTime * (speed - m.lastSpeed) * 3.6f * 9.81f * 2f; // Calcul douteux
 			float alt = Vector3.Distance (new Vector3 (0f, -6371000, 0f), m.target.transform.position);
 			alt -= 6371000;
 			m.lastPosition = m.target.transform.position;


hack to fix giant leaf bug

hack to fix giant leaf bug

--- Awesome-Game/Assets/Scripts/Leaf.cs
+++ Awesome-Game/Assets/Scripts/Leaf.cs
@@ -14,9 +14,12 @@
             y = -0.001f;
         else
             y = 0.001f;
+        this.transform.localScale = new Vector3(x * 100, y * 100, 1);
     }

 	void FixedUpdate () {
         this.transform.localScale += new Vector3(x, y, 0);
 	}
+
+
 }


fix point rendering in desktop

fix point rendering in desktop

--- BCad/UI/View/XamlRenderer.Shared.cs
+++ BCad/UI/View/XamlRenderer.Shared.cs
@@ -34,6 +34,7 @@
 {
     public partial class XamlRenderer : UserControl
     {
+        private const double PointSize = 15.0;
         private IWorkspace Workspace;
         private Matrix4 PlaneProjection;
         private BindingClass BindObject = new BindingClass();
@@ -53,7 +54,7 @@
                 }
             }

-            private ScaleTransform scale = new ScaleTransform(1.0, 1.0);
+            private ScaleTransform scale = new ScaleTransform() { ScaleX = 1.0, ScaleY = 1.0 };
             public ScaleTransform Scale
             {
                 get { return scale; }
@@ -162,7 +163,7 @@
             t.Children.Add(new TranslateTransform() { X = 0, Y = Workspace.ViewControl.DisplayHeight });
             this.PrimitiveCanvas.RenderTransform = t;
             BindObject.Thickness = 1.0 / scale;
-            BindObject.Scale = new ScaleTransform() { ScaleX = scale, ScaleY = scale };
+            BindObject.Scale = new ScaleTransform() { ScaleX = PointSize / scale, ScaleY = PointSize / scale };
         }

         private void BeginInvoke(Action action)
@@ -195,7 +196,7 @@

         private void AddPrimitive(IPrimitive prim, IndexedColor color, Entity containingEntity)
         {
-            FrameworkElement element;
+            FrameworkElement element = null;
             switch (prim.Kind)
             {
                 case PrimitiveKind.Ellipse:
@@ -214,8 +215,11 @@
                     throw new NotImplementedException();
             }

-            element.Tag = containingEntity;
-            PrimitiveCanvas.Children.Add(element);
+            if (element != null)
+            {
+                element.Tag = containingEntity;
+                PrimitiveCanvas.Children.Add(element);
+            }
         }

         private Shape CreatePrimitiveEllipse(PrimitiveEllipse ellipse, IndexedColor color)
@@ -295,7 +299,7 @@

         private Path CreatePrimitivePoint(PrimitivePoint point, IndexedColor color)
         {
-            const int size = 15;
+            const double size = 0.5;
             var loc = PlaneProjection.Transform(point.Location);
             var path = new Path()
             {
@@ -309,35 +313,34 @@
                             {
                                 new PathFigure()
                                 {
-                                    StartPoint = new DisplayPoint(loc.X - size, loc.Y),
+                                    StartPoint = new DisplayPoint(-size, 0.0),
                                     Segments = new PathSegmentCollection()
                                     {
                                         new LineSegment()
                                         {
-                                            Point = new DisplayPoint(loc.X + size, loc.Y)
+                                            Point = new DisplayPoint(size, 0.0)
                                         }
                                     }
                                 },
                                 new PathFigure()
                                 {
-                                    StartPoint = new DisplayPoint(loc.X, loc.Y - size),
+                                    StartPoint = new DisplayPoint(0.0, -size),
                                     Segments = new PathSegmentCollection()
                                     {
                                         new LineSegment()
                                         {
-                                            Point = new DisplayPoint(loc.X, loc.Y + size)
+                                            Point = new DisplayPoint(0.0, size)
                                         }
                                     }
                                 },
                             }
                         }
                     }
-                }
+                },
+                RenderTransform = new TranslateTransform() { X = loc.X, Y = loc.Y },
+                StrokeThickness = 1.0 / PointSize
             };
-            SetThicknessBinding(path);
-            //SetBinding(path, "Scale", Shape.LayoutTransformProperty);
-            //SetBinding(path, "PointThickness", Shape.StrokeThicknessProperty);
-            //SetBinding(path, "PointScale", Shape.RenderTransformProperty);
+            SetBinding(path, "Scale", Path.LayoutTransformProperty);
             SetColorBinding(path, color);
             return path;
         }
@@ -367,11 +370,11 @@
             return primitiveColor.IsAuto ? layerColor : primitiveColor;
         }

-        private void SetBinding(FrameworkElement element, string propertyName, DependencyProperty property)
+        private void SetBinding(DependencyObject element, string propertyName, DependencyProperty property)
         {
             var binding = new Binding() { Path = new PropertyPath(propertyName) };
             binding.Source = BindObject;
-            element.SetBinding(property, binding);
+            BindingOperations.SetBinding(element, property, binding);
         }

         private void SetThicknessBinding(Shape shape)


Make `Http` readonly

Make `Http` readonly

--- code/Update.cs
+++ code/Update.cs
@@ -28,7 +28,7 @@
 		/// <summary>
 		/// Http client used to check for updates
 		/// </summary>
-		private HttpClient Http = new HttpClient();
+		private readonly HttpClient Http = new HttpClient();

 		/// <summary>
 		/// Reference to the main interface


Remove the null check.

Remove the null check.

--- osu.Desktop/Updater/SquirrelUpdateManager.cs
+++ osu.Desktop/Updater/SquirrelUpdateManager.cs
@@ -152,7 +152,7 @@
                 Activated = () =>
                 {
                     updateManager.PrepareUpdateAsync()
-                                 .ContinueWith(_ => updateManager.Schedule(() => game?.AttemptExit()));
+                                 .ContinueWith(_ => updateManager.Schedule(() => game.AttemptExit()));
                     return true;
                 };
             }


XDoc: added Become(XDoc) method

XDoc: added Become(XDoc) method

--- src/mindtouch.dream/Xml/XDoc.cs
+++ src/mindtouch.dream/Xml/XDoc.cs
@@ -1876,6 +1876,19 @@
         }

         /// <summary>
+        /// Make this XDoc instance become equivalent to the supplied one.
+        /// </summary>
+        /// <param name="doc"></param>
+        public void Become(XDoc doc) {
+            _doc = doc._doc;
+            _root = doc._root;
+            _list = doc._list;
+            _index = doc._index;
+            _nsManager = doc._nsManager;
+            _exclusive = doc._exclusive;
+        }
+
+        /// <summary>
         /// Replaces this XDoc instance with another one.
         /// </summary>
         /// <param name="doc">Replacement XDoc instance.</param>


Make window render to the cutout areas of android devices

--- osu.Framework.Android/AndroidGameActivity.cs
+++ osu.Framework.Android/AndroidGameActivity.cs
@@ -55,6 +55,9 @@
                 }
             };

+            if (Build.VERSION.SdkInt >= BuildVersionCodes.P)
+                Window.Attributes.LayoutInDisplayCutoutMode = LayoutInDisplayCutoutMode.ShortEdges;
+
             gameView.HostStarted += host =>
             {
                 host.AllowScreenSuspension.BindValueChanged(allow =>


Improve ISampleChannel.Play's xmldoc

Improve ISampleChannel.Play's xmldoc

--- osu.Framework/Audio/Sample/ISampleChannel.cs
+++ osu.Framework/Audio/Sample/ISampleChannel.cs
@@ -1,5 +1,7 @@
 // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
 // See the LICENCE file in the repository root for full licence text.
+
+using osu.Framework.Audio.Track;

 namespace osu.Framework.Audio.Sample
 {
@@ -9,7 +11,8 @@
     public interface ISampleChannel : IHasAmplitudes
     {
         /// <summary>
-        /// Start playback.
+        /// Start a new playback of this sample.
+        /// Note that this will not stop previous playbacks (but concurrency will be limited by the source <see cref="ISampleStore.PlaybackConcurrency"/>.
         /// </summary>
         /// <param name="restart">Whether to restart the sample from the beginning.</param>
         void Play(bool restart = true);


Fix CI issues

Fix CI issues

--- osu.Framework/Graphics/Video/VideoDecoder.cs
+++ osu.Framework/Graphics/Video/VideoDecoder.cs
@@ -105,13 +105,13 @@
             decoderCommands = new ConcurrentQueue<Action>();
         }

-        private int readPacket(void* opaque, byte* buf, int buf_size)
-        {
-            if (buf_size != managedContextBuffer.Length)
-                managedContextBuffer = new byte[buf_size];
-
-            var bytesRead = videoStream.Read(managedContextBuffer, 0, buf_size);
-            Marshal.Copy(managedContextBuffer, 0, (IntPtr)buf, bytesRead);
+        private int readPacket(void* opaque, byte* bufferPtr, int bufferSize)
+        {
+            if (bufferSize != managedContextBuffer.Length)
+                managedContextBuffer = new byte[bufferSize];
+
+            var bytesRead = videoStream.Read(managedContextBuffer, 0, bufferSize);
+            Marshal.Copy(managedContextBuffer, 0, (IntPtr)bufferPtr, bytesRead);
             return bytesRead;
         }


Fix wrong ordering

Fix wrong ordering

--- osu.Game.Rulesets.Catch/UI/CatchPlayfield.cs
+++ osu.Game.Rulesets.Catch/UI/CatchPlayfield.cs
@@ -51,8 +51,8 @@

             comboDisplay = new CatchComboDisplay
             {
+                RelativeSizeAxes = Axes.None,
                 AutoSizeAxes = Axes.Both,
-                RelativeSizeAxes = Axes.None,
                 Anchor = Anchor.CentreLeft,
                 Origin = Anchor.Centre,
                 Y = 30f,


Made the Chat testcase include a beatmapsetoverlay so links can be clicked from in there. Also had to implement private DI to make it work

--- osu.Game.Tests/Visual/TestCaseChatDisplay.cs
+++ osu.Game.Tests/Visual/TestCaseChatDisplay.cs
@@ -2,7 +2,9 @@
 // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE

 using System.ComponentModel;
+using osu.Framework.Allocation;
 using osu.Framework.Graphics.Containers;
+using osu.Game.Online.API;
 using osu.Game.Overlays;

 namespace osu.Game.Tests.Visual
@@ -10,12 +12,26 @@
     [Description("Testing chat api and overlay")]
     internal class TestCaseChatDisplay : OsuTestCase
     {
+        private BeatmapSetOverlay beatmapSetOverlay;
+
+        private DependencyContainer dependencies;
+
+        protected override IReadOnlyDependencyContainer CreateLocalDependencies(IReadOnlyDependencyContainer parent) => dependencies = new DependencyContainer(parent);
+
         public TestCaseChatDisplay()
         {
             Add(new ChatOverlay
             {
                 State = Visibility.Visible
             });
+
+            Add(beatmapSetOverlay = new BeatmapSetOverlay());
+        }
+
+        [BackgroundDependencyLoader]
+        private void load()
+        {
+            dependencies.Cache(beatmapSetOverlay);
         }
     }
 }


Add null-permissive operator to manager back

--- osu.Game/Online/DownloadTrackingComposite.cs
+++ osu.Game/Online/DownloadTrackingComposite.cs
@@ -80,7 +80,7 @@
         /// By default, this calls <see cref="IModelDownloader{TModel}.IsAvailableLocally"/>,
         /// but can be overriden to add additional checks for verifying the model in database.
         /// </summary>
-        protected virtual bool IsModelAvailableLocally() => Manager.IsAvailableLocally(Model.Value);
+        protected virtual bool IsModelAvailableLocally() => Manager?.IsAvailableLocally(Model.Value) == true;

         private void downloadBegan(ValueChangedEvent<WeakReference<ArchiveDownloadRequest<TModel>>> weakRequest)
         {


move colour provider to BDL

move colour provider to BDL

--- osu.Game/Overlays/Wiki/WikiPanelContainer.cs
+++ osu.Game/Overlays/Wiki/WikiPanelContainer.cs
@@ -21,9 +21,6 @@
 {
     public class WikiPanelContainer : Container
     {
-        [Resolved]
-        private OverlayColourProvider colourProvider { get; set; }
-
         private WikiPanelMarkdownContainer panelContainer;

         public string Text;
@@ -37,7 +34,7 @@
         }

         [BackgroundDependencyLoader]
-        private void load()
+        private void load(OverlayColourProvider colourProvider)
         {
             Children = new Drawable[]
             {


Simplify control point group binding/update logic

--- osu.Game/Screens/Edit/Timing/TimingScreen.cs
+++ osu.Game/Screens/Edit/Timing/TimingScreen.cs
@@ -63,7 +63,7 @@
             private OsuButton deleteButton;
             private ControlPointTable table;

-            private IBindableList<ControlPointGroup> controlGroups;
+            private BindableList<ControlPointGroup> controlGroups;

             [Resolved]
             private EditorClock clock { get; set; }
@@ -128,12 +128,14 @@

                 selectedGroup.BindValueChanged(selected => { deleteButton.Enabled.Value = selected.NewValue != null; }, true);

-                controlGroups = Beatmap.Value.Beatmap.ControlPointInfo.Groups.GetBoundCopy();
-                controlGroups.CollectionChanged += (sender, args) => createContent();
-                createContent();
+                // todo: remove cast after https://github.com/ppy/osu-framework/pull/3906 is merged
+                controlGroups = (BindableList<ControlPointGroup>)Beatmap.Value.Beatmap.ControlPointInfo.Groups.GetBoundCopy();
+
+                controlGroups.BindCollectionChanged((sender, args) =>
+                {
+                    table.ControlGroups = controlGroups;
+                }, true);
             }
-
-            private void createContent() => table.ControlGroups = controlGroups;

             private void delete()
             {


Add colon parsing support in search length criteria

--- osu.Game/Screens/Select/FilterQueryParser.cs
+++ osu.Game/Screens/Select/FilterQueryParser.cs
@@ -312,9 +312,25 @@

         private static bool tryUpdateLengthRange(FilterCriteria criteria, Operator op, string val)
         {
+            if (val.Contains(':'))
+            {
+                if (val.Contains('h') || val.Contains('m') || val.Contains('s'))
+                    return false;
+
+                int count = val.Count(c => c == ':');
+                if (count > 3)
+                    return false;
+
+                if (count > 2)
+                    val = val.Replace(':', 'h');
+
+                val = val.Replace(':', 'm');
+            }
+
             string[] parts = Regex.Split(val, @"(?<=[msh])").Where(x => x.Length > 0).ToArray();
             double totalLength = 0;
             int minScale = 1000;
+
             foreach (string part in parts)
             {
                 if (!tryParseDoubleWithPoint(part.TrimEnd('m', 's', 'h'), out double length))
@@ -323,6 +339,7 @@
                 totalLength += length * scale;
                 minScale = Math.Min(minScale, scale);
             }
+
             return tryUpdateCriteriaRange(ref criteria.Length, op, totalLength, minScale / 2.0);
         }
     }


Fix potentially starting play when finished

The UserFinishedPlaying event may trigger before the event is subscribed
to by SpectatorScreen. For such cases, an extra check is done to make
sure the user is _actually_ playing.

--- osu.Game/Screens/Spectate/SpectatorScreen.cs
+++ osu.Game/Screens/Spectate/SpectatorScreen.cs
@@ -127,6 +127,10 @@
                 if (!userMap.ContainsKey(userId))
                     return;

+                // The user may have stopped playing.
+                if (!spectatorClient.TryGetPlayingUserState(userId, out _))
+                    return;
+
                 Schedule(() => OnUserStateChanged(userId, state));

                 updateGameplayState(userId);


Clean up previous sample immediately on skin source change to avoid `Play` after disposal

This seems to be the simplest way to avoid calls to `Play` after the
underlying sample may have been disposed. As per the issue thread, a
local workaround is acceptable here.

Closes #13223.

--- osu.Game/Skinning/PoolableSkinnableSample.cs
+++ osu.Game/Skinning/PoolableSkinnableSample.cs
@@ -2,6 +2,7 @@
 // See the LICENCE file in the repository root for full licence text.

 using System;
+using System.Linq;
 using JetBrains.Annotations;
 using osu.Framework.Allocation;
 using osu.Framework.Audio;
@@ -70,21 +71,47 @@
                 updateSample();
         }

+        protected override void LoadComplete()
+        {
+            base.LoadComplete();
+
+            CurrentSkin.SourceChanged += skinChangedImmediate;
+        }
+
+        private void skinChangedImmediate()
+        {
+            // Clean up the previous sample immediately on a source change.
+            // This avoids a potential call to Play() of an already disposed sample (samples are disposed along with the skin, but SkinChanged is scheduled).
+            clearPreviousSamples();
+        }
+
         protected override void SkinChanged(ISkinSource skin, bool allowFallback)
         {
             base.SkinChanged(skin, allowFallback);
             updateSample();
         }

+        /// <summary>
+        /// Whether this sample was playing before a skin source change.
+        /// </summary>
+        private bool wasPlaying;
+
+        private void clearPreviousSamples()
+        {
+            // only run if the samples aren't already cleared.
+            // this ensures the "wasPlaying" state is stored correctly even if multiple clear calls are executed.
+            if (!sampleContainer.Any()) return;
+
+            wasPlaying = Playing;
+
+            sampleContainer.Clear();
+            Sample = null;
+        }
+
         private void updateSample()
         {
             if (sampleInfo == null)
                 return;
-
-            bool wasPlaying = Playing;
-
-            sampleContainer.Clear();
-            Sample = null;

             var sample = CurrentSkin.GetSample(sampleInfo);

@@ -155,6 +182,13 @@
             }
         }

+        protected override void Dispose(bool isDisposing)
+        {
+            base.Dispose(isDisposing);
+
+            CurrentSkin.SourceChanged -= skinChangedImmediate;
+        }
+
         #region Re-expose AudioContainer

         public BindableNumber<double> Volume => sampleContainer.Volume;


cleaned for publication

cleaned for publication

--- BuildingCoder/BuildingCoder/Util.cs
+++ BuildingCoder/BuildingCoder/Util.cs
@@ -1264,14 +1264,14 @@
   public static class CompatibilityMethods
   {
     #region Autodesk.Revit.DB.Curve
-    public static XYZ GetPoint2(
+    public static XYZ GetPoint2(
       this Curve curva,
       int i )
     {
       XYZ value = null;

-      MethodInfo met = curva.GetType().GetMethod(
-        "GetEndPoint",
+      MethodInfo met = curva.GetType().GetMethod(
+        "GetEndPoint",
         new Type[] { typeof( int ) } );

       if( met == null )
@@ -1281,19 +1281,19 @@
           new Type[] { typeof( int ) } );
       }

-      value = met.Invoke( curva, new object[] { i } )
+      value = met.Invoke( curva, new object[] { i } )
         as XYZ;
-
+
       return value;
     }
     #endregion // Autodesk.Revit.DB.Curve

     #region Autodesk.Revit.DB.Definitions
-    public static Definition Create2(
-      this Definitions definitions,
-      Document doc,
+    public static Definition Create2(
+      this Definitions definitions,
+      Document doc,
       string nome,
-      ParameterType tipo,
+      ParameterType tipo,
       bool visibilidade )
     {
       Definition value = null;
@@ -1305,22 +1305,22 @@
         Type t = ls[0];
         ConstructorInfo c = t
         .GetConstructor( new Type[] { typeof(string),
-                 typeof(ParameterType) } );
+                typeof(ParameterType) } );
         object ed = c
         .Invoke( new object[] { nome, tipo } );
         ed.GetType().GetProperty( "Visible" )
         .SetValue( ed, visibilidade, null );
         value = definitions.GetType()
         .GetMethod( "Create", new Type[] { t } ).Invoke( definitions,
-         new object[] { ed } ) as Definition;
+          new object[] { ed } ) as Definition;
       }
       else
       {
         value = definitions.GetType()
         .GetMethod( "Create", new Type[] { typeof(string),
-                 typeof(ParameterType), typeof(bool) } ).Invoke( definitions,
-         new object[] { nome, tipo,
-                 visibilidade } ) as Definition;
+                typeof(ParameterType), typeof(bool) } ).Invoke( definitions,
+          new object[] { nome, tipo,
+                visibilidade } ) as Definition;
       }
       return value;
     }
@@ -1337,7 +1337,7 @@
         met = doc.GetType()
         .GetMethod( "GetElement", new Type[] { typeof( ElementId ) } );
       value = met.Invoke( doc,
-       new object[] { id } ) as Element;
+        new object[] { id } ) as Element;
       return value;
     }
     public static Element GetElement2( this Document
@@ -1348,27 +1348,27 @@
       return value;
     }
     public static Line CreateLine2( this Document doc,
-     XYZ p1, XYZ p2, bool bound = true )
+      XYZ p1, XYZ p2, bool bound = true )
     {
       Line value = null;
       object[] parametros = new object[] { p1,
-             p2 };
+            p2 };
       Type[] tipos = parametros.Select( a => a
       .GetType() ).ToArray();
       string metodo = "CreateBound";
       if( bound == false ) metodo =
-       "CreateUnbound";
+        "CreateUnbound";
       MethodInfo met = typeof( Line )
       .GetMethod( metodo, tipos );
       if( met != null )
       {
         value = met.Invoke( null,
-         parametros ) as Line;
+          parametros ) as Line;
       }
       else
       {
         parametros = new object[] { p1, p2,
-                 bound };
+                bound };
         tipos = parametros.Select( a => a
         .GetType() ).ToArray();
         value = doc.Application.Create
@@ -1378,14 +1378,14 @@
       return value;
     }
     public static Wall CreateWall2( this Document doc,
-     Curve curve, ElementId wallTypeId,
-     ElementId levelId, double height, double offset, bool flip,
-     bool structural )
+      Curve curve, ElementId wallTypeId,
+      ElementId levelId, double height, double offset, bool flip,
+      bool structural )
     {
       Wall value = null;
       object[] parametros = new object[] { doc,
-             curve, wallTypeId, levelId, height, offset, flip,
-             structural };
+            curve, wallTypeId, levelId, height, offset, flip,
+            structural };
       Type[] tipos = parametros.Select( a => a
       .GetType() ).ToArray();
       MethodInfo met = typeof( Wall )
@@ -1393,28 +1393,28 @@
       if( met != null )
       {
         value = met.Invoke( null,
-         parametros ) as Wall;
+          parametros ) as Wall;
       }
       else
       {
         parametros = new object[] { curve,
-                 (WallType)doc.GetElement2(wallTypeId), (Level)doc
-                .GetElement2(levelId), height, offset, flip,
-                 structural };
+                (WallType)doc.GetElement2(wallTypeId), (Level)doc
+              .GetElement2(levelId), height, offset, flip,
+                structural };
         tipos = parametros.Select( a => a
         .GetType() ).ToArray();
         value = doc.Create.GetType()
         .GetMethod( "NewWall", tipos ).Invoke( doc.Create,
-         parametros ) as Wall;
+          parametros ) as Wall;
       }
       return value;
     }
     public static Arc CreateArc2( this Document doc,
-     XYZ p1, XYZ p2, XYZ p3 )
+      XYZ p1, XYZ p2, XYZ p3 )
     {
       Arc value = null;
       object[] parametros = new object[] { p1,
-             p2, p3 };
+            p2, p3 };
       Type[] tipos = parametros.Select( a => a
       .GetType() ).ToArray();
       string metodo = "Create";
@@ -1423,7 +1423,7 @@
       if( met != null )
       {
         value = met.Invoke( null,
-         parametros ) as Arc;
+          parametros ) as Arc;
       }
       else
       {
@@ -1434,7 +1434,7 @@
       return value;
     }
     public static char GetDecimalSymbol2( this
-    Document doc )
+  Document doc )
     {
       char valor = ',';
       MethodInfo met = doc.GetType()
@@ -1471,7 +1471,7 @@
       .GetTypes().Where( a => a.IsClass && a
       .Name == "JoinGeometryUtils" ).ToList();
       object[] parametros = new object[] { doc,
-             firstElement, secondElement };
+            firstElement, secondElement };
       Type[] tipos = parametros.Select( a => a
       .GetType() ).ToArray();
       if( ls.Count > 0 )
@@ -1489,7 +1489,7 @@
       .GetTypes().Where( a => a.IsClass && a
       .Name == "JoinGeometryUtils" ).ToList();
       object[] parametros = new object[] { doc,
-             firstElement, secondElement };
+            firstElement, secondElement };
       Type[] tipos = parametros.Select( a => a
       .GetType() ).ToArray();
       if( ls.Count > 0 )
@@ -1501,14 +1501,14 @@
       }
     }
     public static bool IsJoined2( this Document doc,
-     Element firstElement, Element secondElement )
+      Element firstElement, Element secondElement )
     {
       bool value = false;
       List<Type> ls = doc.GetType().Assembly
       .GetTypes().Where( a => a.IsClass && a
       .Name == "JoinGeometryUtils" ).ToList();
       object[] parametros = new object[] { doc,
-             firstElement, secondElement };
+            firstElement, secondElement };
       Type[] tipos = parametros.Select( a => a
       .GetType() ).ToArray();
       if( ls.Count > 0 )
@@ -1517,12 +1517,12 @@
         MethodInfo met = t
         .GetMethod( "AreElementsJoined", tipos );
         value = (bool) met.Invoke( null,
-         parametros );
+          parametros );
       }
       return value;
     }
     public static bool CalculateVolumeArea2( this
-    Document doc, bool value )
+  Document doc, bool value )
     {
       List<Type> ls = doc.GetType().Assembly
       .GetTypes().Where( a => a.IsClass && a
@@ -1531,13 +1531,13 @@
       {
         Type t = ls[0];
         object[] parametros = new object[] {
-                doc };
+              doc };
         Type[] tipos = parametros
         .Select( a => a.GetType() ).ToArray();
         MethodInfo met = t
         .GetMethod( "GetAreaVolumeSettings", tipos );
         object temp = met.Invoke( null,
-         parametros );
+          parametros );
         temp.GetType()
         .GetProperty( "ComputeVolumes" ).SetValue( temp, value, null );
       }
@@ -1579,12 +1579,12 @@
         met = obj.GetType()
         .GetMethod( "NewGroup", new Type[] { eleset.GetType() } );
         met.Invoke( obj,
-         new object[] { eleset } );
+          new object[] { eleset } );
       }
       return value;
     }
     public static void Delete2( this Document doc,
-     Element ele )
+      Element ele )
     {
       object obj = doc;
       MethodInfo met = obj.GetType()
@@ -1598,7 +1598,7 @@
         met = obj.GetType()
         .GetMethod( "Delete", new Type[] { typeof( ElementId ) } );
         met.Invoke( obj, new object[] { ele
-                .Id } );
+              .Id } );
       }
     }
     #endregion // Autodesk.Revit.DB.Document
@@ -1618,7 +1618,7 @@
       return value;
     }
     public static List<Material> Materiais2( this
-    Element ele )
+  Element ele )
     {
       List<Material> value = new List<Material>();
       Document doc = ele.Document;
@@ -1638,7 +1638,7 @@
       return value;
     }
     public static Parameter GetParameter2( this
-    Element ele, string nome_paramentro )
+  Element ele, string nome_paramentro )
     {
       Parameter value = null;
       Type t = ele.GetType();
@@ -1646,9 +1646,9 @@
       .GetMethod( "LookupParameter", new Type[] { typeof( string ) } );
       if( met == null )
         met = t.GetMethod( "get_Parameter",
-         new Type[] { typeof( string ) } );
+          new Type[] { typeof( string ) } );
       value = met.Invoke( ele,
-       new object[] { nome_paramentro } ) as Parameter;
+        new object[] { nome_paramentro } ) as Parameter;
       if( value == null )
       {
         var pas = ele.Parameters
@@ -1662,7 +1662,7 @@
       return value;
     }
     public static Parameter GetParameter2( this
-    Element ele, BuiltInParameter builtInParameter )
+  Element ele, BuiltInParameter builtInParameter )
     {
       Parameter value = null;
       Type t = ele.GetType();
@@ -1670,52 +1670,52 @@
       .GetMethod( "LookupParameter", new Type[] { typeof( BuiltInParameter ) } );
       if( met == null )
         met = t.GetMethod( "get_Parameter",
-         new Type[] { typeof( BuiltInParameter ) } );
+          new Type[] { typeof( BuiltInParameter ) } );
       value = met.Invoke( ele,
-       new object[] { builtInParameter } ) as Parameter;
+        new object[] { builtInParameter } ) as Parameter;
       return value;
     }
     public static double GetMaterialArea2( this
-    Element ele, Material m )
+  Element ele, Material m )
     {
       double value = 0;
       Type t = ele.GetType();
       MethodInfo met = t
       .GetMethod( "GetMaterialArea", new Type[] { typeof(ElementId),
-             typeof(bool) } );
+            typeof(bool) } );
       if( met != null )
       {
         value = (double) met.Invoke( ele,
-         new object[] { m.Id, false } );
+          new object[] { m.Id, false } );
       }
       else
       {
         met = t.GetMethod( "GetMaterialArea",
-         new Type[] { typeof( Element ) } );
+          new Type[] { typeof( Element ) } );
         value = (double) met.Invoke( ele,
-         new object[] { m } );
+          new object[] { m } );
       }
       return value;
     }
     public static double GetMaterialVolume2( this
-    Element ele, Material m )
+  Element ele, Material m )
     {
       double value = 0;
       Type t = ele.GetType();
       MethodInfo met = t
       .GetMethod( "GetMaterialVolume", new Type[] { typeof(ElementId),
-             typeof(bool) } );
+            typeof(bool) } );
       if( met != null )
       {
         value = (double) met.Invoke( ele,
-         new object[] { m.Id, false } );
+          new object[] { m.Id, false } );
       }
       else
       {
         met = t
         .GetMethod( "GetMaterialVolume", new Type[] { typeof( ElementId ) } );
         value = (double) met.Invoke( ele,
-         new object[] { m.Id } );
+          new object[] { m.Id } );
       }
       return value;
     }
@@ -1752,7 +1752,7 @@

     #region Autodesk.Revit.DB.FamilySymbol
     public static void EnableFamilySymbol2( this
-    FamilySymbol fsymbol )
+  FamilySymbol fsymbol )
     {
       MethodInfo met = fsymbol.GetType()
       .GetMethod( "Activate" );
@@ -1765,10 +1765,10 @@

     #region Autodesk.Revit.DB.InternalDefinition
     public static void VaryGroup2( this
-    InternalDefinition def, Document doc )
+  InternalDefinition def, Document doc )
     {
       object[] parametros = new object[] { doc,
-             true };
+            true };
       Type[] tipos = parametros.Select( a => a
       .GetType() ).ToArray();
       MethodInfo met = def.GetType()
@@ -1788,7 +1788,7 @@
       .GetProperty( "OriginalDividedElementId" );
       if( prop != null )
         value = prop.GetValue( part,
-         null ) as ElementId;
+          null ) as ElementId;
       else
       {
         MethodInfo met = part.GetType()
@@ -1800,7 +1800,7 @@
         prop = temp.GetType()
         .GetProperty( "HostElementId" );
         value = prop.GetValue( temp,
-         null ) as ElementId;
+          null ) as ElementId;
       }
       return value;
     }
@@ -1808,7 +1808,7 @@

     #region Autodesk.Revit.UI.Selection.Selection
     public static List<Element> GetSelection2( this
-    Selection sel, Document doc )
+  Selection sel, Document doc )
     {
       List<Element> value = new List<Element>();
       sel.GetElementIds();
@@ -1834,7 +1834,7 @@
     {
       sel.ClearSelection2();
       object[] parametros = new object[] {
-            elementos };
+          elementos };
       Type[] tipos = parametros.Select( a => a
       .GetType() ).ToArray();
       MethodInfo met = sel.GetType()
@@ -1861,7 +1861,7 @@
             Element elemento = doc
             .GetElement2( id );
             parametros = new object[] {
-                        elemento };
+                      elemento };
             tipos = parametros
             .Select( a => a.GetType() ).ToArray();
             met = temp.GetType()
@@ -1871,7 +1871,7 @@
         }
       }
     }
-    public static void ClearSelection2(
+    public static void ClearSelection2(
       this Selection sel )
     {
       PropertyInfo prop = sel.GetType()
@@ -1885,9 +1885,9 @@
       }
       else
       {
-        ICollection<ElementId> ids
+        ICollection<ElementId> ids
           = new List<ElementId>();
-        MethodInfo met = sel.GetType().GetMethod(
+        MethodInfo met = sel.GetType().GetMethod(
           "SetElementIds", new Type[] { ids.GetType() } );
         met.Invoke( sel, new object[] { ids } );
       }
@@ -1910,33 +1910,33 @@
       ElementId value = null;
       Document doc = view.Document;
       List<Type> ls = doc.GetType().Assembly.GetTypes()
-        .Where( a => a.IsEnum
+        .Where( a => a.IsEnum
           && a.Name == "ViewDuplicateOption" )
         .ToList();
       if( ls.Count > 0 )
       {
         Type t = ls[0];
         object obj = view;
-        MethodInfo met = view.GetType().GetMethod(
+        MethodInfo met = view.GetType().GetMethod(
           "Duplicate", new Type[] { t } );
         if( met != null )
         {
           value = met.Invoke( obj,
-           new object[] { 2 } ) as ElementId;
+            new object[] { 2 } ) as ElementId;
         }
       }
       return value;
     }
-    public static void SetOverlayView2(
-      this View view,
-      List<ElementId> ids,
+    public static void SetOverlayView2(
+      this View view,
+      List<ElementId> ids,
       Color cor = null,
       int espessura = -1 )
     {
       Document doc = view.Document;
       List<Type> ls = doc.GetType().Assembly
-        .GetTypes().Where(
-          a => a.IsClass
+        .GetTypes().Where(
+          a => a.IsClass
             && a.Name == "OverrideGraphicSettings" )
         .ToList();
       if( ls.Count > 0 )
@@ -1947,17 +1947,17 @@
         construtor.Invoke( new object[] { } );
         object obj = construtor.Invoke( new object[] { } );
         MethodInfo met = obj.GetType()
-          .GetMethod( "SetProjectionLineColor",
+          .GetMethod( "SetProjectionLineColor",
             new Type[] { cor.GetType() } );
         met.Invoke( obj, new object[] { cor } );
         met = obj.GetType()
-          .GetMethod( "SetProjectionLineWeight",
+          .GetMethod( "SetProjectionLineWeight",
             new Type[] { espessura.GetType() } );
         met.Invoke( obj, new object[] { espessura } );
         met = view.GetType()
-          .GetMethod( "SetElementOverrides",
+          .GetMethod( "SetElementOverrides",
             new Type[] { typeof(ElementId),
-              obj.GetType() } );
+            obj.GetType() } );
         foreach( ElementId id in ids )
         {
           met.Invoke( view, new object[] { id, obj } );
@@ -1968,19 +1968,19 @@
         MethodInfo met = view.GetType()
           .GetMethod( "set_ProjColorOverrideByElement",
             new Type[] { typeof( ICollection<ElementId> ),
-              typeof( Color ) } );
+            typeof( Color ) } );
         met.Invoke( view, new object[] { ids, cor } );
         met = view.GetType()
           .GetMethod( "set_ProjLineWeightOverrideByElement",
             new Type[] { typeof( ICollection<ElementId> ),
-              typeof( int ) } );
+            typeof( int ) } );
         met.Invoke( view, new object[] { ids, espessura } );
       }
     }
     #endregion // Autodesk.Revit.DB.View

     #region Autodesk.Revit.DB.Viewplan
-    public static ElementId GetViewTemplateId2(
+    public static ElementId GetViewTemplateId2(
       this ViewPlan view )
     {
       ElementId value = null;
@@ -1989,12 +1989,12 @@
       if( prop != null )
       {
         value = prop.GetValue( view,
-         null ) as ElementId;
+          null ) as ElementId;
       }
       return value;
     }
     public static void SetViewTemplateId2( this
-    ViewPlan view, ElementId id )
+  ViewPlan view, ElementId id )
     {
       PropertyInfo prop = view.GetType()
         .GetProperty( "ViewTemplateId" );


added 301 for redirect of old tag=pageid format

--- CMSBaseClasses/VirtualFileSystem.cs
+++ CMSBaseClasses/VirtualFileSystem.cs
@@ -91,8 +91,14 @@
 					if (sFileRequested.Length < 3 || sFileRequested.ToLower() == DEFAULT_FILE) {
 						if (context.Request.QueryString["tag"] != null) {
 							sFileRequested = "/" + context.Request.QueryString["tag"].ToString() + ".aspx";
+
+							context.Response.StatusCode = 301;
+							context.Response.AppendHeader("Status", "301 Moved Permanently");
+							context.Response.AppendHeader("Location", sFileRequested);
+							context.Response.Cache.SetLastModified(DateTime.Today.Date);
+							context.Response.Write("
301 Moved Permanently
");
+
 							context.Response.Redirect(sFileRequested);
-
 							context.Items[REQ_PATH] = sFileRequested;
 							context.Items[REQ_QUERY] = "";
 						}


Remove exception handling in ConstructorProxy.Invoke

--- NiL.JS/Core/Functions/ConstructorProxy.cs
+++ NiL.JS/Core/Functions/ConstructorProxy.cs
@@ -168,23 +168,21 @@
                     return new Date().ToString();
             }

-            try
-            {
-                object obj;
-                if (_staticProxy._hostedType == typeof(BaseLibrary.Array))
-                {
-                    if (arguments == null)
-                    {
-                        obj = new BaseLibrary.Array();
-                    }
-                    else
-                    {
-                        switch (arguments._iValue)
-                        {
-                            case 0:
-                                obj = new BaseLibrary.Array();
-                                break;
-                            case 1:
+            object obj;
+            if (_staticProxy._hostedType == typeof(BaseLibrary.Array))
+            {
+                if (arguments == null)
+                {
+                    obj = new BaseLibrary.Array();
+                }
+                else
+                {
+                    switch (arguments._iValue)
+                    {
+                        case 0:
+                            obj = new BaseLibrary.Array();
+                            break;
+                        case 1:
                             {
                                 var a0 = arguments[0];
                                 switch (a0._valueType)
@@ -201,102 +199,93 @@
                                 }
                                 break;
                             }
-                            default:
-                                obj = new BaseLibrary.Array(arguments);
-                                break;
-                        }
-                    }
-                }
-                else
-                {
-                    if ((arguments == null || arguments._iValue == 0)
+                        default:
+                            obj = new BaseLibrary.Array(arguments);
+                            break;
+                    }
+                }
+            }
+            else
+            {
+                if ((arguments == null || arguments._iValue == 0)
 #if (PORTABLE || NETCORE)
- && _staticProxy._hostedType.GetTypeInfo().IsValueType)
+&& _staticProxy._hostedType.GetTypeInfo().IsValueType)
 #else
  && _staticProxy._hostedType.IsValueType)
 #endif
-                    {
-                        obj = Activator.CreateInstance(_staticProxy._hostedType);
-                    }
+                {
+                    obj = Activator.CreateInstance(_staticProxy._hostedType);
+                }
+                else
+                {
+                    object[] args = null;
+                    var constructor = findConstructor(arguments, ref args);
+
+                    if (constructor == null)
+                        ExceptionHelper.ThrowTypeError(_staticProxy._hostedType.Name + " can't be created.");
+
+                    if (args == null)
+                        args = new object[] { arguments };
+
+                    var target = constructor.GetTargetObject(targetObject, null);
+                    if (target != null)
+                        obj = constructor._method.Invoke(target, args);
                     else
-                    {
-                        object[] args = null;
-                        var constructor = findConstructor(arguments, ref args);
-
-                        if (constructor == null)
-                            ExceptionHelper.ThrowTypeError(_staticProxy._hostedType.Name + " can't be created.");
-
-                        if (args == null)
-                            args = new object[] { arguments };
-
-                        var target = constructor.GetTargetObject(targetObject, null);
-                        if (target != null)
-                            obj = constructor._method.Invoke(target, args);
-                        else
-                            obj = (constructor._method as ConstructorInfo).Invoke(args);
-                    }
-                }
-
-                JSValue res = obj as JSValue;
-
-                if (construct)
-                {
-                    if (res != null)
-                    {
-                        // Для Number, Boolean и String
-                        if (res._valueType < JSValueType.Object)
-                        {
-                            objc.instance = obj;
-                            if (objc._objectPrototype == null)
-                                objc._objectPrototype = res.__proto__;
-                            res = objc;
-                        }
-                        else if (res._oValue is JSValue)
-                        {
-                            res._oValue = res;
-                            // На той стороне понять, по new или нет вызван конструктор не получится,
-                            // поэтому по соглашению такие типы себя настраивают так, как будто они по new,
-                            // а в oValue пишут экземпляр аргумента на тот случай, если вызван конструктор типа как функция
-                            // с передачей в качестве аргумента существующего экземпляра
-                        }
-                    }
-                    else
+                        obj = (constructor._method as ConstructorInfo).Invoke(args);
+                }
+            }
+
+            JSValue res = obj as JSValue;
+
+            if (construct)
+            {
+                if (res != null)
+                {
+                    // Для Number, Boolean и String
+                    if (res._valueType < JSValueType.Object)
                     {
                         objc.instance = obj;
-
-                        objc._attributes |= _staticProxy._hostedType.GetTypeInfo().IsDefined(typeof(ImmutableAttribute), false) ? JSValueAttributesInternal.Immutable : JSValueAttributesInternal.None;
-                        if (obj.GetType() == typeof(Date))
-                            objc._valueType = JSValueType.Date;
-                        else if (res != null)
-                            objc._valueType = (JSValueType)System.Math.Max((int)objc._valueType, (int)res._valueType);
-
+                        if (objc._objectPrototype == null)
+                            objc._objectPrototype = res.__proto__;
                         res = objc;
                     }
+                    else if (res._oValue is JSValue)
+                    {
+                        res._oValue = res;
+                        // На той стороне понять, по new или нет вызван конструктор не получится,
+                        // поэтому по соглашению такие типы себя настраивают так, как будто они по new,
+                        // а в oValue пишут экземпляр аргумента на тот случай, если вызван конструктор типа как функция
+                        // с передачей в качестве аргумента существующего экземпляра
+                    }
                 }
                 else
                 {
-                    if (_staticProxy._hostedType == typeof(JSValue))
-                    {
-                        if ((res._oValue is JSValue) && (res._oValue as JSValue)._valueType >= JSValueType.Object)
-                            return res._oValue as JSValue;
-                    }
-
-                    res = res ?? new ObjectWrapper(obj)
-                    {
-                        _attributes = JSValueAttributesInternal.SystemObject | (_staticProxy._hostedType.GetTypeInfo().IsDefined(typeof(ImmutableAttribute), false) ? JSValueAttributesInternal.Immutable : JSValueAttributesInternal.None)
-                    };
-                }
-
-                return res;
-            }
-            catch (TargetInvocationException e)
-            {
-#if !(PORTABLE || NETCORE)
-                if (System.Diagnostics.Debugger.IsAttached)
-                    System.Diagnostics.Debugger.Log(10, "Exception", e.ToString());
-#endif
-                throw e.GetBaseException();
-            }
+                    objc.instance = obj;
+
+                    objc._attributes |= _staticProxy._hostedType.GetTypeInfo().IsDefined(typeof(ImmutableAttribute), false) ? JSValueAttributesInternal.Immutable : JSValueAttributesInternal.None;
+                    if (obj.GetType() == typeof(Date))
+                        objc._valueType = JSValueType.Date;
+                    else if (res != null)
+                        objc._valueType = (JSValueType)System.Math.Max((int)objc._valueType, (int)res._valueType);
+
+                    res = objc;
+                }
+            }
+            else
+            {
+                if (_staticProxy._hostedType == typeof(JSValue))
+                {
+                    if ((res._oValue is JSValue) && (res._oValue as JSValue)._valueType >= JSValueType.Object)
+                        return res._oValue as JSValue;
+                }
+
+                res = res ?? new ObjectWrapper(obj)
+                {
+                    _attributes = JSValueAttributesInternal.SystemObject | (_staticProxy._hostedType.GetTypeInfo().IsDefined(typeof(ImmutableAttribute), false) ? JSValueAttributesInternal.Immutable : JSValueAttributesInternal.None)
+                };
+            }
+
+            return res;
         }

         protected internal override JSValue ConstructObject()


find usages big speed improvement

find usages big speed improvement

--- OmniSharp/FindUsages/FindUsagesHandler.cs
+++ OmniSharp/FindUsages/FindUsagesHandler.cs
@@ -109,19 +109,11 @@

                 foreach (var project in _solution.Projects)
                 {
+                    var pctx = project.ProjectContent.CreateCompilation();
+                    var interesting = (from file in project.Files
+                                    select (file.ParsedFile as CSharpUnresolvedFile)).ToList();

-                    var interesting = new List<CSharpUnresolvedFile>();
-                    var pctx = project.ProjectContent.CreateCompilation();
-
-                    foreach(var scope in searchScopes)
-                    {
-                        foreach(var innerScope in scope)
-                        {
-                            interesting.AddRange(findReferences.GetInterestingFiles(innerScope, pctx));
-                        }
-                    }
-
-                    Parallel.ForEach(interesting, file =>
+                    Parallel.ForEach(interesting.Distinct(), file =>
                     {
                         string text = _solution.GetFile(file.FileName.LowerCaseDriveLetter()).Content.Text;
                         var unit = new CSharpParser().Parse(text, file.FileName);


trivial whitespace removal to trigger a panda rebuild

--- OpenSim/Region/Application/Application.cs
+++ OpenSim/Region/Application/Application.cs
@@ -250,9 +250,7 @@
             m_saveCrashDumps = configSource.Configs["Startup"].GetBoolean("save_crashes", false);

             // load Crash directory config
-            m_crashDir = configSource.Configs["Startup"].GetString("crash_dir", m_crashDir);
-
-
+            m_crashDir = configSource.Configs["Startup"].GetString("crash_dir", m_crashDir);

             if (background)
             {
@@ -260,15 +258,9 @@
                 m_sim.Startup();
             }
             else
-            {
-
-
-
-
+            {
                 m_sim = new OpenSim(configSource);
-
-
-
+
                 m_sim.Startup();

                 while (true)