Refactor benchmarks to only demonstrate what's needed

--- osu.Framework.Benchmarks/BenchmarkBindableInstantiation.cs
+++ osu.Framework.Benchmarks/BenchmarkBindableInstantiation.cs
@@ -9,36 +9,20 @@
 {
     public class BenchmarkBindableInstantiation
     {
-        private Bindable<int> bindable;
+        [Benchmark(Baseline = true)]
+        public Bindable<int> GetBoundCopyOld() => new BindableOld<int>().GetBoundCopy();

-        [GlobalSetup]
-        public void GlobalSetup() => bindable = new Bindable<int>();
+        [Benchmark]
+        public Bindable<int> GetBoundCopy() => new Bindable<int>().GetBoundCopy();

-        /// <summary>
-        /// Creates an instance of the bindable directly by construction.
-        /// </summary>
-        [Benchmark(Baseline = true)]
-        public Bindable<int> CreateInstanceViaConstruction() => new Bindable<int>();
+        private class BindableOld<T> : Bindable<T>
+        {
+            public BindableOld(T defaultValue = default)
+                : base(defaultValue)
+            {
+            }

-        /// <summary>
-        /// Creates an instance of the bindable via <see cref="Activator.CreateInstance(Type, object[])"/>.
-        /// This used to be how <see cref="Bindable{T}.GetBoundCopy"/> creates an instance before binding, which has turned out to be inefficient in performance.
-        /// </summary>
-        [Benchmark]
-        public Bindable<int> CreateInstanceViaActivatorWithParams() => (Bindable<int>)Activator.CreateInstance(typeof(Bindable<int>), 0);
-
-        /// <summary>
-        /// Creates an instance of the bindable via <see cref="Activator.CreateInstance(Type)"/>.
-        /// More performant than <see cref="CreateInstanceViaActivatorWithParams"/>, due to not passing parameters to <see cref="Activator"/> during instance creation.
-        /// </summary>
-        [Benchmark]
-        public Bindable<int> CreateInstanceViaActivatorWithoutParams() => (Bindable<int>)Activator.CreateInstance(typeof(Bindable<int>), true);
-
-        /// <summary>
-        /// Creates an instance of the bindable via <see cref="IBindable.CreateInstance"/>.
-        /// This is the current and most performant version used for <see cref="IBindable.GetBoundCopy"/>, as equally performant as <see cref="CreateInstanceViaConstruction"/>.
-        /// </summary>
-        [Benchmark]
-        public Bindable<int> CreateInstanceViaBindableCreateInstance() => bindable.CreateInstance();
+            protected internal override Bindable<T> CreateInstance() => (BindableOld<T>)Activator.CreateInstance(GetType(), Value);
+        }
     }
 }


Privatise ShadowModel

Privatise ShadowModel

--- osu.Framework/Allocation/CachedModelDependencyContainer.cs
+++ osu.Framework/Allocation/CachedModelDependencyContainer.cs
@@ -14,7 +14,8 @@
         private const BindingFlags activator_flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly;

         public readonly Bindable<TModel> Model = new Bindable<TModel>();
-        public readonly TModel ShadowModel = new TModel();
+
+        private readonly TModel shadowModel = new TModel();

         private readonly IReadOnlyDependencyContainer parent;
         private readonly IReadOnlyDependencyContainer shadowDependencies;
@@ -25,7 +26,7 @@
         {
             this.parent = parent;

-            shadowDependencies = DependencyActivator.MergeDependencies(ShadowModel, null, new CacheInfo(parent: typeof(TModel)));
+            shadowDependencies = DependencyActivator.MergeDependencies(shadowModel, null, new CacheInfo(parent: typeof(TModel)));

             Model.BindValueChanged(newModel =>
             {
@@ -33,7 +34,7 @@
                 // rather than leaving the current state on-going
                 newModel = newModel ?? new TModel();

-                updateShadowModel(ShadowModel, currentModel, newModel);
+                updateShadowModel(shadowModel, currentModel, newModel);

                 currentModel = newModel;
             });
@@ -53,12 +54,12 @@
         public void Inject<T>(T instance) where T : class => DependencyActivator.Activate(instance, this);

         /// <summary>
-        /// Creates a new shadow model bound to <see cref="ShadowModel"/>.
+        /// Creates a new shadow model bound to <see cref="shadowModel"/>.
         /// </summary>
         private TModel createChildShadowModel()
         {
             var result = new TModel();
-            updateShadowModel(result, default, ShadowModel);
+            updateShadowModel(result, default, shadowModel);
             return result;
         }


beatmap can not be null in DifficultyColouredContainer.cs

--- osu.Game/Beatmaps/Drawables/DifficultyColouredContainer.cs
+++ osu.Game/Beatmaps/Drawables/DifficultyColouredContainer.cs
@@ -43,6 +43,9 @@

         private DifficultyRating getDifficultyRating(BeatmapInfo beatmap)
         {
+            if (beatmap == null)
+                throw new ArgumentNullException(nameof(beatmap));
+
             var rating = beatmap.StarDifficulty;

             if (rating < 1.5) return DifficultyRating.Easy;


Fix storyboard imlpementation

Fix storyboard imlpementation

--- osu.Game/Storyboards/Drawables/DrawableStoryboardSample.cs
+++ osu.Game/Storyboards/Drawables/DrawableStoryboardSample.cs
@@ -37,8 +37,8 @@

             foreach (var mod in mods.Value.OfType<IApplicableToSample>())
             {
-                // foreach (var sample in SamplesContainer)
-                //     mod.ApplyToSample(sample.Sample);
+                foreach (var sample in SamplesContainer)
+                    mod.ApplyToSample(sample.Sample);
             }
         }


Fix finished-play state not handled correctly

--- osu.Game/Tests/Visual/Multiplayer/TestMultiplayerClient.cs
+++ osu.Game/Tests/Visual/Multiplayer/TestMultiplayerClient.cs
@@ -96,31 +96,31 @@
         public void ChangeUserState(int userId, MultiplayerUserState newState)
         {
             Debug.Assert(Room != null);
-
             ((IMultiplayerClient)this).UserStateChanged(userId, newState);

             Schedule(() =>
             {
-                switch (newState)
+                switch (Room.State)
                 {
-                    case MultiplayerUserState.Loaded:
+                    case MultiplayerRoomState.WaitingForLoad:
                         if (Room.Users.All(u => u.State != MultiplayerUserState.WaitingForLoad))
                         {
-                            ChangeRoomState(MultiplayerRoomState.Playing);
                             foreach (var u in Room.Users.Where(u => u.State == MultiplayerUserState.Loaded))
                                 ChangeUserState(u.UserID, MultiplayerUserState.Playing);

                             ((IMultiplayerClient)this).MatchStarted();
+
+                            ChangeRoomState(MultiplayerRoomState.Playing);
                         }

                         break;

-                    case MultiplayerUserState.FinishedPlay:
+                    case MultiplayerRoomState.Playing:
                         if (Room.Users.All(u => u.State != MultiplayerUserState.Playing))
                         {
-                            ChangeRoomState(MultiplayerRoomState.Open);
                             foreach (var u in Room.Users.Where(u => u.State == MultiplayerUserState.FinishedPlay))
                                 ChangeUserState(u.UserID, MultiplayerUserState.Results);
+                            ChangeRoomState(MultiplayerRoomState.Open);

                             ((IMultiplayerClient)this).ResultsReady();
                         }


OPTIMIZATION QL: calculate involved classes for SoqlQueryExpression.

Reduces precommitted objects for SOQL subqueries, LINQ Any() etc.

--- src/Sooda/QL/GetInvolvedClassesVisitor.cs
+++ src/Sooda/QL/GetInvolvedClassesVisitor.cs
@@ -227,8 +227,21 @@

         void Sooda.QL.ISoqlVisitor.Visit(SoqlQueryExpression v)
         {
-            throw new NotImplementedException();
-            // TODO:  Add GetInvolvedClassesVisitor.Sooda.QL.ISoqlVisitor.Visit implementation
+            if (v.From.Count != 1)
+                throw new NotImplementedException();
+            ClassInfo queryClass = _rootClass.Schema.FindClassByName(v.From[0]);
+            if (queryClass == null)
+                throw new NotImplementedException(); // TODO: error?
+            ClassInfo outerClass = _rootClass;
+            _rootClass = queryClass;
+            try
+            {
+                GetInvolvedClasses(v);
+            }
+            finally
+            {
+                _rootClass = outerClass;
+            }
         }

         void Sooda.QL.ISoqlVisitor.Visit(SoqlUnaryNegationExpression v)


Simplify the implementation of SMTLIBQueryPrinter.AddDeclaration(Constraint ...). Constraints now have the used uninterpreted functions attached to them so there is no longer a need to compute this in the SMTLIBQueryPrinter.

--- src/Symbooglix/Expr/SMTLIBQueryPrinter.cs
+++ src/Symbooglix/Expr/SMTLIBQueryPrinter.cs
@@ -143,17 +143,22 @@
             }
         }

-        // For this verion of AddDeclarations we already know what variables are used.
+        // For this verion of AddDeclarations we already know what variables
+        // and uninterpreted functions are used.
         public void AddDeclarations(Constraint c)
         {
-            FFV.Visit(c.Condition);
-
             // Add variables used in Constraint
             foreach (var usedVariable in c.UsedVariables)
             {
                 symbolicsToDeclare.Add(usedVariable);
             }

+            // Add uninterpreted functions used in Constraint
+            foreach (var usedUninterpretedFunction in c.UsedUninterpretedFunctions)
+            {
+                functionsToDeclare.Add(usedUninterpretedFunction);
+            }
+
             if (UseNamedAttributeBindings)
                 BindingsFinder.Visit(c.Condition);
         }
@@ -161,7 +166,7 @@
         public void AddDeclarations(Expr e)
         {
             FSV.Visit(e); // We don't know what variables are used here so find them by traversing the Expr
-            FFV.Visit(e);
+            FFV.Visit(e); // We don't know what uninterpreted functions are sued here so find them by traversing Expr

             if (UseNamedAttributeBindings)
                 BindingsFinder.Visit(e);


Add detailed parse error strings. (#1758)

This is part of converging the Kestrel and CoreFxLab
parsers. Kestrel expects this information for logging
and also expects it to be pay-for-play.

--- src/System.Text.Http.Parser/HttpParser.cs
+++ src/System.Text.Http.Parser/HttpParser.cs
@@ -22,6 +22,18 @@
         private const byte ByteTab = (byte)'\t';
         private const byte ByteQuestionMark = (byte)'?';
         private const byte BytePercentage = (byte)'%';
+
+        private readonly bool _showErrorDetails;
+
+        public HttpParser()
+            : this(showErrorDetails: true)
+        {
+        }
+
+        public HttpParser(bool showErrorDetails)
+        {
+            _showErrorDetails = showErrorDetails;
+        }

         public unsafe bool ParseRequestLine<T>(T handler, in ReadableBuffer buffer, out ReadCursor consumed, out ReadCursor examined) where T : IHttpRequestLineHandler
         {
@@ -668,7 +680,10 @@

         private unsafe BadHttpRequestException GetInvalidRequestException(RequestRejectionReason reason, byte* detail, int length)
         {
-            return BadHttpRequestException.GetException(reason, "");
+            string errorDetails = _showErrorDetails ?
+                new Span<byte>(detail, length).GetAsciiStringEscaped(Constants.MaxExceptionDetailSize) :
+                string.Empty;
+            return BadHttpRequestException.GetException(reason, errorDetails);
         }

         public void Reset()


Add missing using

Add missing using

--- src/Telegram.Bot/Types/ChatJoinRequest.cs
+++ src/Telegram.Bot/Types/ChatJoinRequest.cs
@@ -1,5 +1,6 @@
 using System;
 using Newtonsoft.Json;
+using Newtonsoft.Json.Converters;
 using Newtonsoft.Json.Serialization;

 namespace Telegram.Bot.Types


Fixed adding/updating UmbracoMapper constructors

--- src/Umbraco.Core/Mapping/UmbracoMapper.cs
+++ src/Umbraco.Core/Mapping/UmbracoMapper.cs
@@ -343,16 +343,19 @@

             if (ctor == null) return null;

-            if (_ctors.ContainsKey(sourceType))
-            {
+            _ctors.AddOrUpdate(sourceType, sourceCtor, (k, v) => {
+                // Add missing constructors
                 foreach (var c in sourceCtor)
                 {
-                    if (!_ctors[sourceType].TryGetValue(c.Key, out _))
-                        _ctors[sourceType].Add(c.Key, c.Value);
-                }
-            }
-            else
-                _ctors[sourceType] = sourceCtor;
+                    if (!v.ContainsKey(c.Key))
+                    {
+                        v.Add(c.Key, c.Value);
+                    }
+                }
+
+                return v;
+            });
+

             return ctor;
         }


Fixed response not returning

Fixed response not returning

--- TwitterAutherino/TwitterAuth.cs
+++ TwitterAutherino/TwitterAuth.cs
@@ -97,8 +97,7 @@
         {
             //Stop and hide the browser
             if (args.Uri.Query.Contains("denied")
-                || args.Uri.Query.Contains("oauth_verifier=")
-                || args.Uri.AbsoluteUri == "https://api.twitter.com/oauth/authorize")
+                || args.Uri.Query.Contains("oauth_verifier="))
             {
                 sender.Stop();
                 flyout.Hide();


Optimize FieldwiseEquality

Optimize FieldwiseEquality

When the type is a primitive or has a custom == operator, use that to compare values.
These operators are generally the fastest.
Otherwise, if the type T has an instance method Equals(T obj), use that.
This instance method avoids a cast, and is commonly implemented due to IEquatable<>
only if all else fails use object.Equals; it's slower because it needs a cast and virtual method lookup.

--- ValueUtils/FieldwiseEquality.cs
+++ ValueUtils/FieldwiseEquality.cs
@@ -35,23 +35,52 @@

             var aExpr = Expression.Parameter(typeof(T), "a");
             var bExpr = Expression.Parameter(typeof(T), "b");
-            var objectEqualsMethod = ((Func<object, object, bool>)object.Equals).Method;

             Expression eqExpr = Expression.Constant(true);

             foreach (var fieldInfo in fields) {
                 var aFieldExpr = Expression.Field(aExpr, fieldInfo);
                 var bFieldExpr = Expression.Field(bExpr, fieldInfo);
-                var fieldsEqualExpr =
-                    Expression.Call(objectEqualsMethod,
-                        Expression.Convert(aFieldExpr, typeof(object)),
-                        Expression.Convert(bFieldExpr, typeof(object))
-                    );
-                eqExpr = Expression.AndAlso(eqExpr, fieldsEqualExpr);
+                var bestEqualityApproach =
+                    EqualityByOperatorOrNull(aFieldExpr, bFieldExpr, fieldInfo)
+                    ?? InstanceEqualsOrNull(aFieldExpr, bFieldExpr, fieldInfo)
+                    ;
+
+                eqExpr = Expression.AndAlso(eqExpr, bestEqualityApproach);
             }
             var funcExpr = Expression.Lambda<Func<T, T, bool>>(eqExpr, aExpr, bExpr);
+            return funcExpr.Compile();
+        }

-            return funcExpr.Compile();
+        static Expression EqualityByOperatorOrNull(Expression aFieldExpr, Expression bFieldExpr, FieldInfo fieldInfo) {
+            //only use operator == if it's explicitly defined.
+            return fieldInfo.FieldType.IsPrimitive || fieldInfo.FieldType.GetMethod("op_Equality", BindingFlags.Public | BindingFlags.Static) != null
+                ? Expression.Equal(aFieldExpr, bFieldExpr)
+                : null;
+        }
+
+        static Expression InstanceEqualsOrNull(Expression aFieldExpr, Expression bFieldExpr, FieldInfo fieldInfo) {
+            Console.WriteLine("Instance equals needed for " + fieldInfo.FieldType);
+            var fieldType = fieldInfo.FieldType;
+            var equalsMethod = fieldType.GetMethod(
+                "Equals", BindingFlags.Public | BindingFlags.Instance,
+                null, new[] { fieldType }, null);
+
+            var fieldsEqualExpr = equalsMethod == null
+                ? Expression.Call(((Func<object, object, bool>)object.Equals).Method,
+                    Expression.Convert(aFieldExpr, typeof(object)),
+                    Expression.Convert(bFieldExpr, typeof(object))
+                )
+                : Expression.Call(aFieldExpr, equalsMethod, bFieldExpr)
+                ;
+            var nullSafeFieldsEqualExpr = fieldInfo.FieldType.IsValueType || equalsMethod == null
+                ? (Expression)fieldsEqualExpr
+                : Expression.Condition(
+                  Expression.Equal(Expression.Default(fieldInfo.FieldType), aFieldExpr),
+                     Expression.Equal(Expression.Default(fieldInfo.FieldType), aFieldExpr),
+                     fieldsEqualExpr
+               );
+            return nullSafeFieldsEqualExpr;
         }
     }
 }


Fix HashJob queries.

Fix HashJob queries.

--- extensions/Tools/HashJob/HashJob.cs
+++ extensions/Tools/HashJob/HashJob.cs
@@ -36,9 +36,9 @@
 		{
 			// This query is not very fast, but it's a 'one-time' so don't care much...
 			SqliteDataReader reader = FSpot.App.Instance.Database.Database.Query (
-				"SELECT COUNT(*) FROM photos p WHERE md5_sum IS NULL OR md5_sum = '' OR EXISTS " +
-					"(SELECT * FROM photo_versions pv WHERE p.id=pv.photo_id AND version_id <> '1' AND " +
-					"(pv.md5_sum IS NULL OR pv.md5_sum = ''))");
+				"SELECT COUNT(*) FROM photos p WHERE EXISTS " +
+					"(SELECT * FROM photo_versions pv WHERE p.id=pv.photo_id AND " +
+					"(pv.import_md5 IS NULL OR pv.import_md5 = ''))");
 			reader.Read ();
 			uint missing_md5 = Convert.ToUInt32 (reader[0]);
 			reader.Close ();
@@ -91,9 +91,9 @@
 		void HandleExecuteClicked (object o, EventArgs e)
 		{
 			SqliteDataReader reader = FSpot.App.Instance.Database.Database.Query (
-				"SELECT id FROM photos p WHERE md5_sum IS NULL OR md5_sum = '' OR EXISTS " +
-					"(SELECT * FROM photo_versions pv WHERE p.id=pv.photo_id AND version_id <> '1' AND " +
-					"(pv.md5_sum IS NULL OR pv.md5_sum = '') )");
+				"SELECT id FROM photos p WHERE EXISTS " +
+					"(SELECT * FROM photo_versions pv WHERE p.id=pv.photo_id AND " +
+					"(pv.import_md5 IS NULL OR pv.import_md5 = '') )");
 			FSpot.App.Instance.Database.Database.BeginTransaction ();
 			while (reader.Read ())
 				FSpot.Jobs.CalculateHashJob.Create (FSpot.App.Instance.Database.Jobs, Convert.ToUInt32 (reader[0]));


refactor(FileSystem): 为Delete(...), Exists(...) 方法增加参数为空的判断。 :koko: :guitar:

--- src/IO/FileSystem.cs
+++ src/IO/FileSystem.cs
@@ -244,6 +244,9 @@

 			public bool Delete(string virtualPath, bool recursive = false)
 			{
+				if(string.IsNullOrWhiteSpace(virtualPath))
+					return false;
+
 				Path path;
 				var service = FileSystem.GetDirectoryProvider(virtualPath, out path);

@@ -252,6 +255,9 @@

 			public Task<bool> DeleteAsync(string virtualPath, bool recursive)
 			{
+				if(string.IsNullOrWhiteSpace(virtualPath))
+					return Task.Run(() => false);
+
 				Path path;
 				var service = FileSystem.GetDirectoryProvider(virtualPath, out path);

@@ -282,6 +288,9 @@

 			public bool Exists(string virtualPath)
 			{
+				if(string.IsNullOrWhiteSpace(virtualPath))
+					return false;
+
 				Path path;
 				var service = FileSystem.GetDirectoryProvider(virtualPath, out path);

@@ -290,6 +299,9 @@

 			public Task<bool> ExistsAsync(string virtualPath)
 			{
+				if(string.IsNullOrWhiteSpace(virtualPath))
+					return Task.Run(() => false);
+
 				Path path;
 				var service = FileSystem.GetDirectoryProvider(virtualPath, out path);

@@ -411,6 +423,9 @@
 		{
 			public bool Delete(string virtualPath)
 			{
+				if(string.IsNullOrWhiteSpace(virtualPath))
+					return false;
+
 				Path path;
 				var service = FileSystem.GetFileProvider(virtualPath, out path);

@@ -419,6 +434,9 @@

 			public Task<bool> DeleteAsync(string virtualPath)
 			{
+				if(string.IsNullOrWhiteSpace(virtualPath))
+					return Task.Run(() => false);
+
 				Path path;
 				var service = FileSystem.GetFileProvider(virtualPath, out path);

@@ -427,6 +445,9 @@

 			public bool Exists(string virtualPath)
 			{
+				if(string.IsNullOrWhiteSpace(virtualPath))
+					return false;
+
 				Path path;
 				var service = FileSystem.GetFileProvider(virtualPath, out path);

@@ -435,6 +456,9 @@

 			public Task<bool> ExistsAsync(string virtualPath)
 			{
+				if(string.IsNullOrWhiteSpace(virtualPath))
+					return Task.Run(() => false);
+
 				Path path;
 				var service = FileSystem.GetFileProvider(virtualPath, out path);


refactored unit test

refactored unit test

--- Voron.Graph.Tests/BasicTests.cs
+++ Voron.Graph.Tests/BasicTests.cs
@@ -131,17 +131,10 @@

                 foreach (var curNode in graph.Queries.GetAdjacentOf(tx, centerNode))
                 {
-                    var curEdge = graph.Queries.GetEdgesBetween(tx, centerNode, curNode).FirstOrDefault();
-                    if (curNode == null)
-                    {
-                        curEdge = graph.Queries.GetEdgesBetween(tx, curNode, centerNode).FirstOrDefault();
-                    }
+                    var curEdge = graph.Queries.GetEdgesBetween(tx, centerNode, curNode).FirstOrDefault();
                     Assert.IsNotNull(curEdge);

-                    Assert.AreNotEqual(0, curEdge.Data.Value<int>("Value"));
                     curEdgeVal = curEdge.Data.Value<string>("Value");
-
-                    Assert.AreNotEqual(0, curNode.Data.Value<int>("Value"));
                     curNodeVal = curNode.Data.Value<string>("Value");

                     nodeValues.Add(curNodeVal, curEdgeVal);
@@ -161,12 +154,12 @@
                 centerNodeKey = centerNode.Key;

-                for (var i = 0; i < 5; i++)
+                for (var i = 1; i < 6; i++)
                 {
                     var curChild = graph.Commands.CreateNode(tx,JsonFromValue("childNode" + i.ToString()));
                     graph.Commands.CreateEdgeBetween(tx, centerNode, curChild, JsonFromValue(i.ToString()));

-                    for (var j = 0; j < 5; j++)
+                    for (var j = 1; j < 6; j++)
                     {
                         var curGrandChild = graph.Commands.CreateNode(tx, JsonFromValue(string.Concat("childNode", i.ToString(), "child", i.ToString())));
                         graph.Commands.CreateEdgeBetween(tx, curChild, curGrandChild,JsonFromValue((i * 10 + j).ToString()));


reading only .locale files from locales path ad design time

--- WPFLocales/LocalesDesignTime.cs
+++ WPFLocales/LocalesDesignTime.cs
@@ -94,8 +94,8 @@

             var locales = new List<string>();

-            //rading all locales from XMLs
-            var files = Directory.GetFiles(path);
+            //reading all locales from XMLs
+            var files = Directory.GetFiles(path).Where(f => f.EndsWith(".locale")); ;
             foreach (var file in files)
             {
                 using (var stream = new FileStream(file, FileMode.Open))


Add callsite support for NLogLogProvider, fix issue #102

--- src/LibLog/LibLog.cs
+++ src/LibLog/LibLog.cs
@@ -873,6 +873,55 @@
         {
             private readonly dynamic _logger;

+            private static Func<string, object, string, Exception, object> _logEventInfoFact;
+
+            private static readonly object _levelTrace;
+            private static readonly object _levelDebug;
+            private static readonly object _levelInfo;
+            private static readonly object _levelWarn;
+            private static readonly object _levelError;
+            private static readonly object _levelFatal;
+
+            static NLogLogger()
+            {
+                try
+                {
+                    var logEventLevelType = Type.GetType("NLog.LogLevel, NLog");
+                    if (logEventLevelType == null)
+                    {
+                        throw new InvalidOperationException("Type NLog.LogLevel was not found.");
+                    }
+
+                    var levelFields = logEventLevelType.GetFieldsPortable().ToList();
+                    _levelTrace = levelFields.First(x => x.Name == "Trace").GetValue(null);
+                    _levelDebug = levelFields.First(x => x.Name == "Debug").GetValue(null);
+                    _levelInfo = levelFields.First(x => x.Name == "Info").GetValue(null);
+                    _levelWarn = levelFields.First(x => x.Name == "Warn").GetValue(null);
+                    _levelError = levelFields.First(x => x.Name == "Error").GetValue(null);
+                    _levelFatal = levelFields.First(x => x.Name == "Fatal").GetValue(null);
+
+                    var logEventInfoType = Type.GetType("NLog.LogEventInfo, NLog");
+                    if (logEventInfoType == null)
+                    {
+                        throw new InvalidOperationException("Type NLog.LogEventInfo was not found.");
+                    }
+                    MethodInfo createLogEventInfoMethodInfo = logEventInfoType.GetMethodPortable("Create",
+                        logEventLevelType, typeof(string), typeof(Exception), typeof(IFormatProvider), typeof(string), typeof(object[]));
+                    ParameterExpression loggerNameParam = Expression.Parameter(typeof(string));
+                    ParameterExpression levelParam = Expression.Parameter(typeof(object));
+                    ParameterExpression messageParam = Expression.Parameter(typeof(string));
+                    ParameterExpression exceptionParam = Expression.Parameter(typeof(Exception));
+                    UnaryExpression levelCast = Expression.Convert(levelParam, logEventLevelType);
+                    MethodCallExpression createLogEventInfoMethodCall = Expression.Call(null,
+                        createLogEventInfoMethodInfo,
+                        levelCast, loggerNameParam, exceptionParam,
+                        Expression.Constant(null, typeof(IFormatProvider)), messageParam, Expression.Constant(null, typeof(object[])));
+                    _logEventInfoFact = Expression.Lambda<Func<string, object, string, Exception, object>>(createLogEventInfoMethodCall,
+                        loggerNameParam, levelParam, messageParam, exceptionParam).Compile();
+                }
+                catch { }
+            }
+
             internal NLogLogger(dynamic logger)
             {
                 _logger = logger;
@@ -886,6 +935,43 @@
                     return IsLogLevelEnable(logLevel);
                 }
                 messageFunc = LogMessageFormatter.SimulateStructuredLogging(messageFunc, formatParameters);
+
+                if (_logEventInfoFact != null)
+                {
+                    if (IsLogLevelEnable(logLevel))
+                    {
+                        var nlogLevel = this.TranslateLevel(logLevel);
+                        Type s_callerStackBoundaryType;
+#if !LIBLOG_PORTABLE
+                        StackTrace stack = new StackTrace();
+                        Type thisType = GetType();
+                        Type knownType0 = typeof(LoggerExecutionWrapper);
+                        Type knownType1 = typeof(LogExtensions);
+                        //Maybe inline, so we may can't found any LibLog classes in stack
+                        s_callerStackBoundaryType = null;
+                        for (var i = 0; i < stack.FrameCount; i++)
+                        {
+                            var declaringType = stack.GetFrame(i).GetMethod().DeclaringType;
+                            if (!IsInTypeHierarchy(thisType, declaringType) &&
+                                !IsInTypeHierarchy(knownType0, declaringType) &&
+                                !IsInTypeHierarchy(knownType1, declaringType))
+                            {
+                                if (i > 1)
+                                    s_callerStackBoundaryType = stack.GetFrame(i - 1).GetMethod().DeclaringType;
+                                break;
+                            }
+                        }
+#else
+                        s_callerStackBoundaryType = null;
+#endif
+                        if (s_callerStackBoundaryType != null)
+                            _logger.Log(s_callerStackBoundaryType, _logEventInfoFact(_logger.Name, nlogLevel, messageFunc(), exception));
+                        else
+                            _logger.Log(_logEventInfoFact(_logger.Name, nlogLevel, messageFunc(), exception));
+                        return true;
+                    }
+                    return false;
+                }

                 if(exception != null)
                 {
@@ -939,6 +1025,19 @@
                 return false;
             }

+            private static bool IsInTypeHierarchy(Type currentType, Type checkType)
+            {
+                while (currentType != null && currentType != typeof(object))
+                {
+                    if (currentType == checkType)
+                    {
+                        return true;
+                    }
+                    currentType = currentType.GetBaseTypePortable();
+                }
+                return false;
+            }
+
             [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
             private bool LogException(LogLevel logLevel, Func<string> messageFunc, Exception exception)
             {
@@ -1008,6 +1107,27 @@
                         return _logger.IsTraceEnabled;
                 }
             }
+
+            private object TranslateLevel(LogLevel logLevel)
+            {
+                switch (logLevel)
+                {
+                    case LogLevel.Trace:
+                        return _levelTrace;
+                    case LogLevel.Debug:
+                        return _levelDebug;
+                    case LogLevel.Info:
+                        return _levelInfo;
+                    case LogLevel.Warn:
+                        return _levelWarn;
+                    case LogLevel.Error:
+                        return _levelError;
+                    case LogLevel.Fatal:
+                        return _levelFatal;
+                    default:
+                        throw new ArgumentOutOfRangeException("logLevel", logLevel, null);
+                }
+            }
         }
     }


get post by id (untested)

get post by id (untested)

--- WordPressUWP/WordPressClient.cs
+++ WordPressUWP/WordPressClient.cs
@@ -36,5 +36,25 @@
             return result;
         }

+        public async Task<Post> GetPost(String id)
+        {
+            Post result = null;
+            using (var client = new HttpClient())
+            {
+                client.BaseAddress = new Uri(Endpoint);
+                client.DefaultRequestHeaders.Accept.Clear();
+                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
+
+                var response = await client.GetAsync($"posts/{id}");
+                if (response.IsSuccessStatusCode)
+                {
+                    Debug.WriteLine("success");
+                    var responseString = await response.Content.ReadAsStringAsync();
+                    result = JsonConvert.DeserializeObject<Post>(responseString);
+                }
+            }
+            return result;
+        }
+
     }
 }


Fixing inconsistencies that made build impossibe.

--- src/dotnet/Telemetry.cs
+++ src/dotnet/Telemetry.cs
@@ -80,7 +80,7 @@
             try
             {
                 _trackEventTask = _trackEventTask.ContinueWith(
-                    () => TrackEventTask(eventName,
+                    x => TrackEventTask(eventName,
                         properties,
                         measurements)
                 );


use sample config.json

use sample config.json

--- dot-net/Demo/Program.cs
+++ dot-net/Demo/Program.cs
@@ -11,7 +11,7 @@
     {
         static void Main(string[] args)
         {
-            var c = new Centroid();
+            var c = new Centroid("../../../../config.json");
             foreach (string env in new [] { "Dev", "Test", "Prod" })
             {
                 dynamic config = c.Environment(env);


Set default page count for the shoutbox history function to 1

--- src/epvpapi/Shoutbox.cs
+++ src/epvpapi/Shoutbox.cs
@@ -142,7 +142,7 @@
             /// <param name="updateShoutbox"> When set to true, additional shoutbox information will be updated on the fly. This does not cause any major
             /// resources to be used since the information can be parsed from the same <c>HtmlDocument</c> as the channel history </param>
             /// <returns> Shouts listed in the channel history that could be obtained and parsed </returns>
-            public List<Shout> History(ProfileSession<PremiumUser> session, uint pageCount = 10, uint firstPage = 1, bool updateShoutbox = true)
+            public List<Shout> History(ProfileSession<PremiumUser> session, uint pageCount = 1, uint firstPage = 1, bool updateShoutbox = true)
             {
                 session.ThrowIfInvalid();


add AutoSprite

add AutoSprite

--- unity/UnityUIUtil.cs
+++ unity/UnityUIUtil.cs
@@ -206,9 +206,6 @@

-
-
-
 #if F3_ENABLE_TEXT_MESH_PRO

         public static void SetBackgroundColor(TMPro.TMP_InputField field, Color color) {
@@ -220,5 +217,28 @@
 #endif

+
+
+
+
+
+
+        public class AutoSprite
+        {
+            string path;
+            Sprite sprite;
+            public AutoSprite(string resource_path)
+            {
+                path = resource_path;
+            }
+            public Sprite Sprite {
+                get {
+                    if (sprite == null)
+                        sprite = Resources.Load<Sprite>(path);
+                    return sprite;
+                }
+            }
+        }
+
     }
 }


Fix issue where the maximum width is also treated as the maximum height.

--- src/SilDev/WinApi.cs
+++ src/SilDev/WinApi.cs
@@ -5,7 +5,7 @@
 // ==============================================
 //
 // Filename: WinApi.cs
-// Version:  2017-10-21 14:59
+// Version:  2017-10-31 03:21
 //
 // Copyright (c) 2017, Si13n7 Developments (r)
 // All rights reserved.
@@ -3106,7 +3106,7 @@
             /// </param>
             public static ProcessBasicInformation GetProcessBasicInformation(IntPtr hWnd)
             {
-                var status = NativeMethods.NtQueryInformationProcess(hWnd, ProcessInfoFlags.ProcessBasicInformation, out ProcessBasicInformation pbi, (uint)Marshal.SizeOf(typeof(ProcessBasicInformation)), out IntPtr _);
+                var status = NativeMethods.NtQueryInformationProcess(hWnd, ProcessInfoFlags.ProcessBasicInformation, out var pbi, (uint)Marshal.SizeOf(typeof(ProcessBasicInformation)), out IntPtr _);
                 try
                 {
                     if (status >= 0xc0000000)
@@ -3531,7 +3531,7 @@
             /// </param>
             public static void MoveWindowToVisibleScreenArea(IntPtr hWnd)
             {
-                if (!WindowIsOutOfScreenArea(hWnd, out Rectangle rect))
+                if (!WindowIsOutOfScreenArea(hWnd, out var rect))
                     return;
                 NativeMethods.MoveWindow(hWnd, rect.X, rect.Y, rect.Width, rect.Height, false);
             }
@@ -4797,7 +4797,7 @@
                         range = new Rectangle
                         {
                             X = vRect.X + vRect.Width / 2,
-                            Y = vRect.Y + vRect.Width / 2,
+                            Y = vRect.Y + vRect.Height / 2,
                             Width = vRect.Width / 2,
                             Height = vRect.Height / 2
                         };


Added additional char to default values for HtmlEscape

--- Wyam.Modules.Html/HtmlEscape.cs
+++ Wyam.Modules.Html/HtmlEscape.cs
@@ -9,7 +9,7 @@
 using Wyam.Common.Modules;
 using Wyam.Common.Pipelines;

-namespace Wyam.Modules.CreateReferences
+namespace Wyam.Modules.Html
 {
     public class HtmlEscape : IModule
     {
@@ -131,7 +131,9 @@
                 _standardCharacters.Add(c);
             for (char c = 'A'; c <= 'Z'; c++)
                 _standardCharacters.Add(c);
+            _standardCharacters.Add('\r');
             _standardCharacters.Add('\n');
+            _standardCharacters.Add(' ');
             return this;
         }


Recognize Rocket League as a supported game(partially).


usingの順序を変更

usingの順序を変更

--- uxConsole/Program.cs
+++ uxConsole/Program.cs
@@ -2,9 +2,9 @@
  * Copyright (C) 2013 Tomona Nanase. All rights reserved.
  */

-using ALSharp;
 using System;
 using System.Linq;
+using ALSharp;
 using uxMidi;

 namespace uxConsole


Added missing xml doc

Added missing xml doc

--- source/Graphite/Configuration/ConnectionStringContainer.cs
+++ source/Graphite/Configuration/ConnectionStringContainer.cs
@@ -20,11 +20,17 @@
             this.statsd = new Lazy<IStatsDConfiguration>(() => new StatsDConnectionStringConfiguration());
         }

+        /// <summary>
+        /// The graphite configuration.
+        /// </summary>
         public IGraphiteConfiguration Graphite
         {
             get { return this.graphite.Value; }
         }

+        /// <summary>
+        /// The statsd configuration.
+        /// </summary>
         public IStatsDConfiguration StatsD
         {
             get { return this.statsd.Value; }


Add tags to search

Add tags to search

--- src/ArcGISRuntime.Samples.Shared/Managers/SampleManager.cs
+++ src/ArcGISRuntime.Samples.Shared/Managers/SampleManager.cs
@@ -154,7 +154,8 @@
             searchText = searchText.ToLower();
             return sample.SampleName.ToLower().Contains(searchText) ||
                    sample.Category.ToLower().Contains(searchText) ||
-                   sample.Description.ToLower().Contains(searchText);
+                   sample.Description.ToLower().Contains(searchText) ||
+                   sample.Tags.Any(tag => tag.Contains(searchText));
         }
     }
 }


Save state of skip registration and voting checkboxes after validation.

--- src/CompetitionPlatform/Views/Project/CreateProject.cshtml
+++ src/CompetitionPlatform/Views/Project/CreateProject.cshtml
@@ -30,20 +30,36 @@

Project Flow

+
+                        @{
+                            var enableRegistrationChecked = "checked";
+                            if (Model != null && Model.SkipRegistration)
+                            {
+                                enableRegistrationChecked = "";
+                            }
+                        }
+

                                     Registration

-                                        <input id="enableRegistration" name="enableRegistration" type="checkbox" class="switcher__elem" value="true" checked="checked" />
+                                        <input id="enableRegistration" name="enableRegistration" type="checkbox" class="switcher__elem" value="true" @enableRegistrationChecked />

-                                            <input id="registrationDeadlineDatepicker" asp-for="CompetitionRegistrationDeadline" class="form-control datetimepicker" />
+                                            @if (Model != null && Model.SkipRegistration)
+                                            {
+                                                <input id="registrationDeadlineDatepicker" asp-for="CompetitionRegistrationDeadline" class="form-control datetimepicker" style="display: none" />
+                                            }
+                                            else
+                                            {
+                                                <input id="registrationDeadlineDatepicker" asp-for="CompetitionRegistrationDeadline" class="form-control datetimepicker" />
+                                            }

@@ -72,20 +88,35 @@

+                        @{
+                            var enableVotingChecked = "checked";
+                            if (Model != null && Model.SkipVoting)
+                            {
+                                enableVotingChecked = "";
+                            }
+                        }
+

                                     Voting

-                                        <input id="enableVoting" name="enableVoting" type="checkbox" class="switcher__elem" value="true" checked="checked" />
+                                        <input id="enableVoting" name="enableVoting" type="checkbox" class="switcher__elem" value="true" @enableVotingChecked />

-                                            <input id="votingDeadlineDatepicker" asp-for="VotingDeadline" class="form-control datetimepicker" />
+                                            @if (Model != null && Model.SkipVoting)
+                                            {
+                                                <input id="votingDeadlineDatepicker" asp-for="VotingDeadline" class="form-control datetimepicker" style="display: none" />
+                                            }
+                                            else
+                                            {
+                                                <input id="votingDeadlineDatepicker" asp-for="VotingDeadline" class="form-control datetimepicker" />
+                                            }

@@ -219,7 +250,7 @@

-
+


Prevent two is/as checks.

Prevent two is/as checks.

--- src/Compilers/CSharp/Portable/Binder/LocalBinderFactory.cs
+++ src/Compilers/CSharp/Portable/Binder/LocalBinderFactory.cs
@@ -53,11 +53,12 @@
         {
             var builder = new LocalBinderFactory(containingMemberOrLambda, syntax, enclosing, methodsWithYields);

-            if (syntax is ExpressionSyntax)
+            var exprNode = syntax as ExpressionSyntax;
+            if (exprNode != null)
             {
                 var binder = new ExpressionVariableBinder(syntax, enclosing);
                 builder.AddToMap(syntax, binder);
-                builder.Visit((CSharpSyntaxNode)syntax, binder);
+                builder.Visit(exprNode, binder);
             }
             else
             {


Moved shadow down

Moved shadow down

--- Assets/Shadow.cs
+++ Assets/Shadow.cs
@@ -30,7 +30,7 @@
 		for (; j < points.Count; j++) {
 			Point p = points[j];
 			double x = centre - Math.Cos (p.getTheta()) * p.getRad();
-			double y = -Camera.main.orthographicSize - (Math.Sin (p.getTheta()) * p.getRad());
+			double y = -Camera.main.orthographicSize - Camera.main.orthographicSize * 0.05d + (Math.Sin (p.getTheta()) * p.getRad());
 			vertices[j] = new Vector2((float)x,(float) y);
 		}
 		vertices [j++] = new Vector2 ((float)+ size,(float) -size);
@@ -178,7 +178,7 @@
 			for (; j < points.Count; j++) {
 				Point p = points [j];
 				double x = centre - Math.Cos (p.getTheta ()) * (p.getRad () + p.getDrawOffset ());
-				double y = -Camera.main.orthographicSize + (Math.Sin (p.getTheta ()) * (p.getRad () + p.getDrawOffset ()));
+				double y = -Camera.main.orthographicSize - Camera.main.orthographicSize * 0.05d + (Math.Sin (p.getTheta ()) * (p.getRad () + p.getDrawOffset ()));
 				vertices [j] = new Vector2 ((float)x, (float)y);
 			}
 			vertices [j++] = new Vector2 ((float)+ size, (float)-size);


Fixed multi-line descriptions in code generation.

--- src/DtronixModeler/Generator/Output/CSharpCodeGenerator.cs
+++ src/DtronixModeler/Generator/Output/CSharpCodeGenerator.cs
@@ -256,8 +256,13 @@
                 {
                     sb.AppendLine($"        /// <summary>");
                     sb.AppendLine($"        /// Column name.");
-                    if (string.IsNullOrWhiteSpace(table.Column[i].Description) == false)
-                        sb.AppendLine($"        /// {table.Column[i].Description}");
+                    var description = table.Column[i].Description;
+                    var descriptionLines = description?.Split('\n');
+                    if (string.IsNullOrWhiteSpace(description) == false)
+                    {
+                        foreach (var descriptionLine in descriptionLines)
+                            sb.AppendLine($"        /// {descriptionLine}");
+                    }

                     sb.AppendLine("        /// </summary>");
                     sb.AppendLine(
@@ -268,11 +273,12 @@
                     sb.AppendLine($"        /// </summary>");
                     sb.AppendLine($"        private {ColumnNetType(table.Column[i])} _{table.Column[i].Name};");
                     sb.AppendLine($"");
-                    if (string.IsNullOrWhiteSpace(table.Column[i].Description) == false)
-                    {
-                        sb.AppendLine("        /// <summary>");
-                        sb.AppendLine($"        /// {table.Column[i].Description}");
-                        sb.AppendLine("        /// </summary>");
+                    if (string.IsNullOrWhiteSpace(description) == false)
+                    {
+                        sb.AppendLine($"        /// <summary>");
+                        foreach (var descriptionLine in descriptionLines)
+                            sb.AppendLine($"        /// {descriptionLine}");
+                        sb.AppendLine($"        /// </summary>");
                     }

                     if (this.database.ImplementProtobufNetDataContracts)


fix ExchangeDeclare

fix ExchangeDeclare

--- src/LinFx/Extensions/EventBus/RabbitMQ/EventBusRabbitMQ.cs
+++ src/LinFx/Extensions/EventBus/RabbitMQ/EventBusRabbitMQ.cs
@@ -84,7 +84,9 @@
                 var eventName = evt.GetType().Name;

                 channel.ExchangeDeclare(exchange: _options.BrokerName,
-                                    type: "direct");
+                                    type: "direct",
+                                    durable: _options.Durable,
+                                    autoDelete: _options.AutoDelete);

                 var message = JsonConvert.SerializeObject(evt);
                 var body = Encoding.UTF8.GetBytes(message);


Expose format in PropertyModel (liquid), https://github.com/RicoSuter/NSwag/issues/3246

--- src/NJsonSchema.CodeGeneration/Models/PropertyModelBase.cs
+++ src/NJsonSchema.CodeGeneration/Models/PropertyModelBase.cs
@@ -70,6 +70,9 @@
         /// Gets the property extension data.
         public IDictionary<string, object> ExtensionData => _property.ExtensionData;

+        /// Gets the JSON Schema format property.
+        public string Format => _property.ActualSchema.Format;
+
         /// Gets the type name hint for the property.
         protected string GetTypeNameHint()
         {


Added async schema factory to ObjectTypeMapper

--- src/NJsonSchema/Generation/TypeMappers/ObjectTypeMapper.cs
+++ src/NJsonSchema/Generation/TypeMappers/ObjectTypeMapper.cs
@@ -14,7 +14,7 @@
     /// Maps .NET type to a generated JSON Schema describing an object.
     public class ObjectTypeMapper : ITypeMapper
     {
-        private readonly Func<JsonSchemaGenerator, JsonSchemaResolver, JsonSchema4> _schemaFactory;
+        private readonly Func<JsonSchemaGenerator, JsonSchemaResolver, Task<JsonSchema4>> _schemaFactory;

         /// Initializes a new instance of the <see cref="ObjectTypeMapper"/> class.
         /// <param name="mappedType">Type of the mapped.</param>
@@ -24,10 +24,21 @@
         {
         }

+
         /// Initializes a new instance of the <see cref="ObjectTypeMapper"/> class.
         /// <param name="mappedType">Type of the mapped.</param>
         /// <param name="schemaFactory">The schema factory.</param>
         public ObjectTypeMapper(Type mappedType, Func<JsonSchemaGenerator, JsonSchemaResolver, JsonSchema4> schemaFactory)
+#pragma warning disable 1998
+            : this(mappedType, async (schemaGenerator, schemaResolver) => schemaFactory(schemaGenerator, schemaResolver))
+#pragma warning restore 1998
+        {
+        }
+
+        /// Initializes a new instance of the <see cref="ObjectTypeMapper"/> class.
+        /// <param name="mappedType">Type of the mapped.</param>
+        /// <param name="schemaFactory">The schema factory.</param>
+        public ObjectTypeMapper(Type mappedType, Func<JsonSchemaGenerator, JsonSchemaResolver, Task<JsonSchema4>> schemaFactory)
         {
             _schemaFactory = schemaFactory;
             MappedType = mappedType;
@@ -47,7 +58,7 @@
 #pragma warning restore 1998
         {
             if (!context.JsonSchemaResolver.HasSchema(MappedType, false))
-                context.JsonSchemaResolver.AddSchema(MappedType, false, _schemaFactory(context.JsonSchemaGenerator, context.JsonSchemaResolver));
+                context.JsonSchemaResolver.AddSchema(MappedType, false, await _schemaFactory(context.JsonSchemaGenerator, context.JsonSchemaResolver));

             schema.Reference = context.JsonSchemaResolver.GetSchema(MappedType, false);
         }


Fix indentation in compound conditional

Fix indentation in compound conditional

--- src/NUnitFramework/tests/Internal/RuntimeFrameworkTests.cs
+++ src/NUnitFramework/tests/Internal/RuntimeFrameworkTests.cs
@@ -34,10 +34,10 @@
             RuntimeType.Silverlight;
 #else
             Type.GetType("Mono.Runtime", false) != null
-            ? RuntimeType.Mono
-            : Environment.OSVersion.Platform == PlatformID.WinCE
-            ? RuntimeType.NetCF
-            : RuntimeType.Net;
+				? RuntimeType.Mono
+				: Environment.OSVersion.Platform == PlatformID.WinCE
+					? RuntimeType.NetCF
+					: RuntimeType.Net;
 #endif

         [Test]


Included non-public properties in the config bootstrapper test

--- src/Nancy.Testing.Tests/ConfigurableBootstrapperFixture.cs
+++ src/Nancy.Testing.Tests/ConfigurableBootstrapperFixture.cs
@@ -179,7 +179,7 @@
                 new[] { typeof(NancyBootstrapperBase<>), typeof(NancyInternalConfiguration) };

             return typesToReflect
-                .SelectMany(x => x.GetProperties(BindingFlags.Public | BindingFlags.Instance))
+                .SelectMany(x => x.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic))
                 .Select(x => x.Name)
                 .Where(x => !ignoreList.Contains(x, StringComparer.OrdinalIgnoreCase));
         }


修复酷Q发送自定义图片和语音在CQ码中使用绝对路径的BUG

修复酷Q发送自定义图片和语音在CQ码中使用绝对路径的BUG

--- src/Newbe.Mahua.CQP/Messages/Builders/CqpMessageBuilder.cs
+++ src/Newbe.Mahua.CQP/Messages/Builders/CqpMessageBuilder.cs
@@ -60,24 +60,24 @@
         /// <param name="file"></param>
         public void Image(string file)
         {
-            var destFileName = file;
+            var fileName = Path.GetFileName(file);
             if (!file.StartsWith(CqpDirectories.Image))
             {
-                destFileName = Path.Combine(CqpDirectories.Image, Path.GetFileName(file));
-                File.Copy(file, destFileName);
+                var destFileName = Path.Combine(CqpDirectories.Image, fileName);
+                File.Copy(file, destFileName,true);
             }
-            _message.Append($"[CQ:image,file={destFileName}]");
+            _message.Append($"[CQ:image,file={fileName}]");
         }

         public void Record(string file)
         {
-            var destFileName = file;
-            if (!file.StartsWith(CqpDirectories.Record))
+            var fileName = Path.GetFileName(file);
+            if (!file.StartsWith(CqpDirectories.Image))
             {
-                destFileName = Path.Combine(CqpDirectories.Record, Path.GetFileName(file));
-                File.Copy(file, destFileName);
+                var destFileName = Path.Combine(CqpDirectories.Image, fileName);
+                File.Copy(file, destFileName, true);
             }
-            _message.Append($"[CQ:record,file={destFileName},magic=false]");
+            _message.Append($"[CQ:record,file={fileName},magic=false]");
         }

         public void SFace(string id)


cleanup

cleanup

--- src/Peachpie.CodeAnalysis/Utilities/EnumeratorExtension.cs
+++ src/Peachpie.CodeAnalysis/Utilities/EnumeratorExtension.cs
@@ -41,13 +41,12 @@
         /// <returns>Value corresponding to key or default of <typeparamref name="T"/>.</returns>
         public static T TryGetOrDefault<K, T>(this IDictionary<K, T> dict, K key)
         {
-            T value;
-            if (!dict.TryGetValue(key, out value))
-            {
-                value = default(T);
-            }
-
-            return value;
+            if (dict.TryGetValue(key, out var value))
+            {
+                return value;
+            }
+
+            return default;
         }

         /// <summary>


Try catch on receiver to try to track down the AggregateException being thrown.

--- src/ProjectExtensions.Azure.ServiceBus/AzureBusReceiver.cs
+++ src/ProjectExtensions.Azure.ServiceBus/AzureBusReceiver.cs
@@ -179,6 +179,8 @@
             RetryPolicy retryPolicy;
             AzureBusReceiverState data;

+            int failCounter = 0;
+
             public AzureBusReceiverState Data {
                 get {
                     return data;
@@ -191,150 +193,163 @@
             }

             public void ProcessMessagesForSubscription() {
-                Guard.ArgumentNotNull(data, "data");
-
-                logger.Info("ProcessMessagesForSubscription Message Start {0} Declared {1} MessageTytpe {2}, IsReusable {3}", data.EndPointData.SubscriptionName,
-                        data.EndPointData.DeclaredType.ToString(), data.EndPointData.MessageType.ToString(), data.EndPointData.IsReusable);
-
-                //TODO create a cache for object creation.
-                var gt = typeof(IReceivedMessage<>).MakeGenericType(data.EndPointData.MessageType);
-
-                //set up the methodinfo
-                var methodInfo = data.EndPointData.DeclaredType.GetMethod("Handle",
-                    new Type[] { gt, typeof(IDictionary<string, object>) });
-
-                var serializer = BusConfiguration.Container.Resolve<IServiceBusSerializer>();
-
-                var waitTimeout = TimeSpan.FromSeconds(30);
-
-                // Declare an action acting as a callback whenever a message arrives on a queue.
-                AsyncCallback completeReceive = null;
-
-                // Declare an action acting as a callback whenever a non-transient exception occurs while receiving or processing messages.
-                Action<Exception> recoverReceive = null;
-
-                // Declare an action implementing the main processing logic for received messages.
-                Action<AzureReceiveState> processMessage = ((receiveState) => {
-                    // Put your custom processing logic here. DO NOT swallow any exceptions.
-                    ProcessMessageCallBack(receiveState);
-                });
-
-                var client = data.Client;
-
-                bool messageReceived = false;
-
-                // Declare an action responsible for the core operations in the message receive loop.
-                Action receiveMessage = (() => {
-                    // Use a retry policy to execute the Receive action in an asynchronous and reliable fashion.
-                    retryPolicy.ExecuteAction
-                    (
-                        (cb) => {
-                            // Start receiving a new message asynchronously.
-                            client.BeginReceive(waitTimeout, cb, null);
-                        },
-                        (ar) => {
-                            messageReceived = false;
-                            // Make sure we are not told to stop receiving while we were waiting for a new message.
-                            if (!data.CancelToken.IsCancellationRequested) {
-                                // Complete the asynchronous operation. This may throw an exception that will be handled internally by retry policy.
-                                BrokeredMessage msg = client.EndReceive(ar);
-
-                                // Check if we actually received any messages.
-                                if (msg != null) {
-                                    // Make sure we are not told to stop receiving while we were waiting for a new message.
-                                    if (!data.CancelToken.IsCancellationRequested) {
-                                        try {
-                                            // Process the received message.
-                                            messageReceived = true;
-                                            logger.Debug("ProcessMessagesForSubscription Start received new message: {0}", data.EndPointData.SubscriptionName);
-                                            var receiveState = new AzureReceiveState(data, methodInfo, serializer, msg);
-                                            processMessage(receiveState);
-                                            logger.Debug("ProcessMessagesForSubscription End received new message: {0}", data.EndPointData.SubscriptionName);
-
-                                            // With PeekLock mode, we should mark the processed message as completed.
-                                            if (client.Mode == ReceiveMode.PeekLock) {
-                                                // Mark brokered message as completed at which point it's removed from the queue.
-                                                SafeComplete(msg);
+
+                try {
+
+                    Guard.ArgumentNotNull(data, "data");
+
+                    logger.Info("ProcessMessagesForSubscription Message Start {0} Declared {1} MessageTytpe {2}, IsReusable {3}", data.EndPointData.SubscriptionName,
+                            data.EndPointData.DeclaredType.ToString(), data.EndPointData.MessageType.ToString(), data.EndPointData.IsReusable);
+
+                    //TODO create a cache for object creation.
+                    var gt = typeof(IReceivedMessage<>).MakeGenericType(data.EndPointData.MessageType);
+
+                    //set up the methodinfo
+                    var methodInfo = data.EndPointData.DeclaredType.GetMethod("Handle",
+                        new Type[] { gt, typeof(IDictionary<string, object>) });
+
+                    var serializer = BusConfiguration.Container.Resolve<IServiceBusSerializer>();
+
+                    var waitTimeout = TimeSpan.FromSeconds(30);
+
+                    // Declare an action acting as a callback whenever a message arrives on a queue.
+                    AsyncCallback completeReceive = null;
+
+                    // Declare an action acting as a callback whenever a non-transient exception occurs while receiving or processing messages.
+                    Action<Exception> recoverReceive = null;
+
+                    // Declare an action implementing the main processing logic for received messages.
+                    Action<AzureReceiveState> processMessage = ((receiveState) => {
+                        // Put your custom processing logic here. DO NOT swallow any exceptions.
+                        ProcessMessageCallBack(receiveState);
+                    });
+
+                    var client = data.Client;
+
+                    bool messageReceived = false;
+
+                    // Declare an action responsible for the core operations in the message receive loop.
+                    Action receiveMessage = (() => {
+                        // Use a retry policy to execute the Receive action in an asynchronous and reliable fashion.
+                        retryPolicy.ExecuteAction
+                        (
+                            (cb) => {
+                                // Start receiving a new message asynchronously.
+                                client.BeginReceive(waitTimeout, cb, null);
+                            },
+                            (ar) => {
+                                messageReceived = false;
+                                // Make sure we are not told to stop receiving while we were waiting for a new message.
+                                if (!data.CancelToken.IsCancellationRequested) {
+                                    // Complete the asynchronous operation. This may throw an exception that will be handled internally by retry policy.
+                                    BrokeredMessage msg = client.EndReceive(ar);
+
+                                    // Check if we actually received any messages.
+                                    if (msg != null) {
+                                        // Make sure we are not told to stop receiving while we were waiting for a new message.
+                                        if (!data.CancelToken.IsCancellationRequested) {
+                                            try {
+                                                // Process the received message.
+                                                messageReceived = true;
+                                                logger.Debug("ProcessMessagesForSubscription Start received new message: {0}", data.EndPointData.SubscriptionName);
+                                                var receiveState = new AzureReceiveState(data, methodInfo, serializer, msg);
+                                                processMessage(receiveState);
+                                                logger.Debug("ProcessMessagesForSubscription End received new message: {0}", data.EndPointData.SubscriptionName);
+
+                                                // With PeekLock mode, we should mark the processed message as completed.
+                                                if (client.Mode == ReceiveMode.PeekLock) {
+                                                    // Mark brokered message as completed at which point it's removed from the queue.
+                                                    SafeComplete(msg);
+                                                }
+                                            }
+                                            catch {
+                                                // With PeekLock mode, we should mark the failed message as abandoned.
+                                                if (client.Mode == ReceiveMode.PeekLock) {
+                                                    // Abandons a brokered message. This will cause Service Bus to unlock the message and make it available
+                                                    // to be received again, either by the same consumer or by another completing consumer.
+                                                    SafeAbandon(msg);
+                                                }
+
+                                                // Re-throw the exception so that we can report it in the fault handler.
+                                                throw;
+                                            }
+                                            finally {
+                                                // Ensure that any resources allocated by a BrokeredMessage instance are released.
+                                                msg.Dispose();
                                             }
                                         }
-                                        catch {
-                                            // With PeekLock mode, we should mark the failed message as abandoned.
+                                        else {
+                                            // If we were told to stop processing, the current message needs to be unlocked and return back to the queue.
                                             if (client.Mode == ReceiveMode.PeekLock) {
-                                                // Abandons a brokered message. This will cause Service Bus to unlock the message and make it available
-                                                // to be received again, either by the same consumer or by another completing consumer.
                                                 SafeAbandon(msg);
                                             }
-
-                                            // Re-throw the exception so that we can report it in the fault handler.
-                                            throw;
-                                        }
-                                        finally {
-                                            // Ensure that any resources allocated by a BrokeredMessage instance are released.
-                                            msg.Dispose();
-                                        }
-                                    }
-                                    else {
-                                        // If we were told to stop processing, the current message needs to be unlocked and return back to the queue.
-                                        if (client.Mode == ReceiveMode.PeekLock) {
-                                            SafeAbandon(msg);
                                         }
                                     }
                                 }
-                            }
-
-                            // Invoke a custom callback method to indicate that we have completed an iteration in the message receive loop.
-                            completeReceive(ar);
-                        },
-                        (ex) => {
-                            // Invoke a custom action to indicate that we have encountered an exception and
-                            // need further decision as to whether to continue receiving messages.
-                            recoverReceive(ex);
-                        });
-                });
-
-                // Initialize a custom action acting as a callback whenever a message arrives on a queue.
-                completeReceive = ((ar) => {
-                    if (!data.CancelToken.IsCancellationRequested) {
-                        // Continue receiving and processing new messages until we are told to stop.
-                        receiveMessage();
-                    }
-                    else {
-                        data.SetMessageLoopCompleted();
-                    }
-
-                    if (messageReceived) {
-                        logger.Debug("ProcessMessagesForSubscription Message Complete={0} Declared={1} MessageTytpe={2} IsReusable={3}", data.EndPointData.SubscriptionName,
-                            data.EndPointData.DeclaredType.ToString(), data.EndPointData.MessageType.ToString(), data.EndPointData.IsReusable);
-                    }
-                });
-
-                // Initialize a custom action acting as a callback whenever a non-transient exception occurs while receiving or processing messages.
-                recoverReceive = ((ex) => {
-                    // Just log an exception. Do not allow an unhandled exception to terminate the message receive loop abnormally.
-
-                    logger.Error(string.Format("ProcessMessagesForSubscription Message Error={0} Declared={1} MessageTytpe={2} IsReusable={3} Error={4}",
-                        data.EndPointData.SubscriptionName,
-                        data.EndPointData.DeclaredType.ToString(),
-                        data.EndPointData.MessageType.ToString(),
-                        data.EndPointData.IsReusable,
-                        ex.ToString()));
-
-                    if (!data.CancelToken.IsCancellationRequested) {
-                        // Continue receiving and processing new messages until we are told to stop regardless of any exceptions.
-                        receiveMessage();
-                    }
-                    else {
-                        data.SetMessageLoopCompleted();
-                    }
-
-                    if (messageReceived) {
-                        logger.Debug("ProcessMessagesForSubscription Message Complete={0} Declared={1} MessageTytpe={2} IsReusable={3}", data.EndPointData.SubscriptionName,
-                            data.EndPointData.DeclaredType.ToString(), data.EndPointData.MessageType.ToString(), data.EndPointData.IsReusable);
-                    }
-                });
-
-                // Start receiving messages asynchronously.
-                receiveMessage();
+
+                                // Invoke a custom callback method to indicate that we have completed an iteration in the message receive loop.
+                                completeReceive(ar);
+                            },
+                            (ex) => {
+                                // Invoke a custom action to indicate that we have encountered an exception and
+                                // need further decision as to whether to continue receiving messages.
+                                recoverReceive(ex);
+                            });
+                    });
+
+                    // Initialize a custom action acting as a callback whenever a message arrives on a queue.
+                    completeReceive = ((ar) => {
+                        if (!data.CancelToken.IsCancellationRequested) {
+                            // Continue receiving and processing new messages until we are told to stop.
+                            receiveMessage();
+                        }
+                        else {
+                            data.SetMessageLoopCompleted();
+                        }
+
+                        if (messageReceived) {
+                            logger.Debug("ProcessMessagesForSubscription Message Complete={0} Declared={1} MessageTytpe={2} IsReusable={3}", data.EndPointData.SubscriptionName,
+                                data.EndPointData.DeclaredType.ToString(), data.EndPointData.MessageType.ToString(), data.EndPointData.IsReusable);
+                        }
+                    });
+
+                    // Initialize a custom action acting as a callback whenever a non-transient exception occurs while receiving or processing messages.
+                    recoverReceive = ((ex) => {
+                        // Just log an exception. Do not allow an unhandled exception to terminate the message receive loop abnormally.
+
+                        logger.Error(string.Format("ProcessMessagesForSubscription Message Error={0} Declared={1} MessageTytpe={2} IsReusable={3} Error={4}",
+                            data.EndPointData.SubscriptionName,
+                            data.EndPointData.DeclaredType.ToString(),
+                            data.EndPointData.MessageType.ToString(),
+                            data.EndPointData.IsReusable,
+                            ex.ToString()));
+
+                        if (!data.CancelToken.IsCancellationRequested) {
+                            // Continue receiving and processing new messages until we are told to stop regardless of any exceptions.
+                            receiveMessage();
+                        }
+                        else {
+                            data.SetMessageLoopCompleted();
+                        }
+
+                        if (messageReceived) {
+                            logger.Debug("ProcessMessagesForSubscription Message Complete={0} Declared={1} MessageTytpe={2} IsReusable={3}", data.EndPointData.SubscriptionName,
+                                data.EndPointData.DeclaredType.ToString(), data.EndPointData.MessageType.ToString(), data.EndPointData.IsReusable);
+                        }
+                    });
+
+                    // Start receiving messages asynchronously.
+                    receiveMessage();
+                }
+                catch (Exception ex) {
+                    failCounter++;
+                    logger.Error("ProcessMessagesForSubscription: Error during receive during loop. See details and fix: {0}", ex);
+                    if (failCounter < 100) {
+                        //try again
+                        ProcessMessagesForSubscription();
+                    }
+                }
+
             }

             void ProcessMessageCallBack(AzureReceiveState state) {


Fix shocking grammar and typos in block comment

Co-authored-by: Bartłomiej Dach <809709723693c4e7ecc6f5379a3099c830279741@gmail.com>

--- osu.Game/Graphics/Containers/ScalingContainer.cs
+++ osu.Game/Graphics/Containers/ScalingContainer.cs
@@ -190,9 +190,9 @@
             sizableContainer.MoveTo(targetRect.Location, duration, Easing.OutQuart);
             sizableContainer.ResizeTo(targetRect.Size, duration, Easing.OutQuart);

-            // Of note, this will not working great in the case of nested ScalingContainers where multiple are applying corner radius.
-            // There should likely only be masking and corner radius applied at one point in the full game stack to fix this.
-            // An example of how this can occur is it the skin editor is visible and the game screen scaling is set to "Everything".
+            // Of note, this will not work great in the case of nested ScalingContainers where multiple are applying corner radius.
+            // Masking and corner radius should likely only be applied at one point in the full game stack to fix this.
+            // An example of how this can occur is when the skin editor is visible and the game screen scaling is set to "Everything".
             sizableContainer.TransformTo(nameof(CornerRadius), requiresMasking ? corner_radius : 0, duration, requiresMasking ? Easing.OutQuart : Easing.None)
                             .OnComplete(_ => { sizableContainer.Masking = requiresMasking; });
         }


Fix issue #2 from Github: Mono: NullReferenceException for concurrent requests.

--- src/RedisSessionStateProvider/RedisSessionStateProvider.cs
+++ src/RedisSessionStateProvider/RedisSessionStateProvider.cs
@@ -199,6 +199,10 @@
                 lockAge = TimeSpan.Zero;
                 lockId = 0;
                 actions = SessionStateActions.None;
+                if (id == null)
+                {
+                    return null;
+                }
                 GetAccessToStore(id);
                 ISessionStateItemCollection sessionData = null;


Moved ShowProfile to the bottom of the enum

--- osu.Game/Input/Bindings/GlobalActionContainer.cs
+++ osu.Game/Input/Bindings/GlobalActionContainer.cs
@@ -233,9 +233,6 @@
         [LocalisableDescription(typeof(GlobalActionKeyBindingStrings), nameof(GlobalActionKeyBindingStrings.ToggleNotifications))]
         ToggleNotifications,

-        [LocalisableDescription(typeof(GlobalActionKeyBindingStrings), nameof(GlobalActionKeyBindingStrings.ShowProfile))]
-        ShowProfile,
-
         [LocalisableDescription(typeof(GlobalActionKeyBindingStrings), nameof(GlobalActionKeyBindingStrings.PauseGameplay))]
         PauseGameplay,

@@ -336,5 +333,8 @@

         [LocalisableDescription(typeof(GlobalActionKeyBindingStrings), nameof(GlobalActionKeyBindingStrings.ToggleFPSCounter))]
         ToggleFPSDisplay,
+
+        [LocalisableDescription(typeof(GlobalActionKeyBindingStrings), nameof(GlobalActionKeyBindingStrings.ShowProfile))]
+        ShowProfile,
     }
 }


Tweak

Tweak

--- src/SFA.DAS.EAS.Web/Views/Shared/EditApprenticeship.cshtml
+++ src/SFA.DAS.EAS.Web/Views/Shared/EditApprenticeship.cshtml
@@ -144,7 +144,7 @@
     Add a reference, such as employee number or location - this can help identify this apprentice if you have more than one with the same name.
     @Html.ValidationMessage("EmployerRef", new { id = "error-message-EmployerRef" })
     @Html.TextBox("EmployerRef", Model.Apprenticeship.EmployerRef, new { @class = "form-control form-control-3-4" })
-
Enter upto a maximum of 20 characters

+
Enter up to a maximum of 20 characters

 characters remaining


Enable nullable: System.Management.Automation.ICommandRuntime2 (#14183)

--- src/System.Management.Automation/engine/ICommandRuntime.cs
+++ src/System.Management.Automation/engine/ICommandRuntime.cs
@@ -560,6 +560,7 @@
     /// execute an instance of a Cmdlet. ICommandRuntime2 extends the ICommandRuntime interface
     /// by adding support for the informational data stream.
     /// </summary>
+#nullable enable
     public interface ICommandRuntime2 : ICommandRuntime
     {
         /// <summary>
@@ -614,6 +615,6 @@
         /// performed, and the Cmdlet should move on to the next target resource.
         /// </returns>
         [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference")]
-        bool ShouldContinue(string query, string caption, bool hasSecurityImpact, ref bool yesToAll, ref bool noToAll);
+        bool ShouldContinue(string? query, string? caption, bool hasSecurityImpact, ref bool yesToAll, ref bool noToAll);
     }
 }


Improved ReceiveAsync in PersistentChannel

--- src/Takenet.MessagingHub.Client/PersistentClientChannel.cs
+++ src/Takenet.MessagingHub.Client/PersistentClientChannel.cs
@@ -4,7 +4,9 @@
 using Lime.Protocol.Security;
 using System;
 using System.Collections.Generic;
+using System.IO;
 using System.Linq;
+using System.Net.Sockets;
 using System.Text;
 using System.Threading;
 using System.Threading.Tasks;
@@ -101,12 +103,32 @@

         private async Task<T> ReceiveAsync<T>(CancellationToken cancellationToken, Func<CancellationToken, Task<T>> func)
         {
-            if (!_isConnected)
-            {
-                await EstabilishSessionAsync(cancellationToken).ConfigureAwait(false);
-            }
-
-            return await func(cancellationToken).ConfigureAwait(false);
+            while (!cancellationToken.IsCancellationRequested)
+            {
+                if (!_isConnected)
+                {
+                    await EstabilishSessionAsync(cancellationToken).ConfigureAwait(false);
+                }
+
+                try
+                {
+                    return await func(cancellationToken).ConfigureAwait(false);
+                }
+                catch (LimeException)
+                {
+                    if (_isConnected) throw;
+                }
+                catch (SocketException)
+                {
+                    if (_isConnected) throw;
+                }
+                catch (IOException)
+                {
+                    if (_isConnected) throw;
+                }
+            }
+
+            throw new OperationCanceledException();
         }

         private async Task SendAsync<T>(T envelope, Func<T, Task> func)


Delete legacy code

Delete legacy code

--- src/Umbraco.Web/_Legacy/Actions/ActionCollectionBuilder.cs
+++ src/Umbraco.Web/_Legacy/Actions/ActionCollectionBuilder.cs
@@ -1,34 +0,0 @@
-using System;
-using System.Collections.Generic;
-using Umbraco.Core.Composing;
-
-namespace Umbraco.Web._Legacy.Actions
-{
-    internal class ActionCollectionBuilder : ICollectionBuilder<ActionCollection, IAction>
-    {
-        private Func<IEnumerable<Type>> _producer;
-        private ActionCollection _collection;
-
-        // for tests only - does not register the collection
-        public ActionCollectionBuilder()
-        { }
-
-        public ActionCollectionBuilder(IContainer container)
-        {
-            // register the collection
-            container.RegisterSingleton(factory => factory.GetInstance<ActionCollectionBuilder>().CreateCollection());
-        }
-
-        public ActionCollection CreateCollection()
-        {
-            // create a special collection that can be resetted (ouch)
-            return _collection = new ActionCollection(_producer);
-        }
-
-        public void SetProducer(Func<IEnumerable<Type>> producer)
-        {
-            _producer = producer;
-            _collection?.Reset(producer);
-        }
-    }
-}


Always vertically center the git logo mark

--- src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs
+++ src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs
@@ -5,7 +5,7 @@
 using System.Linq;
 using UnityEditor;
 using UnityEngine;
-using Debug = System.Diagnostics.Debug;
+// using Debug = System.Diagnostics.Debug;

 namespace GitHub.Unity
 {
@@ -136,13 +136,14 @@

         private void DoOfferToInitializeRepositoryGUI()
         {
-            GUILayout.BeginHorizontal(Styles.HeaderBoxStyle);
+            var headerRect = EditorGUILayout.BeginHorizontal(Styles.HeaderBoxStyle);
             {
                 GUILayout.Space(3);
                 GUILayout.BeginVertical(GUILayout.Width(16));
                 {
-                    GUILayout.Space(9);
-                    GUILayout.Label(Styles.BigLogo, GUILayout.Height(20), GUILayout.Width(20));
+                    var iconRect = GUILayoutUtility.GetRect(new GUIContent(Styles.BigLogo), GUIStyle.none, GUILayout.Height(20), GUILayout.Width(20));
+                    iconRect.y = headerRect.center.y - (iconRect.height / 2);
+                    GUI.DrawTexture(iconRect, Styles.BigLogo, ScaleMode.ScaleToFit);
                 }
                 GUILayout.EndVertical();

@@ -153,7 +154,7 @@
                 }
                 GUILayout.EndVertical();
             }
-            GUILayout.EndHorizontal();
+            EditorGUILayout.EndHorizontal();
             GUILayout.BeginVertical();
             {
                 GUILayout.FlexibleSpace();


- Modified basePath() to also iterate through dict()'s and leave the recursive structure as found rather than using flatten(). This is less destructive and allows it to work with the ProjectTool.project 'items' parameter.

--- src/cake/config.cake
+++ src/cake/config.cake
@@ -12,7 +12,7 @@
 from cake.library.zipping import ZipTool
 from cake.library.compilers import CompilerNotFoundError
 from cake.library.compilers.dummy import DummyCompiler
-from cake.library import flatten, waitForAsyncResult
+from cake.library import waitForAsyncResult
 import cake.system
 import cake.path

@@ -22,12 +22,12 @@
 configuration = Script.getCurrent().configuration

 # Override the configuration basePath() function.
-@waitForAsyncResult
 def basePath(value):
   # Note: Any initial AsyncResult's should have been expanded by now,
   # so we should know if the value should be a sequence or single value.
   from cake.tools import script, env

+  @waitForAsyncResult
   def _basePath(path):
     if isinstance(path, basestring):
       path = env.expand(path)
@@ -40,13 +40,16 @@
         return path # Keep absolute paths as found.
       else:
         return script.cwd(path) # Prefix relative paths with scripts dir.
+    elif isinstance(path, (list, set)): # Convert set->list in case of valid duplicates.
+      return list(_basePath(p) for p in path)
+    elif isinstance(path, tuple):
+      return tuple(_basePath(p) for p in path)
+    elif isinstance(path, dict):
+      return dict((k, _basePath(v)) for k, v in path.iteritems())
     else:
-      return path # Could be a FileTarget.
+      return path # Could be a FileTarget. Leave it as is.

-  if isinstance(value, (list, tuple, set)):
-    return [_basePath(p) for p in flatten(value)]
-  else:
-    return _basePath(value)
+  return _basePath(value)

 configuration.basePath = basePath


(DrsOpener): additional entry offset sanity checks.

--- ArcFormats/ArcDRS.cs
+++ ArcFormats/ArcDRS.cs
@@ -43,7 +43,7 @@

         public DrsOpener ()
         {
-            Extensions = new string[0]; // DRS archives have no extensions
+            Extensions = Enumerable.Empty<string>(); // DRS archives have no extensions
         }

         public override ArcFile TryOpen (ArcView file)
@@ -60,7 +60,7 @@
             int dir_offset = 2;

             uint next_offset = file.View.ReadUInt32 (dir_offset+12);
-            if (next_offset > file.MaxOffset)
+            if (next_offset > file.MaxOffset || next_offset < dir_size+2)
                 return null;
             var encoding = Encodings.cp932.WithFatalFallback();
             byte[] name_raw = new byte[12];
@@ -78,7 +78,7 @@
                 uint offset = next_offset;
                 dir_offset += 0x10;
                 next_offset = file.View.ReadUInt32 (dir_offset+12);
-                if (next_offset > file.MaxOffset)
+                if (next_offset > file.MaxOffset || next_offset < offset)
                     return null;
                 string name = encoding.GetString (name_raw, 0, name_length).ToLowerInvariant();
                 var entry = FormatCatalog.Instance.CreateEntry (name);


[Core] Local policies were being applied at the wrong time, after recent changes

--- Bam.Core/Settings.cs
+++ Bam.Core/Settings.cs
@@ -127,11 +127,10 @@
                         i.defaultMethod.Invoke(null, new object[] { this, module });
                     }
                 }
-
-                if (null != LocalPolicy)
-                {
-                    LocalPolicy.DefineLocalSettings(this, module);
-                }
+            }
+            if (useDefaults && (null != LocalPolicy))
+            {
+                LocalPolicy.DefineLocalSettings(this, module);
             }
         }
     }


Instance를 정적 변수로 변경

Instance를 정적 변수로 변경

--- Bible2PPT/BibleDb.cs
+++ Bible2PPT/BibleDb.cs
@@ -10,14 +10,10 @@

 namespace Bible2PPT
 {
-    /// <summary>
-    /// 하나 이상의 인스턴스를 만들지 않도록 주의할 것!
-    /// </summary>
     class BibleDb : IDisposable
     {
-        private static BibleDb instance = null;
-
-        public IsamInstance Instance;
+        private static IsamInstance Instance = null;
+        private static int InstanceRefs = 0;

         public IsamSession Session;
         public IsamDatabase Database;
@@ -31,16 +27,16 @@

         public BibleDb()
         {
-            // Pre-condition Check
-            Debug.Assert(instance == null);
-            instance = this;
-
             // 주의!!
             // Instance 생성 시 매개변수로 Directory들과 BaseName, EventSource 등은
             // 고유한 값이어야 하며, 동시에 사용할 수 없음!
-            Instance = new IsamInstance(AppConfig.DatabaseWorkingDirectory);
+            if (Instance == null)
+            {
+                Instance = new IsamInstance(AppConfig.DatabaseWorkingDirectory);
+            }

             Session = Instance.CreateSession();
+            InstanceRefs++;

             try
             {
@@ -59,8 +55,16 @@
             InitializeTable(typeof(Verse));
         }

+        private static void DisposeInstance()
+        {
+            Instance?.Dispose();
+            InstanceRefs = 0;
+            Instance = null;
+        }
+
         public static void Reset()
         {
+            DisposeInstance();
             File.Delete(AppConfig.DatabasePath);
         }

@@ -173,9 +177,11 @@
                     // TODO: dispose managed state (managed objects).
                     Database.Dispose();
                     Session.Dispose();
-                    Instance.Dispose();
-
-                    instance = null;
+
+                    if (--InstanceRefs == 0)
+                    {
+                        DisposeInstance();
+                    }
                 }

                 // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.