Fix method name normalization

Fix method name normalization

--- Mono.Cecil/Import.cs
+++ Mono.Cecil/Import.cs
@@ -90,7 +90,7 @@

 		public string NormalizeMethodName (MethodReference method)
 		{
-			return method.DeclaringType.FullName + "." + method.Name;
+			return method.DeclaringType.GetElementType ().FullName + "." + method.Name;
 		}

 		public TypeReference TypeParameter (string type, int position)


Remove Zip stub file

Remove Zip stub file

This was there for the source package[1] when embedded in a project
targeting Microsoft .NET Framework 4.0. The source packages are not
being maintained anymore since it would prevent use of newer C#
releases that are now being published with much greater cadence
than in the past.

[1] https://www.nuget.org/packages/MoreLinq.Source.MoreEnumerable.Zip/

--- MoreLinq/Zip.stub.cs
+++ MoreLinq/Zip.stub.cs
@@ -1,4 +0,0 @@
-// An implementation of Zip for sequences is included in Microsoft .NET
-// Framework starting with version 4.0 and is identical to Zip in MoreLINQ.
-// For more information on Zip, see the following reference on MSDN:
-// http://msdn.microsoft.com/en-us/library/dd267698.aspx


Added ability to parse longs.

Added ability to parse longs.

--- NXmlMapper/Mapper.cs
+++ NXmlMapper/Mapper.cs
@@ -309,6 +309,14 @@
                     propertyInfo.SetValue(target, value);
                 }
             }
+            else if (propertyType == typeof(long))
+            {
+                long value;
+                if (long.TryParse(input, out value))
+                {
+                    propertyInfo.SetValue(target, value);
+                }
+            }
             else if (propertyType == typeof(string))
             {
                 propertyInfo.SetValue(target, input);
@@ -317,9 +325,9 @@
             {
                 DateTime dt;
                 bool success = false;
-
-                success = string.IsNullOrEmpty(parseOptions)
-                    ? DateTime.TryParse(input, out dt)
+
+                success = string.IsNullOrEmpty(parseOptions)
+                    ? DateTime.TryParse(input, out dt)
                     : DateTime.TryParseExact(input, parseOptions, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);

                 if (success)


Implement AND OR XOR

Implement AND OR XOR

--- RakudaSlack/Basic.cs
+++ RakudaSlack/Basic.cs
@@ -82,6 +82,9 @@
         MakeProcInstance,
         Def,
         End,
+        And,
+        Or,
+        Xor,
     }
     struct Token
     {
@@ -466,6 +469,12 @@
                                 return new Token(TokenType.Def, v);
                             case "END":
                                 return new Token(TokenType.End, v);
+                            case "AND":
+                                return new Token(TokenType.And, v);
+                            case "OR":
+                                return new Token(TokenType.Or, v);
+                            case "XOR":
+                                return new Token(TokenType.Xor, v);
                             default:
                                 return new Token(TokenType.Iden, v);
                         }
@@ -704,9 +713,49 @@

                 }
             }
+            public Value Expr7()
+            {
+                var expr = Expr6();
+                while (true)
+                {
+                    var token = Current;
+                    if (token.Type != TokenType.And)
+                    {
+                        return expr;
+                    }
+                    Next();
+                    var expr2 = Expr6();
+                    if (token.Type == TokenType.And)
+                    {
+                        expr = new Value((int)expr.Number & (int)expr2.Number);
+                    }
+                }
+            }
+            public Value Expr9()
+            {
+                var expr = Expr7();
+                while (true)
+                {
+                    var token = Current;
+                    if (token.Type != TokenType.Or && token.Type != TokenType.Xor)
+                    {
+                        return expr;
+                    }
+                    Next();
+                    var expr2 = Expr7();
+                    if (token.Type == TokenType.Or)
+                    {
+                        expr = new Value((int)expr.Number | (int)expr2.Number);
+                    }
+                    if (token.Type == TokenType.Xor)
+                    {
+                        expr = new Value((int)expr.Number ^ (int)expr2.Number);
+                    }
+                }
+            }
             public Value Expr()
             {
-                return Expr6();
+                return Expr9();
             }
             public void Print()
             {


Made camera movement less jarring in VR.

The camera no longer moves up or down while following
the ball - it remains locked to the plane that the ball
is on, so it should be less jarring when the ball jumps
or falls off into the abyss.

Change-Id: I95271b259ddae82ffb6b815d3bd168b368542776

--- Assets/Hamster/Scripts/CameraController.cs
+++ Assets/Hamster/Scripts/CameraController.cs
@@ -33,6 +33,9 @@
     public float EditorScrollSpeed = 8.0f;
     // How fast the camera zooms to its new target:
     public float CameraZoom = 0.05f;
+    // Height of the object the camera focuses on.  (Normally
+    // the center of the hamster ball.)
+    public float CameraFocusHeight = 0.5f;

     // The height is a lowered in VR mode.
     const float VRHeightScalar = 0.75f;
@@ -98,8 +101,9 @@
           if (player == null)
             player = FindObjectOfType<PlayerController>();
           if (player != null) {
-            transform.position = player.transform.position +
-                ViewAngleVector * ViewDistance;
+            Vector3 camTarget = player.transform.position;
+            camTarget.y = CameraFocusHeight;
+            transform.position = camTarget + ViewAngleVector * ViewDistance;
             if (!CommonData.inVrMode) {
               transform.LookAt(player.transform.position, kUpVector);
             }


OKSettings editor section updated, version bump to 1.0.1

--- Assets/Odnoklassniki/Scripts/OKSettings.cs
+++ Assets/Odnoklassniki/Scripts/OKSettings.cs
@@ -13,7 +13,7 @@

 	public const string SDK_VERSION = "2";
 	public const string CLIENT_TYPE = "SDK_UNITY3D";
-	public const string CLIENT_VERSION = "1.0.0";
+	public const string CLIENT_VERSION = "1.0.1";

 	const string OdnoklassnikiSettingsAssetName = "OdnoklassnikiSettings";
 	const string OdnoklassnikiSettingsPath = "Odnoklassniki/Resources";
@@ -57,24 +57,26 @@
 		Selection.activeObject = Instance;
 	}

-	[MenuItem("Odnoklassniki/Developers Page")]
+	[MenuItem("Odnoklassniki/Open Application Page")]
 	public static void OpenAppPage()
 	{
-		string url = string.Format("http://ok.ru/dk?st.cmd=appEdit&st.appId={0}&st._aid=App_Main_EditApp", AppId);
+		string url = string.Format("http://ok.ru/game/{0}", AppId);
 		Application.OpenURL(url);
 	}

 	[MenuItem("Odnoklassniki/SDK Documentation")]
 	public static void OpenDocumentation()
 	{
-		string url = "http://apiok.ru";
+		string url = "https://github.com/odnoklassniki/ok-unity3d-sdk";
 		Application.OpenURL(url);
 	}

 	[MenuItem("Odnoklassniki/Report a SDK Bug")]
 	public static void ReportABug()
 	{
-		string url = "mailto:api-support@odnoklassniki.ru";
+		string subject = "Unity 3D sdk bug";
+		string body = "Client version: " + CLIENT_VERSION;
+		string url = string.Format("mailto:api-support@ok.ru?subject={0}&body={1}", subject, body);
 		Application.OpenURL(url);
 	}
 #endif


adjust judgement

adjust judgement

--- Assets/Scenes/InGame/Scripts/GamePlayer.cs
+++ Assets/Scenes/InGame/Scripts/GamePlayer.cs
@@ -291,9 +291,9 @@

 				if (PerfectCount == HitObjects.Count)
 					PlayerPrefs.SetString ("Judgement", "X");
-				else if (PerfectCount >= HitObjects.Count * 0.8f)
+				else if (PerfectCount >= HitObjects.Count * 0.9f)
 					PlayerPrefs.SetString ("Judgement", "S");
-				else if (PerfectCount >= HitObjects.Count * 0.7f)
+				else if (PerfectCount >= HitObjects.Count * 0.75f)
 					PlayerPrefs.SetString ("Judgement", "A");
 				else if (PerfectCount >= HitObjects.Count * 0.6f)
 					PlayerPrefs.SetString ("Judgement", "B");


Added extra bomb turn command aliases

Added extra bomb turn command aliases

!bomb flip
!bomb spin

--- Assets/Scripts/Commanders/BombCommander.cs
+++ Assets/Scripts/Commanders/BombCommander.cs
@@ -74,7 +74,9 @@
         }
         else if (message.Equals("turn", StringComparison.InvariantCultureIgnoreCase) ||
                  message.Equals("turn round", StringComparison.InvariantCultureIgnoreCase) ||
-                 message.Equals("turn around", StringComparison.InvariantCultureIgnoreCase))
+                 message.Equals("turn around", StringComparison.InvariantCultureIgnoreCase) ||
+                 message.Equals("flip", StringComparison.InvariantCultureIgnoreCase) ||
+                 message.Equals("spin", StringComparison.InvariantCultureIgnoreCase))
         {
             responseNotifier.ProcessResponse(CommandResponse.Start);


explosions destroyed after a few seconds

--- Assets/Scripts/Misc/ExplosionController.cs
+++ Assets/Scripts/Misc/ExplosionController.cs
@@ -62,6 +62,7 @@
             var pa = ((GameObject)Instantiate(go, position, Quaternion.identity)).GetComponent<ParticleSystem>();
             pa.startColor = color;
             pa.Emit(1);
+            Destroy(pa.gameObject, KeepTime);
         }
     }
 }


Fix to Authorized Defuser logic

Fix to Authorized Defuser logic

There was a bug that was causing the "Command only for authorized
defuser" message to pop up when it should not have been, (and never
popping up when it should.)

--- Assets/Scripts/UI/TwitchComponentHandle.cs
+++ Assets/Scripts/UI/TwitchComponentHandle.cs
@@ -563,8 +563,6 @@
 						return null;
 					}
 				}
-
-				if (messageOut == null) ircConnection.SendMessage(TwitchPlaySettings.data.TwitchPlaysDisabled, userNickName);
 			}

 			if (internalCommand.Equals("player", StringComparison.InvariantCultureIgnoreCase))
@@ -601,7 +599,11 @@

 		if (_solver != null)
 		{
-		    if (!IsAuthorizedDefuser(userNickName)) return null;
+		    if (!IsAuthorizedDefuser(userNickName))
+		    {
+		        ircConnection.SendMessage(TwitchPlaySettings.data.TwitchPlaysDisabled, userNickName);
+		        return null;
+		    }
             if ((bombCommander.CurrentTimer > 60.0f) && (playerName != null) && (playerName != userNickName) && (!(internalCommand.Equals("take", StringComparison.InvariantCultureIgnoreCase))))
 			{
 				ircConnection.SendMessage(TwitchPlaySettings.data.AlreadyClaimed, targetModule, playerName, userNickName, headerText.text);


logging now Thread-Safe, files cleared

logging now Thread-Safe, files cleared

earlier files weren't truncated (size set to 0) before overwriting,
which left some thrash (old file content) at the end of the file

--- BSXmlReshaper/BSReshaper/BSReshaperForm.cs
+++ BSXmlReshaper/BSReshaper/BSReshaperForm.cs
@@ -18,6 +18,11 @@
     /// </summary>
     public partial class BSReshaper : Form
     {
+
+        // This delegate enables asynchronous calls for setting
+        // the text property on a TextBox control.
+        delegate void AppendTextCallback(string text);
+
         private bool folderSelected;
         private bool xslSelected;
         private static readonly string debugDefaultPath = @"D:\Documents\BattleScribe\data\wh40k\";
@@ -107,12 +112,6 @@
             Task.Run(new Action(reshaper.RegenerateIds));
         }

-        private void log(string logText)
-        {
-            logBox.AppendText(logText);
-            logBox.AppendText("\r\n");
-        }
-
         private void transformButton_Click(object sender, EventArgs e)
         {
             if (!xslSelected)
@@ -131,7 +130,7 @@
                     using (var stream = new MemoryStream())
                     {
                         transformer.Transform(path, null, stream);
-                        using (FileStream file = File.OpenWrite(path))
+                        using (FileStream file = File.Open(path, FileMode.Create))
                         {
                             stream.WriteTo(file);
                         }
@@ -166,5 +165,34 @@
                 File.WriteAllText(saveLogDialog.FileName, logBox.Text);
             }
         }
+
+        // If the calling thread is different from the thread that
+        // created the TextBox control, this method creates a
+        // SetTextCallback and calls itself asynchronously using the
+        // Invoke method.
+        //
+        // If the calling thread is the same as the thread that created
+        // the TextBox control, the Text property is set directly.
+        private void log(string text)
+        {
+            // InvokeRequired required compares the thread ID of the
+            // calling thread to the thread ID of the creating thread.
+            // If these threads are different, it returns true.
+            if (this.logBox.InvokeRequired)
+            {
+                AppendTextCallback d = new AppendTextCallback(log);
+                this.Invoke(d, new object[] { text });
+            }
+            else
+            {
+                AppendText(text);
+            }
+        }
+
+        private void AppendText(string logText)
+        {
+            logBox.AppendText(logText);
+            logBox.AppendText("\r\n");
+        }
     }
 }


Fix spelling

Fix spelling

--- BTCPayServer/Views/Shared/SyncModal.cshtml
+++ BTCPayServer/Views/Shared/SyncModal.cshtml
@@ -10,8 +10,8 @@

-                Some of your nodes are still synching...

-                BTCPay Server will not work correctly until it is over.
+                Some of your nodes are still synchronizing...

+                BTCPay Server will not create invoices with those cryptocurrencies.

             @foreach (var line in dashboard.GetAll())
             {
@@ -47,12 +47,12 @@
                         }
                         else if (line.Status.BitcoinStatus.IsSynched)
                         {
-
The node is synched (Height: @line.Status.BitcoinStatus.Headers)

+
The node is synchronized (Height: @line.Status.BitcoinStatus.Headers)

                             @if (line.Status.BitcoinStatus.IsSynched &&
                                 line.Status.SyncHeight.HasValue &&
                                 line.Status.SyncHeight.Value < line.Status.BitcoinStatus.Headers)
                             {
-
NBXplorer is synching... (Height: @line.Status.SyncHeight.Value)

+
NBXplorer is synchronizing... (Height: @line.Status.SyncHeight.Value)

                             }
                         }
                         else


Tidy up

Tidy up

--- BudgetAnalyser/Matching/RulesController.cs
+++ BudgetAnalyser/Matching/RulesController.cs
@@ -1,7 +1,6 @@
 using System;
 using System.Collections.Generic;
 using System.Collections.ObjectModel;
-using System.ComponentModel;
 using System.IO;
 using System.Linq;
 using System.Windows;
@@ -28,8 +27,6 @@
         private readonly ILogger logger;
         private readonly IUserQuestionBoxYesNo questionBox;
         private readonly IMatchingRuleRepository ruleRepository;
-        private RulesGroupedByBucket addNewGroup;
-        private MatchingRule addingNewRule;
         private bool doNotUseFlatListBoxVisibility;
         private bool doNotUseGroupByListBoxVisibility;
         private MatchingRule doNotUseSelectedRule;
@@ -37,8 +34,6 @@
         private bool doNotUseShown;

         private string doNotUseSortBy;
-
-        private Guid debugId = Guid.NewGuid();

         /// <summary>
         ///     Only used if a custom matching rules file is being used. If this is null when the application state has loaded
@@ -57,7 +52,6 @@
             }

             this.logger = uiContext.Logger;
-            this.logger.LogInfo(() => "RulesController Constructed with Id: " + this.debugId);
             this.questionBox = uiContext.UserPrompts.YesNoBox;
             this.ruleRepository = ruleRepository;
             NewRuleController = uiContext.NewRuleController;
@@ -256,17 +250,14 @@
             RulesGroupedByBucket existingGroup = RulesGroupedByBucket.FirstOrDefault(group => group.Bucket == rule.Bucket);
             if (existingGroup == null)
             {
-                this.addNewGroup = new RulesGroupedByBucket(rule.Bucket, new[] { rule });
-                RulesGroupedByBucket.Add(this.addNewGroup);
+                var addNewGroup = new RulesGroupedByBucket(rule.Bucket, new[] { rule });
+                RulesGroupedByBucket.Add(addNewGroup);
                 Rules.Add(rule);
-                this.addNewGroup = null;
             }
             else
             {
-                this.addingNewRule = rule;
-                existingGroup.Rules.Add(this.addingNewRule);
+                existingGroup.Rules.Add(rule);
                 Rules.Add(rule);
-                this.addingNewRule = null;
             }

             SaveRules();
@@ -281,16 +272,6 @@
         private bool CanExecuteDeleteRuleCommand()
         {
             return SelectedRule != null;
-        }
-
-        private void OnAddingNewGroup(object sender, AddingNewEventArgs addingNewEventArgs)
-        {
-            addingNewEventArgs.NewObject = this.addNewGroup;
-        }
-
-        private void OnAddingNewRuleToGroup(object sender, AddingNewEventArgs addingNewEventArgs)
-        {
-            addingNewEventArgs.NewObject = this.addingNewRule;
         }

         private void OnApplicationStateLoaded(ApplicationStateLoadedMessage message)


Added OnConnected and OnDisconnected events

--- SharpTox/Core/Tox.cs
+++ SharpTox/Core/Tox.cs
@@ -29,6 +29,8 @@
     public delegate void OnReadReceiptDelegate(int friendnumber, uint receipt);

     public delegate void OnPacketDelegate(int friendnumber, byte[] data);
+
+    public delegate void OnConnectionDelegate();
     #endregion

     /// <summary>
@@ -125,6 +127,16 @@
         /// Occurs when a lossless packet is received.
         /// </summary>
         public event OnPacketDelegate OnLosslessPacket;
+
+        /// <summary>
+        /// Occurs when a connection to the DHT has been established.
+        /// </summary>
+        public event OnConnectionDelegate OnConnected;
+
+        /// <summary>
+        /// Occurs when the connection to the DHT was lost.
+        /// </summary>
+        public event OnConnectionDelegate OnDisconnected;

         public delegate object InvokeDelegate(Delegate method, params object[] p);

@@ -159,6 +171,7 @@
         private Thread thread;

         private bool disposed = false;
+        private bool connected = false;

         /// <summary>
         /// Setting this to false will make sure that resolving sticks strictly to IPv4 addresses.
@@ -384,6 +397,21 @@
         {
             while (true)
             {
+                if (IsConnected() && !connected)
+                {
+                    if (OnConnected != null)
+                        Invoker(OnConnected);
+
+                    connected = true;
+                }
+                else if (!IsConnected() && connected)
+                {
+                    if (OnDisconnected != null)
+                        Invoker(OnDisconnected);
+
+                    connected = false;
+                }
+
                 ToxFunctions.Do(tox);
                 Thread.Sleep((int)ToxFunctions.DoInterval(tox));
             }


Corrected turns ratio

Corrected turns ratio

--- Circuit/Components/CenterTapTransformer.cs
+++ Circuit/Components/CenterTapTransformer.cs
@@ -58,8 +58,8 @@
             Expression Vp = pa.V - pc.V;
             Expression Vs1 = sa.V - st.V;
             Expression Vs2 = st.V - sc.V;
-            Mna.AddEquation(Vp, Vs1 * turns);
-            Mna.AddEquation(Vp, Vs2 * turns);
+            Mna.AddEquation(Vp, Vs1 * turns / 2);
+            Mna.AddEquation(Vp, Vs2 * turns / 2);
         }

         public override void LayoutSymbol(SymbolLayout Sym)
@@ -82,7 +82,6 @@
             Inductor.DrawCoil(Sym, 10, -36.0, 0.0, 4, false);
             Inductor.DrawCoil(Sym, 10, 36.0, 0.0, 4, false);

-
             Sym.DrawText(Name, new Coord(16, -20), Alignment.Near, Alignment.Center);
             Sym.DrawText(Turns.ToString(), new Coord(16, 20), Alignment.Near, Alignment.Center);
         }


more precise ground impact detection (during atmospheric flight)

--- Plugin/Trajectory.cs
+++ Plugin/Trajectory.cs
@@ -270,7 +270,8 @@
             }
         }

-        // relativePosition is in world frame, but relative to the body
+        // relativePosition is in world frame, but relative to the body (i.e. inertial body space)
+        // returns the altitude above sea level (can be negative for bodies without ocean)
         private double GetGroundAltitude(CelestialBody body, Vector3 relativePosition)
         {
             if (body.pqsController == null)
@@ -446,7 +447,9 @@
                     Vector3d prevPos = pos - vel * dt;
                     //Util.PostSingleScreenMessage("initial vel", "initial vel = " + vel);
                     double currentTime = entryTime;
-                    double lastPositionStored = 0;
+                    double lastPositionStoredUT = 0;
+                    Vector3d lastPositionStored = new Vector3d();
+                    bool hitGround = false;
                     int iteration = 0;
                     while (true)
                     {
@@ -458,39 +461,12 @@
                         double R = pos.magnitude;
                         double altitude = R - body.Radius;
                         double atmosphereCoeff = altitude / maxAtmosphereAltitude;
-                        if (atmosphereCoeff <= 0.0 || atmosphereCoeff >= 1.0 || iteration == maxIterations || currentTime > patch.endTime)
+                        if (hitGround || atmosphereCoeff <= 0.0 || atmosphereCoeff >= 1.0 || iteration == maxIterations || currentTime > patch.endTime)
                         {
-                            if (atmosphereCoeff <= 0.0)
-                            {
-                                //rewind trajectory a bit to get actual intersection with the ground (we assume the ground is horizontal around the impact position)
-                                double groundAltitude = GetGroundAltitude(body, calculateRotatedPosition(body, pos, currentTime)) + body.Radius;
-                                if (nextPosIdx == 0 && buffer.Count > 1)
-                                {
-                                    nextPosIdx = chunkSize;
-                                    buffer.RemoveAt(buffer.Count - 1);
-                                }
-                                while (pos.magnitude <= groundAltitude)
-                                {
-                                    --nextPosIdx;
-                                    currentTime -= dt;
-                                    if (nextPosIdx == 0)
-                                    {
-                                        if (buffer.Count == 1)
-                                            break;
-                                        nextPosIdx = chunkSize;
-                                        buffer.RemoveAt(buffer.Count - 1);
-                                    }
-                                    pos = buffer.Last()[nextPosIdx - 1].pos;
-                                }
-
-                                if (Settings.fetch.BodyFixedMode) {
-                                    //if we do fixed-mode calculations, pos is already rotated
-                                    patch.impactPosition = pos;
-                                    patch.rawImpactPosition = calculateRotatedPosition(body, patch.impactPosition.Value, 2.0 * Planetarium.GetUniversalTime() - currentTime);
-                                } else {
-                                    patch.rawImpactPosition = pos;
-                                    patch.impactPosition = calculateRotatedPosition(body, patch.rawImpactPosition.Value, currentTime);
-                                }
+                            if (hitGround || atmosphereCoeff <= 0.0)
+                            {
+                                patch.rawImpactPosition = pos;
+                                patch.impactPosition = calculateRotatedPosition(body, patch.rawImpactPosition.Value, currentTime);
                                 patch.impactVelocity = vel;
                             }

@@ -556,23 +532,40 @@

                         currentTime += dt;

-                        double interval = altitude < 15000.0 ? trajectoryInterval * 0.1 : trajectoryInterval;
-                        if (currentTime >= lastPositionStored + interval)
+                        double interval = altitude < 10000.0 ? trajectoryInterval * 0.3 : trajectoryInterval;
+                        if (currentTime >= lastPositionStoredUT + interval)
                         {
-                            lastPositionStored = currentTime;
+                            if (lastPositionStoredUT > 0)
+                            {
+                                // check terrain collision, to detect impact on mountains etc.
+                                Vector3 rayOrigin = lastPositionStored;
+                                Vector3 rayEnd = pos;
+                                double groundAltitude = GetGroundAltitude(body, calculateRotatedPosition(body,rayEnd,currentTime)) + body.Radius;
+                                if (groundAltitude > rayEnd.magnitude)
+                                {
+                                    hitGround = true;
+                                    float coeff = Math.Max(0.01f, (float)((groundAltitude - rayOrigin.magnitude) / (rayEnd.magnitude - rayOrigin.magnitude)));
+                                    pos = rayEnd * coeff + rayOrigin * (1.0f - coeff);
+                                    currentTime = currentTime * coeff + lastPositionStoredUT * (1.0f - coeff);
+                                }
+                            }
+
+                            lastPositionStoredUT = currentTime;
                             if (nextPosIdx == chunkSize)
                             {
                                 buffer.Add(new Point[chunkSize]);
                                 nextPosIdx = 0;
                             }
                             Vector3d nextPos = pos;
-                            if (Settings.fetch.BodyFixedMode) {
+                            if (Settings.fetch.BodyFixedMode)
+                            {
                                 nextPos = calculateRotatedPosition(body, nextPos, currentTime);
                             }
                             buffer.Last()[nextPosIdx].aerodynamicForce = aerodynamicForce;
                             buffer.Last()[nextPosIdx].orbitalVelocity = vel;
                             buffer.Last()[nextPosIdx].airVelocity = airVelocity;
                             buffer.Last()[nextPosIdx++].pos = nextPos;
+                            lastPositionStored = pos;
                         }
                     }
                 }


Fixed get test to add outof range stuff

Fixed get test to add outof range stuff

--- ClassicBasic.Test/CommandTests/GetTests.cs
+++ ClassicBasic.Test/CommandTests/GetTests.cs
@@ -63,11 +63,17 @@
         /// <summary>
         /// Tests Get throws syntax error for Alpha in numeric mode.
         /// </summary>
-        [TestMethod]
-        public void GetThrowsForAlphaInNumeric()
+        /// <param name="character">Character to test.</param>
+        /// <param name="throwsException">Should throw exception</param>
+        [DataTestMethod]
+        [DataRow('0', false)]
+        [DataRow('9', false)]
+        [DataRow('/', true)]
+        [DataRow(':', true)]
+        public void GetThrowsForAlphaInNumeric(char character, bool throwsException)
         {
             SetupSut();
-            _mockTeletypeWithPosition.Setup(mtwp => mtwp.ReadChar()).Returns('A');
+            _mockTeletypeWithPosition.Setup(mtwp => mtwp.ReadChar()).Returns(character);
             var variableReference = _variableRepository.GetOrCreateVariable("A", new short[] { });
             _mockExpressionEvaluator.Setup(mee => mee.GetLeftValue()).Returns(variableReference);
             bool exceptionThrown = false;
@@ -80,7 +86,7 @@
                 exceptionThrown = true;
             }

-            Assert.IsTrue(exceptionThrown);
+            Assert.AreEqual(throwsException, exceptionThrown);
         }

         /// <summary>


[Modify] Polish it

[Modify] Polish it


refactor code

refactor code


Only creating a mapped object cache for the declared type mapping data

--- AgileMapper/ObjectPopulation/ObjectMappingData.cs
+++ AgileMapper/ObjectPopulation/ObjectMappingData.cs
@@ -55,14 +55,14 @@
                 return;
             }

+            IsRoot = true;
+
+            if (IsPartOfDerivedTypeMapping)
+            {
+                return;
+            }
+
             _mappedObjectsBySource = new Dictionary<object, List<object>>();
-            IsRoot = true;
-
-            if (IsPartOfDerivedTypeMapping)
-            {
-                return;
-            }
-
             Mapper = MapperContext.ObjectMapperFactory.GetOrCreateRoot(this);
         }


security hardening

security hardening

--- AjaxControlToolkit.SampleSite/NoBot/NoBot.aspx.cs
+++ AjaxControlToolkit.SampleSite/NoBot/NoBot.aspx.cs
@@ -18,11 +18,11 @@
         // Display results view
         MultiView1.SetActiveView(View2);
         NoBotState state;
-        Label1.Text = String.Format(
+        Label1.Text = HttpUtility.HtmlEncode(String.Format(
             (NoBot1.IsValid(out state)
                 ? "Congratulations, \"{1} {2}\", you do not appear to be a bot. (Details: {0})"
                 : "Rejected; user appears to be a bot. (Details: {0})"),
-            state.ToString(), TextBox1.Text, TextBox2.Text);
+            state.ToString(), TextBox1.Text, TextBox2.Text));

         var sb = new StringBuilder();
         foreach(var kvp in NoBot.GetCopyOfUserAddressCache())


Added a new line in the fibonacci application

--- C#1/ConsoleInputOuput/FibonacciNumbers/Program.cs
+++ C#1/ConsoleInputOuput/FibonacciNumbers/Program.cs
@@ -31,5 +31,6 @@
 			twoNumbersBefore = lastNumber;
 			lastNumber = temp + twoNumbersBefore;
 		}
+        Console.WriteLine();
 	}
 }


#19 Categories should be synced

#19 Categories should be synced

--- CalDavSynchronizer/Implementation/EntityMapper.cs
+++ CalDavSynchronizer/Implementation/EntityMapper.cs
@@ -16,6 +16,8 @@

 using System;
 using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
 using System.Reflection;
 using CalDavSynchronizer.Generic.EntityMapping;
 using DDay.iCal;
@@ -76,7 +78,20 @@
       target.Class = MapPrivacy1To2 (source.Sensitivity);
       MapReminder1To2 (source, target);

+      MapCategories1To2(source, target);
+
       return target;
+    }
+
+    private static void MapCategories1To2 (AppointmentItem source, IEvent target)
+    {
+      if (!string.IsNullOrEmpty (source.Categories))
+      {
+        Array.ForEach (
+            source.Categories.Split (new[] { CultureInfo.CurrentCulture.TextInfo.ListSeparator }, StringSplitOptions.RemoveEmptyEntries),
+            c => target.Categories.Add (c)
+            );
+      }
     }

     private void MapReminder1To2 (AppointmentItem source, IEvent target)
@@ -433,16 +448,15 @@
         if (!IsOwnIdentity (recipient))
         {
           Attendee attendee;
-
-          if(!string.IsNullOrEmpty(recipient.Address))
+
+          if (!string.IsNullOrEmpty (recipient.Address))
             attendee = new Attendee (GetMailUrl (recipient.AddressEntry));
           else
-            attendee = new Attendee ();
-
+            attendee = new Attendee();
+
           attendee.CommonName = recipient.Name;
           attendee.Role = MapAttendeeType1To2 ((OlMeetingRecipientType) recipient.Type);
           target.Attendees.Add (attendee);
-
         }
         if (((OlMeetingRecipientType) recipient.Type) == OlMeetingRecipientType.olOrganizer)
         {
@@ -534,7 +548,14 @@
       target.Sensitivity = MapPrivacy2To1 (source.Class);
       MapReminder2To1 (source, target);

+      MapCategories2To1(source, target);
+
       return target;
+    }
+
+    private static void MapCategories2To1 (IEvent source, AppointmentItem target)
+    {
+      target.Categories = string.Join (CultureInfo.CurrentCulture.TextInfo.ListSeparator, source.Categories);
     }

@@ -547,7 +568,7 @@
       {
         Recipient targetRecipient = null;

-        if (attendee.Value != null && !string.IsNullOrEmpty(attendee.Value.ToString().Substring (s_mailtoSchemaLength)))
+        if (attendee.Value != null && !string.IsNullOrEmpty (attendee.Value.ToString().Substring (s_mailtoSchemaLength)))
         {
           if (!indexByEmailAddresses.TryGetValue (attendee.Value.ToString(), out targetRecipient))
           {
@@ -585,7 +606,7 @@
       foreach (Recipient recipient in appointment.Recipients)
       {
         if (! string.IsNullOrEmpty (recipient.Address))
-          indexByEmailAddresses[GetMailUrl (recipient.AddressEntry)] =  recipient;
+          indexByEmailAddresses[GetMailUrl (recipient.AddressEntry)] = recipient;
         else
           indexByEmailAddresses[recipient.Name] = recipient;
       }


Prevent matching own matchmake, added lock

--- D2MPMaster/Matchmaking/MatchmakeManager.cs
+++ D2MPMaster/Matchmaking/MatchmakeManager.cs
@@ -123,72 +123,78 @@

         private static void doMatchmake()
         {
-            foreach (var m in inMatchmaking.ToArray())
-            {
-                bool matched = false;
-                foreach (KeyValuePair<string, int> modMmr in m.rating)
+            lock (inMatchmaking)
+            {
+                foreach (var m in inMatchmaking.ToArray())
                 {
-                    // Find match with a similar rating (search margin increases every try), enough free slots and a common mod
-                    var match = inMatchmaking.FirstOrDefault(x => x.rating.Any(
-                        y => y.Key == modMmr.Key && Math.Abs(y.Value - modMmr.Value) < m.matchTries * ratingMargin
-                        ) && 5 - x.users.Count() >= m.users.Count() && x.mods.Intersect(m.mods).Any());
-                    if (match != null)
-                    {
-                        // Merge users to one matchmake
-                        match.MoveUsers(m.users, match.users);
-                        foreach (var browser in Browsers.Find(b => b.user != null && b.matchmake != null && b.matchmake.id == m.id))
+                    bool matched = false;
+                    foreach (KeyValuePair<string, int> modMmr in m.rating)
+                    {
+                        // Find match with a similar rating (search margin increases every try), enough free slots and a common mod
+                        var match = inMatchmaking.FirstOrDefault(x => x != m && x.rating.Any(
+                            y => y.Key == modMmr.Key && Math.Abs(y.Value - modMmr.Value) < m.matchTries * ratingMargin
+                            ) && 5 - x.users.Count() >= m.users.Count() && x.mods.Intersect(m.mods).Any());
+                        if (match != null)
                         {
-                            browser.matchmake = match;
+                            // Merge users to one matchmake
+                            match.MoveUsers(m.users, match.users);
+                            foreach (var browser in Browsers.Find(b => b.user != null && b.matchmake != null && b.matchmake.id == m.id))
+                            {
+                                browser.matchmake = match;
+                            }
+                            m.users = null;
+                            match.mods = match.mods.Intersect(m.mods).ToArray();
+                            calculateMmr(match);
+                            inMatchmaking.Remove(m);
+                            matched = true;
+                            log.InfoFormat("Matchmake merged from {0} players to {1} players after {2} tries. New rating: {3}", m.users.Count(), match.users.Count(), m.matchTries, match.rating);
+                            if (match.users.Count() == 5)
+                            {
+                                match.matchTries = 1;
+                                inTeamMatchmaking.Add(match);
+                                inMatchmaking.Remove(match);
+                            }
                         }
-                        m.users = null;
-                        match.mods = match.mods.Intersect(m.mods).ToArray();
-                        calculateMmr(match);
-                        inMatchmaking.Remove(m);
-                        matched = true;
-                        log.InfoFormat("Matchmake merged from {0} players to {1} players after {2} tries. New rating: {3}", m.users.Count(), match.users.Count(), m.matchTries, match.rating);
-                        if (match.users.Count() == 5)
+                    }
+                    if (!matched)
+                    {
+                        m.matchTries++;
+                    }
+                }
+            }
+        }
+
+        private static void doTeamMatchmake()
+        {
+            lock (inTeamMatchmaking)
+            {
+                foreach (var m in inTeamMatchmaking.ToArray())
+                {
+                    bool matched = false;
+                    foreach (KeyValuePair<string, int> modMmr in m.rating)
+                    {
+                        var match = inMatchmaking.FirstOrDefault(x => x != m && x.rating.Any(
+                       y => y.Key == modMmr.Key && Math.Abs(y.Value - modMmr.Value) < m.matchTries * ratingMargin
+                       ) && x.mods.Intersect(m.mods).Any());
+                        if (match != null)
                         {
-                            match.matchTries = 1;
-                            inTeamMatchmaking.Add(match);
-                            inMatchmaking.Remove(match);
+                            Random rnd = new Random();
+                            var mods = match.mods.Intersect(m.mods).ToArray();
+                            var lobby = LobbyManager.CreateMatchedLobby(m, match, mods[rnd.Next(0, mods.Length)]);
+                            foreach (var browser in Browsers.Find(b => b.user != null && b.matchmake != null && (b.matchmake.id == m.id || b.matchmake.id == match.id)))
+                            {
+                                browser.lobby = lobby;
+                                browser.matchmake = null;
+                            }
+                            inTeamMatchmaking.Remove(m);
+                            inTeamMatchmaking.Remove(match);
+                            matched = true;
                         }
                     }
-                }
-                if (!matched)
-                {
-                    m.matchTries++;
-                }
-            }
-        }
-
-        private static void doTeamMatchmake()
-        {
-            foreach (var m in inTeamMatchmaking.ToArray())
-            {
-                bool matched = false;
-                foreach (KeyValuePair<string, int> modMmr in m.rating)
-                {
-                    var match = inMatchmaking.FirstOrDefault(x => x.rating.Any(
-                   y => y.Key == modMmr.Key && Math.Abs(y.Value - modMmr.Value) < m.matchTries * ratingMargin
-                   ) && x.mods.Intersect(m.mods).Any());
-                    if (match != null)
-                    {
-                        Random rnd = new Random();
-                        var mods = match.mods.Intersect(m.mods).ToArray();
-                        var lobby = LobbyManager.CreateMatchedLobby(m, match, mods[rnd.Next(0, mods.Length)]);
-                        foreach (var browser in Browsers.Find(b => b.user != null && b.matchmake != null && (b.matchmake.id == m.id || b.matchmake.id == match.id)))
-                        {
-                            browser.lobby = lobby;
-                            browser.matchmake = null;
-                        }
-                        inTeamMatchmaking.Remove(m);
-                        inTeamMatchmaking.Remove(match);
-                        matched = true;
-                    }
-                }
-                if (!matched)
-                {
-                    m.matchTries++;
+                    if (!matched)
+                    {
+                        m.matchTries++;
+                    }
                 }
             }
         }


Improved grid rendering speed

Improved grid rendering speed

--- TimeBeam/Timeline.cs
+++ TimeBeam/Timeline.cs
@@ -432,6 +432,9 @@
       Rectangle trackAreaBounds = GetTrackAreaBounds();

       // Draw horizontal grid.
+      // Premultiply with alpha to improve drawing speed.
+      int gridPenColor = (int)( 255 * GridAlpha / 255f );
+      Pen gridPen = new Pen( Color.FromArgb( gridPenColor, gridPenColor, gridPenColor ) );
       // Calculate the Y position of the first line.
       int firstLineY = (int)( TrackHeight * _renderingScale.Y + trackAreaBounds.Y + _renderingOffset.Y );
       // Calculate the distance between each following line.
@@ -439,10 +442,10 @@
       actualRowHeight = Math.Max( 1, actualRowHeight );
       // Draw the actual lines.
       for( int y = firstLineY; y < Height; y += actualRowHeight ) {
-        GraphicsContainer.DrawLine( new Pen( Color.FromArgb( GridAlpha, Color.White ) ), trackAreaBounds.X, y, trackAreaBounds.Width, y );
-      }
-
-      // The dinstance between the minor ticks.
+        GraphicsContainer.DrawLine( gridPen, trackAreaBounds.X, y, trackAreaBounds.Width, y );
+      }
+
+      // The distance between the minor ticks.
       float minorTickDistance = _renderingScale.X;
       int minorTickOffset = (int)( _renderingOffset.X % minorTickDistance );

@@ -463,24 +466,33 @@

       // Should we draw minor ticks?
       if( minorTickDistance > 2.0f ) {
-        for( float x = minorTickOffset; x < Width; x += minorTickDistance ) {
-          GraphicsContainer.DrawLine(
-            new Pen( Color.FromArgb( 30, Color.White ) ) {
-              DashStyle = DashStyle.Dot
-            }, trackAreaBounds.X + x, trackAreaBounds.Y, trackAreaBounds.X + x, trackAreaBounds.Height );
+        using( Pen minorGridPen = new Pen( Color.FromArgb( 30, Color.White ) ) {
+          DashStyle = DashStyle.Dot
+        } ) {
+          for( float x = minorTickOffset; x < Width; x += minorTickDistance ) {
+            GraphicsContainer.DrawLine( minorGridPen, trackAreaBounds.X + x, trackAreaBounds.Y, trackAreaBounds.X + x, trackAreaBounds.Height );
+          }
         }
       }

       // We start one tick distance after the offset to draw the first line that is actually in the display area
       // The one that is only tickOffset pixels away it behind the track labels.
+      int minutePenColor = (int)( 255 * Math.Min( 255, GridAlpha * 2 ) / 255f );
+      Pen brightPen = new Pen( Color.FromArgb( minutePenColor, minutePenColor, minutePenColor ) );
       for( int x = tickOffset + tickDistance; x < Width; x += columnWidth ) {
-        int alpha = GridAlpha;
         // Every 60 ticks, we put a brighter, thicker line.
+        Pen penToUse;
         if( ( x - minuteOffset ) % minuteDistance == 0 ) {
-          alpha = Math.Min( 255, alpha *= 2 );
-        }
-        GraphicsContainer.DrawLine( new Pen( Color.FromArgb( alpha, Color.White ) ), trackAreaBounds.X + x, trackAreaBounds.Y, trackAreaBounds.X + x, trackAreaBounds.Height );
-      }
+          penToUse = brightPen;
+        } else {
+          penToUse = gridPen;
+        }
+
+        GraphicsContainer.DrawLine( penToUse, trackAreaBounds.X + x, trackAreaBounds.Y, trackAreaBounds.X + x, trackAreaBounds.Height );
+      }
+
+      gridPen.Dispose();
+      brightPen.Dispose();
     }

     /// <summary>


Fix small error.

Fix small error.

--- TimeLeft/TimeLeft.cs
+++ TimeLeft/TimeLeft.cs
@@ -162,7 +162,7 @@
         {
             TimeLeftUnit[] sortedByTime;
             lock (_locker)
-                sortedByTime = SortByDate( storage.GetAll() );
+                sortedByTime = SortByDate( storage.Search(name) );

             foreach (var tlu in sortedByTime)
                 SendTime(channel, tlu.Name, tlu.Date);


Somehow this got readded.

Somehow this got readded.

--- VersionrCore/Area.cs
+++ VersionrCore/Area.cs
@@ -39,7 +39,6 @@
         private LocalDB LocalData { get; set; }
         public Directives Directives { get; set; }
         public DateTime ReferenceTime { get; set; }
-        public Newtonsoft.Json.Linq.JObject Configuration { get; set; }

         public Dictionary<string, FileTimestamp> FileTimeCache { get; set; }

@@ -3594,9 +3593,9 @@
         {
             return Database.GetMergeInfo(iD);
         }
-
-		public void LoadDirectives()
-		{
+
+        public void LoadDirectives()
+        {
             string error;

             // Load .vrmeta
@@ -3612,17 +3611,8 @@
             directives = DirectivesUtils.LoadVRUser(this, out error);
             if (directives != null)
                 Directives.Merge(directives);
-		}
-        public T LoadConfigurationElement<T>(string v)
-            where T : new()
-        {
-			if (Configuration == null)
-				return new T();
-            var element = Configuration[v];
-            if (element == null)
-                return new T();
-            return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(element.ToString());
-        }
+        }
+
         private bool Load(bool headless = false)
         {
             try


Removed 'name' from MyDbContext.

Removed 'name' from MyDbContext.

--- DotNetAppSqlDb/Models/MyDatabaseContext.cs
+++ DotNetAppSqlDb/Models/MyDatabaseContext.cs
@@ -15,10 +15,12 @@
         // For more information refer to the documentation:
         // http://msdn.microsoft.com/en-us/data/jj591621.aspx

+
         public MyDatabaseContext() : base("MyDbConnection")
         {
         }

+
         public System.Data.Entity.DbSet<DotNetAppSqlDb.Models.Todo> Todoes { get; set; }
     }
 }


First pass at refactoring tabular form.

First pass at refactoring tabular form.

--- EPPlus/Table/PivotTable/ExcelPivotTable.cs
+++ EPPlus/Table/PivotTable/ExcelPivotTable.cs
@@ -1535,193 +1535,10 @@
 			if (!tabularTable)
 				this.WriteRowHeaders(stringResources);
 			else
-			{
-				int dataFieldColumn = this.WriteTabularRowHeaders(stringResources);
-				this.WriteTabularHeadersInColumns(dataFieldColumn);
-			}
+				this.WriteTabularRowHeaders(stringResources);

 			// Update the column headers in the worksheet.
 			this.WriteColumnHeaders(stringResources);
-		}
-
-		private int WriteTabularRowHeaders(StringResources stringResources)
-		{
-			int dataFieldColumn = 0;
-			int row = this.Address.Start.Row + this.FirstDataRow;
-			int startColumn = this.Address.Start.Column;
-			int firstColumnWrittenTo = row;
-			int lastColumnWrittenTo = startColumn;
-			RowColumnItem previousNonTotalItem = null;
-			for (int i = 0; i < this.RowItems.Count; i++)
-			{
-				int currentColumn = startColumn;
-				var item = this.RowItems[i];
-				var header = this.RowHeaders[i];
-				for (int j = 0; j < item.Count; j++)
-				{
-					// Write subtotal headers.
-					var totalHeader = this.GetTotalCaptionCellValue(this.RowFields, item, header, stringResources);
-					if (!string.IsNullOrEmpty(totalHeader))
-					{
-						lastColumnWrittenTo = this.GetTabularSubtotalHeaderColumn(item, previousNonTotalItem, startColumn, currentColumn, lastColumnWrittenTo, firstColumnWrittenTo, i, j);
-						this.Worksheet.Cells[row, lastColumnWrittenTo].Value = totalHeader;
-						continue;
-					}
-
-					// Get sharedItem header value.
-					var itemIndex = item.RepeatedItemsCount == 0 ? j : j + item.RepeatedItemsCount;
-					string headerValue = this.GetSharedItemValue(this.RowFields, item, itemIndex, j);
-					int pivotFieldIndex = this.RowFields[itemIndex].Index;
-
-					// Write row headers.
-					if (item.Count == 1 && header.IsLeafNode)
-					{
-						// If the item is a leaf node with pivot fields that have tabular form disabled, then print out the
-						// header values at the last written in column.
-						this.Worksheet.Cells[row, lastColumnWrittenTo].Value = headerValue;
-					}
-					else
-					{
-						// If the item's repeatedItemsCount is zero, then it does not have a parent, so always set the column to the start column.
-						// Otherwise, the item is an inner item, so get the correct column to write to.
-						if (item.RepeatedItemsCount != 0)
-							currentColumn = this.GetInnerItemColumn(item, previousNonTotalItem, currentColumn, startColumn, ref firstColumnWrittenTo, lastColumnWrittenTo, i, j);
-						this.Worksheet.Cells[row, currentColumn].Value = headerValue;
-						if (pivotFieldIndex == -2)
-							dataFieldColumn = currentColumn;
-						lastColumnWrittenTo = currentColumn;
-						previousNonTotalItem = item;
-					}
-
-					// If the row item contains pivot fields in tabular form, then stay on the same row and increment the column.
-					if (item.Count > 1)
-						currentColumn++;
-				}
-				row++;
-			}
-			return dataFieldColumn;
-		}
-
-		private int GetInnerItemColumn(RowColumnItem currentItem, RowColumnItem previousNonTotalItem, int currentColumn, int startColumn, ref int firstColumnWrittenTo, int lastColumnWrittenTo, int i, int j)
-		{
-			var currentRowFieldIndex = currentItem.RepeatedItemsCount + j;
-			var isAboveDataField = this.RowFields.Skip(currentRowFieldIndex).Any(x => x.Index == -2);
-			// If we are at an inner node, then get the column based on whether or not we are the the first child.
-			if (previousNonTotalItem.RepeatedItemsCount == 0)
-			{
-				// First child.
-				int previousRepeatedItemsCount = previousNonTotalItem.RepeatedItemsCount;
-				int previousIndex = previousRepeatedItemsCount + previousNonTotalItem.Count;
-				int previousRowFieldIndex = this.RowFields[previousIndex - 1].Index;
-				// If the last written in header is a datafield value, then check whether or not this item is above a datafield
-				// and get the appropriate column value.
-				if (previousRowFieldIndex == -2)
-				{
-					if (isAboveDataField)
-						currentColumn = j == 0 ? startColumn + currentItem.RepeatedItemsCount : currentColumn;
-					else
-						currentColumn = j == 0 ? lastColumnWrittenTo : currentColumn;
-				}
-				else
-				{
-					var previousPivotField = this.Fields[previousRowFieldIndex];
-					// If the previous item's pivot field has tabular form disabled and it is not the last field in the row field
-					// collection, then write to the last written column. Otherwise, calculate the start column.
-					if (previousPivotField.Outline && previousNonTotalItem.Count < this.RowFields.Count)
-						currentColumn = j == 0 ? lastColumnWrittenTo : currentColumn;
-					else
-						currentColumn = j == 0 ? startColumn + currentItem.RepeatedItemsCount : currentColumn;
-				}
-				firstColumnWrittenTo = j == 0 ? currentColumn : firstColumnWrittenTo;
-			}
-			else
-			{
-				// If there are multiple datafields, then calculate the correct column to write to based on the position of the item
-				// relative to the datafields. Otherwise, use the firstColumnWrittenTo value as the starting column to write to.
-				if (this.HasRowDataFields)
-				{
-					var rowFieldIndex = this.RowFields[currentRowFieldIndex].Index;
-					if (rowFieldIndex == -2 || !isAboveDataField)
-						currentColumn = j == 0 ? lastColumnWrittenTo : currentColumn;
-					else
-					{
-						var isLastNonDataField = this.RowFields.Skip(currentRowFieldIndex + 1).All(x => x.Index == -2);
-						// If the item is the last non-datafield row field and the previous item was not a data field or the previous item was not a
-						// subtotal item, then write to the last column written to. Otherwise, calculate the column.
-						if ((isLastNonDataField && !this.RowHeaders[i - 1].IsDataField) || !string.IsNullOrEmpty(this.RowItems[i - 1].ItemType))
-							currentColumn = j == 0 ? lastColumnWrittenTo : currentColumn;
-						else
-							currentColumn = j == 0 ? startColumn + currentItem.RepeatedItemsCount : currentColumn;
-					}
-				}
-				else
-					currentColumn = j == 0 ? firstColumnWrittenTo : currentColumn;
-			}
-			return currentColumn;
-		}
-
-		private int GetTabularSubtotalHeaderColumn(RowColumnItem item, RowColumnItem previousNonTotalItem, int startColumn, int currentColumn, int lastColumnWrittenTo,
-			int firstColumnWrittenTo, int i, int j)
-		{
-			int returnColumn = 0;
-			if (item.RepeatedItemsCount == 0)
-				returnColumn = currentColumn;
-			else
-			{
-				int previousRepeatedItemsCount = previousNonTotalItem.RepeatedItemsCount;
-				int rowFieldIndex = previousRepeatedItemsCount == 0 ? previousRepeatedItemsCount : this.RowFields[previousRepeatedItemsCount - 1].Index;
-				ExcelPivotTableField field = null;
-				if (rowFieldIndex != -2)
-					field = this.Fields[rowFieldIndex];
-
-				if (field != null)
-				{
-					// If the current pivot field has tabular form disabled and we are not a parent item, then get the column to write to using the previous
-					// non-total item and header. Otherwise, use the row field collection to get the column.
-					if (field.Outline && previousRepeatedItemsCount != 0)
-					{
-						// If the current item is not a datafield item and the pivot field has tabular form disabled and we're not the first child of a parent.
-						// Case 1: If the last non-total header is a leaf node that contains a tabular field and the subtotal's repeatedItemsCount is greater than the
-						//		   last non-default, calculate the correct column to write to.
-						// Case 2: If the subtotal's repeatedItemsCount is greater than the last non-default/non-leaf node, print the header in the last column written to.
-						// Case 3: Otherwise, always print the header to the first column that was written to by the last non-default/non-leaf node.
-						// Note: When a subtotal's repeated item count is greater than the last non-default node, that means it shares values with the last non-default node.
-						// AKA, this subtotal node is for a child of the last non-default node.
-						if (this.RowHeaders[i - 1].IsLeafNode && previousRepeatedItemsCount < item.RepeatedItemsCount)
-							returnColumn = startColumn + item.RepeatedItemsCount - 1;
-						else if (previousRepeatedItemsCount < item.RepeatedItemsCount)
-							returnColumn = lastColumnWrittenTo;
-						else
-							returnColumn = firstColumnWrittenTo;
-					}
-					else
-					{
-						int currentRowFieldIndex = item.RepeatedItemsCount + j;
-						var isAboveDataField = this.RowFields.Skip(currentRowFieldIndex).Any(x => x.Index == -2);
-						if (this.HasRowDataFields && !isAboveDataField)
-							returnColumn = startColumn + item.RepeatedItemsCount - 1;
-						else
-						{
-							int previousFieldIndex = this.RowFields[item.RepeatedItemsCount - 1].Index;
-							var previousField = this.Fields[previousFieldIndex];
-							if (previousField.Outline)
-								returnColumn = startColumn + item.RepeatedItemsCount - 1;
-							else
-								returnColumn = startColumn + item.RepeatedItemsCount;
-						}
-					}
-				}
-				else
-				{
-					// If datafields are the first row field, then for every non-leaf field under it, calculate the column to print the total header to.
-					// Otherwise, always print it to the firstColumnWrittenTo value.
-					if (previousRepeatedItemsCount < item.RepeatedItemsCount)
-						returnColumn = startColumn + item.RepeatedItemsCount - 1;
-					else
-						returnColumn = firstColumnWrittenTo;
-				}
-			}
-			return returnColumn;
 		}

 		private void WriteRowHeaders(StringResources stringResources)
@@ -1754,7 +1571,7 @@
 					string sharedItemValue = this.GetSharedItemValue(this.RowFields, item, item.RepeatedItemsCount, 0);
 					int newColumn = this.GetCompactFormHeaderColumn(header, item, compactFormPivotFields, column, previousColumn, previousHeaderCompactForm, topNodeHeaderCompactForm, i);
 					this.Worksheet.Cells[row++, newColumn].Value = sharedItemValue;
-
+
 					// Reset the local variables.
 					if (newColumn > previousColumn)
 					{
@@ -1774,6 +1591,160 @@
 				this.Worksheet.Cells[row++, this.Address.Start.Column].Value = this.DataFields.First().Name;

 			this.WriteRowHeadersInColumn(columnFieldNames);
+		}
+
+		private void WriteTabularRowHeaders(StringResources stringResources)
+		{
+			int row = this.Address.Start.Row + this.FirstDataRow;
+			int previousColumn = this.Address.Start.Column;
+			bool previousHeaderTabularForm = true;
+			bool topNodeHeaderTabularForm = true;
+			var columnFieldNames = new List<string>();
+
+			var tabularFormPivotFields = this.Fields.Where(x => x.Outline == false);
+			bool hasTabularFormFields = this.Fields.Any(x => x.Outline == false);
+			if (this.RowFields.Any())
+			{
+				for (int i = 0; i < this.RowItems.Count; i++)
+				{
+					int column = this.Address.Start.Column;
+					var item = this.RowItems[i];
+					var header = this.RowHeaders[i];
+					for (int j = 0; j < item.Count; j++)
+					{
+						// Get the subtotal caption header if subtotals are enabled.
+						string itemType = this.GetTotalCaptionCellValue(this.RowFields, item, header, stringResources);
+						if (!string.IsNullOrEmpty(itemType))
+						{
+							if (hasTabularFormFields && !header.TotalType.IsEquivalentTo("grand"))
+								column = this.GetTabularSubtotalHeaderColumn(header, item.RepeatedItemsCount, column, topNodeHeaderTabularForm);
+							this.Worksheet.Cells[row, column].Value = itemType;
+							previousColumn = column;
+							continue;
+						}
+
+						// Get the header value to print to the cell.
+						var itemIndex = item.RepeatedItemsCount == 0 ? j : j + item.RepeatedItemsCount;
+						string sharedItemValue = this.GetSharedItemValue(this.RowFields, item, itemIndex, j);
+						if (j == 0)
+							column = this.GetTabularFormHeaderColumn(header, item, tabularFormPivotFields, column, previousColumn, previousHeaderTabularForm, topNodeHeaderTabularForm, i);
+						this.Worksheet.Cells[row, column].Value = sharedItemValue;
+
+						// Reset the local variables.
+						if (column > previousColumn)
+						{
+							var rowFieldIndex = this.RowFields[item.RepeatedItemsCount + j].Index;
+							var pivotFieldName = rowFieldIndex == -2 ? "Values" : this.Fields[rowFieldIndex].Name;
+							if (!columnFieldNames.Contains(pivotFieldName))
+								columnFieldNames.Add(pivotFieldName);
+						}
+						previousHeaderTabularForm = header.IsDataField || header.IsLeafNode ? previousHeaderTabularForm : header.IsCompactForm;
+						if (item.RepeatedItemsCount == 0 && !header.IsDataField)
+							topNodeHeaderTabularForm = header.IsTabularHeader;
+						else if (this.RowFields.First().Index == -2)
+							topNodeHeaderTabularForm = false;
+						previousColumn = column;
+						column++;
+					}
+					row++;
+				}
+			}
+			// If there are no row headers and only one data field, print the name of the data field for the row.
+			else if (this.DataFields.Count == 1)
+				this.Worksheet.Cells[row++, this.Address.Start.Column].Value = this.DataFields.First().Name;
+
+			this.WriteRowHeadersInColumn(columnFieldNames);
+		}
+
+		private int GetTabularSubtotalHeaderColumn(PivotTableHeader header, int repeatedItemsCount, int column, bool tabularTopNode)
+		{
+			int returnColumn = 0;
+			if (repeatedItemsCount == 0)
+				returnColumn = column;
+			else
+			{
+				var parentIndices = header.CacheRecordIndices.GetRange(0, repeatedItemsCount).ToList();
+				var nonTabularFields = this.Fields.Where(f => f.Outline);
+				bool hasNonTabularParent = parentIndices.Any(i => nonTabularFields.Any(f => f.Index == i.Item1));
+				bool hasDataFieldParent = parentIndices.Any(i => i.Item1 == -2);
+				if (tabularTopNode)
+				{
+					// The very top node is in tabular form.
+					if (hasNonTabularParent || hasDataFieldParent)
+						returnColumn = column + repeatedItemsCount - 1;
+					else
+						returnColumn = column + repeatedItemsCount;
+				}
+				else
+				{
+					// The very top node is not in tabular form.
+					if (hasNonTabularParent)
+					{
+						int nonTabularParentCount = parentIndices.Count(x => x.Item1 == -2 || nonTabularFields.Any(j => j.Index == x.Item1));
+						returnColumn = column + repeatedItemsCount - nonTabularParentCount;
+					}
+					else
+						returnColumn = column + repeatedItemsCount - 1;
+				}
+			}
+			return returnColumn;
+		}
+
+		private int GetTabularFormHeaderColumn(PivotTableHeader header, RowColumnItem item, IEnumerable<ExcelPivotTableField> tabularFormPivotFields, int column, int previousColumn, bool previousHeaderTabularForm, bool topNodeTabularForm, int i = 0)
+		{
+			int returnColumn = 0;
+			var parentList = header.CacheRecordIndices.GetRange(0, item.RepeatedItemsCount).ToList();
+			if (item.RepeatedItemsCount == 0)
+				returnColumn = column;
+			else
+			{
+				if (topNodeTabularForm)
+				{
+					// The top node is in compact form.
+					if (header.IsDataField && item.Count == 1)
+						returnColumn = previousColumn;
+					else
+					{
+						// If a datafield is the top node or if datafields are the leaf nodes, then all leaf nodes must be written in the same column.
+						// Otherwise, the header is a leaf node, it's parent is not in compact form and it's grandparents are all in compact form.
+						int previousIndex = this.RowFields[item.RepeatedItemsCount - 1].Index;
+						bool nonTabularField = previousIndex != -2 ? this.Fields[previousIndex].Outline : false;
+						if (previousIndex == -2)
+							returnColumn = previousColumn;
+						else if (nonTabularField)
+							returnColumn = previousColumn;
+						else
+							returnColumn = column + item.RepeatedItemsCount;
+					}
+				}
+				else
+				{
+					// The top node is not in compact form.
+					bool hasTabularFormParent = tabularFormPivotFields.Any(x => parentList.Any(j => j.Item1 == x.Index));
+					bool hasAllTabularFieldParents = parentList.All(x => x.Item1 == -2 || tabularFormPivotFields.Any(j => j.Index == x.Item1));
+					int previousIndex = this.RowFields[item.RepeatedItemsCount - 1].Index;
+					if (header.IsDataField)
+						returnColumn = previousColumn;
+					else if (previousIndex == -2 || (this.RowFields.First().Index == -2 && !hasTabularFormParent))
+					{
+						var nonTabularFields = this.Fields.Where(f => f.Outline);
+						int nonTabularParentCount = parentList.Count(x => x.Item1 == -2 || nonTabularFields.Any(j => j.Index == x.Item1));
+						returnColumn = column + item.RepeatedItemsCount - nonTabularParentCount;
+					}
+					else if (hasAllTabularFieldParents || !hasTabularFormParent)
+					{
+						// If a non-tabular form parent node has multiple children, then calculate the return column.
+						// Otherwise, this is the only child so use the previous column.
+						if (this.RowHeaders[i - 1].IsLeafNode)
+							returnColumn = column + item.RepeatedItemsCount - 1;
+						else
+							returnColumn = previousColumn;
+					}
+					else if (header.IsLeafNode && item.Count == 1)
+						returnColumn = previousColumn;
+				}
+			}
+			return returnColumn;
 		}

 		private void WriteRowHeadersInColumn(List<string> headers)


Save errors to user logs in live mode

Save errors to user logs in live mode

--- Engine/Results/LiveTradingResultHandler.cs
+++ Engine/Results/LiveTradingResultHandler.cs
@@ -529,6 +529,7 @@
         {
             if (Messages.Count > 500) return;
             Messages.Enqueue(new HandledErrorPacket(_deployId, message, stacktrace));
+            AddToLogStore(message + (!string.IsNullOrEmpty(stacktrace) ? ": StackTrace: " + stacktrace : string.Empty));
         }

         /// <summary>
@@ -549,6 +550,7 @@
         public void RuntimeError(string message, string stacktrace = "")
         {
             Messages.Enqueue(new RuntimeErrorPacket(_deployId, message, stacktrace));
+            AddToLogStore(message + (!string.IsNullOrEmpty(stacktrace) ? ": StackTrace: " + stacktrace : string.Empty));
         }

         /// <summary>


Adding checks for .Add operations on dictionaries

--- Engine/Results/LiveTradingResultHandler.cs
+++ Engine/Results/LiveTradingResultHandler.cs
@@ -214,7 +214,7 @@
                         {
                             // remove directory pathing characters from chart names
                             var safeName = chart.Value.Name.Replace('/', '-');
-                            deltaCharts.Add(safeName, chart.Value.GetUpdates());
+                            DictionarySafeAdd(deltaCharts, safeName, chart.Value.GetUpdates(), "deltaCharts");
                         }
                     }
                     Log.Debug("LiveTradingResultHandler.Update(): End build delta charts");
@@ -235,7 +235,7 @@

                         if (!security.IsInternalFeed() && !security.Symbol.IsCanonical())
                         {
-                            holdings.Add(security.Symbol.Value, new Holding(security));
+                            DictionarySafeAdd(holdings, security.Symbol.Value, new Holding(security), "holdings");
                         }
                     }

@@ -256,13 +256,13 @@
                                     : 0;

                     //Add other fixed parameters.
-                    runtimeStatistics.Add("Unrealized:", "$" + _algorithm.Portfolio.TotalUnrealizedProfit.ToString("N2"));
-                    runtimeStatistics.Add("Fees:", "-$" + _algorithm.Portfolio.TotalFees.ToString("N2"));
-                    runtimeStatistics.Add("Net Profit:", "$" + (_algorithm.Portfolio.TotalProfit - _algorithm.Portfolio.TotalFees).ToString("N2"));
-                    runtimeStatistics.Add("Return:", netReturn.ToString("P"));
-                    runtimeStatistics.Add("Equity:", "$" + _algorithm.Portfolio.TotalPortfolioValue.ToString("N2"));
-                    runtimeStatistics.Add("Holdings:", "$" + _algorithm.Portfolio.TotalHoldingsValue.ToString("N2"));
-                    runtimeStatistics.Add("Volume:", "$" + _algorithm.Portfolio.TotalSaleVolume.ToString("N2"));
+                    DictionarySafeAdd(runtimeStatistics, "Unrealized:", "$" + _algorithm.Portfolio.TotalUnrealizedProfit.ToString("N2"), "runtimeStatistics");
+                    DictionarySafeAdd(runtimeStatistics, "Fees:", "-$" + _algorithm.Portfolio.TotalFees.ToString("N2"), "runtimeStatistics");
+                    DictionarySafeAdd(runtimeStatistics, "Net Profit:", "$" + (_algorithm.Portfolio.TotalProfit - _algorithm.Portfolio.TotalFees).ToString("N2"), "runtimeStatistics");
+                    DictionarySafeAdd(runtimeStatistics, "Return:", netReturn.ToString("P"), "runtimeStatistics");
+                    DictionarySafeAdd(runtimeStatistics, "Equity:", "$" + _algorithm.Portfolio.TotalPortfolioValue.ToString("N2"), "runtimeStatistics");
+                    DictionarySafeAdd(runtimeStatistics, "Holdings:", "$" + _algorithm.Portfolio.TotalHoldingsValue.ToString("N2"), "runtimeStatistics");
+                    DictionarySafeAdd(runtimeStatistics, "Volume:", "$" + _algorithm.Portfolio.TotalSaleVolume.ToString("N2"), "runtimeStatistics");

                     // since we're sending multiple packets, let's do it async and forget about it
                     // chart data can get big so let's break them up into groups
@@ -285,7 +285,7 @@
                             {
                                 // remove directory pathing characters from chart names
                                 var safeName = chart.Value.Name.Replace('/', '-');
-                                chartComplete.Add(safeName, chart.Value.Clone());
+                                DictionarySafeAdd(chartComplete, safeName, chart.Value.Clone(), "chartComplete");
                             }
                         }
                         var orders = new Dictionary<int, Order>(_transactionHandler.Orders);
@@ -1114,5 +1114,17 @@

             Log.Debug("LiveTradingResultHandler.ProcessSynchronousEvents(): Exit");
         }
+
+        private static void DictionarySafeAdd<T>(Dictionary<string, T> dictionary, string key, T value, string dictionaryName)
+        {
+            if (dictionary.ContainsKey(key))
+            {
+                Log.Error($"LiveTradingResultHandler.DictionarySafeAdd(): dictionary {dictionaryName} already contains key {key}");
+            }
+            else
+            {
+                dictionary.Add(key, value);
+            }
+        }
     }
 }


Added IComponent.TryCast<T>

Added IComponent.TryCast<T>

Used for less ugly casting for derived component types

--- Entities/Components/Internal/IComponent.cs
+++ Entities/Components/Internal/IComponent.cs
@@ -5,6 +5,37 @@

 namespace Andromeda2D.Entities.Components
 {
+    public static class ComponentExtension
+    {
+        /// <summary>
+        /// Used to turn abstract components into derived types
+        /// </summary>
+        /// <typeparam name="T">The type of the component</typeparam>
+        /// <param name="self"></param>
+        /// <param name="component">The destination component object</param>
+        /// <returns>True if derived type is valid for the component</returns>
+        public static bool TryCast<T>(this IComponent self, out T component) where T : IComponent
+        {
+            // The purpose of this function is to save me doing
+            // if (component is DerivedComponent)
+            //      (component as DerivedComponent).DoAction();
+            //
+            // Instead, can do this - which is more readable
+            // if (component.TryCast(out DerivedComponent derived))
+            //      derived.DoAction();
+
+            if (self is T)
+            {
+                component = (T)self;
+                return true;
+            }
+            else
+            {
+                component = default(T);
+                return false;
+            }
+        }
+    }

     public interface IComponent
     {


Fix the tests build

Fix the tests build

--- Espera.Core.Tests/YoutubeSongFinderTest.cs
+++ Espera.Core.Tests/YoutubeSongFinderTest.cs
@@ -14,9 +14,9 @@
             public async Task NullSearchTermDefaultsToEmptyString()
             {
                 var songs = new[] { new YoutubeSong("http://blabla", TimeSpan.Zero) };
-                BlobCache.LocalMachine.InsertObject(BlobCacheKeys.GetKeyForYoutubeCache(string.Empty), songs);
-
-                var finder = new YoutubeSongFinder();
+                var cache = new InMemoryBlobCache();
+                cache.InsertObject(BlobCacheKeys.GetKeyForYoutubeCache(string.Empty), songs);
+                var finder = new YoutubeSongFinder(cache);

                 var result = await finder.GetSongsAsync();

@@ -28,9 +28,9 @@
             {
                 const string searchTerm = "Foo";
                 var songs = new[] { new YoutubeSong("http://blabla", TimeSpan.Zero) };
-                BlobCache.LocalMachine.InsertObject(BlobCacheKeys.GetKeyForYoutubeCache(searchTerm), songs);
-
-                var finder = new YoutubeSongFinder();
+                var cache = new InMemoryBlobCache();
+                cache.InsertObject(BlobCacheKeys.GetKeyForYoutubeCache(searchTerm), songs);
+                var finder = new YoutubeSongFinder(cache);

                 var result = await finder.GetSongsAsync(searchTerm);


It's amazing what two lines of code can do...

--- ExtendedControls/Forms/SmartSysMenuForm.cs
+++ ExtendedControls/Forms/SmartSysMenuForm.cs
@@ -154,6 +154,8 @@
                         else if ((int)m.WParam > SC_OPACITYSUBMENU && (int)m.WParam <= SC_OPACITYSUBMENU + 10)
                             Opacity = ((int)m.WParam - SC_OPACITYSUBMENU) / 10f;
                         else if (!AllowResize && (m.WParam == (IntPtr)SC.MAXIMIZE || m.WParam == (IntPtr)SC.SIZE || m.WParam == (IntPtr)SC.RESTORE))
+                            return;     // Access Denied.
+                        else
                             break;

                         m.Result = IntPtr.Zero;


incremented version number

incremented version number

--- FireRatingCloud/Properties/AssemblyInfo.cs
+++ FireRatingCloud/Properties/AssemblyInfo.cs
@@ -48,6 +48,7 @@
 // 2015-09-14 2016.0.0.11 updated Get to return a list of deserialised DoorData instances
 // 2015-09-14 2016.0.0.12 commented out JsonParser code and pass DoorData instance to Put method
 // 2015-09-15 2016.0.0.13 cleaned up for publication
+// 2015-11-18 2016.0.0.14 readme enhancements and installation instructions for autodesk university
 //
-[assembly: AssemblyVersion( "2016.0.0.13" )]
-[assembly: AssemblyFileVersion( "2016.0.0.13" )]
+[assembly: AssemblyVersion( "2016.0.0.14" )]
+[assembly: AssemblyFileVersion( "2016.0.0.14" )]


Fixed build failure issue. EndOfObject should have been EndObject. (#83)

--- FireSharp/EventStreaming/TemporaryCache.cs
+++ FireSharp/EventStreaming/TemporaryCache.cs
@@ -111,7 +111,7 @@
                     case JsonToken.Null:
                         DeleteChild(root);
                         return;
-                    case JsonToken.EndOfObject: break;
+                    case JsonToken.EndObject: break;
                 }
             }
         }


Fixed a resolver lacking content.

Fixed a resolver lacking content.

--- Framework/Cqrs/Events/EventDataResolver.cs
+++ Framework/Cqrs/Events/EventDataResolver.cs
@@ -7,13 +7,14 @@
 #endregion

 using System;
+using System.Collections.Generic;
 using System.Runtime.Serialization;
 using System.Xml;
 using Cqrs.Services;

 namespace Cqrs.Events
 {
-	public class EventDataResolver : IEventDataResolver
+	public class EventDataResolver<TAuthenticationToken> : IEventDataResolver
 	{
 		#region Implementation of IServiceParameterResolver

@@ -23,6 +24,22 @@
 			{
 				XmlDictionary dictionary = new XmlDictionary();
 				typeName = dictionary.Add("EventData");
+				typeNamespace = dictionary.Add("http://cqrs.co.nz");
+				return true;
+			}
+
+			if (dataContractType == typeof(ServiceRequestWithData<TAuthenticationToken, Guid>))
+			{
+				XmlDictionary dictionary = new XmlDictionary();
+				typeName = dictionary.Add("EventDataGetRequest");
+				typeNamespace = dictionary.Add("http://cqrs.co.nz");
+				return true;
+			}
+
+			if (dataContractType == typeof(ServiceResponseWithResultData<IEnumerable<Guid>>))
+			{
+				XmlDictionary dictionary = new XmlDictionary();
+				typeName = dictionary.Add("EventDataGetResponse");
 				typeNamespace = dictionary.Add("http://cqrs.co.nz");
 				return true;
 			}
@@ -37,6 +54,12 @@
 			if (typeName == "EventData" && typeNamespace == "http://cqrs.co.nz")
 				return typeof(EventData);

+			if (typeName == "EventDataGetRequest" && typeNamespace == "http://cqrs.co.nz")
+				return typeof(ServiceRequestWithData<TAuthenticationToken, Guid>);
+
+			if (typeName == "EventDataGetResponse" && typeNamespace == "http://cqrs.co.nz")
+				return typeof(ServiceResponseWithResultData<IEnumerable<Guid>>);
+
 			return null;
 		}


Updated method call

Updated method call

--- GivenWhenUnity/Assets/Scripts/RunsTests.cs
+++ GivenWhenUnity/Assets/Scripts/RunsTests.cs
@@ -32,7 +32,7 @@

 	// Update is called once per frame
 	void Update () {
-        TestBehaviour[] fixtures = GameObject.FindSceneObjectsOfType(typeof(TestBehaviour)) as TestBehaviour[];
+        TestBehaviour[] fixtures = GameObject.FindObjectsOfType(typeof(TestBehaviour)) as TestBehaviour[];

         foreach (TestBehaviour test in fixtures)
         {


remove unused import

remove unused import

--- GrowableOverhaul/DetourLoadingExtension.cs
+++ GrowableOverhaul/DetourLoadingExtension.cs
@@ -1,6 +1,5 @@
 using System;
 using System.Collections.Generic;
-using System.Linq;
 using System.Reflection;
 using GrowableOverhaul.Redirection;
 using ICities;


Fixed typo in PlayerSound

Fixed typo in PlayerSound

--- Haunt/Assets/Scripts/Player/PlayerSound.cs
+++ Haunt/Assets/Scripts/Player/PlayerSound.cs
@@ -15,7 +15,7 @@
 	}

 	public void Blast () {
-		if(audioSrc != null && clipBlase != null) {
+		if(audioSrc != null && clipBlast != null) {
 			audioSrc.clip = clipBlast;
 			audioSrc.Play ();
 		}


Added a comment

Added a comment

--- InMobile.Sms.ApiClient/ApiRequestHelper.cs
+++ InMobile.Sms.ApiClient/ApiRequestHelper.cs
@@ -12,7 +12,9 @@
         void ExecuteWithNoContent(Method method, string resource, object? payload = null);
         List<T> ExecuteGetAndIteratePagedResult<T>(string resource);
     }
-
+    /// <summary>
+    /// A general help for rest requests
+    /// </summary>
     internal class ApiRequestHelper : IApiRequestHelper
     {
         private readonly HttpBasicAuthenticator _authenticator;


[2.3.16-pre] working on re-open

[2.3.16-pre] working on re-open

--- WinFormDemo/Form1.cs
+++ WinFormDemo/Form1.cs
@@ -104,6 +104,23 @@
         // Business Logic
         ////////////////////////////////////////////////////////////////////////

+        SpectrometerState currentSpectrometerState(string label="???")
+        {
+            if (currentSpectrometer is null)
+            {
+                logger.error($"Unexpected[{label}]: no current spectrometer");
+                return null;
+            }
+
+            if (!spectrometerStates.ContainsKey(currentSpectrometer))
+            {
+                logger.error($"Unexpected[{label}]: missing state for {currentSpectrometer.serialNumber}");
+                return null;
+            }
+
+            return spectrometerStates[currentSpectrometer];
+        }
+
         void initializeSpectrometer(Spectrometer s)
         {
             SpectrometerState state = new SpectrometerState(s, opts);
@@ -150,13 +167,15 @@
             }

             logger.debug($"updateCurrentSpectrometer: {currentSpectrometer.serialNumber}");
-            SpectrometerState state = spectrometerStates[currentSpectrometer];
+            var state = currentSpectrometerState();
+            if (state is null)
+                return;

             // update tree view
             treeViewSettings_DoubleClick(null, null);

             // update start button
-            updateStartButton(spectrometerStates[currentSpectrometer].running);
+            updateStartButton(state.running);

             // update basic controls
             DemoUtil.expandNUD(numericUpDownIntegTimeMS, (int)currentSpectrometer.integrationTimeMS);
@@ -216,9 +235,10 @@
         {
             lock (spectrometers)
             {
-                foreach (Spectrometer spectrometer in spectrometers)
-                {
-                    SpectrometerState state = spectrometerStates[spectrometer];
+                foreach (var pair in spectrometerStates)
+                {
+                    var spectrometer = pair.Key;
+                    var state = pair.Value;

                     if (state.spectrum is null)
                         continue;
@@ -274,22 +294,26 @@

                 // not really sure what behavior would be considered "ideal" in this case,
                 // but I'm stopping all "running" background threads
+                const int delayMS = 1000;
                 foreach (var pair in spectrometerStates)
                 {
                     var spec = pair.Key;
                     var state = pair.Value;

-                    if (!useTasks)
+                    if (useTasks)
                     {
-                        logger.debug("cancelAsync {0}", spec.serialNumber);
+                        state.stopping = true;
+                        await Task.Delay(delayMS);
+                    }
+                    else
+                    {
                         state.worker.CancelAsync();
+                        Thread.Sleep(delayMS);
                     }

-                    const int delayMS = 200;
                     while (state.running)
                     {
                         logger.debug("waiting to stop {0}", spec.serialNumber);
-                        state.stopping = true;
                         if (useTasks)
                             await Task.Delay(delayMS);
                         else
@@ -353,7 +377,10 @@
         // This only affects the currently-running spectrometer
         private void buttonStart_Click(object sender, EventArgs e)
         {
-            SpectrometerState state = spectrometerStates[currentSpectrometer];
+            var state = currentSpectrometerState();
+            if (state is null)
+                return;
+
             if (!state.running)
             {
                 logger.info($"Starting {currentSpectrometer.serialNumber}");
@@ -411,7 +438,10 @@

         private void checkBoxTakeDark_CheckedChanged(object sender, EventArgs e)
         {
-            SpectrometerState state = spectrometerStates[currentSpectrometer];
+            var state = currentSpectrometerState();
+            if (state is null)
+                return;
+
             lock (spectrometers)
             {
                 if (checkBoxTakeDark.Checked)
@@ -441,7 +471,10 @@

         private void checkBoxTakeReference_CheckedChanged(object sender, EventArgs e)
         {
-            SpectrometerState state = spectrometerStates[currentSpectrometer];
+            var state = currentSpectrometerState();
+            if (state is null)
+                return;
+
             lock (spectrometers)
             {
                 bool success = false;
@@ -477,22 +510,30 @@

         private void radioButtonModeScope_CheckedChanged(object sender, EventArgs e)
         {
-            spectrometerStates[currentSpectrometer].processingMode = SpectrometerState.ProcessingModes.SCOPE;
+            var state = currentSpectrometerState();
+            if (state != null)
+                state.processingMode = SpectrometerState.ProcessingModes.SCOPE;
         }

         private void radioButtonModeAbsorbance_CheckedChanged(object sender, EventArgs e)
         {
-            spectrometerStates[currentSpectrometer].processingMode = SpectrometerState.ProcessingModes.ABSORBANCE;
+            var state = currentSpectrometerState();
+            if (state != null)
+                state.processingMode = SpectrometerState.ProcessingModes.ABSORBANCE;
         }

         private void radioButtonModeTransmission_CheckedChanged(object sender, EventArgs e)
         {
-            spectrometerStates[currentSpectrometer].processingMode = SpectrometerState.ProcessingModes.TRANSMISSION;
+            var state = currentSpectrometerState();
+            if (state != null)
+                state.processingMode = SpectrometerState.ProcessingModes.TRANSMISSION;
         }

         private void buttonAddTrace_Click(object sender, EventArgs e)
         {
-            SpectrometerState state = spectrometerStates[currentSpectrometer];
+            var state = currentSpectrometerState();
+            if (state is null)
+                return;

             Series trace = new Series();
             trace.IsVisibleInLegend = false;
@@ -538,8 +579,8 @@

             lock (spectrometers)
             {
-                SpectrometerState state = spectrometerStates[currentSpectrometer];
-                if (state.spectrum is null)
+                var state = currentSpectrometerState();
+                if (state is null || state.spectrum is null)
                     return;

                 state.save();
@@ -639,13 +680,14 @@
                     if (mut.WaitOne(10))
                     {
                         int count = 0;
-                        foreach (Spectrometer s in spectrometers)
+                        foreach (var pair in spectrometerStates)
                         {
-                            count += s.spectrumCount;
-                            if (!s.isARM)
+                            var spectrometer = pair.Key;
+                            count += spectrometer.spectrumCount;
+                            if (!spectrometer.isARM)
                             {
-                                SpectrometerState state = spectrometerStates[s];
-                                state.detTempDegC = s.detectorTemperatureDegC;
+                                var state = pair.Value;
+                                state.detTempDegC = spectrometer.detectorTemperatureDegC;
                             }
                         }
                         labelSpectrumCount.BeginInvoke(new MethodInvoker(delegate { labelSpectrumCount.Text = $"{count}"; }));
@@ -693,7 +735,12 @@
         private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
         {
             Spectrometer spectrometer = (Spectrometer) e.Argument;
-            SpectrometerState state = spectrometerStates[spectrometer];
+            if (!spectrometerStates.ContainsKey(spectrometer))
+            {
+                logger.error("Unexpected: missing state for {spectrometer.serialNumber}");
+                return;
+            }
+            var state = spectrometerStates[spectrometer];

             state.running = true;
             state.stopping = false;
@@ -717,12 +764,18 @@
             }

             logger.debug("worker closing");
+            state.running = false; // shouldn't need this, but RunWorkerCompleted isn't always firing?
             e.Result = spectrometer; // pass spectrometer handle to _Completed callback
         }

         async Task<bool> Task_DoWork(Spectrometer spectrometer)
         {
-            SpectrometerState state = spectrometerStates[spectrometer];
+            if (!spectrometerStates.ContainsKey(spectrometer))
+            {
+                logger.error("Unexpected: missing state for {spectrometer.serialNumber}");
+                return false;
+            }
+            var state = spectrometerStates[spectrometer];

             state.running = true;
             state.stopping = false;
@@ -804,6 +857,13 @@
             if (spectrometer == currentSpectrometer)
                 updateStartButton(false);

+            if (!spectrometerStates.ContainsKey(spectrometer))
+            {
+                // this can happen during deliberate disconnect events
+                logger.error($"Unexpected: spectrometer {spectrometer.serialNumber} has no tracked state");
+                return;
+            }
+
             var state = spectrometerStates[spectrometer];
             state.running = false;

@@ -815,6 +875,12 @@
                 {
                     foreach (Spectrometer s in spectrometers)
                     {
+                        if (!spectrometerStates.ContainsKey(s))
+                        {
+                            logger.error($"Unexpected: missing spectrometerState {s.serialNumber}");
+                            continue;
+                        }
+
                         SpectrometerState ss = spectrometerStates[s];
                         if (ss.scanCount < opts.scanCount)
                             waitList.Add(s.serialNumber);


standardise comments above code

standardise comments above code

--- LINQ.Exercises/LINQ.Exercises/Partition.cs
+++ LINQ.Exercises/LINQ.Exercises/Partition.cs
@@ -24,59 +24,59 @@
             Assert.IsTrue(result.SequenceEqual(new[] { 5, 4, 1 }));
         }

+        // Get the first two numbers in the array
         [TestMethod]
         public void GetFirstTwoNumbers_returns_2_ints()
-        {
-            // Get the first two numbers in the array
+        {
             IEnumerable<int> result = TestData.PartitionNumbers;

             Assert.IsTrue(result.SequenceEqual(new[] { 5, 4 }));
         }

+        // return everything in the array but the first four numbers
         [TestMethod]
         public void IgnoreFirstFourNumbers_returns_4_ints()
-        {
-            // return everything in the array but the first four numbers
+        {
             IEnumerable<int> result = TestData.PartitionNumbers;

             Assert.IsTrue(result.SequenceEqual(new[] { 9, 8, 6, 7, 2, 0 }));
         }

+        // return elements starting from the beginning of the array
+        // until a number is hit that is not less than 6
         [TestMethod]
         public void Enumerate_Till_You_Get_A_Number_NotLessThanSix_returns_4_ints()
-        {
-            // return elements starting from the beginning of the array
-            // until a number is hit that is not less than 6
+        {
             IEnumerable<int> result = TestData.PartitionNumbers;

             Assert.IsTrue(result.SequenceEqual(new[] { 5, 4, 1, 3 }));
         }

+        // return elements starting from the beginning of the array
+        // until a number is hit that is less than its position in the array
         [TestMethod]
         public void Enumerate_Till_A_Number_Hit_Which_is_less_than_its_own_array_position_returns_2_ints()
-        {
-            // return elements starting from the beginning of the array
-            // until a number is hit that is less than its position in the array
+        {
             IEnumerable<int> result = TestData.PartitionNumbers;

             Assert.IsTrue(result.SequenceEqual(new[] { 5, 4 }));
         }

+        // get the elements of the array
+        // starting from the first element divisible by 3
         [TestMethod]
         public void GetElementsOfArrayStartingFromTheFirstElementDivisibleByThree_Return7ints()
-        {
-            // get the elements of the array
-            // starting from the first element divisible by 3
+        {
             IEnumerable<int> result = TestData.PartitionNumbers;

             Assert.IsTrue(result.SequenceEqual(new[] { 3, 9, 8, 6, 7, 2, 0 }));
         }

+        // get the elements of the array
+        // starting from the first element less than its position.
         [TestMethod]
         public void GetElementsStartingFromFirstElementLessThanItsPosition_Return8ints()
-        {
-            // get the elements of the array
-            // starting from the first element less than its position.
+        {
             IEnumerable<int> result = TestData.PartitionNumbers;

             Assert.IsTrue(result.SequenceEqual(new[] { 1, 3, 9, 8, 6, 7, 2, 0 }));


* GUI min track height changed

* GUI min track height changed


SetProperty を修正

SetProperty を修正

--- Libraries/Views/Controls/CaptionControl.cs
+++ Libraries/Views/Controls/CaptionControl.cs
@@ -198,6 +198,10 @@
         protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
             => PropertyChanged?.Invoke(this, e);

+        #endregion
+
+        #region Non-virtual protected methods
+
         /* ----------------------------------------------------------------- */
         ///
         /// SetProperty
@@ -207,10 +211,23 @@
         /// </summary>
         ///
         /* ----------------------------------------------------------------- */
-        protected virtual bool SetProperty<T>(ref T field, T value,
-            [CallerMemberName] string name = null)
-        {
-            if (EqualityComparer<T>.Default.Equals(field, value)) return false;
+        protected bool SetProperty<T>(ref T field, T value,
+            [CallerMemberName] string name = null) =>
+            SetProperty(ref field, value, EqualityComparer<T>.Default, name);
+
+        /* ----------------------------------------------------------------- */
+        ///
+        /// SetProperty
+        ///
+        /// <summary>
+        /// プロパティに値を設定します。
+        /// </summary>
+        ///
+        /* ----------------------------------------------------------------- */
+        protected bool SetProperty<T>(ref T field, T value,
+            IEqualityComparer<T> func, [CallerMemberName] string name = null)
+        {
+            if (func.Equals(field, value)) return false;
             field = value;
             OnPropertyChanged(new PropertyChangedEventArgs(name));
             return true;


minor fix for encoding null described lists

--- LightRail.Amqp/Types/DescribedListCodec.cs
+++ LightRail.Amqp/Types/DescribedListCodec.cs
@@ -144,6 +144,11 @@
                 if (typeof(DescribedType).IsAssignableFrom(propertyType))
                 {
                     var describedValue = (prop.Getter(_instance) as DescribedType);
+                    if (describedValue == null)
+                    {
+                        Encoder.WriteNull(_buffer);
+                        return;
+                    }
                     describedValue.Encode(_buffer);
                     return;
                 }


relocate

relocate

BaseAdminPage

--- MasterChef/MasterChef.Web/BaseAdminPage.cs
+++ MasterChef/MasterChef.Web/BaseAdminPage.cs
@@ -1,43 +0,0 @@
-namespace DrinkAndRate.Web.User
-{
-    using System.Data.Entity.Infrastructure;
-    using System.Linq;
-    using System.Web;
-    using System.Web.UI;
-    using Microsoft.AspNet.EntityDataSource;
-    using MasterChef.Data;
-
-    public abstract class BaseAdminPage : Page
-    {
-        protected IMasterChefDbContext dbContext;
-        protected IMasterChefData data;
-
-        public BaseAdminPage()
-        {
-            dbContext = new MasterChefDbContext();
-            data = new MasterChefData(dbContext);
-
-            bool isAuthenticatedAndAdmin = this.User.Identity.IsAuthenticated;
-
-            if (isAuthenticatedAndAdmin)
-            {
-                var user = data.Users.All()
-                    .Single(x => x.UserName == this.Context.User.Identity.Name);
-                var adminRole = data.Roles.All()
-                    .Single(x => x.Name == "admin");
-
-                isAuthenticatedAndAdmin = user.Roles.Any(role => role.RoleId == adminRole.Id);
-            }
-
-            if (!isAuthenticatedAndAdmin)
-            {
-                HttpContext.Current.Response.Redirect("~/");
-            }
-        }
-
-        protected void dataSource_ContextCreating(object sender, EntityDataSourceContextCreatingEventArgs e)
-        {
-            e.Context = (new MasterChefDbContext() as IObjectContextAdapter).ObjectContext;
-        }
-    }
-}


Updated version number

Updated version number

--- MegaCityOne.Mvc/Properties/AssemblyInfo.cs
+++ MegaCityOne.Mvc/Properties/AssemblyInfo.cs
@@ -32,5 +32,5 @@
 // You can specify all the values or you can default the Build and Revision Numbers
 // by using the '*' as shown below:
 // [assembly: AssemblyVersion("1.0.*")]
-[assembly: AssemblyVersion("2.0.5.0")]
-[assembly: AssemblyFileVersion("2.0.5.0")]
+[assembly: AssemblyVersion("2.0.6.0")]
+[assembly: AssemblyFileVersion("2.0.6.0")]


Correct way of setting content-type in WinRT

--- Mindscape.Raygun4Net.WinRT/RaygunClient.cs
+++ Mindscape.Raygun4Net.WinRT/RaygunClient.cs
@@ -3,6 +3,7 @@
 using System.Collections.Generic;
 using System.Linq;
 using System.Runtime.InteropServices;
+using System.Text;
 using Mindscape.Raygun4Net.Messages;

 using System.Threading.Tasks;
@@ -212,8 +213,7 @@
           {
             client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("raygun4net-winrt", "1.0.0"));

-            HttpContent httpContent = new StringContent(SimpleJson.SerializeObject(raygunMessage));
-            httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json; charset=utf-8");
+            HttpContent httpContent = new StringContent(SimpleJson.SerializeObject(raygunMessage), Encoding.UTF8, "application/json");
             httpContent.Headers.Add("X-ApiKey", _apiKey);

             try


Updated payment status for API v2

Updated payment status for API v2

--- Mollie.Api/Models/Payment/PaymentStatus.cs
+++ Mollie.Api/Models/Payment/PaymentStatus.cs
@@ -3,11 +3,9 @@
         Open,
         Canceled,
         Pending,
-        Paid,
-        PaidOut,
-        Refunded,
+        Authorized,
         Expired,
         Failed,
-        Charged_Back
+        Paid
     }
 }


Reverting part of 3e24c750 which removed version check in OverloadResolve to be backward compatible

--- Mono.Debugging.Soft/SoftDebuggerAdaptor.cs
+++ Mono.Debugging.Soft/SoftDebuggerAdaptor.cs
@@ -1678,7 +1678,11 @@
 				}

 				if (methods == null) {
-					methods = currentType.GetMethodsByNameFlags (methodName, methodByNameFlags, !ctx.CaseSensitive);
+					if (currentType.VirtualMachine.Version.AtLeast (2, 7)) {
+						methods = currentType.GetMethodsByNameFlags (methodName, methodByNameFlags, !ctx.CaseSensitive);
+					} else {
+						methods = currentType.GetMethods ();
+					}

 					if (ctx.CaseSensitive) {
 						lock (cache) {


Changed the NEC donation pool over to miningpool.co

--- MultiMiner.Engine/Helpers/DonationPools.cs
+++ MultiMiner.Engine/Helpers/DonationPools.cs
@@ -158,7 +158,7 @@
             configurations.Add(donationConfiguration);

             //NEC
-            donationConfiguration = CreateCoinConfiguration("NEC", "stratum+tcp://neo.cryptcoins.net", 3331);
+            donationConfiguration = CreateCoinConfiguration("NEC", "stratum+tcp://de1.miningpool.co", 19664);
             configurations.Add(donationConfiguration);

             //TAG


fix for NPE on resetting the bound texture.

--- cocos2d/platform/DrawManager.cs
+++ cocos2d/platform/DrawManager.cs
@@ -565,7 +565,14 @@

             if (!graphicsDevice.IsDisposed && graphicsDevice.GraphicsDeviceStatus == GraphicsDeviceStatus.Normal)
             {
-                graphicsDevice.SamplerStates[0] = texture.m_samplerState;
+                if (tex == null)
+                {
+                    graphicsDevice.SamplerStates[0] = SamplerState.LinearClamp;
+                }
+                else
+                {
+                    graphicsDevice.SamplerStates[0] = texture.m_samplerState;
+                }
                 if (m_currentTexture != tex)
                 {
                     m_currentTexture = tex;


added failing test to issue #113 by Shahab

--- NHibernate.SolrNet.Tests/ListenersTests.cs
+++ NHibernate.SolrNet.Tests/ListenersTests.cs
@@ -64,6 +64,18 @@
         }

         [Test]
+        public void PostInsert_with_commit_adds_to_solr() {
+            var entity = new Entity();
+            using (var session = sessionFactory.OpenSession()) {
+                using (var tx = session.BeginTransaction()) {
+                    session.Save(entity);
+                    tx.Commit();
+                }
+            }
+            mockSolr.AssertWasCalled(x => x.Add(entity), o => o.Repeat.Once().Return(null));
+        }
+
+        [Test]
         [Ignore("Session dispose should follow transaction rollback. See http://www.nhforge.org/doc/nh/en/index.html#manipulatingdata-endingsession-commit")]
         public void Insert_with_multiple_transactions() {
             var entity = new Entity();


Fixing build (xbuild): unused local variable in AutoComplete/SnippetGenerator.cs

--- OmniSharp/AutoComplete/SnippetGenerator.cs
+++ OmniSharp/AutoComplete/SnippetGenerator.cs
@@ -221,7 +221,6 @@
                     if (member is IMethod)
                     {
                         var method = ((IMethod)member);
-                        var typeParams = method.TypeParameters;

                         var methodParameterTypeArguments =
                             from p in method.Parameters