ArrayExtensions tidy-up

ArrayExtensions tidy-up

--- src/Kirkin/Linq/ArrayExtensions.cs
+++ src/Kirkin/Linq/ArrayExtensions.cs
@@ -1,7 +1,8 @@
 namespace System.Linq
 {
     /// <summary>
-    /// LINQ extension method overrides that offer greater efficiency for arrays than the standard LINQ methods.
+    /// LINQ extension method overrides that offer greater
+    /// efficiency for arrays than the standard LINQ methods.
     /// </summary>
     public static class ArrayExtensions
     {
@@ -26,9 +27,9 @@
         {
             if (predicate == null) throw new ArgumentNullException(nameof(predicate));

-            for (int i = 0; i < array.Length; i++)
-            {
-                if (predicate(array[i])) {
+            foreach (T item in array)
+            {
+                if (predicate(item)) {
                     return true;
                 }
             }
@@ -44,9 +45,9 @@
         {
             if (predicate == null) throw new ArgumentNullException(nameof(predicate));

-            for (int i = 0; i < array.Length; i++)
-            {
-                if (!predicate(array[i])) {
+            foreach (T item in array)
+            {
+                if (!predicate(item)) {
                     return false;
                 }
             }
@@ -79,10 +80,10 @@
         {
             if (predicate == null) throw new ArgumentNullException(nameof(predicate));

-            foreach (T v in array)
-            {
-                if (predicate(v)) {
-                    return v;
+            foreach (T item in array)
+            {
+                if (predicate(item)) {
+                    return item;
                 }
             }

@@ -114,10 +115,10 @@
         {
             if (predicate == null) throw new ArgumentNullException(nameof(predicate));

-            foreach (T v in array)
-            {
-                if (predicate(v)) {
-                    return v;
+            foreach (T item in array)
+            {
+                if (predicate(item)) {
+                    return item;
                 }
             }

@@ -144,16 +145,16 @@
             bool first = true;
             T result = default(T);

-            foreach (T v in array)
-            {
-                if (predicate(v))
+            foreach (T item in array)
+            {
+                if (predicate(item))
                 {
                     if (!first) {
                         Enumerable.Single(array); // LINQ exception.
                     }

                     first = false;
-                    result = v;
+                    result = item;
                 }
             }

@@ -185,16 +186,16 @@
             bool first = true;
             T result = default(T);

-            foreach (T v in array)
-            {
-                if (predicate(v))
+            foreach (T item in array)
+            {
+                if (predicate(item))
                 {
                     if (!first) {
-                        Enumerable.Single(array); // throw the same exception as LINQ would
+                        Enumerable.Single(array); // LINQ exception.
                     }

                     first = false;
-                    result = v;
+                    result = item;
                 }
             }


Avoid short form opcode.

Avoid short form opcode.

This hack eliminates the problems described in the following links:

http://www.jasonbock.net/jb/GeneratingExceptionBlocks.aspx
http://stackoverflow.com/questions/3469710/error-with-short-form-opcodes-in-reflection-emit

--- Scripting/Compiler/Bundling/CopyBody.cs
+++ Scripting/Compiler/Bundling/CopyBody.cs
@@ -185,7 +185,8 @@
                 {
                     if(!LabelOrigins.ContainsKey(i))
                         throw new Exception("No label origin found for RVA "+i.ToString("X"));
-
+
+                    Code = OpCodes.Br;
                     Gen.Emit(Code, LabelOrigins[i][0]);
                     i++;


Update

Update

--- Assets/[0]Framework/Runtime/LibTime/Time.cs
+++ Assets/[0]Framework/Runtime/LibTime/Time.cs
@@ -5,11 +5,12 @@
 {
 	public class Time : ITick, IKernel, IComponent
 	{
+		protected const float fps = 60;
 		/// <summary>
 		/// <para> Default Framework Time. Use it for independent timing</para>
 		/// </summary>
 		public static Time Default;
-		protected const float fps = 60;
+		public static int frame => UnityEngine.Time.frameCount;

 		/// <summary>
 		///   <para> The scale at which the time is passing. This can be used for slow motion effects.</para>


Bumped assembly version

Bumped assembly version

--- SimplSockets/Properties/AssemblyInfo.cs
+++ SimplSockets/Properties/AssemblyInfo.cs
@@ -20,4 +20,4 @@
 // You can specify all the values or you can default the Build and Revision Numbers
 // by using the '*' as shown below:
 // [assembly: AssemblyVersion("1.0.*")]
-[assembly: AssemblyVersion("1.4.6.*")]+[assembly: AssemblyVersion("1.4.7.*")]


Fixed test

Fixed test

--- Binance.Net.UnitTests/BinanceClientTests.cs
+++ Binance.Net.UnitTests/BinanceClientTests.cs
@@ -1043,7 +1043,6 @@
         [TestCase("ETHBTC", true)]
         [TestCase("BEETC", true)]
         [TestCase("EETC", false)]
-        [TestCase("NANOUSDTD", false)]
         [TestCase("BTC-USDT", false)]
         [TestCase("BTC-USD", false)]
         public void CheckValidBinanceSymbol(string symbol, bool isValid)


Formating comments, adding comments for fields

--- Box.V2/Managers/BoxCollaborationsManager.cs
+++ Box.V2/Managers/BoxCollaborationsManager.cs
@@ -58,13 +58,14 @@
         }

         /// <summary>
-        ///Used to edit an existing collaboration. Descriptions of the various roles can be found here
+        /// Used to edit an existing collaboration. Descriptions of the various roles can be found here
         /// </summary>
         /// <param name="collaborationRequest">
         /// collaborationRequest.Id (Required) - Id of the collaboration object
         /// collaborationRequest.Role (Required) - The access level of this collaboration
         /// collaborationRequest.Status - Whether this collaboration has been accepted
         /// </param>
+        /// <param name="fields">Attribute(s) to include in the response</param>
         /// <returns>The updated collaboration object is returned. If the role is changed to owner, the collaboration is deleted with a new one created for the previous owner and a 204 is returned.
         /// Errors may occur if the IDs are invalid or if the user does not have permissions to edit the collaboration.
         /// </returns>


Packages.config file must apparently be named as such.

--- CLR/Source/CommonBuildTools/NuGetRelated.cs
+++ CLR/Source/CommonBuildTools/NuGetRelated.cs
@@ -187,6 +187,7 @@
                         try
                         {
                            File.Delete( file );
+                           Directory.Delete( Path.GetDirectoryName( file ) );
                         }
                         catch ( Exception exc )
                         {
@@ -293,7 +294,7 @@
                var key = g.Key;
                var info = new PackagesFileInfo(
                   key.Item1,
-                  Path.Combine( Path.GetTempPath(), Guid.NewGuid().ToString() + ".config" ),
+                  Path.Combine( Path.GetTempPath(), Guid.NewGuid().ToString(), "packages.config" ),
                   key.Item2,
                   key.Item3
                   );
@@ -314,6 +315,11 @@

             try
             {
+               var dir = Path.GetDirectoryName( curFile );
+               if ( !Directory.Exists( dir ) )
+               {
+                  Directory.CreateDirectory( dir );
+               }
                new XDocument(
                   new XDeclaration( "1.0", "utf-8", "yes" ),
                   new XElement( "packages", cfg.Packages.Select( pkg =>


Section list grid view, in progress.

Section list grid view, in progress.

--- Source/Eto.Test/Eto.Test/SectionList.cs
+++ Source/Eto.Test/Eto.Test/SectionList.cs
@@ -6,10 +6,13 @@

 namespace Eto.Test
 {
-	public interface ISection
+	public interface ISectionName
 	{
 		string Text { get; }
-
+	}
+
+	public interface ISection : ISectionName
+	{
 		Control CreateContent();
 	}

@@ -22,14 +25,14 @@
 	/// and can be wrapped within a tree item (SectionTreeItem) or
 	/// any other visual representation.
 	/// </summary>
-	public class Section : List<Section>
+	public class Section : List<Section>, ISectionName
 	{
 		public string Text { get; set; }

 		public Section()
 		{
 		}
-
+
 		public Section(string text, IEnumerable<Section> sections)
 			: base (sections.OrderBy (r => r.Text, StringComparer.CurrentCultureIgnoreCase).ToArray())
 		{
@@ -187,6 +190,48 @@
 		}
 	}

+	public class SectionListGridView : SectionList
+	{
+		class MyItem
+		{
+			public string Name { get; set; }
+			public string SectionName { get; set; }
+			public Section Section { get; set; }
+		}
+
+		GridView gridView;
+		public override Control Control { get { return this.gridView; } }
+		public override ISection SelectedItem
+		{
+			get
+			{
+				var item = gridView.SelectedItem as MyItem;
+				return item != null ? item.Section as ISection: null;
+			}
+		}
+
+		public SectionListGridView(IEnumerable<Section> topNodes)
+		{
+			gridView = new GridView { ShowCellBorders = false };
+			gridView.Columns.Add(new GridColumn { HeaderText = "Name", Width = 100, AutoSize = false, DataCell = new TextBoxCell("Name"), Sortable = true });
+			gridView.Columns.Add(new GridColumn { HeaderText = "Section", DataCell = new TextBoxCell("SectionName"), Sortable = true });
+			var items = new GridItemCollection();
+			foreach (var section in topNodes)
+			{
+				foreach (var test in section)
+				{
+					items.Add(new MyItem {
+						Name = (test as ISectionName).Text,
+						SectionName = (section as ISectionName).Text,
+						Section = test,
+					});
+				}
+			}
+			gridView.DataStore = items;
+			gridView.SelectionChanged += OnSelectedItemChanged;
+		}
+	}
+
 	/// <summary>
 	/// Allows a test case to use a different generator for drawing
 	/// graphics than for windowing.


Revert change to TabControl.Controls.

Revert change to TabControl.Controls.

--- Source/Eto/Forms/Controls/TabControl.cs
+++ Source/Eto/Forms/Controls/TabControl.cs
@@ -28,14 +28,7 @@

 		public override IEnumerable<Control> Controls
 		{
-			get
-			{
-				var result = new List<Control>(); // Needed because covariance does not work on iOS
-				if (pages != null)
-					foreach (var x in pages)
-						result.Add(x);
-				return result;
-			}
+			get { return pages; }
 		}

 		public event EventHandler<EventArgs> SelectedIndexChanged;


Update help

Update help

--- src/NadekoBot/Modules/Help/Help.cs
+++ src/NadekoBot/Modules/Help/Help.cs
@@ -159,8 +159,8 @@
         public async Task Guide()
         {
             await ConfirmLocalized("guide",
-                "http://nadekobot.readthedocs.io/en/latest/Commands%20List/",
-                "http://nadekobot.readthedocs.io/en/latest/").ConfigureAwait(false);
+                "http://nadekobot.readthedocs.io/en/1.3x/Commands%20List/",
+                "http://nadekobot.readthedocs.io/en/1.3x/").ConfigureAwait(false);
         }

         [NadekoCommand, Usage, Description, Aliases]


Fix style warning in TypeCatalogue docs

Fix style warning in TypeCatalogue docs

--- Source/FakeItEasy/Core/TypeCatalogue.cs
+++ Source/FakeItEasy/Core/TypeCatalogue.cs
@@ -20,7 +20,7 @@
         private readonly List<Type> availableTypes = new List<Type>();

         /// <summary>
-        /// Gets the <c>FakeItEasy</c> assembly
+        /// Gets the <c>FakeItEasy</c> assembly.
         /// </summary>
         public static Assembly FakeItEasyAssembly
         {


Update Help.cs

Update Help.cs

--- src/NadekoBot/Modules/Help/Help.cs
+++ src/NadekoBot/Modules/Help/Help.cs
@@ -104,14 +104,15 @@
             if (alias != null)
                 str += $" / `{alias}`";
                 var embed = new EmbedBuilder()
-                .WithAuthor(eau => eau.WithName("Help")
+                .WithAuthor(eau => eau.WithName("Command")
                 .WithUrl("http://nadekobot.readthedocs.io/en/latest/Commands%20List/")
                 .WithIconUrl(NadekoBot.Client.GetCurrentUser().AvatarUrl))
+                .WithDescription(str)
                 //.WithTitle(str)
                 //.WithDescription($"{ string.Format(com.Summary, com.Module.Prefix)}{ GetCommandRequirements(com)}")
-                .AddField(fb => fb.WithIndex(1).WithName("**Command**").WithValue(str).WithIsInline(true))
+                //.AddField(fb => fb.WithIndex(1).WithName("**Command**").WithValue(str).WithIsInline(true))
                 .AddField(fb => fb.WithIndex(2).WithName("**Usage**").WithValue($"{string.Format(com.Remarks, com.Module.Prefix)}").WithIsInline(true))
-                .AddField(fb => fb.WithIndex(3).WithName("Description").WithValue($"{ string.Format(com.Summary, com.Module.Prefix)}{ GetCommandRequirements(com)}").WithIsInline(false))
+                .AddField(fb => fb.WithIndex(3).WithName("**Description**").WithValue($"{ string.Format(com.Summary, com.Module.Prefix)}{ GetCommandRequirements(com)}").WithIsInline(true))
                 .WithColor(NadekoBot.OkColor);
             if (com != null)
                 await channel.EmbedAsync(embed.Build()).ConfigureAwait(false);


Minor doc change.

Minor doc change.

--- Source/Magick.NET/Core/Types/Density.cs
+++ Source/Magick.NET/Core/Types/Density.cs
@@ -221,7 +221,7 @@
     /// </summary>
     /// <param name="width">The width in cm or inches.</param>
     /// <param name="height">The height in cm or inches.</param>
-    /// <returns>A <see cref="MagickGeometry"/> based on the specified width and height.</returns>
+    /// <returns>A <see cref="MagickGeometry"/> based on the specified width and height in cm or inches.</returns>
     public MagickGeometry ToGeometry(double width, double height)
     {
       int pixelWidth = (int)(width * X);


PYTHON27 option added and readability of the Exceptions class improvements as we look toward version 2.7 ...

--- pythonnet/src/runtime/exceptions.cs
+++ pythonnet/src/runtime/exceptions.cs
@@ -31,7 +31,7 @@
         internal ExceptionClassObject(Type tp) : base(tp) {
         }

-#if (PYTHON25 || PYTHON26)
+#if (PYTHON25 || PYTHON26 || PYTHON27)
         internal static Exception ToException(IntPtr ob) {
             CLRObject co = GetManagedObject(ob) as CLRObject;
             if (co == null) {
@@ -114,23 +114,26 @@

             return Runtime.PyObject_GenericGetAttr(ob, key);
         }
-#endif
+#endif      // (PYTHON25 || PYTHON26 || PYTHON27)
     }

     /// <summary>
     /// Encapsulates the Python exception APIs.
     /// </summary>
+    /// <remarks>
+    /// Readability of the Exceptions class improvements as we look toward version 2.7 ...
+    /// </remarks>

     public class Exceptions {
+
+        internal static IntPtr warnings_module;
+        internal static IntPtr exceptions_module;

         private Exceptions() {}

         //===================================================================
         // Initialization performed on startup of the Python runtime.
         //===================================================================
-
-        internal static IntPtr warnings_module;
-        internal static IntPtr exceptions_module;

         internal static void Initialize() {
             exceptions_module = Runtime.PyImport_ImportModule("exceptions");
@@ -200,10 +203,20 @@
         // this-at-home hackery) delegates to the managed exception and
         // obeys the conventions of both Python and managed exceptions.

+        /// <remarks>
+        /// Conditionally initialized variables!
+        /// </remarks>
         static IntPtr ns_exc; // new-style class for System.Exception
         static IntPtr os_exc; // old-style class for System.Exception
         static Hashtable cache;

+        /// <remarks>
+        /// the lines
+        /// // XXX - hack to raise a compatible old-style exception ;(
+        /// if (Runtime.wrap_exceptions) {
+        ///     CallOneOfTheseMethods();
+        ///
+        /// </remarks>
         internal static void SetupExceptionHack() {
             ns_exc = ClassManager.GetClass(typeof(Exception)).pyHandle;
             cache = new Hashtable();
@@ -546,63 +559,79 @@
             return IntPtr.Zero;
         }

-
+        // 2010-11-16: Arranged in python (2.6 & 2.7) source header file order
+        /* Predefined exceptions are
+           puplic static variables on the Exceptions class filled in from
+           the python class using reflection in Initialize() looked up by
+		   name, not posistion. */
+#if (PYTHON25 || PYTHON26 || PYTHON27)
+        public static IntPtr BaseException;
+#endif
+        public static IntPtr Exception;
+        public static IntPtr StopIteration;
+#if (PYTHON25 || PYTHON26 || PYTHON27)
+        public static IntPtr GeneratorExit;
+#endif
+        public static IntPtr StandardError;
         public static IntPtr ArithmeticError;
+        public static IntPtr LookupError;
+
         public static IntPtr AssertionError;
         public static IntPtr AttributeError;
-#if (PYTHON25 || PYTHON26)
-        public static IntPtr BaseException;
-#endif
-        public static IntPtr DeprecationWarning;
         public static IntPtr EOFError;
+        public static IntPtr FloatingPointError;
         public static IntPtr EnvironmentError;
-        public static IntPtr Exception;
-        public static IntPtr FloatingPointError;
-        public static IntPtr FutureWarning;
-#if (PYTHON25 || PYTHON26)
-        public static IntPtr GeneratorExit;
-#endif
         public static IntPtr IOError;
+        public static IntPtr OSError;
         public static IntPtr ImportError;
-#if (PYTHON25 || PYTHON26)
-        public static IntPtr ImportWarning;
-#endif
-        public static IntPtr IndentationError;
         public static IntPtr IndexError;
         public static IntPtr KeyError;
         public static IntPtr KeyboardInterrupt;
-        public static IntPtr LookupError;
         public static IntPtr MemoryError;
         public static IntPtr NameError;
+        public static IntPtr OverflowError;
+        public static IntPtr RuntimeError;
         public static IntPtr NotImplementedError;
-        public static IntPtr OSError;
-        public static IntPtr OverflowError;
-        public static IntPtr PendingDeprecationWarning;
+        public static IntPtr SyntaxError;
+        public static IntPtr IndentationError;
+        public static IntPtr TabError;
         public static IntPtr ReferenceError;
-        public static IntPtr RuntimeError;
-        public static IntPtr RuntimeWarning;
-        public static IntPtr StandardError;
-        public static IntPtr StopIteration;
-        public static IntPtr SyntaxError;
-        public static IntPtr SyntaxWarning;
         public static IntPtr SystemError;
         public static IntPtr SystemExit;
-        public static IntPtr TabError;
         public static IntPtr TypeError;
         public static IntPtr UnboundLocalError;
+        public static IntPtr UnicodeError;
+        public static IntPtr UnicodeEncodeError;
         public static IntPtr UnicodeDecodeError;
-        public static IntPtr UnicodeEncodeError;
-        public static IntPtr UnicodeError;
         public static IntPtr UnicodeTranslateError;
-#if (PYTHON25 || PYTHON26)
+        public static IntPtr ValueError;
+        public static IntPtr ZeroDivisionError;
+//#ifdef MS_WINDOWS
+        //public static IntPtr WindowsError;
+//#endif
+//#ifdef __VMS
+        //public static IntPtr VMSError;
+//#endif
+
+        //PyAPI_DATA(PyObject *) PyExc_BufferError;
+
+        //PyAPI_DATA(PyObject *) PyExc_MemoryErrorInst;
+        //PyAPI_DATA(PyObject *) PyExc_RecursionErrorInst;
+
+
+        /* Predefined warning categories */
+        public static IntPtr Warning;
+        public static IntPtr UserWarning;
+        public static IntPtr DeprecationWarning;
+        public static IntPtr PendingDeprecationWarning;
+        public static IntPtr SyntaxWarning;
+        public static IntPtr RuntimeWarning;
+        public static IntPtr FutureWarning;
+#if (PYTHON25 || PYTHON26 || PYTHON27)
+        public static IntPtr ImportWarning;
         public static IntPtr UnicodeWarning;
+        //PyAPI_DATA(PyObject *) PyExc_BytesWarning;
 #endif
-        public static IntPtr UserWarning;
-        public static IntPtr ValueError;
-        public static IntPtr Warning;
-        //public static IntPtr WindowsError;
-        public static IntPtr ZeroDivisionError;
-
     }


Update for 5.20

Update for 5.20

--- LESs/MainWindow.xaml.cs
+++ LESs/MainWindow.xaml.cs
@@ -21,7 +21,7 @@
     /// </summary>
     public partial class MainWindow : Window
     {
-        private const string INTENDED_VERSION = "0.0.1.161";
+        private const string INTENDED_VERSION = "0.0.1.162";
         public static string current_version;

         private readonly BackgroundWorker _worker = new BackgroundWorker();
@@ -490,4 +490,4 @@
             window.Show();
         }
     }
-}+}


Don't default sort the reports table.

Don't default sort the reports table.

--- CRP.Mvc/Views/ItemManagement/Details.cshtml
+++ CRP.Mvc/Views/ItemManagement/Details.cshtml
@@ -75,7 +75,6 @@
                 ]
             });
             $("#table-Reports").dataTable({
-                "sorting": [[1, "desc"]], //Default sort on second column
                 "columnDefs": [
                     { 'orderable': false, 'targets': [0] }, //Disables sort on icon columns
                 ]


Align with online sample

Align with online sample

--- CSharp7/CSharp7/7.1/2.DefaultExpressions.cs
+++ CSharp7/CSharp7/7.1/2.DefaultExpressions.cs
@@ -9,7 +9,7 @@
         {
             int? DoSomeWorkAndGetResult(int a = default, string s = default)
             {
-                if (s == default || s is default)
+                if (s == default && s is default)
                 {
                     return default;
                 }


Fixes RadioButton rendering Fixes CheckBox glyph rendering

--- Cairo/Perspex.Cairo/Media/DrawingContext.cs
+++ Cairo/Perspex.Cairo/Media/DrawingContext.cs
@@ -118,27 +118,17 @@
         {
             var impl = geometry.PlatformImpl as StreamGeometryImpl;
             var clone = new Queue<GeometryOp>(impl.Operations);
-
-            bool useFill = false;

-            this.SetPen(pen);
-            this.SetBrush(brush);
-
             using (var pop = this.PushTransform(impl.Transform))
             {
                 while (clone.Count > 0)
                 {
-
                     var current = clone.Dequeue();

                     if (current is BeginOp)
                     {
                         var bo = current as BeginOp;
                         this.context.MoveTo(bo.Point.ToCairo());
-
-                        useFill = bo.IsFilled;
-
-                        System.Diagnostics.Debug.WriteLine("Start");
                     }
                     else if (current is LineToOp)
                     {
@@ -149,8 +139,6 @@
                     {
                         if (((EndOp)current).IsClosed)
                             this.context.ClosePath();
-
-                        System.Diagnostics.Debug.WriteLine("End");
                     }
                     else if (current is CurveToOp)
                     {
@@ -159,13 +147,17 @@
                     }
                 }

-                if (useFill)
+                if (brush != null)
                 {
-                    this.context.FillPreserve();
+                    this.SetBrush(brush);
+                    this.context.Fill();
                 }
-                else
+
+
+                if (pen != null)
                 {
-                    this.context.StrokePreserve();
+                    this.SetPen(pen);
+                    this.context.Stroke();
                 }
             }
         }


unable to get device name on windows apps.

--- src/Portable/ClientInfoProvider.cs
+++ src/Portable/ClientInfoProvider.cs
@@ -9,33 +9,15 @@
 #if NETFX_CORE
         public PlatformName Platform => PlatformName.WindowsStore;

-        public async Task<ClientInfo> GetAsync()
+        public Task<ClientInfo> GetAsync()
         {
             var result = new ClientInfo();
             result.OperatingSystem = PlatformName.WindowsStore;
             result.DeviceUniqueId = GetDeviceDeviceUniqueId();
-            result.DeviceName = await TryGetRootDeviceInfoAsync("System.Devices.ModelDeviceName").ConfigureAwait(false);
-            result.DeviceManufacturer = await TryGetRootDeviceInfoAsync("System.Devices.DeviceManufacturer").ConfigureAwait(false);
-            return result;
+            return Task.FromResult(result);
         }

         private static string GetDeviceDeviceUniqueId() => null;
-
-        private static async Task<string> TryGetRootDeviceInfoAsync(string propertyKey)
-        {
-            try
-            {
-                // http://stackoverflow.com/questions/18599589/getting-os-platform-and-device-information-on-windows-8
-                object result;
-                var pnp = await Windows.Devices.Enumeration.Pnp.PnpObject.CreateFromIdAsync(
-                    Windows.Devices.Enumeration.Pnp.PnpObjectType.DeviceContainer, "{00000000-0000-0000-FFFF-FFFFFFFFFFFF}", new[] { propertyKey });
-                return pnp != null && pnp.Properties.TryGetValue(propertyKey, out result) && result != null ? result.ToString() : "";
-            }
-            catch
-            {
-                return null;
-            }
-        }
 #else
         public Task<ClientInfo> GetAsync()
         {


Correct test name

Correct test name

--- SpaydParserLibTests/SpaydParserTests.cs
+++ SpaydParserLibTests/SpaydParserTests.cs
@@ -175,7 +175,7 @@
         }

         [Test]
-        public void TryGetCurrency_WhenValid()
+        public void TryGetCurrency_WhenInvalid()
         {
             // Arrange
             SpaydParser parser = new SpaydParser(CreateTestCase("AV", "XYZ"));


use trygetvalue instead of checking Contains

--- TCC.Core/Data/Databases/DatabaseBase.cs
+++ TCC.Core/Data/Databases/DatabaseBase.cs
@@ -21,8 +21,8 @@
             if (!Exists) return;
             var localHash = HashUtils.GenerateFileHash(customAbsPath ?? FullPath);
             if (UpdateManager.DatabaseHashes.Count == 0) return;
-            if (!UpdateManager.DatabaseHashes.ContainsKey(customRelPath ?? RelativePath)) return;
-            if (UpdateManager.DatabaseHashes[customRelPath ?? RelativePath] == localHash) return;
+            if (!UpdateManager.DatabaseHashes.TryGetValue(customRelPath ?? RelativePath, out var remoteHash)) return;
+            if (remoteHash == localHash) return;
             Log.CW($"Hash mismatch for {customRelPath ?? RelativePath}");
             outdatedCount++;


Added Client.HandlePacketRecieveAntiCheatCheck virtual method

--- src/Rs317.Library.Client/Client.cs
+++ src/Rs317.Library.Client/Client.cs
@@ -8776,9 +8776,7 @@
 			loadingStages();
 			spawnGameObjects();
 			handleMusic();
-			packetReadAnticheat++;
-			if(packetReadAnticheat > 750)
-				dropClient();
+			HandlePacketRecieveAntiCheatCheck();
 			updatePlayerInstances();
 			updateNPCInstances();
 			cycleEntitySpokenText();
@@ -8984,6 +8982,13 @@
 			{
 				logout();
 			}
+		}
+
+		protected virtual void HandlePacketRecieveAntiCheatCheck()
+		{
+			packetReadAnticheat++;
+			if (packetReadAnticheat > 750)
+				dropClient();
 		}

 		private void manageTextInput()


Last crystal shards fix didn't quite fix the issues. Trying again.

Signed-off-by: Stickiler <6b3799be4300e44489a08090123f3842e6419da5@olympusgaming.org>

--- Terraria_Server/WorldMod/WorldModify.cs
+++ Terraria_Server/WorldMod/WorldModify.cs
@@ -148,7 +148,7 @@
 			if (Main.hardMode)
 			{
 				int type = (int)TileRefs(i, j).Type;
-				if (type == 117 && (double)j > Main.rockLayer && Main.rand.Next(110) == 0)
+				if (type == 117 && (double)j > Main.rockLayer && Main.rand.Next(55) == 0)
 				{
 					int num = genRand.Next(4);
 					int num2 = 0;
@@ -159,7 +159,7 @@
 					else if (num == 1)
 						num2 = 1;
 					else
-						num3 = (num == 0) ? -1 : 1;
+						num3 =  1;

 					if (!TileRefs(i + num2, j + num3).Active)
 					{


WPF - Handle case where Bitmap is IntPtr.Zero

Because the OnPaint arrives on a thread other than the UI thread, it the
bitmap rendering process can occur after Dispose() has been called.

--- CefSharp.Wpf/Rendering/InteropBitmapInfo.cs
+++ CefSharp.Wpf/Rendering/InteropBitmapInfo.cs
@@ -2,6 +2,7 @@
 //
 // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.

+using System;
 using System.Windows.Interop;
 using System.Windows.Media;
 using System.Windows.Media.Imaging;
@@ -31,14 +32,24 @@

         public override void Invalidate()
         {
-            Bitmap.Invalidate();
+            if (Bitmap != null)
+            {
+                Bitmap.Invalidate();
+            }
         }

         public override BitmapSource CreateBitmap()
         {
             var stride = Width * BytesPerPixel;

-            Bitmap = (InteropBitmap)Imaging.CreateBitmapSourceFromMemorySection(FileMappingHandle, Width, Height, PixelFormat, stride, 0);
+            if (FileMappingHandle != IntPtr.Zero)
+            {
+                Bitmap = (InteropBitmap)Imaging.CreateBitmapSourceFromMemorySection(FileMappingHandle, Width, Height, PixelFormat, stride, 0);
+            }
+            else
+            {
+                ClearBitmap();
+            }

             return Bitmap;
         }


Refactor further to remove indexing confusion

--- osu.Game.Rulesets.Osu/Difficulty/Skills/Flashlight.cs
+++ osu.Game.Rulesets.Osu/Difficulty/Skills/Flashlight.cs
@@ -40,32 +40,33 @@

             double result = 0.0;

+            OsuDifficultyHitObject lastObj = null;
+
+            // This is iterating backwards in time from the current object.
             for (int i = 0; i < Previous.Count; i++)
             {
-                var osuLoop = (OsuDifficultyHitObject)Previous[i];
-                var osuLoopHitObject = (OsuHitObject)(osuLoop.BaseObject);
+                var currentObj = (OsuDifficultyHitObject)Previous[i];
+                var currentHitObject = (OsuHitObject)(currentObj.BaseObject);

-                OsuDifficultyHitObject osuLoopNext;
-                if (i == 0)
-                    osuLoopNext = osuCurrent;
-                else
-                    osuLoopNext = (OsuDifficultyHitObject)Previous[i - 1];
+                lastObj ??= currentObj;

-                if (!(osuLoop.BaseObject is Spinner))
+                if (!(currentObj.BaseObject is Spinner))
                 {
-                    double jumpDistance = (osuHitObject.StackedPosition - osuLoopHitObject.EndPosition).Length;
+                    double jumpDistance = (osuHitObject.StackedPosition - currentHitObject.EndPosition).Length;

-                    cumulativeStrainTime += osuLoopNext.StrainTime;
+                    cumulativeStrainTime += lastObj.StrainTime;

                     // We want to nerf objects that can be easily seen within the Flashlight circle radius.
                     if (i == 0)
                         smallDistNerf = Math.Min(1.0, jumpDistance / 75.0);

                     // We also want to nerf stacks so that only the first object of the stack is accounted for.
-                    double stackNerf = Math.Min(1.0, (osuLoop.LazyJumpDistance / scalingFactor) / 25.0);
+                    double stackNerf = Math.Min(1.0, (currentObj.LazyJumpDistance / scalingFactor) / 25.0);

                     result += Math.Pow(0.8, i) * stackNerf * scalingFactor * jumpDistance / cumulativeStrainTime;
                 }
+
+                lastObj = currentObj;
             }

             return Math.Pow(smallDistNerf * result, 2.0);


Also test Goods and Perfects

Also test Goods and Perfects

--- osu.Game.Tests/Rulesets/Scoring/ScoreProcessorTest.cs
+++ osu.Game.Tests/Rulesets/Scoring/ScoreProcessorTest.cs
@@ -57,14 +57,16 @@
         [TestCase(ScoringMode.Standardised, HitResult.Miss, HitResult.Great, 0)]
         [TestCase(ScoringMode.Standardised, HitResult.Meh, HitResult.Great, 387_500)]
         [TestCase(ScoringMode.Standardised, HitResult.Ok, HitResult.Great, 425_000)]
+        [TestCase(ScoringMode.Standardised, HitResult.Good, HitResult.Perfect, 3_350_000 / 7.0)]
         [TestCase(ScoringMode.Standardised, HitResult.Great, HitResult.Great, 575_000)]
+        [TestCase(ScoringMode.Standardised, HitResult.Perfect, HitResult.Perfect, 575_000)]
         [TestCase(ScoringMode.Standardised, HitResult.SmallTickMiss, HitResult.SmallTickHit, 0)]
         [TestCase(ScoringMode.Standardised, HitResult.SmallTickHit, HitResult.SmallTickHit, 0)] // TODO: idk, this should be 225_000 from accuracy portion
         [TestCase(ScoringMode.Standardised, HitResult.LargeTickMiss, HitResult.LargeTickHit, 0)]
         [TestCase(ScoringMode.Standardised, HitResult.LargeTickHit, HitResult.LargeTickHit, 575_000)]
         [TestCase(ScoringMode.Standardised, HitResult.SmallBonus, HitResult.SmallBonus, 30)]
         [TestCase(ScoringMode.Standardised, HitResult.LargeBonus, HitResult.LargeBonus, 150)]
-        public void TestFourVariousResultsOneMiss(ScoringMode scoringMode, HitResult hitResult, HitResult maxResult, int expectedScore)
+        public void TestFourVariousResultsOneMiss(ScoringMode scoringMode, HitResult hitResult, HitResult maxResult, double expectedScore)
         {
             var minResult = new JudgementResult(new HitObject(), new TestJudgement(hitResult)).Judgement.MinResult;


Implement `IAdjustableAudioComponent` in `MasterGameplayClockContainer`

--- osu.Game/Screens/Play/MasterGameplayClockContainer.cs
+++ osu.Game/Screens/Play/MasterGameplayClockContainer.cs
@@ -24,7 +24,7 @@
     /// <remarks>
     /// This is intended to be used as a single controller for gameplay, or as a reference source for other <see cref="GameplayClockContainer"/>s.
     /// </remarks>
-    public class MasterGameplayClockContainer : GameplayClockContainer, IBeatSyncProvider
+    public class MasterGameplayClockContainer : GameplayClockContainer, IBeatSyncProvider, IAdjustableAudioComponent
     {
         /// <summary>
         /// Duration before gameplay start time required before skip button displays.
@@ -40,6 +40,8 @@
         };

         private readonly WorkingBeatmap beatmap;
+
+        private readonly Track track;

         private readonly double skipTargetTime;

@@ -66,6 +68,7 @@
         public MasterGameplayClockContainer(WorkingBeatmap beatmap, double skipTargetTime)
             : base(beatmap.Track, true)
         {
+            track = beatmap.Track;
             this.beatmap = beatmap;
             this.skipTargetTime = skipTargetTime;

@@ -195,9 +198,6 @@
             if (speedAdjustmentsApplied)
                 return;

-            if (SourceClock is not Track track)
-                return;
-
             track.AddAdjustment(AdjustableProperty.Frequency, GameplayClock.ExternalPauseFrequencyAdjust);
             track.AddAdjustment(AdjustableProperty.Tempo, UserPlaybackRate);

@@ -212,9 +212,6 @@
             if (!speedAdjustmentsApplied)
                 return;

-            if (SourceClock is not Track track)
-                return;
-
             track.RemoveAdjustment(AdjustableProperty.Frequency, GameplayClock.ExternalPauseFrequencyAdjust);
             track.RemoveAdjustment(AdjustableProperty.Tempo, UserPlaybackRate);

@@ -234,5 +231,29 @@
         IClock IBeatSyncProvider.Clock => this;

         ChannelAmplitudes IHasAmplitudes.CurrentAmplitudes => beatmap.TrackLoaded ? beatmap.Track.CurrentAmplitudes : ChannelAmplitudes.Empty;
+
+        void IAdjustableAudioComponent.AddAdjustment(AdjustableProperty type, IBindable<double> adjustBindable) =>
+            track.AddAdjustment(type, adjustBindable);
+
+        void IAdjustableAudioComponent.RemoveAdjustment(AdjustableProperty type, IBindable<double> adjustBindable) =>
+            track.RemoveAdjustment(type, adjustBindable);
+
+        public void RemoveAllAdjustments(AdjustableProperty type)
+        {
+            throw new NotImplementedException();
+        }
+
+        public void BindAdjustments(IAggregateAudioAdjustment component) => throw new NotImplementedException();
+        public void UnbindAdjustments(IAggregateAudioAdjustment component) => throw new NotImplementedException();
+
+        public BindableNumber<double> Volume => throw new NotImplementedException();
+        public BindableNumber<double> Balance => throw new NotImplementedException();
+        public BindableNumber<double> Frequency => throw new NotImplementedException();
+        public BindableNumber<double> Tempo => throw new NotImplementedException();
+
+        public IBindable<double> AggregateVolume => throw new NotImplementedException();
+        public IBindable<double> AggregateBalance => throw new NotImplementedException();
+        public IBindable<double> AggregateFrequency => throw new NotImplementedException();
+        public IBindable<double> AggregateTempo => throw new NotImplementedException();
     }
 }


Added error message to response code for context update

--- Tweek.ApiService/ContextUpdateModule.cs
+++ Tweek.ApiService/ContextUpdateModule.cs
@@ -33,7 +33,7 @@
                 string identityType = @params.identityType;
                 string identityId = @params.identityId;
                 var identity = new Identity(identityType, identityId);
-                Dictionary<string,string> data;
+                Dictionary<string, string> data;
                 using (var reader = new StreamReader(Request.Body))
                 {
                     data = JsonConvert.DeserializeObject<JObject>(await reader.ReadToEndAsync())
@@ -41,8 +41,19 @@
                         .ToDictionary(x => x.Name, x => x.Value.ToObject<object>()
                             .ToString());
                 }
-
-                await driver.AppendContext(identity, data);
+                try
+                {
+                    await driver.AppendContext(identity, data);
+                }
+                catch (Exception ex)
+                {
+                    return new Response
+                    {
+                        StatusCode = HttpStatusCode.InternalServerError,
+                        ContentType = "text/plain",
+                        Contents = stream => (new StreamWriter(stream) { AutoFlush = true }).Write(ex.Message)
+                    };
+                }

                 return 200;
             };


fixing error handling to throw exceptions on any kind of error and prevent error swallowing (#20)

Thanks!

--- UCWASDK/UCWASDK/Services/HttpService.cs
+++ UCWASDK/UCWASDK/Services/HttpService.cs
@@ -270,6 +270,8 @@
                         throw new ApplicationNotFoundException(error);
                     else
                         throw new ResourceNotFoundException(error);
+                default:
+                    throw new InvalidOperationException(error);

             }
         }


Improved sharing

Improved sharing

--- UWPHelper/UWPHelper/UI/AboutApp.xaml.cs
+++ UWPHelper/UWPHelper/UI/AboutApp.xaml.cs
@@ -13,7 +13,7 @@
     {
         public static readonly DependencyProperty AppStoreIdProperty    = DependencyProperty.Register(nameof(AppStoreId), typeof(string), typeof(AboutApp), null);
         public static readonly DependencyProperty AppUriProperty        = DependencyProperty.Register(nameof(AppUri), typeof(string), typeof(AboutApp), null);
-        public static readonly DependencyProperty AppLogoPathProperty   = DependencyProperty.Register(nameof(AppLogoPath), typeof(string), typeof(AboutApp), new PropertyMetadata(@"ms-appx:Assets\AppLogo.png"));
+        public static readonly DependencyProperty AppLogoPathProperty   = DependencyProperty.Register(nameof(AppLogoPath), typeof(string), typeof(AboutApp), new PropertyMetadata(@"ms-appx:Assets/AppLogo.png"));

         private PackageVersion Version
         {
@@ -88,7 +88,8 @@
         {
             args.Request.Data.Properties.Title = AppName;
             args.Request.Data.Properties.Description = AppStoreLink;
-            args.Request.Data.SetText($@"{AppStoreLink} - https://www.microsoft.com/store/apps/{AppStoreId}");
+            args.Request.Data.SetText($@"{AppStoreLink} (https://www.microsoft.com/store/apps/{AppStoreId})");
+            args.Request.Data.SetWebLink(new Uri($"https://www.microsoft.com/store/apps/{AppStoreId}"));
             args.Request.Data.SetApplicationLink(new Uri(AppUri));

             DataTransferManager.GetForCurrentView().DataRequested -= SharingDataRequested;


Insert our WCF interceptor first into the message inspectors and error handlers collectors, to minimize the chance we'll end up with a closed request message.

--- WCF/Shared/ServiceTelemetryAttribute.cs
+++ WCF/Shared/ServiceTelemetryAttribute.cs
@@ -43,12 +43,12 @@
                 var interceptor = new WcfInterceptor(configuration, contractFilter);
                 foreach ( ChannelDispatcher channelDisp in serviceHost.ChannelDispatchers )
                 {
-                    channelDisp.ErrorHandlers.Add(interceptor);
+                    channelDisp.ErrorHandlers.Insert(0, interceptor);
                     foreach ( var ep in channelDisp.Endpoints )
                     {
                         if ( !ep.IsSystemEndpoint )
                         {
-                            ep.DispatchRuntime.MessageInspectors.Add(interceptor);
+                            ep.DispatchRuntime.MessageInspectors.Insert(0, interceptor);
                         }
                     }
                 }


Fix build

Fix build

--- CodeJam.Main/Arithmetic/OperatorsFactory.cs
+++ CodeJam.Main/Arithmetic/OperatorsFactory.cs
@@ -113,7 +113,7 @@
 			new NotSupportedException($"The type {typeof(T).Name} has no operator {operatorType} defined.", ex);

 		[CanBeNull]
-		private static FieldInfo? TryGetOpField<T>([NotNull] string fieldName)
+		private static FieldInfo TryGetOpField<T>([NotNull] string fieldName)
 		{
 			var t = typeof(T).ToNullableUnderlying();


Don't display the name of the target framework before copying the binary

--- CopyToNuGetTargetFrameworkFolder/Program.cs
+++ CopyToNuGetTargetFrameworkFolder/Program.cs
@@ -85,7 +85,6 @@
             }
             else
             {
-                Console.WriteLine(targetFrameworkAttribute.FrameworkName);
                 frameworkName = new FrameworkName(targetFrameworkAttribute.FrameworkName);
             }
             var identifier = NuGetFrameworkIdentifier(frameworkName);


Avoid creating exception in static constructor

--- Core/Theraot/Threading/ThreadLocalHelper.cs
+++ Core/Theraot/Threading/ThreadLocalHelper.cs
@@ -11,12 +11,17 @@

         static ThreadLocalHelper()
         {
-            _recursionGuardException = new InvalidOperationException("Recursion");
+            _recursionGuardException = GetInvalidOperationException();
         }

         public static Exception RecursionGuardException
         {
             get { return _recursionGuardException; }
+        }
+
+        private static InvalidOperationException GetInvalidOperationException()
+        {
+            return new InvalidOperationException("Recursion");
         }
     }


Escaping quotes in identifiers, see issue #3

--- CqlSharp.Linq/Translation/CqlTextBuilder.cs
+++ CqlSharp.Linq/Translation/CqlTextBuilder.cs
@@ -60,7 +60,7 @@
             builder.Append("SELECT ");
             builder.Append(_translations[selectStatement.SelectClause]);
             builder.Append(" FROM \"");
-            builder.Append(selectStatement.TableName);
+            builder.Append(selectStatement.TableName.Replace("\"", "\"\""));
             builder.Append("\"");

             if (selectStatement.WhereClause != null && selectStatement.WhereClause.Any())
@@ -132,7 +132,7 @@
             switch ((CqlExpressionType)selector.NodeType)
             {
                 case CqlExpressionType.IdentifierSelector:
-                    value = "\"" + selector.Identifier + "\"";
+                    value = "\"" + selector.Identifier.Replace("\"", "\"\"") + "\"";
                     break;
                 case CqlExpressionType.FunctionSelector:
                     var builder = new StringBuilder();


refactorion LazyInput adding ContentResult to LazyInput

--- src/Take.Blip.Builder/LazyInput.cs
+++ src/Take.Blip.Builder/LazyInput.cs
@@ -25,7 +25,10 @@
         private readonly Lazy<string> _lazySerializedContent;
         private readonly Lazy<bool> _analyzable;
         private readonly Lazy<Task<AnalysisResponse>> _lazyAnalyzedContent;
+        private readonly Lazy<Task<ContentResult>> _lazyGetContentResult;
         private readonly Lazy<string> _lazySerializedMessage;
+        private readonly IArtificialIntelligenceExtension _artificialIntelligenceExtension;
+        private readonly CancellationToken _cancellationToken;

         public LazyInput(
             Message message,
@@ -45,40 +48,70 @@
                 Message?.Metadata?.TryGetValue("builder.analyzable", out result);
                 return result?.ToLower() == "true";
             });
-            _lazyAnalyzedContent = new Lazy<Task<AnalysisResponse>>(async () =>
+            _artificialIntelligenceExtension = artificialIntelligenceExtension;
+            _cancellationToken = cancellationToken;
+            _lazyAnalyzedContent = CreateLazyAnalyzedContent(userIdentity);
+            _lazySerializedMessage = CreateLazySerializedMessage(envelopeSerializer);
+            _lazyGetContentResult = CreateLazyGetContentResult();
+        }
+
+        private Lazy<Task<AnalysisResponse>> CreateLazyAnalyzedContent(Identity userIdentity) => new Lazy<Task<AnalysisResponse>>(async () =>
+        {
+            // Only analyze the input if the type is plain text or analyzable metadata is true.
+            if (!_analyzable.Value && Content.GetMediaType() != PlainText.MediaType) return null;
+
+            try
             {
-                // Only analyze the input if the type is plain text or analyzable metadata is true.
-                if (!_analyzable.Value && Content.GetMediaType() != PlainText.MediaType) return null;
+                return await _artificialIntelligenceExtension.AnalyzeAsync(
+                    new AnalysisRequest
+                    {
+                        Text = _lazySerializedContent.Value,
+                        Extras = new Dictionary<string, string>
+                        {
+                            ["MessageId"] = Message.Id,
+                            ["UserIdentity"] = userIdentity.ToString()
+                        }
+                    },
+                    _cancellationToken);
+            }
+            catch (LimeException)
+            {
+                return null;
+            }
+        });

-                try
-                {
-                    return await artificialIntelligenceExtension.AnalyzeAsync(
-                        new AnalysisRequest
-                        {
-                            Text = _lazySerializedContent.Value,
-                            Extras = new Dictionary<string, string>
-                            {
-                                ["MessageId"] = Message.Id,
-                                ["UserIdentity"] = userIdentity.ToString()
-                            }
-                        },
-                        cancellationToken);
-                }
-                catch (LimeException)
-                {
-                    return null;
-                }
-            });
-            _lazySerializedMessage = new Lazy<string>(() =>
+        private Lazy<string> CreateLazySerializedMessage(IEnvelopeSerializer envelopeSerializer) => new Lazy<string>(() =>
+        {
+            if (Message != null)
             {
-                if (Message != null)
-                {
-                    return envelopeSerializer.Serialize(Message);
-                }
+                return envelopeSerializer.Serialize(Message);
+            }
+            return null;
+        });

+        private Lazy<Task<ContentResult>> CreateLazyGetContentResult() => new Lazy<Task<ContentResult>>(async () =>
+        {
+            var intentId = (await GetIntentAsync())?.Id;
+            if (intentId == null) return null;
+            var entityValues = (await AnalyzedContent)?
+                .Entities?
+                .Select(entity => entity.Value)
+                .ToArray();
+            try
+            {
+                return await _artificialIntelligenceExtension.GetContentResultAsync(
+                   new ContentCombination
+                   {
+                       Intent = intentId,
+                       Entities = entityValues
+                   },
+                   _cancellationToken);
+            }
+            catch (LimeException)
+            {
                 return null;
-            });
-        }
+            }
+        });

         public Message Message { get; }

@@ -89,6 +122,8 @@
         public string SerializedMessage => _lazySerializedMessage.Value;

         public Task<AnalysisResponse> AnalyzedContent => _lazyAnalyzedContent.Value;
+
+        public Task<ContentResult> ContentResult => _lazyGetContentResult.Value;

         public async Task<IntentionResponse> GetIntentAsync()
         {


translation of comments

translation of comments

--- WpfApplication2/Control/Element.xaml.cs
+++ WpfApplication2/Control/Element.xaml.cs
@@ -903,7 +903,7 @@

         private void editor_PreviewKeyUp(object sender, KeyEventArgs e)
         {
-            if (e.Key == Key.PageUp || e.Key == Key.PageDown) // klavesy, ktere textbox krade, posleme rucne parentu...
+            if (e.Key == Key.PageUp || e.Key == Key.PageDown) // avalon edit handles some keys, just send them to parent
             {
                 KeyEventArgs kea = new KeyEventArgs((KeyboardDevice)e.Device, PresentationSource.FromVisual(this), e.Timestamp, e.Key) { RoutedEvent = Element.PreviewKeyUpEvent };
                 RaiseEvent(kea);
@@ -990,19 +990,19 @@
                     string etext = (EditPhonetics ? p.Phonetics : p.Text);
                     int len = etext.Length;

-                    if (pos + len > offset) //konec fraze je za zacatkem mazani
+                    if (pos + len > offset) //end of phraze is after the deletion
                     {
                         int iidx = offset - pos;
-                        if (removedl > len - iidx) //odmazani textu pokracuje i za aktualni frazi
+                        if (removedl > len - iidx) //deletion continues after current phrase
                         {

-                            if (iidx == 0) //mazeme celou frazi
+                            if (iidx == 0) //delete whole phrase
                             {
                                 removedl -= len;
                                 offset = pos + len;
                                 todelete.Add(p);
                             }
-                            else //zkracujeme frazy
+                            else //shorten phrase
                             {

                                 string s = etext.Remove(iidx);
@@ -1017,13 +1017,13 @@

                             }
                         }
-                        else if (len == removedl) //maze se presne 1 fraze
+                        else if (len == removedl) //remove exactly 1 phrase
                         {
                             removedl -= len;
                             offset = pos + len;
                             if (addedl <= 0)
                                 todelete.Add(p);
-                            else //v pripade replace
+                            else //in case of replace
                             {
                                 if (EditPhonetics)
                                     p.Phonetics = "";
@@ -1033,7 +1033,7 @@
                             }
                             break;
                         }
-                        else//odmazani konci ve frazi
+                        else//deletion ends in phrase
                         {
                             string s = (EditPhonetics ? p.Phonetics : p.Text).Remove(iidx, removedl);
                             if (EditPhonetics)
@@ -1060,7 +1060,7 @@
                 {
                     foreach (TranscriptionPhrase p in par.Phrases)
                     {
-                        if (offset <= pos + (EditPhonetics ? p.Phonetics.Length : p.Text.Length)) //vlozeni
+                        if (offset <= pos + (EditPhonetics ? p.Phonetics.Length : p.Text.Length)) //insertion
                         {
                             string s = (EditPhonetics ? p.Phonetics : p.Text).Insert(offset - pos, text.Substring(offset, addedl));
                             if (EditPhonetics)


WIP #296 - Add further docs

WIP #296 - Add further docs

--- ZptSharp/Dom/IReadsAndWritesDocument.cs
+++ ZptSharp/Dom/IReadsAndWritesDocument.cs
@@ -8,16 +8,57 @@
 {
     /// <summary>
     /// An object which may read & write <see cref="IDocument"/> instances to/from
-    /// streams.
+    /// streams.  This is the core interface of "a document provider".
     /// </summary>
+    /// <remarks>
+    /// <para>
+    /// A document provider is a required add-on for ZptSharp which allows it to read and write
+    /// markup documents.
+    /// On its own, the ZptSharp core deals only in an abstraction, the <see cref="IDocument"/> interface
+    /// and its members.
+    /// The document provider is how a stream may be read as a document and how a modified/rendered
+    /// document may be written/saved back to a stream.
+    /// </para>
+    /// <para>
+    /// Implementations of this interface typically use other/3rd-party libraries to read/write the
+    /// markup, and "bridge the gap" between the specific document reading/writing API, and the abstractions
+    /// which the ZptSharp core uses.
+    /// </para>
+    /// <para>
+    /// In order to have a working/usable ZptSharp environment, at least one document provider
+    /// must be registered with dependency injection and must also be registered for use with
+    /// <see cref="IRegistersDocumentReaderWriter"/>.
+    /// This registration is usually accomplished via extension methods for
+    /// <see cref="Microsoft.Extensions.DependencyInjection.IServiceCollection"/> and
+    /// <see cref="System.IServiceProvider"/> and does not usually need to be done manually.
+    /// </para>
+    /// </remarks>
+    /// <seealso cref="IDocument"/>
+    /// <seealso cref="INode"/>
+    /// <seealso cref="IAttribute"/>
+    /// <seealso cref="IRegistersDocumentReaderWriter"/>
     public interface IReadsAndWritesDocument
     {
         /// <summary>
-        /// Gets whether or not the current instance may be used to read & write documents
+        /// Gets a value which indicates whether or not the current instance may be used to read & write documents
         /// which have the specified filename.
         /// </summary>
-        /// <returns><c>true</c>, if this instance maybe used, <c>false</c> otherwise.</returns>
-        /// <param name="filenameOrPath">The filename of a ZPT document.</param>
+        /// <remarks>
+        /// <para>
+        /// This is the mechanism by which an <see cref="IGetsZptDocumentRendererForFilePath"/>
+        /// (and ultimately an <see cref="IRendersZptFile"/>) selects an appropriate document provider implementation
+        /// for a specified file.
+        /// </para>
+        /// <para>
+        /// This enables document providers to be used with the strategy pattern -
+        /// <see href="https://en.wikipedia.org/wiki/Strategy_pattern" /> - interrogating each of the available providers
+        /// to determine which can perform the required task.
+        /// </para>
+        /// </remarks>
+        /// <returns><c>true</c>, if this instance may be used for the specified file name/file path; <c>false</c> if not.</returns>
+        /// <param name="filenameOrPath">The file name or file path of a ZPT document.</param>
+        /// <seealso cref="IGetsZptDocumentRendererForFilePath"/>
+        /// <seealso cref="IRendersZptFile"/>
         bool CanReadWriteForFilename(string filenameOrPath);

         /// <summary>


Fix "Update Prompt" revision display logic

--- DesktopWidgets/Windows/UpdatePrompt.xaml.cs
+++ DesktopWidgets/Windows/UpdatePrompt.xaml.cs
@@ -43,15 +43,21 @@
                     UpdateSubText =
                         $"A new major release, {AssemblyInfo.Title} {updateVersion.Major}.{updateVersion.Minor} is now available!";
                 }
-                else if (updateVersion.Revision != AssemblyInfo.Version.Revision)
-                {
-                    UpdateSubText =
-                        $"{AssemblyInfo.Title} {updateVersion} is now available!";
-                }
                 else
                 {
-                    UpdateSubText =
-                        $"{AssemblyInfo.Title} {updateVersion.Major}.{updateVersion.Minor}.{updateVersion.Build} is now available!";
+                    if (updateVersion.Major == AssemblyInfo.Version.Major &&
+                        updateVersion.Minor == AssemblyInfo.Version.Minor &&
+                        updateVersion.Build == AssemblyInfo.Version.Build &&
+                        updateVersion.Revision != AssemblyInfo.Version.Revision)
+                    {
+                        UpdateSubText =
+                            $"{AssemblyInfo.Title} {updateVersion} is now available!";
+                    }
+                    else
+                    {
+                        UpdateSubText =
+                            $"{AssemblyInfo.Title} {updateVersion.Major}.{updateVersion.Minor}.{updateVersion.Build} is now available!";
+                    }
                 }
                 UpdateSubText += "\nDo you want to update to the latest version?";
             }


Removing win forms

Removing win forms

--- Dev/Editor/EffekseerMP/GUI/Menu/MainMenu.cs
+++ Dev/Editor/EffekseerMP/GUI/Menu/MainMenu.cs
@@ -3,7 +3,7 @@
 using System.Linq;
 using System.Text;
 using System.Threading.Tasks;
-using System.Windows.Forms;
+//using System.Windows.Forms;

 namespace Effekseer.GUI.Menu
 {
@@ -133,6 +133,22 @@
 						item.Label = script.Title;
 						item.Clicked += () =>
 						{
+							var filter = script.Filter.Split('.').Last();
+							var result = swig.FileDialog.OpenDialog(filter, System.IO.Directory.GetCurrentDirectory());
+
+							if (!string.IsNullOrEmpty(result))
+							{
+								var filepath = result;
+
+								script.Function(filepath);
+								System.IO.Directory.SetCurrentDirectory(System.IO.Path.GetDirectoryName(filepath));
+							}
+							else
+							{
+								return;
+							}
+
+							/*
 							OpenFileDialog ofd = new OpenFileDialog();

 							ofd.InitialDirectory = System.IO.Directory.GetCurrentDirectory();
@@ -151,6 +167,7 @@
 							{
 								return;
 							}
+							*/
 						};
 						import_menu.Controls.Add(item);
 					}
@@ -168,6 +185,21 @@
 						item.Label = script.Title;
 						item.Clicked += () =>
 						{
+							var filter = script.Filter.Split('.').Last();
+							var result = swig.FileDialog.SaveDialog(filter, System.IO.Directory.GetCurrentDirectory());
+
+							if (!string.IsNullOrEmpty(result))
+							{
+								var filepath = result;
+								script.Function(filepath);
+
+								System.IO.Directory.SetCurrentDirectory(System.IO.Path.GetDirectoryName(filepath));
+							}
+							else
+							{
+								return;
+							}
+							/*
 							SaveFileDialog ofd = new SaveFileDialog();

 							ofd.InitialDirectory = System.IO.Directory.GetCurrentDirectory();
@@ -186,6 +218,7 @@
 							{
 								return;
 							}
+							*/
 						};
 						export_menu.Controls.Add(item);
 					}


Implement SetValue

Implement SetValue

Implement SetValue

--- DevelopmentInProgress.DipType/TypeHelper.cs
+++ DevelopmentInProgress.DipType/TypeHelper.cs
@@ -34,7 +34,7 @@
             if (assemblyBuilder == null)
             {
                 assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(
-                    new AssemblyName("TypeHelperAssembly"), AssemblyBuilderAccess.Run);
+                    new AssemblyName("TypeHelperAssembly"), AssemblyBuilderAccess.RunAndSave);

                 moduleBuilder = assemblyBuilder.DefineDynamicModule("TypeHelperModule");
             }
@@ -83,7 +83,7 @@

             var setValueBody = typeBuilder.DefineMethod(baseSetValue.Name,
                 baseSetValue.Attributes & ~MethodAttributes.Abstract,
-                typeof(void), new Type[] { typeof(object), typeof(string), typeof(object) });
+                null, new Type[] { typeof(object), typeof(string), typeof(object) });

             var setValueIL = setValueBody.GetILGenerator();

@@ -164,7 +164,6 @@
                 il.Emit(OpCodes.Beq, labels[i]);
             }

-            //il.Emit(OpCodes.Ldstr, typeof(T).Name + " doesn't have a property called ");
             il.Emit(OpCodes.Ldarg_2);
             il.Emit(OpCodes.Newobj, typeof(ArgumentOutOfRangeException).GetConstructor(new Type[] { typeof(string) }));
             il.Emit(OpCodes.Throw);
@@ -175,11 +174,11 @@

                 il.MarkLabel(labels[i]);

+                il.Emit(OpCodes.Ldarg_1);
+
                 if (isGet)
                 {
                     var getAccessor = property.GetGetMethod();
-
-                    il.Emit(OpCodes.Ldarg_1);

                     il.EmitCall(OpCodes.Callvirt, getAccessor, null);

@@ -190,13 +189,13 @@
                 }
                 else
                 {
-                    var setAccessor = property.GetGetMethod();
-
-                    il.Emit(OpCodes.Ldarg_2);
+                    var setAccessor = property.GetSetMethod();
+
+                    il.Emit(OpCodes.Ldarg_3);

                     if (property.PropertyType.IsValueType)
                     {
-                        il.Emit(OpCodes.Unbox, property.PropertyType);
+                        il.Emit(OpCodes.Unbox_Any, property.PropertyType);
                     }

                     il.EmitCall(OpCodes.Callvirt, setAccessor, null);


Mark the cache internal so it can be used by the test project.

Mark the cache internal so it can be used by the test project.

--- DevelopmentInProgress.DipType/TypeHelper.cs
+++ DevelopmentInProgress.DipType/TypeHelper.cs
@@ -21,7 +21,7 @@

     public static class TypeHelper
     {
-        private static readonly IDictionary<Type, object> cache = new ConcurrentDictionary<Type, object>();
+        internal static readonly IDictionary<Type, object> cache = new ConcurrentDictionary<Type, object>();

         private static AssemblyBuilder assemblyBuilder;


fix shared data

fix shared data

--- ModCore/ModCoreShard.cs
+++ ModCore/ModCoreShard.cs
@@ -24,7 +24,7 @@
         public InteractivityExtension Interactivity { get; private set; }
         public CommandsNextExtension Commands { get; private set; }

-        public SharedData ShardData { get; set; }
+        public SharedData SharedData { get; set; }
         internal Settings Settings { get; }

         public DatabaseContextBuilder Database { get; }
@@ -32,7 +32,7 @@
         public ModCoreShard(Settings settings, int id, SharedData sharedData)
         {
             this.Settings = settings;
-            this.ShardData = sharedData;
+            this.SharedData = sharedData;
             Database = settings.Database.CreateContextBuilder();
         }

@@ -41,7 +41,7 @@
             // Store the Start Times to use in DI
             // SocketStartTime will be updated in the SocketOpened event,
             // For now we just need to make sure its not null.
-            StartTimes = new StartTimes(ShardData.ProcessStartTime, ShardData.ProcessStartTime);
+            StartTimes = new StartTimes(SharedData.ProcessStartTime, SharedData.ProcessStartTime);

             // Initialize the DiscordClient
             this.Client = new DiscordClient(new DiscordConfiguration
@@ -79,7 +79,7 @@

             // Add the instances we need to dependencies
             var deps = new ServiceCollection()
-                .AddSingleton(this.ShardData)
+                .AddSingleton(this.SharedData)
                 //.AddInstance(this.Settings)
                 .AddSingleton(this.Interactivity)
                 .AddSingleton(this.StartTimes)


ConditionTargets JSON output now only contains ConditionTypes having targets

--- ExoWeb/LoadMethod.cs
+++ ExoWeb/LoadMethod.cs
@@ -550,19 +550,15 @@
 		/// <param name="response"></param>
 		protected void OutputConditionTargets(HttpResponse response)
 		{
-			// get all condition types and initialize
-			Dictionary<ConditionType, List<ConditionTarget>> targetsByType = new Dictionary<ConditionType, List<ConditionTarget>>();
-			foreach (ConditionType conditionType in instances.Keys
-						.SelectMany(graphType => ServiceHandler.Adapter.GetConditionTypes(graphType))
-						.Where(conditionType => conditionType.ConditionRule == null || conditionType.ConditionRule is PropertyRule)
-						.Distinct())
-				targetsByType[conditionType] = new List<ConditionTarget>();
-
 			// populate condition targets by condition type
+			Dictionary<ConditionType, List<ConditionTarget>> targetsByType = new Dictionary<ConditionType, List<ConditionTarget>>();
 			foreach (var target in instances.Values.SelectMany(d => d.Keys)
 				.SelectMany(instance => Condition.GetConditions(instance))
 				.SelectMany(condition => condition.Targets))
 			{
+				if (!targetsByType.ContainsKey(target.Condition.Type))
+					targetsByType.Add(target.Condition.Type, new List<ConditionTarget>());
+
 				if (!targetsByType[target.Condition.Type].Contains(target))
 					targetsByType[target.Condition.Type].Add(target);
 			}


Fix up the error method in the logger - to pass the exception to Serilog correctly (was wrong way round) & for it to add context of the <T> too

--- src/Umbraco.Core/Logging/Logger.cs
+++ src/Umbraco.Core/Logging/Logger.cs
@@ -83,7 +83,7 @@
                 }
             }

-            logger.Error(message, exception);
+            logger.ForContext(reporting).Error(exception, message);
         }

         public void Error(Type reporting, string messageTemplate, Exception exception = null, params object[] propertyValues)


File2VDK fix to allow drag and drop

File2VDK fix to allow drag and drop

Strip path component from files to be written to the VDK disk image.
Convert all file names to uppercase.

--- File2VDK/File2VDK.cs
+++ File2VDK/File2VDK.cs
@@ -88,7 +88,7 @@
                     {
                         if (Verbose)
                             Console.WriteLine("Writing file \"{0}\" to disk image.", file);
-                        dos.WriteFile(file, DragonDosFile.CreateDataFile(IOUtils.ReadStreamFully(new FileStream(file, FileMode.Open))));
+                        dos.WriteFile(Path.GetFileName(file).ToUpper(), DragonDosFile.CreateDataFile(IOUtils.ReadStreamFully(new FileStream(file, FileMode.Open))));
                     }
                 }


Refactoring of the code to select a tree view item given a data object.

--- src/VsChromium/Wpf/WpfUtilities.cs
+++ src/VsChromium/Wpf/WpfUtilities.cs
@@ -93,29 +93,30 @@
     /// object. Note: This method is synchronous (i.e. does not post any message
     /// to the UI thread queue).
     /// </summary>
-    public static void SelectTreeViewItem(TreeView treeView, IHierarchyObject item) {
-      // Build child->parent->ancestor(s) stack so we can go top-down in the
-      // tree during next phase.
-      var viewItems = new Stack<IHierarchyObject>();
-      while (item != null) {
-        viewItems.Push(item);
-        item = item.GetParent();
+    public static TreeViewItem SelectTreeViewItem(TreeView treeView, IHierarchyObject dataObject) {
+      // Build child->parent->ancestor(s) sequenc as a stack so we can go
+      // top-down in the tree during next phase.
+      var dataObjectStack = new Stack<IHierarchyObject>();
+      while (dataObject != null) {
+        dataObjectStack.Push(dataObject);
+        dataObject = dataObject.GetParent();
       }

       // For each visual element in the stack, expand and bring to view the
       // corresponding TreeViewItem
       ItemsControl parentItemsControl = treeView;
-      IHierarchyObject parentViewItem = null;
-      while (viewItems.Count > 0) {
-        var viewItem = viewItems.Pop();
-
-        if (viewItem.IsVisual) {
-          parentItemsControl = BringViewItemToView(treeView, parentItemsControl, parentViewItem, viewItem);
-          if (parentItemsControl == null)
+      IHierarchyObject parentDataObject = null;
+      while (dataObjectStack.Count > 0) {
+        var childDataObject = dataObjectStack.Pop();
+
+        if (childDataObject.IsVisual) {
+          var childItemsControl = BringDataObjectToView(treeView, parentItemsControl, parentDataObject, childDataObject);
+          if (childItemsControl == null)
             break;
-        }
-
-        parentViewItem = viewItem;
+          parentItemsControl = childItemsControl;
+        }
+
+        parentDataObject = childDataObject;
       }

       // If the desired selection is found, select it
@@ -123,9 +124,12 @@
       if (desiredSelection != null) {
         SetSelectedItem(treeView, desiredSelection);
       }
-    }
+      return desiredSelection;
+    }
+
     /// <summary>
-    /// Programmatically select an item from a tree view (idea from http://goo.gl/w0KFL5)
+    /// Programmatically select an item from a tree view (idea from
+    /// http://goo.gl/w0KFL5)
     /// </summary>
     public static void SetSelectedItem(TreeView treeView, TreeViewItem item) {
       Logger.WrapActionInvocation(() => {
@@ -137,7 +141,63 @@
       });
     }

-    private static ItemsControl BringViewItemToView(DispatcherObject dispatcher, ItemsControl parentItemsControl, IHierarchyObject parentViewItem, IHierarchyObject viewItem) {
+    private static ItemsControl BringDataObjectToView(
+      DispatcherObject dispatcher,
+      ItemsControl parentItemsControl,
+      IHierarchyObject parentDataObject,
+      IHierarchyObject dataObject) {
+      Debug.Assert(dispatcher != null);
+      Debug.Assert(parentDataObject != null);
+
+      // Try to generate the ItemsPresenter and the ItemsPanel. by calling
+      // ApplyTemplate.  Note that in the virtualizing case even if the item is
+      // marked expanded we still need to do this step in order to regenerate
+      // the visuals because they may have been virtualized away.
+      parentItemsControl.ApplyTemplate();
+      var itemsPresenter =
+          (ItemsPresenter)parentItemsControl.Template.FindName("ItemsHost", parentItemsControl);
+      if (itemsPresenter != null) {
+        itemsPresenter.ApplyTemplate();
+      } else {
+        // The Tree template has not named the ItemsPresenter,
+        // so walk the descendents and find the child.
+        itemsPresenter = FindVisualChild<ItemsPresenter>(parentItemsControl);
+        if (itemsPresenter == null) {
+          parentItemsControl.UpdateLayout();
+
+          itemsPresenter = FindVisualChild<ItemsPresenter>(parentItemsControl);
+        }
+      }
+
+      if (itemsPresenter == null) {
+        Logger.LogError("Can't find items presenter.");
+        return null;
+      }
+
+      // Access the custom VSP that exposes BringIntoView
+      var virtualizingStackPanel = VisualTreeHelper.GetChild(itemsPresenter, 0) as MyVirtualizingStackPanel;
+      if (virtualizingStackPanel == null) {
+        Logger.LogError("Can't find virtual stack panel for parentItemsControl.");
+        return null;
+      }
+
+      var dataObjetIndex = parentDataObject.GetAllChildren().IndexOf(dataObject);
+      if (dataObjetIndex >= parentItemsControl.Items.Count) {
+        Logger.LogError("TreeView node has fewer parents than its corresponding data object.");
+        return null;
+      }
+
+      virtualizingStackPanel.BringIntoView(dataObjetIndex);
+      var treeViewItem =
+        (ItemsControl) parentItemsControl.ItemContainerGenerator.ContainerFromIndex(dataObjetIndex);
+      if (treeViewItem.DataContext != dataObject) {
+        Logger.LogError("TreeView item data context is not the right data object.");
+        return null;
+      }
+      return treeViewItem;
+    }
+
+    private static ItemsControl BringViewItemToViewOld(DispatcherObject dispatcher, ItemsControl parentItemsControl, IHierarchyObject parentViewItem, IHierarchyObject viewItem) {
       Debug.Assert(parentViewItem != null);
       // Access the custom VSP that exposes BringIntoView
       var itemsHost = FindVisualChild<MyVirtualizingStackPanel>(parentItemsControl);
@@ -174,6 +234,103 @@
       return null;
     }

+    /// <summary>
+    /// Recursively search for an item in this subtree.
+    /// </summary>
+    /// <param name="container">
+    /// The parent ItemsControl. This can be a TreeView or a TreeViewItem.
+    /// </param>
+    /// <param name="item">
+    /// The item to search for.
+    /// </param>
+    /// <returns>
+    /// The TreeViewItem that contains the specified item.
+    /// </returns>
+    public static TreeViewItem GetTreeViewItem(ItemsControl container, object item) {
+      if (container != null) {
+        if (container.DataContext == item) {
+          return container as TreeViewItem;
+        }
+
+        // Expand the current container
+        if (container is TreeViewItem && !((TreeViewItem)container).IsExpanded) {
+          container.SetValue(TreeViewItem.IsExpandedProperty, true);
+        }
+
+        // Try to generate the ItemsPresenter and the ItemsPanel.
+        // by calling ApplyTemplate.  Note that in the
+        // virtualizing case even if the item is marked
+        // expanded we still need to do this step in order to
+        // regenerate the visuals because they may have been virtualized away.
+
+        container.ApplyTemplate();
+        ItemsPresenter itemsPresenter =
+            (ItemsPresenter)container.Template.FindName("ItemsHost", container);
+        if (itemsPresenter != null) {
+          itemsPresenter.ApplyTemplate();
+        } else {
+          // The Tree template has not named the ItemsPresenter,
+          // so walk the descendents and find the child.
+          itemsPresenter = FindVisualChild<ItemsPresenter>(container);
+          if (itemsPresenter == null) {
+            container.UpdateLayout();
+
+            itemsPresenter = FindVisualChild<ItemsPresenter>(container);
+          }
+        }
+
+        Panel itemsHostPanel = (Panel)VisualTreeHelper.GetChild(itemsPresenter, 0);
+
+
+        // Ensure that the generator for this panel has been created.
+        UIElementCollection children = itemsHostPanel.Children;
+
+        MyVirtualizingStackPanel virtualizingPanel =
+            itemsHostPanel as MyVirtualizingStackPanel;
+
+        for (int i = 0, count = container.Items.Count; i < count; i++) {
+          TreeViewItem subContainer;
+          if (virtualizingPanel != null) {
+            // Bring the item into view so
+            // that the container will be generated.
+            virtualizingPanel.BringIntoView(i);
+
+            subContainer =
+                (TreeViewItem)container.ItemContainerGenerator.
+                ContainerFromIndex(i);
+          } else {
+            subContainer =
+                (TreeViewItem)container.ItemContainerGenerator.
+                ContainerFromIndex(i);
+
+            // Bring the item into view to maintain the
+            // same behavior as with a virtualizing panel.
+            subContainer.BringIntoView();
+          }
+
+          if (subContainer != null) {
+            // Search the next level for the object.
+            TreeViewItem resultContainer = GetTreeViewItem(subContainer, item);
+            if (resultContainer != null) {
+              return resultContainer;
+            } else {
+              // The object is not under this TreeViewItem
+              // so collapse it.
+              subContainer.IsExpanded = false;
+            }
+          }
+        }
+      }
+
+      return null;
+    }
+
+    /// <summary>
+    /// Search for an element of a certain type in the visual tree.
+    /// </summary>
+    /// <typeparam name="T">The type of element to find.</typeparam>
+    /// <param name="visual">The parent element.</param>
+    /// <returns>The child element, or null if not found.</returns>
     private static T FindVisualChild<T>(Visual visual) where T : Visual {
       for (int i = 0; i < VisualTreeHelper.GetChildrenCount(visual); i++) {
         var child = (Visual)VisualTreeHelper.GetChild(visual, i);


Duplicate loop count arg check in NestedLoops

--- MoreLinq/NestedLoops.cs
+++ MoreLinq/NestedLoops.cs
@@ -24,19 +24,23 @@

             using (var iter = loopCounts.GetEnumerator())
             {
-                if (!iter.MoveNext())
+                var loopCount = NextLoopCount(iter);
+                if (loopCount == null)
                     return Enumerable.Empty<Action>(); // null loop
-                if (iter.Current < 0)
-                    throw new ArgumentException("All loop counts must be >= 0", "loopCounts");
-                var loop = Enumerable.Repeat(action, iter.Current);
-                while (iter.MoveNext())
-                {
-                    if (iter.Current < 0)
-                        throw new ArgumentException("All loop counts must be >= 0", "loopCounts");
-                    loop = loop.Repeat(iter.Current);
-                }
+                var loop = Enumerable.Repeat(action, loopCount.Value);
+                while ((loopCount = NextLoopCount(iter)) != null)
+                    loop = loop.Repeat(loopCount.Value);
                 return loop;
             }
         }
+
+        private static int? NextLoopCount(IEnumerator<int> iter)
+        {
+            if (!iter.MoveNext())
+                return null;
+            if (iter.Current < 0)
+                throw new ArgumentException("All loop counts must be >= 0", "loopCounts");
+            return iter.Current;
+        }
     }
 }


added missing Step.SkipReason

added missing Step.SkipReason

--- src/Xbehave.Net40/Internal/Step.cs
+++ src/Xbehave.Net40/Internal/Step.cs
@@ -44,6 +44,11 @@
             get { return this.message; }
         }

+        public string SkipReason
+        {
+            get { return this.skipReason; }
+        }
+
         public bool InIsolation
         {
             get { return this.inIsolation; }


git-svn-id: svn://localhost/mosa@834 45b04e34-05f1-4d87-a130-40a8491d5c8b

--- Mosa/HelloWorld/Boot.cs
+++ Mosa/HelloWorld/Boot.cs
@@ -357,7 +357,17 @@
 			 	Native.Out8((byte*)0x70, 0);
 				byte second = Native.In8((byte*)0x71);

-				Screen.SetCursor(55, 24);
+				Native.Out8((byte*)0x70, 2);
+				byte minute = Native.In8((byte*)0x71);
+
+				Native.Out8((byte*)0x70, 4);
+				byte hour = Native.In8((byte*)0x71);
+
+				Screen.SetCursor(71, 24);
+				Screen.Write(hour, 16, 2);
+				Screen.Write(':');
+				Screen.Write(minute, 16, 2);
+				Screen.Write(':');
 				Screen.Write(second, 16, 2);
 		}


Removed a couple of whitespaces

Removed a couple of whitespaces

--- MusicBrainz.DNX/Help.cs
+++ MusicBrainz.DNX/Help.cs
@@ -41,8 +41,8 @@
           else
           {
             result += paras[i].Name.ToLower() + ":" + search[i] + "%20AND%20";
-          }
-        }
+          }
+        }
       }

       return result.LastIndexOf("%20AND%20", StringComparison.Ordinal) > 0


Cleanup: string.Format crash on ToString() (may not repro)

--- EarTrumpet/UI/ViewModels/DeviceViewModel.cs
+++ EarTrumpet/UI/ViewModels/DeviceViewModel.cs
@@ -222,6 +222,6 @@

         public void MakeDefaultDevice() => _deviceManager.Default = _device;
         public void IncrementVolume(int delta) => Volume += delta;
-        public override string ToString() => string.Format(IsMuted ? Properties.Resources.AppOrDeviceMutedFormatAccessibleText : Properties.Resources.AppOrDeviceFormatAccessibleText, DisplayName, Volume);
+        public override string ToString() => AccessibleName;
     }
 }


Mark method as pure

Mark method as pure

--- ExpressionToCodeLib/ExpressionToCodeImpl.cs
+++ ExpressionToCodeLib/ExpressionToCodeImpl.cs
@@ -109,6 +109,7 @@
             readonly List<StringifiedExpression> kids;
             KidsBuilder(List<StringifiedExpression> init) { kids = init; }

+            [Pure]
             public static KidsBuilder Create() => new KidsBuilder(new List<StringifiedExpression>());

             public void Add(StringifiedExpression node) { kids.Add(node); }


Fix cache condition

Fix cache condition

--- NBXplorer/Repository.cs
+++ NBXplorer/Repository.cs
@@ -1421,7 +1421,7 @@
 		public async Task<TrackedTransaction[]> GetMatches(Transaction tx, uint256 blockId, DateTimeOffset now)
 		{
 			var h = tx.GetHash();
-			if (blockId != null && noMatchCache.Contains(h))
+			if (blockId != null || noMatchCache.Contains(h))
 			{
 				return Array.Empty<TrackedTransaction>();
 			}


More test cleanups; add test cases for inferred char constants.

--- ExpressionToCodeTest/ImplicitCastingTest.cs
+++ ExpressionToCodeTest/ImplicitCastingTest.cs
@@ -16,15 +16,34 @@
 		}

 		[Test]
-		public void StringsImplicitCast() {
+		public void CharComp() {
+			var c = 'c';
+			Assert.AreEqual(
+				@"() => c == 'b'",
+				ExpressionToCode.ToCode(() => c == 'b'));
+		}
+
+
+		[Test, Ignore("issue 4")]
+		public void DecimalImplicitCast() {
 			var i = 1;
 			var x = "X";
 			Assert.AreEqual(
-				@"() => ((""a\n\\b"" ?? x) + x).Length == 2 ? false : true && (1m + -i > 0 || false)",
-				ExpressionToCode.ToCode(() => (("a\n\\b" ?? x) + x).Length == 2 ? false : true && (1m + -i > 0 || false)));
+				@"() => (1m + -i > 0 || false)",
+				ExpressionToCode.ToCode(() => (1m + -i > 0 || false)));
 		}

-		[Test]
+
+		[Test, Ignore("issue 4")]
+		public void StringImplicitConcat() {
+			var i = 1;
+			var x = "X";
+			Assert.AreEqual(
+				@"() => 1m + x + ""!!"" + i)",
+				ExpressionToCode.ToCode(() => 1m + x + "!!" + i));
+		}
+
+		[Test, Ignore("issue 4")]
 		public void NotImplicitCast() {
 			byte z = 42;
 			Assert.AreEqual(
@@ -32,4 +51,4 @@
 				ExpressionToCode.ToCode(() => ~z == 0));
 		}
 	}
-}
+}


Const of material changed

Const of material changed

--- Nano/Cluster/Program.cs
+++ Nano/Cluster/Program.cs
@@ -34,7 +34,7 @@
     {
         static void Main (string[] args)
         {
-            var material = new Material (4000, 500, 20e-7);
+            var material = new Material (4000, 800, 20e-7);

             const double radius = 80e-7;
             var magneticVector = new Vector (1) / Math.Sqrt (3);


some ode refactoring

some ode refactoring

--- FluentFTP/Extensions/HashAlgorithm/CRC32.cs
+++ FluentFTP/Extensions/HashAlgorithm/CRC32.cs
@@ -1,19 +1,17 @@
-using System;
-using System.Security.Cryptography;
+using System.Security.Cryptography;

 namespace FluentFTP.Extensions.Hash
 {
 	class CRC32 : HashAlgorithm
 	{
+		public const uint DefaultPolynomial = 0xedb88320;

-		public const UInt32 DefaultPolynomial = 0xedb88320;
+		public const uint DefaultSeed = 0xffffffff;

-		public const UInt32 DefaultSeed = 0xffffffff;
-
-		private UInt32 hash;
-		private UInt32 seed;
-		private UInt32[] table;
-		private static UInt32[] defaultTable;
+		private uint hash;
+		private readonly uint seed;
+		private readonly uint[] table;
+		private static uint[] defaultTable;

 		public CRC32()
 		{
@@ -22,7 +20,7 @@
 			Initialize();
 		}

-		public CRC32(UInt32 polynomial, UInt32 seed)
+		public CRC32(uint polynomial, uint seed)
 		{
 			table = InitializeTable(polynomial);
 			this.seed = seed;
@@ -59,35 +57,40 @@
 			get { return 32; }
 		}

-		public static UInt32 Compute(byte[] buffer)
+		public static uint Compute(byte[] buffer)
 		{
 			return ~CalculateHash(InitializeTable(DefaultPolynomial), DefaultSeed, buffer, 0, buffer.Length);
 		}

-		public static UInt32 Compute(UInt32 seed, byte[] buffer)
+		public static uint Compute(uint seed, byte[] buffer)
 		{
 			return ~CalculateHash(InitializeTable(DefaultPolynomial), seed, buffer, 0, buffer.Length);
 		}

-		public static UInt32 Compute(UInt32 polynomial, UInt32 seed, byte[] buffer)
+		public static uint Compute(uint polynomial, uint seed, byte[] buffer)
 		{
 			return ~CalculateHash(InitializeTable(polynomial), seed, buffer, 0, buffer.Length);
 		}

-		private static UInt32[] InitializeTable(UInt32 polynomial)
+		private static uint[] InitializeTable(uint polynomial)
 		{
 			if (polynomial == DefaultPolynomial && defaultTable != null)
+			{
 				return defaultTable;
+			}

-			UInt32[] createTable = new UInt32[256];
+			uint[] createTable = new uint[256];
 			for (int i = 0; i < 256; i++)
 			{
-				UInt32 entry = (UInt32)i;
+				uint entry = (uint)i;
 				for (int j = 0; j < 8; j++)
+				{
 					if ((entry & 1) == 1)
 						entry = (entry >> 1) ^ polynomial;
 					else
-						entry = entry >> 1;
+						entry >>= 1;
+				}
+
 				createTable[i] = entry;
 			}

@@ -97,20 +100,23 @@
 			return createTable;
 		}

-		private static UInt32 CalculateHash(UInt32[] table, UInt32 seed, byte[] buffer, int start, int size)
+		private static uint CalculateHash(uint[] table, uint seed, byte[] buffer, int start, int size)
 		{
-			UInt32 crc = seed;
+			uint crc = seed;
 			for (int i = start; i < size; i++)
+			{
 				unchecked
 				{
-					crc = (crc >> 8) ^ table[buffer[i] ^ crc & 0xff];
+					crc = (crc >> 8) ^ table[buffer[i] ^ (crc & 0xff)];
 				}
+			}
+
 			return crc;
 		}

-		private byte[] UInt32ToBigEndianBytes(UInt32 x)
+		private byte[] UInt32ToBigEndianBytes(uint x)
 		{
-			return new byte[] {
+			return new [] {
 				(byte)((x >> 24) & 0xff),
 				(byte)((x >> 16) & 0xff),
 				(byte)((x >> 8) & 0xff),


Added IfEmpty and IfValue to Optional

Added IfEmpty and IfValue to Optional

--- Framework/Lokad.Cqrs.Portable/Optional.1.cs
+++ Framework/Lokad.Cqrs.Portable/Optional.1.cs
@@ -1,7 +1,8 @@
-#region (c) 2010-2011 Lokad - CQRS for Windows Azure - New BSD License
-
-// Copyright (c) Lokad 2010-2011, http://www.lokad.com
+#region (c) 2010-2011 Lokad CQRS - New BSD License
+
+// Copyright (c) Lokad SAS 2010-2011 (http://www.lokad.com)
 // This code is released as Open Source under the terms of the New BSD Licence
+// Homepage: http://lokad.github.com/lokad-cqrs/

 #endregion

@@ -10,11 +11,12 @@
 namespace Lokad.Cqrs
 {
     /// <summary>
-    /// Helper class that indicates nullable value in a good-citizenship code
+    /// Helper class that indicates nullable value in a good-citizenship code and
+    /// provides some additional piping syntax
     /// </summary>
     /// <typeparam name="T">underlying type</typeparam>
     [Serializable]
-    public sealed class Optional<T> : IEquatable<Optional<T>>
+    public sealed class Optional<T> : IEquatable<Optional<T>>
     {
         readonly T _value;
         readonly bool _hasValue;
@@ -99,7 +101,6 @@
         {
             return _hasValue ? this : defaultValue();
         }
-

         /// <summary>
@@ -145,7 +146,6 @@
         /// </summary>
         /// <typeparam name="TTarget">type of the conversion target</typeparam>
         /// <param name="converter">The converter.</param>
-
         /// <returns>value</returns>
         public Optional<TTarget> Combine<TTarget>(Func<T, Optional<TTarget>> converter)
         {
@@ -198,7 +198,7 @@
             unchecked
             {
                 // ReSharper disable CompareNonConstrainedGenericWithNull
-                return ((_value != null ? _value.GetHashCode() : 0)*397) ^ _hasValue.GetHashCode();
+                return ((_value != null ? _value.GetHashCode() : 0) * 397) ^ _hasValue.GetHashCode();
                 // ReSharper restore CompareNonConstrainedGenericWithNull
             }
         }
@@ -255,5 +255,34 @@

             return "<Empty>";
         }
+
+        /// <summary>
+        /// Eagerly applies the <paramref name="applicator"/> function, if the optional has a value.
+        /// </summary>
+        /// <param name="applicator">The applicator function.</param>
+        /// <returns>same instance for further chaining</returns>
+        public Optional<T> IfValue(Action<T> applicator)
+        {
+            if (_hasValue)
+            {
+                applicator(_value);
+            }
+            return this;
+        }
+
+        /// <summary>
+        /// Eagerly executes the <paramref name="applicator"/> functional,
+        /// if this optional does not have a value.
+        /// </summary>
+        /// <param name="applicator">The applicator.</param>
+        /// <returns>same instance for further chaining</returns>
+        public Optional<T> IfEmpty(Action applicator)
+        {
+            if (!_hasValue)
+            {
+                applicator();
+            }
+            return this;
+        }
     }
 }


Parse numbers as double by default

Parse numbers as double by default


Don't use obsolete API.

Don't use obsolete API.

--- Gu.Roslyn.Asserts/AnalyzerAssert.CodeFix.cs
+++ Gu.Roslyn.Asserts/AnalyzerAssert.CodeFix.cs
@@ -322,6 +322,29 @@

         /// <summary>
         /// Verifies that
+        /// 1. <paramref name="code"/> produces the expected diagnostics when analyzed.
+        /// 2. The code fix fixes the code.
+        /// </summary>
+        /// <param name="analyzer">The analyzer to run on the code..</param>
+        /// <param name="fix">The code fix to apply.</param>
+        /// <param name="expectedDiagnostic">The expected diagnostic.</param>
+        /// <param name="code">The code to analyze.</param>
+        /// <param name="fixedCode">The expected code produced by the code fix.</param>
+        /// <param name="fixTitle">The title of the fix to apply if more than one.</param>
+        /// <param name="allowCompilationErrors">If compilation errors are accepted in the fixed code.</param>
+        /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
+        public static async Task CodeFixAsync(DiagnosticAnalyzer analyzer, CodeFixProvider fix, ExpectedDiagnostic expectedDiagnostic, string code, string fixedCode, string fixTitle = null, AllowCompilationErrors allowCompilationErrors = AllowCompilationErrors.No)
+        {
+            CodeFixSupportsAnalyzer(analyzer, fix);
+            var diagnosticsAndSources = DiagnosticsAndSources.Create(expectedDiagnostic, new[] { code });
+            var sln = CodeFactory.CreateSolution(diagnosticsAndSources, analyzer, SuppressedDiagnostics, MetadataReferences);
+            var diagnostics = await Analyze.GetDiagnosticsAsync(sln, analyzer).ConfigureAwait(false);
+            VerifyDiagnostics(diagnosticsAndSources, diagnostics);
+            await VerifyFixAsync(sln, diagnostics, analyzer, fix, fixedCode, fixTitle, allowCompilationErrors);
+        }
+
+        /// <summary>
+        /// Verifies that
         /// 1. <paramref name="diagnosticsAndSources"/> produces the expected diagnostics when analyzed.
         /// 2. The code fix fixes the code.
         /// </summary>
@@ -337,45 +360,11 @@
         public static async Task CodeFixAsync(DiagnosticAnalyzer analyzer, CodeFixProvider fix, DiagnosticsAndSources diagnosticsAndSources, string fixedCode, string fixTitle, CSharpCompilationOptions compilationOptions, IReadOnlyList<MetadataReference> metadataReferences, AllowCompilationErrors allowCompilationErrors)
         {
             CodeFixSupportsAnalyzer(analyzer, fix);
-            var data = await DiagnosticsWithMetadataAsync(analyzer, diagnosticsAndSources, compilationOptions, metadataReferences).ConfigureAwait(false);
-            var fixableDiagnostics = data.ActualDiagnostics.SelectMany(x => x)
-                                         .Where(x => fix.FixableDiagnosticIds.Contains(x.Id))
-                                         .ToArray();
-            if (fixableDiagnostics.Length == 0)
-            {
-                var message = $"Code analyzed with {analyzer} did not generate any diagnostics fixable by {fix}.{Environment.NewLine}" +
-                              $"The analyzed code contained the following diagnostics: {{{string.Join(", ", data.ExpectedDiagnostics.Select(d => d.Id))}}}{Environment.NewLine}" +
-                              $"The code fix supports the following diagnostics: {{{string.Join(", ", fix.FixableDiagnosticIds)}}}";
-                throw AssertException.Create(message);
-            }
-
-            if (fixableDiagnostics.Length > 1)
-            {
-                var message = $"Code analyzed with {analyzer} generated more than one diagnostic fixable by {fix}.{Environment.NewLine}" +
-                              $"The analyzed code contained the following diagnostics: {{{string.Join(", ", data.ExpectedDiagnostics.Select(d => d.Id))}}}{Environment.NewLine}" +
-                              $"The code fix supports the following diagnostics: {{{string.Join(", ", fix.FixableDiagnosticIds)}}}{Environment.NewLine}" +
-                              $"Maybe you meant to call AnalyzerAssert.FixAll?";
-                throw AssertException.Create(message);
-            }
-
-            var diagnostic = fixableDiagnostics.Single();
-            var fixedSolution = await Fix.ApplyAsync(data.Solution, fix, diagnostic, fixTitle, CancellationToken.None).ConfigureAwait(false);
-            if (ReferenceEquals(data.Solution, fixedSolution))
-            {
-                throw AssertException.Create($"{fix} did not change any document.");
-            }
-
-            var fixedSource = await CodeReader.GetStringFromDocumentAsync(
-                                                  fixedSolution.GetDocument(data.Solution.GetDocument(diagnostic.Location.SourceTree).Id),
-                                                  Formatter.Annotation,
-                                                  CancellationToken.None)
-                                              .ConfigureAwait(false);
-            CodeAssert.AreEqual(fixedCode, fixedSource);
-
-            if (allowCompilationErrors == AllowCompilationErrors.No)
-            {
-                await AssertNoCompilerErrorsAsync(fix, fixedSolution).ConfigureAwait(false);
-            }
+            AnalyzerSupportsDiagnostics(analyzer, diagnosticsAndSources.ExpectedDiagnostics);
+            var sln = CodeFactory.CreateSolution(diagnosticsAndSources.Code, compilationOptions, metadataReferences);
+            var diagnostics = await Analyze.GetDiagnosticsAsync(sln, analyzer).ConfigureAwait(false);
+            VerifyDiagnostics(diagnosticsAndSources, diagnostics);
+            await VerifyFixAsync(sln, diagnostics, analyzer, fix, fixedCode, fixTitle, allowCompilationErrors);
         }

         /// <summary>
@@ -436,6 +425,48 @@
                 .GetResult();
         }

+        private static async Task VerifyFixAsync(Solution sln, IReadOnlyList<ImmutableArray<Diagnostic>> diagnostics, DiagnosticAnalyzer analyzer, CodeFixProvider fix, string fixedCode, string fixTitle = null, AllowCompilationErrors allowCompilationErrors = AllowCompilationErrors.No)
+        {
+            var fixableDiagnostics = diagnostics.SelectMany(x => x)
+                                                .Where(x => fix.FixableDiagnosticIds.Contains(x.Id))
+                                                .ToArray();
+            if (fixableDiagnostics.Length == 0)
+            {
+                var message = $"Code analyzed with {analyzer} did not generate any diagnostics fixable by {fix}.{Environment.NewLine}" +
+                              $"The analyzed code contained the following diagnostics: {{{string.Join(", ", diagnostics.SelectMany(x => x).Select(d => d.Id))}}}{Environment.NewLine}" +
+                              $"The code fix supports the following diagnostics: {{{string.Join(", ", fix.FixableDiagnosticIds)}}}";
+                throw AssertException.Create(message);
+            }
+
+            if (fixableDiagnostics.Length > 1)
+            {
+                var message = $"Code analyzed with {analyzer} generated more than one diagnostic fixable by {fix}.{Environment.NewLine}" +
+                              $"The analyzed code contained the following diagnostics: {{{string.Join(", ", diagnostics.SelectMany(x => x).Select(d => d.Id))}}}{Environment.NewLine}" +
+                              $"The code fix supports the following diagnostics: {{{string.Join(", ", fix.FixableDiagnosticIds)}}}{Environment.NewLine}" +
+                              $"Maybe you meant to call AnalyzerAssert.FixAll?";
+                throw AssertException.Create(message);
+            }
+
+            var diagnostic = fixableDiagnostics.Single();
+            var fixedSolution = await Fix.ApplyAsync(sln, fix, diagnostic, fixTitle).ConfigureAwait(false);
+            if (ReferenceEquals(sln, fixedSolution))
+            {
+                throw AssertException.Create($"{fix} did not change any document.");
+            }
+
+            var fixedSource = await CodeReader.GetStringFromDocumentAsync(
+                                                  fixedSolution.GetDocument(sln.GetDocument(diagnostic.Location.SourceTree).Id),
+                                                  Formatter.Annotation,
+                                                  CancellationToken.None)
+                                              .ConfigureAwait(false);
+            CodeAssert.AreEqual(fixedCode, fixedSource);
+
+            if (allowCompilationErrors == AllowCompilationErrors.No)
+            {
+                await AssertNoCompilerErrorsAsync(fix, fixedSolution).ConfigureAwait(false);
+            }
+        }
+
         private static void VerifyFix(Solution sln, IReadOnlyList<ImmutableArray<Diagnostic>> diagnostics, DiagnosticAnalyzer analyzer, CodeFixProvider fix, string fixedCode, string fixTitle = null, AllowCompilationErrors allowCompilationErrors = AllowCompilationErrors.No)
         {
             var fixableDiagnostics = diagnostics.SelectMany(x => x)


Moved energy visual effects to PlayerEnergy

--- Haunt/Assets/Scripts/Player/PlayerEnergy.cs
+++ Haunt/Assets/Scripts/Player/PlayerEnergy.cs
@@ -49,6 +49,13 @@
 			energy = 1;
 		energyBar.rectTransform.sizeDelta = new Vector2(25, energy * 250);
 		energyBar.rectTransform.localPosition = new Vector3(energyBar.rectTransform.localPosition.x, 0f - 0.5f*(250 - energyBar.rectTransform.sizeDelta.y), energyBar.rectTransform.localPosition.z);
+
+		//Energy visual effects
+		controller.transform.localScale = new Vector3(energy, energy, energy);
+		controller.trailRend.startWidth = energy;
+		controller.pointLight.intensity = 6 * energy;
+		controller.pointLight.range = controller.pointLight.intensity * 20f < 2 ? controller.pointLight.intensity * 20 : 2;
+		controller.effectManager.lowEnergy = energy < 0.2 && energy > 0;
 	}

 	void DrainEnergy ()