[UWP] added focus area support

[UWP] added focus area support

--- Source/ZXing.Net.Mobile.WindowsUniversal/ZXingScannerControl.xaml.cs
+++ Source/ZXing.Net.Mobile.WindowsUniversal/ZXingScannerControl.xaml.cs
@@ -368,7 +368,6 @@

                 if (focusSettings.Mode == FocusMode.Continuous || focusSettings.Mode == FocusMode.Auto)
                 {
-                    //await focusControl.UnlockAsync();
                     focusSettings.WaitForFocus = false;
                     focusControl.Configure(focusSettings);
                     await focusControl.FocusAsync();
@@ -414,36 +413,48 @@
             if (IsFocusSupported)
             {
                 var focusControl = mediaCapture.VideoDeviceController.FocusControl;
-
+                var roiControl = mediaCapture.VideoDeviceController.RegionsOfInterestControl;
                 try
                 {
-                    // todo
-                    //await focusControl.LockAsync();
-                    //var roiControl = mediaCapture.VideoDeviceController.RegionsOfInterestControl;
-                    //if (useCoordinates)
-                    //{
-                    //    await roiControl.SetRegionsAsync(new[] { region }, true);
-
-                    //    var focusRange = focusControl.SupportedFocusRanges.Contains(AutoFocusRange.FullRange)
-                    //        ? AutoFocusRange.FullRange
-                    //        : focusControl.SupportedFocusRanges.FirstOrDefault();
-
-                    //    var focusMode = focusControl.SupportedFocusModes.Contains(FocusMode.Single)
-                    //        ? FocusMode.Single
-                    //        : focusControl.SupportedFocusModes.FirstOrDefault();
-                    //    var settings = new FocusSettings
-                    //    {
-                    //        Mode = focusMode,
-                    //        AutoFocusRange = focusRange
-                    //    };
-
-                    //    focusControl.Configure(settings);
-                    //}
-                    //else
-                    //{
-                    //    // If no region provided, clear any regions and reset focus
-                    //    await roiControl.ClearRegionsAsync();
-                    //}
+                    if (roiControl.AutoFocusSupported && roiControl.MaxRegions > 0)
+                    {
+                        if (useCoordinates)
+                        {
+                            var previewEncodingProperties = mediaCapture.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview) as VideoEncodingProperties;
+                            var previewRect = GetPreviewStreamRectInControl(previewEncodingProperties, captureElement, displayOrientation);
+                            var focusPreview = ConvertUiTapToPreviewRect(new Point(x, y), new Size(20, 20), previewRect);
+                            var regionOfInterest = new RegionOfInterest
+                            {
+                                AutoFocusEnabled = true,
+                                BoundsNormalized = true,
+                                Bounds = focusPreview,
+                                Type = RegionOfInterestType.Unknown,
+                                Weight = 100
+                            };
+                            await roiControl.SetRegionsAsync(new[] { regionOfInterest }, true);
+
+                            var focusRange = focusControl.SupportedFocusRanges.Contains(AutoFocusRange.FullRange)
+                                ? AutoFocusRange.FullRange
+                                : focusControl.SupportedFocusRanges.FirstOrDefault();
+
+                            var focusMode = focusControl.SupportedFocusModes.Contains(FocusMode.Single)
+                                ? FocusMode.Single
+                                : focusControl.SupportedFocusModes.FirstOrDefault();
+
+                            var settings = new FocusSettings
+                            {
+                                Mode = focusMode,
+                                AutoFocusRange = focusRange,
+                            };
+
+                            focusControl.Configure(settings);
+                        }
+                        else
+                        {
+                            // If no region provided, clear any regions and reset focus
+                            await roiControl.ClearRegionsAsync();
+                        }
+                    }

                     await focusControl.FocusAsync();
                 }
@@ -558,24 +569,126 @@
         }

         /// <summary>
-        /// Converts the given orientation of the app on the screen to the corresponding rotation in degrees
+        /// Applies the necessary rotation to a tap on a CaptureElement (with Stretch mode set to Uniform) to account for device orientation
         /// </summary>
-        /// <param name="orientation">The orientation of the app on the screen</param>
-        /// <returns>An orientation in degrees</returns>
-        private static int ConvertDisplayOrientationToDegrees(DisplayOrientations orientation)
-        {
-            switch (orientation)
+        /// <param name="tap">The location, in UI coordinates, of the user tap</param>
+        /// <param name="size">The size, in UI coordinates, of the desired focus rectangle</param>
+        /// <param name="previewRect">The area within the CaptureElement that is actively showing the preview, and is not part of the letterboxed area</param>
+        /// <returns>A Rect that can be passed to the MediaCapture Focus and RegionsOfInterest APIs, with normalized bounds in the orientation of the native stream</returns>
+        private Rect ConvertUiTapToPreviewRect(Point tap, Size size, Rect previewRect)
+        {
+            // Adjust for the resulting focus rectangle to be centered around the position
+            double left = tap.X - size.Width / 2, top = tap.Y - size.Height / 2;
+
+            // Get the information about the active preview area within the CaptureElement (in case it's letterboxed)
+            double previewWidth = previewRect.Width, previewHeight = previewRect.Height;
+            double previewLeft = previewRect.Left, previewTop = previewRect.Top;
+
+            // Transform the left and top of the tap to account for rotation
+            switch (displayOrientation)
             {
                 case DisplayOrientations.Portrait:
-                    return 90;
+                    var tempLeft = left;
+
+                    left = top;
+                    top = previewRect.Width - tempLeft;
+                    break;
                 case DisplayOrientations.LandscapeFlipped:
-                    return 180;
+                    left = previewRect.Width - left;
+                    top = previewRect.Height - top;
+                    break;
                 case DisplayOrientations.PortraitFlipped:
-                    return 270;
-                case DisplayOrientations.Landscape:
-                default:
-                    return 0;
-            }
+                    var tempTop = top;
+
+                    top = left;
+                    left = previewRect.Width - tempTop;
+                    break;
+            }
+
+            // For portrait orientations, the information about the active preview area needs to be rotated
+            if (displayOrientation == DisplayOrientations.Portrait || displayOrientation == DisplayOrientations.PortraitFlipped)
+            {
+                previewWidth = previewRect.Height;
+                previewHeight = previewRect.Width;
+                previewLeft = previewRect.Top;
+                previewTop = previewRect.Left;
+            }
+
+            // Normalize width and height of the focus rectangle
+            var width = size.Width / previewWidth;
+            var height = size.Height / previewHeight;
+
+            // Shift rect left and top to be relative to just the active preview area
+            left -= previewLeft;
+            top -= previewTop;
+
+            // Normalize left and top
+            left /= previewWidth;
+            top /= previewHeight;
+
+            // Ensure rectangle is fully contained within the active preview area horizontally
+            left = Math.Max(left, 0);
+            left = Math.Min(1 - width, left);
+
+            // Ensure rectangle is fully contained within the active preview area vertically
+            top = Math.Max(top, 0);
+            top = Math.Min(1 - height, top);
+
+            // Create and return resulting rectangle
+            return new Rect(left, top, width, height);
+        }
+
+        /// <summary>
+        /// Calculates the size and location of the rectangle that contains the preview stream within the preview control, when the scaling mode is Uniform
+        /// </summary>
+        /// <param name="previewResolution">The resolution at which the preview is running</param>
+        /// <param name="previewControl">The control that is displaying the preview using Uniform as the scaling mode</param>
+        /// <param name="displayOrientation">The orientation of the display, to account for device rotation and changing of the CaptureElement display ratio compared to the camera stream</param>
+        /// <returns></returns>
+        public static Rect GetPreviewStreamRectInControl(VideoEncodingProperties previewResolution, CaptureElement previewControl, DisplayOrientations displayOrientation)
+        {
+            var result = new Rect();
+
+            // In case this function is called before everything is initialized correctly, return an empty result
+            if (previewControl == null || previewControl.ActualHeight < 1 || previewControl.ActualWidth < 1 ||
+                previewResolution == null || previewResolution.Height == 0 || previewResolution.Width == 0)
+            {
+                return result;
+            }
+
+            var streamWidth = previewResolution.Width;
+            var streamHeight = previewResolution.Height;
+
+            // For portrait orientations, the width and height need to be swapped
+            if (displayOrientation == DisplayOrientations.Portrait || displayOrientation == DisplayOrientations.PortraitFlipped)
+            {
+                streamWidth = previewResolution.Height;
+                streamHeight = previewResolution.Width;
+            }
+
+            // Start by assuming the preview display area in the control spans the entire width and height both (this is corrected in the next if for the necessary dimension)
+            result.Width = previewControl.ActualWidth;
+            result.Height = previewControl.ActualHeight;
+
+            // If UI is "wider" than preview, letterboxing will be on the sides
+            if ((previewControl.ActualWidth / previewControl.ActualHeight > streamWidth / (double)streamHeight))
+            {
+                var scale = previewControl.ActualHeight / streamHeight;
+                var scaledWidth = streamWidth * scale;
+
+                result.X = (previewControl.ActualWidth - scaledWidth) / 2.0;
+                result.Width = scaledWidth;
+            }
+            else // Preview stream is "wider" than UI, so letterboxing will be on the top+bottom
+            {
+                var scale = previewControl.ActualWidth / streamWidth;
+                var scaledHeight = streamHeight * scale;
+
+                result.Y = (previewControl.ActualHeight - scaledHeight) / 2.0;
+                result.Height = scaledHeight;
+            }
+
+            return result;
         }
     }
 }


Code First  BUG

Code First  BUG

--- Src/Asp.Net/SqlSugar/Abstract/CodeFirstProvider/CodeFirstProvider.cs
+++ Src/Asp.Net/SqlSugar/Abstract/CodeFirstProvider/CodeFirstProvider.cs
@@ -206,7 +206,7 @@
         }
         protected virtual string GetTableName(EntityInfo entityInfo)
         {
-            return entityInfo.DbTableName == null ? entityInfo.EntityName : entityInfo.DbTableName;
+            return this.Context.EntityProvider.GetTableName(entityInfo.DbTableName);
         }
         protected virtual DbColumnInfo EntityColumnToDbColumn(EntityInfo entityInfo, string tableName, EntityColumnInfo item)
         {


Make sure filter out instance members inherited by outer types. (changeset 1296196)

--- Src/Workspaces/Core/Recommendations/AbstractRecommendationService.cs
+++ Src/Workspaces/Core/Recommendations/AbstractRecommendationService.cs
@@ -77,11 +77,14 @@
             // unless our enclosing type derives from the members's containing type.
             if ((context.IsStatementContext || context.IsAnyExpressionContext) &&
                 !symbol.IsStatic &&
-                isMember &&
-                context.GetOuterTypes(cancellationToken).SelectMany(o => o.GetBaseTypesAndThis()).Contains(symbol.ContainingType.OriginalDefinition))
+                isMember)
             {
-                var enclosingType = context.SemanticModel.GetEnclosingNamedType(context.LeftToken.SpanStart, cancellationToken);
-                return enclosingType != null && enclosingType.GetBaseTypes().Select(b => b.OriginalDefinition).Contains(symbol.ContainingType.OriginalDefinition);
+                var outerTypesAndBases = context.GetOuterTypes(cancellationToken).SelectMany(o => o.GetBaseTypesAndThis()).Select(t => t.OriginalDefinition);
+                if (outerTypesAndBases.Contains(symbol.ContainingType.OriginalDefinition))
+                {
+                    var enclosingType = context.SemanticModel.GetEnclosingNamedType(context.LeftToken.SpanStart, cancellationToken);
+                    return enclosingType != null && enclosingType.GetBaseTypes().Select(b => b.OriginalDefinition).Contains(symbol.ContainingType.OriginalDefinition);
+                }
             }

             var namespaceSymbol = symbol as INamespaceSymbol;


Improved exception handling a tiny bit. More informative.

--- SubtextSystem/SubtextSolution/Subtext.Framework/XmlRpc/MetaWeblog.cs
+++ SubtextSystem/SubtextSolution/Subtext.Framework/XmlRpc/MetaWeblog.cs
@@ -40,21 +40,19 @@
 	/// </summary>
 	public class MetaWeblog : XmlRpcService, Subtext.Framework.XmlRpc.IMetaWeblog
 	{
-		public MetaWeblog()
-		{
-
-		}
-
-		private bool ValidateUser(string username, string password, bool AllowServiceAccess)
-		{
-			return (Config.Settings.AllowServiceAccess && AllowServiceAccess && Security.IsValidUser(username,password));
+		private bool ValidateUser(string username, string password, bool allowServiceAccess)
+		{
+			if(!Config.Settings.AllowServiceAccess || !allowServiceAccess)
+				throw new XmlRpcFaultException(0, "Web Service Access is not enabled.");
+
+			return (Security.IsValidUser(username, password));
 		}

 		#region BlogApi Members
-		public BlogInfo[] getUsersBlogs(string appKey,string username,string password)
-		{
-			Framework.BlogInfo info = Config.CurrentBlog;
-			if(ValidateUser(username,password,info.AllowServiceAccess))
+		public BlogInfo[] getUsersBlogs(string appKey, string username, string password)
+		{
+			Framework.BlogInfo info = Config.CurrentBlog;
+			if(ValidateUser(username, password, info.AllowServiceAccess))
 			{
 				BlogInfo[] bi = new BlogInfo[1];
 				BlogInfo b = new BlogInfo();
@@ -63,8 +61,8 @@
 				b.url = info.RootUrl;
 				bi[0]=b;
 				return bi;
-			}
-			throw new XmlRpcFaultException(0,"User does not exist");
+			}
+			throw new XmlRpcFaultException(0, "User does not exist.");
 		}

 		public bool deletePost(string appKey,string postid,string username,string password,[XmlRpcParameter(Description="Where applicable, this specifies whether the blog should be republished after the post has been deleted.")] bool publish)
@@ -82,7 +80,7 @@
 				}
 			}

-			throw new XmlRpcFaultException(0,"User does not exist");
+			throw new XmlRpcFaultException(0, "User does not exist");

 		}

@@ -115,7 +113,7 @@
 				}
 				return false;
 			}
-			throw new XmlRpcFaultException(0,"User does not exist");
+			throw new XmlRpcFaultException(0, "User does not exist");
 		}

 		public Post getPost(string postid,string username,string password)
@@ -135,26 +133,8 @@

 				return post;
 			}
-			throw new XmlRpcFaultException(0,"User does not exist");
-
-		}
-
-		private string[] GetCategories(int postID)
-		{
-			LinkCollection lc = Links.GetLinkCollectionByPostID(postID);
-			if(lc != null)
-			{
-				ArrayList al = new ArrayList();
-				foreach(Link l in lc)
-				{
-					al.Add(l.Title);
-				}
-				if(al.Count > 0)
-				{
-					return (string[])al.ToArray(typeof(string));
-				}
-			}
-			return null;
+			throw new XmlRpcFaultException(0, "User does not exist");
+
 		}

 		public Post[] getRecentPosts(string blogid, string username, string password, int numberOfPosts)
@@ -185,7 +165,7 @@
 				return posts;
 			}

-			throw new XmlRpcFaultException(0,"User does not exist");
+			throw new XmlRpcFaultException(0, "User does not exist");
 		}

 		public CategoryInfo[] getCategories(string blogid,string username,string password)
@@ -213,7 +193,7 @@
 				}
 				return categories;
 			}
-			throw new XmlRpcFaultException(0,"User does not exist");
+			throw new XmlRpcFaultException(0, "User does not exist");
 		}

 		public string newPost(string blogid, string username, string password, Post post, bool publish)
@@ -258,7 +238,7 @@
 				}
 				return postID.ToString(CultureInfo.InvariantCulture);
 			}
-			throw new XmlRpcFaultException(0,"User does not exist");
+			throw new XmlRpcFaultException(0, "User does not exist");
 		}

 		#region w.bloggar workarounds/nominal MT support - HACKS
@@ -332,7 +312,7 @@
 				}
 				return categories;
 			}
-			throw new XmlRpcFaultException(0,"User does not exist");
+			throw new XmlRpcFaultException(0, "User does not exist");
 		}

 		[XmlRpcMethod("mt.setPostCategories",
@@ -362,7 +342,7 @@

 				return true;
 			}
-			throw new XmlRpcFaultException(0,"User does not exist");
+			throw new XmlRpcFaultException(0, "User does not exist");
 		}

 		[XmlRpcMethod("mt.getPostCategories",
@@ -396,7 +376,7 @@

 				return categories;
 			}
-			throw new XmlRpcFaultException(0,"User does not exist");
+			throw new XmlRpcFaultException(0, "User does not exist");
 		}
 		#endregion


fix auto auto complete test

fix auto auto complete test

--- Test/NakedObjects.Mvc.Selenium.Test/Test/ObjectViewAndActionTests.cs
+++ Test/NakedObjects.Mvc.Selenium.Test/Test/ObjectViewAndActionTests.cs
@@ -385,14 +385,14 @@

             var ok = wait.ClickAndWait("#WorkOrderRepository-CreateNewWorkOrder2 button", "button[title='OK']");

-            br.FindElement(By.CssSelector("#WorkOrderRepository-CreateNewWorkOrder2-Product-Select-AutoComplete")).TypeText("f");
+            br.FindElement(By.CssSelector("#WorkOrderRepository-CreateNewWorkOrder2-Product-Select-AutoComplete")).TypeText("s");

             wait.Until(wd => wd.FindElements(By.CssSelector(".ui-menu-item")).Count > 0);

-            Assert.AreEqual(3, br.FindElements(By.CssSelector(".ui-menu-item")));
+            Assert.AreEqual(3, br.FindElements(By.CssSelector(".ui-menu-item")).Count);

             br.FindElement(By.CssSelector("#WorkOrderRepository-CreateNewWorkOrder2-Product-Select-AutoComplete")).SendKeys(Keys.ArrowDown);
-            br.FindElement(By.CssSelector("#WorkOrderRepository-CreateNewWorkOrder-Product-Select-AutoComplete")).SendKeys(Keys.Tab);
+            br.FindElement(By.CssSelector("#WorkOrderRepository-CreateNewWorkOrder2-Product-Select-AutoComplete")).SendKeys(Keys.Tab);

             wait.Until(wd => wd.FindElement(By.CssSelector("#WorkOrderRepository-CreateNewWorkOrder2-Product input")).GetAttribute("value") == "Flat Washer 3");
         }


Do not generate reference reset for container references

--- Transformations/Models.MetaTransformation/Meta/Reference2Property.cs
+++ Transformations/Models.MetaTransformation/Meta/Reference2Property.cs
@@ -434,15 +434,18 @@
                     newCheck.TrueStatements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(val, "Parent"), thisRef));
                 }

-                var resetEvent = property.IsContainment || (property.Opposite?.IsContainment).GetValueOrDefault() ? "ParentChanged" : "Deleted";
-
-                oldCheck.TrueStatements.Add(new CodeRemoveEventStatement(
-                    new CodeEventReferenceExpression(oldRef, resetEvent),
-                    new CodeMethodReferenceExpression(thisRef, "OnReset" + codeProperty.Name)));
-
-                newCheck.TrueStatements.Add(new CodeAttachEventStatement(
-                    new CodeEventReferenceExpression(val, resetEvent),
-                    new CodeMethodReferenceExpression(thisRef, "OnReset" + codeProperty.Name)));
+                if (!(property.Opposite?.IsContainment).GetValueOrDefault(false))
+                {
+                    var resetEvent = property.IsContainment ? "ParentChanged" : "Deleted";
+
+                    oldCheck.TrueStatements.Add(new CodeRemoveEventStatement(
+                        new CodeEventReferenceExpression(oldRef, resetEvent),
+                        new CodeMethodReferenceExpression(thisRef, "OnReset" + codeProperty.Name)));
+
+                    newCheck.TrueStatements.Add(new CodeAttachEventStatement(
+                        new CodeEventReferenceExpression(val, resetEvent),
+                        new CodeMethodReferenceExpression(thisRef, "OnReset" + codeProperty.Name)));
+                }

                 ifStmt.TrueStatements.Add(oldCheck);
                 ifStmt.TrueStatements.Add(newCheck);


Fix Map.VisibleRegion is null when first CameraChanged

--- Xamarin.Forms.GoogleMaps/Xamarin.Forms.GoogleMaps.UWP/MapRenderer.cs
+++ Xamarin.Forms.GoogleMaps/Xamarin.Forms.GoogleMaps.UWP/MapRenderer.cs
@@ -112,9 +112,8 @@
                 camera.Pitch,
                 sender.ZoomLevel);
             Map.CameraPosition = pos;
+            await UpdateVisibleRegion();
             Map?.SendCameraChanged(pos);
-
-            await UpdateVisibleRegion();
         }

         private void OnActualCameraChanged(MapControl sender, MapActualCameraChangedEventArgs args)


[Modify] Replace them

[Modify] Replace them

--- websocket-sharp/Server/WebSocketServer.cs
+++ websocket-sharp/Server/WebSocketServer.cs
@@ -504,14 +504,14 @@

       set {
         string msg;
-        if (!checkIfAvailable (true, false, false, true, out msg)) {
-          _logger.Error (msg);
+        if (!canSet (out msg)) {
+          _logger.Warn (msg);
           return;
         }

         lock (_sync) {
-          if (!checkIfAvailable (true, false, false, true, out msg)) {
-            _logger.Error (msg);
+          if (!canSet (out msg)) {
+            _logger.Warn (msg);
             return;
           }


[Modify] Edit it

[Modify] Edit it

--- websocket-sharp/Server/WebSocketServer.cs
+++ websocket-sharp/Server/WebSocketServer.cs
@@ -235,7 +235,7 @@
     /// </summary>
     /// <remarks>
     ///   <para>
-    ///   The new instance listens for the incoming handshake requests on
+    ///   The new instance listens for incoming handshake requests on
     ///   <paramref name="address"/> and <paramref name="port"/>.
     ///   </para>
     ///   <para>
@@ -244,11 +244,11 @@
     /// </remarks>
     /// <param name="address">
     /// A <see cref="System.Net.IPAddress"/> that represents
-    /// a local IP address of the server.
+    /// the local IP address on which to listen.
     /// </param>
     /// <param name="port">
-    /// An <see cref="int"/> that represents the number of the port
-    /// on which to listen.
+    /// An <see cref="int"/> that represents the number of
+    /// the port on which to listen.
     /// </param>
     /// <exception cref="ArgumentNullException">
     /// <paramref name="address"/> is <see langword="null"/>.


Change the DropDownListControl class, the DropDownList will be localized only once in the constructor, it will help in performance.

--- CodedUIAgilityPack/Controls/DropDownListControl.cs
+++ CodedUIAgilityPack/Controls/DropDownListControl.cs
@@ -10,22 +10,18 @@
     /// <summary>
     /// Class representing DropDownList control
     /// </summary>
-    public class DropDownListControl : IDropDownListControls
+    public class DropDownListControl : BaseControl, IDropDownListControls
     {
-        private string _controlName;
-
         /// <summary>
         /// Create a new 'select' control
         /// </summary>
         /// <param name="controlName">ID Property (ID that is render on the browser)</param>
-        public DropDownListControl(string controlName)
+        public DropDownListControl(string controlName) : base(controlName)
         {
-            if (Browse.BrowserWindow == null)
-            {
-                throw new Exception("BrowserWindow is null!");
-            }
+            DropDownList = LoadPageControls.GetComboboxByID(Browse.BrowserWindow, controlName);

-            _controlName = controlName;
+            if (DropDownList == null)
+                throw new Exception("DropDownList not found!");
         }

         /// <summary>
@@ -34,13 +30,11 @@
         /// <param name="dropDownValue">DropDown value</param>
         public void Select(string dropDownValue)
         {
-            HtmlComboBox dropDown = LoadPageControls.GetComboboxByID(Browse.BrowserWindow, _controlName);
-
-            foreach (HtmlListItem item in dropDown.Items)
+            foreach (HtmlListItem item in DropDownList.Items)
             {
                 if (item.ValueAttribute == dropDownValue)
                 {
-                    dropDown.SelectedItem = item.InnerText;
+                    DropDownList.SelectedItem = item.InnerText;
                     break;
                 }
             }
@@ -54,8 +48,7 @@
         {
             get
             {
-                HtmlComboBox dropDown = LoadPageControls.GetComboboxByID(Browse.BrowserWindow, _controlName);
-                return ((HtmlListItem)dropDown.Items[dropDown.SelectedIndex]).ValueAttribute;
+                return ((HtmlListItem)DropDownList.Items[DropDownList.SelectedIndex]).ValueAttribute;
             }
         }

@@ -67,8 +60,7 @@
         {
             get
             {
-                HtmlComboBox dropDown = LoadPageControls.GetComboboxByID(Browse.BrowserWindow, _controlName);
-                HtmlListItem item = (HtmlListItem)dropDown.Items[dropDown.SelectedIndex];
+                HtmlListItem item = (HtmlListItem)DropDownList.Items[DropDownList.SelectedIndex];
                 return new ListOptions(item.ValueAttribute, item.InnerText);
             }
         }
@@ -81,8 +73,7 @@
         {
             get
             {
-                HtmlComboBox dropDown = LoadPageControls.GetComboboxByID(Browse.BrowserWindow, _controlName);
-                return dropDown.Class;
+                return DropDownList.Class;
             }
         }

@@ -93,8 +84,7 @@
         {
             get
             {
-                HtmlComboBox dropDown = LoadPageControls.GetComboboxByID(Browse.BrowserWindow, _controlName);
-                return dropDown.GetChildren().Count;
+                return DropDownList.GetChildren().Count;
             }
         }

@@ -104,8 +94,7 @@
         /// <returns></returns>
         public List<ListOptions> GetChildren()
         {
-            HtmlComboBox dropDown = LoadPageControls.GetComboboxByID(Browse.BrowserWindow, _controlName);
-            UITestControlCollection collectionItems = dropDown.GetChildren();
+            UITestControlCollection collectionItems = DropDownList.GetChildren();

             return collectionItems.Select(item => new ListOptions(((HtmlListItem)item).ValueAttribute, ((HtmlListItem)item).InnerText)).ToList();
         }
@@ -115,10 +104,7 @@
         /// </summary>
         public HtmlComboBox DropDownList
         {
-            get
-            {
-                return LoadPageControls.GetComboboxByID(Browse.BrowserWindow, _controlName);
-            }
+            get; private set;
         }
     }
 }


Fix IsPublicFunction.Evaluate according to the report of @bignoncedric

--- Confuser.Core/Project/Patterns/IsPublicFunction.cs
+++ Confuser.Core/Project/Patterns/IsPublicFunction.cs
@@ -40,6 +40,9 @@
 				return ((PropertyDef)member).IsPublic();
 			if (member is EventDef)
 				return ((EventDef)member).IsPublic();
+			if (member is TypeDef)
+				return ((TypeDef)member).IsPublic || ((TypeDef)member).IsNestedPublic;
+
 			throw new NotSupportedException();
 		}


Type conversion using standard dotnet.

Type conversion using standard dotnet.

--- ConsoleHelpers/Console/ClassAndMethodRecognizer.cs
+++ ConsoleHelpers/Console/ClassAndMethodRecognizer.cs
@@ -9,17 +9,11 @@
     public class ClassAndMethodRecognizer
     {
         public Type Type { get; private set; }
-        private readonly Func<Object,Type,Object> _changeType;
-
+        /// <summary>
+        /// </summary>
         public ClassAndMethodRecognizer(Type type)
-            : this(type, Convert.ChangeType)
-        {
-        }
-
-        public ClassAndMethodRecognizer(Type type, Func<Object,Type,Object> changeType)
         {
             Type = type;
-            _changeType = changeType;
         }

         public bool Recognize(IEnumerable<string> arg)
@@ -38,7 +32,12 @@
             }
             return null;
         }
-
+        /// <summary>
+        /// Note that in order to register a converter you can use:
+        /// TypeDescriptor.AddAttributes(typeof(AType), new TypeConverterAttribute(typeof(ATypeConverter)));
+        /// </summary>
+        /// <param name="arg"></param>
+        /// <returns></returns>
         public ParsedMethod Parse(IEnumerable<string> arg)
         {
             var methodInfo = FindMethodInfo(arg);
@@ -55,7 +54,7 @@
                            RecognizedAction = methodInfo,
                            RecognizedActionParameters = parsedArguments.RecognizedArguments
                                .Select(
-                                   (arg1, i) => _changeType(arg1.Value, parameterInfos[i].ParameterType))
+                                   (arg1, i) => TypeDescriptor.GetConverter(parameterInfos[i].ParameterType).ConvertFrom(arg1.Value))
                                .ToList()
                        };
         }


Don't add bots as 'users' to the channel pool.

--- Coremero/Coremero.Client.Discord/DiscordChannel.cs
+++ Coremero/Coremero.Client.Discord/DiscordChannel.cs
@@ -73,10 +73,15 @@
             {
                 List<IUser> result = new List<IUser>();
                 var enumerator = _channel.GetUsersAsync().GetEnumerator();
-                while (enumerator.MoveNext().Result == true)
+                while (enumerator.MoveNext().Result)
                 {
                     foreach (var user in enumerator.Current)
                     {
+                        if (user.IsBot)
+                        {
+                            continue;
+                        }
+
                         result.Add(DiscordFactory.UserFactory.Get(user));
                     }
                 }


een iteratiefe versie van het algoritme toegevoegd recursief liep met grote getallen tegen de grenzen van de stack aan ondanks het gebruik van caching

--- MathBarld/Collatz.cs
+++ MathBarld/Collatz.cs
@@ -8,13 +8,13 @@
 {
     public static class Collatz
     {
-        static Dictionary<int, int> collatzCountCollections = new Dictionary<int, int>();
+        static Dictionary<long, long> collatzCountCollections = new Dictionary<long, long>();
         public static int GetCollectionCountRecursief(int n)
         {
             if (n == 1)
                 return 1;
             else if (collatzCountCollections.ContainsKey(n))
-                return collatzCountCollections[n];
+                return (int)collatzCountCollections[n];
             else
             {
                 int nl;
@@ -29,5 +29,39 @@
                 return nl;
             }
         }
+
+        public static int GetCollectionCountIteratief(int n)
+        {
+            int rtw = 0;
+
+            long i = n;
+
+            while (true)
+            {
+
+                if (i == 1)
+                {
+                    rtw++;
+                    break;
+                }
+                else if (collatzCountCollections.ContainsKey(i))
+                {
+                    rtw += (int)collatzCountCollections[i];
+                    break;
+                }
+                else
+                {
+                    if (i % 2 == 0)
+                        i = (i / 2);
+                    else
+                        i = (3 * i + 1);
+                    rtw++;
+                }
+            }
+
+            collatzCountCollections[n] = rtw;
+
+            return rtw;
+        }
     }
 }


Make MemoryStream read-only

Make MemoryStream read-only

--- MaxMind.Db/Reader.cs
+++ MaxMind.Db/Reader.cs
@@ -118,7 +118,7 @@
                 }
                 _stream = new ThreadLocal<Stream>(() =>
                 {
-                    return new MemoryStream(fileBytes);
+                    return new MemoryStream(fileBytes, false);
                 });
             }
             else


code back in play

code back in play

--- Demo/King.Service.ServiceBus.WorkerRole/Factory.cs
+++ Demo/King.Service.ServiceBus.WorkerRole/Factory.cs
@@ -60,10 +60,10 @@
                 Processor = () => { return new ExampleProcessor(); },
             };

-            //foreach (var t in factory.Tasks<ExampleModel>(setup))
-            //{
-            //    yield return t;
-            //}
+            foreach (var t in factory.Tasks<ExampleModel>(setup))
+            {
+                yield return t;
+            }

             //Simulate messages being added to queues
             yield return new QueueForAction(new BusQueueSender(config.PollingName, config.Connection), "Poll");


Fixed Multipart.WriteTo() to write a NewLine before each boundary

--- MimeKit/Multipart.cs
+++ MimeKit/Multipart.cs
@@ -260,7 +260,7 @@

 			base.WriteTo (options, stream);

-			if (RawPreamble != null) {
+			if (RawPreamble != null && RawPreamble.Length > 0) {
 				stream.Write (RawPreamble, 0, RawPreamble.Length);
 				stream.Write (options.NewLineBytes, 0, options.NewLineBytes.Length);
 			}
@@ -271,12 +271,13 @@
 				stream.Write (boundary, 0, boundary.Length - 2);
 				stream.Write (options.NewLineBytes, 0, options.NewLineBytes.Length);
 				part.WriteTo (options, stream);
+				stream.Write (options.NewLineBytes, 0, options.NewLineBytes.Length);
 			}

 			stream.Write (boundary, 0, boundary.Length);
 			stream.Write (options.NewLineBytes, 0, options.NewLineBytes.Length);

-			if (RawEpilogue != null) {
+			if (RawEpilogue != null && RawEpilogue.Length > 0) {
 				stream.Write (RawEpilogue, 0, RawEpilogue.Length);
 				stream.Write (options.NewLineBytes, 0, options.NewLineBytes.Length);
 			}


[UDP] Fix/finish message responses

[UDP] Fix/finish message responses

--- Desktop/Tempest/Providers/Network/UdpConnection.cs
+++ Desktop/Tempest/Providers/Network/UdpConnection.cs
@@ -325,7 +325,16 @@
 			{
 				OnMessageReceived (args);

-				// TODO responses
+				if (args.Message.Header.IsResponse)
+				{
+					TaskCompletionSource<Message> tcs;
+					bool found;
+					lock (this.messageResponses)
+						found = this.messageResponses.TryGetValue (args.Message.Header.MessageId, out tcs);
+
+					if (found)
+						tcs.TrySetResult (args.Message);
+				}
 			}
 		}


Take uploadID of the matched key not the last()

--- Minio/MinioClient.cs
+++ Minio/MinioClient.cs
@@ -109,7 +109,7 @@
         /// <param name="uri">Location of the server, supports HTTP and HTTPS.</param>
         /// <returns>Client with the uri set as the server location.</returns>
         public MinioClient(Uri uri)
-        : this(uri, null, null)
+            : this(uri, null, null)
         {
         }

@@ -121,7 +121,7 @@
         /// <param name="secretKey">Secret Key for authenticated requests</param>
         /// <returns>Client with the uri set as the server location and authentication parameters set.</returns>
         public MinioClient(string url, string accessKey, string secretKey)
-        : this(new Uri(url), accessKey, secretKey)
+            : this(new Uri(url), accessKey, secretKey)
         {
         }

@@ -131,7 +131,7 @@
         /// <param name="url">Location of the server, supports HTTP and HTTPS</param>
         /// <returns>Client with the uri set as the server location and authentication parameters set.</returns>
         public MinioClient(string url)
-        : this(new Uri(url), null, null)
+            : this(new Uri(url), null, null)
         {
         }

@@ -480,7 +480,7 @@
                     {
                         if (key == upload.Key)
                         {
-                            uploadId = uploads.Last().UploadId;
+                            uploadId = upload.UploadId;
                             var parts = this.ListParts(bucket, key, uploadId);
                             foreach (Part part in parts)
                             {


Changed access modifiers of some BorderlessWindowBase functions to Protected so that child classes can access them.

--- Digimezzo.WPFControls/Base/BorderlessWindowBase.cs
+++ Digimezzo.WPFControls/Base/BorderlessWindowBase.cs
@@ -157,8 +157,8 @@
         }
         #endregion

-        #region Private
-        private void InitializeWindow()
+        #region Public
+        protected void InitializeWindow()
         {
             // Create the WindowChrome
             this.windowChrome = new WindowChrome
@@ -188,7 +188,7 @@
             // Update the Window for the first time
             this.UpdateWindow();
         }
-        private void UpdateWindow()
+        protected void UpdateWindow()
         {
             if (this.ResizeMode == ResizeMode.CanResize || this.ResizeMode == ResizeMode.CanResizeWithGrip)
             {


Added warning if block has incorrect size

--- Duplicati/Library/Main/Operation/RestoreHandler.cs
+++ Duplicati/Library/Main/Operation/RestoreHandler.cs
@@ -243,7 +243,11 @@
                                             file.Write(blockbuffer, 0, size);
                                             blockmarker.SetBlockRestored(restorelist.FileID, targetblock.Offset / blocksize, targetblock.Key, size, false);
                                         }
-                                    }
+                                    }
+                                    else
+                                    {
+                                        result.AddWarning(string.Format("Block with hash {0} should have size {1} but has size {2}", targetblock.Key, targetblock.Size, size), null);
+                                    }
                                 }

                             if (updateCounter++ % 20 == 0)


add handleCellSwitch ()

add handleCellSwitch ()

--- DynamicListView/DynamicListView/DynamicListView.cs
+++ DynamicListView/DynamicListView/DynamicListView.cs
@@ -1,5 +1,6 @@
 using System;
 using System.Collections.Generic;
+using Android.Animation;
 using Android.Content;
 using Android.Graphics;
 using Android.Graphics.Drawables;
@@ -9,8 +10,10 @@

 namespace DynamicListView
 {
-    public class DynamicListView : ListView
+    public class DynamicListView : ListView, ViewTreeObserver.IOnPreDrawListener
     {
+        Context _context;
+
         const int SMOOTH_SCROLL_AMOUNT_AT_EDGE = 15;
         const int MOVE_DURATION = 150;
         const int LINE_THICKNESS = 15;
@@ -37,19 +40,27 @@
         Rect mHoverCellCurrentBounds;
         Rect mHoverCellOriginalBounds;

+
         const int INVALID_POINTER_ID = -1;
         int mActivePointerId = INVALID_POINTER_ID;

         bool mIsWaitingForScrollFinish = false;
         int mScrollState = 0; //OnScrollListener.SCROLL_STATE_IDLE;

+        #region ViewTreeObserver
+        ViewTreeObserver observer;
+        long observeSwitchItemID;
+        int observeSwitchViewStartTop;
+        int observeDeltaY;
+        #endregion
+
         #region Constructors
         public DynamicListView (Context context) : base (context)
         {
             Init (context);
         }

-        public DynamicListView (Context context, IAttributeSet attrs, int defStyle) : base(context, attrs, defStyle)
+        public DynamicListView (Context context, IAttributeSet attrs, int defStyle) : base (context, attrs, defStyle)
         {
             Init (context);
         }
@@ -62,6 +73,7 @@

         void Init (Context context)
         {
+            _context = context;
             throw new NotImplementedException ();
         }

@@ -170,20 +182,20 @@
         {
             switch (e.Action & MotionEventActions.Mask) {
             case MotionEventActions.Down:
-                mDownX = (int)e.GetX();
-                mDownY = (int)e.GetY();
-                mActivePointerId = e.GetPointerId(0);
+                mDownX = (int)e.GetX ();
+                mDownY = (int)e.GetY ();
+                mActivePointerId = e.GetPointerId (0);
                 break;
             case MotionEventActions.Move:
                 if (mActivePointerId == INVALID_POINTER_ID)
                     break;

-                int pointerIndex = e.FindPointerIndex(mActivePointerId);
-                mLastEventY = (int) e.GetY(pointerIndex);
+                int pointerIndex = e.FindPointerIndex (mActivePointerId);
+                mLastEventY = (int)e.GetY (pointerIndex);
                 int deltaY = mLastEventY - mDownY;

                 if (mCellIsMobile) {
-                    mHoverCellCurrentBounds.OffsetTo(mHoverCellOriginalBounds.Left, mHoverCellOriginalBounds.Top + deltaY + mTotalOffset);
+                    mHoverCellCurrentBounds.OffsetTo (mHoverCellOriginalBounds.Left, mHoverCellOriginalBounds.Top + deltaY + mTotalOffset);
                     mHoverCell.Bounds = mHoverCellCurrentBounds; // maybe SetBounds()
                     Invalidate ();
                     handleCellSwitch ();
@@ -204,7 +216,7 @@
                  * ends and the hover cell is animated to its corresponding position
                  * in the listview. */
                 pointerIndex = (int)(e.Action & MotionEventActions.PointerIndexMask) >> (int)MotionEventActions.PointerIndexShift;
-                int pointerId = e.GetPointerId(pointerIndex);
+                int pointerId = e.GetPointerId (pointerIndex);
                 if (pointerId == mActivePointerId)
                     touchEventsEnded ();
                 break;
@@ -225,8 +237,58 @@
             throw new NotImplementedException ();
         }

+        /**
+         * This method determines whether the hover cell has been shifted far enough
+         * to invoke a cell swap. If so, then the respective cell swap candidate is
+         * determined and the data set is changed. Upon posting a notification of the
+         * data set change, a layout is invoked to place the cells in the right place.
+         * Using a ViewTreeObserver and a corresponding OnPreDrawListener, we can
+         * offset the cell being swapped to where it previously was and then animate it to
+         * its new position.
+         */
         void handleCellSwitch ()
         {
+            observeDeltaY = mLastEventY - mDownY;
+            int deltaYTotal = mHoverCellOriginalBounds.Top + mTotalOffset + observeDeltaY;
+
+            View belowView = getViewForID (mBelowItemId);
+            View mobileView = getViewForID (mMobileItemId);
+            View aboveView = getViewForID (mAboveItemId);
+
+            bool isBelow = (belowView != null) && (deltaYTotal > belowView.Top);
+            bool isAbove = (aboveView != null) && (deltaYTotal < aboveView.Top);
+
+            if (isBelow || isAbove) {
+
+                observeSwitchItemID = isBelow ? mBelowItemId : mAboveItemId;
+                View switchView = isBelow ? belowView : aboveView;
+                int originalItem = GetPositionForView (mobileView);
+
+                if (switchView == null) {
+                    updateNeighborViewsForID (mMobileItemId);
+                    return;
+                }
+
+                swapElements (mCheeseList, originalItem, GetPositionForView (switchView));
+
+                ((BaseAdapter)Adapter).NotifyDataSetChanged ();
+
+                mDownY = mLastEventY;
+
+                observeSwitchViewStartTop = switchView.Top;
+
+                mobileView.Visibility = ViewStates.Visible;
+                switchView.Visibility = ViewStates.Invisible;
+
+                updateNeighborViewsForID (mMobileItemId);
+
+                observer = ViewTreeObserver;
+                observer.AddOnPreDrawListener (this);
+            }
+        }
+
+        void swapElements (List<string> mCheeseList, int originalItem, int v)
+        {
             throw new NotImplementedException ();
         }

@@ -234,6 +296,28 @@
         {
             throw new NotImplementedException ();
         }
-   }
+
+        public bool OnPreDraw ()
+        {
+            observer.RemoveOnPreDrawListener (this);
+
+            View switchView = getViewForID (observeSwitchItemID);
+
+            mTotalOffset += observeDeltaY;
+
+            int switchViewNewTop = switchView.Top;
+            int delta = observeSwitchViewStartTop - switchViewNewTop;
+
+            switchView.TranslationY = delta;
+
+            ObjectAnimator animator = ObjectAnimator.OfFloat (switchView, nameof(this.TranslationY), 0); //TODO непонтяно с TranslationY
+            animator.SetDuration (MOVE_DURATION);
+            animator.Start ();
+
+            return true;
+        }
+    }
+
+
 }


Moar Bettar sanity check of movie release date. Also, now trims up movie release date to fix time zones and DST errors.

--- MovieInfo/Program.cs
+++ MovieInfo/Program.cs
@@ -59,7 +59,7 @@
         }

         /// <summary>
-        /// The modification time of the movie.
+        /// Gets or sets the modification time of the movie.
         /// (This is usually when the movie was released in theaters.)
         /// </summary>
         public DateTime ModifiedTime
@@ -67,6 +67,10 @@
             get
             {
                 return File.LastWriteTime;
+            }
+            set
+            {
+                File.LastWriteTime = value;
             }
         }

@@ -155,6 +159,10 @@
     {
         static void Main(string[] args)
         {
+            // Allowable time drift (hours)
+            int allowedTimeError = 4;
+            bool fixFileTimesWithinError = true;
+
             // Match things like "I'm A Moive! (2006) [PG-13] HD 1080p.mkv"
             Regex parser = new Regex(@"(^.+\((TV\s*)?\d{4}\)).*\.(mkv|avi)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
             Regex parserBetter = new Regex(@"(^.+\((TV\s*)?\d{4}\)).*", RegexOptions.Compiled | RegexOptions.IgnoreCase);
@@ -183,18 +191,43 @@
             int addedSinceStartTime = 0;
             foreach (Movie movie in movies)
             {
-                // See if the release date is reasonable
-                string releasedInTheaters = movie.ModifiedTime.ToShortDateString();
-                if ((movie.ModifiedTime.Subtract(new TimeSpan(1, 0, 0)) < movie.CreatedTime) &&
-                    (movie.ModifiedTime.Add(     new TimeSpan(1, 0, 0)) > movie.CreatedTime))
-                {
-                    // The release date is +/- 1 hour from the file creation date.
-                    // That means it is probably not real. Because I'm good, but not that good.
-                    releasedInTheaters = string.Empty;
+                // Sanity check release date & time
+                string releasedInTheaters = string.Empty;
+                if ((movie.ModifiedTime.Minute == 0) &&
+                    (movie.ModifiedTime.Second == 0))
+                {
+                    // If the release minute & second are 0, it is probably a real date
+                    // Now we just need to allow for time zones & DST
+                    TimeSpan lowErr = new TimeSpan(allowedTimeError, 0, 0);
+                    TimeSpan highErr = new TimeSpan(24 - allowedTimeError, 0, 0);
+                    TimeSpan err = TimeSpan.MaxValue;
+                    if (movie.ModifiedTime.TimeOfDay <= lowErr)
+                    {
+                        // Movie is slightly after midnight
+                        err = -movie.ModifiedTime.TimeOfDay;
+                    }
+                    else if (movie.ModifiedTime.TimeOfDay >= highErr)
+                    {
+                        // Movie is slightly before midnight
+                        err = new TimeSpan(24, 0, 0) - movie.ModifiedTime.TimeOfDay;
+                    }
+
+                    // Let's correct the movie's time
+                    if (err != TimeSpan.MaxValue)
+                    {
+                        DateTime releaseDate = movie.ModifiedTime.Add(err);
+                        releasedInTheaters = releaseDate.ToShortDateString();
+
+                        // Fix file time?
+                        if (!err.Equals(TimeSpan.Zero) && fixFileTimesWithinError)
+                        {
+                            movie.ModifiedTime = releaseDate;
+                        }
+                    }
                 }

                 // Write the CSV line
-                string movieCSV = string.Format("\"{0}\",\"{1}\",{2},{3},{4},\"{5}\",{6},\"{7}\",\"{8}\"", movie.Name, movie.Path, movie.Size, movie.Width, movie.Height, movie.Quality.ToString(), movie.Trailers.ToString(), movie.CreatedTime, movie.ModifiedTime);
+                string movieCSV = string.Format("\"{0}\",\"{1}\",{2},{3},{4},\"{5}\",{6},\"{7}\",\"{8}\"", movie.Name, movie.Path, movie.Size, movie.Width, movie.Height, movie.Quality.ToString(), movie.Trailers.ToString(), movie.CreatedTime, releasedInTheaters);
                 file.WriteLine(movieCSV);

                 // See if it is new


Remove now-redundant code previously used for dictionary support

--- apis/Google.Cloud.Spanner.Data/Google.Cloud.Spanner.Data/TypeUtil.cs
+++ apis/Google.Cloud.Spanner.Data/Google.Cloud.Spanner.Data/TypeUtil.cs
@@ -13,7 +13,6 @@
 // limitations under the License.

 using System.Collections;
-using System.Collections.Generic;
 using System.Linq;

 namespace Google.Cloud.Spanner.Data
@@ -35,21 +34,5 @@
             return d1.Count == d2.Count
                 && d1.Keys.Cast<object>().All(key => d2.Contains(key) && Equals(d2[key], d1[key]));
         }
-
-        public static bool DictionaryEquals<TK, TV>(IDictionary<TK, TV> d1, IDictionary<TK, TV> d2)
-        {
-            if (d1 == null && d2 == null)
-            {
-                return true;
-            }
-
-            if (d1 == null || d2 == null)
-            {
-                return false;
-            }
-
-            return d1.Count == d2.Count
-                && d1.Keys.All(key => d2.ContainsKey(key) && Equals(d2[key], d1[key]));
-        }
     }
 }


Add implicit conversion from double to BorderDouble

--- agg/BorderDouble.cs
+++ agg/BorderDouble.cs
@@ -40,6 +40,11 @@
 		}

 		public static implicit operator BorderDouble(int valueForAll)  // explicit byte to digit conversion operator
+		{
+			return new BorderDouble(valueForAll);
+		}
+
+		public static implicit operator BorderDouble(double valueForAll)
 		{
 			return new BorderDouble(valueForAll);
 		}


Fixed a bug where each contour drawed an extra line.

--- NRasterizer/Glyph.cs
+++ NRasterizer/Glyph.cs
@@ -61,7 +61,7 @@
         private int GetContourBegin(int contourIndex)
         {
             if (contourIndex == 0) return 0;
-            return _contourEndPoints[contourIndex - 1];
+            return _contourEndPoints[contourIndex - 1]+1;
         }

         private int GetContourEnd(int contourIndex)


add some comments to structures

add some comments to structures

--- PEAnalyzer/PEFile.cs
+++ PEAnalyzer/PEFile.cs
@@ -1250,6 +1250,12 @@
             public int e_lfanew;
         }

+        /// <summary>
+        /// Represents the PE header format. (32-bit version)
+        /// </summary>
+        /// <remarks>
+        /// http://msdn.microsoft.com/en-us/library/windows/desktop/ms680336.aspx
+        /// </remarks>
         [StructLayout(LayoutKind.Explicit)]
         public struct IMAGE_NT_HEADERS32
         {
@@ -1264,6 +1270,12 @@
             public IMAGE_OPTIONAL_HEADER32 OptionalHeader;
         }

+        /// <summary>
+        /// Represents the PE header format. (64-bit version)
+        /// </summary>
+        /// <remarks>
+        /// http://msdn.microsoft.com/en-us/library/windows/desktop/ms680336.aspx
+        /// </remarks>
         [StructLayout(LayoutKind.Explicit)]
         public struct IMAGE_NT_HEADERS64
         {
@@ -1278,18 +1290,33 @@
             public IMAGE_OPTIONAL_HEADER64 OptionalHeader;
         }

+        /// <summary>
+        /// Represents the COFF header format.
+        /// </summary>
         [StructLayout(LayoutKind.Sequential)]
         public struct IMAGE_FILE_HEADER
         {
             public MachineType Machine;
+
             public ushort NumberOfSections;
+
             public uint TimeDateStamp;
+
             public uint PointerToSymbolTable;
+
             public uint NumberOfSymbols;
+
             public ushort SizeOfOptionalHeader;
+
             public ushort Characteristics;
         }

+        /// <summary>
+        /// Represents the optional header format. (32-bit version)
+        /// </summary>
+        /// <remarks>
+        /// http://msdn.microsoft.com/en-us/library/windows/desktop/ms680339.aspx
+        /// </remarks>
         [StructLayout(LayoutKind.Explicit)]
         public struct IMAGE_OPTIONAL_HEADER32
         {
@@ -1432,6 +1459,12 @@
             public IMAGE_DATA_DIRECTORY Reserved;
         }

+        /// <summary>
+        /// Represents the optional header format. (64-bit version)
+        /// </summary>
+        /// <remarks>
+        /// http://msdn.microsoft.com/en-us/library/windows/desktop/ms680339.aspx
+        /// </remarks>
         [StructLayout(LayoutKind.Explicit)]
         public struct IMAGE_OPTIONAL_HEADER64
         {
@@ -1571,13 +1604,26 @@
             public IMAGE_DATA_DIRECTORY Reserved;
         }

+        /// <summary>
+        /// Represents the data directory.
+        /// </summary>
+        /// <remarks>
+        /// http://msdn.microsoft.com/en-us/library/windows/desktop/ms680305.aspx
+        /// </remarks>
         [StructLayout(LayoutKind.Sequential)]
         public struct IMAGE_DATA_DIRECTORY
         {
             public uint VirtualAddress;
+
             public uint Size;
         }

+        /// <summary>
+        /// Represents the image section header format.
+        /// </summary>
+        /// <remarks>
+        /// http://msdn.microsoft.com/en-us/library/windows/desktop/ms680341.aspx
+        /// </remarks>
         [StructLayout(LayoutKind.Explicit)]
         public struct IMAGE_SECTION_HEADER
         {
@@ -1612,6 +1658,9 @@
             [FieldOffset(36)]
             public DataSectionFlags Characteristics;

+            /// <summary>
+            /// Gets a string representation of the section.
+            /// </summary>
             public string Section
             {
                 get { return new string(this.Name); }


Update ReleaseNotesSpecs tests to handle parsed dates from notes

Currently failing because the date "2013/11/5" isn't being caught by the
regular expression being used.

--- src/test/Test.FAKECore/ReleaseNotesSpecs.cs
+++ src/test/Test.FAKECore/ReleaseNotesSpecs.cs
@@ -37,6 +37,7 @@

         static readonly ReleaseNotesHelper.ReleaseNotes expected = ReleaseNotesHelper.ReleaseNotes.New("1.1.10",
             "1.1.10",
+            new Microsoft.FSharp.Core.FSharpOption<DateTime>(new DateTime(2013, 09, 12)),
             new[]
             {
                 "Support for heterogeneous XML attributes.",
@@ -52,20 +53,20 @@

         It should_parse_empty_notes =
             () => ReleaseNotesHelper.parseReleaseNotes(Notes.FromString(@"### New in 1.1.10 (Released 2013/09/12)"))
-                .ShouldEqual(ReleaseNotesHelper.ReleaseNotes.New("1.1.10", "1.1.10", FSharpList<string>.Empty));
+                .ShouldEqual(ReleaseNotesHelper.ReleaseNotes.New("1.1.10", "1.1.10", new Microsoft.FSharp.Core.FSharpOption<DateTime>(new DateTime(2013, 09, 12)), FSharpList<string>.Empty));

         It should_parse_simple_format =
             () => ReleaseNotesHelper.parseReleaseNotes(Notes.FromString(@"
 * 1.1.9 - Infer booleans for ints that only manifest 0 and 1. Support for partially overriding the Schema in CsvProvider.
 * 1.1.10 - Support for heterogeneous XML attributes. Make CsvFile re-entrant."))
-                .ShouldEqual(ReleaseNotesHelper.ReleaseNotes.New("1.1.10", "1.1.10",
+                .ShouldEqual(ReleaseNotesHelper.ReleaseNotes.New("1.1.10", "1.1.10", null,
                     new[] {"Support for heterogeneous XML attributes.", "Make CsvFile re-entrant."}.ToFSharpList()));

         It should_parse_simple_format_with_dots =
             () => ReleaseNotesHelper.parseReleaseNotes(Notes.FromString(@"
 * 1.2.0 - Allow currency symbols on decimals. Remove .AsTuple member from CsvProvider. CsvProvider now uses GetSample instead of constructor like the other providers."))
-                .ShouldEqual(ReleaseNotesHelper.ReleaseNotes.New("1.2.0", "1.2.0",
+                .ShouldEqual(ReleaseNotesHelper.ReleaseNotes.New("1.2.0", "1.2.0", null,
                     new[]
                     {
                         "Allow currency symbols on decimals.", "Remove .AsTuple member from CsvProvider.",
@@ -98,7 +99,7 @@
 #### 2.0.0-alpha001 - December 15 2013
 * A";
         static readonly ReleaseNotesHelper.ReleaseNotes expected =
-            ReleaseNotesHelper.ReleaseNotes.New("2.0.0", "2.0.0-alpha2", new[] { "B" }.ToFSharpList());
+            ReleaseNotesHelper.ReleaseNotes.New("2.0.0", "2.0.0-alpha2", null, new[] { "B" }.ToFSharpList());

         It should_parse =
            () => ReleaseNotesHelper.parseReleaseNotes(Notes.FromString(input)).ShouldEqual(expected);
@@ -131,7 +132,7 @@
 #### 2.0.0-alpha001 - December 15 2013
 * A";
         static readonly ReleaseNotesHelper.ReleaseNotes expected =
-            ReleaseNotesHelper.ReleaseNotes.New("2.0.0", "2.0.0-rc007", new[] { "A" }.ToFSharpList());
+            ReleaseNotesHelper.ReleaseNotes.New("2.0.0", "2.0.0-rc007", null, new[] { "A" }.ToFSharpList());

         It should_parse =
            () => ReleaseNotesHelper.parseReleaseNotes(Notes.FromString(input)).ShouldEqual(expected);
@@ -159,6 +160,7 @@

         static readonly ReleaseNotesHelper.ReleaseNotes expected = ReleaseNotesHelper.ReleaseNotes.New("1.1.10",
             "1.1.10",
+            new Microsoft.FSharp.Core.FSharpOption<DateTime>(new DateTime(2013, 09, 12)),
             new[]
             {
                 "Support for heterogeneous XML attributes.",
@@ -174,13 +176,13 @@

         It should_parse_empty_notes =
             () => ReleaseNotesHelper.parseReleaseNotes(Notes.FromString(@"### New in 1.1.10 (Released 2013/09/12)"))
-                .ShouldEqual(ReleaseNotesHelper.ReleaseNotes.New("1.1.10", "1.1.10", FSharpList<string>.Empty));
+                .ShouldEqual(ReleaseNotesHelper.ReleaseNotes.New("1.1.10", "1.1.10", new Microsoft.FSharp.Core.FSharpOption<DateTime>(new DateTime(2013, 09, 12)), FSharpList<string>.Empty));

         It should_parse_simple_format =
             () => ReleaseNotesHelper.parseReleaseNotes(Notes.FromString(@"
 * 1.1.10 - Support for heterogeneous XML attributes. Make CsvFile re-entrant.
 * 1.0.9 - Infer booleans for ints that only manifest 0 and 1. Support for partially overriding the Schema in CsvProvider."))
-                .ShouldEqual(ReleaseNotesHelper.ReleaseNotes.New("1.1.10", "1.1.10",
+                .ShouldEqual(ReleaseNotesHelper.ReleaseNotes.New("1.1.10", "1.1.10", null,
                     new[] {"Support for heterogeneous XML attributes.", "Make CsvFile re-entrant."}.ToFSharpList()));

         It should_throws_on_empty_seq_input =
@@ -215,6 +217,7 @@

         static readonly ReleaseNotesHelper.ReleaseNotes expected = ReleaseNotesHelper.ReleaseNotes.New("1.1.10",
             "1.1.10",
+            new Microsoft.FSharp.Core.FSharpOption<DateTime>(new DateTime(2013, 09, 12)),
             new[]
             {
                 "Support for heterogeneous XML attributes.",
@@ -226,6 +229,7 @@
                 .ToFSharpList());

         static readonly ReleaseNotesHelper.ReleaseNotes expected2 = ReleaseNotesHelper.ReleaseNotes.New("1.1.9", "1.1.9",
+            new Microsoft.FSharp.Core.FSharpOption<DateTime>(new DateTime(2013, 07, 21)),
             new[] {"Infer booleans for ints that only manifest 0 and 1."}
                 .ToFSharpList());

@@ -249,6 +253,7 @@

         static readonly ReleaseNotesHelper.ReleaseNotes expected = ReleaseNotesHelper.ReleaseNotes.New("0.1.3", "0.1.3",
+            new Microsoft.FSharp.Core.FSharpOption<DateTime>(new DateTime(2013, 11, 5)),
             new[]
             {
                 "New Xamarin Component store versions of Octokit.net",
@@ -275,6 +280,7 @@

         static readonly ReleaseNotesHelper.ReleaseNotes expected = ReleaseNotesHelper.ReleaseNotes.New("1.8.0", "1.8.0",
+            null,
             new[]
             {
                 "When the subject's constructor throws an exception, it is now bubbled up and shown in the failure message.",
@@ -303,6 +309,7 @@
         static readonly ReleaseNotesHelper.ReleaseNotes expected =
             ReleaseNotesHelper.ReleaseNotes.New("1.0.0",
                 "1.0.0-rc.1",
+                new Microsoft.FSharp.Core.FSharpOption<DateTime>(new DateTime(2013, 10, 30)),
                 new[]
                 {
                     "Initial release"
@@ -312,6 +319,7 @@
         static readonly ReleaseNotesHelper.ReleaseNotes expected2 =
             ReleaseNotesHelper.ReleaseNotes.New("1.0.0",
                 "1.0.0-beta.2",
+                null,
                 new[]
                 {
                     "Fixed problems with Microsoft.Threading.Tasks"


Trajectory: Fix compilation with Telemetry enabled, add force directions

--- Plugin/Trajectory.cs
+++ Plugin/Trajectory.cs
@@ -290,8 +290,14 @@
             Telemetry.AddChannel<double>("temperature_calc");

             Telemetry.AddChannel<double>("force_actual");
+            Telemetry.AddChannel<double>("force_actual.x");
+            Telemetry.AddChannel<double>("force_actual.y");
+            Telemetry.AddChannel<double>("force_actual.z");
             //Telemetry.AddChannel<double>("force_total");
             Telemetry.AddChannel<double>("force_predicted");
+            Telemetry.AddChannel<double>("force_predicted.x");
+            Telemetry.AddChannel<double>("force_predicted.y");
+            Telemetry.AddChannel<double>("force_predicted.z");
             Telemetry.AddChannel<double>("force_predicted_cache");
             //Telemetry.AddChannel<double>("force_reference");
         }
@@ -319,28 +325,28 @@
                 Vector3d bodySpacePosition = new Vector3d();
                 Vector3d bodySpaceVelocity = new Vector3d();

-                if (aerodynamicModel_ != null && vessel_ != null)
-                {
-                    CelestialBody body = vessel_.orbit.referenceBody;
-
-                    bodySpacePosition = vessel_.GetWorldPos3D() - body.position;
-                    bodySpaceVelocity = vessel_.obt_velocity;
+                if (aerodynamicModel_ != null && attachedVessel != null)
+                {
+                    CelestialBody body = attachedVessel.orbit.referenceBody;
+
+                    bodySpacePosition = attachedVessel.GetWorldPos3D() - body.position;
+                    bodySpaceVelocity = attachedVessel.obt_velocity;

                     double altitudeAboveSea = bodySpacePosition.magnitude - body.Radius;

                     Vector3d airVelocity = bodySpaceVelocity - body.getRFrmVel(body.position + bodySpacePosition);

                     double R = PreviousFramePos.magnitude;
-                    Vector3d gravityForce = PreviousFramePos * (-body.gravParameter / (R * R * R) * vessel_.totalMass);
+                    Vector3d gravityForce = PreviousFramePos * (-body.gravParameter / (R * R * R) * attachedVessel.totalMass);

                     Quaternion inverseRotationFix = body.inverseRotation ?
                         Quaternion.AngleAxis((float)(body.angularVelocity.magnitude / Math.PI * 180.0 * dt), Vector3.up)
                         : Quaternion.identity;
-                    Vector3d TotalForce = (bodySpaceVelocity - inverseRotationFix * PreviousFrameVelocity) * (vessel_.totalMass / dt);
+                    Vector3d TotalForce = (bodySpaceVelocity - inverseRotationFix * PreviousFrameVelocity) * (attachedVessel.totalMass / dt);
                     TotalForce += bodySpaceVelocity * (dt * 0.000015); // numeric precision fix
                     Vector3d ActualForce = TotalForce - gravityForce;

-                    Transform vesselTransform = vessel_.ReferenceTransform;
+                    Transform vesselTransform = attachedVessel.ReferenceTransform;
                     Vector3d vesselBackward = (Vector3d)(-vesselTransform.up.normalized);
                     Vector3d vesselForward = -vesselBackward;
                     Vector3d vesselUp = (Vector3d)(-vesselTransform.forward.normalized);
@@ -376,15 +382,15 @@
                         Vector3d.Dot(predictedForceWithCache, vesselBackward));

                     Telemetry.Send("ut", now);
-                    Telemetry.Send("altitude", vessel_.altitude);
+                    Telemetry.Send("altitude", attachedVessel.altitude);

                     Telemetry.Send("airspeed", Math.Floor(airVelocity.magnitude));
                     Telemetry.Send("aoa", (AoA * 180.0 / Math.PI));

                     Telemetry.Send("force_actual", localActualForce.magnitude);
-                    //Telemetry.Send("force_actual.x", localActualForce.x);
-                    //Telemetry.Send("force_actual.y", localActualForce.y);
-                    //Telemetry.Send("force_actual.z", localActualForce.z);
+                    Telemetry.Send("force_actual.x", localActualForce.x);
+                    Telemetry.Send("force_actual.y", localActualForce.y);
+                    Telemetry.Send("force_actual.z", localActualForce.z);

                     //Telemetry.Send("force_total", localTotalForce.magnitude);
@@ -393,9 +399,9 @@
                     //Telemetry.Send("force_total.z", localTotalForce.z);

                     Telemetry.Send("force_predicted", localPredictedForce.magnitude);
-                    //Telemetry.Send("force_predicted.x", localPredictedForce.x);
-                    //Telemetry.Send("force_predicted.y", localPredictedForce.y);
-                    //Telemetry.Send("force_predicted.z", localPredictedForce.z);
+                    Telemetry.Send("force_predicted.x", localPredictedForce.x);
+                    Telemetry.Send("force_predicted.y", localPredictedForce.y);
+                    Telemetry.Send("force_predicted.z", localPredictedForce.z);

                     Telemetry.Send("force_predicted_cache", localPredictedForceWithCache.magnitude);
                     //Telemetry.Send("force_predicted_cache.x", localPredictedForceWithCache.x);
@@ -416,14 +422,14 @@
                     //Telemetry.Send("velocity_pos.y", velocity_pos.y);
                     //Telemetry.Send("velocity_pos.z", velocity_pos.z);

-                    Telemetry.Send("drag", vessel_.rootPart.rb.drag);
-
-                    Telemetry.Send("density", vessel_.atmDensity);
+                    Telemetry.Send("drag", attachedVessel.rootPart.rb.drag);
+
+                    Telemetry.Send("density", attachedVessel.atmDensity);
                     Telemetry.Send("density_calc", StockAeroUtil.GetDensity(altitudeAboveSea, body));
-                    Telemetry.Send("density_calc_precise", StockAeroUtil.GetDensity(vessel_.GetWorldPos3D(), body));
-
-                    Telemetry.Send("temperature", vessel_.atmosphericTemperature);
-                    Telemetry.Send("temperature_calc", StockAeroUtil.GetTemperature(vessel_.GetWorldPos3D(), body));
+                    Telemetry.Send("density_calc_precise", StockAeroUtil.GetDensity(attachedVessel.GetWorldPos3D(), body));
+
+                    Telemetry.Send("temperature", attachedVessel.atmosphericTemperature);
+                    Telemetry.Send("temperature_calc", StockAeroUtil.GetTemperature(attachedVessel.GetWorldPos3D(), body));
                 }

                 PreviousFrameVelocity = bodySpaceVelocity;


Add debugging code to print font bitmap with bounds

This occurs before any glyph retargeting happens

--- QuickFont/Builder.cs
+++ QuickFont/Builder.cs
@@ -454,7 +454,25 @@
             var sizes = GetGlyphSizes(font);
             var maxSize = GetMaxGlyphSize(sizes);
             var initialBmp = CreateInitialBitmap(font, maxSize, margin, out initialGlyphs,config.TextGenerationRenderHint);
-            var initialBitmapData = initialBmp.LockBits(new Rectangle(0, 0, initialBmp.Width, initialBmp.Height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
+
+#if DEBUG
+			// print bitmap with bounds to debug it
+			var debugBmp = initialBmp.Clone() as Bitmap;
+			var graphics = Graphics.FromImage(debugBmp);
+			var pen = new Pen(Color.Red, 1);
+
+			foreach (var g in initialGlyphs)
+			{
+				graphics.DrawRectangle(pen, g.rect);
+			}
+
+			graphics.Flush();
+			graphics.Dispose();
+
+			debugBmp.Save(font.ToString() + "-DEBUG.png", ImageFormat.Png);
+#endif
+
+			var initialBitmapData = initialBmp.LockBits(new Rectangle(0, 0, initialBmp.Width, initialBmp.Height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);

             int minYOffset = int.MaxValue;
             foreach (var glyph in initialGlyphs)


Avoid exception in TypeInfo cache finalizer. Fixes issue #12.

--- RunSharp/TypeInfo.cs
+++ RunSharp/TypeInfo.cs
@@ -81,7 +81,8 @@
 			{
 				lock (cache)
 				{
-					if (cache[t].Target == this || cache[t].Target == null)
+					WeakReference wr;
+					if (cache.TryGetValue(t, out wr) && (wr.Target == this || wr.Target == null))
 						cache.Remove(t);
 				}
 			}


Minor code refactorings

Minor code refactorings

--- SampleB2B/Program.cs
+++ SampleB2B/Program.cs
@@ -11,7 +11,8 @@
         static void Main(string[] args)
         {
             Console.WriteLine("Hello World!");
-            //Suppose we want to move money from our *awesomeproduct* to *coolproduct*
+
+            // Suppose we want to move money from our *awesomeproduct* to *coolproduct*
             /*
              * Remember to register  B2B products and callback urls:else these trasactions will fail
              */
@@ -21,31 +22,39 @@
             string currencyCode = "KES";
             decimal amount = 15;
             string provider = "Athena";
-            string destinationChannel = "mychannel"; //This is the channel that will be receiving the payment
+            string destinationChannel = "mychannel"; // This is the channel that will be receiving the payment
             string destinationAccount = "coolproduct";
-            //Transfer Type
+
+            // Transfer Type
             /*
              *BusinessBuyGoods
              *BusinessPayBill
              *DisburseFundsToBusiness
              *BusinessToBusinessTransfer
              */
-            dynamic metadataDetails =  new JObject();
+            dynamic metadataDetails = new JObject();
             metadataDetails.shopName = "cartNumber";
             metadataDetails.Info = "Stuff";
             string transferType = "BusinessToBusinessTransfer";
-            var gateWay = new AfricasTalkingGateway(username,apiKey);
+            var gateWay = new AfricasTalkingGateway(username, apiKey);
             try
             {
-                string response = gateWay.MobileB2B(productName, provider, transferType, currencyCode, amount,
-                    destinationChannel, destinationAccount, metadataDetails);
+                string response = gateWay.MobileB2B(
+                    productName,
+                    provider,
+                    transferType,
+                    currencyCode,
+                    amount,
+                    destinationChannel,
+                    destinationAccount,
+                    metadataDetails);
                 Console.WriteLine(response);
             }
             catch (AfricasTalkingGatewayException e)
             {
-                Console.WriteLine("Woopsies! We ran into issues: "+e.StackTrace+" : "+e.Message);
-
+                Console.WriteLine("Woopsies! We ran into issues: " + e.StackTrace + " : " + e.Message);
             }
+
             Console.ReadLine();
         }
     }


Fixes Reverp/Toxy#19

Fixes Reverp/Toxy#19

--- SharpTox/Core/Tox.cs
+++ SharpTox/Core/Tox.cs
@@ -189,7 +189,7 @@
         private bool connected = false;

         /// <summary>
-        /// Setting this to false will make sure that resolving sticks strictly to IPv4 addresses.
+        /// Options used for this instance of Tox.
         /// </summary>
         public ToxOptions Options { get; private set; }

@@ -364,8 +364,8 @@

             int result = ToxFunctions.Load(tox, bytes, (uint)bytes.Length);

-            if (result != 1)
-                return result == 0;
+            if (result == 0 || result == -1) //apparently -1 doesn't necessarily mean that the data didn't load
+                return true;
             else
                 throw new Exception("Could not load encrypted data file. Use LoadEncrypted instead.");
         }


Change the logic to avoid nesting the Action<T>

--- SlackSocketClient.cs
+++ SlackSocketClient.cs
@@ -74,9 +74,11 @@
                 userName = MySelf.id;
             }

-            underlyingSocket.Send(
-                new Message() { channel = channelId, text = textData, user = userName, type = "message" },
-                new Action<MessageReceived>(received => onSent?.Invoke(received)));
+            if (onSent != null) {
+                underlyingSocket.Send( new Message() {channel = channelId, text = textData, user = userName, type = "message"}, onSent);
+            } else {
+                underlyingSocket.Send(new Message() { channel = channelId, text = textData, user = userName, type = "message" });
+            }
         }

         public void HandleHello(Hello hello)


Use error code constant instead of magic number

--- SnappyMap/Program.cs
+++ SnappyMap/Program.cs
@@ -29,7 +29,7 @@
                 Console.WriteLine("Missing required arguments.");
                 Console.WriteLine();
                 Console.WriteLine(options.GetUsage());
-                return 1;
+                return ErrorExitCode;
             }

             string[] parts = options.Size.Split(new[] { 'x' }, 2);
@@ -38,7 +38,7 @@
                 Console.WriteLine("Invalid map size: " + options.Size);
                 Console.WriteLine();
                 Console.WriteLine(options.GetUsage());
-                return 1;
+                return ErrorExitCode;
             }

             int mapWidth;
@@ -49,7 +49,7 @@
                 Console.WriteLine("Invalid map width: " + parts[0]);
                 Console.WriteLine();
                 Console.WriteLine(options.GetUsage());
-                return 1;
+                return ErrorExitCode;
             }

             if (!int.TryParse(parts[1], out mapHeight))
@@ -57,7 +57,7 @@
                 Console.WriteLine("Invalid map height: " + parts[1]);
                 Console.WriteLine();
                 Console.WriteLine(options.GetUsage());
-                return 1;
+                return ErrorExitCode;
             }

             if (mapWidth <= 0 || mapHeight <= 0)
@@ -65,7 +65,7 @@
                 Console.WriteLine("Map dimensions ({0}x{1}) too small.", mapWidth, mapHeight);
                 Console.WriteLine();
                 Console.WriteLine(options.GetUsage());
-                return 1;
+                return ErrorExitCode;
             }

             // We only place tiles on grid intersections,


debug stuff

debug stuff

--- TCC.Core/App.xaml.cs
+++ TCC.Core/App.xaml.cs
@@ -1,5 +1,6 @@
 using Newtonsoft.Json.Linq;
 using System;
+using System.Collections.Generic;
 using System.Diagnostics;
 using System.IO;
 using System.Linq;
@@ -7,6 +8,7 @@
 using System.Reflection;
 using System.Text;
 using System.Threading;
+using System.Threading.Tasks;
 using System.Windows;
 using System.Windows.Interop;
 using System.Windows.Media;
@@ -31,7 +33,7 @@

         public const string ThankYou_mEME =
             "Due to the recent events regarding EME's DMCA takedowns of proxy related repositories, TCC will stop to be supported for NA, meaning that all data required to make it work after patch won't be released for this region. Sorry for this and thanks for all your support.";
-        public static bool Loading { get; set; }
+        public static bool Loading { get; private set; }
         //public static DebugWindow DebugWindow;

         private void OnStartup(object sender, StartupEventArgs e)
@@ -93,35 +95,70 @@

             UpdateManager.StartCheck();

-            if(Settings.LastRegion == "NA" || Settings.LastRegion == "")
+            if (Settings.LastRegion == "NA" || Settings.LastRegion == "")
                 WindowManager.FloatingButton.NotifyExtended("So long, and thanks for all the fish", ThankYou_mEME, NotificationType.Error, 15000);
-
-            if(Debug) DebugStuff();
+            DebugStuff();
             Loading = false;
         }
-
+

         private static void DebugStuff()
         {
-            GroupWindowViewModel.Instance.AddOrUpdateMember(new User(BaseDispatcher)
-            {
-                Alive = true,
-                Awakened = true,
-                CurrentHp = 1000,
-                MaxHp = 1000,
-                EntityId = 1,
-                ServerId = 1,
-                PlayerId = 1,
-                UserClass = Class.Archer,
-                Online = true
-            });
-            EntitiesManager.SpawnNPC(920, 3000, 11, Visibility.Visible);
-            EntitiesManager.SpawnNPC(15, 1, 12, Visibility.Visible);
-            EntitiesManager.UpdateNPC(12,1000,1000);
-            AbnormalityManager.BeginOrRefreshPartyMemberAbnormality(1,1, 1495, 200000,1);
-            AbnormalityManager.BeginAbnormality(1495,10,200000,1);
-            AbnormalityManager.BeginAbnormality(1495,11,200000,1);
-            AbnormalityManager.BeginAbnormality(1495,12,200000,1);
+
+
+            //var i = 0;
+            //while (i < 20000)
+            //{
+            //    ChatWindowManager.Instance.AddTccMessage($"Test {i++}");
+            //}
+            //GC.Collect();
+            //GC.WaitForPendingFinalizers();
+            //GroupWindowViewModel.Instance.AddOrUpdateMember(new User(BaseDispatcher)
+            //{
+            //    Alive = true,
+            //    Awakened = true,
+            //    CurrentHp = 1000,
+            //    MaxHp = 1000,
+            //    EntityId = 1,
+            //    ServerId = 1,
+            //    PlayerId = 1,
+            //    UserClass = Class.Archer,
+            //    Online = true
+            //});
+            //bool up = true;
+            //bool inv = false;
+            //ulong i = 0;
+            //while (true)
+            //{
+            //    if (i > 1000)
+            //    {
+            //        up = false;
+            //        if(!inv) Thread.Sleep(10000);
+            //        inv = true;
+            //    }
+
+            //    if (up)
+            //    {
+
+            //        Console.WriteLine($"[{i}] Spawning NPCs");
+            //        EntitiesManager.SpawnNPC(15, 1, i, Visibility.Visible);
+            //        i++;
+            //    }
+            //    else
+            //    {
+            //        Console.WriteLine($"[{i}] Despawning NPCs");
+            //        EntitiesManager.DespawnNPC(i, DespawnType.OutOfView);
+            //        i--;
+            //    }
+            //    Thread.Sleep(2);
+            //    if (i == 0) {break;}
+            //}
+            //EntitiesManager.SpawnNPC(920, 3000, 11, Visibility.Visible);
+            //EntitiesManager.UpdateNPC(12, 1000, 1000);
+            //AbnormalityManager.BeginOrRefreshPartyMemberAbnormality(1, 1, 1495, 200000, 1);
+            //AbnormalityManager.BeginAbnormality(1495, 10, 200000, 1);
+            //AbnormalityManager.BeginAbnormality(1495, 11, 200000, 1);
+            //AbnormalityManager.BeginAbnormality(1495, 12, 200000, 1);

             //for (int i = 0; i < 2000; i++)
             //{
@@ -176,7 +213,7 @@

             //var l = new List<User>();
             //var r = new Random();
-            //for (uint i = 0; i < 10; i++)
+            //for (uint i = 0; i <= 10; i++)
             //{
             //    var u = new User(GroupWindowViewModel.Instance.GetDispatcher())
             //    {
@@ -185,9 +222,9 @@
             //        ServerId = i,
             //        EntityId = i,
             //        Online = true,
-            //        Laurel = (Laurel)(r.Next(0, 5)),
+            //        Laurel = (Laurel)(r.Next(0, 6)),
             //        HasAggro = i == 1,
-            //        Alive = i != 0,
+            //        Alive = true, //i != 0,
             //        UserClass = (Class)r.Next(0, 12),
             //        Awakened = i < 5,
             //    };
@@ -201,7 +238,6 @@
         private static void TeraSniffer_OnNewConnection(Server srv)
         {
             PacketProcessor.Server = srv;
-            SkillManager.Clear();
             WindowManager.TrayIcon.Icon = WindowManager.ConnectedIcon;
             ChatWindowManager.Instance.AddTccMessage($"Connected to {srv.Name}.");
             WindowManager.FloatingButton.NotifyExtended("TCC", $"Connected to {srv.Name}", NotificationType.Success);
@@ -224,7 +260,7 @@
         private static void GlobalUnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs e)
         {
             var ex = (Exception)e.ExceptionObject;
-            File.WriteAllText(Path.GetDirectoryName(typeof(App).Assembly.Location)+ "/error.txt",
+            File.WriteAllText(Path.GetDirectoryName(typeof(App).Assembly.Location) + "/error.txt",
                 "##### CRASH #####\r\n" + ex.Message + "\r\n" +
                 ex.StackTrace + "\r\n" + ex.Source + "\r\n" + ex + "\r\n" + ex.Data + "\r\n" + ex.InnerException +
                 "\r\n" + ex.TargetSite);
@@ -315,7 +351,7 @@
         {
             try
             {
-                File.Delete(Path.GetDirectoryName(typeof(App).Assembly.Location)+ "/TCCupdater.exe");
+                File.Delete(Path.GetDirectoryName(typeof(App).Assembly.Location) + "/TCCupdater.exe");
             }
             catch
             {


[add]: データを受け取る処理記述

[add]: データを受け取る処理記述

--- block-program/Communication/CommunicationService.cs
+++ block-program/Communication/CommunicationService.cs
@@ -13,6 +13,19 @@
         public CommunicationService()
         {
             this.RobotPort = new SerialPort();
+            this.RobotPort.DataReceived += DataReceived;
+        }
+
+        private void DataReceived(object sender, SerialDataReceivedEventArgs e)
+        {
+            var port = sender as SerialPort;
+            if(port == null)
+            {
+                return;
+            }
+            string indata = port.ReadExisting();
+            byte[] data = System.Text.ASCIIEncoding.ASCII.GetBytes(indata);
+            var packet = new Robot.Robot2PcPacket(data);
         }

         protected void Do(Robot.Command command)


Write the move method

Write the move method

--- Tron/Tron/Car/Car.cs
+++ Tron/Tron/Car/Car.cs
@@ -94,17 +94,33 @@
         /// <summary>
         /// Moves the car.
         /// </summary>
+        /// <param name="grid"> The grid cars move in. </param>
         /// <param name="firstMove"> Whether this is the first time running the method when it is acting recursively. </param>
-        public void Move(bool firstMove = true)
+        public void Move(CellValues[][] grid, bool firstMove = true)
         {
             if (this.Alive)
             {
-                // TODO: Implement move method
+                // Check if the car has crashed before movement
+                if (this.Crashed(grid))
+                {
+                    this.Alive = false;
+                    return;
+                }
+
+                // Move the car now we know it hasn't already crashed
+                this.Move();
+
+                // Check collision again
+                if (this.Crashed(grid))
+                {
+                    this.Alive = false;
+                    return;
+                }

                 // Move twice if boost is active
                 if (this.IsBoosting && firstMove)
                 {
-                    this.Move(false);
+                    this.Move(grid, false);

                     // Check if boost time is up
                     this.BoostTimeRemeaning--;
@@ -117,6 +133,23 @@
         }

         /// <summary>
+        /// Checks if the car has crashed.
+        /// </summary>
+        /// <param name="grid"> The grid cars move in. </param>
+        /// <returns> Whether the car has crashed. </returns>
+        public bool Crashed(CellValues[][] grid)
+        {
+            if (grid[this.X][this.Y] != CellValues.None)
+            {
+                return true;
+            }
+            else
+            {
+                return false;
+            }
+        }
+
+        /// <summary>
         /// Changes the direction of the car.
         /// </summary>
         /// <param name="direction"> The new direction. </param>
@@ -148,5 +181,28 @@
                 this.BoostTimeRemeaning = 15;
             }
         }
+
+        /// <summary>
+        /// Move the car.
+        /// </summary>
+        protected void Move()
+        {
+            if (this.Direction == Tron.Direction.Up)
+            {
+                this.Y--;
+            }
+            else if (this.Direction == Tron.Direction.Right)
+            {
+                this.X++;
+            }
+            else if (this.Direction == Tron.Direction.Down)
+            {
+                this.Y++;
+            }
+            else if (this.Direction == Tron.Direction.Left)
+            {
+                this.X--;
+            }
+        }
     }
 }


Add timestamp and match_type variables

Add timestamp and match_type variables

--- tcpTrigger/Classes/UserVariableExpansion.cs
+++ tcpTrigger/Classes/UserVariableExpansion.cs
@@ -1,4 +1,5 @@
-using System.Net;
+using System;
+using System.Net;

 namespace tcpTrigger
 {
@@ -8,14 +9,16 @@
         public const string InterfaceMac = "{INTERFACE_MAC}";
         public const string InterfaceDescription = "{INTERFACE_DESCRIPTION}";
         public const string ConnectionLog = "{CONNECTION_LOG}";
+
         public const string SourceIp = "{SOURCE_IP}";
+        public const string SourcePort = "{SOURCE_PORT}";
+        public const string SourceHostname = "{SOURCE_HOSTNAME}";
         public const string DestinationIp = "{DESTINATION_IP}";
-        public const string SourcePort = "{SOURCE_PORT}";
         public const string DestinationPort = "{DESTINATION_PORT}";
-        public const string SourceHostname = "{SOURCE_HOSTNAME}";
         public const string DestinationHostname = "{DESTINATION_HOSTNAME}";
         public const string DestinationMac = "{DESTINATION_MAC}";
-        public const string DhcpServerIp = "{DHCP_SERVER_IP}";
+        public const string Timestamp = "{TIMESTAMP}";
+        public const string MatchType = "{MATCH_TYPE}";
         public const string TcpFlags = "{TCP_FLAGS}";

         public static string GetExpandedString(string message, PacketHeader header)
@@ -23,11 +26,11 @@
             if (message.Contains(SourceIp))
                 message = message.Replace(SourceIp, header.SourceIP?.ToString());

+            if (message.Contains(SourcePort))
+                message = message.Replace(SourcePort, header.SourcePort.ToString());
+
             if (message.Contains(DestinationIp))
                 message = message.Replace(DestinationIp, header.DestinationIP?.ToString());
-
-            if (message.Contains(SourcePort))
-                message = message.Replace(SourcePort, header.SourcePort.ToString());

             if (message.Contains(DestinationPort))
                 message = message.Replace(DestinationPort, header.DestinationPort.ToString());
@@ -35,11 +38,36 @@
             if (message.Contains(DestinationMac))
                 message = message.Replace(DestinationMac, header.DestinationMacAsString);

-            if (message.Contains(DhcpServerIp))
-                message = message.Replace(DhcpServerIp, header.DhcpServerAddress?.ToString());
-
             if (message.Contains(TcpFlags))
                 message = message.Replace(TcpFlags, header.TcpFlagsAsString);
+
+            if (message.Contains(Timestamp))
+                message = message.Replace(Timestamp, DateTime.Now.ToString(Settings.TimestampFormat));
+
+            if (message.Contains(MatchType))
+            {
+                string t;
+                switch (header.MatchType)
+                {
+                    case PacketMatch.IcmpRequest:
+                        t = "ICMP";
+                        break;
+                    case PacketMatch.TcpConnect:
+                        t = "TCP";
+                        break;
+                    case PacketMatch.UdpCommunication:
+                        t = "UDP";
+                        break;
+                    case PacketMatch.RogueDhcp:
+                        t = "DHCP";
+                        break;
+                    case PacketMatch.None:
+                    default:
+                        t = "None";
+                        break;
+                }
+                message = message.Replace(MatchType, t);
+            }

             if (message.Contains(SourceHostname))
             {


tweak comments for time series

tweak comments for time series

--- csharp/src/ITimeSeries.cs
+++ csharp/src/ITimeSeries.cs
@@ -3,32 +3,28 @@
     using System;
     using System.Collections.Generic;

-    /// <summary>
-    /// Interface for timeseries element.
-    /// You should derive your time series element from this class
-    /// and implement Ticks getter method.
+    /// <summary>Interface for time series elements.
+    /// Objects inserted into time series must implement this interface.
     /// </summary>
     public interface ITimeSeriesTick
     {
         /// <summary>
-        /// Get time series element timestamp (100 nanoseconds)
+        /// Get time series element timestamp. Has the same meaning as DateTime.Ticks (100 nanoseconds).
         /// </summary>
         long Ticks { get; }
     }

-    /// <summary>
-    /// Time series is used for efficient
-    /// handling of time series data. Usually time series contains a very large number
-    /// of relatively small elements which are usually accessed in sucessive order.
-    /// To avoid overhead of loading from the disk each particular time series element,
-    /// this class group several subsequent time series elements together and store them
+    /// <summary>Time series is used for efficiently handling of time series data.
+    /// Time series usually contains a very large number
+    /// of small elements which are usually accessed in sucessive order.
+    /// To avoid overhead of loading elements from the disk one at a time,
+    /// Volante groups several elements together and stores them
     /// as single object (block).
     /// </summary>
     public interface ITimeSeries<T> : IPersistent, IResource, ICollection<T> where T : ITimeSeriesTick
     {
-
         /// <summary>
-        /// Get forward iterator for time series elements belonging to the specified range
+        /// Get forward iterator for time series elements in the given time interval
         /// </summary>
         /// <param name="from">inclusive time of the beginning of interval</param>
         /// <param name="till">inclusive time of the ending of interval</param>
@@ -36,23 +32,23 @@
         IEnumerator<T> GetEnumerator(DateTime from, DateTime till);

         /// <summary>
-        /// Get iterator through all time series elements
+        /// Get iterator for all time series elements
         /// </summary>
         /// <param name="order">direction of iteration</param>
         /// <returns>iterator in specified direction</returns>
         IEnumerator<T> GetEnumerator(IterationOrder order);

         /// <summary>
-        /// Get forward iterator for time series elements belonging to the specified range
+        /// Get forward iterator for time series elements in a given time interval
         /// </summary>
         /// <param name="from">inclusive time of the beginning  of interval</param>
         /// <param name="till">inclusive time of the ending of interval</param>
         /// <param name="order">direction of iteration</param>
-        /// <returns>iterator within specified range in specified direction</returns>
+        /// <returns>iterator within specified range in the specified direction</returns>
         IEnumerator<T> GetEnumerator(DateTime from, DateTime till, IterationOrder order);

         /// <summary>
-        /// Get forward iterator for time series elements belonging to the specified range
+        /// Get forward iterator for time series elements in a given time interval
         /// </summary>
         /// <param name="from">inclusive time of the beginning  of interval</param>
         /// <param name="till">inclusive time of the ending of interval</param>
@@ -96,19 +92,19 @@
         IEnumerable<T> Reverse();

         /// <summary>
-        /// Get timestamp of first time series element
+        /// Get timestamp of first element in time series
         /// </summary>
         /// <exception cref="Volante.DatabaseException">DatabaseException(DatabaseException.ErrorClass.KEY_NOT_FOUND) if time series is empy</exception>
         DateTime FirstTime { get; }

         /// <summary>
-        /// Get timestamp of last time series element
+        /// Get timestamp of last element in time series
         /// </summary>
         /// <exception cref="Volante.DatabaseException">DatabaseException(DatabaseException.ErrorClass.KEY_NOT_FOUND) if time series is empy</exception>
         DateTime LastTime { get; }

         /// <summary>
-        /// Get tick for specified data
+        /// Get element for a given timestamp
         /// </summary>
         /// <param name="timestamp">time series element timestamp</param>
         /// <exception cref="Volante.DatabaseException">DatabaseException(DatabaseException.ErrorClass.KEY_NOT_FOUND) if no element with such timestamp exists</exception>
@@ -141,14 +137,14 @@
         int RemoveFrom(DateTime from);

         /// <summary>
-        /// Remove time series elements with timestamp less or equal then specified
+        /// Remove elements with timestamp less or equal then specified
         /// </summary>
         /// <param name="till">inclusive time of the ending of interval</param>
         /// <returns>number of removed elements</returns>
         int RemoveTill(DateTime till);

         /// <summary>
-        /// Remove all time series elements
+        /// Remove all elements
         /// </summary>
         /// <returns>number of removed elements</returns>
         int RemoveAll();


Removes the benchmark for SharedQueueWatcher. No longer needed.

This reverts commit 53af242e35c4190f694429f75f383b2a444251c4.

--- test/Benchmarks/WebjobsExtensionsStorage.cs
+++ test/Benchmarks/WebjobsExtensionsStorage.cs
@@ -2,7 +2,6 @@
 using BenchmarkDotNet.Attributes;
 using Microsoft.Azure.Storage.Queue;
 using Microsoft.Azure.WebJobs.Host.Queues;
-using Microsoft.Azure.WebJobs.Host.Queues.Listeners;
 using Newtonsoft.Json.Linq;

 namespace Benchmarks
@@ -10,10 +9,8 @@
     [MemoryDiagnoser]
     public class WebjobsExtensionsStorage
     {
-        const string WatcherQueueName = "test";
         readonly CloudQueueMessage _minimal;
         readonly CloudQueueMessage _moderate;
-        readonly SharedQueueWatcher _watcher;

         public WebjobsExtensionsStorage()
         {
@@ -34,10 +31,6 @@
             };

             _moderate = new CloudQueueMessage(moderate.ToString());
-
-            // assume one listener
-            _watcher = new SharedQueueWatcher();
-            _watcher.Register(WatcherQueueName, new NoopNotifyCommand());
         }

         [Benchmark]
@@ -51,16 +44,5 @@
         {
             return QueueCausalityManager.GetOwner(_moderate);
         }
-
-        [Benchmark]
-        public void SharedQueueWatcher_Notify()
-        {
-            _watcher.Notify(WatcherQueueName);
-        }
-
-        class NoopNotifyCommand : INotificationCommand
-        {
-            public void Notify() { }
-        }
     }
 }


Bug fix

Bug fix

--- test/Evolve.Core.Test.Driver/TestContext.cs
+++ test/Evolve.Core.Test.Driver/TestContext.cs
@@ -22,7 +22,11 @@
         public static string DriverResourcesDepsFile { get; }
         public static string NugetPackageFolder => $@"{EnvHome}/.nuget/packages";
         public static string PgPassword => Environment.GetEnvironmentVariable("PGPASSWORD") ?? "Password12!";
-        public static string MySqlPassword => Environment.GetEnvironmentVariable("MYSQL_PWD") ?? "";
+#if DEBUG
+        public static string MySqlPassword => "Password12!";
+#else
+        public static string MySqlPassword => Environment.GetEnvironmentVariable("MYSQL_PWD") ?? ""; // "" pour Travis CI
+#endif
         public static string EnvHome => Environment.GetEnvironmentVariable("USERPROFILE") ?? Environment.GetEnvironmentVariable("HOME");
     }
 }


Enable endpoint routing

Enable endpoint routing

--- test/LtiLibrary.AspNetCore.Tests/Startup.cs
+++ test/LtiLibrary.AspNetCore.Tests/Startup.cs
@@ -17,7 +17,10 @@
         // This method gets called by the runtime. Use this method to add services to the container.
         public void ConfigureServices(IServiceCollection services)
         {
-            services.AddMvc();
+            services.AddMvc(opt =>
+            {
+                opt.EnableEndpointRouting = true;
+            });
             services.AddLogging(opt =>
             {
                 opt.AddConsole();


ZooKeeperNet: Minor cleanup: Remove unused field in Packet class

The presence of the unused field causes a warning with current .NET
compilers:

> warning CS0649: Field 'Packet.finished' is never assigned to, and
> will always have its default value 0

--- src/dotnet/ZooKeeperNet/Packet.cs
+++ src/dotnet/ZooKeeperNet/Packet.cs
@@ -35,7 +35,6 @@
         private string serverPath;
         internal ReplyHeader replyHeader;
         internal IRecord response;
-        private int finished;
         internal ZooKeeper.WatchRegistration watchRegistration;
         internal readonly byte[] data;
         public readonly DateTime DateCreated;
@@ -109,7 +108,7 @@

             sb.Append("  clientPath:").Append(clientPath);
             sb.Append("  serverPath:").Append(serverPath);
-            sb.Append("    finished:").Append(finished);
+            sb.Append("    finished:").Append(mreslim.IsSet);
             sb.Append("     header::").Append(header);
             sb.Append("replyHeader::").Append(replyHeader);
             sb.Append("    request::").Append(request);