Add support for BSWAP intrinsic (dotnet/coreclr#18398)

With this change, the JIT will recognize a call to BinaryPrimitives.ReverseEndianness and will emit a bswap instruction.
This logic is currently only hooked up for x86 and x64; ARM still uses fallback logic.
If the JIT can't emit a bswap instruction (for example, trying to emit a 64-bit bswap in a 32-bit process), it will fall back to a software implementation, so the APIs will work across all architectures.

Signed-off-by: dotnet-bot <03c4cb6107ae99956a7681f2c97ff7104809a2bd@microsoft.com>

--- src/Common/src/CoreLib/System/Buffers/Binary/Reader.cs
+++ src/Common/src/CoreLib/System/Buffers/Binary/Reader.cs
@@ -30,21 +30,21 @@
         /// <summary>
         /// Reverses a primitive value - performs an endianness swap
         /// </summary>
+        [Intrinsic]
         [MethodImpl(MethodImplOptions.AggressiveInlining)]
-        public static short ReverseEndianness(short value)
-        {
-            return (short)((value & 0x00FF) << 8 | (value & 0xFF00) >> 8);
-        }
+        public static short ReverseEndianness(short value) => (short)ReverseEndianness((ushort)value);

         /// <summary>
         /// Reverses a primitive value - performs an endianness swap
         /// </summary>
+        [Intrinsic]
         [MethodImpl(MethodImplOptions.AggressiveInlining)]
         public static int ReverseEndianness(int value) => (int)ReverseEndianness((uint)value);

         /// <summary>
         /// Reverses a primitive value - performs an endianness swap
         /// </summary>
+        [Intrinsic]
         [MethodImpl(MethodImplOptions.AggressiveInlining)]
         public static long ReverseEndianness(long value) => (long)ReverseEndianness((ulong)value);

@@ -54,7 +54,7 @@
         /// rather than having to skip byte fields.
         /// </summary>
         [MethodImpl(MethodImplOptions.AggressiveInlining)]
-        public static byte ReverseEndianness(byte value)
+        public static byte ReverseEndianness(byte value)
         {
             return value;
         }
@@ -63,6 +63,7 @@
         /// Reverses a primitive value - performs an endianness swap
         /// </summary>
         [CLSCompliant(false)]
+        [Intrinsic]
         [MethodImpl(MethodImplOptions.AggressiveInlining)]
         public static ushort ReverseEndianness(ushort value)
         {
@@ -80,6 +81,7 @@
         /// Reverses a primitive value - performs an endianness swap
         /// </summary>
         [CLSCompliant(false)]
+        [Intrinsic]
         [MethodImpl(MethodImplOptions.AggressiveInlining)]
         public static uint ReverseEndianness(uint value)
         {
@@ -113,6 +115,7 @@
         /// Reverses a primitive value - performs an endianness swap
         /// </summary>
         [CLSCompliant(false)]
+        [Intrinsic]
         [MethodImpl(MethodImplOptions.AggressiveInlining)]
         public static ulong ReverseEndianness(ulong value)
         {


Typo in SyntaxAnnotation class description

--- src/Compilers/Core/Portable/Syntax/SyntaxAnnotation.cs
+++ src/Compilers/Core/Portable/Syntax/SyntaxAnnotation.cs
@@ -7,7 +7,7 @@
 namespace Microsoft.CodeAnalysis
 {
     /// <summary>
-    /// A SynatxAnnotation is used to annotate syntax elements with additional information.
+    /// A SyntaxAnnotation is used to annotate syntax elements with additional information.
     ///
     /// Since syntax elements are immutable, annotating them requires creating new instances of them
     /// with the annotations attached.


InhibitNewItems

InhibitNewItems

--- src/DatenMeisterWPF/Forms/Base/ListViewControl.xaml.cs
+++ src/DatenMeisterWPF/Forms/Base/ListViewControl.xaml.cs
@@ -66,7 +66,8 @@
         /// </summary>
         public void UpdateContent()
         {
-            //SupportNewItems = !DotNetHelper. FormDefinition.get("inhibitNewItems")
+            SupportNewItems = !DotNetHelper.AsBoolean(FormDefinition.get(_FormAndFields._Form.inhibitNewItems));
+
             var listItems = new List<ExpandoObject>();
             _itemMapping.Clear();


Removed redundant this qualifier.

Removed redundant this qualifier.

--- src/ExcelDataReader/Core/BinaryFormat/XlsBiffStream.cs
+++ src/ExcelDataReader/Core/BinaryFormat/XlsBiffStream.cs
@@ -21,12 +21,12 @@

         public XlsBiffStream(XlsHeader hdr, uint streamStart, bool isMini, XlsRootDirectory rootDir, ExcelBinaryReader reader)
         {
-            this._reader = reader;
+            _reader = reader;
             var xlsStream = new XlsStream(hdr, streamStart, isMini, rootDir);
             _bytes = xlsStream.ReadStream();

 #if NET45 || NET20
-            XlsBiffRecord rec = XlsBiffRecord.GetRecord(_bytes, 0, this._reader);
+            XlsBiffRecord rec = XlsBiffRecord.GetRecord(_bytes, 0, _reader);
             XlsBiffRecord rec2 = XlsBiffRecord.GetRecord(_bytes, (uint)rec.Size, reader);
             XlsBiffFilePass filePass = rec2 as XlsBiffFilePass;
             if (filePass == null)


Removed Server Certificate check

Removed Server Certificate check

--- src/Exceptionless.Insulation/Mail/MailKitMailSender.cs
+++ src/Exceptionless.Insulation/Mail/MailKitMailSender.cs
@@ -34,8 +34,6 @@
             message.Headers.Add("Auto-Submitted", "auto-generated");

             using (var client = new SmtpClient()) {
-                client.ServerCertificateValidationCallback = (s, c, h, e) => true;
-
                 string host = _emailOptions.Value.SmtpHost;
                 int port = _emailOptions.Value.SmtpPort;
                 var encryption = GetSecureSocketOption(_emailOptions.Value.SmtpEncryption);


Compute fixes by order of fixers, so we don't have to sort them afterwards

--- src/Features/Core/Portable/CodeFixes/CodeFixService.cs
+++ src/Features/Core/Portable/CodeFixes/CodeFixService.cs
@@ -42,7 +42,7 @@
         private readonly ImmutableArray<Lazy<CodeFixProvider, CodeChangeProviderMetadata>> _fixers;
         private readonly Dictionary<string, List<Lazy<CodeFixProvider, CodeChangeProviderMetadata>>> _fixersPerLanguageMap;

-        private readonly ConditionalWeakTable<IReadOnlyList<AnalyzerReference>, ImmutableDictionary<DiagnosticId, List<CodeFixProvider>>> _projectFixersMap = new();
+        private readonly ConditionalWeakTable<IReadOnlyList<AnalyzerReference>, ImmutableDictionary<DiagnosticId, ImmutableArray<CodeFixProvider>>> _projectFixersMap = new();

         // Shared by project fixers and workspace fixers.
         private readonly Lazy<ImmutableDictionary<CodeFixProvider, CodeChangeProviderMetadata>> _lazyFixerToMetadataMap;
@@ -183,51 +183,33 @@
                 if (diagnostic.IsSuppressed)
                     continue;

-                cancellationToken.ThrowIfCancellationRequested();
-
-                aggregatedDiagnostics.GetOrAdd(diagnostic.GetTextSpan(), _ => new List<DiagnosticData>()).Add(diagnostic);
+                var list = aggregatedDiagnostics.GetOrAdd(diagnostic.GetTextSpan(), static _ => new List<DiagnosticData>());
+                list.Add(diagnostic);
             }

             if (aggregatedDiagnostics.Count == 0)
                 return ImmutableArray<CodeFixCollection>.Empty;

             // Order diagnostics by DiagnosticId so the fixes are in a deterministic order.
-            foreach (var diagnosticsWithSpan in aggregatedDiagnostics.Values)
-            {
-                diagnosticsWithSpan.Sort(s_diagnosticDataComparisonById);
-            }
+            foreach (var (_, diagnosticList) in aggregatedDiagnostics)
+                diagnosticList.Sort(s_diagnosticDataComparisonById);

             // append fixes for all diagnostics with the same diagnostics span
-            using var resultDisposer = ArrayBuilder<CodeFixCollection>.GetInstance(out var result);
+            using var _1 = ArrayBuilder<CodeFixCollection>.GetInstance(out var result);

             // 'CodeActionRequestPriority.Lowest' is used when the client only wants suppression/configuration fixes.
             if (priority != CodeActionRequestPriority.Lowest)
             {
-                foreach (var spanAndDiagnostic in aggregatedDiagnostics)
-                {
-                    await AppendFixesAsync(
-                        document, spanAndDiagnostic.Key, spanAndDiagnostic.Value, fixAllForInSpan: false,
-                        priority, options, result, addOperationScope, cancellationToken).ConfigureAwait(false);
-                }
-            }
-
-            if (result.Count > 0 && TryGetWorkspaceFixersPriorityMap(document, out var fixersForLanguage))
-            {
-                // sort the result to the order defined by the fixers
-#pragma warning disable IDE0007 // Use implicit type - Explicit type is need to suppress an incorrect nullable warning on dereferencing the map.
-                ImmutableDictionary<CodeFixProvider, int> priorityMap = fixersForLanguage.Value;
-#pragma warning restore IDE0007 // Use implicit type
-                result.Sort((d1, d2) => GetValue(d1).CompareTo(GetValue(d2)));
-
-                int GetValue(CodeFixCollection c)
-                    => priorityMap.TryGetValue((CodeFixProvider)c.Provider, out var value) ? value : int.MaxValue;
+                await AppendFixesAsync(
+                    document, aggregatedDiagnostics, fixAllForInSpan: false,
+                    priority, options, result, addOperationScope, cancellationToken).ConfigureAwait(false);
             }

             // TODO (https://github.com/dotnet/roslyn/issues/4932): Don't restrict CodeFixes in Interactive
             if (document.Project.Solution.Workspace.Kind != WorkspaceKind.Interactive && includeSuppressionFixes)
             {
                 // Ensure that we do not register duplicate configuration fixes.
-                using var _ = PooledHashSet<string>.GetInstance(out var registeredConfigurationFixTitles);
+                using var _2 = PooledHashSet<string>.GetInstance(out var registeredConfigurationFixTitles);
                 foreach (var (span, diagnosticList) in aggregatedDiagnostics)
                 {
                     await AppendConfigurationsAsync(
@@ -254,16 +236,22 @@
             }
         }

-        public async Task<CodeFixCollection?> GetDocumentFixAllForIdInSpanAsync(Document document, TextSpan range, string diagnosticId, CodeActionOptions options, CancellationToken cancellationToken)
+        public async Task<CodeFixCollection?> GetDocumentFixAllForIdInSpanAsync(
+            Document document, TextSpan range, string diagnosticId, CodeActionOptions options, CancellationToken cancellationToken)
         {
             var diagnostics = (await _diagnosticService.GetDiagnosticsForSpanAsync(document, range, diagnosticId, includeSuppressedDiagnostics: false, cancellationToken: cancellationToken).ConfigureAwait(false)).ToList();
             if (diagnostics.Count == 0)
-            {
                 return null;
-            }

             using var resultDisposer = ArrayBuilder<CodeFixCollection>.GetInstance(out var result);
-            await AppendFixesAsync(document, range, diagnostics, fixAllForInSpan: true, CodeActionRequestPriority.None, options, result, addOperationScope: _ => null, cancellationToken).ConfigureAwait(false);
+            var spanToDiagnostics = new SortedDictionary<TextSpan, List<DiagnosticData>>
+            {
+                {range, diagnostics },
+            };
+
+            await AppendFixesAsync(
+                document, spanToDiagnostics, fixAllForInSpan: true, CodeActionRequestPriority.None,
+                options, result, addOperationScope: static _ => null, cancellationToken).ConfigureAwait(false);

             // TODO: Just get the first fix for now until we have a way to config user's preferred fix
             // https://github.com/dotnet/roslyn/issues/27066
@@ -356,8 +344,7 @@

         private async Task AppendFixesAsync(
             Document document,
-            TextSpan span,
-            IEnumerable<DiagnosticData> diagnostics,
+            SortedDictionary<TextSpan, List<DiagnosticData>> spanToDiagnostics,
             bool fixAllForInSpan,
             CodeActionRequestPriority priority,
             CodeActionOptions options,
@@ -371,39 +358,47 @@
             var hasAnyProjectFixer = projectFixersMap.Any();

             if (!hasAnySharedFixer && !hasAnyProjectFixer)
-            {
                 return;
-            }
-
-            var allFixers = new List<CodeFixProvider>();

             // TODO (https://github.com/dotnet/roslyn/issues/4932): Don't restrict CodeFixes in Interactive
             var isInteractive = document.Project.Solution.Workspace.Kind == WorkspaceKind.Interactive;

             // gather CodeFixProviders for all distinct diagnostics found for current span
-            foreach (var diagnosticId in diagnostics.Select(d => d.Id).Distinct())
-            {
-                cancellationToken.ThrowIfCancellationRequested();
-
-                // Prioritize NuGet based project code fixers over VSIX based workspace code fixers.
-                if (hasAnyProjectFixer && projectFixersMap.TryGetValue(diagnosticId, out var projectFixers))
-                {
-                    Debug.Assert(!isInteractive);
-                    allFixers.AddRange(projectFixers);
-                }
-
-                if (hasAnySharedFixer && fixerMap!.Value.TryGetValue(diagnosticId, out var workspaceFixers))
-                {
-                    if (isInteractive)
-                    {
-                        allFixers.AddRange(workspaceFixers.Where(IsInteractiveCodeFixProvider));
-                    }
-                    else
-                    {
-                        allFixers.AddRange(workspaceFixers);
-                    }
-                }
-            }
+            using var _1 = ArrayBuilder<CodeFixProvider>.GetInstance(out var allFixers);
+            using var _2 = PooledDictionary<CodeFixProvider, List<(TextSpan range, List<DiagnosticData> diagnostics)>>.GetInstance(out var fixerToRangesAndDiagnostics);
+
+            foreach (var (range, diagnostics) in spanToDiagnostics)
+            {
+                foreach (var diagnosticId in diagnostics.Select(d => d.Id).Distinct())
+                {
+                    cancellationToken.ThrowIfCancellationRequested();
+
+                    // Prioritize NuGet based project code fixers over VSIX based workspace code fixers.
+                    if (hasAnyProjectFixer && projectFixersMap.TryGetValue(diagnosticId, out var projectFixers))
+                    {
+                        Debug.Assert(!isInteractive);
+                        AddAllFixers(projectFixers, range, diagnostics);
+                    }
+
+                    if (hasAnySharedFixer && fixerMap!.Value.TryGetValue(diagnosticId, out var workspaceFixers))
+                    {
+                        if (isInteractive)
+                        {
+                            AddAllFixers(workspaceFixers.WhereAsArray(IsInteractiveCodeFixProvider), range, diagnostics);
+                        }
+                        else
+                        {
+                            AddAllFixers(workspaceFixers, range, diagnostics);
+                        }
+                    }
+                }
+            }
+
+            allFixers.RemoveDuplicates();
+
+            // Now, sort the fixers so that the ones that are ordered before others get their chance to run first.
+            if (TryGetWorkspaceFixersPriorityMap(document, out var fixersForLanguage))
+                allFixers.Sort(new FixerComparer(fixersForLanguage.Value));

             var extensionManager = document.Project.Solution.Workspace.Services.GetService<IExtensionManager>();

@@ -420,39 +415,42 @@

             try
             {
-                foreach (var fixer in allFixers.Distinct())
+                foreach (var fixer in allFixers)
                 {
                     cancellationToken.ThrowIfCancellationRequested();

                     if (priority != CodeActionRequestPriority.None && priority != fixer.RequestPriority)
                         continue;

-                    await AppendFixesOrConfigurationsAsync(
-                        document, span, diagnostics, fixAllForInSpan, result, fixer,
-                        hasFix: d => this.GetFixableDiagnosticIds(fixer, extensionManager).Contains(d.Id),
-                        getFixes: dxs =>
-                        {
-                            var fixerName = fixer.GetType().Name;
-                            FixerToMetadataMap.TryGetValue(fixer, out var fixerMetadata);
-
-                            using (addOperationScope(fixerName))
-                            using (RoslynEventSource.LogInformationalBlock(FunctionId.CodeFixes_GetCodeFixesAsync, fixerName, cancellationToken))
+                    foreach (var (span, diagnostics) in fixerToRangesAndDiagnostics[fixer])
+                    {
+                        await AppendFixesOrConfigurationsAsync(
+                            document, span, diagnostics, fixAllForInSpan, result, fixer,
+                            hasFix: d => this.GetFixableDiagnosticIds(fixer, extensionManager).Contains(d.Id),
+                            getFixes: dxs =>
                             {
-                                if (fixAllForInSpan)
+                                var fixerName = fixer.GetType().Name;
+                                FixerToMetadataMap.TryGetValue(fixer, out var fixerMetadata);
+
+                                using (addOperationScope(fixerName))
+                                using (RoslynEventSource.LogInformationalBlock(FunctionId.CodeFixes_GetCodeFixesAsync, fixerName, cancellationToken))
                                 {
-                                    var primaryDiagnostic = dxs.First();
-                                    return GetCodeFixesAsync(document, primaryDiagnostic.Location.SourceSpan, fixer, fixerMetadata, options,
-                                        ImmutableArray.Create(primaryDiagnostic), uniqueDiagosticToEquivalenceKeysMap,
-                                        diagnosticAndEquivalenceKeyToFixersMap, cancellationToken);
+                                    if (fixAllForInSpan)
+                                    {
+                                        var primaryDiagnostic = dxs.First();
+                                        return GetCodeFixesAsync(document, primaryDiagnostic.Location.SourceSpan, fixer, fixerMetadata, options,
+                                            ImmutableArray.Create(primaryDiagnostic), uniqueDiagosticToEquivalenceKeysMap,
+                                            diagnosticAndEquivalenceKeyToFixersMap, cancellationToken);
+                                    }
+                                    else
+                                    {
+                                        return GetCodeFixesAsync(document, span, fixer, fixerMetadata, options, dxs,
+                                            uniqueDiagosticToEquivalenceKeysMap, diagnosticAndEquivalenceKeyToFixersMap, cancellationToken);
+                                    }
                                 }
-                                else
-                                {
-                                    return GetCodeFixesAsync(document, span, fixer, fixerMetadata, options, dxs,
-                                        uniqueDiagosticToEquivalenceKeysMap, diagnosticAndEquivalenceKeyToFixersMap, cancellationToken);
-                                }
-                            }
-                        },
-                        cancellationToken: cancellationToken).ConfigureAwait(false);
+                            },
+                            cancellationToken).ConfigureAwait(false);
+                    }

                     // Just need the first result if we are doing fix all in span
                     if (fixAllForInSpan && result.Any())
@@ -465,6 +463,18 @@
                 {
                     pooledSet.Free();
                 }
+            }
+
+            return;
+
+            void AddAllFixers(
+                ImmutableArray<CodeFixProvider> fixers,
+                TextSpan range,
+                List<DiagnosticData> diagnostics)
+            {
+                allFixers.AddRange(fixers);
+                foreach (var fixer in fixers)
+                    fixerToRangesAndDiagnostics.GetOrAdd(fixer, static _ => new()).Add((range, diagnostics));
             }
         }

@@ -611,7 +621,8 @@
             }

             // If the fix provider supports fix all occurrences, then get the corresponding FixAllProviderInfo and fix all context.
-            var fixAllProviderInfo = extensionManager.PerformFunction<FixAllProviderInfo?>(fixer, () => ImmutableInterlocked.GetOrAdd(ref _fixAllProviderMap, fixer, FixAllProviderInfo.Create), defaultValue: null);
+            var fixAllProviderInfo = extensionManager.PerformFunction(
+                fixer, () => ImmutableInterlocked.GetOrAdd(ref _fixAllProviderMap, fixer, FixAllProviderInfo.Create), defaultValue: null);

             FixAllState? fixAllState = null;
             var supportedScopes = ImmutableArray<FixAllScope>.Empty;
@@ -620,8 +631,8 @@
                 var codeFixProvider = (fixer as CodeFixProvider) ?? new WrapperCodeFixProvider((IConfigurationFixProvider)fixer, diagnostics.Select(d => d.Id));

                 var diagnosticIds = diagnostics.Where(fixAllProviderInfo.CanBeFixed)
-                                          .Select(d => d.Id)
-                                          .ToImmutableHashSet();
+                                               .Select(d => d.Id)
+                                               .ToImmutableHashSet();

                 // When computing FixAll for unnecessary pragma suppression diagnostic,
                 // we need to include suppressed diagnostics, as well as reported compiler and analyzer diagnostics.
@@ -932,37 +943,59 @@
             return languageMap.ToImmutable();
         }

-        private ImmutableDictionary<DiagnosticId, List<CodeFixProvider>> GetProjectFixers(Project project)
+        private ImmutableDictionary<DiagnosticId, ImmutableArray<CodeFixProvider>> GetProjectFixers(Project project)
         {
             // TODO (https://github.com/dotnet/roslyn/issues/4932): Don't restrict CodeFixes in Interactive
             return project.Solution.Workspace.Kind == WorkspaceKind.Interactive
-                ? ImmutableDictionary<DiagnosticId, List<CodeFixProvider>>.Empty
+                ? ImmutableDictionary<DiagnosticId, ImmutableArray<CodeFixProvider>>.Empty
                 : _projectFixersMap.GetValue(project.AnalyzerReferences, _ => ComputeProjectFixers(project));
         }

-        private ImmutableDictionary<DiagnosticId, List<CodeFixProvider>> ComputeProjectFixers(Project project)
+        private ImmutableDictionary<DiagnosticId, ImmutableArray<CodeFixProvider>> ComputeProjectFixers(Project project)
         {
             var extensionManager = project.Solution.Workspace.Services.GetService<IExtensionManager>();

-            var builder = ImmutableDictionary.CreateBuilder<DiagnosticId, List<CodeFixProvider>>();
-            foreach (var reference in project.AnalyzerReferences)
-            {
-                var projectCodeFixerProvider = _analyzerReferenceToFixersMap.GetValue(reference, _createProjectCodeFixProvider);
-                foreach (var fixer in projectCodeFixerProvider.GetExtensions(project.Language))
-                {
-                    var fixableIds = this.GetFixableDiagnosticIds(fixer, extensionManager);
-                    foreach (var id in fixableIds)
-                    {
-                        if (string.IsNullOrWhiteSpace(id))
-                            continue;
-
-                        var list = builder.GetOrAdd(id, static _ => new List<CodeFixProvider>());
-                        list.Add(fixer);
-                    }
-                }
-            }
-
-            return builder.ToImmutable();
+            using var _ = PooledDictionary<DiagnosticId, ArrayBuilder<CodeFixProvider>>.GetInstance(out var builder);
+            try
+            {
+                foreach (var reference in project.AnalyzerReferences)
+                {
+                    var projectCodeFixerProvider = _analyzerReferenceToFixersMap.GetValue(reference, _createProjectCodeFixProvider);
+                    foreach (var fixer in projectCodeFixerProvider.GetExtensions(project.Language))
+                    {
+                        var fixableIds = this.GetFixableDiagnosticIds(fixer, extensionManager);
+                        foreach (var id in fixableIds)
+                        {
+                            if (string.IsNullOrWhiteSpace(id))
+                                continue;
+
+                            var list = builder.GetOrAdd(id, static _ => ArrayBuilder<CodeFixProvider>.GetInstance());
+                            list.Add(fixer);
+                        }
+                    }
+                }
+
+                return builder.ToImmutableDictionary(kvp => kvp.Key, kvp => kvp.Value.ToImmutable());
+            }
+            finally
+            {
+                foreach (var kvp in builder)
+                    kvp.Value.Free();
+            }
+        }
+
+        private sealed class FixerComparer : IComparer<CodeFixProvider>
+        {
+            private readonly ImmutableDictionary<CodeFixProvider, int> _priorityMap;
+
+            public FixerComparer(ImmutableDictionary<CodeFixProvider, int> priorityMap)
+                => _priorityMap = priorityMap;
+
+            public int Compare([AllowNull] CodeFixProvider x, [AllowNull] CodeFixProvider y)
+                => GetValue(x).CompareTo(GetValue(y));
+
+            private int GetValue(CodeFixProvider provider)
+                => _priorityMap.TryGetValue(provider, out var value) ? value : int.MaxValue;
         }
     }
 }


add TODO to handle when to auto-close the issue

--- src/FilterLists.Agent/Features/Urls/ValidateAllUrls.cs
+++ src/FilterLists.Agent/Features/Urls/ValidateAllUrls.cs
@@ -31,31 +31,33 @@
                 var results = new List<DataFileUrlValidationResults>();

                 var licenseUrls = await _repo.GetAllAsync<LicenseUrls>();
-                var licenseUrlErrors = (await _mediator.Send(new ValidateUrls.Command(licenseUrls), cancellationToken));
+                var licenseUrlErrors = await _mediator.Send(new ValidateUrls.Command(licenseUrls), cancellationToken);
                 if (licenseUrlErrors.Any())
                     results.Add(new DataFileUrlValidationResults("License.json", licenseUrlErrors));

                 var listUrls = await _repo.GetAllAsync<ListUrls>();
-                var listUrlErrors = (await _mediator.Send(new ValidateUrls.Command(listUrls), cancellationToken));
+                var listUrlErrors = await _mediator.Send(new ValidateUrls.Command(listUrls), cancellationToken);
                 if (listUrlErrors.Any())
                     results.Add(new DataFileUrlValidationResults("FilterList.json", listUrlErrors));

                 var maintainerUrls = await _repo.GetAllAsync<MaintainerUrls>();
-                var maintainerUrlErrors = (await _mediator.Send(new ValidateUrls.Command(maintainerUrls), cancellationToken));
+                var maintainerUrlErrors = await _mediator.Send(new ValidateUrls.Command(maintainerUrls), cancellationToken);
                 if (maintainerUrlErrors.Any())
                     results.Add(new DataFileUrlValidationResults("Maintainer.json", maintainerUrlErrors));

                 var softwareUrls = await _repo.GetAllAsync<SoftwareUrls>();
-                var softwareUrlErrors = (await _mediator.Send(new ValidateUrls.Command(softwareUrls), cancellationToken));
+                var softwareUrlErrors = await _mediator.Send(new ValidateUrls.Command(softwareUrls), cancellationToken);
                 if (softwareUrlErrors.Any())
                     results.Add(new DataFileUrlValidationResults("Software.json", softwareUrlErrors));

                 var syntaxUrls = await _repo.GetAllAsync<SyntaxUrls>();
-                var syntaxUrlErrors = (await _mediator.Send(new ValidateUrls.Command(syntaxUrls), cancellationToken));
+                var syntaxUrlErrors = await _mediator.Send(new ValidateUrls.Command(syntaxUrls), cancellationToken);
                 if (syntaxUrlErrors.Any())
                     results.Add(new DataFileUrlValidationResults("Syntax.json", syntaxUrlErrors));

-                await _mediator.Send(new CreateOrUpdateGitHubIssue.Command(results), cancellationToken);
+                if(results.Any())
+                    await _mediator.Send(new CreateOrUpdateGitHubIssue.Command(results), cancellationToken);
+                //TODO: else, close issue
             }
         }
     }


:flushed: remove authentication

:flushed: remove authentication

--- src/GoatTrip.RestApi/Controllers/LocationController.cs
+++ src/GoatTrip.RestApi/Controllers/LocationController.cs
@@ -12,7 +12,6 @@
             _service = service;
         }

-        [Authentication.Authorize]
         [Route("search/{query?}")]
         [HttpGet]
         public IHttpActionResult Search(string query = "") {
@@ -25,7 +24,6 @@
             return Ok(result);
         }

-        [Authentication.Authorize]
         [Route("{query?}")]
         public IHttpActionResult Get(string query = "") {


avoid unnecessary object allocations in CronExpression

--- src/Quartz/CronExpression.cs
+++ src/Quartz/CronExpression.cs
@@ -1578,15 +1578,14 @@
             // loop until we've computed the next time, or we've past the endTime
             while (!gotOne)
             {
-                ISortedSet<int> st;
+                int st;
                 int t;
                 int sec = d.Second;

                 // get second.................................................
-                st = seconds.TailSet(sec);
-                if (st != null && st.Count != 0)
-                {
-                    sec = st.First();
+                if (seconds.TryWeakSuccessor(sec, out st))
+                {
+                    sec = st;
                 }
                 else
                 {
@@ -1600,11 +1599,10 @@
                 t = -1;

                 // get minute.................................................
-                st = minutes.TailSet(min);
-                if (st != null && st.Count != 0)
+                if (minutes.TryWeakSuccessor(min, out st))
                 {
                     t = min;
-                    min = st.First();
+                    min = st;
                 }
                 else
                 {
@@ -1624,11 +1622,10 @@
                 t = -1;

                 // get hour...................................................
-                st = hours.TailSet(hr);
-                if (st != null && st.Count != 0)
+                if (hours.TryWeakSuccessor(hr, out st))
                 {
                     t = hr;
-                    hr = st.First();
+                    hr = st;
                 }
                 else
                 {
@@ -1662,7 +1659,7 @@
                 if (dayOfMSpec && !dayOfWSpec)
                 {
                     // get day by day of month rule
-                    st = daysOfMonth.TailSet(day);
+                    bool found = daysOfMonth.TryWeakSuccessor(day, out st);
                     if (lastdayOfMonth)
                     {
                         if (!nearestWeekday)
@@ -1753,10 +1750,10 @@
                             mon++;
                         }
                     }
-                    else if (st != null && st.Count != 0)
+                    else if (found)
                     {
                         t = day;
-                        day = st.First();
+                        day = st;

                         // make sure we don't over-run a short month, such as february
                         int lastDay = GetLastDayOfMonth(mon, d.Year);
@@ -1903,10 +1900,9 @@
                         int cDow = ((int) d.DayOfWeek) + 1; // current d-o-w
                         int dow = daysOfWeek.First(); // desired
                         // d-o-w
-                        st = daysOfWeek.TailSet(cDow);
-                        if (st != null && st.Count > 0)
-                        {
-                            dow = st.First();
+                        if (daysOfWeek.TryWeakSuccessor(cDow, out st))
+                        {
+                            dow = st;
                         }

                         int daysToAdd = 0;
@@ -1965,11 +1961,10 @@
                 }

                 // get month...................................................
-                st = months.TailSet((mon));
-                if (st != null && st.Count != 0)
+                if (months.TryWeakSuccessor(mon, out st))
                 {
                     t = mon;
-                    mon = st.First();
+                    mon = st;
                 }
                 else
                 {
@@ -1986,11 +1981,10 @@
                 t = -1;

                 // get year...................................................
-                st = years.TailSet((year));
-                if (st != null && st.Count != 0)
+                if (years.TryWeakSuccessor(year, out st))
                 {
                     t = year;
-                    year = st.First();
+                    year = st;
                 }
                 else
                 {


Fix Events tests, need to create at least one order to test event.

--- test/BizwebSharp.Tests.xUnit/Event_Tests.cs
+++ test/BizwebSharp.Tests.xUnit/Event_Tests.cs
@@ -1,6 +1,10 @@
-using System.Collections.Generic;
+using System;
+using System.Collections.Generic;
 using System.Linq;
+using System.Net;
 using System.Threading.Tasks;
+using BizwebSharp.Enums;
+using BizwebSharp.Infrastructure;
 using BizwebSharp.Options;
 using Xunit;

@@ -35,15 +39,9 @@
         [Fact(DisplayName = "List Events For Subjects")]
         public async Task Lists_Events_For_Subjects()
         {
-            // Get an order id
-            var orderId = (await new OrderService(Utils.AuthState).ListAsync(new OrderOption
-            {
-                Limit = 1
-            })).First().Id.Value;
-
             const string subject = "order";
             const string subjectType = "orders";
-            var list = await Fixture.Service.ListAsync(subjectType, orderId);
+            var list = await Fixture.Service.ListAsync(subjectType, Fixture.OrderId.Value);

             Assert.NotNull(list);
             Assert.All(list, e => Assert.Equal(subject, e.SubjectType));
@@ -68,10 +66,126 @@
         }
     }

-    public class Event_Tests_Fixture
+    public class Event_Tests_Fixture : IAsyncLifetime
     {
+        public async Task InitializeAsync()
+        {
+            // Create at least one Order for Event tests.
+            OrderId = (await CreateAOrder()).Id.Value;
+        }
+
+        public async Task DisposeAsync()
+        {
+            foreach (var order in CreatedOrders)
+            {
+                try
+                {
+                    await OrderService.DeleteAsync(order.Id.Value);
+                }
+                catch (BizwebSharpException ex)
+                {
+                    if (ex.HttpStatusCode != HttpStatusCode.NotFound)
+                    {
+                        Console.WriteLine($"Failed to delete Order with id {order.Id.Value}. {ex.Message}");
+                    }
+                }
+            }
+        }
+
+        private async Task CleanUpOrdersSetup()
+        {
+            foreach (var order in CreatedOrders)
+            {
+                try
+                {
+                    await OrderService.DeleteAsync(order.Id.Value);
+                }
+                catch (BizwebSharpException ex)
+                {
+                    if (ex.HttpStatusCode != HttpStatusCode.NotFound)
+                    {
+                        Console.WriteLine($"Failed to delete Order with id {order.Id.Value}. {ex.Message}");
+                    }
+                }
+            }
+
+            var customerService = new CustomerService(Utils.AuthState);
+            foreach (var obj in CreatedCustomers)
+            {
+                try
+                {
+                    await customerService.DeleteAsync(obj.Id.Value);
+                }
+                catch (BizwebSharpException ex)
+                {
+                    if (ex.HttpStatusCode != HttpStatusCode.NotFound)
+                    {
+                        Console.WriteLine($"Failed to delete created Customer with id {obj.Id.Value}. {ex.Message}");
+                    }
+                }
+            }
+        }
+
+        public long? OrderId { get; set; }
+
         public EventService Service => new EventService(Utils.AuthState);

-        public List<Event> Created { get; } = new List<Event>();
+        public OrderService OrderService => new OrderService(Utils.AuthState);
+
+        public List<Order> CreatedOrders { get; } = new List<Order>();
+
+        public List<Customer> CreatedCustomers { get; } = new List<Customer>();
+
+        public async Task<Order> CreateAOrder(bool skipAddToCreatedList = false)
+        {
+            var obj = await OrderService.CreateAsync(new Order()
+            {
+                CreatedOn = DateTime.UtcNow,
+                BillingAddress = new Address()
+                {
+                    Address1 = "123 4th Street",
+                    City = "Minneapolis",
+                    Province = "Minnesota",
+                    ProvinceCode = "MN",
+                    Zip = "55401",
+                    Phone = "555-555-5555",
+                    FirstName = "John",
+                    LastName = "Doe",
+                    Company = "Tomorrow Corporation",
+                    Country = "United States",
+                    CountryCode = "US",
+                    Default = true,
+                },
+                LineItems = new List<LineItem>()
+                {
+                    new LineItem()
+                    {
+                        Name = "Test Line Item",
+                        Title = "Test Line Item Title",
+                        Quantity = 2,
+                        Price = 5
+                    },
+                    new LineItem()
+                    {
+                        Name = "Test Line Item 2",
+                        Title = "Test Line Item Title 2",
+                        Quantity = 2,
+                        Price = 5
+                    }
+                },
+                FinancialStatus = OrderFinancialStatus.Paid,
+                TotalPrice = 5.00m,
+                Email = Guid.NewGuid() + "@example.com",
+                Note = "This order was created while testing BizwebSharp!",
+            });
+
+            if (!skipAddToCreatedList)
+            {
+                CreatedOrders.Add(obj);
+                CreatedCustomers.Add(obj.Customer);
+            }
+
+            return obj;
+        }
     }
 }


Update HttpServer unit tests

Update HttpServer unit tests

--- test/System.Web.Http.Test/HttpServerTest.cs
+++ test/System.Web.Http.Test/HttpServerTest.cs
@@ -5,6 +5,7 @@
 using System.Security.Principal;
 using System.Threading;
 using System.Threading.Tasks;
+using System.Web.Http.Controllers;
 using System.Web.Http.Dispatcher;
 using System.Web.Http.Routing;
 using Microsoft.TestCommon;
@@ -291,7 +292,7 @@
         }

         [Fact]
-        public void TestRequestContext_HttpServer()
+        public void HttpServerAddsDefaultRequestContext()
         {
             // Arrange
             HttpServer server = new HttpServer();
@@ -301,30 +302,71 @@
             server.Configuration.MapHttpAttributeRoutes();
             server.Configuration.EnsureInitialized();

-            HttpClient client = new HttpClient(server);
-
-            // Act
-            var response = client.GetAsync("http://localhost/Customers").Result;
+            var invoker = new HttpMessageInvoker(server);
+
+            var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Customers");
+
+            // Act
+            var response = invoker.SendAsync(request, CancellationToken.None).Result;

             // Assert
             response.EnsureSuccessStatusCode();
             Assert.True(handler.ContextFound);
         }

+        [Fact]
+        public void HttpServerDoesNotReplaceOriginalRequestContext()
+        {
+            // Arrange
+            HttpServer server = new HttpServer();
+            var handler = new ThrowIfNoContext();
+
+            server.Configuration.MessageHandlers.Add(handler);
+            server.Configuration.MapHttpAttributeRoutes();
+            server.Configuration.EnsureInitialized();
+
+            HttpMessageInvoker invoker = new HttpMessageInvoker(server);
+
+            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Customers");
+
+            HttpRequestContext context = new HttpRequestContext();
+
+            request.SetRequestContext(context);
+
+            // Act
+            var response = invoker.SendAsync(request, CancellationToken.None).Result;
+
+            // Assert
+            response.EnsureSuccessStatusCode();
+            Assert.True(handler.ContextFound);
+            Assert.Equal(context, response.RequestMessage.GetRequestContext());
+        }
+
         private class ThrowIfNoContext : DelegatingHandler
         {
             public bool ContextFound { get; set; }

             protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
             {
-                if (request.GetRequestContext() == null)
+                HttpRequestContext incomingContext = request.GetRequestContext();
+
+                if (incomingContext == null)
                 {
                     throw new InvalidOperationException("context missing");
                 }

                 ContextFound = true;

-                return base.SendAsync(request, cancellationToken);
+                Task<HttpResponseMessage> result = base.SendAsync(request, cancellationToken);
+
+                HttpRequestContext outgoingContext = result.Result.RequestMessage.GetRequestContext();
+
+                if (outgoingContext != incomingContext)
+                {
+                    throw new InvalidOperationException("context mismatch");
+                }
+
+                return result;
             }
         }


Fix NullReferenceException on missing lexemes

There was an assumption in the LfMerge code that an FDO entry would
always have a lexeme, but that is not actually true for all projects.

--- src/LfMerge/DataConverters/ConvertMongoToFdoLexicon.cs
+++ src/LfMerge/DataConverters/ConvertMongoToFdoLexicon.cs
@@ -449,15 +449,20 @@
 				}
 				return; // Don't set fields on a deleted entry
 			}
-			string entryNameForDebugging = String.Join(", ", lfEntry.Lexeme.Values.Select(x => x.Value ?? ""));
+			string entryNameForDebugging = "";
+			if (lfEntry.Lexeme != null && lfEntry.Lexeme.Values != null)
+				entryNameForDebugging = String.Join(", ", lfEntry.Lexeme.Values.Select(x => x.Value ?? ""));
 			Logger.Info("Processing entry {0} ({1}) from LF lexicon", guid, entryNameForDebugging);

 			// Fields in order by lfEntry property, except for Senses and CustomFields, which are handled at the end
 			SetMultiStringFrom(fdoEntry.CitationForm, lfEntry.CitationForm);
 			// Use AuthorInfo for dates as this should always reflect user changes (Mongo or FDO)
 			// Weirdly, FDO expects Dates to be in LOCAL time, not UTC.
-			fdoEntry.DateCreated = lfEntry.AuthorInfo.CreatedDate.ToLocalTime();
-			fdoEntry.DateModified = lfEntry.AuthorInfo.ModifiedDate.ToLocalTime();
+			if (lfEntry.AuthorInfo != null)
+			{
+				fdoEntry.DateCreated = lfEntry.AuthorInfo.CreatedDate.ToLocalTime();
+				fdoEntry.DateModified = lfEntry.AuthorInfo.ModifiedDate.ToLocalTime();
+			}
 			SetMultiStringFrom(fdoEntry.Bibliography, lfEntry.EntryBibliography);
 			SetMultiStringFrom(fdoEntry.Restrictions, lfEntry.EntryRestrictions);
 			SetEtymologyFields(fdoEntry, lfEntry);


Check for either null *or* empty fields when deleting

When deleting Pronunciation, Etymology or Lexeme objects, we should
check if the LF fields are either null *or* empty (e.g., contain nothing
but empty strings).

--- src/LfMerge/DataConverters/ConvertMongoToFdoLexicon.cs
+++ src/LfMerge/DataConverters/ConvertMongoToFdoLexicon.cs
@@ -721,10 +721,10 @@
 		public void SetEtymologyFields(ILexEntry fdoEntry, LfLexEntry lfEntry)
 		{
 			ILexEtymology fdoEtymology = fdoEntry.EtymologyOA;
-			if (lfEntry.Etymology == null &&
-				lfEntry.EtymologyComment == null &&
-				lfEntry.EtymologyGloss == null &&
-				lfEntry.EtymologySource == null)
+			if ((lfEntry.Etymology        == null || lfEntry.Etymology       .IsEmpty) &&
+			    (lfEntry.EtymologyComment == null || lfEntry.EtymologyComment.IsEmpty) &&
+			    (lfEntry.EtymologyGloss   == null || lfEntry.EtymologyGloss  .IsEmpty) &&
+			    (lfEntry.EtymologySource  == null || lfEntry.EtymologySource .IsEmpty))
 			{
 				if (fdoEtymology == null)
 					return; // Don't delete an Etymology object if there was none already
@@ -746,7 +746,7 @@
 		public void SetLexeme(ILexEntry fdoEntry, LfLexEntry lfEntry)
 		{
 			IMoForm fdoLexeme = fdoEntry.LexemeFormOA;
-			if (lfEntry.Lexeme == null)
+			if (lfEntry.Lexeme == null || lfEntry.Lexeme.IsEmpty)
 			{
 				if (fdoLexeme == null)
 					return;
@@ -765,10 +765,10 @@
 		{
 			// var fdoPronunciation = GetOrCreatePronunciationByGuid(lfEntry.PronunciationGuid, fdoEntry);
 			ILexPronunciation fdoPronunciation = fdoEntry.PronunciationsOS.FirstOrDefault();
-			if (lfEntry.Pronunciation == null &&
-				lfEntry.CvPattern == null &&
-				lfEntry.Tone == null &&
-				lfEntry.Location == null)
+			if ((lfEntry.Pronunciation == null || lfEntry.Pronunciation.IsEmpty) &&
+			    (lfEntry.CvPattern     == null || lfEntry.CvPattern    .IsEmpty) &&
+			    (lfEntry.Tone          == null || lfEntry.Tone         .IsEmpty) &&
+			    (lfEntry.Location      == null || lfEntry.Location     .IsEmpty))
 			{
 				// No pronunication at all in LF: either there was never one, or we deleted it
 				if (fdoPronunciation == null)


avoid possible race condition

avoid possible race condition

--- src/LogsearchShipper.Core/NxLog/NxLogProcessManager.cs
+++ src/LogsearchShipper.Core/NxLog/NxLogProcessManager.cs
@@ -105,11 +105,12 @@

 		public int Start()
 		{
+			_stopped = false;
+
 			ExtractNXLog();
 			SetupConfigFile();
 			StartNxLogProcess();

-			_stopped = false;
 			return NxLogProcess.Id;
 		}


removed dead code

removed dead code

--- src/Maestro.Core/Configuration/IContainerExpression.cs
+++ src/Maestro.Core/Configuration/IContainerExpression.cs
@@ -10,36 +10,6 @@
 		IPluginExpression For(Type type, string name);
 		IPluginExpression<T> For<T>(string name);

-		///// <summary>
-		///// Used to configure instance, lifetime, interception etc for default instance of type <paramref name="type"/>.
-		///// </summary>
-		///// <param name="type"></param>
-		///// <returns></returns>
-		//IInstanceExpression<object> For(Type type);
-
-		///// <summary>
-		///// Used to configure instance, lifetime, interception etc for for default instance of type <typeparamref name="TPlugin"/>.
-		///// </summary>
-		///// <typeparam name="TPlugin"></typeparam>
-		///// <returns></returns>
-		//IInstanceExpression<TPlugin> For<TPlugin>();
-
-		///// <summary>
-		///// Used to configure instance, lifetime, interception etc for type <paramref name="type"/> named <paramref name="name"/>.
-		///// </summary>
-		///// <param name="type"></param>
-		///// <param name="name"></param>
-		///// <returns></returns>
-		//INamedInstanceExpression<object> For(Type type, string name);
-
-		///// <summary>
-		///// Used to configure instance, lifetime, interception etc for type <typeparamref name="TPlugin"/> named <paramref name="name"/>.
-		///// </summary>
-		///// <typeparam name="TPlugin"></typeparam>
-		///// <param name="name"></param>
-		///// <returns></returns>
-		//INamedInstanceExpression<TPlugin> For<TPlugin>(string name);
-
 		/// <summary>
 		/// Used for conventional configuration.
 		/// </summary>


uid in overwrite doc is case sensitive (#1482)

--- src/Microsoft.DocAsCode.Build.Common/MarkdownReader.cs
+++ src/Microsoft.DocAsCode.Build.Common/MarkdownReader.cs
@@ -119,11 +119,11 @@

         private static bool CheckRequiredProperties(ImmutableDictionary<string, object> properties, IEnumerable<string> requiredKeys, out string message)
         {
-            var notExistsKeys = requiredKeys.Where(k => !properties.Keys.Contains(k, StringComparer.OrdinalIgnoreCase));
+            var notExistsKeys = requiredKeys.Where(k => !properties.Keys.Contains(k));
             if (notExistsKeys.Any())
             {
                 message =
-                    $"Required properties {{{{{string.Join(",", notExistsKeys)}}}}} are not set. Note that keys are case insensitive.";
+                    $"Required properties {{{{{string.Join(",", notExistsKeys)}}}}} are not set. Note that keys are case sensitive.";
                 return false;
             }


Fixing bug with InflateViewRenderer.

Fixing bug with InflateViewRenderer.

--- src/NativeCode.Mobile.AppCompat/InflateViewRenderer.cs
+++ src/NativeCode.Mobile.AppCompat/InflateViewRenderer.cs
@@ -5,7 +5,6 @@
     using System.Windows.Input;

     using Android.App;
-    using Android.Support.Design.Widget;
     using Android.Views;

     using NativeCode.Mobile.AppCompat.EventListeners;
@@ -120,15 +119,8 @@
         protected T InflateNativeControl<T>(int id, ViewGroup @group = null, bool attachToRoot = false) where T : Android.Views.View
         {
             var inflated = this.LayoutInflater.Inflate(id, @group, attachToRoot);
-            var view = inflated.FindViewById<FloatingActionButton>(inflated.Id);
-            var native = view as T;

-            if (native == null)
-            {
-                throw new InvalidCastException(string.Format("Could not cast the view {0} to a {1}.", view.GetType().Name, typeof(T).Name));
-            }
-
-            return native;
+            return inflated.FindViewById<T>(inflated.Id);
         }

         /// <summary>


Removing unnecessary rows limit

Removing unnecessary rows limit

--- src/Orchard/ContentManagement/DefaultContentManager.cs
+++ src/Orchard/ContentManagement/DefaultContentManager.cs
@@ -177,7 +177,7 @@

                         contentItemVersionCriteria.SetFetchMode("ContentItemRecord", FetchMode.Eager);
                         contentItemVersionCriteria.SetFetchMode("ContentItemRecord.ContentType", FetchMode.Eager);
-                        contentItemVersionCriteria.SetMaxResults(1);
+                        //contentItemVersionCriteria.SetMaxResults(1);
                     });


Fix test for IRCMessage not implementing IClientMessage

--- tests/NetIRC.Tests/IRCMessageTests.cs
+++ tests/NetIRC.Tests/IRCMessageTests.cs
@@ -208,7 +208,7 @@
         {
             var testMessage = new TestIRCMessage();

-            Assert.Equal(nameof(TestIRCMessage), testMessage.ToString());
+            Assert.Equal(typeof(TestIRCMessage).FullName, testMessage.ToString());
         }

         [Fact]
@@ -320,6 +320,5 @@

     public class TestIRCMessage : IRCMessage
     {
-        public override string ToString() => nameof(TestIRCMessage);
     }
 }


cleanup

cleanup

--- src/Peachpie.CodeAnalysis/CodeGen/VariableReference.cs
+++ src/Peachpie.CodeAnalysis/CodeGen/VariableReference.cs
@@ -347,8 +347,7 @@
                     // STACK: PhpAlias, PhpValue

                     // Template: <alias>.Value = STACK
-                    cg.Builder.EmitOpCode(ILOpCode.Stfld);
-                    cg.EmitSymbolToken(cg.CoreMethods.PhpAlias.Value.Symbol, null);
+                    cg.Emit_PhpAlias_SetValue();
                     return;
                 }


Make the snake visually grow.

Make the snake visually grow.

--- src/SnakeApp/Models/Snake.cs
+++ src/SnakeApp/Models/Snake.cs
@@ -11,10 +11,12 @@
 		private readonly List<Point> _snakePoints;
 		private Direction _direction;
 		private Point _lastSnakePointToErase;
+		private readonly List<GrowingPointIndicator> _growingPointIndicators;

 		public Snake(int initialSize, Point initialHeadPosition, Direction initialDirection = Direction.Right)
 		{
 			_snakePoints = new List<Point>();
+			_growingPointIndicators = new List<GrowingPointIndicator>();
 			_direction = initialDirection;
 			InitSnake(initialHeadPosition, initialSize, initialDirection);
 		}
@@ -26,23 +28,23 @@

 		public async Task Advance()
 		{
-			Point newHead = null;
+			Point whenToGrow = null;
 			switch (_direction)
 			{
 				case Direction.Left:
-					newHead = new Point { X = _snakePoints[0].X - 1, Y = _snakePoints[0].Y };
+					whenToGrow = new Point { X = _snakePoints[0].X - 1, Y = _snakePoints[0].Y };
 					break;

 				case Direction.Right:
-					newHead = new Point { X = _snakePoints[0].X + 1, Y = _snakePoints[0].Y };
+					whenToGrow = new Point { X = _snakePoints[0].X + 1, Y = _snakePoints[0].Y };
 					break;

 				case Direction.Up:
-					newHead = new Point { X = _snakePoints[0].X, Y = _snakePoints[0].Y - 1 };
+					whenToGrow = new Point { X = _snakePoints[0].X, Y = _snakePoints[0].Y - 1 };
 					break;

 				case Direction.Down:
-					newHead = new Point { X = _snakePoints[0].X, Y = _snakePoints[0].Y + 1 };
+					whenToGrow = new Point { X = _snakePoints[0].X, Y = _snakePoints[0].Y + 1 };
 					break;

 				default:
@@ -50,17 +52,61 @@
 			}

 			// add the new head
-			_snakePoints.Insert(0, newHead);
+			_snakePoints.Insert(0, whenToGrow);

 			// delete the last snake point
 			_lastSnakePointToErase = _snakePoints[_snakePoints.Count - 1];
 			_snakePoints.RemoveAt(_snakePoints.Count - 1);
+
+			// check if the snake has to grow
+			for(int i = 0; i < _growingPointIndicators.Count; i++)
+			{
+				var p = _growingPointIndicators[i];
+				if (Head == p.TailPositionWhenToGrow)
+				{
+					_snakePoints.Add(p.OriginalFoodPosition);
+					_growingPointIndicators.RemoveAt(i);
+					i--;
+				}
+			}
 		}

 		public void Consume(Food food)
 		{
 			// mark the food as eaten
 			food.IsConsumed = true;
+
+			// Save the next position the snake head will land in. That will indicate when snake's tail will grow
+			var growingPointIndicator = new GrowingPointIndicator();
+			growingPointIndicator.OriginalFoodPosition = new Point(food.Position);
+
+			// TODO: refactor this because it's repeating
+			Point whenToGrow = null;
+			switch (_direction)
+			{
+				case Direction.Left:
+					whenToGrow = new Point { X = _snakePoints[0].X - 1, Y = _snakePoints[0].Y };
+					break;
+
+				case Direction.Right:
+					whenToGrow = new Point { X = _snakePoints[0].X + 1, Y = _snakePoints[0].Y };
+					break;
+
+				case Direction.Up:
+					whenToGrow = new Point { X = _snakePoints[0].X, Y = _snakePoints[0].Y - 1 };
+					break;
+
+				case Direction.Down:
+					whenToGrow = new Point { X = _snakePoints[0].X, Y = _snakePoints[0].Y + 1 };
+					break;
+
+				default:
+					break;
+			}
+			growingPointIndicator.TailPositionWhenToGrow = whenToGrow;
+
+			// when the tail of the snake leaves the position of the food then the snake grows by adding one more point to its tail
+			_growingPointIndicators.Add(growingPointIndicator);
 		}

 		public async Task SetDirection(Direction requestedDirection)
@@ -108,5 +154,11 @@
 				}
 			}
 		}
+
+		private class GrowingPointIndicator
+		{
+			public Point OriginalFoodPosition { get; set; }
+			public Point TailPositionWhenToGrow { get;set;}
+		}
 	}
 }


This fixes the conditional breakpoint moving around issue by removing some breakpoint setting "optimization" code that unfortunately, messes up the order the breakpoint info returned to VSCode.

--- src/PowerShellEditorServices/Debugging/DebugService.cs
+++ src/PowerShellEditorServices/Debugging/DebugService.cs
@@ -83,34 +83,7 @@
                 string escapedScriptPath =
                     PowerShellContext.EscapePath(scriptFile.FilePath, escapeSpaces: false);

-                // Line breakpoints with no condition and no column number are the most common,
-                // so let's optimize for that case by making a single call to Set-PSBreakpoint
-                // with all the lines to set a breakpoint on.
-                int[] lineOnlyBreakpoints =
-                    breakpoints.Where(b => (b.ColumnNumber == null) && (b.Condition == null))
-                        .Select(b => b.LineNumber)
-                        .ToArray();
-
-                if (lineOnlyBreakpoints.Length > 0)
-                {
-                    PSCommand psCommand = new PSCommand();
-                    psCommand.AddCommand("Set-PSBreakpoint");
-                    psCommand.AddParameter("Script", escapedScriptPath);
-                    psCommand.AddParameter("Line", lineOnlyBreakpoints);
-
-                    var configuredBreakpoints =
-                        await this.powerShellContext.ExecuteCommand<Breakpoint>(psCommand);
-
-                    resultBreakpointDetails.AddRange(
-                        configuredBreakpoints.Select(BreakpointDetails.Create));
-                }
-
-                // Process the rest of the breakpoints
-                var advancedLineBreakpoints =
-                    breakpoints.Where(b => (b.ColumnNumber != null) || (b.Condition != null))
-                        .ToArray();
-
-                foreach (BreakpointDetails breakpoint in advancedLineBreakpoints)
+                foreach (BreakpointDetails breakpoint in breakpoints)
                 {
                     PSCommand psCommand = new PSCommand();
                     psCommand.AddCommand("Set-PSBreakpoint");
@@ -174,33 +147,7 @@

             if (breakpoints.Length > 0)
             {
-                // Line function breakpoints with no condition are the most common,
-                // so let's optimize for that case by making a single call to Set-PSBreakpoint
-                // with all the command names to set a breakpoint on.
-                string[] commandOnlyBreakpoints =
-                    breakpoints.Where(b => (b.Condition == null))
-                        .Select(b => b.Name)
-                        .ToArray();
-
-                if (commandOnlyBreakpoints.Length > 0)
-                {
-                    PSCommand psCommand = new PSCommand();
-                    psCommand.AddCommand(@"Microsoft.PowerShell.Utility\Set-PSBreakpoint");
-                    psCommand.AddParameter("Command", commandOnlyBreakpoints);
-
-                    var configuredBreakpoints =
-                        await this.powerShellContext.ExecuteCommand<Breakpoint>(psCommand);
-
-                    resultBreakpointDetails.AddRange(
-                        configuredBreakpoints.Select(FunctionBreakpointDetails.Create));
-                }
-
-                // Process the rest of the breakpoints
-                var advancedCommandBreakpoints =
-                    breakpoints.Where(b => (b.Condition != null))
-                        .ToArray();
-
-                foreach (FunctionBreakpointDetails breakpoint in advancedCommandBreakpoints)
+                foreach (FunctionBreakpointDetails breakpoint in breakpoints)
                 {
                     PSCommand psCommand = new PSCommand();
                     psCommand.AddCommand(@"Microsoft.PowerShell.Utility\Set-PSBreakpoint");


Fix tests for current institutions & new API

--- tests/Plaid.MSTest/Tests/PlaidClientTest.cs
+++ tests/Plaid.MSTest/Tests/PlaidClientTest.cs
@@ -72,7 +72,7 @@
             // Act
             var request = new Institution.SearchRequest()
             {
-                Query = "tartan"
+                Query = "citi",
             }.UseDefaults();

             var result = sut.FetchInstitutionsAsync(request).Result;
@@ -168,14 +168,13 @@

             // Act
             var result = sut.FetchUserIdentityAsync(request).Result;
-            bool publicKeyDontHaveAccess = result.Exception.ErrorCode == "INVALID_PRODUCT";
+            bool publicKeyDontHaveAccess = result.Exception?.ErrorCode == "INVALID_PRODUCT";
             if (publicKeyDontHaveAccess) Assert.Inconclusive(Helper.your_public_key_do_not_have_access_contact_plaid);

             // Assert
             result.IsSuccessStatusCode.ShouldBeTrue();
             result.RequestId.ShouldNotBeNullOrEmpty();
             result.Accounts.Length.ShouldBeGreaterThan(0);
-            result.Identity.Names.Length.ShouldBeGreaterThan(0);
             result.Item.ShouldNotBeNull();
         }

@@ -190,7 +189,7 @@

             // Act
             var result = sut.FetchUserIncomeAsync(request).Result;
-            bool publicKeyDontHaveAccess = result.Exception.ErrorCode == "INVALID_PRODUCT";
+            bool publicKeyDontHaveAccess = result.Exception?.ErrorCode == "INVALID_PRODUCT";
             if (publicKeyDontHaveAccess) Assert.Inconclusive(Helper.your_public_key_do_not_have_access_contact_plaid);

             // Assert
@@ -198,7 +197,6 @@
             result.RequestId.ShouldNotBeNullOrEmpty();
             result.Income.Streams.Length.ShouldBeGreaterThan(0);
             result.Income.LastYearIncome.ShouldBeGreaterThan(0);
-            result.Item.ShouldNotBeNull();
         }
     }
 }


Add new 4.0 PSM modes.

Add new 4.0 PSM modes.

--- src/Tesseract/PageSegMode.cs
+++ src/Tesseract/PageSegMode.cs
@@ -65,6 +65,21 @@
         SingleChar,

         /// <summary>
+        /// Find as much text as possible in no particular order.
+        /// </summary>
+	SparseText,
+
+        /// <summary>
+        /// Sparse text with orientation and script det.
+        /// </summary>
+	SparseTextOsd,
+
+        /// <summary>
+        /// Treat the image as a single text line, bypassing hacks that are Tesseract-specific.
+        /// </summary>
+	RawLine,
+
+        /// <summary>
         /// Number of enum entries.
         /// </summary>
         Count


Add the FindWindow and GetDesktopWindow functions. Add MarshalAs(UnmanagedType.Bool) to functions and parameters declared as such on MSDN.

--- src/User32.Desktop/User32.cs
+++ src/User32.Desktop/User32.cs
@@ -103,6 +103,7 @@
         public static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);

         [DllImport(nameof(User32), SetLastError = true)]
+        [return: MarshalAs(UnmanagedType.Bool)]
         public static extern bool SetWindowPos(
             IntPtr hWnd,
             IntPtr hWndInsertAfter,
@@ -113,13 +114,14 @@
             SetWindowPosFlags uFlags);

         [DllImport(nameof(User32), SetLastError = true)]
+        [return: MarshalAs(UnmanagedType.Bool)]
         public static extern bool MoveWindow(
             IntPtr hWnd,
             int X,
             int Y,
             int nWidth,
             int nHeight,
-            bool bRepaint);
+            [MarshalAs(UnmanagedType.Bool)] bool bRepaint);

         [DllImport(nameof(User32), SetLastError = true)]
         public static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
@@ -135,6 +137,16 @@
         /// </returns>
         [DllImport(nameof(User32), SetLastError = false)]
         public static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);
+
+        ///
+        /// Retrieves a handle to the top-level window whose class name and window name match the specified strings. This function does not search child windows. This function does not perform a case-sensitive search. To search child windows, beginning with a specified child window, use the FindWindowEx function.
+        ///
+        /// <param name="lpClassName">The window class name. If lpClassName is NULL, it finds any window whose title matches the lpWindowName parameter. </param>
+        /// <param name="lpWindowName">The window name (the window's title). If this parameter is NULL, all window names match.</param>
+        /// <returns>If the function succeeds, the return value is a handle to the window that has the specified
+        ///  class name and window name. If the function fails, the return value is NULL.</returns>
+        [DllImport(nameof(User32), SetLastError = true, CharSet = CharSet.Unicode)]
+        public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

         [DllImport(nameof(User32), SetLastError = true, CharSet = CharSet.Unicode)]
         public static extern IntPtr FindWindowEx(
@@ -144,7 +156,15 @@
             string windowTitle);

         [DllImport(nameof(User32))]
+        [return: MarshalAs(UnmanagedType.Bool)]
         public static extern bool ShowWindow(IntPtr hWnd, WindowShowStyle nCmdShow);
+
+        ///
+        /// Retrieves a handle to the desktop window. The desktop window covers the entire screen. The desktop window is the area on top of which other windows are painted.
+        ///
+        /// <returns>The return value is a handle to the desktop window.</returns>
+        [DllImport(nameof(User32))]
+        public static extern IntPtr GetDesktopWindow();

         [DllImport(nameof(User32))]
         public static extern IntPtr GetForegroundWindow();
@@ -201,6 +221,7 @@
         ///     <para>If the window was not brought to the foreground, the return value is false.</para>
         /// </returns>
         [DllImport(nameof(User32), SetLastError = true)]
+        [return: MarshalAs(UnmanagedType.Bool)]
         public static extern bool SetForegroundWindow(IntPtr hWnd);

         /// Retrieves the handle to the ancestor of the specified window.
@@ -343,6 +364,7 @@
         ///     <para>If the function fails, the return value is false. To get extended error information, call GetLastError.</para>
         /// </returns>
         [DllImport(nameof(User32), SetLastError = true)]
+        [return: MarshalAs(UnmanagedType.Bool)]
         public static extern bool ReleaseCapture();

         [DllImport(nameof(User32), SetLastError = true)]
@@ -356,6 +378,7 @@
         ///     caption was drawn as active before the call, the return value is nonzero. Otherwise, the return value is zero.
         /// </returns>
         [DllImport(nameof(User32), SetLastError = true)]
+        [return: MarshalAs(UnmanagedType.Bool)]
         public static extern bool FlashWindowEx(ref FLASHWINFO pwfi);

         ///
@@ -374,7 +397,7 @@
         ///     parameter is TRUE, the return value is NULL.
         /// </returns>
         [DllImport(nameof(User32), SetLastError = true)]
-        public static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);
+        public static extern IntPtr GetSystemMenu(IntPtr hWnd, [MarshalAs(UnmanagedType.Bool)] bool bRevert);

         ///
         ///     Appends a new item to the end of the specified menu bar, drop-down menu, submenu, or shortcut menu. You can
@@ -403,6 +426,7 @@
         ///     <para>If the function fails, the return value is false. To get extended error information, call GetLastError.</para>
         /// </returns>
         [DllImport(nameof(User32), SetLastError = true, CharSet = CharSet.Unicode)]
+        [return: MarshalAs(UnmanagedType.Bool)]
         public static extern bool AppendMenu(
             IntPtr hMenu,
             MenuItemFlags uFlags,
@@ -428,10 +452,11 @@
         ///     <para>If the function fails, the return value is false. To get extended error information, call GetLastError.</para>
         /// </returns>
         [DllImport(nameof(User32), SetLastError = true, CharSet = CharSet.Unicode)]
+        [return: MarshalAs(UnmanagedType.Bool)]
         public static extern bool SetMenuItemInfo(
             IntPtr hMenu,
             uint uItem,
-            bool fByPosition,
+            [MarshalAs(UnmanagedType.Bool)] bool fByPosition,
             [In] ref MENUITEMINFO lpmii);

         /// Retrieves information about a menu item.
@@ -454,10 +479,11 @@
         ///     <para>If the function fails, the return value is false. To get extended error information, call GetLastError.</para>
         /// </returns>
         [DllImport(nameof(User32), SetLastError = true, CharSet = CharSet.Unicode)]
+        [return: MarshalAs(UnmanagedType.Bool)]
         public static extern bool GetMenuItemInfo(
             IntPtr hMenu,
             uint uItem,
-            bool fByPosition,
+            [MarshalAs(UnmanagedType.Bool)] bool fByPosition,
             ref MENUITEMINFO lpmii);

         ///
@@ -619,6 +645,7 @@
         ///     <para>If the function fails, the return value is false. To get extended error information, call GetLastError.</para>
         /// </returns>
         [DllImport(nameof(User32), SetLastError = true)]
+        [return: MarshalAs(UnmanagedType.Bool)]
         private static extern bool UnhookWindowsHookEx(IntPtr hhk);
     }
 }


Чтение/запись в TCPSocket выполняется без закрытия networkstream

--- src/ScriptEngine.HostedScript/Library/Net/TCPClient.cs
+++ src/ScriptEngine.HostedScript/Library/Net/TCPClient.cs
@@ -24,47 +24,44 @@
         public string ReadString(string encoding = null)
         {
             var enc = GetEncodingByName(encoding);
-            using (var stream = _client.GetStream())
+            var stream = _client.GetStream();
+
+            byte[] readBuffer = new byte[1024];
+            StringBuilder completeMessage = new StringBuilder();
+
+            do
             {
-                byte[] readBuffer = new byte[1024];
-                StringBuilder completeMessage = new StringBuilder();
+                int numberOfBytesRead = stream.Read(readBuffer, 0, readBuffer.Length);
+                completeMessage.Append(enc.GetString(readBuffer, 0, numberOfBytesRead));
+            } while (stream.DataAvailable);

-                do
-                {
-                    int numberOfBytesRead = stream.Read(readBuffer, 0, readBuffer.Length);
-                    completeMessage.Append(enc.GetString(readBuffer, 0, numberOfBytesRead));
-                } while (stream.DataAvailable);
+            return completeMessage.ToString();

-                return completeMessage.ToString();
-
-            }
         }

         [ContextMethod("ПрочитатьДвоичныеДанные", "ReadBinaryData")]
         public BinaryDataContext ReadBinaryData(int len = 0)
         {
-            using (var stream = _client.GetStream())
+            var stream = _client.GetStream();
+
+            bool useLimit = len > 0;
+
+            MemoryStream ms = new MemoryStream();
+            byte[] readBuffer = new byte[1024];
+            do
             {
-                bool useLimit = len > 0;
-
-                MemoryStream ms = new MemoryStream();
-                byte[] readBuffer = new byte[1024];
-                do
-                {
-                    int portion = useLimit ? Math.Min(len, readBuffer.Length) : readBuffer.Length;
+                int portion = useLimit ? Math.Min(len, readBuffer.Length) : readBuffer.Length;

-                    int numberOfBytesRead = stream.Read(readBuffer, 0, portion);
-                    ms.Write(readBuffer, 0, numberOfBytesRead);
-                    if(useLimit)
-                        len -= numberOfBytesRead;
+                int numberOfBytesRead = stream.Read(readBuffer, 0, portion);
+                ms.Write(readBuffer, 0, numberOfBytesRead);
+                if(useLimit)
+                    len -= numberOfBytesRead;

-                } while (stream.DataAvailable);
+            } while (stream.DataAvailable);

-                var data = ms.ToArray();
+            var data = ms.ToArray();

-                return new BinaryDataContext(data);
-
-            }
+            return new BinaryDataContext(data);
         }

         [ContextMethod("ОтправитьСтроку","SendString")]
@@ -75,10 +72,10 @@

             var enc = GetEncodingByName(encoding);
             byte[] bytes = enc.GetBytes(data);
-            using (var stream = _client.GetStream())
-            {
-                stream.Write(bytes, 0, bytes.Length);
-            }
+            var stream = _client.GetStream();
+
+            stream.Write(bytes, 0, bytes.Length);
+            stream.Flush();
         }

         [ContextMethod("ОтправитьДвоичныеДанные", "SendBinaryData")]
@@ -87,10 +84,16 @@
             if (data.Buffer.Length == 0)
                 return;

-            using (var stream = _client.GetStream())
-            {
-                stream.Write(data.Buffer, 0, data.Buffer.Length);
-            }
+            var stream = _client.GetStream();
+            stream.Write(data.Buffer, 0, data.Buffer.Length);
+            stream.Flush();
+
+        }
+
+        [ContextProperty("Активно","IsActive")]
+        public bool IsActive
+        {
+            get { return _client.Connected; }
         }

         private static Encoding GetEncodingByName(string encoding)


Removed restriction on 7zip file entries

--- src/SharpCompress/Archives/SevenZip/SevenZipArchive.cs
+++ src/SharpCompress/Archives/SevenZip/SevenZipArchive.cs
@@ -106,10 +106,7 @@
             for (int i = 0; i < database.Files.Count; i++)
             {
                 var file = database.Files[i];
-                if (!file.IsDir)
-                {
-                    yield return new SevenZipArchiveEntry(this, new SevenZipFilePart(stream, database, i, file));
-                }
+                yield return new SevenZipArchiveEntry(this, new SevenZipFilePart(stream, database, i, file));
             }
         }

@@ -209,4 +206,4 @@
             }
         }
     }
-}+}


Temporary fix for #101

Temporary fix for #101

This adds a fallback to setting IPAddress, but we'll need a settings refactor like MiniProfiler to pass HttpContext or HttpRequest to the GetIPAddress setting (which is really what's needed here).

--- src/StackExchange.Exceptional.AspNetCore/Extensions.cs
+++ src/StackExchange.Exceptional.AspNetCore/Extensions.cs
@@ -160,6 +160,11 @@
                 }
             }

+            if (error.IPAddress.IsNullOrEmpty())
+            {
+                error.IPAddress = context.Connection.RemoteIpAddress.ToString();
+            }
+
             error.Url = $"{request.Scheme}://{request.Host}{request.PathBase}{request.Path}{request.QueryString}";
             error.ServerVariables = new NameValueCollection
             {


Default reg method hostname

Default reg method hostname

--- src/Steeltoe.Discovery.Client/EurekaInstanceOptions.cs
+++ src/Steeltoe.Discovery.Client/EurekaInstanceOptions.cs
@@ -32,7 +32,7 @@
         public const string Default_StatusPageUrlPath = "/info";
         public const string Default_HomePageUrlPath = "/";
         public const string Default_HealthCheckUrlPath = "/health";
-        public const string Default_RegistrationMethod = "route";
+        public const string Default_RegistrationMethod = "hostname";

         public EurekaInstanceOptions()
         {


Add support for person_token on Person creation

--- src/Stripe.net/Services/Persons/PersonSharedOptions.cs
+++ src/Stripe.net/Services/Persons/PersonSharedOptions.cs
@@ -52,6 +52,9 @@
         [JsonProperty("metadata")]
         public Dictionary<string, string> Metadata { get; set; }

+        [JsonProperty("person_token")]
+        public string PersonToken { get; set; }
+
         [JsonProperty("personal_id_number")]
         public string PersonalIdNumber { get; set; }


Fix FileSystemProviderManagerTests

Fix FileSystemProviderManagerTests

--- src/Umbraco.Tests/IO/FileSystemProviderManagerTests.cs
+++ src/Umbraco.Tests/IO/FileSystemProviderManagerTests.cs
@@ -1,10 +1,10 @@
 using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using System.Text;
+using Moq;
 using NUnit.Framework;
+using Umbraco.Core;
 using Umbraco.Core.IO;
+using Umbraco.Core.Logging;
+using Umbraco.Core.Profiling;
 using Umbraco.Tests.TestHelpers;

 namespace Umbraco.Tests.IO
@@ -18,6 +18,9 @@
             //init the config singleton
             var config = SettingsForTests.GetDefault();
             SettingsForTests.ConfigureSettings(config);
+
+            // media fs wants this
+            ApplicationContext.Current = new ApplicationContext(CacheHelper.CreateDisabledCacheHelper(), new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>()));
         }

         [Test]
@@ -42,7 +45,6 @@
 			Assert.Throws<InvalidOperationException>(() => FileSystemProviderManager.Current.GetFileSystemProvider<InvalidTypedFileSystem>());
 		}

-
 	    /// <summary>
 	    /// Used in unit tests, for a typed file system we need to inherit from FileSystemWrapper and they MUST have a ctor
 	    /// that only accepts a base IFileSystem object


Add regression test

Add regression test

--- tests/src/Simple/Generics/Generics.cs
+++ tests/src/Simple/Generics/Generics.cs
@@ -13,6 +13,7 @@
         TestInitThisClass.Run();
         TestDelegateFatFunctionPointers.Run();
         TestVirtualMethodUseTracking.Run();
+        TestNameManglingCollisionRegression.Run();

         return 100;
     }
@@ -224,5 +225,23 @@
                 throw new Exception();
         }
     }
+
+    //
+    // Regression test for issue https://github.com/dotnet/corert/issues/1964
+    //
+    class TestNameManglingCollisionRegression
+    {
+        class Gen1<T>
+        {
+            public Gen1(T t) {}
+        }
+
+        public static void Run()
+        {
+            Gen1<object[]>[] g1 = new Gen1<object[]>[1];
+            g1[0] = new Gen1<object[]>(new object[] {new object[1]});
+
+            Gen1<object[][]> g2 = new Gen1<object[][]>(new object[1][]);
+        }
+    }
 }
-


[Modify] Polish it

[Modify] Polish it

--- websocket-sharp/Server/WebSocketServiceManager.cs
+++ websocket-sharp/Server/WebSocketServiceManager.cs
@@ -515,10 +515,11 @@
         throw new ArgumentException ("An empty string.", "path");

       if (path[0] != '/')
-        throw new ArgumentException ("Not an absolute path.", "path");
+        throw new ArgumentException ("It is not an absolute path.", "path");

       if (path.IndexOfAny (new[] { '?', '#' }) > -1) {
         var msg = "It includes either or both query and fragment components.";
+
         throw new ArgumentException (msg, "path");
       }

@@ -526,8 +527,9 @@

       lock (_sync) {
         WebSocketServiceHost host;
+
         if (_hosts.TryGetValue (path, out host))
-          throw new ArgumentException ("Already in use.", "path");
+          throw new ArgumentException ("It is already in use.", "path");

         host = new WebSocketServiceHost<TBehavior> (
                  path, () => new TBehavior (), initializer, _log


unused variable

unused variable

git-svn-id: 648254992e62896316d6a1d4b75c778d65bd21a1@409 458802cb-8328-0410-b1d9-a76001e3bb52

--- xmlunit/src/main/net-core/validation/Validator.cs
+++ xmlunit/src/main/net-core/validation/Validator.cs
@@ -80,8 +80,7 @@
                 List<ValidationProblem> problems =
                     new List<ValidationProblem>();
                 foreach (ISource loc in sourceLocations) {
-                    XmlSchema s = XmlSchema.Read(loc.Reader,
-                                                 CollectProblems(problems));
+                    XmlSchema.Read(loc.Reader, CollectProblems(problems));
                 }
                 return new ValidationResult(problems.Count == 0, problems);
             }


[FIXED #55] css after uncheck

[FIXED #55] css after uncheck

--- yaf_dnn/Components/WebAPI/MultiQuoteController.cs
+++ yaf_dnn/Components/WebAPI/MultiQuoteController.cs
@@ -96,7 +96,7 @@
                     yafSession.MultiQuoteIds.Remove(multiQuote);
                 }

-                buttonCssClass = "MultiQuoteButton";
+                buttonCssClass = "MultiQuoteButton custom-control custom-checkbox btn btn-link";
             }

             return this.Ok(new ReturnClass { Id = buttonId, NewTitle = buttonCssClass });


Added simple array support to ComputeBufferUtil

--- ActorKit/Scripts/Tools.Common/ComputeBufferUtil.cs
+++ ActorKit/Scripts/Tools.Common/ComputeBufferUtil.cs
@@ -16,6 +16,16 @@
 namespace Tools.Common {

     public static class ComputeBufferUtil {
+
+        public static ComputeBuffer CreateBufferForSimpleArray<Tval>(Tval[] values) {
+            int stride, count;
+            stride = SizeInBytes<Tval>();
+            count = values.Length;
+            var computeBuffer = new ComputeBuffer(count, stride);
+            computeBuffer.SetData(values);
+            return computeBuffer;
+        }
+
         public static ComputeBuffer CreateBufferForListOfArrays<Tval>(List<Tval[]> values) {
             int stride, count;


Added error check for invalid arrays as this kind of problem can be hard to track down

--- ActorKit/Scripts/Tools.Common/ComputeBufferUtil.cs
+++ ActorKit/Scripts/Tools.Common/ComputeBufferUtil.cs
@@ -19,6 +19,8 @@

         public static ComputeBuffer CreateBufferForSimpleArray<Tval>(Tval[] values) {
             int stride, count;
+
+            ExceptionIfInvalidArray(values);
             stride = SizeInBytes<Tval>();
             count = values.Length;
             var computeBuffer = new ComputeBuffer(count, stride);
@@ -54,6 +56,7 @@
                 stride = 0;
                 return false;
             } else {
+                values.ForEach(valArray => ExceptionIfInvalidArray(valArray));
                 int totalSize = TotalValuesInArrayList(values);
                 stride = totalSize * SizeInBytes<Tval>() / values.Count();
                 count = values.Count();
@@ -63,6 +66,17 @@

         public static int SizeInBytes<T>() {
             return Marshal.SizeOf(typeof(T));
+        }
+
+        private static void ExceptionIfInvalidArray<T>(T[] values) {
+            if (values == null) {
+                throw new ArgumentException(string.Format("Invalid Argument: NULL of type '{0}' Arrary given for ComputeBuffer", TypeUtil.NameOf<T>()));
+            }
+            if (values.Length == 0) {
+                throw new ArgumentException(
+                    string.Format("Invalid Argument: Type '{0}' Array of 0 length given for ComputeBuffer", TypeUtil.NameOf<T>())
+                );
+            }
         }

         private static Tval[] FlattenedArray<Tval>(List<Tval[]> values) {


Removed old example

Removed old example

--- ApiExamples/CSharp/ApiExamples/ExMailMergeEvent.cs
+++ ApiExamples/CSharp/ApiExamples/ExMailMergeEvent.cs
@@ -272,65 +272,5 @@
             Assert.IsNotNull(logoImage);
             Assert.IsTrue(logoImage.HasImage);
         }
-
-#if !(NETSTANDARD2_0 || __MOBILE__)
-        [Test]
-        [Ignore("Test need to be reworked")]
-        public void MailMergeImageFromBlob()
-        {
-            //ExStart
-            //ExFor:MailMerge.FieldMergingCallback
-            //ExFor:MailMerge.ExecuteWithRegions(IDataReader,String)
-            //ExFor:IFieldMergingCallback
-            //ExFor:ImageFieldMergingArgs
-            //ExFor:IFieldMergingCallback.FieldMerging
-            //ExFor:IFieldMergingCallback.ImageFieldMerging
-            //ExFor:ImageFieldMergingArgs.ImageStream
-            //ExId:MailMergeImageFromBlob
-            //ExSummary:Shows how to insert images stored in a database BLOB field into a report.
-            Document doc = new Document(MyDir + "MailMerge.MergeImage.doc");
-
-            // Set up the event handler for image fields.
-            doc.MailMerge.FieldMergingCallback = new HandleMergeImageFieldFromBlob();
-
-            // Open a database connection.
-            string connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + DatabaseDir + "Northwind.mdb";
-            OleDbConnection conn = new OleDbConnection(connString);
-            conn.Open();
-
-            // Open the data reader. It needs to be in the normal mode that reads all record at once.
-            OleDbCommand cmd = new OleDbCommand("SELECT * FROM Employees", conn);
-            IDataReader dataReader = cmd.ExecuteReader();
-
-            // Perform mail merge.
-            doc.MailMerge.ExecuteWithRegions(dataReader, "Employees");
-
-            // Close the database.
-            conn.Close();
-
-            doc.Save(ArtifactsDir + "MailMerge.MergeImage.doc");
-        }
-
-        private class HandleMergeImageFieldFromBlob : IFieldMergingCallback
-        {
-            void IFieldMergingCallback.FieldMerging(FieldMergingArgs args)
-            {
-                // Do nothing.
-            }
-
-            /// <summary>
-            /// This is called when mail merge engine encounters Image:XXX merge field in the document.
-            /// You have a chance to return an Image object, file name or a stream that contains the image.
-            /// </summary>
-            void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs e)
-            {
-                // The field value is a byte array, just cast it and create a stream on it.
-                MemoryStream imageStream = new MemoryStream((byte[])e.FieldValue);
-                // Now the mail merge engine will retrieve the image from the stream.
-                e.ImageStream = imageStream;
-            }
-        }
-        //ExEnd
-#endif
     }
 }


Sync w/Shared world anchor branch

Sync w/Shared world anchor branch

--- Assets/HoloToolkit/Sharing/Scripts/SharingStage.cs
+++ Assets/HoloToolkit/Sharing/Scripts/SharingStage.cs
@@ -26,13 +26,13 @@
         /// <summary>
         /// Default username to use when joining a session.
         /// </summary>
-        /// <remarks>User code should set the user name by setting the UserName property.</remarks>
+        /// <remarks>Set the user name by setting <see cref="UserName"/> property.</remarks>
         private const string DefaultUserName = "User ";

         /// <summary>
         /// Set whether this app should be a Primary or Secondary client.
-        /// Primary: Connects directly to the Session Server, can create/join/leave sessions
-        /// Secondary: Connects to a Primary client.  Cannot do any session management
+        /// <para> Primary: Connects directly to the Session Server, can create/join/leave sessions.</para>
+        /// <para> Secondary: Connects to a Primary client.  Cannot do any session management.</para>
         /// </summary>
         public ClientRole ClientRole = ClientRole.Primary;

@@ -68,7 +68,7 @@
         public bool IsAudioEndpoint = true;

         /// <summary>
-        /// Pipes XTools console output to Unity's output window for debugging
+        /// Pipes sharing server console output to Unity's output window for debugging
         /// </summary>
         private ConsoleLogWriter logWriter;

@@ -80,6 +80,8 @@
         /// <summary>
         /// Server sessions tracker.
         /// </summary>
+        /// <remarks>Note that if this processes takes the role of a secondary client,
+        ///  then the sessionsTracker will always be null.</remarks>
         public ServerSessionsTracker SessionsTracker { get; private set; }

         /// <summary>
@@ -104,7 +106,7 @@
         public event Action<string> UserNameChanged;

         /// <summary>
-        /// Enables Server Discovery on the network
+        /// Enables Server Discovery on the network.
         /// </summary>
         private DiscoveryClient discoveryClient;

@@ -123,7 +125,10 @@
         /// </summary>
         private bool isTryingToFindServer;

-        [Tooltip("Show Detailed Information for server connections")]
+        /// <summary>
+        /// Show Detailed Information for sharing services.
+        /// </summary>
+        [Tooltip("Show Detailed Information for sharing services.")]
         public bool ShowDetailedLogs;

         public string UserName
@@ -179,7 +184,7 @@
             }
             else
             {
-                ManagerInit();
+                ManagerInit(connectOnAwake);
             }
         }

@@ -263,7 +268,7 @@

         #endregion // Unity Methods

-        #region Callbacks
+        #region Event Callbacks

         private void OnNetworkConnectionChanged(NetworkConnection networkConnection)
         {
@@ -288,6 +293,7 @@
             if (system.GetRole() != SystemRole.SessionDiscoveryServerRole) { return; }

             // Found a server. Stop pinging the network and connect.
+            discoveryClientAdapter.DiscoveredEvent -= OnSystemDiscovered;
             isTryingToFindServer = false;
             ServerAddress = system.GetAddress();

@@ -296,7 +302,7 @@
                 Debug.Log("Server discovered at: " + ServerAddress);
             }

-            ManagerInit();
+            ManagerInit(true);

             if (ShowDetailedLogs)
             {
@@ -329,16 +335,15 @@
             }
         }

-        #endregion // Callbacks
-
-        private void ManagerInit()
+        #endregion // Event Callbacks
+
+        private void ManagerInit(bool setConnection)
         {
             var config = new ClientConfig(ClientRole);
             config.SetIsAudioEndpoint(IsAudioEndpoint);
             config.SetLogWriter(logWriter);

-            // Only set the server info is we are connecting on awake
-            if (connectOnAwake)
+            if (setConnection)
             {
                 config.SetServerAddress(ServerAddress);
                 config.SetServerPort(ServerPort);
@@ -384,6 +389,7 @@
             {
                 Debug.Log("Looking for servers...");
             }
+
             discoveryClientAdapter = new DiscoveryClientAdapter();
             discoveryClientAdapter.DiscoveredEvent += OnSystemDiscovered;


Fixed improper OnDestroy implementation

Fixed improper OnDestroy implementation

--- Assets/HoloToolkit/Utilities/Scripts/FadeScript.cs
+++ Assets/HoloToolkit/Utilities/Scripts/FadeScript.cs
@@ -83,7 +83,7 @@
             }
         }

-        new void OnDestroy()
+        protected override void OnDestroy()
         {
             if (fadeMaterial != null)
             {


fix triangles error from point/line-topology meshes

--- Assets/Scripts/Editor/Tools/GetSelectedMeshInfo.cs
+++ Assets/Scripts/Editor/Tools/GetSelectedMeshInfo.cs
@@ -59,7 +59,8 @@
                     {
                         int verts = meshes[i].sharedMesh.vertexCount;
                         totalVertices += verts;
-                        totalTris += meshes[i].sharedMesh.triangles.Length / 3;
+                        // not for point/line meshes
+                        if (meshes[i].sharedMesh.GetTopology(0) == MeshTopology.Triangles) totalTris += meshes[i].sharedMesh.triangles.Length / 3;
                         totalMeshes++;
                         topList.Add(i, verts);
                     }


methode add/rm listener sur UserActionManager

--- Assets/Scripts/UI/UserActions/UserActionManager.cs
+++ Assets/Scripts/UI/UserActions/UserActionManager.cs
@@ -66,6 +66,14 @@
         else
             unlockUserActions();
     }
+    public void addUserActionListener(UserActionListener listener)
+    {
+        listeners.Add(listener);
+    }
+    public void removeUserActionListener(UserActionListener listener)
+    {
+        listeners.Remove(listener);
+    }
 }

 public interface UserActionListener


add colors for unity basic skin

add colors for unity basic skin

--- Assets/pb_Profiler/Editor/pb_Profiler_Interface.cs
+++ Assets/pb_Profiler/Editor/pb_Profiler_Interface.cs
@@ -52,6 +52,13 @@
 		resolution = (Resolution) EditorPrefs.GetInt("pb_Profiler.resolution", 2);
 		EditorApplication.update -= Update;
 		EditorApplication.update += Update;
+
+		if(!EditorGUIUtility.isProSkin)
+		{
+			highlight = new Color(.3f, .3f, .3f, 1f);
+			column_colors[0] = new Color(0.7607f, 0.7607f, 0.7607f, 1f);
+			column_colors[1] = new Color(0.73f, 0.73f, 0.73f, 1f);
+		}
 	}

 	const int UDPATE_FREQ = 1;	// 1 per frame
@@ -89,6 +96,9 @@
 			entryStyle.normal.background = EditorGUIUtility.whiteTexture;
 			chartStyle.onNormal.background = null;
 			entryStyle.onNormal.background = EditorGUIUtility.whiteTexture;
+
+			if(!EditorGUIUtility.isProSkin)
+				entryStyle.normal.textColor = Color.black;
 		}

 		string[] display = new string[profiles.Count];


Fix potential cross-thread access in host-firing events.

--- osu.Framework/Platform/BasicGameHost.cs
+++ osu.Framework/Platform/BasicGameHost.cs
@@ -104,17 +104,36 @@

         protected virtual void OnActivated(object sender, EventArgs args)
         {
-            Activated?.Invoke(this, EventArgs.Empty);
+            UpdateScheduler.Add(delegate
+            {
+                Activated?.Invoke(this, EventArgs.Empty);
+            });
         }

         protected virtual void OnDeactivated(object sender, EventArgs args)
         {
-            Deactivated?.Invoke(this, EventArgs.Empty);
+            UpdateScheduler.Add(delegate
+            {
+                Deactivated?.Invoke(this, EventArgs.Empty);
+            });
         }

         protected virtual bool OnExitRequested()
         {
-            if (Exiting?.Invoke() == true)
+            if (ExitRequested) return false;
+
+            bool? response = null;
+
+            UpdateScheduler.Add(delegate
+            {
+                response = Exiting?.Invoke() == true;
+            });
+
+            //wait for a potentially blocking response
+            while (!response.HasValue)
+                Thread.Sleep(1);
+
+            if (response.Value)
                 return true;

             ExitRequested = true;


Fix crash when selecting mods after entering play mode

Closes #3260.

--- osu.Game/Screens/Play/HUD/ModDisplay.cs
+++ osu.Game/Screens/Play/HUD/ModDisplay.cs
@@ -63,6 +63,12 @@
             };
         }

+        protected override void Dispose(bool isDisposing)
+        {
+            base.Dispose(isDisposing);
+            mods.UnbindAll();
+        }
+
         protected override void LoadComplete()
         {
             base.LoadComplete();


Adjust design and feel

Adjust design and feel

--- osu.Game/Screens/Play/HUD/QuitButton.cs
+++ osu.Game/Screens/Play/HUD/QuitButton.cs
@@ -8,6 +8,7 @@
 using osu.Framework.Graphics.Shapes;
 using osu.Framework.Graphics.UserInterface;
 using osu.Framework.Input;
+using osu.Framework.MathUtils;
 using osu.Game.Graphics;
 using osu.Game.Graphics.Sprites;
 using OpenTK;
@@ -26,7 +27,7 @@
             set => button.ExitAction = value;
         }

-        OsuSpriteText text;
+        private readonly OsuSpriteText text;

         public QuitButton()
         {
@@ -65,15 +66,32 @@
             base.OnHoverLost(state);
         }

+        protected override void Update()
+        {
+            base.Update();
+
+            float adjust = Vector2.Distance(GetContainingInputManager().CurrentState.Mouse.NativeState.Position, button.ScreenSpaceDrawQuad.Centre) / 200;
+            double elapsed = MathHelper.Clamp(Clock.ElapsedFrameTime, 0, 1000);
+
+            bool stayVisible = text.Alpha > 0 || button.Progress > 0 || IsHovered;
+
+            Alpha = stayVisible ? 1 : Interpolation.ValueAt(elapsed, Alpha, MathHelper.Clamp(1 - adjust, 0.04f, 1), 0, 200, Easing.OutQuint);
+        }
+
         private class Button : CircularContainer
         {
             private SpriteIcon icon;
             private CircularProgress progress;
+            private Circle innerCircle;
+
+            private bool triggered;

             public Action ExitAction { get; set; }

+            public double Progress => progress.Current.Value;
+
             private const int fade_duration = 200;
-            private const int progress_duration = 1000;
+            private const int progress_duration = 600;

             [BackgroundDependencyLoader]
             private void load(OsuColour colours)
@@ -86,31 +104,55 @@
                     {
                         RelativeSizeAxes = Axes.Both,
                         Colour = colours.Gray1,
-                        Alpha = 0.8f,
+                        Alpha = 0.5f,
+                    },
+                    progress = new CircularProgress
+                    {
+                        RelativeSizeAxes = Axes.Both,
+                        InnerRadius = 1
+                    },
+                    innerCircle = new Circle
+                    {
+                        Anchor = Anchor.Centre,
+                        Origin = Anchor.Centre,
+                        RelativeSizeAxes = Axes.Both,
+                        Colour = colours.Gray1,
+                        Size = new Vector2(0.9f),
                     },
                     icon = new SpriteIcon
                     {
+                        Shadow = false,
                         Anchor = Anchor.Centre,
                         Origin = Anchor.Centre,
                         Size = new Vector2(15),
                         Icon = FontAwesome.fa_close
                     },
-                    progress = new CircularProgress { RelativeSizeAxes = Axes.Both, InnerRadius = 0.1f }
                 });
             }

             protected override bool OnMouseDown(InputState state, MouseDownEventArgs args)
             {
-                icon.ScaleTo(1.5f);
-                progress.FillTo(1, progress_duration).OnComplete(cp => ExitAction());
+                if (state.Mouse.Buttons.Count > 1 || triggered)
+                    return true;
+
+                icon.ScaleTo(1.4f, progress_duration);
+                progress.FillTo(1, progress_duration, Easing.OutSine).OnComplete(_ =>
+                {
+                    innerCircle.ScaleTo(0, 100).Then().FadeOut().ScaleTo(1).FadeIn(500);
+                    triggered = true;
+                    ExitAction();
+                });

                 return base.OnMouseDown(state, args);
             }

             protected override bool OnMouseUp(InputState state, MouseUpEventArgs args)
             {
-                icon.ScaleTo(1f);
-                progress.FillTo(0, progress_duration / 4f).OnComplete(cp => progress.Current.SetDefault());
+                if (state.Mouse.Buttons.Count > 0 || triggered)
+                    return true;
+
+                icon.ScaleTo(1, 800, Easing.OutElastic);
+                progress.FillTo(0, progress_duration, Easing.OutQuint).OnComplete(cp => progress.Current.SetDefault());

                 return base.OnMouseUp(state, args);
             }


Don't obtain DependencyContainer via DI

Don't obtain DependencyContainer via DI

--- osu.Game/Screens/Tournament/Drawings.cs
+++ osu.Game/Screens/Tournament/Drawings.cs
@@ -53,7 +53,7 @@
             dependencies = new DependencyContainer(base.CreateLocalDependencies(parent));

         [BackgroundDependencyLoader]
-        private void load(TextureStore textures, Storage storage, DependencyContainer dependencies)
+        private void load(TextureStore textures, Storage storage)
         {
             this.storage = storage;


Remove unused skin resolution in `LegacyScoreCounter`

--- osu.Game/Skinning/LegacyScoreCounter.cs
+++ osu.Game/Skinning/LegacyScoreCounter.cs
@@ -1,7 +1,6 @@
 // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
 // See the LICENCE file in the repository root for full licence text.

-using osu.Framework.Allocation;
 using osu.Framework.Graphics;
 using osu.Game.Graphics.Sprites;
 using osu.Game.Screens.Play.HUD;
@@ -13,9 +12,6 @@
     {
         protected override double RollingDuration => 1000;
         protected override Easing RollingEasing => Easing.Out;
-
-        [Resolved]
-        private ISkinSource skin { get; set; }

         public LegacyScoreCounter()
             : base(6)