Improve logging in the TransactionStreamMiddleware class

--- src/Openchain.Server/Models/TransactionStreamMiddleware.cs
+++ src/Openchain.Server/Models/TransactionStreamMiddleware.cs
@@ -12,12 +12,13 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.

-using Microsoft.AspNet.Builder;
-using Microsoft.AspNet.Http;
 using System;
 using System.Net.WebSockets;
 using System.Threading;
 using System.Threading.Tasks;
+using Microsoft.AspNet.Builder;
+using Microsoft.AspNet.Http;
+using Microsoft.Framework.Logging;

 namespace Openchain.Server.Models
 {
@@ -41,6 +42,7 @@
                 else
                     lastLedgerRecordHash = ByteString.Parse(from);

+                ILogger logger = (ILogger)context.ApplicationServices.GetService(typeof(ILogger));
                 ITransactionStore store = (ITransactionStore)context.ApplicationServices.GetService(typeof(ITransactionStore));

                 IObservable<ByteString> stream = store.GetTransactionStream(lastLedgerRecordHash);
@@ -49,7 +51,7 @@
                 {
                     ArraySegment<byte> receiveBuffer = new ArraySegment<byte>(new byte[512]);

-                    using (Observer observer = new Observer(webSocket, context.RequestAborted))
+                    using (Observer observer = new Observer(webSocket, logger, context.RequestAborted))
                     {
                         using (stream.Subscribe(observer))
                         {
@@ -69,15 +71,17 @@
         private class Observer : IObserver<ByteString>, IDisposable
         {
             private readonly WebSocket webSocket;
+            private readonly ILogger logger;
             private Task currentTask = Task.FromResult(0);
             private readonly object currentTaskLock = new object();
             private readonly TaskCompletionSource<int> completed = new TaskCompletionSource<int>();
             private readonly CancellationToken cancel;
             private readonly CancellationTokenRegistration registration;

-            public Observer(WebSocket webSocket, CancellationToken cancel)
+            public Observer(WebSocket webSocket, ILogger logger, CancellationToken cancel)
             {
                 this.webSocket = webSocket;
+                this.logger = logger;
                 this.cancel = cancel;
                 this.registration = cancel.Register(() => completed.TrySetResult(0));
             }
@@ -99,6 +103,8 @@

             public void OnError(Exception error)
             {
+                this.logger.LogError($"An error occured in the transaction stream server: {error.ToString()}");
+
                 QueueTask(async () =>
                 {
                     await webSocket.CloseAsync(


Wait before aborting connections to defunct silos (#5810)

--- src/Orleans.Runtime/Networking/SiloConnectionMaintainer.cs
+++ src/Orleans.Runtime/Networking/SiloConnectionMaintainer.cs
@@ -1,4 +1,5 @@
-using System.Threading;
+using System;
+using System.Threading;
 using System.Threading.Tasks;
 using Microsoft.Extensions.Logging;

@@ -41,8 +42,23 @@
         {
             if (status == SiloStatus.Dead)
             {
-                this.log.LogInformation("Aborting connections to defunct silo {SiloAddress}", updatedSilo);
-                this.connectionManager.Abort(updatedSilo);
+                _ = Task.Run(() => this.AbortConnectionAsync(updatedSilo));
+            }
+        }
+
+        private async Task AbortConnectionAsync(SiloAddress silo)
+        {
+            try
+            {
+                // Allow a short grace period to complete sending pending messages (eg, gossip responses)
+                await Task.Delay(TimeSpan.FromSeconds(1));
+
+                this.log.LogInformation("Aborting connections to defunct silo {SiloAddress}", silo);
+                this.connectionManager.Abort(silo);
+            }
+            catch (Exception exception)
+            {
+                this.log.LogInformation("Exception while aborting connections to defunct silo {SiloAddress}: {Exception}", silo, exception);
             }
         }
     }


Updated jacobi sample in NumCIL with some debug info

--- benchmark/CIL/Tester/JacobiSolver.cs
+++ benchmark/CIL/Tester/JacobiSolver.cs
@@ -31,6 +31,12 @@
             var right = full[R.Slice(2,  0),  R.Slice(1, -1) ];
             var down =  full[R.Slice(1, -1),  R.Slice(2,  0) ];

+            cells.Name = "cells";
+            up.Name = "up";
+            left.Name = "left";
+            right.Name = "right";
+            down.Name = "down";
+
             full[R.All, R.El(0)] += -273.5f;
             full[R.All, R.El(-1)] += -273.5f;
             full[0] += 40f;
@@ -53,6 +59,9 @@
                 Mul.Apply(work, 0.2f, work);

                 //This will do the same but not in-place
+                // We need to recompile the kernels to
+                // support this
+
                 /*work += up;
                 work += left;
                 work += right;


BugFix UploadNcFile

BugFix UploadNcFile

--- LibNoDaveConnectionLibrary/Communication/PLCConnection.cs
+++ LibNoDaveConnectionLibrary/Communication/PLCConnection.cs
@@ -3944,7 +3944,7 @@
             string filename = fullFileName.Remove(0, fullFileName.LastIndexOf('/') > 0 ? fullFileName.LastIndexOf('/') + 1 : 0);

             if (size == 0)
-                size = UploadNcFileSize(fullFileName, F_XFER);
+                size = 20 * GetPduSize(); //UploadNcFileSize(fullFileName, F_XFER);
             if (F_XFER)
                 PI_Service("_N_F_XFER", new string[] { "P01", fullFileName });

@@ -3975,7 +3975,7 @@
             string filename = fullFileName.Remove(0, fullFileName.LastIndexOf('/') > 0 ? fullFileName.LastIndexOf('/') + 1 : 0);

             if (size == 0)
-                size = UploadNcFileSize(fullFileName, F_XFER);
+                size = 20 * GetPduSize(); //UploadNcFileSize(fullFileName, F_XFER);
             if (F_XFER)
                 PI_Service("_N_F_XFER", new string[] { "P01", fullFileName });


change login link

change login link

--- Views/KawalDesa/Index.cshtml
+++ Views/KawalDesa/Index.cshtml
@@ -40,7 +40,7 @@

-
Login

+
Login


Remove useless code.

Remove useless code.

--- tests/Basic/Basic.cs
+++ tests/Basic/Basic.cs
@@ -1,5 +1,3 @@
-using System;
-using System.IO;
 using CppSharp.AST;
 using CppSharp.Generators;
 using CppSharp.Utils;
@@ -32,7 +30,6 @@

         public static void Main(string[] args)
         {
-            Console.WriteLine(Directory.GetCurrentDirectory());
             ConsoleDriver.Run(new Basic(GeneratorKind.CLI));
             ConsoleDriver.Run(new Basic(GeneratorKind.CSharp));
         }


Change AnyPrintTaskRunning to be true while PreparingToPrint

- Issue MatterHackers/MCCentral#4789
Do not allow sign in/out while printing

--- MatterControlLib/ApplicationView/ApplicationController.cs
+++ MatterControlLib/ApplicationView/ApplicationController.cs
@@ -2195,7 +2195,7 @@
 		/// <summary>
 		/// Indicates if any ActivePrinter is running a print task, either in paused or printing states
 		/// </summary>
-		public bool AnyPrintTaskRunning => this.ActivePrinters.Any(p => p.Connection.PrinterIsPrinting || p.Connection.PrinterIsPaused);
+		public bool AnyPrintTaskRunning => this.ActivePrinters.Any(p => p.Connection.PrinterIsPrinting || p.Connection.PrinterIsPaused || p.Connection.CommunicationState == CommunicationStates.PreparingToPrint);

 		private List<TourLocation> _productTour;


Cleanup

Cleanup

--- OpenSim/Region/CoreModules/World/Estate/TelehubManager.cs
+++ OpenSim/Region/CoreModules/World/Estate/TelehubManager.cs
@@ -109,10 +109,13 @@

             try
             {
-                float dist = (float) Util.GetDistanceTo(m_Scene.RegionInfo.RegionSettings.TelehubPos, point);
-                Vector3 nvec = Util.GetNormalizedVector(point - m_Scene.RegionInfo.RegionSettings.TelehubPos);
+                Vector3 thPos = m_Scene.RegionInfo.RegionSettings.TelehubPos;
+                Quaternion thRot = m_Scene.RegionInfo.RegionSettings.TelehubRot;
+
+                float dist = (float) Util.GetDistanceTo(thPos, point);
+                Vector3 nvec = Util.GetNormalizedVector(point - thPos);
                 Vector3 spoint = nvec * dist;
-
+
                 m_Scene.RegionInfo.RegionSettings.AddSpawnPoint(spoint);
                 m_Scene.RegionInfo.RegionSettings.Save();
                 result = true;


some fixes/changes on land send

some fixes/changes on land send

--- OpenSim/Region/CoreModules/World/Terrain/TerrainModule.cs
+++ OpenSim/Region/CoreModules/World/Terrain/TerrainModule.cs
@@ -1028,6 +1028,9 @@
             {
                 foreach (PatchUpdates pups in m_perClientPatchUpdates.Values)
                 {
+                    if(pups.Presence.IsDeleted)
+                        continue;
+
                     // throught acording to land queue free to send bytes
                     if (!pups.Presence.ControllingClient.CanSendLayerData())
                         continue;
@@ -1104,8 +1107,7 @@
                         patchs.Add(new PatchesToSend(x, y, 0));
                         if (++npatchs >= 128)
                         {
-                            pups.sendAllcurrentX = x + 1;
-                            pups.sendAllcurrentY = y;
+                            x++;
                             break;
                         }
                     }
@@ -1120,6 +1122,11 @@
                 pups.sendAll = false;
                 pups.sendAllcurrentX = 0;
                 pups.sendAllcurrentY = 0;
+            }
+            else
+            {
+                pups.sendAllcurrentX = x;
+                pups.sendAllcurrentY = y;
             }

             npatchs = patchs.Count;
@@ -1181,14 +1188,14 @@
             int startX = testposX - DrawDistance;
             if (startX < 0)
                 startX = 0;
-            else if (startX > limitX)
-                startX = limitX;
+            else if (startX >= limitX)
+                startX = limitX - 1;

             int startY = testposY - DrawDistance;
             if (startY < 0)
                 startY = 0;
-            else if (startY > limitY)
-                startY = limitY;
+            else if (startY >= limitY)
+                startY = limitY - 1;

             int endX = testposX + DrawDistance;
             if (endX < 0)
@@ -1221,7 +1228,7 @@
                         {
                             pups.SetByPatch(x, y, false);
                             ret.Add(new PatchesToSend(x, y, (float)distsq));
-                            if (npatchs++ > 512)
+                            if (npatchs++ > 1024)
                             {
                                 y = endY;
                                 x = endX;


Fixes an exception that is seen on regions running XEngine, where DNE tries to stop a script that is not run by it

--- OpenSim/Region/ScriptEngine/DotNetEngine/ScriptManager.cs
+++ OpenSim/Region/ScriptEngine/DotNetEngine/ScriptManager.cs
@@ -169,17 +169,12 @@

         public override void _StopScript(uint localID, UUID itemID)
         {
-            // Stop script
-//#if DEBUG
-//            m_scriptEngine.Log.Debug("[" + m_scriptEngine.ScriptEngineName + "]: Stop script localID: " + localID + " LLUID: " + itemID.ToString());
-//#endif
-
-            // Stop long command on script
-            AsyncCommandManager.RemoveScript(m_scriptEngine, localID, itemID);
-
             IScript LSLBC = GetScript(localID, itemID);
             if (LSLBC == null)
                 return;
+
+            // Stop long command on script
+            AsyncCommandManager.RemoveScript(m_scriptEngine, localID, itemID);

             // TEMP: First serialize it
             //GetSerializedScript(localID, itemID);


Fixed consonant bug

Fixed consonant bug

--- OpenUtau.Plugin.Builtin/SpanishSyllableBasedPhonemizer.cs
+++ OpenUtau.Plugin.Builtin/SpanishSyllableBasedPhonemizer.cs
@@ -31,14 +31,13 @@
         private readonly string[] longConsonants = "b,ch,d,dz,g,h,s,sh,k,p,rr,t,ts,z,l,m,n".Split(',');
         private readonly string[] burstConsonants = "b,ch,d,dz,g,j,k,p,r,t,ts".Split(',');
         private readonly string[] notClusters = "dz,hh,ll,nh,sh,zz,zh".Split(',');
-        private readonly string[] specialClusters = "by,dy,fy,gy,hy,jy,ky,ly,my,py,ry,rry,sy,ty,vy,zy,bw,chw,dw,fw,gw,hw,jw,kw,lw,llw,mw,nw,pw,rw,rrw,sw,tw,vw,zw,bl,fl,gl,kl,pl,br,dr,fr,gr,kr,pr,tr".Split(',');
+        private readonly string[] specialClusters = "by,dy,fy,gy,hy,jy,ky,ly,my,py,ry,rry,sy,ty,vy,zy,bw,chw,dw,fw,gw,hw,jw,kw,lw,llw,mw,nw,pw,rw,rrw,sw,tw,vw,zw,bl,fl,gl,kl,pl,br,dr,fr,gr,kr,pr,tr,si".Split(',');

         protected override string[] GetVowels() => vowels;
         protected override string[] GetConsonants() => consonants;
         protected override string GetDictionaryName() => "cmudict_es.txt";
         protected override Dictionary<string, string> GetDictionaryPhonemesReplacement() => dictionaryReplacements;
-
-        protected override List<string> ProcessSyllable(Syllable syllable) {
+        protected override List<string> ProcessSyllable(Syllable syllable){
             string prevV = syllable.prevV;
             string[] cc = syllable.cc;
             string v = syllable.v;
@@ -192,7 +191,7 @@
                         var syccv = $"{cc[0]} sy{v}";
                         var swccv = $"{cc[0]} sw{v}";
                         if (specialClusters.Contains(string.Join("", cc.Skip(i)))) {
-                            basePhoneme = spccv;
+                        basePhoneme = spccv;
                         }
                         if (specialClusters.Contains(string.Join("", cc.Skip(i))) && HasOto(ccv3, syllable.vowelTone)) {
                             basePhoneme = ccv3;
@@ -240,15 +239,11 @@
                         }
                         // like [V C1] [C1 C2] [C2 ..]
                     } else if (!HasOto(cc2, syllable.tone)
-                        && !vc1.Contains($"{prevV} {cc[i]}")
-                        && !vc2.Contains($"{prevV}{cc[i]}")
                         && !HasOto(vcc, syllable.tone)
                         && !HasOto(vcc2, syllable.tone)
-                        && !specialClusters.Contains(string.Join("", cc.Skip(i)))
-                        && !burstConsonants.Contains(cc[i])
-                        && HasOto(cc[i], syllable.tone)) {
-                        phonemes.Add(cc[i]);
-                    } else if (burstConsonants.Contains(cc[i]) && !specialClusters.Contains(string.Join("", cc.Skip(i)))) {
+                        && !burstConsonants.Contains(cc[i])) {
+                        TryAddPhoneme(phonemes, syllable.tone, cc[i], $"{cc[i]}u");
+                    } else if (burstConsonants.Contains(cc[i])) {
                         // like [V C1] [C1] [C2 ..]
                         TryAddPhoneme(phonemes, syllable.tone, cc[i]);
                     }
@@ -264,29 +259,24 @@
                         TryAddPhoneme(phonemes, syllable.tone, ncc1);
                     }
                     if (!HasOto(cc1, syllable.tone)
-                        && !specialClusters.Contains(string.Join("", cc.Skip(i)))
                         && !HasOto(vc1, syllable.tone)
                         && !HasOto(vc2, syllable.tone)
-                        && !burstConsonants.Contains(cc[i])
-                        && HasOto(cc[i], syllable.tone)) {
-                        phonemes.Add(cc[i]);
-                    } else if (!HasOto(cc1, syllable.tone)
-                          && !specialClusters.Contains(string.Join("", cc.Skip(i)))
-                          && !burstConsonants.Contains(cc[i])
-                          && !vc1.Contains($"{prevV} {cc[i]}")
-                          && !vc2.Contains($"{prevV}{cc[i]}")
-                          && !HasOto(vcc, syllable.tone)
-                          && !HasOto(vcc2, syllable.tone)
-                          && HasOto(cc[i], syllable.tone)) {
-                        phonemes.Add(cc[i]);
-
+                        && !burstConsonants.Contains(cc[i])) {
+                        TryAddPhoneme(phonemes, syllable.tone, cc[i], $"{cc[i]}u");
+                    }
+                    if (!HasOto(cc1, syllable.tone)
+                        && !vc1.Contains($"{prevV} {cc[i]}")
+                        && !vc2.Contains($"{prevV}{cc[i]}")
+                        && !cc.Last().Contains("y")
+                        && !cc.Last().Contains("w")) {
+                        TryAddPhoneme(phonemes, syllable.tone, cc[i], $"{cc[i]}u");
+                    } else if (burstConsonants.Contains(cc[i]) && !syllable.IsStartingCVWithMoreThanOneConsonant && !specialClusters.Contains(string.Join("", cc.Skip(i)))) {
+                        TryAddPhoneme(phonemes, syllable.tone, cc[i]);
                     }
                     if (cc[i] == "r" && HasOto($"{prevV}rr", syllable.tone)) {
                         phonemes.Remove(vc1);
                         phonemes.Remove(vc2);
                         phonemes.Add($"{prevV}rr");
-                    } else if (burstConsonants.Contains(cc[i]) && !syllable.IsStartingCVWithMoreThanOneConsonant && !specialClusters.Contains(string.Join("", cc.Skip(i)))) {
-                        TryAddPhoneme(phonemes, syllable.tone, cc[i]);
                     }
                 }
             }


Forcing table cache to be rebuilt when new project added

--- src/SSDTDevPack.Clippy/Operations/TableNameCorrectCaser.cs
+++ src/SSDTDevPack.Clippy/Operations/TableNameCorrectCaser.cs
@@ -107,6 +107,10 @@
                             rebuildCache = true;
                         }
                     }
+                    else
+                    {
+                        rebuildCache = true;
+                    }

                 }
                 catch (Exception)


Update

Update

--- leetcode/C_sharp/online_judge/leetcode/easy/Problem876.cs
+++ leetcode/C_sharp/online_judge/leetcode/easy/Problem876.cs
@@ -11,8 +11,8 @@
         public ListNode MiddleNode(ListNode head)
         {
             int length = GetLength(head);
-            int move = length % 2 == 0 ? (length / 2) + 1 : (length / 2);
-            while(move > 0)
+            int move = length % 2 == 0 ? (length / 2) : (length / 2) + 1;
+            while (move > 0)
             {
                 head = head.next;
                 move--;
@@ -24,7 +24,7 @@
         {
             int length = 0;
             ListNode node = head;
-            while(node.next != null)
+            while (node.next != null)
             {
                 node = node.next;
                 length++;


Fix end range value for arrays

Fix end range value for arrays

--- debugger/debugger-worker/src/Values/Render/ChildrenRenderers/SerialisedPropertyChildrenRenderer.cs
+++ debugger/debugger-worker/src/Values/Render/ChildrenRenderers/SerialisedPropertyChildrenRenderer.cs
@@ -397,7 +397,7 @@
                                       MethodSelector getMethodElementSelector,
                                       IValueServicesFacade<TValue> valueServices,
                                       ILogger logger)
-                : base($"[0..{arraySize}]")
+                : base($"[0..{arraySize - 1}]")
             {
                 mySerializedPropertyRole = serializedPropertyRole;
                 myArraySize = arraySize;


assignment to PhpAlias fix

assignment to PhpAlias fix

https://github.com/peachpiecompiler/peachpie/issues/134

--- src/Peachpie.CodeAnalysis/CodeGen/Graph/BoundExpression.cs
+++ src/Peachpie.CodeAnalysis/CodeGen/Graph/BoundExpression.cs
@@ -3007,13 +3007,16 @@
             Debug.Assert(target_place.TypeOpt == null || target_place.TypeOpt.SpecialType != SpecialType.System_Void);

             // T tmp; // in case access is Read
-            TypeSymbol t_value;
             LocalDefinition tmp = null;

             // <target> = <value>
             target_place.EmitStorePrepare(cg);

-            if (target_place.TypeOpt != null && !Value.Access.IsReadRef && Access.IsNone)
+            TypeSymbol t_value = target_place.TypeOpt;
+            if (t_value != null &&
+                !t_value.Is_PhpAlias() &&
+                !Value.Access.IsReadRef &&
+                Access.IsNone)
             {
                 // we can convert more efficiently here
                 t_value = target_place.TypeOpt;


refactor IO add frame class fix whitespace input

--- src/ConsoleMenu/IO.cs
+++ src/ConsoleMenu/IO.cs
@@ -7,7 +7,17 @@
 {
 	public static class IO
 	{
-		private static readonly Stack<IEnumerator<string>> _Frames = new Stack<IEnumerator<string>> ();
+		private class Frame
+		{
+			public IEnumerator<string> E;
+
+			public Frame (IEnumerable<string> source)
+			{
+				E = source.GetEnumerator ();
+			}
+		}
+
+		private static readonly Stack<Frame> _Frames = new Stack<Frame> ();

 		static IO ()
 		{
@@ -16,12 +26,18 @@

 		public static string QueryInput ()
 		{
-			var f = _Frames.Peek ();
-			while (!f.MoveNext ()) {
-				_Frames.Pop ();
-				f = _Frames.Peek ();
+			for (; ; ) {
+				var f = _Frames.Peek ();
+				while (!f.E.MoveNext ()) {
+					_Frames.Pop ();
+					f = _Frames.Peek ();
+				}
+
+				var input = f.E.Current;
+				if (!string.IsNullOrWhiteSpace (input)) {
+					return input;
+				}
 			}
-			return f.Current;
 		}

 		private static IEnumerable<string> DefaultInputSource ()
@@ -33,7 +49,7 @@

 		public static void AddInput (IEnumerable<string> source)
 		{
-			_Frames.Push (source.GetEnumerator ());
+			_Frames.Push (new Frame (source));
 		}

 		public static void ImmediateInput (string source)


detect 24 hours properly

detect 24 hours properly

--- src/Controls/Clock.cs
+++ src/Controls/Clock.cs
@@ -3,6 +3,7 @@
 using System.Globalization;
 using System.Linq;
 using Windows.Foundation;
+using Windows.Globalization.DateTimeFormatting;
 using Windows.UI.Xaml;
 using Windows.UI.Xaml.Controls;
 using Windows.UI.Xaml.Controls.Primitives;
@@ -67,7 +68,7 @@
         {
             // default to the system settings at initialization
             // can be overriden later
-            this.Is24HoursEnabled = false; // IsUsing24HoursTime(CultureInfo.CurrentCulture);
+            this.Is24HoursEnabled = IsUsing24HoursTime();
         }

         private static void OnTimeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
@@ -131,6 +132,9 @@
         {
             var clock = (Clock)d;

+            if (clock.hoursCanvas == null)
+                return; // template hasn't been loaded yet
+
             clock.UpdateHeaderDisplay();

             var buttons = clock.hoursCanvas.Children.OfType<ClockButton>().ToList();
@@ -162,6 +166,9 @@

         private void UpdateHeaderDisplay()
         {
+            if (this.hoursCanvas == null)
+                return;  // template hasn't been loaded yet
+
             if (this.Is24HoursEnabled)
                 this.textBlockHours.Text = this.Time.Hour.ToString("D2");
             else if (this.Time.Hour > 12)
@@ -402,9 +409,11 @@
             this.SetDisplayMode(ClockItemMember.Minutes);
         }

-        private static bool IsUsing24HoursTime(CultureInfo culture)
-        {
-            return culture.DateTimeFormat.ShortTimePattern.Contains("h");
-        }
+        private static bool IsUsing24HoursTime()
+        {
+            // a hack to get "real" culture when app runs on a machine where it's not localized (example: Finland)
+            var cultureName = new DateTimeFormatter("longdate", new[] { "US" }).ResolvedLanguage;
+            return new CultureInfo(cultureName).DateTimeFormat.ShortTimePattern.Contains("H");
+        }
     }
 }


Don't replicate clock docs

Don't replicate clock docs

--- src/Raven.Bundles.Contrib.ClockDocs/ClockDocsMaintainer.cs
+++ src/Raven.Bundles.Contrib.ClockDocs/ClockDocsMaintainer.cs
@@ -3,6 +3,7 @@
 using System.Threading;
 using System.Threading.Tasks;
 using Raven.Abstractions;
+using Raven.Abstractions.Data;
 using Raven.Abstractions.Extensions;
 using Raven.Database;
 using Raven.Database.Plugins;
@@ -101,7 +102,9 @@

             using (_database.DisableAllTriggersForCurrentThread())
             {
-                _database.Put(id, null, RavenJObject.FromObject(clock), new RavenJObject(), null);
+                var document = RavenJObject.FromObject(clock);
+                var metadata = new RavenJObject { { Constants.NotForReplication, true } };
+                _database.Put(id, null, document, metadata, null);
             }
         }
     }


UL end tag typo

UL end tag typo

--- src/Elmah/SpeedBar.cs
+++ src/Elmah/SpeedBar.cs
@@ -58,7 +58,7 @@
                         writer.Write(Html.Encode(part).ToHtmlString());
                     writer.Write("
");
                 }
-                writer.Write(/* TODO fix end tag */ "
");
+                writer.Write("
");
             });
         }


fixed a handshake bug by use "\r\n" instead of Environment.NewLine

git-svn-id: 264d93eb9283b6a3bfed80dd266caeb8f93e7ca3@71604 81fbe566-5dc4-48c1-bdea-7421811ca204

--- mainline/SuperWebSocket/Protocol/WebSocketHeaderReader.cs
+++ mainline/SuperWebSocket/Protocol/WebSocketHeaderReader.cs
@@ -12,7 +12,7 @@
 {
     public class WebSocketHeaderReader : WebSocketReaderBase
     {
-        private static readonly byte[] m_HeaderTerminator = Encoding.UTF8.GetBytes(Environment.NewLine + Environment.NewLine);
+        private static readonly byte[] m_HeaderTerminator = Encoding.UTF8.GetBytes("\r\n\r\n");

         public WebSocketHeaderReader(IAppServer server)
             : base(server)


added configurable depended services feature for SocketService

git-svn-id: 264d93eb9283b6a3bfed80dd266caeb8f93e7ca3@71856 81fbe566-5dc4-48c1-bdea-7421811ca204

--- mainline/SuperWebSocketService/SuperWebSocketInstaller.cs
+++ mainline/SuperWebSocketService/SuperWebSocketInstaller.cs
@@ -27,6 +27,14 @@
             serviceInstaller.StartType = ServiceStartMode.Automatic;
             serviceInstaller.ServiceName = ConfigurationManager.AppSettings["ServiceName"];

+            var servicesDependedOn = new List<string> { "tcpip" };
+            var servicesDependedOnConfig = ConfigurationManager.AppSettings["ServicesDependedOn"];
+
+            if (!string.IsNullOrEmpty(servicesDependedOnConfig))
+                servicesDependedOn.AddRange(servicesDependedOnConfig.Split(new char[] { ',', ';' }));
+
+            serviceInstaller.ServicesDependedOn = servicesDependedOn.ToArray();
+
             Installers.Add(serviceInstaller);
             Installers.Add(processInstaller);
         }


Include DataGrid unit tests in CI

Include DataGrid unit tests in CI

--- nukebuild/Build.cs
+++ nukebuild/Build.cs
@@ -191,6 +191,7 @@
             RunCoreTest("./tests/Avalonia.Animation.UnitTests");
             RunCoreTest("./tests/Avalonia.Base.UnitTests");
             RunCoreTest("./tests/Avalonia.Controls.UnitTests");
+            RunCoreTest("./tests/Avalonia.Controls.DataGrid.UnitTests");
             RunCoreTest("./tests/Avalonia.Input.UnitTests");
             RunCoreTest("./tests/Avalonia.Interactivity.UnitTests");
             RunCoreTest("./tests/Avalonia.Layout.UnitTests");


移植 EncryptHelper.cs

移植 EncryptHelper.cs

--- src/Senparc.Weixin/Senparc.Weixin/Helpers/EncryptHelper.cs
+++ src/Senparc.Weixin/Senparc.Weixin/Helpers/EncryptHelper.cs
@@ -36,6 +36,12 @@
     修改标识：Senparc - 20180101
     修改描述：v4.18.10 添加 EncryptHelper.GetHmacSha256() 方法，为“小游戏”签名提供支持

+
+
+    ----  CO2NET   ----
+
+    修改标识：Senparc - 20180601
+    修改描述：v5.0.0 引入 Senparc.CO2NET
 ----------------------------------------------------------------*/

@@ -51,262 +57,9 @@
     /// <summary>
     /// 安全帮助类，提供SHA-1算法等
     /// </summary>
+    [Obsolete("请使用 Senparc.CO2NET.Helpers.EncryptHelper 类")]
     public class EncryptHelper
     {
-        #region SHA相关

-        /// <summary>
-        /// 采用SHA-1算法加密字符串（小写）
-        /// </summary>
-        /// <param name="encypStr">需要加密的字符串</param>
-        /// <returns></returns>
-        public static string GetSha1(string encypStr)
-        {
-            var sha1 = SHA1.Create();
-            var sha1Arr = sha1.ComputeHash(Encoding.UTF8.GetBytes(encypStr));
-            StringBuilder enText = new StringBuilder();
-            foreach (var b in sha1Arr)
-            {
-                enText.AppendFormat("{0:x2}", b);
-            }
-
-            return enText.ToString();
-
-            //byte[] strRes = Encoding.Default.GetBytes(encypStr);
-            //HashAlgorithm iSHA = new SHA1CryptoServiceProvider();
-            //strRes = iSHA.ComputeHash(strRes);
-            //StringBuilder enText = new StringBuilder();
-            //foreach (byte iByte in strRes)
-            //{
-            //    enText.AppendFormat("{0:x2}", iByte);
-            //}
-        }
-
-        /// <summary>
-        /// HMAC SHA256 加密
-        /// </summary>
-        /// <param name="message">加密消息原文。当为小程序SessionKey签名提供服务时，其中message为本次POST请求的数据包（通常为JSON）。特别地，对于GET请求，message等于长度为0的字符串。</param>
-        /// <param name="secret">秘钥（如小程序的SessionKey）</param>
-        /// <returns></returns>
-        public static string GetHmacSha256(string message, string secret)
-        {
-            message = message ?? "";
-            secret = secret ?? "";
-            byte[] keyByte = Encoding.UTF8.GetBytes(secret);
-            byte[] messageBytes = Encoding.UTF8.GetBytes(message);
-            using (var hmacsha256 = new HMACSHA256(keyByte))
-            {
-                byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
-                StringBuilder enText = new StringBuilder();
-                foreach (var b in hashmessage)
-                {
-                    enText.AppendFormat("{0:x2}", b);
-                }
-                return enText.ToString();
-            }
-        }
-
-
-        #endregion
-
-        #region MD5
-
-        /// <summary>
-        /// 获取大写的MD5签名结果
-        /// </summary>
-        /// <param name="encypStr">需要加密的字符串</param>
-        /// <param name="encoding">编码</param>
-        /// <returns></returns>
-        public static string GetMD5(string encypStr, Encoding encoding)
-        {
-            string retStr;
-
-#if NET35 || NET40 || NET45
-            MD5CryptoServiceProvider m5 = new MD5CryptoServiceProvider();
-#else
-            MD5 m5 = MD5.Create();
-#endif
-
-            //创建md5对象
-            byte[] inputBye;
-            byte[] outputBye;
-
-            //使用指定编码方式把字符串转化为字节数组．
-            try
-            {
-                inputBye = encoding.GetBytes(encypStr);
-            }
-            catch
-            {
-                inputBye = Encoding.GetEncoding("utf-8").GetBytes(encypStr);
-
-            }
-            outputBye = m5.ComputeHash(inputBye);
-
-            retStr = BitConverter.ToString(outputBye);
-            retStr = retStr.Replace("-", "").ToUpper();
-            return retStr;
-        }
-
-        /// <summary>
-        /// 获取大写的MD5签名结果
-        /// </summary>
-        /// <param name="encypStr">需要加密的字符串</param>
-        /// <param name="charset">编码</param>
-        /// <returns></returns>
-        public static string GetMD5(string encypStr, string charset = "utf-8")
-        {
-            charset = charset ?? "utf-8";
-            try
-            {
-                //使用指定编码
-                return GetMD5(encypStr, Encoding.GetEncoding(charset));
-            }
-            catch (Exception ex)
-            {
-                //使用UTF-8编码
-                return GetMD5("utf-8", Encoding.GetEncoding(charset));
-
-                //#if NET35 || NET40 || NET45
-                //                inputBye = Encoding.GetEncoding("GB2312").GetBytes(encypStr);
-                //#else
-                //                inputBye = Encoding.GetEncoding(936).GetBytes(encypStr);
-                //#endif
-            }
-        }
-
-        /// <summary>
-        /// 获取小写的MD5签名结果
-        /// </summary>
-        /// <param name="encypStr">需要加密的字符串</param>
-        /// <param name="encoding">编码</param>
-        /// <returns></returns>
-        public static string GetLowerMD5(string encypStr, Encoding encoding)
-        {
-            return GetMD5(encypStr, encoding).ToLower();
-        }
-
-        #endregion
-
-        #region AES
-
-        /// <summary>
-        /// AES加密
-        /// </summary>
-        /// <param name="inputdata">输入的数据</param>
-        /// <param name="iv">向量</param>
-        /// <param name="strKey">加密密钥</param>
-        /// <returns></returns>
-        public static byte[] AESEncrypt(byte[] inputdata, byte[] iv, string strKey)
-        {
-            //分组加密算法
-#if NET35 || NET40 || NET45
-            SymmetricAlgorithm des = Rijndael.Create();
-#else
-            SymmetricAlgorithm des = Aes.Create();
-#endif
-
-            byte[] inputByteArray = inputdata;//得到需要加密的字节数组
-                                              //设置密钥及密钥向量
-            des.Key = Encoding.UTF8.GetBytes(strKey.Substring(0, 32));
-            des.IV = iv;
-            using (MemoryStream ms = new MemoryStream())
-            {
-                using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write))
-                {
-                    cs.Write(inputByteArray, 0, inputByteArray.Length);
-                    cs.FlushFinalBlock();
-                    byte[] cipherBytes = ms.ToArray();//得到加密后的字节数组
-                    //cs.Close();
-                    //ms.Close();
-                    return cipherBytes;
-                }
-            }
-        }
-
-
-        /// <summary>
-        /// AES解密
-        /// </summary>
-        /// <param name="inputdata">输入的数据</param>
-        /// <param name="iv">向量</param>
-        /// <param name="strKey">key</param>
-        /// <returns></returns>
-        public static byte[] AESDecrypt(byte[] inputdata, byte[] iv, byte[] strKey)
-        {
-#if NET35 || NET40 || NET45
-            SymmetricAlgorithm des = Rijndael.Create();
-#else
-            SymmetricAlgorithm des = Aes.Create();
-#endif
-
-            des.Key = strKey;//Encoding.UTF8.GetBytes(strKey);//.Substring(0, 7)
-            des.IV = iv;
-            byte[] decryptBytes = new byte[inputdata.Length];
-            using (MemoryStream ms = new MemoryStream(inputdata))
-            {
-                using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Read))
-                {
-                    cs.Read(decryptBytes, 0, decryptBytes.Length);
-                    //cs.Close();
-                    //ms.Close();
-                }
-            }
-            return decryptBytes;
-        }
-
-        /// <summary>
-        /// AES解密(无向量)
-        /// </summary>
-        /// <param name="data">被加密的明文</param>
-        /// <param name="key">密钥</param>
-        /// <returns>明文</returns>
-        public static string AESDecrypt(String data, String key)
-        {
-            Byte[] encryptedBytes = Convert.FromBase64String(data);
-            Byte[] bKey = new Byte[32];
-            Array.Copy(Encoding.UTF8.GetBytes(key.PadRight(bKey.Length)), bKey, bKey.Length);
-
-            MemoryStream mStream = new MemoryStream(encryptedBytes);
-            //mStream.Write( encryptedBytes, 0, encryptedBytes.Length );
-            //mStream.Seek( 0, SeekOrigin.Begin );
-
-
-            //RijndaelManaged aes = new RijndaelManaged();
-#if NET35 || NET40 || NET45
-            SymmetricAlgorithm aes = Rijndael.Create();
-#else
-            SymmetricAlgorithm aes = Aes.Create();
-#endif
-
-            aes.Mode = CipherMode.ECB;
-            aes.Padding = PaddingMode.PKCS7;
-            aes.KeySize = 128;
-            aes.Key = bKey;
-            //aes.IV = _iV;
-            CryptoStream cryptoStream = new CryptoStream(mStream, aes.CreateDecryptor(), CryptoStreamMode.Read);
-            try
-            {
-                byte[] tmp = new byte[encryptedBytes.Length + 32];
-                int len = cryptoStream.Read(tmp, 0, encryptedBytes.Length + 32);
-                byte[] ret = new byte[len];
-                Array.Copy(tmp, 0, ret, 0, len);
-                return Encoding.UTF8.GetString(ret);
-            }
-            finally
-            {
-#if NET35 || NET40 || NET45
-                cryptoStream.Close();
-                mStream.Close();
-                aes.Clear();
-#else
-                //cryptoStream.();
-                //mStream.Close();
-                //aes.Clear();
-#endif
-            }
-        }
-
-        #endregion
     }
 }


Removed more white space

Removed more white space

--- src/Skybrud.Umbraco.Redirects/Services/RedirectsService.cs
+++ src/Skybrud.Umbraco.Redirects/Services/RedirectsService.cs
@@ -21,12 +21,12 @@
 using Umbraco.Extensions;

 namespace Skybrud.Umbraco.Redirects.Services {
-
+
     /// <summary>
     /// Default implementation of the <see cref="IRedirectsService"/> interface.
     /// </summary>
     public class RedirectsService : IRedirectsService {
-
+
         private readonly ILogger<RedirectsService> _logger;
         private readonly IScopeProvider _scopeProvider;
         private readonly IDomainService _domains;
@@ -85,7 +85,7 @@
             scope.Complete();

         }
-
+
         /// <summary>
         /// Gets the redirect mathing the specified <paramref name="url"/>.
         /// </summary>
@@ -96,7 +96,7 @@
             url.Split('?', out string path, out string query);
             return GetRedirectByPathAndQuery(rootNodeKey, path, query);
         }
-
+
         /// <summary>
         /// Gets the redirect mathing the specified <paramref name="path"/> and <paramref name="query"/>.
         /// </summary>
@@ -113,9 +113,9 @@
             query = (query ?? string.Empty).Trim();

             RedirectDto dto;
-
+
             using (var scope = _scopeProvider.CreateScope()) {
-
+
                 // Generate the SQL for the query
                 var sql = scope.SqlContext.Sql()
                     .Select<RedirectDto>()
@@ -146,14 +146,14 @@
             return dto == null ? null : new Redirect(dto);

         }
-
+
         /// <summary>
         /// Returns the first redirect matching the specified <paramref name="request"/>, or <c>null</c> if the request does not match any redirects.
         /// </summary>
         /// <param name="request">The request.</param>
         /// <returns>An instance of <see cref="IRedirect"/>, or <c>null</c> if no matching redirects were found.</returns>
         public IRedirect GetRedirectByRequest(HttpRequest request) {
-
+
             // Get the URI from the request
             Uri uri = request.GetUri();

@@ -161,7 +161,7 @@
             return GetRedirectByUri(uri);

         }
-
+
         /// <summary>
         /// Returns the first redirect matching the specified <paramref name="uri"/>, or <c>null</c> if the URI does not match any redirects.
         /// </summary>
@@ -177,7 +177,7 @@

             // Get the current Umbraco context
             _umbracoContextAccessor.TryGetUmbracoContext(out IUmbracoContext umbracoContext);
-
+
             // Determine the root node via domain of the request
             Guid rootKey = Guid.Empty;
             if (TryGetDomain(uri, out Domain domain)) {
@@ -190,12 +190,12 @@
                 IRedirect redirect = GetRedirectByPathAndQuery(rootKey, path, query);
                 if (redirect != null) return redirect;
             }
-
+
             // Look for a global redirect
             return GetRedirectByPathAndQuery(Guid.Empty, path, query);

         }
-
+
         private bool TryGetDomain(Uri uri, out Domain domain) {
             domain = DomainUtils.FindDomainForUri(_domains, uri);
             return domain != null;
@@ -278,7 +278,7 @@

             // Initialize the new redirect and populate the properties
             Redirect item = new Redirect {
-
+
                 RootKey = options.RootNodeKey,
                 Url = options.OriginalUrl,
                 CreateDate = EssentialsTime.UtcNow,
@@ -358,10 +358,10 @@
         public RedirectsSearchResult GetRedirects(RedirectsSearchOptions options) {

             if (options == null) throw new ArgumentNullException(nameof(options));
-
+
             // Create a new scope
             using var scope = _scopeProvider.CreateScope();
-
+
             // Generate the SQL for the query
             var sql = scope.SqlContext.Sql().Select<RedirectDto>().From<RedirectDto>();

@@ -427,28 +427,28 @@
             return result;

         }
-
+
         /// <summary>
         /// Returns a collection with all redirects.
         /// </summary>
         /// <returns>An instance of <see cref="IEnumerable{Redirect}"/>.</returns>
         public IEnumerable<IRedirect> GetAllRedirects()  {
-
+
             // Create a new scope
             using var scope = _scopeProvider.CreateScope();
-
+
             // Generate the SQL for the query
             var sql = scope.SqlContext.Sql().Select<RedirectDto>().From<RedirectDto>();
-
+
             // Make the call to the database
             var redirects = scope.Database.Fetch<RedirectDto>(sql).Select(Redirect.CreateFromDto);
-
+
             scope.Complete();

             return redirects;

         }
-
+
         /// <summary>
         /// Returns an array of all rode nodes configured in Umbraco.
         /// </summary>
@@ -476,7 +476,7 @@
         public virtual string GetDestinationUrl(IRedirectBase redirect) {
             return GetDestinationUrl(redirect, null);
         }
-
+
         /// <summary>
         /// Returns the calculated destination URL for the specified <paramref name="redirect"/>.
         /// </summary>
@@ -484,7 +484,7 @@
         /// <param name="uri">The inbound URL.</param>
         /// <returns>The destination URL.</returns>
         public virtual string GetDestinationUrl(IRedirectBase redirect, Uri uri) {
-
+
             if (string.IsNullOrWhiteSpace(redirect?.Destination?.Url)) return null;

             // Get the query string (if any)
@@ -511,7 +511,7 @@
                         content = context.Media?.GetById(redirect.Destination.Key);
                     }
                     break;
-
+
             }

             // Put the destination URL back together
@@ -529,7 +529,7 @@
             if (!query1.HasValue()) return query2.TrimStart('?');
             return query1 + "&" + query2.TrimStart('?');
         }
-
+
         /// <summary>
         /// Returns an array of redirects where the destination matches the specified <paramref name="nodeType"/> and <paramref name="nodeId"/>.
         /// </summary>
@@ -540,7 +540,7 @@
             if (nodeType == RedirectDestinationType.Url) throw new RedirectsException($"Unsupported node type: {nodeType}");
             return GetRedirectsByNodeId(nodeType.ToString(), nodeId);
         }
-
+
         /// <summary>
         /// Returns an array of redirects where the destination matches the specified <paramref name="nodeType"/> and <paramref name="nodeKey"/>.
         /// </summary>
@@ -551,7 +551,7 @@
             if (nodeType == RedirectDestinationType.Url) throw new RedirectsException($"Unsupported node type: {nodeType}");
             return GetRedirectsByNodeKey(nodeType.ToString(), nodeKey);
         }
-
+
         /// <summary>
         /// Returns an array of redirects where the destination matches the specified <paramref name="nodeType"/> and <paramref name="nodeId"/>.
         /// </summary>
@@ -559,17 +559,17 @@
         /// <param name="nodeId">The numeric ID of the destination node.</param>
         /// <returns>An array of <see cref="IRedirect"/>.</returns>
         protected virtual IRedirect[] GetRedirectsByNodeId(string nodeType, int nodeId) {
-
+
             // Create a new scope
             using var scope = _scopeProvider.CreateScope();
-
+
             // Generate the SQL for the query
             Sql<ISqlContext> sql = scope.SqlContext
                 .Sql()
                 .Select<RedirectDto>()
                 .From<RedirectDto>()
                 .Where<RedirectDto>(x => x.DestinationType == nodeType && x.DestinationId == nodeId);
-
+
             // Make the call to the database
             var rows = scope.Database
                 .Fetch<RedirectDto>(sql)
@@ -582,7 +582,7 @@
             return rows;

         }
-
+
         /// <summary>
         /// Returns an array of redirects where the destination matches the specified <paramref name="nodeType"/> and <paramref name="nodeKey"/>.
         /// </summary>
@@ -590,16 +590,16 @@
         /// <param name="nodeKey">The key (GUID) of the destination node.</param>
         /// <returns>An array of <see cref="IRedirect"/>.</returns>
         protected virtual IRedirect[] GetRedirectsByNodeKey(string nodeType, Guid nodeKey) {
-
+
             // Create a new scope
             using var scope = _scopeProvider.CreateScope();
-
+
             // Generate the SQL for the query
             Sql<ISqlContext> sql = scope.SqlContext
                 .Sql()
                 .Select<RedirectDto>().From<RedirectDto>()
                 .Where<RedirectDto>(x => x.DestinationType == nodeType && x.DestinationKey == nodeKey);
-
+
             // Make the call to the database
             var rows = scope.Database
                 .Fetch<RedirectDto>(sql)


level gen in gameManager

level gen in gameManager


fix typo

fix typo

--- src/MSharp/Misskey.cs
+++ src/MSharp/Misskey.cs
@@ -62,7 +62,7 @@
 		{
 			var ret = await new MisskeyRequest(this, MethodType.GET, "sauth/get-user-key",
 				new Dictionary<string, string> {
-					{ "authentication-session-key", AuthenticationSessionKey },
+					{ "authentication-session-key", this.AuthenticationSessionKey },
 					{ "pin-code", pinCode}
 				}).Request();


Made sure responses which don't contain a REAL_STATUS header still are accepted

--- Unity/Assets/BackendManager.cs
+++ Unity/Assets/BackendManager.cs
@@ -103,16 +103,21 @@
             }
             yield break;
         }
-        string status = request.responseHeaders["REAL_STATUS"];
-        int statusCode = int.Parse(status.Split(' ')[0]);
+        int statusCode = 200;
+
+        if (request.responseHeaders.ContainsKey("REAL_STATUS")) {
+            string status = request.responseHeaders["REAL_STATUS"];
+            statusCode = int.Parse(status.Split(' ')[0]);
+        }
+        //if any other error occurred(probably 4xx range), see http://www.django-rest-framework.org/api-guide/status-codes/
+        bool responseSuccessful = (statusCode >= 200 && statusCode <= 206);
         JObject responseObj = null;

         try {
             responseObj = JObject.Parse(request.text);
         } catch (Exception ex) {
             if (onResponse != null) {
-                //if any other error occurred(probably 4xx range), see http://www.django-rest-framework.org/api-guide/status-codes/
-                if (statusCode < 200 || statusCode > 206) {
+                if (!responseSuccessful) {
                     Debug.Log("Could not parse the response, request.text=" + request.text);
                     Debug.Log("Exception=" + ex.ToString());
                     onResponse(ResponseType.ParseError, null, callee);
@@ -126,8 +131,8 @@
             }
             yield break;
         }
-        //if any other error occurred(probably 4xx range), see http://www.django-rest-framework.org/api-guide/status-codes/
-        if (statusCode < 200 || statusCode > 206) {
+
+        if (!responseSuccessful) {
             if (onResponse != null) {
                 onResponse(ResponseType.ErrorFromServer, responseObj, callee);
             }


Mark CharEnumerator as [Serializable] (dotnet/coreclr#11124)

Fixes https://github.com/dotnet/corefx/issues/18704

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

--- src/System.Private.CoreLib/shared/System/CharEnumerator.cs
+++ src/System.Private.CoreLib/shared/System/CharEnumerator.cs
@@ -17,6 +17,7 @@

 namespace System
 {
+    [Serializable]
     public sealed class CharEnumerator : IEnumerator, IEnumerator<char>, IDisposable, ICloneable
     {
         private String _str;


Cleanup tuple usage.

Cleanup tuple usage.

--- src/Test/Utilities/Portable/MarkedSource/MarkupTestFile.cs
+++ src/Test/Utilities/Portable/MarkedSource/MarkupTestFile.cs
@@ -58,12 +58,12 @@

             // A stack of span starts along with their associated annotation name.  [||] spans simply
             // have empty string for their annotation name.
-            var spanStartStack = new Stack<(int, string)>();
-            var namedSpanStartStack = new Stack<(int, string)>();
+            var spanStartStack = new Stack<(int matchIndex, string name)>();
+            var namedSpanStartStack = new Stack<(int matchIndex, string name)>();

             while (true)
             {
-                var matches = new List<(int, string)>();
+                var matches = new List<(int matchIndex, string name)>();
                 AddMatch(input, PositionString, currentIndexInInput, matches);
                 AddMatch(input, SpanStartString, currentIndexInInput, matches);
                 AddMatch(input, SpanEndString, currentIndexInInput, matches);
@@ -81,10 +81,10 @@
                     break;
                 }

-                var orderedMatches = matches.OrderBy((t1, t2) => t1.Item1 - t2.Item1).ToList();
+                var orderedMatches = matches.OrderBy((t1, t2) => t1.matchIndex - t2.matchIndex).ToList();
                 if (orderedMatches.Count >= 2 &&
                     (spanStartStack.Count > 0 || namedSpanStartStack.Count > 0) &&
-                    matches[0].Item1 == matches[1].Item1 - 1)
+                    matches[0].matchIndex == matches[1].matchIndex - 1)
                 {
                     // We have a slight ambiguity with cases like these:
                     //
@@ -93,8 +93,8 @@
                     // Is it starting a new match, or ending an existing match.  As a workaround, we
                     // special case these and consider it ending a match if we have something on the
                     // stack already.
-                    if ((matches[0].Item2 == SpanStartString && matches[1].Item2 == SpanEndString && !spanStartStack.IsEmpty()) ||
-                        (matches[0].Item2 == SpanStartString && matches[1].Item2 == NamedSpanEndString && !namedSpanStartStack.IsEmpty()))
+                    if ((matches[0].name == SpanStartString && matches[1].name == SpanEndString && !spanStartStack.IsEmpty()) ||
+                        (matches[0].name == SpanStartString && matches[1].name == NamedSpanEndString && !namedSpanStartStack.IsEmpty()))
                     {
                         orderedMatches.RemoveAt(0);
                     }
@@ -103,8 +103,8 @@
                 // Order the matches by their index
                 var firstMatch = orderedMatches.First();

-                var matchIndexInInput = firstMatch.Item1;
-                var matchString = firstMatch.Item2;
+                var matchIndexInInput = firstMatch.matchIndex;
+                var matchString = firstMatch.name;

                 var matchIndexInOutput = matchIndexInInput - inputOutputOffset;
                 outputBuilder.Append(input.Substring(currentIndexInInput, matchIndexInInput - currentIndexInInput));
@@ -184,14 +184,14 @@
         }

         private static void PopSpan(
-            Stack<(int, string)> spanStartStack,
+            Stack<(int matchIndex, string name)> spanStartStack,
             IDictionary<string, ArrayBuilder<TextSpan>> spans,
             int finalIndex)
         {
-            var spanStartTuple = spanStartStack.Pop();
-
-            var span = TextSpan.FromBounds(spanStartTuple.Item1, finalIndex);
-            GetOrAdd(spans, spanStartTuple.Item2, _ => ArrayBuilder<TextSpan>.GetInstance()).Add(span);
+            var (matchIndex, name) = spanStartStack.Pop();
+
+            var span = TextSpan.FromBounds(matchIndex, finalIndex);
+            GetOrAdd(spans, name, _ => ArrayBuilder<TextSpan>.GetInstance()).Add(span);
         }

         private static void AddMatch(string input, string value, int currentIndex, List<(int, string)> matches)


fixed a bug where validation didnt update properly adressed in https://github.com/umbraco/Umbraco-CMS/pull/10688

--- src/Umbraco.Web.BackOffice/Controllers/MemberController.cs
+++ src/Umbraco.Web.BackOffice/Controllers/MemberController.cs
@@ -368,7 +368,45 @@

             if (created.Succeeded == false)
             {
-                return ValidationProblem(created.Errors.ToErrorMessage());
+                MemberDisplay forDisplay = _umbracoMapper.Map<MemberDisplay>(contentItem.PersistedContent);
+                foreach (IdentityError error in created.Errors)
+                {
+                    switch (error.Code)
+                    {
+                        case nameof(IdentityErrorDescriber.InvalidUserName):
+                            ModelState.AddPropertyError(
+                                new ValidationResult(error.Description, new[] { "value" }),
+                                string.Format("{0}login", Constants.PropertyEditors.InternalGenericPropertiesPrefix));
+                            break;
+                        case nameof(IdentityErrorDescriber.PasswordMismatch):
+                        case nameof(IdentityErrorDescriber.PasswordRequiresDigit):
+                        case nameof(IdentityErrorDescriber.PasswordRequiresLower):
+                        case nameof(IdentityErrorDescriber.PasswordRequiresNonAlphanumeric):
+                        case nameof(IdentityErrorDescriber.PasswordRequiresUniqueChars):
+                        case nameof(IdentityErrorDescriber.PasswordRequiresUpper):
+                        case nameof(IdentityErrorDescriber.PasswordTooShort):
+                            ModelState.AddPropertyError(
+                                new ValidationResult(error.Description, new[] { "value" }),
+                                string.Format("{0}password", Constants.PropertyEditors.InternalGenericPropertiesPrefix));
+                            break;
+                        case nameof(IdentityErrorDescriber.InvalidEmail):
+                            ModelState.AddPropertyError(
+                                new ValidationResult(error.Description, new[] { "value" }),
+                                string.Format("{0}email", Constants.PropertyEditors.InternalGenericPropertiesPrefix));
+                            break;
+                        case nameof(IdentityErrorDescriber.DuplicateUserName):
+                            ModelState.AddPropertyError(
+                                new ValidationResult(error.Description, new[] { "value" }),
+                                string.Format("{0}login", Constants.PropertyEditors.InternalGenericPropertiesPrefix));
+                            break;
+                        case nameof(IdentityErrorDescriber.DuplicateEmail):
+                            ModelState.AddPropertyError(
+                                new ValidationResult(error.Description, new[] { "value" }),
+                                string.Format("{0}email", Constants.PropertyEditors.InternalGenericPropertiesPrefix));
+                            break;
+                    }
+                }
+                return ValidationProblem(forDisplay, ModelState);
             }

             // now re-look up the member, which will now exist


Fixes PublishedContent.cs when the property index doesn't contain the alias index (due to adding a new property type and the json not matchin)

--- src/Umbraco.Web/PublishedCache/NuCache/PublishedContent.cs
+++ src/Umbraco.Web/PublishedCache/NuCache/PublishedContent.cs
@@ -36,7 +36,14 @@
             foreach (var propertyType in _contentNode.ContentType.PropertyTypes)
             {
                 if (contentData.Properties.TryGetValue(propertyType.Alias, out var pdatas))
+                {
                     properties.Add(new Property(propertyType, this, pdatas, _publishedSnapshotAccessor));
+                }
+                else
+                {
+                    //it doesn't exist in our serialized json but we should add it as an empty property so they are in sync
+                    properties.Add(new Property(propertyType, this, null, _publishedSnapshotAccessor));
+                }
             }
             PropertiesArray = properties.ToArray();
         }
@@ -259,8 +266,7 @@
         {
             var index = _contentNode.ContentType.GetPropertyIndex(alias);
             if (index < 0) return null;
-            //TODO: Should we log here? I think this can happen when property types are added/removed from the doc type and the json serialized properties
-            // no longer match the list of property types since that is how the PropertiesArray is populated.
+            //fixme: This should not happen since we align the PropertiesArray with the property types in the ctor, if this does happen maybe we should throw a descriptive exception
             if (index >= PropertiesArray.Length) return null;
             var property = PropertiesArray[index];
             return property;


Make use of fact that when YieldContentNode == YieldInMoveTreeSection, all tag pairs and sections have already been captured.

--- Sandra.Chess/Pgn/PgnParser.cs
+++ Sandra.Chess/Pgn/PgnParser.cs
@@ -392,87 +392,52 @@
             switch (symbolBeingYielded.ContentNode.SymbolType)
             {
                 case PgnSymbolType.BracketOpen:
-                    // When encountering a new '[', open a new tag pair.
-                    CaptureTagPairIfNecessary();
                     HasTagPairBracketOpen = true;
                     AddTagElementToBuilder();
                     YieldContentNode = YieldInTagSectionAction;
                     break;
                 case PgnSymbolType.BracketClose:
-                    // When encountering a ']', always immediately close this tag pair.
+                    // When encountering a ']', switch to tag section and immediately open and close a tag pair.
                     AddTagElementToBuilder();
                     CaptureTagPair(hasTagPairBracketClose: true);
                     YieldContentNode = YieldInTagSectionAction;
                     break;
                 case PgnSymbolType.TagName:
-                    // Open a new tag pair if a tag name or value was seen earlier in the same tag pair.
-                    if (HasTagPairTagName || HasTagPairTagValue) CaptureTagPair(hasTagPairBracketClose: false);
                     HasTagPairTagName = true;
                     AddTagElementToBuilder();
                     YieldContentNode = YieldInTagSectionAction;
                     break;
                 case PgnSymbolType.TagValue:
                 case PgnSymbolType.ErrorTagValue:
-                    // Only accept the first tag value.
-                    if (!HasTagPairTagValue)
-                    {
-                        HasTagPairTagValue = true;
-                    }
-                    else
-                    {
-                        Errors.Add(new PgnErrorInfo(
-                            PgnErrorCode.MultipleTagValues,
-                            symbolStartIndex,
-                            symbolBeingYielded.ContentNode.Length));
-                    }
+                    HasTagPairTagValue = true;
                     AddTagElementToBuilder();
                     YieldContentNode = YieldInTagSectionAction;
                     break;
                 case PgnSymbolType.MoveNumber:
-                    // Switch to move tree section.
-                    CaptureTagPairIfNecessary();
-                    CaptureTagSection();
                     SymbolBuilder.Add(new GreenPgnTopLevelSymbolSyntax(symbolBeingYielded, (parent, index, green) => new PgnMoveNumberWithTriviaSyntax(parent, index, green)));
                     break;
                 case PgnSymbolType.Period:
-                    // Switch to move tree section.
-                    CaptureTagPairIfNecessary();
-                    CaptureTagSection();
                     SymbolBuilder.Add(new GreenPgnTopLevelSymbolSyntax(symbolBeingYielded, (parent, index, green) => new PgnPeriodWithTriviaSyntax(parent, index, green)));
                     break;
                 case PgnSymbolType.Move:
                 case PgnSymbolType.UnrecognizedMove:
-                    // Switch to move tree section.
-                    CaptureTagPairIfNecessary();
-                    CaptureTagSection();
                     SymbolBuilder.Add(new GreenPgnTopLevelSymbolSyntax(symbolBeingYielded, (parent, index, green) => new PgnMoveWithTriviaSyntax(parent, index, green)));
                     break;
                 case PgnSymbolType.Nag:
                 case PgnSymbolType.EmptyNag:
                 case PgnSymbolType.OverflowNag:
-                    // Switch to move tree section.
-                    CaptureTagPairIfNecessary();
-                    CaptureTagSection();
                     SymbolBuilder.Add(new GreenPgnTopLevelSymbolSyntax(symbolBeingYielded, (parent, index, green) => new PgnNagWithTriviaSyntax(parent, index, green)));
                     break;
                 case PgnSymbolType.ParenthesisOpen:
-                    // Switch to move tree section.
-                    CaptureTagPairIfNecessary();
-                    CaptureTagSection();
                     SymbolBuilder.Add(new GreenPgnTopLevelSymbolSyntax(symbolBeingYielded, (parent, index, green) => new PgnParenthesisOpenWithTriviaSyntax(parent, index, green)));
                     break;
                 case PgnSymbolType.ParenthesisClose:
-                    // Switch to move tree section.
-                    CaptureTagPairIfNecessary();
-                    CaptureTagSection();
                     SymbolBuilder.Add(new GreenPgnTopLevelSymbolSyntax(symbolBeingYielded, (parent, index, green) => new PgnParenthesisCloseWithTriviaSyntax(parent, index, green)));
                     break;
                 case PgnSymbolType.Asterisk:
                 case PgnSymbolType.DrawMarker:
                 case PgnSymbolType.WhiteWinMarker:
                 case PgnSymbolType.BlackWinMarker:
-                    CaptureTagPairIfNecessary();
-                    CaptureTagSection();
                     SymbolBuilder.Add(new GreenPgnTopLevelSymbolSyntax(symbolBeingYielded, (parent, index, green) => new PgnGameResultWithTriviaSyntax(parent, index, green)));
                     break;
                 default:
@@ -508,8 +473,11 @@
             trailingTrivia = GreenPgnTriviaSyntax.Create(TriviaBuilder, BackgroundBuilder);
             symbolBeingYielded = null;

-            CaptureTagPairIfNecessary();
-            CaptureTagSection();
+            if (YieldContentNode == YieldInTagSectionAction)
+            {
+                CaptureTagPairIfNecessary();
+                CaptureTagSection();
+            }

             return trailingTrivia;
         }


Structure PgnParser members.

Structure PgnParser members.

--- Sandra.Chess/Pgn/PgnParser.cs
+++ Sandra.Chess/Pgn/PgnParser.cs
@@ -176,63 +176,7 @@
             SymbolBuilder = new List<IGreenPgnTopLevelSyntax>();
         }

-        private void Yield(IGreenPgnSymbol symbol)
-        {
-            Errors.AddRange(symbol.GetErrors(symbolStartIndex));
-
-            var symbolType = symbol.SymbolType;
-
-            if (symbolType.IsBackground())
-            {
-                BackgroundBuilder.Add((GreenPgnBackgroundSyntax)symbol);
-            }
-            else if (symbolType.IsTrivia())
-            {
-                TriviaBuilder.Add(new GreenPgnTriviaElementSyntax(BackgroundBuilder, (GreenPgnCommentSyntax)symbol));
-                BackgroundBuilder.Clear();
-            }
-            else
-            {
-                GreenPgnTriviaSyntax leadingTrivia = GreenPgnTriviaSyntax.Create(TriviaBuilder, BackgroundBuilder);
-
-                if (symbolType.IsTagSection())
-                {
-                    if (symbolType == PgnSymbolType.BracketOpen)
-                    {
-                        // When encountering a new '[', open a new tag pair.
-                        CaptureTagPair();
-                    }
-                    else if (symbolType == PgnSymbolType.TagName)
-                    {
-                        // Open a new tag pair if a tag name or value was seen earlier in the same tag pair.
-                        if (HasTagPairTagName || HasTagPairTagValue) CaptureTagPair();
-                        HasTagPairTagName = true;
-                    }
-                    else if (symbolType == PgnSymbolType.TagValue || symbolType == PgnSymbolType.ErrorTagValue)
-                    {
-                        // If HasTagPairTagValue was already true, this symbol is ignored.
-                        HasTagPairTagValue = true;
-                    }
-
-                    TagPairBuilder.Add(new WithTrivia<GreenPgnTagElementSyntax>(leadingTrivia, (GreenPgnTagElementSyntax)symbol));
-
-                    if (symbolType == PgnSymbolType.BracketClose)
-                    {
-                        // When encountering a new ']', always close this tag pair.
-                        CaptureTagPair();
-                    }
-                }
-                else
-                {
-                    CaptureTagPair();
-                    CaptureTagSection();
-                    SymbolBuilder.Add(new GreenPgnTopLevelSymbolSyntax(leadingTrivia, symbol));
-                }
-
-                BackgroundBuilder.Clear();
-                TriviaBuilder.Clear();
-            }
-        }
+        #region Tag section parsing

         private void CaptureTagPair()
         {
@@ -251,6 +195,68 @@
             {
                 SymbolBuilder.Add(new GreenPgnTagSectionSyntax(TagSectionBuilder));
                 TagSectionBuilder.Clear();
+            }
+        }
+
+        #endregion Tag section parsing
+
+        #region Yield tokens and EOF
+
+        private void Yield(IGreenPgnSymbol symbol)
+        {
+            Errors.AddRange(symbol.GetErrors(symbolStartIndex));
+
+            var symbolType = symbol.SymbolType;
+
+            if (symbolType.IsBackground())
+            {
+                BackgroundBuilder.Add((GreenPgnBackgroundSyntax)symbol);
+            }
+            else if (symbolType.IsTrivia())
+            {
+                TriviaBuilder.Add(new GreenPgnTriviaElementSyntax(BackgroundBuilder, (GreenPgnCommentSyntax)symbol));
+                BackgroundBuilder.Clear();
+            }
+            else
+            {
+                GreenPgnTriviaSyntax leadingTrivia = GreenPgnTriviaSyntax.Create(TriviaBuilder, BackgroundBuilder);
+
+                if (symbolType.IsTagSection())
+                {
+                    if (symbolType == PgnSymbolType.BracketOpen)
+                    {
+                        // When encountering a new '[', open a new tag pair.
+                        CaptureTagPair();
+                    }
+                    else if (symbolType == PgnSymbolType.TagName)
+                    {
+                        // Open a new tag pair if a tag name or value was seen earlier in the same tag pair.
+                        if (HasTagPairTagName || HasTagPairTagValue) CaptureTagPair();
+                        HasTagPairTagName = true;
+                    }
+                    else if (symbolType == PgnSymbolType.TagValue || symbolType == PgnSymbolType.ErrorTagValue)
+                    {
+                        // If HasTagPairTagValue was already true, this symbol is ignored.
+                        HasTagPairTagValue = true;
+                    }
+
+                    TagPairBuilder.Add(new WithTrivia<GreenPgnTagElementSyntax>(leadingTrivia, (GreenPgnTagElementSyntax)symbol));
+
+                    if (symbolType == PgnSymbolType.BracketClose)
+                    {
+                        // When encountering a new ']', always close this tag pair.
+                        CaptureTagPair();
+                    }
+                }
+                else
+                {
+                    CaptureTagPair();
+                    CaptureTagSection();
+                    SymbolBuilder.Add(new GreenPgnTopLevelSymbolSyntax(leadingTrivia, symbol));
+                }
+
+                BackgroundBuilder.Clear();
+                TriviaBuilder.Clear();
             }
         }

@@ -259,6 +265,10 @@
             CaptureTagPair();
             CaptureTagSection();
         }
+
+        #endregion Yield tokens and EOF
+
+        #region Lexing

         [MethodImpl(MethodImplOptions.AggressiveInlining)]
         private void YieldPgnSymbol(ref PgnSymbolStateMachine symbolBuilder, string pgnText, int symbolStartIndex, int length)
@@ -703,5 +713,7 @@
             else if (!overflowNag) Yield(new GreenPgnNagSyntax((PgnAnnotation)annotationValue, length - symbolStartIndex));
             else Yield(new GreenPgnOverflowNagSyntax(pgnText.Substring(symbolStartIndex, currentIndex - symbolStartIndex)));
         }
+
+        #endregion Lexing
     }
 }


Emulate window menu in the globe menu dropdown.

--- Sandra.UI/MdiContainerForm.cs
+++ Sandra.UI/MdiContainerForm.cs
@@ -55,13 +55,20 @@
             if (Session.Current.RegisteredLocalizers.Count() >= 2)
             {
                 // More than one localizer: can switch between them.
-                var langMenu = new List<Union<DefaultUIActionBinding, MainMenuDropDownItem>>();
-                langMenu.AddRange(Session.Current.RegisteredLocalizers.Select(x => (Union<DefaultUIActionBinding, MainMenuDropDownItem>)x.SwitchToLangUIActionBinding));
+                var langWindowMenu = new List<Union<DefaultUIActionBinding, MainMenuDropDownItem>>();
+                langWindowMenu.AddRange(Session.Current.RegisteredLocalizers.Select(x => (Union<DefaultUIActionBinding, MainMenuDropDownItem>)x.SwitchToLangUIActionBinding));
+
+                langWindowMenu.Add(SharedUIAction.WindowMenuRestore);
+                langWindowMenu.Add(SharedUIAction.WindowMenuMove);
+                langWindowMenu.Add(SharedUIAction.WindowMenuSize);
+                langWindowMenu.Add(SharedUIAction.WindowMenuMinimize);
+                langWindowMenu.Add(SharedUIAction.WindowMenuMaximize);
+                langWindowMenu.Add(SharedUIAction.Close);

                 mainMenuRootNodes.Add(new MainMenuDropDownItem
                 {
                     Container = new UIMenuNode.Container(null, SharedResources.globe.ToImageProvider()),
-                    DropDownItems = langMenu
+                    DropDownItems = langWindowMenu
                 });
             }


bugfix

bugfix

--- Scripts/DapCore/core_/Pass.cs
+++ Scripts/DapCore/core_/Pass.cs
@@ -53,7 +53,7 @@
         }

         public bool CheckWritePass(Pass pass) {
-            if (_AllowWrite) {
+            if (_Writable) {
                 return true;
             }
             return CheckAdminPass(pass);


Fix wrong database name for set multi user

--- Serenity.Testing/DbManager.cs
+++ Serenity.Testing/DbManager.cs
@@ -1,11 +1,11 @@
-using Serenity.Data;
-using System;
+using System;
 using System.Collections.Generic;
 using System.Data;
 using System.Data.SqlClient;
 using System.IO;
 using System.Security.Cryptography;
 using System.Text;
+using Serenity.Data;

 namespace Serenity.Testing
 {
@@ -44,8 +44,8 @@
                     "if db_id('{0}') is not null\n" +
                     "BEGIN\n" +
                     "ALTER DATABASE [{0}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;" +
-                    "ALTER DATABASE [{0}] MODIFY NAME = {1};" +
-                    "ALTER DATABASE [{0}] SET MULTI_USER;" +
+                    "ALTER DATABASE [{0}] MODIFY NAME = [{1}];" +
+                    "ALTER DATABASE [{1}] SET MULTI_USER;" +
                     "END\n", oldAlias, newAlias));
             }
         }


Fixed the TKMK00 bug that dropped half the textures while loading them

--- Services/MarioKart64Reader.cs
+++ Services/MarioKart64Reader.cs
@@ -21,7 +21,8 @@
             //Now read the different data bits here, if they haven't been read in yet
             for (int i = 0; i < MarioKartRomInfo.TKMK00TextureLocations.Length; i++)
             {
-                if (!RomProject.Instance.Files[0].HasElementExactlyAt(MarioKartRomInfo.TKMK00TextureLocations[i].RomOffset))
+                N64DataElement preExistingElement = RomProject.Instance.Files[0].GetElementAt(MarioKartRomInfo.TKMK00TextureLocations[i].RomOffset);
+                if (preExistingElement != null && preExistingElement.GetType() == typeof(UnknownData))
                 {
                     ushort alpha = MarioKartRomInfo.TKMK00TextureLocations[i].AlphaColor;
                     int offset = MarioKartRomInfo.TKMK00TextureLocations[i].RomOffset;


Whitespace fixes.

Whitespace fixes.

--- Settings/OptionsDialogPage.cs
+++ Settings/OptionsDialogPage.cs
@@ -24,7 +24,7 @@
 {
 	public class OptionsDialogPage : Rhino.UI.OptionsDialogPage
 	{
-    public OptionsDialogPage() : base("Cycles")
+		public OptionsDialogPage() : base("Cycles")
 		{
 			CollapsibleSectionHolder = new OptionsDialogCollapsibleSectionUIPanel();
 		}
@@ -33,14 +33,14 @@

 		public override bool ShowApplyButton => false;
 		public override bool ShowDefaultsButton => true;
-    public override string LocalPageTitle => Localization.LocalizeString ("Cycles", 7);
+		public override string LocalPageTitle => Localization.LocalizeString("Cycles", 7);

-    public override Image PageImage {
-      get {
-        var icon = Properties.Resources.Cycles_viewport_properties;
-        return icon.ToBitmap ();
-      }
-    }
+		public override Image PageImage {
+			get {
+				var icon = Properties.Resources.Cycles_viewport_properties;
+				return icon.ToBitmap();
+			}
+		}

 		public override void OnDefaults()
 		{


Test for more complicated patch

Test for more complicated patch

--- SharpDiff.Tests/PatchTests.cs
+++ SharpDiff.Tests/PatchTests.cs
@@ -134,6 +134,80 @@

             Assert.That(output, Is.EqualTo(""));
         }
+
+        [Test]
+        public void AdditionsAndRemovalsInSingleFile()
+        {
+            var patch = new Patch(
+                new Diff(null, new[]
+                {
+                    new Chunk(
+                        new ChunkRange(new ChangeRange(3, 9), new ChangeRange(3, 12)), new ILine[]
+                        {
+                            new ContextLine("this"),
+                            new ContextLine("is"),
+                            new ContextLine("a"),
+                            new AdditionLine("here"),
+                            new AdditionLine("are"),
+                            new ContextLine("load"),
+                            new ContextLine("of"),
+                            new SubtractionLine("new"),
+                            new AdditionLine("some"),
+                            new AdditionLine("additions"),
+                            new ContextLine("lines"),
+                            new ContextLine("for"),
+                            new ContextLine("complicating")
+                        }),
+                })
+            );
+
+            //@@ -3,9 +3,12 @@
+            // this
+            // is
+            // a
+            //+here
+            //+are
+            // load
+            // of
+            //-new
+            //+some
+            //+additions
+            // lines
+            // for
+            // complicating
+
+            patch.File = new StubFileAccessor(
+                "hello\r\n" +
+                "there\r\n" +
+                "this\r\n" +
+                "is\r\n" +
+                "a\r\n" +
+                "load\r\n" +
+                "of\r\n" +
+                "new\r\n" +
+                "lines\r\n" +
+                "for\r\n" +
+                "complicating\r\n" +
+                "matters\r\n");
+            var output = patch.ApplyTo("fake path");
+
+            Assert.That(output, Is.EqualTo(
+                "hello\r\n" +
+                "there\r\n" +
+                "this\r\n" +
+                "is\r\n" +
+                "a\r\n" +
+                "here\r\n" +
+                "are\r\n" +
+                "load\r\n" +
+                "of\r\n" +
+                "some\r\n" +
+                "additions\r\n" +
+                "lines\r\n" +
+                "for\r\n" +
+                "complicating\r\n" +
+                "matters\r\n"));
+        }
     }

     internal class StubFileAccessor : IFileAccessor


Revert Formatting.Indented on JSON serialization.

--- SharpRaven/Data/JsonPacket.cs
+++ SharpRaven/Data/JsonPacket.cs
@@ -176,7 +176,7 @@
         /// <returns>json string</returns>
         public string Serialize()
         {
-            return JsonConvert.SerializeObject(this, Formatting.Indented);
+            return JsonConvert.SerializeObject(this);

             //return @"{""project"": ""SharpRaven"",""event_id"": ""fc6d8c0c43fc4630ad850ee518f1b9d0"",""culprit"": ""my.module.function_name"",""timestamp"": ""2012-11-11T17:41:36"",""message"": ""SyntaxError: Wattttt!"",""sentry.interfaces.Exception"": {""type"": ""SyntaxError"",""value"": ""Wattttt!"",""module"": ""__builtins__""}""}";
         }


cleanup file creation

cleanup file creation

--- Shoutr.Integration/Program.cs
+++ Shoutr.Integration/Program.cs
@@ -148,24 +148,40 @@
             var inputFilePath = "test.7z";
             await broadcaster.BroadcastFile(inputFilePath, transporter, streamFactory, cancellationToken: cts.Token);

-            await listenTask;
-
-            var inputFile = new FileInfo(inputFilePath);
-
-            var outputFile = new FileInfo(outputFilePath);
-            Assert.IsTrue(outputFile.Exists);
-
-            Assert.AreEqual(inputFile.Length, outputFile.Length);
-
-            var inputBytes = File.ReadAllBytes(inputFilePath);
-            var outputBytes = File.ReadAllBytes(outputFilePath);
-            using (var md5 = MD5.Create())
-            {
-                var inputHash = md5.ComputeHash(inputBytes);
-                var outputHash = md5.ComputeHash(outputBytes);
-                CollectionAssert.AreEqual(inputHash, outputHash);
-            }
-            CollectionAssert.AreEqual(inputBytes, outputBytes);
+            try
+            {
+                await listenTask;
+
+                var inputFile = new FileInfo(inputFilePath);
+
+                var outputFile = new FileInfo(outputFilePath);
+                Assert.IsTrue(outputFile.Exists);
+
+                Assert.AreEqual(inputFile.Length, outputFile.Length);
+
+                var inputBytes = File.ReadAllBytes(inputFilePath);
+                var outputBytes = File.ReadAllBytes(outputFilePath);
+                using (var md5 = MD5.Create())
+                {
+                    var inputHash = md5.ComputeHash(inputBytes);
+                    var outputHash = md5.ComputeHash(outputBytes);
+                    CollectionAssert.AreEqual(inputHash, outputHash);
+                }
+                CollectionAssert.AreEqual(inputBytes, outputBytes);
+            }
+            finally
+            {
+                if (!string.IsNullOrWhiteSpace(outputFilePath))
+                {
+                    var outputFile = new FileInfo(outputFilePath);
+                    outputFile.Refresh();
+                    if (outputFile.Exists)
+                    {
+                        outputFile.Delete();
+                    }
+                }
+
+            }
         }

         private static void Register(UnityContainer container)


Enabled overriding TextFile properties and functions

--- SkyEditor.Core/IO/TextFile.cs
+++ SkyEditor.Core/IO/TextFile.cs
@@ -8,30 +8,30 @@
 {
     public class TextFile : ICreatableFile, IOpenableFile, ISavableAs, IDetectableFileType
     {
-        public string Filename { get; set; }
+        public virtual string Filename { get; set; }

-        public string Name { get; set; }
+        public virtual string Name { get; set; }

-        public string Contents { get; set; }
+        public virtual string Contents { get; set; }

         public event EventHandler FileSaved;

-        public void CreateFile(string name)
+        public virtual void CreateFile(string name)
         {
             this.Name = name;
         }

-        public string GetDefaultExtension()
+        public virtual string GetDefaultExtension()
         {
             return "*.txt";
         }

-        public IEnumerable<string> GetSupportedExtensions()
+        public virtual IEnumerable<string> GetSupportedExtensions()
         {
             return new string[] { "*.txt" };
         }

-        public Task OpenFile(string filename, IIOProvider provider)
+        public virtual Task OpenFile(string filename, IIOProvider provider)
         {
             this.Contents = provider.ReadAllText(filename);
             this.Filename = filename;
@@ -39,12 +39,12 @@
             return Task.CompletedTask;
         }

-        public async Task Save(IIOProvider provider)
+        public virtual async Task Save(IIOProvider provider)
         {
             await Save(Filename, provider);
         }

-        public Task Save(string filename, IIOProvider provider)
+        public virtual Task Save(string filename, IIOProvider provider)
         {
             provider.WriteAllText(filename, Contents);
             this.Filename = filename;
@@ -52,7 +52,7 @@
             return Task.CompletedTask;
         }

-        public async Task<bool> IsOfType(GenericFile file)
+        public virtual async Task<bool> IsOfType(GenericFile file)
         {
             for (int i = 0;i < file.Length;i++)
             {


added kinte origins

added kinte origins

--- Songhay/Models/CorsOrigins.cs
+++ Songhay/Models/CorsOrigins.cs
@@ -38,7 +38,12 @@
         /// <summary>
         /// Uri <see cref="string"/> constant
         /// </summary>
-        public const string KintespaceCom = "http://kintespace.com";
+        public const string KinteSpaceAzure = "http://kintespace.azurewebsites.net";
+
+        /// <summary>
+        /// Uri <see cref="string"/> constant
+        /// </summary>
+        public const string KinteSpaceCom = "http://kintespace.com";

         /// <summary>
         /// Uri <see cref="string"/> constant


Improve test generation

Improve test generation

--- Wkx.TestGenerator/Program.cs
+++ Wkx.TestGenerator/Program.cs
@@ -44,33 +44,40 @@

                         foreach (var testInput in testDimension.Value.ToObject<JObject>())
                         {
-                            command.CommandText = GenerateTestSql(geometryFormats);
+                            JObject testOutput = new JObject();
+                            JObject testOutputResult = new JObject();

-                            command.Parameters.Clear();
-                            command.Parameters.Add(new NpgsqlParameter("input", testInput.Value.Value<string>()));
+                            dimension[testInput.Key] = testOutput;

-                            using (NpgsqlDataReader reader = command.ExecuteReader())
+                            foreach (GeometryFormat geometryFormat in geometryFormats)
                             {
-                                reader.Read();
+                                command.CommandText = GenerateTestSql(geometryFormat);

-                                JObject testOutput = new JObject();
-                                JObject testOutputResult = new JObject();
+                                command.Parameters.Clear();
+                                command.Parameters.Add(new NpgsqlParameter("input", testInput.Value.Value<string>()));

-                                dimension[testInput.Key] = testOutput;
+                                try
+                                {
+                                    using (NpgsqlDataReader reader = command.ExecuteReader())
+                                    {
+                                        reader.Read();
+
+                                        testOutput[geometryFormat.Name] = reader.GetString(reader.GetOrdinal(geometryFormat.Name));

-                                foreach (GeometryFormat geometryFormat in geometryFormats)
+                                        string result = reader.GetString(reader.GetOrdinal(geometryFormat.Name + "result"));
+
+                                        if (testInput.Value.Value<string>() != result)
+                                            testOutputResult[geometryFormat.Name] = result;
+                                    }
+                                }
+                                catch (PostgresException)
                                 {
-                                    testOutput[geometryFormat.Name] = reader.GetString(reader.GetOrdinal(geometryFormat.Name));
+                                    testOutput[geometryFormat.Name] = null;
+                                }
+                            }

-                                    string result = reader.GetString(reader.GetOrdinal(geometryFormat.Name + "result"));
-
-                                    if (testInput.Value.Value<string>() != result)
-                                        testOutputResult[geometryFormat.Name] = result;
-                                }
-
-                                if (testOutputResult.Count > 0)
-                                    testOutput["results"] = testOutputResult;
-                            }
+                            if (testOutputResult.Count > 0)
+                                testOutput["results"] = testOutputResult;
                         }
                     }
                 }
@@ -79,9 +86,9 @@
             File.WriteAllText("../../../Wkx.Tests/testdata.json", JsonConvert.SerializeObject(testOutputData, Formatting.Indented));
         }

-        private static string GenerateTestSql(IEnumerable<GeometryFormat> geometryFormats)
+        private static string GenerateTestSql(GeometryFormat geometryFormat)
         {
-            return "SELECT " + string.Join(", \r\n", geometryFormats.Select(t => t.GenerateSql()));
+            return "SELECT " + geometryFormat.GenerateSql();
         }
     }
 }


Set up client, settings, logging, and connection

--- Wycademy/Wycademy/Program.cs
+++ Wycademy/Wycademy/Program.cs
@@ -1,4 +1,6 @@
-using System;
+using Discord;
+using Discord.Commands;
+using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;
@@ -8,8 +10,53 @@
 {
     class Program
     {
-        static void Main(string[] args)
+        //Call Start() so that the bot runs in a non static method
+        static void Main(string[] args) => new Program().Start();
+
+        private DiscordClient _client;
+
+        public void Start()
         {
+            //Set basic settings
+            _client = new DiscordClient(x =>
+            {
+                x.AppName = "Wycademy";
+                x.LogLevel = LogSeverity.Info;
+                x.LogHandler = Log;
+            })
+            .UsingCommands(x =>
+            {
+                x.PrefixChar = '<';
+                x.HelpMode = HelpMode.Private;
+            });
+
+            //Set up message logging
+            _client.MessageReceived += (s, e) =>
+            {
+                if (e.Message.IsAuthor)
+                {
+                    _client.Log.Info(">>Message", $"{((e.Server != null) ? e.Server.Name : "Private")}/#{((!e.Channel.IsPrivate) ? e.Channel.Name : "")} by {e.User.Name}");
+                }
+                else if (!e.Message.IsAuthor)
+                {
+                    _client.Log.Info("<<Message", $"{((e.Server != null) ? e.Server.Name : "Private")}/#{((!e.Channel.IsPrivate) ? e.Channel.Name : "")} by {e.User.Name}");
+                }
+            };
+
+            //Bot token is stored in an environment variable so that nobody sees it when I push to GitHub :D
+            string token = Environment.GetEnvironmentVariable("WYCADEMY_TOKEN", EnvironmentVariableTarget.User);
+
+            //Connect to all guilds that the bot is part of and then block until the bot is manually exited.
+            _client.ExecuteAndWait(async () =>
+            {
+                await _client.Connect(token);
+            });
+        }
+
+        //Whenever we log data, this method is called.
+        private void Log(object sender, LogMessageEventArgs e)
+        {
+            Console.WriteLine($"[{e.Severity}] [{e.Source}] {e.Message}");
         }
     }
 }


Fixed naming inconsistency

Fixed naming inconsistency

--- src/Xablu.WebApiClient/Services/GraphQL/MutationRequest.cs
+++ src/Xablu.WebApiClient/Services/GraphQL/MutationRequest.cs
@@ -159,7 +159,7 @@
             if (mutationDetail != null && !string.IsNullOrEmpty(variableInputName))
             {
                 var parameterInputName = parameterInputList[0];
-                inputString = $"(${ToLowerFirstChar(parameterInputName)}: {variableInputName}!)" + $"{{{mutationDetail.MutationName}({mutationDetail.MutationParameterName}: ${parameterInputName})";
+                inputString = $"(${ToLowerFirstChar(parameterInputName)}: {variableInputName}!)" + $"{{{mutationDetail.MutationName}({mutationDetail.MutationParameterName}: ${ToLowerFirstChar(parameterInputName)})";
             }
             return inputString;
         }


Start implementing ChaumianCoinJoinTestsAsync

--- WalletWasabi.Tests/RegTests.cs
+++ WalletWasabi.Tests/RegTests.cs
@@ -1425,7 +1425,15 @@
 			}
 		}

+		[Fact]
+		public async Task ChaumianCoinJoinTestsAsync() // These tests are taken from HiddenWallet, they were tests on the testnet.
+		{
+			var network = Global.RpcClient.Network;
+
+
+		}
+
 		#endregion
-
+
 	}
 }


(GH-231) nupkg should be created in current directory

When running choco pack, the resulting nupkg used to be created in the current
directory and not necessarily in the same directory as the nuspec file. The
previous behavior is preferred. Allow for the package to be created in the
current working directory instead of the nuspec directory.

--- src/chocolatey/infrastructure.app/services/NugetService.cs
+++ src/chocolatey/infrastructure.app/services/NugetService.cs
@@ -160,7 +160,7 @@
             }

             string outputFile = builder.Id + "." + builder.Version + Constants.PackageExtension;
-            string outputPath = _fileSystem.combine_paths(nuspecDirectory, outputFile);
+            string outputPath = _fileSystem.combine_paths(_fileSystem.get_current_directory(), outputFile);

             this.Log().Info(() => "Attempting to build package from '{0}'.".format_with(_fileSystem.get_file_name(nuspecFilePath)));