[FIX] replace method with a one-liner

[FIX] replace method with a one-liner

--- src/CK.Glouton.Web/Controllers/LogController.cs
+++ src/CK.Glouton.Web/Controllers/LogController.cs
@@ -27,12 +27,9 @@
         /// <param name="max">The number of logs to return.</param>
         /// <returns></returns>
         [HttpGet("{appName}")]
-        public List<ILogViewModel> GetAll( [FromRoute] string appName ,int max = 10 )
+        public List<ILogViewModel> GetAll( [FromRoute] string appName ,int max = 0 )
         {
-            List<ILogViewModel> logs = _luceneSearcherService.GetAll( appName, max == 0 ? max : 500);
-            if (logs == null)
-                return new List<ILogViewModel>();
-            return logs;
+            return _luceneSearcherService.GetAll(appName, max == 0 ? 10 : max) ?? new List<ILogViewModel>();
         }


Improved pattern matching

Improved pattern matching

--- src/Common/Dispatch/AggregateDispatcher.Func.cs
+++ src/Common/Dispatch/AggregateDispatcher.Func.cs
@@ -35,7 +35,7 @@
             if (function == null) throw new ArgumentNullException(nameof(function));
             #endregion

-            _delegates.Add(value => !(value is TSpecific specificValue) ? null : function(specificValue));
+            _delegates.Add(value => value is not TSpecific specificValue ? null : function(specificValue));

             return this;
         }


InterlockedBoolean overloads equality(==) for comparisons with bools and other instances of InterlockedBoolean.

--- src/Common/RestBus.Common/InterlockedBoolean.cs
+++ src/Common/RestBus.Common/InterlockedBoolean.cs
@@ -134,5 +134,35 @@
         {
             return IsTrue.GetHashCode();
         }
+
+        public static bool operator ==(InterlockedBoolean a, InterlockedBoolean b)
+        {
+            return a._value == b._value;
+        }
+
+        public static bool operator !=(InterlockedBoolean a, InterlockedBoolean b)
+        {
+            return a._value != b._value;
+        }
+
+        public static bool operator ==(InterlockedBoolean a, bool b)
+        {
+            return a.IsTrue == b;
+        }
+
+        public static bool operator !=(InterlockedBoolean a, bool b)
+        {
+            return a.IsTrue != b;
+        }
+
+        public static bool operator ==(bool a, InterlockedBoolean b)
+        {
+            return a == b.IsTrue;
+        }
+
+        public static bool operator !=(bool a, InterlockedBoolean b)
+        {
+            return a != b.IsTrue;
+        }
     }
 }


add a new method to support interfaces rather then assemblies

--- src/Core/ExistAll.SimpleConfig/ConfigBuilder.cs
+++ src/Core/ExistAll.SimpleConfig/ConfigBuilder.cs
@@ -38,13 +38,32 @@

 		public IConfigCollection Build(IEnumerable<Assembly> assemblies, ConfigOptions options)
 		{
+			if (assemblies == null) throw new ArgumentNullException(nameof(assemblies));
 			if (options == null) throw new ArgumentNullException(nameof(options));
+			var configInterfaces = _configTypesExtractor.ExtractConfigTypes(assemblies, options);
+			return InnerBuild(configInterfaces, options);
+		}
+
+		public IConfigCollection Build(IEnumerable<Type> interfaces, ConfigOptions options)
+		{
+			if (interfaces == null) throw new ArgumentNullException(nameof(interfaces));
+			if (options == null) throw new ArgumentNullException(nameof(options));
+			return InnerBuild(interfaces, options);
+		}
+
+		public void Add(ISectionBinder sectionBinder)
+		{
+			if (sectionBinder == null) throw new ArgumentNullException(nameof(sectionBinder));
+			_binders.Add(_counter++, sectionBinder);
+		}
+
+		private IConfigCollection InnerBuild(IEnumerable<Type> interfaces, ConfigOptions options)
+		{
 			_configOptionsValidator.ValidateOptions(options);
-			var configInterfaces = _configTypesExtractor.ExtractConfigTypes(assemblies, options);

 			var collection = new ConfigCollection();

-			foreach (var configInterface in configInterfaces)
+			foreach (var configInterface in interfaces)
 			{
 				var generateType = _configClassGenerator.GenerateType(configInterface);

@@ -56,17 +75,6 @@
 			}

 			return collection;
-		}
-
-		public IConfigCollection Build(IEnumerable<Type> interfaces, ConfigOptions options)
-		{
-			throw new NotImplementedException();
-		}
-
-		public void Add(ISectionBinder sectionBinder)
-		{
-			if (sectionBinder == null) throw new ArgumentNullException(nameof(sectionBinder));
-			_binders.Add(_counter++, sectionBinder);
 		}

 		private void ConvertAndSetPropertyValue(string value, PropertyInfo property, object instance, ConfigOptions options, bool hasBinderSetValue)


Incremented version to v1.2.1

Incremented version to v1.2.1

--- src/Dapper.FluentMap/Properties/AssemblyInfo.cs
+++ src/Dapper.FluentMap/Properties/AssemblyInfo.cs
@@ -32,4 +32,4 @@
 // You can specify all the values or you can default the Build and Revision Numbers
 // by using the '*' as shown below:
 // [assembly: AssemblyVersion("1.0.*")]
-[assembly: AssemblyVersion("1.2.0")]
+[assembly: AssemblyVersion("1.2.1")]


Fix https://github.com/ExRam/ExRam.Gremlinq/issues/568.

--- src/ExRam.Gremlinq.Core/Queries/GremlinQuery.cs
+++ src/ExRam.Gremlinq.Core/Queries/GremlinQuery.cs
@@ -44,21 +44,30 @@
         private GremlinQuery<TElement, TOutVertex, TInVertex, TScalar, TMeta, TFoldedQuery> AddOrUpdate(TElement element, bool add)
         {
             var ret = this;
-            var props = element.Serialize(
-                Environment,
-                add
-                    ? SerializationBehaviour.IgnoreOnAdd
-                    : SerializationBehaviour.IgnoreOnUpdate);
+            var props = element
+                .Serialize(
+                    Environment,
+                    add
+                        ? SerializationBehaviour.IgnoreOnAdd
+                        : SerializationBehaviour.IgnoreOnUpdate)
+                .ToArray();

             if (!add)
             {
-                ret = ret.SideEffect(_ => _
-                    .Properties<object, object, object>(
-                        Projection.Empty,
-                        props
-                            .Select(p => p.key.RawKey)
-                            .OfType<string>())
-                    .Drop());
+                var droppableKeys = props
+                    .Select(p => p.key.RawKey)
+                    .OfType<string>()
+                    .ToArray();
+
+                if (droppableKeys.Length > 0)
+                {
+                    ret = ret
+                        .SideEffect(__ => __
+                            .Properties<object, object, object>(
+                                Projection.Empty,
+                                droppableKeys)
+                            .Drop());
+                }
             }

             foreach (var (key, value) in props)


Fixed so case is ignored when querying for container names

--- src/Framework/N2/Edit/ContainerRepositoryOfT.cs
+++ src/Framework/N2/Edit/ContainerRepositoryOfT.cs
@@ -71,6 +71,8 @@
 			if (Navigate)
 			{
 				var q = containerContainer.Children.Query().OfType<T>();
+				if (!string.IsNullOrEmpty(name))
+					q = q.Where(i => string.Equals(i.Name, name, StringComparison.InvariantCultureIgnoreCase));
 				return q.FirstOrDefault();
 			}
 			else
@@ -78,7 +80,7 @@
 				var q = finder.Where.Parent.Eq(containerContainer)
 					.And.Type.Eq(typeof(T));
 				if (!string.IsNullOrEmpty(name))
-					q = q.And.Name.Eq(name);
+					q = q.And.Name.Like(name);
 				var items = q.MaxResults(1).Select<T>();
 				return items.Count > 0 ? items[0] : null;
 			}


Changed: don't show Window when init. For window-less unit test: the window is only used for rendering with OpenGL.

--- src/ImGui/OSImplentation/Windows/Win32Window.cs
+++ src/ImGui/OSImplentation/Windows/Win32Window.cs
@@ -382,9 +382,6 @@
                 throw new WindowCreateException(string.Format("CreateWindowEx error: {0}", Marshal.GetLastWin32Error()));
             }

-            ShowWindow(hwnd, 1/*SW_SHOWNORMAL*/);
-            UpdateWindow(hwnd);
-
             this.hwnd = hwnd;
         }


Improved the DefaultTypeLoader to cache the exported types for an assembly.

--- src/Kephas.Core/Reflection/DefaultTypeLoader.cs
+++ src/Kephas.Core/Reflection/DefaultTypeLoader.cs
@@ -8,15 +8,15 @@
 // </summary>
 // --------------------------------------------------------------------------------------------------------------------

-#nullable enable
-
 namespace Kephas.Reflection
 {
     using System;
+    using System.Collections.Concurrent;
     using System.Collections.Generic;
     using System.Linq;
     using System.Reflection;

+    using Kephas.Diagnostics.Contracts;
     using Kephas.Logging;
     using Kephas.Resources;

@@ -25,6 +25,10 @@
     /// </summary>
     public class DefaultTypeLoader : Loggable, ITypeLoader
     {
+        private static readonly Lazy<ITypeLoader> LazyInstance = new Lazy<ITypeLoader>(() => new DefaultTypeLoader());
+        private readonly ConcurrentDictionary<Assembly, IEnumerable<Type>> assemblyCache =
+            new ConcurrentDictionary<Assembly, IEnumerable<Type>>();
+
         /// <summary>
         /// Initializes a new instance of the <see cref="DefaultTypeLoader"/> class.
         /// </summary>
@@ -35,6 +39,11 @@
         }

         /// <summary>
+        /// Gets the static instance of the <see cref="DefaultTypeLoader"/>.
+        /// </summary>
+        public static ITypeLoader Instance => LazyInstance.Value;
+
+        /// <summary>
         /// Gets the loadable exported types from the provided assembly.
         /// </summary>
         /// <param name="assembly">The assembly containing the types.</param>
@@ -43,29 +52,36 @@
         /// </returns>
         public IEnumerable<Type> GetExportedTypes(Assembly assembly)
         {
-            // for more information check also:
-            // http://stackoverflow.com/questions/7889228/how-to-prevent-reflectiontypeloadexception-when-calling-assembly-gettypes
-            try
-            {
-                return assembly.IsDynamic ? new Type[0] : assembly.ExportedTypes;
-            }
-            catch (ReflectionTypeLoadException e)
-            {
-                this.Logger.Error(e, Strings.DefaultTypeLoader_GetLoadableExportedTypes_ReflectionTypeLoadException, assembly);
-                return e.Types.Where(t => t != null);
-            }
-            catch (TypeLoadException tle)
-            {
-                this.Logger.Error(tle, Strings.DefaultTypeLoader_GetLoadableExportedTypes_TypeLoadException, tle.TypeName, assembly);
+            Requires.NotNull(assembly, nameof(assembly));

-                return this.GetLoadableDefinedTypes(assembly);
-            }
-            catch (Exception e)
-            {
-                this.Logger.Error(e, Strings.DefaultTypeLoader_GetLoadableExportedTypes_ReflectionTypeLoadException, assembly);
+            return this.assemblyCache.GetOrAdd(
+                assembly,
+                _ =>
+                {
+                    // for more information check also:
+                    // http://stackoverflow.com/questions/7889228/how-to-prevent-reflectiontypeloadexception-when-calling-assembly-gettypes
+                    try
+                    {
+                        return assembly.IsDynamic ? new Type[0] : assembly.ExportedTypes;
+                    }
+                    catch (ReflectionTypeLoadException e)
+                    {
+                        this.Logger.Error(e, Strings.DefaultTypeLoader_GetLoadableExportedTypes_ReflectionTypeLoadException, assembly);
+                        return e.Types.Where(t => t != null);
+                    }
+                    catch (TypeLoadException tle)
+                    {
+                        this.Logger.Error(tle, Strings.DefaultTypeLoader_GetLoadableExportedTypes_TypeLoadException, tle.TypeName, assembly);

-                return this.GetLoadableDefinedTypes(assembly);
-            }
+                        return this.GetLoadableDefinedTypes(assembly);
+                    }
+                    catch (Exception e)
+                    {
+                        this.Logger.Error(e, Strings.DefaultTypeLoader_GetLoadableExportedTypes_ReflectionTypeLoadException, assembly);
+
+                        return this.GetLoadableDefinedTypes(assembly);
+                    }
+                });
         }

         /// <summary>


Clear data as soon as possible

Clear data as soon as possible

--- src/Kliva/ViewModels/ActivityDetailViewModel.cs
+++ src/Kliva/ViewModels/ActivityDetailViewModel.cs
@@ -78,6 +78,10 @@

         private async Task LoadActivityDetails(string activityId)
         {
+            Kudos.Clear();
+            Comments.Clear();
+            RelatedAthletes.Clear();
+
             var activity = await _stravaService.GetActivityAsync(activityId, true);
             var athlete = await _stravaService.GetAthleteAsync();

@@ -85,21 +89,18 @@
             {
                 SelectedActivity = activity;

-                Kudos.Clear();
                 if (activity.KudosCount > 0 && activity.Kudos != null && activity.Kudos.Any())
                 {
                     foreach (Athlete kudo in activity.Kudos)
                         Kudos.Add(kudo);
                 }
-
-                Comments.Clear();
+
                 if (activity.CommentCount > 0 && activity.Comments != null && activity.Comments.Any())
                 {
                     foreach(Comment comment in activity.Comments)
                         Comments.Add(comment);
                 }
-
-                RelatedAthletes.Clear();
+
                 if (activity.OtherAthleteCount > 0 && activity.RelatedActivities != null && activity.RelatedActivities.Any())
                 {
                     foreach (ActivitySummary relatedActivity in activity.RelatedActivities)


remove decorator attributes

remove decorator attributes

--- abremir.AllMyBricks.Data/Models/Review.cs
+++ abremir.AllMyBricks.Data/Models/Review.cs
@@ -1,10 +1,8 @@
 using System;
 using System.Collections.Generic;
-using System.Diagnostics;

 namespace abremir.AllMyBricks.Data.Models
 {
-    [DebuggerStepThrough]
     public class Review
     {
         public string Author { get; set; }


Remessa Itaú, não enviar DV nosso número na remessa

--- src/Boleto.Net/Banco/Banco_Itau.cs
+++ src/Boleto.Net/Banco/Banco_Itau.cs
@@ -1152,7 +1152,9 @@
                 _detalhe += "0000";

                 _detalhe += Utils.FitStringLength(boleto.NumeroDocumento, 25, 25, ' ', 0, true, true, false); //Identificao do ttulo na empresa
-                _detalhe += Utils.FitStringLength(boleto.NossoNumero, 8, 8, '0', 0, true, true, true);
+
+                var nossoNumeroSemDV = boleto.NossoNumero.Substring(0, boleto.NossoNumero.Count() - 1);
+                _detalhe += Utils.FitStringLength(nossoNumeroSemDV, 8, 8, '0', 0, true, true, true);
                 // Quantidade de moeda varivel - Preencher com zeros se a moeda for REAL
                 // O manual do Banco ITA no diz como preencher caso a moeda no seja o REAL
                 if (boleto.Moeda == 9)


Fixed a couple more issues caused by running Budford with command line parameters

--- src/Budford/View/FormMainWindow.cs
+++ src/Budford/View/FormMainWindow.cs
@@ -2429,11 +2429,14 @@
             }
             else
             {
-                UnregisterHotKey(Handle, MyactionHotkeyId);
-                EnableControlsForGameExitted();
                 if (launchGame != "")
                 {
-                    Close();
+                    if (Model.Settings.StopHotkey == "None")
+                    {
+                        UnregisterHotKey(Handle, MyactionHotkeyId);
+                        EnableControlsForGameExitted();
+                        Close();
+                    }
                 }
             }
         }


fix regex name (#481)

fix regex name (#481)


Fixed share multiplier for network diff

Fixed share multiplier for network diff

--- src/MiningCore/Blockchain/Bitcoin/BitcoinJob.cs
+++ src/MiningCore/Blockchain/Bitcoin/BitcoinJob.cs
@@ -341,7 +341,7 @@
             result.BlockHash = blockHasher.Digest(headerBytes, nTime).ToHexString();
             result.BlockHeight = BlockTemplate.Height;
             result.BlockReward = rewardToPool.ToDecimal(MoneyUnit.BTC);
-            result.NetworkDifficulty = Difficulty;
+            result.NetworkDifficulty = Difficulty * shareMultiplier;
             result.Difficulty = stratumDifficulty;

             return result;


Fixing a compilation warning in AccountController.

--- src/MusicStore/Controllers/AccountController.cs
+++ src/MusicStore/Controllers/AccountController.cs
@@ -101,7 +101,7 @@
         // GET: /Account/Manage
         //Bug: https://github.com/aspnet/WebFx/issues/339
         [HttpGet]
-        public async Task<IActionResult> Manage(ManageMessageId? message)
+        public IActionResult Manage(ManageMessageId? message)
         {
             ViewBag.StatusMessage =
                 message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."


optimize MinChangeCount

optimize MinChangeCount

--- src/NMoneys/Change/Operations.MinChangeCount.cs
+++ src/NMoneys/Change/Operations.MinChangeCount.cs
@@ -21,19 +21,16 @@

 			// Base case (If given value n is 0)
 			table[0] = 0;
-
-			// Initialize all table values as Infinite
-			for (int i = 1; i <= n; i++)
-			{
-				table[i] = ushort.MaxValue;
-			}
-
+
 			// Compute minimum denominations required for all
 			// values from 1 to n
 			for (long i = 1; i <= n; i++)
 			{
+				// Initialize all table values as Infinite
+				table[i] = ushort.MaxValue;
 				// Go through all denominations smaller than i
 				for (int j = 0; j < m; j++)
+				{
 					if (integralDenominations[j] <= i)
 					{
 						uint subResult = table[i - integralDenominations[j]];
@@ -42,6 +39,7 @@
 							table[i] = (ushort) (subResult + 1);
 						}
 					}
+				}
 			}
 			return table[n] == ushort.MaxValue ? default(ushort) : table[n];
 		}


Fix aggregate element imports

Fix aggregate element imports

Expose aggregate expression imports at the aggregate element level

--- src/NRules/NRules.RuleModel/AggregateElement.cs
+++ src/NRules/NRules.RuleModel/AggregateElement.cs
@@ -1,4 +1,6 @@
 using System;
+using System.Collections.Generic;
+using System.Linq;

 namespace NRules.RuleModel
 {
@@ -55,6 +57,7 @@
             CustomFactoryType = customFactoryType;

             AddImports(source);
+            AddImports(expressions.SelectMany(x => x.Imports.Except(source.Exports)));
         }

         internal override void Accept<TContext>(TContext context, RuleElementVisitor<TContext> visitor)


Remove obsolete performance test

Remove obsolete performance test

--- UnitLibraryTests/GenericUnitTests.cs
+++ UnitLibraryTests/GenericUnitTests.cs
@@ -146,33 +146,5 @@
             //(kilometerTime == new Time(new Meter(), 1000)).Should().BeTrue();
             //kilometerTime.Architectural.Should().Be("3280'10 1/16\""); //need to recheck
         }
-
-
-        [Test()]
-        public void DerivedUnits_PerformanceTest()
-        {
-            Time oneSecond = new Time(new Minute(), 1);
-            Unit result1 = new Unit<DerivedUnitType>(new DerivedUnitType(),1.0);
-
-            for (int i = 0; i < 10000; i++)
-            {
-                result1 *= oneSecond;
-            }
-            (result1.ConversionFactor).Should().Be(Math.Pow(60, 10000));
-
-            Unit frequency = new Unit<DerivedUnitType>(new DerivedUnitType(1.0, null, new Second()), 1);
-            Unit result2 = new Unit<DerivedUnitType>(new DerivedUnitType(), 1.0);
-
-            for (int i = 0; i < 10000; i++)
-            {
-                result2 *= frequency;
-            }
-            (result2.ConversionFactor).Should().Be(1);
-
-            var result3 = result1 * result2;
-
-            (result3.Measurement == Math.Pow(60, 10000)).Should().BeTrue();
-
-        }
     }
 }


updateproperties is now a method

updateproperties is now a method

--- UnitOfWork.NET/Classes/UnitOfWork.cs
+++ UnitOfWork.NET/Classes/UnitOfWork.cs
@@ -41,11 +41,19 @@
             {
                 RegisterAssembly(args.NewItems.Cast<Assembly>().ToArray());

-                foreach (var field in fields.Where(t => t.FieldType.IsAssignableTo<IRepository>())) field.SetValue(this, _container.ResolveOptional(field.FieldType));
-                foreach (var property in properties.Where(t => t.PropertyType.IsAssignableTo<IRepository>())) property.SetValue(this, _container.ResolveOptional(property.PropertyType));
+                UpdateProperties();
             };

             foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) _assemblies.Add(assembly);
+        }
+
+        protected void UpdateProperties()
+        {
+            var fields = GetType().GetFields().ToArray();
+            var properties = GetType().GetProperties().ToArray();
+
+            foreach (var field in fields.Where(t => t.FieldType.IsAssignableTo<IRepository>())) field.SetValue(this, _container.ResolveOptional(field.FieldType));
+            foreach (var property in properties.Where(t => t.PropertyType.IsAssignableTo<IRepository>())) property.SetValue(this, _container.ResolveOptional(property.PropertyType));
         }

         private bool IsRepository(Type t)


Improving parser

Improving parser

--- src/Cr.ArgParse/ActionContainer.cs
+++ src/Cr.ArgParse/ActionContainer.cs
@@ -72,7 +72,7 @@
             actions = new List<ArgumentAction>();

             optionStringActions =
-                new Dictionary<string, ArgumentAction>(StringComparer.InvariantCultureIgnoreCase);
+                new Dictionary<string, ArgumentAction>(StringComparer.InvariantCulture);

             //groups
             ActionGroups = new List<ArgumentGroup>();


Added an event to signal that the app was restored from termination.

--- src/Crystal3/CrystalApplication.cs
+++ src/Crystal3/CrystalApplication.cs
@@ -31,6 +31,8 @@

         public CrystalConfiguration Options { get; private set; }

+        public event EventHandler Restored;
+

         public CrystalApplication() : base()
         {
@@ -130,6 +132,9 @@
                         //navService.HandleTerminationReload();

                         //todo handle multiple windows in this case.
+
+                        if (Restored != null)
+                            Restored(this, EventArgs.Empty);
                     }
                 }
             }


Fixes compiler warning

Fixes compiler warning

--- src/DbfDataReader/DbfDataReader.cs
+++ src/DbfDataReader/DbfDataReader.cs
@@ -41,11 +41,7 @@

         public DbfRecord DbfRecord { get; private set; }

-#if NETSTANDARD2_0
-        public void Close()
-#else
         public override void Close()
-#endif
         {
             try
             {


Don't create a new instance of Data list, if no properties specified on log event

--- src/Elmah.Io.NLog/ElmahIoTarget.cs
+++ src/Elmah.Io.NLog/ElmahIoTarget.cs
@@ -67,7 +67,7 @@
                 Severity = LevelToSeverity(logEvent.Level),
                 DateTime = logEvent.TimeStamp.ToUniversalTime(),
                 Detail = logEvent.Exception?.ToString(),
-                Data = PropertiesToData(logEvent.Properties),
+                Data = PropertiesToData(logEvent),
                 Source = logEvent.LoggerName,
                 Hostname = MachineName(logEvent),
                 Application = Application,
@@ -105,10 +105,12 @@
 #endif
         }

-        private List<Item> PropertiesToData(IDictionary<object, object> properties)
+        private List<Item> PropertiesToData(LogEventInfo logEvent)
         {
+            if (logEvent.Properties == null || logEvent.Properties.Count == 0) return null;
+
             var items = new List<Item>();
-            foreach (var obj in properties)
+            foreach (var obj in logEvent.Properties)
             {
                 if (obj.Value != null)
                 {


Refactored cookie extensions to use IHttpSettingsContainer to reduce code

--- src/Flurl.Http/CookieExtensions.cs
+++ src/Flurl.Http/CookieExtensions.cs
@@ -16,100 +16,53 @@
 		/// <summary>
 		/// Allows cookies to be sent and received. Not necessary to call when setting cookies via WithCookie/WithCookies.
 		/// </summary>
-		/// <param name="client">The IFlurlClient.</param>
+		/// <param name="clientOrRequest">The IFlurlClient or IFlurlRequest.</param>
 		/// <returns>This IFlurlClient.</returns>
-		public static IFlurlClient EnableCookies(this IFlurlClient client) {
-			client.Settings.CookiesEnabled = true;
-			return client;
+		public static T EnableCookies<T>(this T clientOrRequest) where T : IHttpSettingsContainer {
+			clientOrRequest.Settings.CookiesEnabled = true;
+			return clientOrRequest;
 		}

 		/// <summary>
-		/// Sets an HTTP cookie to be sent with all requests made with this IFlurlClient.
+		/// Sets an HTTP cookie to be sent with this IFlurlRequest or all requests made with this IFlurlClient.
 		/// </summary>
-		/// <param name="client">The IFlurlClient.</param>
+		/// <param name="clientOrRequest">The IFlurlClient or IFlurlRequest.</param>
 		/// <param name="cookie">The cookie to set.</param>
 		/// <returns>This IFlurlClient.</returns>
-		public static IFlurlClient WithCookie(this IFlurlClient client, Cookie cookie) {
-			client.Settings.CookiesEnabled = true;
-			client.Cookies[cookie.Name] = cookie;
-			return client;
+		public static T WithCookie<T>(this T clientOrRequest, Cookie cookie) where T : IHttpSettingsContainer {
+			clientOrRequest.Settings.CookiesEnabled = true;
+			clientOrRequest.Cookies[cookie.Name] = cookie;
+			return clientOrRequest;
 		}

 		/// <summary>
-		/// Sets an HTTP cookie to be sent with all requests made with this IFlurlClient.
+		/// Sets an HTTP cookie to be sent with this IFlurlRequest or all requests made with this IFlurlClient.
 		/// </summary>
-		/// <param name="client">The IFlurlClient.</param>
+		/// <param name="clientOrRequest">The IFlurlClient or IFlurlRequest.</param>
 		/// <param name="name">The cookie name.</param>
 		/// <param name="value">The cookie value.</param>
 		/// <param name="expires">The cookie expiration (optional). If excluded, cookie only lives for duration of session.</param>
 		/// <returns>This IFlurlClient.</returns>
-		public static IFlurlClient WithCookie(this IFlurlClient client, string name, object value, DateTime? expires = null) {
+		public static T WithCookie<T>(this T clientOrRequest, string name, object value, DateTime? expires = null) where T : IHttpSettingsContainer {
 			var cookie = new Cookie(name, value?.ToInvariantString()) { Expires = expires ?? DateTime.MinValue };
-			return client.WithCookie(cookie);
+			return clientOrRequest.WithCookie(cookie);
 		}

 		/// <summary>
-		/// Sets HTTP cookies to be sent with all requests made with this IFlurlClient, based on property names/values of the provided object, or keys/values if object is a dictionary.
+		/// Sets HTTP cookies to be sent with this IFlurlRequest or all requests made with this IFlurlClient, based on property names/values of the provided object, or keys/values if object is a dictionary.
 		/// </summary>
-		/// <param name="client">The IFlurlClient.</param>
+		/// <param name="clientOrRequest">The IFlurlClient or IFlurlRequest.</param>
 		/// <param name="cookies">Names/values of HTTP cookies to set. Typically an anonymous object or IDictionary.</param>
 		/// <param name="expires">Expiration for all cookies (optional). If excluded, cookies only live for duration of session.</param>
 		/// <returns>This IFlurlClient.</returns>
-		public static IFlurlClient WithCookies(this IFlurlClient client, object cookies, DateTime? expires = null) {
+		public static T WithCookies<T>(this T clientOrRequest, object cookies, DateTime? expires = null) where T : IHttpSettingsContainer {
 			if (cookies == null)
-				return client;
+				return clientOrRequest;

 			foreach (var kv in cookies.ToKeyValuePairs())
-				client.WithCookie(kv.Key, kv.Value, expires);
+				clientOrRequest.WithCookie(kv.Key, kv.Value, expires);

-			return client;
-		}
-
-		/// <summary>
-		/// Allows cookies to be sent and received with this request's IFlurlClient. Not necessary to call when setting cookies via WithCookie/WithCookies.
-		/// </summary>
-		/// <param name="request">The IFlurlRequest.</param>
-		/// <returns>This IFlurlRequest.</returns>
-		public static IFlurlRequest EnableCookies(this IFlurlRequest request) {
-			request.Settings.CookiesEnabled = true; // a little awkward to have this at both the client and request.
-			request.Client.EnableCookies();
-			return request;
-		}
-
-		/// <summary>
-		/// Sets an HTTP cookie to be sent with this request's IFlurlClient.
-		/// </summary>
-		/// <param name="request">The IFlurlRequest.</param>
-		/// <param name="cookie">The cookie to set.</param>
-		/// <returns>This IFlurlRequest.</returns>
-		public static IFlurlRequest WithCookie(this IFlurlRequest request, Cookie cookie) {
-			request.Client.WithCookie(cookie);
-			return request;
-		}
-
-		/// <summary>
-		/// Sets an HTTP cookie to be sent with this request's IFlurlClient.
-		/// </summary>
-		/// <param name="request">The IFlurlRequest.</param>
-		/// <param name="name">The cookie name.</param>
-		/// <param name="value">The cookie value.</param>
-		/// <param name="expires">The cookie expiration (optional). If excluded, cookie only lives for duration of session.</param>
-		/// <returns>This IFlurlRequest.</returns>
-		public static IFlurlRequest WithCookie(this IFlurlRequest request, string name, object value, DateTime? expires = null) {
-			request.Client.WithCookie(name, value, expires);
-			return request;
-		}
-
-		/// <summary>
-		/// Sets HTTP cookies to be sent with this request's IFlurlClient, based on property names/values of the provided object, or keys/values if object is a dictionary.
-		/// </summary>
-		/// <param name="request">The IFlurlRequest.</param>
-		/// <param name="cookies">Names/values of HTTP cookies to set. Typically an anonymous object or IDictionary.</param>
-		/// <param name="expires">Expiration for all cookies (optional). If excluded, cookies only live for duration of session.</param>
-		/// <returns>This IFlurlRequest.</returns>
-		public static IFlurlRequest WithCookies(this IFlurlRequest request, object cookies, DateTime? expires = null) {
-			request.Client.WithCookies(cookies, expires);
-			return request;
+			return clientOrRequest;
 		}
 	}
 }


Azure.Identity Fixing AzureCliCredential check for no logged in account (#10497)

* Fixing AzureCliCredential check for no logged in account

* switch to IndexOf instead of Contains to specify StringComparison type

--- sdk/identity/Azure.Identity/src/AzureCliCredentialClient.cs
+++ sdk/identity/Azure.Identity/src/AzureCliCredentialClient.cs
@@ -68,7 +68,8 @@

             if (exitCode != 0)
             {
-                bool isLoginError = output.StartsWith("Please run 'az login'", StringComparison.CurrentCultureIgnoreCase);
+                bool isLoginError = output.IndexOf("az login", StringComparison.OrdinalIgnoreCase) != -1 || output.IndexOf("az account set", StringComparison.OrdinalIgnoreCase) != -1;
+
                 bool isWinError = output.StartsWith(WinAzureCLIError, StringComparison.CurrentCultureIgnoreCase);

                 bool isOtherOsError = AzNotFoundPattern.IsMatch(output);


CP-20245: PVS Supplemental pack name change

Signed-off-by: Mihaela Stoica <be95049f8e30d921fc7e2579c00c48bd84c40606@citrix.com>

--- XenModel/Utils/Helpers.cs
+++ XenModel/Utils/Helpers.cs
@@ -2099,7 +2099,7 @@
        public static bool PvsCacheCapability(IXenConnection connection)
        {
            var master = GetMaster(connection);
-           return master != null && master.AppliedUpdates().Any(update => update.Name.ToLower().StartsWith("xspvscache"));
+           return master != null && master.AppliedUpdates().Any(update => update.Name.ToLower().StartsWith("pvsaccelerator"));
        }

        /// <summary>


Added tests to verify working trns / adj

--- YAMP.Core.Tests/Matrix.cs
+++ YAMP.Core.Tests/Matrix.cs
@@ -11,140 +11,179 @@
         {
             Test("|[2,3,1]-[1,3,1]|", 1.0);
         }
+
         [Test]
         public void ScalarArithmeticsInMatrixLiteral()
         {
             Test("|[2^2,2+3,-2,-2]|", 7.0);
         }
+
         [Test]
         public void MatrixMultiplication()
         {
             Test("|[3,2,1]*[1;2;3]|", 10.0);
         }
+
         [Test]
         public void DifferentDimensionSameValue()
         {
             Test("|[1;2;3]|-|[1,2,3]|", 0.0);
         }
+
         [Test]
         public void ScalarTimesMatrix()
         {
             Test("|2*[1,2;1,2]|", 0.0);
         }
+
         [Test]
         public void SubtractMatrices()
         {
             Test("|[2,1;3,5]-[2,1;3,5]'|", 4.0);
         }
+
         [Test]
         public void MultiplyVectors()
         {
             Test("[2,1,0]*[5;2;1]", 12.0);
         }
+
         [Test]
         public void Det()
         {
             Test("det([1;2]*[2,1])", 0.0);
         }
+
         [Test]
         public void RangeWithExplicitDelta()
         {
             Test("|1:1:3|", Math.Sqrt(1 + 4 + 9));
         }
+
         [Test]
         public void CommaIsNewColumn()
         {
             Test("|[1,2,3]|", Math.Sqrt(1 + 4 + 9));
         }
+
         [Test]
         public void SemicolonIsNewLine()
         {
             Test("|[1;2;3]|", Math.Sqrt(1 + 4 + 9));
         }
+
         [Test]
         public void SubtractionOfMatrices()
         {
             Test("([3 2 1] - [1 2 3])(3)", -2.0);
         }
+
         [Test]
         public void AdditionOfMatrices()
         {
             Test("([3 2 1] + [1 2 3])(2)", 4.0);
         }
+
         [Test]
         public void Cholesky()
         {
             Test("det(chol([1, 1i; -1i, pi]))", Math.Sqrt(Math.PI - 1.0), 1e-8);
         }
+
         [Test]
         public void AbsoluteValue()
         {
             Test("|[2 3 4]|", Math.Sqrt(29.0));
         }
+
         [Test]
         public void NewLineIsSignificant()
         {
             Test("[2 3 4\n1 2 3](2, 2)", 2.0);
         }
+
         [Test]
         public void SpaceIsSignificant()
         {
             Test(" [2 2 * 2 - 2^3 4](1, 2) ", -4.0);
         }
+
         [Test]
         public void TwoDimensionalIndex()
         {
             Test("[1,2,3;4,5,6;7,8,9](2,3)", 6.0);
         }
+
         [Test]
         public void AssignToVariableAndAbsolute()
         {
             Test("|(x=[1,2,3;4,5,6;7,8,9])(:,1)|", Math.Sqrt(66.0));
         }
+
         [Test]
         public void AbsoluteOfEigenvalue()
         {
             Test("abs(eigval([1,2;4,5])(1:2))", 6.48074069840786, 1e-8);
         }
+
         [Test]
         public void AbsoluteOfEigenvector()
         {
             Test("abs(eigvec([1,2;4,5])(1:2))", 1.0);
         }
+
         [Test]
         public void SineOfMatrix()
         {
             Test("-sin([1,2,3])(2)", -Math.Sin(2));
         }
+
         [Test]
         public void SumOfPowers()
         {
             Test("sum([0:10, 2^(0:2:20), 2^(1:2:21)](:,1))", 55.0);
         }
+
         [Test]
         public void LengthOfRange()
         {
             Test("length(-pi/4:0.1:pi/4)", 16.0);
         }
+
         [Test]
         public void AssignMultiple()
         {
             Test("[a, b, c] = 12.0;b", 12.0);
         }
+
         [Test]
         public void Sort()
         {
             Test("sort([25, 1, 0, 29, 105, 0, -5])(4)", 1.0);
         }
+
         [Test]
         public void LuAndSum()
         {
             Test("A=[4, 3; 6, 3]; [L, U, p] = lu(A); sum(sum(A - p * L * U))", 0.0, 1e-8);
         }
+
         [Test]
         public void QrAndDet()
         {
             Test("A=[12,-51,4;6,167,-68;-4,24,-41]; [q, r] = qr(A); det(q)", -1.0, 1e-8);
         }
+
+        [Test]
+        public void TransposeMatrix()
+        {
+            Test("A=[1, 2i; 3, 4]; 1i*(A.')(2,1)", -2.0);
+        }
+
+        [Test]
+        public void AdjungateMatrix()
+        {
+            Test("A=[1, 2i; 3, 4]; 1i*(A')(2,1)", 2.0);
+        }
     }
 }


Added Exception.StackTrace

Added Exception.StackTrace

--- src/Libraries/CoreLib/Exception.cs
+++ src/Libraries/CoreLib/Exception.cs
@@ -1,53 +1,61 @@
-// Exception.cs
-// Script#/Libraries/CoreLib
-// This source code is subject to terms and conditions of the Apache License, Version 2.0.
-//
-
-using System.Collections;
-using System.Runtime.CompilerServices;
-
-namespace System {
-
-    /// <summary>
-    /// Equivalent to the Error type in Javascript.
-    /// </summary>
-    [IgnoreNamespace]
-    [Imported]
-    [ScriptName("Error")]
-    public sealed class Exception {
-
-        public Exception(string message) {
-        }
-
-        [IntrinsicProperty]
-        public Exception InnerException {
-            get {
-                return null;
-            }
-        }
-
-        [IntrinsicProperty]
-        public string Message {
-            get {
-                return null;
-            }
-        }
-
-        [IntrinsicProperty]
-        public object this[string key] {
-            get {
-                return null;
-            }
-        }
-
-        [ScriptAlias("Error.createError")]
-        public static Exception Create(string message, Dictionary errorInfo) {
-            return null;
-        }
-
-        [ScriptAlias("Error.createError")]
-        public static Exception Create(string message, Dictionary errorInfo, Exception innerException) {
-            return null;
-        }
-    }
-}
+// Exception.cs
+// Script#/Libraries/CoreLib
+// This source code is subject to terms and conditions of the Apache License, Version 2.0.
+//
+
+using System.Collections;
+using System.Runtime.CompilerServices;
+
+namespace System {
+
+    /// <summary>
+    /// Equivalent to the Error type in Javascript.
+    /// </summary>
+    [IgnoreNamespace]
+    [Imported]
+    [ScriptName("Error")]
+    public sealed class Exception {
+
+        public Exception(string message) {
+        }
+
+        [IntrinsicProperty]
+        public Exception InnerException {
+            get {
+                return null;
+            }
+        }
+
+        [IntrinsicProperty]
+        public string Message {
+            get {
+                return null;
+            }
+        }
+
+        [IntrinsicProperty]
+        [ScriptName("stack")]
+        public string StackTrace {
+            get {
+                return null;
+            }
+        }
+
+        [IntrinsicProperty]
+        public object this[string key] {
+            get {
+                return null;
+            }
+        }
+
+        [ScriptAlias("Error.createError")]
+        public static Exception Create(string message, Dictionary errorInfo) {
+            return null;
+        }
+
+        [ScriptAlias("Error.createError")]
+        public static Exception Create(string message, Dictionary errorInfo, Exception innerException) {
+            return null;
+        }
+    }
+}


Add PathUtil.SearchPAttern

Add PathUtil.SearchPAttern

--- src/Lunet.Core/Helpers/PathUtil.cs
+++ src/Lunet.Core/Helpers/PathUtil.cs
@@ -1,6 +1,7 @@
 using System;
 using System.IO;
 using System.Text;
+using Zio;

 namespace Lunet.Helpers
 {
@@ -8,6 +9,39 @@
     {
         private static readonly char[] TrimCharStart = new[] {'/'};

+        public static SearchPattern SearchPattern(this UPath path)
+        {
+            var rootPath = UPath.Root;
+            string searchPath = null;
+            var items = path.Split();
+            foreach (var item in items)
+            {
+                if (searchPath != null || (item.Contains("*") || item.Contains("?")))
+                {
+                    if (searchPath == null)
+                    {
+                        searchPath = "";
+                    }
+                    else
+                    {
+                        searchPath += "/";
+                    }
+                    searchPath += item;
+                }
+                else
+                {
+                    rootPath = rootPath / item;
+                }
+            }
+
+            if (searchPath == null)
+            {
+                searchPath = rootPath.GetName();
+                rootPath = rootPath.GetDirectory();
+            }
+
+            return Zio.SearchPattern.Parse(ref rootPath, ref searchPath);
+        }

         public static string NormalizeExtension(string extension)
         {


[FastCgi] Revert useless changes

[FastCgi] Revert useless changes

--- src/Mono.WebServer.FastCgi/main.cs
+++ src/Mono.WebServer.FastCgi/main.cs
@@ -65,7 +65,7 @@
 			return func(att);
 		}

-		static void ShowHelp (ConfigurationManager configurationManager)
+		static void ShowHelp (ConfigurationManager configmanager)
 		{
 			string name = Path.GetFileName (
 				Assembly.GetExecutingAssembly ().Location);
@@ -75,7 +75,7 @@
 			Console.WriteLine ("Usage is:\n");
 			Console.WriteLine ("    {0} [...]", name);
 			Console.WriteLine ();
-			configurationManager.PrintHelp ();
+			configmanager.PrintHelp ();
 		}

 		static ApplicationServer appserver;
@@ -90,12 +90,12 @@

 		public static int Main (string [] args)
 		{
-			var configurationManager = new ConfigurationManager ();
-			configurationManager.LoadCommandLineArgs (args);
+			var configmanager = new ConfigurationManager ();
+			configmanager.LoadCommandLineArgs (args);

 			// Show the help and exit.
-			if (configurationManager.Help) {
-				ShowHelp (configurationManager);
+			if (configmanager.Help) {
+				ShowHelp (configmanager);
 #if DEBUG
 				Console.WriteLine("Press any key...");
 				Console.ReadKey ();
@@ -104,7 +104,7 @@
 			}

 			// Show the version and exit.
-			if (configurationManager.Version) {
+			if (configmanager.Version) {
 				ShowVersion ();
 				return 0;
 			}
@@ -112,7 +112,7 @@
 			// Enable console logging during Main ().
 			Logger.WriteToConsole = true;

-			if (!LoadConfigFile(configurationManager))
+			if (!LoadConfigFile(configmanager))
 				return 1;

 #if DEBUG
@@ -120,32 +120,32 @@
 			Logger.Level = LogLevel.All;
 #endif

-			SetLogLevel(configurationManager);
-
-			OpenLogFile (configurationManager);
+			SetLogLevel(configmanager);
+
+			OpenLogFile (configmanager);

 			Logger.Write (LogLevel.Debug,
 				Assembly.GetExecutingAssembly ().GetName ().Name);

 			Socket socket;
-			if (!CreateSocket (out socket, configurationManager))
+			if (!CreateSocket (configmanager, out socket))
 				return 1;

 			string root_dir;
-			if (!GetRootDirectory (out root_dir, configurationManager))
+			if (!GetRootDirectory (configmanager, out root_dir))
 				return 1;

-			CreateAppServer (root_dir, configurationManager);
-
-			if (!LoadApplicationsConfig (configurationManager))
+			CreateAppServer (configmanager, root_dir);
+
+			if (!LoadApplicationsConfig (configmanager))
 				return 1;

-			Mono.FastCgi.Server server = CreateServer (socket, configurationManager);
-
-			Logger.WriteToConsole = configurationManager.PrintLog;
-
-			var stoppable = configurationManager.Stoppable;
+			Mono.FastCgi.Server server = CreateServer (configmanager, socket);
+
+			Logger.WriteToConsole = configmanager.PrintLog;
+
+			var stoppable = configmanager.Stoppable;
 			server.Start (stoppable);

 			if (stoppable) {
@@ -158,15 +158,16 @@
 			return 0;
 		}

-		static Mono.FastCgi.Server CreateServer (Socket socket, ConfigurationManager configurationManager)
+		static Mono.FastCgi.Server CreateServer (ConfigurationManager configmanager,
+		                                         Socket socket)
 		{
 			var server = new Mono.FastCgi.Server (socket);

 			server.SetResponder (typeof (Responder));

-			server.MaxConnections = configurationManager.MaxConns;
-			server.MaxRequests = configurationManager.MaxReqs;
-			server.MultiplexConnections = configurationManager.Multiplex;
+			server.MaxConnections = configmanager.MaxConns;
+			server.MaxRequests = configmanager.MaxReqs;
+			server.MultiplexConnections = configmanager.Multiplex;

 			Logger.Write (LogLevel.Debug, "Max connections: {0}",
 				server.MaxConnections);
@@ -178,19 +179,20 @@
 			return server;
 		}

-		static void CreateAppServer (string rootDir, ConfigurationManager configurationManager)
+		static void CreateAppServer (ConfigurationManager configmanager,
+		                             string rootDir)
 		{
 			var webSource = new WebSource ();
 			appserver = new ApplicationServer (webSource, rootDir) {
-				Verbose = configurationManager.Verbose
+				Verbose = configmanager.Verbose
 			};
 		}

-		static bool LoadApplicationsConfig (ConfigurationManager configurationManager)
+		static bool LoadApplicationsConfig (ConfigurationManager configmanager)
 		{
 			bool autoMap = false; //(bool) configmanager ["automappaths"];

-			var applications = configurationManager.Applications;
+			var applications = configmanager.Applications;
 			if (applications != null)
 				appserver.AddApplicationsFromCommandLine (applications);

@@ -198,8 +200,8 @@
 			string app_config_dir;

 			try {
-				app_config_file = configurationManager.AppConfigFile;
-				app_config_dir = configurationManager.AppConfigDir;
+				app_config_file = configmanager.AppConfigFile;
+				app_config_dir = configmanager.AppConfigDir;
 			} catch (ApplicationException e) {
 				Logger.Write (LogLevel.Error, e.Message);
 				return false;
@@ -225,20 +227,21 @@
 			return true;
 		}

-		delegate bool SocketCreator (string[] socket_parts, out Socket socket, ConfigurationManager configurationManager);
-
-		static bool CreateSocket (out Socket socket, ConfigurationManager configurationManager)
+		delegate bool SocketCreator (ConfigurationManager configmanager, string[] socket_parts, out Socket socket);
+
+		static bool CreateSocket (ConfigurationManager configmanager,
+		                          out Socket socket)
 		{
 			socket = null;

 			// Socket strings are in the format
 			// "type[:ARG1[:ARG2[:...]]]".
-			var socket_type = configurationManager.Socket;
+			var socket_type = configmanager.Socket;

 			string[] socket_parts = socket_type.Split (new[] {':'}, 3);

 			SocketCreator creator = GetSocketCreator (socket_parts);
-			return creator != null && creator (socket_parts, out socket, configurationManager);
+			return creator != null && creator (configmanager, socket_parts, out socket);
 		}

 		static SocketCreator GetSocketCreator (string[] socket_parts)
@@ -263,9 +266,10 @@
 			}
 		}

-		static bool GetRootDirectory (out string rootDir, ConfigurationManager configurationManager)
-		{
-			rootDir = configurationManager.Root;
+		static bool GetRootDirectory (ConfigurationManager configmanager,
+		                              out string rootDir)
+		{
+			rootDir = configmanager.Root;
 			if (!String.IsNullOrEmpty (rootDir)) {
 				try {
 					Environment.CurrentDirectory = rootDir;
@@ -280,7 +284,7 @@
 			return true;
 		}

-		static bool CreateTcpSocket (string [] socketParts, out Socket socket, ConfigurationManager configurationManager)
+		static bool CreateTcpSocket (ConfigurationManager configmanager, string[] socketParts, out Socket socket)
 		{
 			socket = null;
 			ushort port;
@@ -291,7 +295,7 @@
 						return false;
 					}
 				} else {
-					port = configurationManager.Port;
+					port = configmanager.Port;
 				}
 			} catch (ApplicationException e) {
 				Logger.Write (LogLevel.Error, e.Message);
@@ -300,7 +304,7 @@

 			string address_str = socketParts.Length == 3
 				? socketParts[1]
-				: configurationManager.Address;
+				: configmanager.Address;
 			IPAddress address;

 			if (address_str == null)
@@ -329,11 +333,11 @@
 			return true;
 		}

-		static bool CreateUnixSocket (string [] socketParts, out Socket socket, ConfigurationManager configurationManager)
+		static bool CreateUnixSocket (ConfigurationManager configmanager, string[] socketParts, out Socket socket)
 		{
 			string path = socketParts.Length == 2
 				? socketParts[1]
-				: configurationManager.Filename;
+				: configmanager.Filename;

 			socket = null;

@@ -351,7 +355,7 @@
 			return true;
 		}

-		static bool CreatePipe (string[] socketParts, out Socket socket, ConfigurationManager configurationManager)
+		static bool CreatePipe (ConfigurationManager configmanager, string[] socketParts, out Socket socket)
 		{
 			socket = null;
 			try {
@@ -373,10 +377,10 @@
 			return true;
 		}

-		static void OpenLogFile (ConfigurationManager configurationManager)
-		{
-			try {
-				var log_file = configurationManager.LogFile;
+		static void OpenLogFile (ConfigurationManager configmanager)
+		{
+			try {
+				var log_file = configmanager.LogFile;

 				if (log_file != null)
 					Logger.Open (log_file);
@@ -389,9 +393,9 @@
 			}
 		}

-		static void SetLogLevel (ConfigurationManager configurationManager)
-		{
-			Logger.Level = configurationManager.LogLevels;
+		static void SetLogLevel (ConfigurationManager configmanager)
+		{
+			Logger.Level = configmanager.LogLevels;
 		}

 		/// <summary>
@@ -400,12 +404,12 @@
 		/// </summary>
 		/// <returns>false on failure, true on success or
 		/// option not present</returns>
-		static bool LoadConfigFile(ConfigurationManager configurationManager)
-		{
-			try {
-				var config_file = configurationManager.ConfigFile;
+		static bool LoadConfigFile(ConfigurationManager configmanager)
+		{
+			try {
+				var config_file = configmanager.ConfigFile;
 				if (config_file != null)
-					configurationManager.LoadXmlConfig(config_file);
+					configmanager.LoadXmlConfig(config_file);
 			}
 			catch (ApplicationException e) {
 				Logger.Write(LogLevel.Error, e.Message);


Fixed: Screen.ScaleFactor always returns 1, even on a Retina display

--- Xwt.Mac/Xwt.Mac/MacDesktopBackend.cs
+++ Xwt.Mac/Xwt.Mac/MacDesktopBackend.cs
@@ -107,6 +107,11 @@
 			return ((NSScreen)backend).DeviceDescription ["NSScreenNumber"].ToString ();
 		}

+		public override double GetScaleFactor (object backend)
+		{
+			return ((NSScreen)backend).BackingScaleFactor;
+		}
+
 		#endregion
 	}
 }


Fixes #279 and #276

Fixes #279 and #276

--- src/Myra/Graphics2D/UI/MenuItem.cs
+++ src/Myra/Graphics2D/UI/MenuItem.cs
@@ -69,6 +69,8 @@
 						UnderscoreChar = char.ToLower(value[underscoreIndex + 1]);
 					}
 				}
+
+				FireChanged();
 			}
 		}

@@ -172,26 +174,6 @@
 				}

 				_shortcutColor = value;
-				FireChanged();
-			}
-		}
-
-		[DefaultValue(false)]
-		public bool Toggleable
-		{
-			get
-			{
-				return _toggleable;
-			}
-
-			set
-			{
-				if (value == _toggleable)
-				{
-					return;
-				}
-
-				_toggleable = value;
 				FireChanged();
 			}
 		}


Handle a==b==0 case when it always generates NaN

--- src/Numerics/Distributions/Beta.cs
+++ src/Numerics/Distributions/Beta.cs
@@ -393,11 +393,20 @@
         internal static double SampleUnchecked(System.Random rnd, double a, double b)
         {
             double x, y;
-            do
+            if (a == b)
             {
                 x = Gamma.SampleUnchecked(rnd, a, 1.0);
                 y = Gamma.SampleUnchecked(rnd, b, 1.0);
-            } while (x == 0 && y == 0);
+                //When a==b (and possibly a==b==0), return value is equally possible to be 0 or 1
+                if (x == 0 && y == 0)
+                    return Bernoulli.Sample(0.5);//In particular, when a==b==0, Beta distribution degradates to Bernoulli distribution.
+            }
+            else
+                do
+                {
+                    x = Gamma.SampleUnchecked(rnd, a, 1.0);
+                    y = Gamma.SampleUnchecked(rnd, b, 1.0);
+                } while (x == 0 && y == 0);//When a!=b, return value is not equally possible to be 0 or 1. Regenerate.
             return x / (x + y);
         }


[Debugger] Fix game output missing from debug pane

When a game is run with debugger attached, we mirror the game's output
on Visual Studio's Debug output pane. However, we were often missing
the last few lines, which are often the more important ones.

The reason is interesting. We were switching to the main thread on
every output line. When a game exits, we shut down all processes and
actually wait for a second for the tail job to finish. However, this
is done synchronously, so it preempts line printing tasks, so that
further event handlers for output lines are never called.

This CL queues up log lines and flushes them every 500ms. This is
better for performance, anyway.

GitOrigin-RevId: c298266ae7bd1f2dce2272acc2f197020ce09155

--- YetiVSI.Shared/YetiDebugTransport.cs
+++ YetiVSI.Shared/YetiDebugTransport.cs
@@ -11,6 +11,7 @@
 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 // See the License for the specific language governing permissions and
 // limitations under the License.
+
 using DebuggerGrpcClient;
 using Microsoft.VisualStudio;
 using Microsoft.VisualStudio.Shell.Interop;
@@ -26,8 +27,12 @@
 using Microsoft.VisualStudio.Threading;
 using YetiVSI.Util;
 using System.Text;
+using System.Threading.Tasks;
+using System.Timers;
+using System.Windows.Threading;
 using YetiVSI.DebugEngine.Exit;
 using YetiVSI.DebugEngine.Interfaces;
+
 namespace YetiVSI
 {
     public class YetiDebugTransportException : Exception, IUserVisibleError
@@ -36,6 +41,7 @@
         {
         }
     }
+
     // Used by the debug engine in order to initialize Yeti-specific components.
     public class YetiDebugTransport
     {
@@ -43,9 +49,11 @@
         {
             public GrpcConnection GrpcConnection { get; internal set; }
             public ITransportSession TransportSession { get; internal set; }
+
             public int GetLocalDebuggerPort() =>
                 TransportSession?.GetLocalDebuggerPort() ?? 0;
         }
+
         // An event indicating that the transprot has stopped.
         public event Action<Exception> OnStop;
         readonly object _thisLock = new object();
@@ -55,11 +63,14 @@
         readonly Action _onAsyncRpcCompleted;
         readonly ManagedProcess.Factory _managedProcessFactory;
         readonly IVsOutputWindowPane _debugPane;
+        readonly List<string> _queuedDebugOutput;
         readonly IDialogUtil _dialogUtil;
         readonly IYetiVSIService _yetiVSIService;
         PipeCallInvoker _grpcCallInvoker;
         ProcessManager _processManager;
         GrpcSession _grpcSession;
+        Timer _debugOutputUpdateTimer;
+
         public YetiDebugTransport(JoinableTaskContext taskContext,
                                   PipeCallInvokerFactory grpcCallInvokerFactory,
                                   GrpcConnectionFactory grpcConnectionFactory,
@@ -77,8 +88,10 @@
             _dialogUtil = dialogUtil;
             Guid debugPaneGuid = VSConstants.GUID_OutWindowDebugPane;
             vsOutputWindow?.GetPane(ref debugPaneGuid, out _debugPane);
+            _queuedDebugOutput = new List<string>();
             _yetiVSIService = yetiVSIService;
         }
+
         public GrpcSession StartGrpcServer()
         {
             lock (_thisLock)
@@ -90,6 +103,7 @@
                     Trace.WriteLine("Unable to start the debug transport, invalid session.");
                     throw new YetiDebugTransportException(ErrorStrings.FailedToStartTransport);
                 }
+
                 _grpcSession = new GrpcSession
                 {
                     TransportSession = session
@@ -101,6 +115,7 @@
                     Stop(ExitReason.Unknown);
                     throw new YetiDebugTransportException("Failed to launch grpc server process");
                 }
+
                 Trace.WriteLine("Started debug transport.  Session ID: " +
                                 _grpcSession.TransportSession.GetSessionId());
                 // The transport class owns the Grpc session. However, it makes sense to return
@@ -109,6 +124,7 @@
                 return _grpcSession;
             }
         }
+
         public void StartPreGame(LaunchOption launchOption, SshTarget target, GrpcSession session)
         {
             lock (_thisLock)
@@ -121,6 +137,7 @@
                 }
             }
         }
+
         public void StartPostGame(LaunchOption launchOption, SshTarget target, uint remotePid)
         {
             lock (_thisLock)
@@ -131,14 +148,18 @@
                     throw new YetiDebugTransportException(
                         "Failed to start post-game processes. Transport session not started yet.");
                 }
+
                 if (!LaunchPostGameProcesses(launchOption, target, remotePid))
                 {
                     Stop(ExitReason.Unknown);
                     throw new YetiDebugTransportException(
                         "Failed to launch all needed post-game processes");
                 }
-            }
-        }
+
+                StartFlushDebugOutput();
+            }
+        }
+
         // Exits and disposes of all processes, the TransportSession, and GrpcConnection.
         public void Stop(ExitReason exitReason)
         {
@@ -153,8 +174,10 @@
                 _grpcSession = null;
                 _processManager?.StopAll(exitReason);
                 _processManager = null;
-            }
-        }
+                StopFlushDebugOutput();
+            }
+        }
+
         void StopWithException(Exception ex)
         {
             // Synchronously pass the execution exception to the on stop handlers before calling
@@ -163,6 +186,7 @@
             OnStop?.Invoke(ex);
             Stop(ExitReason.Unknown);
         }
+
         // Launches a process, configured using Yeti project properties.
         // If |monitorExit| is true, when the process exits the debugger will be stopped.
         // Throws a ProcessException if the process fails to launch.
@@ -179,24 +203,81 @@
                 {
                     if (data != null)
                     {
-                        _taskContext.Factory.Run(async () =>
+                        // Queue the data up and print it in the main thread. If we switch to main
+                        // thread here, it interfers with process shutdown, which causes us to miss
+                        // the last few output lines. Switching to the main thread for each line is
+                        // not good for performance, anyway. See (internal).
+                        lock (_queuedDebugOutput)
                         {
-                            await _taskContext.Factory.SwitchToMainThreadAsync();
-#pragma warning disable RS0030 // symbol LoadedProject is banned
-                            _debugPane?.OutputString(data.Text + "\n");
-#pragma warning restore RS0030
-                        });
+                            _queuedDebugOutput.Add(data.Text + "\n");
+                        }
                     }
                 };
             }
+
             if (startData.MonitorExit)
             {
                 process.OnExit += _processManager.OnExit;
             }
+
             process.Start();
             startData.AfterStart?.Invoke();
             _processManager.AddProcess(process, startData.StopHandler);
         }
+
+        void StartFlushDebugOutput()
+        {
+            if (_debugOutputUpdateTimer == null)
+            {
+                _debugOutputUpdateTimer = new Timer();
+                _debugOutputUpdateTimer.Elapsed += (sender, args) => FlushDebugOutput();
+                _debugOutputUpdateTimer.Interval = 0.5;
+                _debugOutputUpdateTimer.Start();
+            }
+        }
+
+        void StopFlushDebugOutput()
+        {
+            if (_debugOutputUpdateTimer != null)
+            {
+                _debugOutputUpdateTimer.Stop();
+                _debugOutputUpdateTimer.Dispose();
+                _debugOutputUpdateTimer = null;
+            }
+
+            // Flush anything still in the queue.
+            FlushDebugOutput();
+        }
+
+        void FlushDebugOutput()
+        {
+            // Early out if there's nothing to do.
+            lock (_queuedDebugOutput)
+            {
+                if (_queuedDebugOutput.Count == 0)
+                {
+                    return;
+                }
+            }
+
+            _taskContext.Factory.Run(async () =>
+            {
+                await _taskContext.Factory.SwitchToMainThreadAsync();
+
+                lock (_queuedDebugOutput)
+                {
+                    foreach (string txt in _queuedDebugOutput)
+                    {
+#pragma warning disable RS0030 // symbol LoadedProject is banned
+                        _debugPane?.OutputString(txt);
+#pragma warning restore RS0030
+                    }
+
+                    _queuedDebugOutput.Clear();
+                }
+            });
+        }
+
         /// <summary>
         /// Launches all needed processes that can be launched before the game.
         /// </summary>
@@ -218,6 +299,7 @@

             return LaunchProcesses(processes, "pre-game");
         }
+
         /// <summary>
         /// Launches all needed processes that can be launched after the game.
         /// </summary>
@@ -236,8 +318,10 @@
             {
                 processes.Add(CreateTailLogsProcessStartData(target, remotePid));
             }
+
             return LaunchProcesses(processes, "post-game");
         }
+
         bool LaunchProcesses(List<ProcessStartData> processes, string name)
         {
             if (_processManager == null)
@@ -248,6 +332,7 @@
                                           $"{processName} exited with exit code {exitCode}",
                                           exitCode));
             }
+
             foreach (var item in processes)
             {
                 try
@@ -261,9 +346,11 @@
                     return false;
                 }
             }
+
             Trace.WriteLine($"Manager successfully started all {name} processes");
             return true;
         }
+
         ProcessStartData CreatePortForwardingProcessStartData(SshTarget target, GrpcSession session)
         {
             var ports = new List<ProcessStartInfoBuilder.PortForwardEntry>()
@@ -284,6 +371,7 @@
             var startInfo = ProcessStartInfoBuilder.BuildForSshPortForward(ports, target);
             return new ProcessStartData("lldb port forwarding", startInfo);
         }
+
         ProcessStartData CreateLldbServerProcessStartData(SshTarget target, GrpcSession session)
         {
             string lldbServerCommand = string.Format(
@@ -316,6 +404,7 @@
             var startInfo = ProcessStartInfoBuilder.BuildForSsh(lldbServerCommand, target);
             return new ProcessStartData("lldb server", startInfo);
         }
+
         ProcessStartData CreateTailLogsProcessStartData(SshTarget target, uint remotePid)
         {
             // If the game process exits, give the tail process a chance to shut down gracefully.
@@ -327,6 +416,7 @@
                     Trace.WriteLine("Game process did not exit, won't wait for tail process exit");
                     return;
                 }
+
                 // Give it a second to finish.
                 bool exited = process.WaitForExit(TimeSpan.FromSeconds(1));
                 // Emit a log message to help tracking down issues, just in case.
@@ -337,16 +427,19 @@
             return new ProcessStartData("output tail", startInfo, monitorExit: false,
                                         outputToConsole: true, stopHandler: stopHandler);
         }
+
         ProcessStartData CreateDebuggerGrpcServerProcessStartData()
         {
             var startInfo = new ProcessStartInfo
             {
                 FileName = File.Exists(Path.Combine(YetiConstants.DebuggerGrpcServerDir,
-                                                    YetiConstants.DebuggerGrpcServerExecutable)) ?
-                    Path.Combine(YetiConstants.DebuggerGrpcServerDir,
-                                 YetiConstants.DebuggerGrpcServerExecutable) :
-                    Path.Combine(YetiConstants.RootDir, YetiConstants.DebuggerGrpcServerExecutable),
+                                                    YetiConstants.DebuggerGrpcServerExecutable))
+                    ? Path.Combine(YetiConstants.DebuggerGrpcServerDir,
+                                   YetiConstants.DebuggerGrpcServerExecutable)
+                    : Path.Combine(YetiConstants.RootDir,
+                                   YetiConstants.DebuggerGrpcServerExecutable),
             };
+
             // (internal): grpcCallInvoker must be created right before the process is created!
             // If it is created before the other processes are created, they'll hold on to the
             // pipes and they won't get closed if the GRPC server shuts down.
@@ -362,6 +455,7 @@
                 processStartInfo.Arguments = $"-i {string.Join(",", outPipeHandles)} " +
                     $"-o {string.Join(",", inPipeHandles)}";
             }
+
             // Dispose client handles right after start. This is necessary so that pipes are closed
             // when the server exits.
             Action afterStart = () => { _grpcCallInvoker.DisposeLocalCopyOfClientPipeHandles(); };
@@ -428,6 +522,7 @@
             return new ProcessStartData("lldb grpc server", startInfo, beforeStart: beforeStart,
                                         afterStart: afterStart);
         }
+
         class ProcessStartData
         {
             public ProcessStartData(string name, ProcessStartInfo startInfo,
@@ -451,24 +546,29 @@
                     {
                         StartInfo.StandardOutputEncoding = Encoding.UTF8;
                     }
+
                     if (StartInfo.StandardErrorEncoding == null)
                     {
                         StartInfo.StandardErrorEncoding = Encoding.UTF8;
                     }
                 }
             }
+
             public string Name { get; }
             public ProcessStartInfo StartInfo { get; }
             public bool MonitorExit { get; }
             public bool OutputToConsole { get; }
+
             /// <summary>
             /// Action called right before the process is started. May modify start info.
             /// </summary>
             public Action<ProcessStartInfo> BeforeStart { get; }
+
             /// <summary>
             /// Action called right after the process is started.
             /// </summary>
             public Action AfterStart { get; }
+
             /// <summary>
             /// Handler called when the process manager stops all processes. Gives the
             /// process a chance for custom stop handling based on the exit reason.
@@ -477,4 +577,4 @@
             public ProcessManager.ProcessStopHandler StopHandler { get; }
         }
     }
-}
+}


Fixed unknown ratings being displayed as not available on the application list

--- source/BulkCrapUninstaller/Functions/Ratings/RatingEntry.cs
+++ source/BulkCrapUninstaller/Functions/Ratings/RatingEntry.cs
@@ -33,7 +33,7 @@

         public bool Equals(RatingEntry other)
         {
-            return AverageRating == other.AverageRating && MyRating == other.MyRating;
+            return AverageRating == other.AverageRating && MyRating == other.MyRating && ApplicationName == other.ApplicationName;
         }

         public override bool Equals(object obj)


Fix an UI freeze on Windows 10.

Fix an UI freeze on Windows 10.

--- source/FFImageLoading.Windows/Extensions/ImageExtensions.cs
+++ source/FFImageLoading.Windows/Extensions/ImageExtensions.cs
@@ -64,10 +64,10 @@

                 WriteableBitmap bitmap = null;

-                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Low, () =>
+                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Low, async () =>
                 {
                     bitmap = new WriteableBitmap((int)decoder.PixelWidth, (int)decoder.PixelHeight);
-                    bitmap.SetSource(image);
+                    await bitmap.SetSourceAsync(image);
                 });

                 return bitmap;


Optimise BufferFile parser

Optimise BufferFile parser

--- src/PeNet/FileParser/BufferFile.cs
+++ src/PeNet/FileParser/BufferFile.cs
@@ -1,127 +1,77 @@
 using System;
-using System.Collections.Generic;
-using System.Linq;
+using System.Runtime.InteropServices;
 using System.Text;

 namespace PeNet.FileParser
 {
     public class BufferFile : IRawFile
     {
-        private byte[] _buff;
+        private Memory<byte> _buffer;

-        public long Length => _buff.Length;
+        public long Length => _buffer.Length;

-        public BufferFile(byte[] file)
-            => (_buff) = (file);
+        public BufferFile(byte[] file) => _buffer = file;

         public string ReadAsciiString(long offset)
         {
-            static int GetCStringLength(IReadOnlyList<byte> buff, int stringOffset)
-            {
-                var currentOffset = stringOffset;
-                var currentLength = 0;
-                while (buff[currentOffset] != 0x00)
-                {
-                    currentLength++;
-                    currentOffset++;
-                }
-                return currentLength;
-            }
+            var nullTerminator = byte.MinValue;

-            var length = GetCStringLength(_buff, (int) offset);
-            var tmp = _buff.AsSpan((int)offset, length);
-            return Encoding.ASCII.GetString(tmp);
+            var stringLength = _buffer.Span.Slice((int) offset).IndexOf(nullTerminator);
+
+            return Encoding.ASCII.GetString(_buffer.Span.Slice((int) offset, stringLength));
         }

-        public Span<byte> AsSpan(long offset, long length)
-            => _buff.AsSpan((int) offset, (int) length);
+        public Span<byte> AsSpan(long offset, long length) => _buffer.Span.Slice((int) offset, (int) length);

         public string ReadUnicodeString(long offset)
         {
-            var size = 1;
-            for (var i = offset; i < _buff.Length - 1; i++)
-            {
-                if (_buff[i] == 0 && _buff[i + 1] == 0)
-                {
-                    break;
-                }
-                size++;
-            }
+            Span<byte> nullTerminator = stackalloc byte[] {byte.MinValue, byte.MinValue};

-            var bytes = _buff.AsSpan((int) offset, size);
-            return Encoding.Unicode.GetString(bytes);
+            var stringLength = _buffer.Span.Slice((int) offset).IndexOf(nullTerminator) + 1;
+
+            return Encoding.Unicode.GetString(_buffer.Span.Slice((int) offset, stringLength));
         }

-        public string ReadUnicodeString(long offset, long length)
-        {
-            var bytes = _buff.AsSpan((int) offset, (int) length * 2);
-            return Encoding.Unicode.GetString(bytes);
-        }
-
-        public byte ReadByte(long offset) => _buff[offset];
+        public string ReadUnicodeString(long offset, long length) => Encoding.Unicode.GetString(_buffer.Span.Slice((int) offset, (int) length * 2));

-        public uint ReadUInt(long offset)
-            => BitConverter.ToUInt32(_buff, (int) offset);
+        public byte ReadByte(long offset) => _buffer.Span[(int) offset];

-        public ulong ReadULong(long offset)
-            => BitConverter.ToUInt64(_buff, (int) offset);
+        public uint ReadUInt(long offset) => MemoryMarshal.Read<uint>(_buffer.Span.Slice((int) offset));

-        public ushort ReadUShort(long offset)
-            => BitConverter.ToUInt16(_buff, (int) offset);
+        public ulong ReadULong(long offset) => MemoryMarshal.Read<ulong>(_buffer.Span.Slice((int) offset));

-        public void WriteByte(long offset, byte value)
-        {
-            _buff[offset] = value;
-        }
+        public ushort ReadUShort(long offset) => MemoryMarshal.Read<ushort>(_buffer.Span.Slice((int) offset));

-        public void WriteBytes(long offset, Span<byte> bytes)
-        {
-            Array.Copy(bytes.ToArray(), 0, _buff, offset, bytes.Length);
-        }
+        public void WriteByte(long offset, byte value) => _buffer.Span[(int) offset] = value;

-        public void WriteUInt(long offset, uint value)
-        {
-            var x = BitConverter.GetBytes(value);
-            _buff[offset] = x[0];
-            _buff[offset + 1] = x[1];
-            _buff[offset + 2] = x[2];
-            _buff[offset + 3] = x[3];
-        }
+        public void WriteBytes(long offset, Span<byte> bytes) => bytes.CopyTo(_buffer.Span.Slice((int) offset));

-        public void WriteULong(long offset, ulong value)
-        {
-            var x = BitConverter.GetBytes(value);
-            _buff[offset] = x[0];
-            _buff[offset + 1] = x[1];
-            _buff[offset + 2] = x[2];
-            _buff[offset + 3] = x[3];
-            _buff[offset + 4] = x[4];
-            _buff[offset + 5] = x[5];
-            _buff[offset + 6] = x[6];
-            _buff[offset + 7] = x[7];
-        }
+        public void WriteUInt(long offset, uint value) => MemoryMarshal.Write(_buffer.Span.Slice((int) offset), ref value);

-        public void WriteUShort(long offset, ushort value)
-        {
-            var x = BitConverter.GetBytes(value);
-            _buff[offset] = x[0];
-            _buff[offset + 1] = x[1];
-        }
+        public void WriteULong(long offset, ulong value) => MemoryMarshal.Write(_buffer.Span.Slice((int) offset), ref value);

-        public byte[] ToArray() => _buff;
+        public void WriteUShort(long offset, ushort value) => MemoryMarshal.Write(_buffer.Span.Slice((int) offset), ref value);
+
+        public byte[] ToArray() => _buffer.ToArray();

         public void RemoveRange(long offset, long length)
         {
-            var x = _buff.ToList();
-            x.RemoveRange((int) offset, (int) length);
-            _buff = x.ToArray();
+            var newBuffer = new Memory<byte>(new byte[_buffer.Length - length]);
+
+            _buffer.Slice(0, (int) offset).CopyTo(newBuffer);
+            _buffer.Slice((int) (offset + length)).CopyTo(newBuffer.Slice((int) offset));
+
+            _buffer = newBuffer;
         }

         public int AppendBytes(Span<byte> bytes)
         {
-            var oldLength = _buff.Length;
-            Array.Resize(ref _buff, _buff.Length + bytes.Length);
-            Array.Copy(bytes.ToArray(), 0, _buff, oldLength, bytes.Length);
+            var oldLength = _buffer.Length;
+
+            var newBuffer = new Memory<byte>(new byte[_buffer.Length + bytes.Length]);
+            _buffer.CopyTo(newBuffer);
+            bytes.CopyTo(newBuffer.Span.Slice(oldLength));
+            _buffer = newBuffer;

             return oldLength;
         }


插件编译时默认引用NSubstitute

插件编译时默认引用NSubstitute

--- ZKWeb/Plugin/PluginInfoExtensions.cs
+++ ZKWeb/Plugin/PluginInfoExtensions.cs
@@ -13,10 +13,10 @@
 	/// </summary>
 	public static class PluginInfoExtensions {
 		/// <summary>
-		/// 编译插件时的默认引用程序集
+		/// 编译插件时默认引用的程序集
 		/// </summary>
 		public static List<string> DefaultReferences { get; } =
-			new List<string>() { "NHibernate", "FluentNHibernate", "DotLiquid" };
+			new List<string>() { "NHibernate", "FluentNHibernate", "DotLiquid", "NSubstitute" };

 		/// <summary>
 		/// 编译插件


add the dumbest read/write text viewmodel you ever saw

--- src/AkavacheTest.Shared/ViewModels/MainActivityViewModel.cs
+++ src/AkavacheTest.Shared/ViewModels/MainActivityViewModel.cs
@@ -35,14 +35,22 @@
             WriteStringToCache.Subscribe(returnedString => TextFromCache = returnedString);

             WriteStringToCache.ThrownExceptions.Subscribe(
-                exception => this.Log().ErrorException("There was an error reading/writing to cache", exception));
+                exception =>
+                {
+                    this.Log().ErrorException("There was an error reading/writing to cache", exception);
+                    TextFromCache = string.Format("Error reading/writing to cache: {0}", exception);
+                });

-
-            ReadStringFromCache = ReactiveCommand.CreateAsyncTask(canStore, async _ => await ReadStringFromCacheImpl());
+            var canRead = Observable.Return(true);
+            ReadStringFromCache = ReactiveCommand.CreateAsyncTask(canRead, async _ => await ReadStringFromCacheImpl());
             ReadStringFromCache.Subscribe(returnedString => TextFromCache = returnedString);

             ReadStringFromCache.ThrownExceptions.Subscribe(
-                exception => this.Log().ErrorException("There was an error reading from the cache", exception));
+                exception =>
+                {
+                    this.Log().ErrorException("There was an error reading from the cache", exception);
+                    TextFromCache = string.Format("Error reading cache: {0}", exception);
+                });

         }


Improve ReaderWriterLockSlim scalability (#13495)

* Improve ReaderWriterLockSlim scalability

Subset of #13243, fixes #12780

- Prevented waking more than one waiter when only one of them may acquire the lock
- Limited spinning in some cases where it is very unlikely that spinning would help

The _myLock spin lock runs into some bad scalability issues. For example:
1. Readers can starve writers for an unreasonable amount of time. Typically there would be more readers than writers, and it doesn't take many readers to starve a writer. On my machine with 6 cores (12 logical processors with hyperthreading), 6 to 16 reader threads attempting to acquire the spin lock to acquire or release a read lock can starve one writer thread from acquiring the spin lock for several or many seconds. The issue magnifies with more reader threads.
2. Readers and especially writers that hold the RW lock can be starved from even releasing their lock. Releasing an RW lock requires acquiring the spin lock, so releasers are easliy starved by acquirers. How badly they are starved depends on how many acquirers there are, and it doesn't take many to show a very noticeable scalability issue. Often, these acquirers are those that would not be able to acquire the RW lock until one or more releasers release their lock, so the acquirers effectively starve themselves.

This PR does not solve (1), but solves (2) to a degree that could be considered sufficient. #13243 solves (1) and (2) and for (2) it is still better by order-of-magnitude compared with this PR in several cases that I believe are not extreme, but if the complexity of deprioritization is deemed excessive for the goals then of what I tried so far this is the perhaps simplest and most reasonable way to solve (2).

I believe this PR would also be a reasonably low-risk one to port back to .NET Framework.

--- src/mscorlib/shared/System/Threading/ReaderWriterLockSlim.cs
+++ src/mscorlib/shared/System/Threading/ReaderWriterLockSlim.cs
@@ -4,7 +4,6 @@

 using Internal.Runtime.Augments;
 using System.Diagnostics; // for TraceInformation
-using System.Threading;
 using System.Runtime.CompilerServices;

 namespace System.Threading
@@ -54,8 +53,10 @@
     /// </summary>
     public class ReaderWriterLockSlim : IDisposable
     {
+        private static readonly int ProcessorCount = Environment.ProcessorCount;
+
         //Specifying if locked can be reacquired recursively.
-        private bool _fIsReentrant;
+        private readonly bool _fIsReentrant;

         // Lock specification for myLock:  This lock protects exactly the local fields associated with this
         // instance of ReaderWriterLockSlim.  It does NOT protect the memory associated with
@@ -74,8 +75,7 @@
         private uint _numWriteUpgradeWaiters;      // maximum number of threads that can be doing a WaitOne on the upgradeEvent (at most 1).
         private uint _numUpgradeWaiters;

-        //Variable used for quick check when there are no waiters.
-        private bool _fNoWaiters;
+        private WaiterStates _waiterStates;

         private int _upgradeLockOwnerId;
         private int _writeLockOwnerId;
@@ -146,8 +146,35 @@
                 _fIsReentrant = true;
             }
             InitializeThreadCounts();
-            _fNoWaiters = true;
+            _waiterStates = WaiterStates.NoWaiters;
             _lockID = Interlocked.Increment(ref s_nextLockID);
+        }
+
+        private bool HasNoWaiters
+        {
+            get
+            {
+#if DEBUG
+                Debug.Assert(MyLockHeld);
+#endif
+
+                return (_waiterStates & WaiterStates.NoWaiters) != WaiterStates.None;
+            }
+            set
+            {
+#if DEBUG
+                Debug.Assert(MyLockHeld);
+#endif
+
+                if (value)
+                {
+                    _waiterStates |= WaiterStates.NoWaiters;
+                }
+                else
+                {
+                    _waiterStates &= ~WaiterStates.NoWaiters;
+                }
+            }
         }

         [MethodImpl(MethodImplOptions.AggressiveInlining)]
@@ -352,8 +379,7 @@
             }

             bool retVal = true;
-
-            int spincount = 0;
+            int spinCount = 0;

             for (; ;)
             {
@@ -368,13 +394,17 @@
                     break;
                 }

-                if (spincount < MaxSpinCount)
-                {
-                    ExitMyLock();
-                    if (timeout.IsExpired)
-                        return false;
-                    spincount++;
-                    SpinWait(spincount);
+                if (timeout.IsExpired)
+                {
+                    ExitMyLock();
+                    return false;
+                }
+
+                if (spinCount < MaxSpinCount && ShouldSpinForEnterAnyRead())
+                {
+                    ExitMyLock();
+                    spinCount++;
+                    SpinWait(spinCount);
                     EnterMyLock();
                     //The per-thread structure may have been recycled as the lock is acquired (due to message pumping), load again.
                     if (IsRwHashEntryChanged(lrwc))
@@ -391,7 +421,13 @@
                     continue;   // since we left the lock, start over.
                 }

-                retVal = WaitOnEvent(_readEvent, ref _numReadWaiters, timeout, isWriteWaiter: false);
+                retVal =
+                    WaitOnEvent(
+                        _readEvent,
+                        ref _numReadWaiters,
+                        timeout,
+                        isWriteWaiter: false,
+                        waiterSignaledState: WaiterStates.None);
                 if (!retVal)
                 {
                     return false;
@@ -480,8 +516,8 @@
                 }
             }

-            int spincount = 0;
             bool retVal = true;
+            int spinCount = 0;

             for (; ;)
             {
@@ -528,13 +564,17 @@
                     }
                 }

-                if (spincount < MaxSpinCount)
-                {
-                    ExitMyLock();
-                    if (timeout.IsExpired)
-                        return false;
-                    spincount++;
-                    SpinWait(spincount);
+                if (timeout.IsExpired)
+                {
+                    ExitMyLock();
+                    return false;
+                }
+
+                if (spinCount < MaxSpinCount && ShouldSpinForEnterAnyWrite(upgradingToWrite))
+                {
+                    ExitMyLock();
+                    spinCount++;
+                    SpinWait(spinCount);
                     EnterMyLock();
                     continue;
                 }
@@ -549,7 +589,13 @@

                     Debug.Assert(_numWriteUpgradeWaiters == 0, "There can be at most one thread with the upgrade lock held.");

-                    retVal = WaitOnEvent(_waitUpgradeEvent, ref _numWriteUpgradeWaiters, timeout, isWriteWaiter: true);
+                    retVal =
+                        WaitOnEvent(
+                            _waitUpgradeEvent,
+                            ref _numWriteUpgradeWaiters,
+                            timeout,
+                            isWriteWaiter: true,
+                            waiterSignaledState: WaiterStates.None);

                     //The lock is not held in case of failure.
                     if (!retVal)
@@ -564,7 +610,13 @@
                         continue;   // since we left the lock, start over.
                     }

-                    retVal = WaitOnEvent(_writeEvent, ref _numWriteWaiters, timeout, isWriteWaiter: true);
+                    retVal =
+                        WaitOnEvent(
+                            _writeEvent,
+                            ref _numWriteWaiters,
+                            timeout,
+                            isWriteWaiter: true,
+                            waiterSignaledState: WaiterStates.WriteWaiterSignaled);
                     //The lock is not held in case of failure.
                     if (!retVal)
                         return false;
@@ -671,8 +723,7 @@
             }

             bool retVal = true;
-
-            int spincount = 0;
+            int spinCount = 0;

             for (; ;)
             {
@@ -686,13 +737,17 @@
                     break;
                 }

-                if (spincount < MaxSpinCount)
-                {
-                    ExitMyLock();
-                    if (timeout.IsExpired)
-                        return false;
-                    spincount++;
-                    SpinWait(spincount);
+                if (timeout.IsExpired)
+                {
+                    ExitMyLock();
+                    return false;
+                }
+
+                if (spinCount < MaxSpinCount && ShouldSpinForEnterAnyRead())
+                {
+                    ExitMyLock();
+                    spinCount++;
+                    SpinWait(spinCount);
                     EnterMyLock();
                     continue;
                 }
@@ -705,7 +760,13 @@
                 }

                 //Only one thread with the upgrade lock held can proceed.
-                retVal = WaitOnEvent(_upgradeEvent, ref _numUpgradeWaiters, timeout, isWriteWaiter: false);
+                retVal =
+                    WaitOnEvent(
+                        _upgradeEvent,
+                        ref _numUpgradeWaiters,
+                        timeout,
+                        isWriteWaiter: false,
+                        waiterSignaledState: WaiterStates.UpgradeableReadWaiterSignaled);
                 if (!retVal)
                     return false;
             }
@@ -890,14 +951,20 @@
             EventWaitHandle waitEvent,
             ref uint numWaiters,
             TimeoutTracker timeout,
-            bool isWriteWaiter)
+            bool isWriteWaiter,
+            WaiterStates waiterSignaledState)
         {
 #if DEBUG
             Debug.Assert(MyLockHeld);
 #endif
+            Debug.Assert(
+                waiterSignaledState == WaiterStates.None ||
+                waiterSignaledState == WaiterStates.WriteWaiterSignaled ||
+                waiterSignaledState == WaiterStates.UpgradeableReadWaiterSignaled);
+
             waitEvent.Reset();
             numWaiters++;
-            _fNoWaiters = false;
+            HasNoWaiters = false;

             //Setting these bits will prevent new readers from getting in.
             if (_numWriteWaiters == 1)
@@ -917,8 +984,19 @@
                 EnterMyLock();
                 --numWaiters;

+                if (waitSuccessful && waiterSignaledState != WaiterStates.None)
+                {
+                    // Indicate that a signaled waiter of this type has woken. Since non-read waiters are signaled to wake one
+                    // at a time, we avoid waking up more than one waiter of that type upon successive enter/exit loops until
+                    // the signaled thread actually wakes up. For example, if there are multiple write waiters and one thread is
+                    // repeatedly entering and exiting a write lock, every exit would otherwise signal a different write waiter
+                    // to wake up unnecessarily when only one woken waiter may actually succeed in entering the write lock.
+                    Debug.Assert((_waiterStates & waiterSignaledState) != WaiterStates.None);
+                    _waiterStates &= ~waiterSignaledState;
+                }
+
                 if (_numWriteWaiters == 0 && _numWriteUpgradeWaiters == 0 && _numUpgradeWaiters == 0 && _numReadWaiters == 0)
-                    _fNoWaiters = true;
+                    HasNoWaiters = true;

                 if (_numWriteWaiters == 0)
                     ClearWritersWaiting();
@@ -948,7 +1026,7 @@
 #if DEBUG
             Debug.Assert(MyLockHeld);
 #endif
-            if (_fNoWaiters)
+            if (HasNoWaiters)
             {
                 ExitMyLock();
                 return;
@@ -984,8 +1062,20 @@
             }
             else if (readercount == 0 && _numWriteWaiters > 0)
             {
+                // Check if a waiter of the same type has already been signaled but hasn't woken yet. If so, avoid signaling
+                // and waking another waiter unnecessarily.
+                WaiterStates signaled = _waiterStates & WaiterStates.WriteWaiterSignaled;
+                if (signaled == WaiterStates.None)
+                {
+                    _waiterStates |= WaiterStates.WriteWaiterSignaled;
+                }
+
                 ExitMyLock();      // Exit before signaling to improve efficiency (wakee will need the lock)
-                _writeEvent.Set();   // release one writer.
+
+                if (signaled == WaiterStates.None)
+                {
+                    _writeEvent.Set();   // release one writer.
+                }
             }
             else
             {
@@ -999,7 +1089,7 @@
             Debug.Assert(MyLockHeld);
 #endif

-            if (_numWriteWaiters != 0 || _numWriteUpgradeWaiters != 0 || _fNoWaiters)
+            if (_numWriteWaiters != 0 || _numWriteUpgradeWaiters != 0 || HasNoWaiters)
             {
                 ExitMyLock();
                 return;
@@ -1009,6 +1099,19 @@

             bool setReadEvent = _numReadWaiters != 0;
             bool setUpgradeEvent = _numUpgradeWaiters != 0 && _upgradeLockOwnerId == -1;
+            if (setUpgradeEvent)
+            {
+                // Check if a waiter of the same type has already been signaled but hasn't woken yet. If so, avoid signaling
+                // and waking another waiter unnecessarily.
+                if ((_waiterStates & WaiterStates.UpgradeableReadWaiterSignaled) == WaiterStates.None)
+                {
+                    _waiterStates |= WaiterStates.UpgradeableReadWaiterSignaled;
+                }
+                else
+                {
+                    setUpgradeEvent = false;
+                }
+            }

             ExitMyLock();    // Exit before signaling to improve efficiency (wakee will need the lock)

@@ -1059,33 +1162,62 @@
             return _owners & READER_MASK;
         }

+        private bool ShouldSpinForEnterAnyRead()
+        {
+            // If there is a write waiter or write upgrade waiter, the waiter would block a reader from acquiring the RW lock
+            // because the waiter takes precedence. In that case, the reader is not likely to make progress by spinning.
+            // Although another thread holding a write lock would prevent this thread from acquiring a read lock, it is by
+            // itself not a good enough reason to skip spinning.
+            return HasNoWaiters || (_numWriteWaiters == 0 && _numWriteUpgradeWaiters == 0);
+        }
+
+        private bool ShouldSpinForEnterAnyWrite(bool isUpgradeToWrite)
+        {
+            // If there is a write upgrade waiter, the waiter would block a writer from acquiring the RW lock because the waiter
+            // holds a read lock. In that case, the writer is not likely to make progress by spinning. Regarding upgrading to a
+            // write lock, there is no type of waiter that would block the upgrade from happening. Although another thread
+            // holding a read or write lock would prevent this thread from acquiring the write lock, it is by itself not a good
+            // enough reason to skip spinning.
+            return isUpgradeToWrite || _numWriteUpgradeWaiters == 0;
+        }
+
+        [MethodImpl(MethodImplOptions.AggressiveInlining)]
+        private bool TryEnterMyLock()
+        {
+            return Interlocked.CompareExchange(ref _myLock, 1, 0) == 0;
+        }
+
         [MethodImpl(MethodImplOptions.AggressiveInlining)]
         private void EnterMyLock()
         {
-            if (Interlocked.CompareExchange(ref _myLock, 1, 0) != 0)
+            if (!TryEnterMyLock())
+            {
                 EnterMyLockSpin();
+            }
         }

         private void EnterMyLockSpin()
         {
-            int pc = Environment.ProcessorCount;
-            for (int i = 0; ; i++)
-            {
-                if (i < LockSpinCount && pc > 1)
-                {
-                    RuntimeThread.SpinWait(LockSpinCycles * (i + 1)); // Wait a few dozen instructions to let another processor release lock.
-                }
-                else if (i < (LockSpinCount + LockSleep0Count))
-                {
-                    RuntimeThread.Sleep(0);   // Give up my quantum.
+            int processorCount = ProcessorCount;
+            for (int spinIndex = 0; ; spinIndex++)
+            {
+                if (spinIndex < LockSpinCount && processorCount > 1)
+                {
+                    RuntimeThread.SpinWait(LockSpinCycles * (spinIndex + 1)); // Wait a few dozen instructions to let another processor release lock.
+                }
+                else if (spinIndex < (LockSpinCount + LockSleep0Count))
+                {
+                    RuntimeThread.Sleep(0);   // Give up my quantum.
                 }
                 else
                 {
-                    RuntimeThread.Sleep(1);   // Give up my quantum.
-                }
-
-                if (_myLock == 0 && Interlocked.CompareExchange(ref _myLock, 1, 0) == 0)
+                    RuntimeThread.Sleep(1);   // Give up my quantum.
+                }
+
+                if (_myLock == 0 && TryEnterMyLock())
+                {
                     return;
+                }
             }
         }

@@ -1099,12 +1231,12 @@
         private bool MyLockHeld { get { return _myLock != 0; } }
 #endif

-        private static void SpinWait(int SpinCount)
+        private static void SpinWait(int spinCount)
         {
             //Exponential back-off
-            if ((SpinCount < 5) && (Environment.ProcessorCount > 1))
-            {
-                RuntimeThread.SpinWait(LockSpinCycles * SpinCount);
+            if ((spinCount < 5) && (ProcessorCount > 1))
+            {
+                RuntimeThread.SpinWait(LockSpinCycles * spinCount);
             }
             else
             {
@@ -1307,5 +1439,19 @@
                 return (int)_numWriteWaiters;
             }
         }
+
+        [Flags]
+        private enum WaiterStates : byte
+        {
+            None = 0x0,
+
+            // Used for quick check when there are no waiters
+            NoWaiters = 0x1,
+
+            // Used to avoid signaling more than one waiter to wake up when only one can make progress, see WaitOnEvent
+            WriteWaiterSignaled = 0x2,
+            UpgradeableReadWaiterSignaled = 0x4
+            // Write upgrade waiters are excluded because there can only be one at any given time
+        }
     }
 }


Move system.printing where mono won't see it

--- src/BloomExe/Publish/MakePdfUsingGeckofxHtmlToPdfProgram.cs
+++ src/BloomExe/Publish/MakePdfUsingGeckofxHtmlToPdfProgram.cs
@@ -4,7 +4,6 @@
 using System.Diagnostics;
 using System.IO;
 using System.Linq;
-using System.Printing;
 using System.Reflection;
 using System.Threading;
 using System.Windows.Forms;
@@ -55,7 +54,7 @@
 				}
 				else
 				{
-					PrintQueue defaultPrinter;
+					System.Printing.PrintQueue defaultPrinter;
 					// BL-2535 it's possible get past the above printQueues.Any() but then get
 					// a System.Printing.PrintQueueException exception with "Access Denied" error here, if
 					// the default printer for some reason is no longer "allowed".