starting to develop a c# wrapper for xgboost: c# implementation of kaggle higgs demo

--- windows/xgboost_sharp_wrapper/xgboost.cs
+++ windows/xgboost_sharp_wrapper/xgboost.cs
@@ -15,14 +15,17 @@

         [DllImport(dll_path+"xgboost_wrapper.dll", CallingConvention=CallingConvention.Cdecl)]
         public static extern IntPtr XGDMatrixCreateFromFile(string fname, int silent);
-
-        public IntPtr SharpXGDMatrixCreateFromFile(string fname, int silent)
+public IntPtr SharpXGDMatrixCreateFromFile(string fname, int silent)
         {
             return XGDMatrixCreateFromFile(fname, silent);
         }

         [DllImport(dll_path + "xgboost_wrapper.dll")]
         public static extern IntPtr XGBoosterCreate(IntPtr[] dmats, System.UInt32 len);
+        public IntPtr SharpXGBoosterCreate(IntPtr[] dmats, System.UInt32 len)
+        {
+            return XGBoosterCreate(dmats, len);
+        }

         [DllImport(dll_path + "xgboost_wrapper.dll")]
         public static extern void XGBoosterUpdateOneIter(IntPtr handle, int iter, IntPtr dtrain);


Enum prototype, test for disputable use cases

--- Main/tests/Enums/EnumTests.cs
+++ Main/tests/Enums/EnumTests.cs
@@ -20,6 +20,15 @@
 			B = 0x2,
 			C = 0x3,
 			D = 0x4,
+		}
+
+		[Test]
+		public void Test00ToDiscuss()
+		{
+			Assert.IsTrue(2.Includes(0));
+			Assert.IsFalse(2.Excludes(0));
+			Assert.IsTrue(2.IncludesAny(0));
+			Assert.IsFalse(2.ExcludesAny(0));
 		}

 		[Test]


code refactoring.

code refactoring.

--- src/kafka-net/HLConsumer.cs
+++ src/kafka-net/HLConsumer.cs
@@ -19,7 +19,7 @@
 namespace KafkaNet
 {
 	/// <summary>
-	/// Description of HLConsumer.
+	/// High level consumer using zookeeper for coordination.
 	/// </summary>
 	public class HLConsumer
 	{
@@ -45,31 +45,18 @@
 		}

 		public IEnumerable<Message> consume(string groupID){
-			var path = new StringBuilder( "/consumers" ); //+ groupID + "/offsets/" + this._topic ;
 			var p = "/consumers/"+groupID+"/offsets/"+this._topic;
 			try {
 				if(_zookeeper.Exists(p , _watcher) ==null){
-					if(_zookeeper.Exists(path.ToString(), _watcher) ==null){
-						_zookeeper.Create(path.ToString(), new byte[0], Ids.CREATOR_ALL_ACL, CreateMode.Persistent);
-
-					} else if(_zookeeper.Exists(path.Append("/").Append(groupID).ToString(), _watcher) == null){
-						_zookeeper.Create(path.ToString(), new byte[0], Ids.CREATOR_ALL_ACL, CreateMode.Persistent);
-
-					} else if (_zookeeper.Exists(path.Append("/offsets").ToString(), _watcher) == null){
-						_zookeeper.Create(path.ToString(), new byte[0], Ids.CREATOR_ALL_ACL, CreateMode.Persistent);
-
-					} else if (_zookeeper.Exists(path.Append("/").Append(this._topic).ToString(), _watcher) == null){
-						_zookeeper.Create(path.ToString(), new byte[0], Ids.CREATOR_ALL_ACL, CreateMode.Persistent);
-					}
-
+					CreateZookeeperPath("/consumers","/"+groupID, "/offsets", "/"+this._topic);
 					var common = new MetadataQueries(_router);
 					var offsets = common.GetTopicOffsetAsync(groupID).Result;
 					_consumer.SetOffsetPosition(offsets.Select(x => new OffsetPosition(x.PartitionId, x.Offsets.Min())).ToArray());
 					offsets.ForEach(off => {
 					                	_zookeeper.Create(p + "/" + off.PartitionId.ToString(),
-					                                  System.Text.Encoding.UTF8.GetBytes(off.Offsets.Min().ToString()),
-					                                  Ids.OPEN_ACL_UNSAFE,
-					                                  CreateMode.PersistentSequential);
+					                	                  System.Text.Encoding.UTF8.GetBytes(off.Offsets.Min().ToString()),
+					                	                  Ids.OPEN_ACL_UNSAFE,
+					                	                  CreateMode.PersistentSequential);
 					                });
 				}
 				else {
@@ -82,7 +69,6 @@
 					                          		if(data != null && data.Length >0){
 					                          			long offset = 0;
 					                          			if(long.TryParse(System.Text.Encoding.Default.GetString(data), out offset)){
-//					                          				_consumer.SetOffsetPosition(new OffsetPosition(partition, offset));
 					                          				offsets.Add(new OffsetPosition(partition, offset));
 					                          			}
 					                          		}
@@ -90,11 +76,33 @@
 					                          });
 					_consumer.SetOffsetPosition(offsets.ToArray());
 				}
-			} catch (Exception e) {
-				//TODO: Log the error, or handle it?
+			} catch (Exception) {
+				//TODO: Log the error, or handle it?
 			}

 			return _consumer.Consume();
 		}
+
+		/// <summary>
+		/// create zookeeper path hierarchically.
+		/// </summary>
+		/// <param name="path">paths by level, the next path should be append to the previous one to form a valid path</param>
+		/// <returns></returns>
+		public bool CreateZookeeperPath(params string[] path){
+			var sb = new StringBuilder();
+			var success = true;
+			try{
+				for (int i = 0; i < path.Length; i++) {
+					sb.Append(path[i]);
+					if(_zookeeper.Exists(sb.ToString(), _watcher) == null){
+						_zookeeper.Create(sb.ToString(), new byte[0], Ids.CREATOR_ALL_ACL, CreateMode.Persistent);
+					}
+				}
+			} catch (Exception){
+				success = false;
+				//TODO:
+			}
+			return success;
+		}
 	}
 }


Add handler for Alpaca rejected order events

--- Brokerages/Alpaca/AlpacaBrokerage.Utility.cs
+++ Brokerages/Alpaca/AlpacaBrokerage.Utility.cs
@@ -146,6 +146,13 @@
                         FillQuantity = fillQuantity * (order.Direction == OrderDirection.Buy ? 1 : -1)
                     });
                 }
+                else if (trade.Event == TradeEvent.Rejected)
+                {
+                    OnOrderEvent(new OrderEvent(order,
+                            DateTime.UtcNow,
+                            OrderFee.Zero,
+                            "Alpaca Rejected Order Event") { Status = OrderStatus.Invalid });
+                }
                 else if (trade.Event == TradeEvent.Canceled)
                 {
                     OnOrderEvent(new OrderEvent(order,


Re-factor AddUserDefinedConversionsOfType and use GetBaseTypesAndThis() instead of loop.

--- src/Features/CSharp/Portable/Completion/CompletionProviders/OperatorsAndIndexer/ConversionCompletionProvider.cs
+++ src/Features/CSharp/Portable/Completion/CompletionProviders/OperatorsAndIndexer/ConversionCompletionProvider.cs
@@ -63,28 +63,23 @@

         private void AddUserDefinedConversionsOfType(ArrayBuilder<CompletionItem> builder, SemanticModel semanticModel, ITypeSymbol container, bool containerIsNullable, int position)
         {
-            var containerOrBaseType = (ITypeSymbol?)container;
-            while (containerOrBaseType is not null)
-            {
-                var allMembers = containerOrBaseType.GetMembers();
-                var allExplicitConversions = from m in allMembers.OfType<IMethodSymbol>()
-                                             where
-                                                 m.IsConversion() && // MethodKind.Conversion
-                                                 m.Name == WellKnownMemberNames.ExplicitConversionName && // op_Explicit
-                                                 m.Parameters.Length == 1 && // Malformed conversion operator may have more or less than one parameter
-                                                 containerOrBaseType.Equals(m.Parameters[0].Type) // Convert from container type to other type
-                                             let typeName = m.ReturnType.ToMinimalDisplayString(semanticModel, position)
-                                             // Lifted conversion https://docs.microsoft.com/hu-hu/dotnet/csharp/language-reference/language-specification/conversions#lifted-conversion-operators
-                                             select CreateSymbolCompletionItem(m, typeName, targetTypeIsNullable: containerIsNullable && m.ReturnType.IsStructType(), position);
-                builder.AddRange(allExplicitConversions);
-
-                // Base types are valid sources for user-defined conversions
-                // https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/conversions#processing-of-user-defined-explicit-conversions
-                // "Find the set of types, D, from which user-defined conversion operators will be considered. This set consists of S0 (if S0 is a class or struct),
-                // the base classes of S0 (if S0 is a class), T0 (if T0 is a class or struct), and the base classes of T0 (if T0 is a class)."
-                // Note: We only look in the source (aka container), because target could be any type (in scope) of the compilation.
-                containerOrBaseType = containerOrBaseType.BaseType;
-            }
+            // Base types are valid sources for user-defined conversions
+            // https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/conversions#processing-of-user-defined-explicit-conversions
+            // "Find the set of types, D, from which user-defined conversion operators will be considered. This set consists of S0 (if S0 is a class or struct),
+            // the base classes of S0 (if S0 is a class), T0 (if T0 is a class or struct), and the base classes of T0 (if T0 is a class)."
+            // Note: We only look in the source (aka container), because target could be any type (in scope) of the compilation.
+            // No need to check for accessibility: "An operator declaration must include both a public and a static modifier." https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/classes#operators
+            var allExplicitConversions = from t in container.GetBaseTypesAndThis()
+                                         from m in t.GetMembers(WellKnownMemberNames.ExplicitConversionName).OfType<IMethodSymbol>()
+                                         where
+                                             m.IsConversion() && // MethodKind.Conversion
+                                             m.Parameters.Length == 1 && // Malformed conversion operator may have more or less than one parameter
+                                             t.Equals(m.Parameters[0].Type) // Convert from container type to other type
+                                         let typeName = m.ReturnType.ToMinimalDisplayString(semanticModel, position)
+                                         // Lifted conversion https://docs.microsoft.com/hu-hu/dotnet/csharp/language-reference/language-specification/conversions#lifted-conversion-operators
+                                         select CreateSymbolCompletionItem(m, typeName, targetTypeIsNullable: containerIsNullable && m.ReturnType.IsStructType(), position);
+            builder.AddRange(allExplicitConversions);
+
         }

         private void AddBuiltInNumericConversions(ArrayBuilder<CompletionItem> builder, SemanticModel semanticModel, INamedTypeSymbol container, bool containerIsNullable, int position)


Check if tool is null.

Check if tool is null.

--- ChalmersxTools/Controllers/ToolController.cs
+++ ChalmersxTools/Controllers/ToolController.cs
@@ -75,7 +75,7 @@
                         session = sessionManager.CreateValidSession(session);
                     }

-                    if (tool != null)
+                    if (tool == null)
                     {
                         tool = _unityContainer.Resolve<ITool>(session.ConsumerKey);
                     }


show ingo from service claim

show ingo from service claim

--- Code/ZipClaim/WebForms/Claims/Editor.aspx.cs
+++ Code/ZipClaim/WebForms/Claims/Editor.aspx.cs
@@ -394,7 +394,7 @@

             //Для установки статуса Назначено сохраняем еще раз если есть
             //if (isNewClaim && claim.IdManager > 0) claim.SetManSelState();
-
+
             string messageText = String.Format("Сохранение заявки №{0} прошло успешно", claim.Id);
             ServerMessageDisplay(new[] { phServerMessage }, messageText);
             return id;


Add Coins.UnspentCount

Add Coins.UnspentCount

--- NBitcoin/BitcoinCore/Coins.cs
+++ NBitcoin/BitcoinCore/Coins.cs
@@ -107,6 +107,14 @@
 					vout.RemoveAt(i);
 				else
 					break;
+			}
+		}
+
+		public int UnspentCount
+		{
+			get
+			{
+				return vout.Where(c => !IsNull(c)).Count();
 			}
 		}


Fix Promise Cascade handling

Fix Promise Cascade handling

--- NiL.JS/BaseLibrary/Promise.cs
+++ NiL.JS/BaseLibrary/Promise.cs
@@ -20,11 +20,12 @@
     public class Promise
     {
         private readonly object _sync = new object();
-        private JSValue _innerResult;
         private Task _innerTask;
         private Function _callback;
         private Task<JSValue> _task;

+        protected JSValue _innerResult;
+
         [Hidden]
         public PromiseState State
         {
@@ -43,11 +44,13 @@
             get { return _task; }
             protected set { _task = value; }
         }
+
         [Hidden]
         public bool Complited
         {
             get { return _task.IsCompleted; }
         }
+
         [Hidden]
         public JSValue Result
         {
@@ -59,6 +62,7 @@
                     (Task.Exception.GetBaseException() as JSException).Error;
             }
         }
+
         [Hidden]
         public Function Callback
         {
@@ -119,6 +123,23 @@
             }
         }

+        protected void handlePromiseCascade(JSValue value)
+        {
+            if (value?.Value is Promise)
+            {
+                var promise = value.Value as Promise;
+                promise.Task.ContinueWith((task) =>
+                {
+                    handlePromiseCascade(task.Result);
+                });
+            }
+            else
+            {
+                _innerResult = value;
+                _task.Start();
+            }
+        }
+
         protected void callbackInvoke()
         {
             var statusSetted = false;
@@ -133,8 +154,8 @@
                         if (!statusSetted)
                         {
                             statusSetted = true;
-                            _innerResult = args[0];
-                            _task.Start();
+
+                            handlePromiseCascade(args[0]);
                         }

                         return null;
@@ -145,8 +166,8 @@
                         {
                             reject = true;
                             statusSetted = true;
-                            _innerResult = args[0];
-                            _task.Start();
+
+                            handlePromiseCascade(args[0]);
                         }

                         return null;
@@ -350,13 +371,11 @@
     [Prototype(typeof(Promise), true)]
     internal class CompletionPromise : Promise
     {
-        private JSValue _arg;
-
         internal CompletionPromise(Function callback)
             : base(null as Task<JSValue>)
         {
             Callback = callback;
-            Task = new Task<JSValue>(() => Callback.Call(new Arguments { _arg }));
+            Task = new Task<JSValue>(() => Callback.Call(new Arguments { _innerResult }));
         }

         internal CompletionPromise(Task<JSValue> task)
@@ -371,10 +390,10 @@

         internal void run(JSValue arg)
         {
-            if (_arg == null)
-            {
-                _arg = arg ?? JSValue.undefined;
-                Task.Start();
+            if (_innerResult == null)
+            {
+                _innerResult = arg ?? JSValue.undefined;
+                handlePromiseCascade(_innerResult);
             }
         }
     }


Close the input stream on the process before waiting for exit

--- Kudu.Core/Infrastructure/Executable.cs
+++ Kudu.Core/Infrastructure/Executable.cs
@@ -20,6 +20,8 @@

             IAsyncResult outputReader = reader.BeginInvoke(process.StandardOutput, null, null);
             IAsyncResult errorReader = reader.BeginInvoke(process.StandardError, null, null);
+
+            process.StandardInput.Close();

             process.WaitForExit();


Stubbed the iOS UnsubscribeWhenNotificationsAreDisabled * This is an Android specific method, so not needed for anything on iOS

--- Com.OneSignal.iOS/OneSignalImplementation.cs
+++ Com.OneSignal.iOS/OneSignalImplementation.cs
@@ -151,6 +151,11 @@
 		{
 			Debug.WriteLine("ClearAndroidOneSignalNotifications() is an android-only function, and is not implemented in iOS.");
 		}
+
+      public override void UnsubscribeWhenNotificationsAreDisabled(bool set)
+      {
+         Debug.WriteLine("UnsubscribeWhenNotificationsAreDisabled() is an android-only function, and is not implemented in iOS.");
+      }

 		public override void IdsAvailable(IdsAvailableCallback idsAvailable)
 		{
@@ -324,6 +329,5 @@
       {
          iOS.OneSignal.Onesignal_Log(iOS.OneSLogLevel.Warn, "OneSignal: PauseInAppMessages - Not yet implemented on iOS");
       }
-
    }
 }


Repaired ssa vars renaming

Repaired ssa vars renaming

--- LYtest/Optimize/SSA/SsaVarsRenaming.cs
+++ LYtest/Optimize/SSA/SsaVarsRenaming.cs
@@ -51,7 +51,7 @@
             foreach (var str in currentNode.Value.Enumerate())
             {
                 //Если встретили фи-функцию, переименовываем ее левую часть
-                if (isPhi(str.LeftOperand as IdentificatorValue) && str.Operation == Operation.Assign)
+                if (Utilities.IsPhiAssignment(str))
                 {
                     IdentificatorValue curVar = str.Destination as IdentificatorValue;
                     GenName(curVar);
@@ -59,7 +59,7 @@
                     str.Destination = new IdentificatorValue(str.Destination.Value + varCounter.ToString());
                 }
                 //Переименовываем use переменные в правой части присваиваний
-                if (!isPhi(str.LeftOperand as IdentificatorValue) && str.Operation != Operation.Phi)
+                if (!Utilities.IsPhiIdentificator(str.LeftOperand as IdentificatorValue) && str.Operation != Operation.Phi)
                 {
                     if (str.RightOperand is IdentificatorValue)
                     {
@@ -90,7 +90,7 @@
                 foreach (var s in child.Value.Enumerate())
                 {
                     //Если встретили фи-функцию, переименовываем ее левую часть
-                    if (isPhi(s.LeftOperand as IdentificatorValue) && s.Operation == Operation.Assign)
+                    if (Utilities.IsPhiAssignment(s))
                     {
                         //Ищем строку соответствующей фи-функции и переименовываем переменную в ее левой части
                         foreach (var line in child.Value.Enumerate()
@@ -138,12 +138,7 @@
             counters[v] = i + 1;
         }

-        private bool isPhi(IdentificatorValue ident)
-        {
-            return ident != null
-                && ident.Value.Count() >= 3
-                && ident.Value.Substring(0, 3) == "phi";
-        }
+

         private HashSet<IdentificatorValue> GetAllVariables(CFGraph inputGraph)
         {
@@ -152,8 +147,17 @@
             {
                 foreach (var line in block.Enumerate())
                 {
-                    if (LinearHelper.AsDefinition(line) != null && !isPhi(line.LeftOperand.Value as IdentificatorValue))
-                        variables.Add(line.Destination as IdentificatorValue);
+                    //if (LinearHelper.AsDefinition(line) != null && !Utilities.IsPhiIdentificator(line.LeftOperand.Value as IdentificatorValue))
+                    //    variables.Add(line.Destination as IdentificatorValue);
+                    if (LinearHelper.AsDefinition(line) != null && !Utilities.IsPhiIdentificator(line.LeftOperand.Value as IdentificatorValue))
+                    {
+                        if (line.LeftOperand is IdentificatorValue)
+                            variables.Add(line.LeftOperand as IdentificatorValue);
+                        if (line.RightOperand is IdentificatorValue)
+                            variables.Add(line.RightOperand as IdentificatorValue);
+                        if (line.Destination is IdentificatorValue)
+                            variables.Add(line.Destination as IdentificatorValue);
+                    }
                 }
             }
             return variables;


Free will not release the valueFactory

Free will not release the valueFactory

Set the value of the needle instead - you can set it to default(T)

--- Core/Theraot/Threading/Needles/LazyNeedle.cs
+++ Core/Theraot/Threading/Needles/LazyNeedle.cs
@@ -10,7 +10,6 @@
     [global::System.Diagnostics.DebuggerNonUserCode]
     public class LazyNeedle<T> : Needle<T>, ICacheNeedle<T>, IEquatable<LazyNeedle<T>>, IPromise<T>
     {
-        // TODO: Free and valueFactory?
         [NonSerialized]
         private Thread _initializerThread;


Avoid accessing beatmaps from BeatSyncedContainer until they are loaded

--- osu.Game/Graphics/Containers/BeatSyncedContainer.cs
+++ osu.Game/Graphics/Containers/BeatSyncedContainer.cs
@@ -35,9 +35,12 @@

         protected override void Update()
         {
+            if (!Beatmap.Value.TrackLoaded || !Beatmap.Value.BeatmapLoaded) return;
+
             var track = Beatmap.Value.Track;
+            var beatmap = Beatmap.Value.Beatmap;

-            if (track == null)
+            if (track == null || beatmap == null)
                 return;

             double currentTrackTime = track.Length > 0 ? track.CurrentTime + EarlyActivationMilliseconds : Clock.CurrentTime;


[packages,DirectXSDK-06.2010] Using latest Bam core classes

--- packages/DirectXSDK-06.2010/bam/Scripts/MetaData.cs
+++ packages/DirectXSDK-06.2010/bam/Scripts/MetaData.cs
@@ -48,7 +48,7 @@
     }

     public class MetaData :
-        Bam.Core.IPackageMetaData,
+        Bam.Core.PackageMetaData,
         IDirectXSDKInstallMeta
     {
         private System.Collections.Generic.Dictionary<string, object> Meta = new System.Collections.Generic.Dictionary<string,object>();
@@ -89,7 +89,7 @@
             }
         }

-        object Bam.Core.IPackageMetaData.this[string index]
+        public override object this[string index]
         {
             get
             {
@@ -97,7 +97,8 @@
             }
         }

-        bool Bam.Core.IPackageMetaData.Contains(
+        public override bool
+        Contains(
             string index)
         {
             return this.Meta.ContainsKey(index);


Use while for getEvent loop.

Use while for getEvent loop.

--- Locana/CameraControl/StatusObserver.cs
+++ Locana/CameraControl/StatusObserver.cs
@@ -59,7 +59,7 @@
             cancel = new CancellationTokenSource();

             IsProcessing = true;
-            PollingLoop();
+            StartPollingLoop();
             return true;
         }

@@ -205,38 +205,37 @@
             }
         }

-        private async void PollingLoop()
-        {
-            if (!IsProcessing)
-            {
-                return;
-            }
-
-            try
-            {
-                OnSuccess(await api.Camera.GetEventAsync(true, version, cancel).ConfigureAwait(false));
-            }
-            catch (RemoteApiException e)
-            {
-                OnError(e.code);
-            }
-        }
-
-        private async void OnSuccess(Event @event)
-        {
-            failure_count = 0;
-            await UpdateStatus(@event).ConfigureAwait(false);
-            PollingLoop();
+        private async void StartPollingLoop()
+        {
+            while (IsProcessing)
+            {
+                try
+                {
+                    var @event = await api.Camera.GetEventAsync(true, version, cancel).ConfigureAwait(false);
+                    await UpdateStatus(@event).ConfigureAwait(false);
+                    failure_count = 0;
+                }
+                catch (RemoteApiException e)
+                {
+                    if (e.code != StatusCode.Timeout)
+                    {
+                        OnError(e.code);
+                        break;
+                    }
+                }
+            }
         }

         private async void OnError(StatusCode code)
         {
             switch (code)
             {
+                /*
                 case StatusCode.Timeout:
                     DebugUtil.Log("GetEvent timeout without any event. Retry for the next event");
                     PollingLoop();
                     return;
+                */
                 case StatusCode.NotAcceptable:
                 case StatusCode.CameraNotReady:
                 case StatusCode.IllegalState:
@@ -246,7 +245,7 @@
                     {
                         DebugUtil.Log("GetEvent failed - retry " + failure_count + ", status: " + code);
                         await Task.Delay(TimeSpan.FromSeconds(RETRY_INTERVAL_SEC)).ConfigureAwait(false);
-                        PollingLoop();
+                        StartPollingLoop();
                         return;
                     }
                     break;


Added an explanation comment for the PreserveTextCase property

--- MahApps.Metro/Controls/ButtonHelper.cs
+++ MahApps.Metro/Controls/ButtonHelper.cs
@@ -9,6 +9,10 @@
                 DependencyProperty.RegisterAttached("PreserveTextCase", typeof(bool), typeof(ButtonHelper), new FrameworkPropertyMetadata(false,
                     FrameworkPropertyMetadataOptions.Inherits | FrameworkPropertyMetadataOptions.AffectsMeasure));

+        /// <summary>
+        /// Overrides the text case behavior for certain buttons.
+        /// When set to <c>true</c>, the text case will be preserved and won't be changed to upper or lower case.
+        /// </summary>
         [AttachedPropertyBrowsableForType(typeof(Button))]
         public static bool GetPreserveTextCase(UIElement element)
         {


Cleanup and async test

Cleanup and async test

--- D2L.Security.OAuth2/Provisioning/D2L.Security.AuthTokenProvisioning.Tests/Unit/Default/AuthTokenProviderTests.cs
+++ D2L.Security.OAuth2/Provisioning/D2L.Security.AuthTokenProvisioning.Tests/Unit/Default/AuthTokenProviderTests.cs
@@ -1,12 +1,8 @@
-using System;
-using System.Collections.Generic;
-using System.IdentityModel.Selectors;
+using System.IdentityModel.Selectors;
 using System.IdentityModel.Tokens;
-using System.Linq;
 using System.Security.Claims;
 using System.Security.Cryptography;
 using System.ServiceModel.Security;
-using System.Text;
 using System.Threading.Tasks;
 using D2L.Security.AuthTokenProvisioning.Default;
 using D2L.Security.AuthTokenProvisioning.Invocation;
@@ -28,20 +24,16 @@
 			new string[] { "https://api.brightspace.com/auth/lores.manage" },
 			"some_tenant_id",
 			"some_tenant_url"
-			);
+			) {
+			UserId = "some_user_id"
+		};

 		[Test]
-		public void b() {
+		public void ProvisionAccessToken_AssertionTokenIsSigned() {
 			byte[] privateKey;
 			byte[] publicKey;
-
 			MakeKeyPair( out privateKey, out publicKey );

-			string signedToken = CreateAndSignToken( privateKey );
-			JwtSecurityToken signatureCheckedToken = CheckSignatureAndGetToken( signedToken, publicKey );
-		}
-
-		private static string CreateAndSignToken( byte[] signingKey ) {
 			InvocationParameters actualInvocationParams = null;
 			Mock<IAuthServiceInvoker> invokerMock = new Mock<IAuthServiceInvoker>();
 			invokerMock
@@ -49,36 +41,83 @@
 				.Callback<InvocationParameters>( x => actualInvocationParams = x )
 				.Returns( ASSERTION_GRANT_RESPONSE );

-			using( RSACryptoServiceProvider rsaService = new RSACryptoServiceProvider( 2048 ) ) {
-				rsaService.PersistKeyInCsp = false;
+			SignToken( invokerMock.Object, privateKey );
+			string signedToken = actualInvocationParams.Assertion;
+
+			JwtSecurityToken signatureCheckedToken = CheckSignatureAndGetToken( signedToken, publicKey );
+			Assert.AreEqual( PROVISIONING_PARAMS.UserId, signatureCheckedToken.Subject );
+		}
+
+		[Test]
+		public async void ProvisionAccessTokenAsync_AssertionTokenIsSigned() {
+			byte[] privateKey;
+			byte[] publicKey;
+			MakeKeyPair( out privateKey, out publicKey );
+
+			InvocationParameters actualInvocationParams = null;
+			Mock<IAuthServiceInvoker> invokerMock = new Mock<IAuthServiceInvoker>();
+			invokerMock
+				.Setup( x => x.ProvisionAccessTokenAsync( It.IsAny<InvocationParameters>() ) )
+				.Callback<InvocationParameters>( x => actualInvocationParams = x )
+				.Returns( () => Task.FromResult<string>( ASSERTION_GRANT_RESPONSE ) );
+
+			await SignTokenAsync( invokerMock.Object, privateKey );
+			string signedToken = actualInvocationParams.Assertion;
+
+			JwtSecurityToken signatureCheckedToken = CheckSignatureAndGetToken( signedToken, publicKey );
+			Assert.AreEqual( PROVISIONING_PARAMS.UserId, signatureCheckedToken.Subject );
+		}
+
+		private static void SignToken( IAuthServiceInvoker serviceInvoker, byte[] signingKey ) {
+
+			using( RSACryptoServiceProvider rsaService = MakeCryptoServiceProvider() ) {
 				rsaService.ImportCspBlob( signingKey );

 				RsaSecurityKey rsaSecurityKey = new RsaSecurityKey( rsaService );
-				SigningCredentials signingCredentials =
-					new SigningCredentials( rsaSecurityKey, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest );
+				SigningCredentials signingCredentials =	new SigningCredentials(
+					rsaSecurityKey,
+					SecurityAlgorithms.RsaSha256Signature,
+					SecurityAlgorithms.Sha256Digest
+					);

 				IAuthTokenProvider provider = new AuthTokenProvider(
 					signingCredentials,
-					invokerMock.Object
+					serviceInvoker
 					);

+				provider.ProvisionAccessToken( PROVISIONING_PARAMS );
+			}
+		}

-				provider.ProvisionAccessToken( PROVISIONING_PARAMS );
+		private async static Task SignTokenAsync( IAuthServiceInvoker serviceInvoker, byte[] signingKey ) {

-				return actualInvocationParams.Assertion;
+			using( RSACryptoServiceProvider rsaService = MakeCryptoServiceProvider() ) {
+				rsaService.ImportCspBlob( signingKey );
+
+				RsaSecurityKey rsaSecurityKey = new RsaSecurityKey( rsaService );
+				SigningCredentials signingCredentials = new SigningCredentials(
+					rsaSecurityKey,
+					SecurityAlgorithms.RsaSha256Signature,
+					SecurityAlgorithms.Sha256Digest
+					);
+
+				IAuthTokenProvider provider = new AuthTokenProvider(
+					signingCredentials,
+					serviceInvoker
+					);
+
+				await provider.ProvisionAccessTokenAsync( PROVISIONING_PARAMS );
 			}
 		}

 		private static JwtSecurityToken CheckSignatureAndGetToken( string signedToken, byte[] publicKey ) {
-			using( RSACryptoServiceProvider rsaService = new RSACryptoServiceProvider( 2048 ) ) {
-				rsaService.PersistKeyInCsp = false;
+			using( RSACryptoServiceProvider rsaService = MakeCryptoServiceProvider() ) {
 				rsaService.ImportCspBlob( publicKey );

 				RsaSecurityToken rsaScurityToken = new RsaSecurityToken( rsaService );
 				SecurityKey securityKey = rsaScurityToken.SecurityKeys[0];

 				TokenValidationParameters validationParameters = CreateTokenValidationParameters( securityKey );
-
 				ISecurityTokenValidator tokenHandler = CreateTokenHandler();

 				SecurityToken securityToken;
@@ -89,12 +128,16 @@
 		}

 		private static void MakeKeyPair( out byte[] privateKey, out byte[] publicKey ) {
-			using( RSACryptoServiceProvider rsaService = new RSACryptoServiceProvider( 2048 ) ) {
-				rsaService.PersistKeyInCsp = false;
-
+			using( RSACryptoServiceProvider rsaService = MakeCryptoServiceProvider() ) {
 				privateKey = rsaService.ExportCspBlob( true );
 				publicKey = rsaService.ExportCspBlob( false );
 			}
+		}
+
+		private static RSACryptoServiceProvider MakeCryptoServiceProvider() {
+			RSACryptoServiceProvider rsaService = new RSACryptoServiceProvider( 2048 );
+			rsaService.PersistKeyInCsp = false;
+			return rsaService;
 		}

 		private static ISecurityTokenValidator CreateTokenHandler() {


small refactor to remove some duplicated code


#312 continue caching

#312 continue caching


add linear acceleration to Android

add linear acceleration to Android


update stats

update stats

--- src/Sir.HttpServer/Views/_Layout.cshtml
+++ src/Sir.HttpServer/Views/_Layout.cshtml
@@ -42,7 +42,7 @@
         @RenderBody()

-
Hosted on: 1 CPU, 1 GB RAM, 2 GB HDD

+
Hosted on: 12 cores, 32 GB RAM, 1 TB storage

Source code on GitHub


remove accidental typo

remove accidental typo

--- Assets/MixedRealityToolkit/Utilities/Gltf/Serialization/ConstructGltf.cs
+++ Assets/MixedRealityToolkit/Utilities/Gltf/Serialization/ConstructGltf.cs
@@ -1,4 +1,4 @@
-update // Copyright (c) Microsoft Corporation. All rights reserved.
+// Copyright (c) Microsoft Corporation. All rights reserved.
 // Licensed under the MIT License. See LICENSE in the project root for license information.

 using Microsoft.MixedReality.Toolkit.Core.Utilities.Async;


EAOutputLogger formatting code

EAOutputLogger formatting code

--- EAAddinFramework/Utilities/EAOutputLogger.cs
+++ EAAddinFramework/Utilities/EAOutputLogger.cs
@@ -38,7 +38,7 @@
 			this.model.wrappedModel.EnsureOutputVisible(this.name);
 			this.model.wrappedModel.ClearOutput(this.name);
 		}
-		private void logToOutput(string message, int elementID = 0)
+        private void logToOutput(string message, int elementID = 0)
 		{
 			this.model.wrappedModel.EnsureOutputVisible(this.name);
 			this.model.wrappedModel.WriteOutput(this.name,message,elementID);


remove unused DataGridViewTextBoxColumn

remove unused DataGridViewTextBoxColumn

--- src/ViewInjectionDemo/Form1.Designer.cs
+++ src/ViewInjectionDemo/Form1.Designer.cs
@@ -162,7 +162,6 @@
         private System.Windows.Forms.DataGridView customerDataGridView;
         private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn1;
         private System.Windows.Forms.DataGridView dataGridView1;
-        private System.Windows.Forms.DataGridViewTextBoxColumn detailsDataGridViewTextBoxColumn;
         private System.Windows.Forms.DataGridViewTextBoxColumn iDDataGridViewTextBoxColumn;
         private System.Windows.Forms.BindingSource ordersBindingSource;
         private System.Windows.Forms.Button button1;


added And

added And

--- Dragon/Source/BooleanExpr.cs
+++ Dragon/Source/BooleanExpr.cs
@@ -86,4 +86,21 @@
                 this.EmitLabel(label);
         }
     }
+
+
+    public class And : Logical
+    {
+        public And(Token tok, Expr lhs, Expr rhs)
+            : base(tok, lhs, rhs)
+        { }
+
+        public override void Jumping(int t, int f)
+        {
+            int label = f != 0 ? f : this.NewLable();
+            this.LhsExpr.Jumping(0, label);
+            this.RhsExpr.Jumping(t, f);
+            if (f == 0)
+                this.EmitLabel(label);
+        }
+    }
 }


Fixed build error

Fixed build error

--- EPPlus/FormulaParsing/CalculateExtentions.cs
+++ EPPlus/FormulaParsing/CalculateExtentions.cs
@@ -48,7 +48,7 @@
             Init(workbook);

             var dc = DependencyChainFactory.Create(workbook, options);
-            worksheet.Workbook._formulaParser = null;
+            workbook._formulaParser = null;
             var parser = workbook.FormulaParser;

             //TODO: Remove when tests are done. Outputs the dc to a text file.


Add reflection recursion depth.

Add reflection recursion depth.

--- LINQPadUtils/LINQPadUtils/LinqPadExtensions.cs
+++ LINQPadUtils/LINQPadUtils/LinqPadExtensions.cs
@@ -10,28 +10,44 @@
     {
         const string IndentString = "  ";

-        #region Public Methods and Operators
-
-        public static IEnumerable<object> DumpReflect<T>(this T obj)
+        public static object DumpReflect<T>(this T obj)
         {
-            return DumpReflect(obj, null, false);
+            return Reflect(obj).Dump();
         }

-        public static IEnumerable<object> DumpReflect<T>(this T obj, string description)
+        public static object DumpReflect<T>(this T obj, bool toDataGrid)
         {
-            return DumpReflect(obj, description, false);
+            return Reflect(obj).Dump(toDataGrid);
         }

-        public static IEnumerable<object> DumpReflect<T>(this T obj, string description, bool toDataGrid)
+        public static object DumpReflect<T>(this T obj, int depth)
         {
-            var result = ReflectOnType(obj);
-
-            return result.Dump(description, toDataGrid);
+            return Reflect(obj, depth).Dump(depth+2);
         }

-        static IEnumerable<object> ReflectOnType(object obj)
+        public static object DumpReflect<T>(this T obj, string description)
         {
-            PropertyInfo[] properties = obj.GetType().GetProperties();
+            return Reflect(obj).Dump(description);
+        }
+
+        public static object DumpReflect<T>(this T obj, string description, bool toDataGrid)
+        {
+            return Reflect(obj).Dump();
+        }
+
+        public static object DumpReflect<T>(this T obj, string description, int depth)
+        {
+            return Reflect(obj, depth).Dump(description, depth+2);
+        }
+
+        public static IEnumerable<object> Reflect<T>(this T obj, int depth = 0)
+        {
+            return ReflectOnType(obj, depth, 0);
+        }
+
+        static IEnumerable<object> ReflectOnType(object obj, int depth, int currentDepth)
+        {
+            PropertyInfo[] properties = obj.GetType().GetProperties((BindingFlags)~0);

             return
                  new[]
@@ -45,15 +61,19 @@
                      .Union(
                          from p in properties
                          let isIndexed = p.GetIndexParameters().Length > 0
-                         where !isIndexed
+                         let getSupported = p.GetMethod != null
+                         where !isIndexed && getSupported
                          select new
                          {
                              p.Name,
-                             Value = p.GetValue(obj, null)
+                             Value =
+                                getSupported
+                                    ? InvokeMethod(() => p.GetValue(obj, null), depth, currentDepth)
+                                    : "<i>Get accessor not implemented.</i>"
                          }
                      )
                      .Union(
-                         from m in obj.GetType().GetMethods(~BindingFlags.NonPublic)
+                         from m in obj.GetType().GetMethods((BindingFlags)~0)
                          let isCallableMethod = m.GetParameters().Length == 0
                          let getterName = m.Name.StartsWith("get_")
                              ? m.Name.Substring(4)
@@ -61,13 +81,19 @@
                          let setterName = m.Name.StartsWith("set_")
                              ? m.Name.Substring(4)
                              : String.Empty
+
                          where isCallableMethod && !properties.Any(p => p.Name == getterName || p.Name == setterName)
+
+                         let result = InvokeMethod(() => m.Invoke(obj, null), depth, currentDepth)
+
                          select new
                          {
                              Name = m.Name + "()",
-                             Value = m.Invoke(obj, null)
+                             Value = result
                          }
-                     );
+                     )
+                     .OrderBy(a => a.Name)
+                     .ToList();
         }

         public static string DumpJson<T>(this T obj)
@@ -82,10 +108,8 @@

         public static string DumpJson<T>(this T obj, string description, bool toDataGrid)
         {
-            var result = ReflectOnType(obj);
-
             var json =
-                new JavaScriptSerializer().Serialize(result);
+                new JavaScriptSerializer().Serialize(obj);

             return FormatJson(json).Dump(description, toDataGrid);
         }
@@ -105,12 +129,38 @@
                 // When quotes are closed and there's a space, ignore it unless we are between quotes.
                 where (quotes % 2 == 0 && !Char.IsSeparator(ch)) || quotes % 2 == 1

-                select lineBreak ??
+                select lineBreak ??
                     (openChar != null && openChar.Length > 1 ? openChar : closeChar);

             return String.Concat(result);
         }

-        #endregion
+        static object InvokeMethod(Func<object> f, int depth, int currentDepth)
+        {
+            try
+            {
+                var result = f();
+
+                if (result == null)
+                {
+                    return null;
+                }
+
+                if (result.GetType().IsPrimitive || currentDepth >= depth)
+                {
+                    return result.ToString();
+                }
+
+                return ReflectOnType(result, depth, ++currentDepth);
+            }
+            catch (TargetInvocationException tex)
+            {
+                return tex.InnerException ?? tex;
+            }
+            catch (Exception ex)
+            {
+                return ex;
+            }
+        }
     }
 }


Add vulcan specific initialization.

Add vulcan specific initialization.

--- AutoRest/Generators/CSharp/CSharp/Templates/ServiceClientTemplate.cshtml
+++ AutoRest/Generators/CSharp/CSharp/Templates/ServiceClientTemplate.cshtml
@@ -1,243 +1,270 @@
-@using System
-@using Microsoft.Rest.Generator.CSharp
-@using Microsoft.Rest.Generator.CSharp.Templates
-@using Microsoft.Rest.Generator.Utilities
-@using System.Linq
-@inherits Microsoft.Rest.Generator.Template<Microsoft.Rest.Generator.CSharp.ServiceClientTemplateModel>
-@Header("// ")
-@EmptyLine
-namespace @Settings.Namespace
-{
-    using System;
-    using System.Linq;
-    using System.Collections.Generic;
-    using System.Net;
-    using System.Net.Http;
-    using System.Net.Http.Headers;
-    using System.Text;
-    using System.Text.RegularExpressions;
-    using System.Threading;
-    using System.Threading.Tasks;
-    using Microsoft.Rest;
-    using Microsoft.Rest.Serialization;
-    using Newtonsoft.Json;
-@foreach (var usingString in Model.Usings) {
-@:    using @usingString;
-}
-@EmptyLine
-    /// <summary>
-    @WrapComment("/// ", Model.Documentation.EscapeXmlComment())
-    /// </summary>
-    public partial class @Model.Name : ServiceClient<@Model.Name>, I@(Model.Name)
-    {
-        /// <summary>
-        /// The base URI of the service.
-        /// </summary>
-        public Uri BaseUri { get; set; }
-        @EmptyLine
-
-        /// <summary>
-        /// Gets or sets json serialization settings.
-        /// </summary>
-        public JsonSerializerSettings SerializationSettings { get; private set; }
-        @EmptyLine
-
-        /// <summary>
-        /// Gets or sets json deserialization settings.
-        /// </summary>
-        public JsonSerializerSettings DeserializationSettings { get; private set; }
-        @EmptyLine
-
-        @foreach (var property in Model.Properties)
-        {
-        @:/// <summary>
-        @:@WrapComment("/// ", property.Documentation.EscapeXmlComment())
-        @:/// </summary>
-        @:public @property.Type @property.Name { get; @(property.IsReadOnly ? "private " : "")set; }
-        @EmptyLine
-        }
-
-        @foreach (var operation in Model.Operations)
-        {
-        @:public virtual I@(operation.MethodGroupType) @(operation.MethodGroupName) { get; private set; }
-        @EmptyLine
-        }
-
-        /// <summary>
-        /// Initializes a new instance of the @Model.Name class.
-        /// </summary>
-        public @(Model.Name)() : base()
-        {
-            this.Initialize();
-        }
-        @EmptyLine
-        /// <summary>
-        /// Initializes a new instance of the @Model.Name class.
-        /// </summary>
-        /// <param name='handlers'>
-        /// Optional. The delegating handlers to add to the http client pipeline.
-        /// </param>
-        public @(Model.Name)(params DelegatingHandler[] handlers) : base(handlers)
-        {
-            this.Initialize();
-        }
-        @EmptyLine
-
-        /// <summary>
-        /// Initializes a new instance of the @Model.Name class.
-        /// </summary>
-        /// <param name='rootHandler'>
-        /// Optional. The http client handler used to handle http transport.
-        /// </param>
-        /// <param name='handlers'>
-        /// Optional. The delegating handlers to add to the http client pipeline.
-        /// </param>
-        public @(Model.Name)(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
-        {
-            this.Initialize();
-        }
-        @EmptyLine
-
-        /// <summary>
-        /// Initializes a new instance of the @Model.Name class.
-        /// </summary>
-        /// <param name='baseUri'>
-        /// Optional. The base URI of the service.
-        /// </param>
-        /// <param name='handlers'>
-        /// Optional. The delegating handlers to add to the http client pipeline.
-        /// </param>
-        public @(Model.Name)(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
-        {
-            if (baseUri == null)
-            {
-                throw new ArgumentNullException("baseUri");
-            }
-            this.Initialize();
-            this.BaseUri = baseUri;
-        }
-        @EmptyLine
-
-        @{var parameters = Model.Properties.Where(p => p.IsRequired && p.IsReadOnly);}
-        @if (parameters.Any())
-        {
-        @:/// <summary>
-        @:/// Initializes a new instance of the @Model.Name class.
-        @:/// </summary>
-        foreach (var param in parameters)
-        {
-        @:/// <param name='@(param.Name.ToCamelCase())'>
-        @:/// Required. @(param.Documentation)
-        @:/// </param>
-        }
-        @:/// <param name='handlers'>
-        @:/// Optional. The delegating handlers to add to the http client pipeline.
-        @:/// </param>
-        @:public @(Model.Name)(@(Model.RequiredConstructorParameters), params DelegatingHandler[] handlers) : this(handlers)
-        @:{
-        foreach (var param in parameters)
-        {
-        @:    if (@(param.Name.ToCamelCase()) == null)
-        @:    {
-        @:        throw new ArgumentNullException("@(param.Name.ToCamelCase())");
-        @:    }
-        }
-        foreach (var param in parameters)
-        {
-        @:    this.@(param.Name) = @(param.Name.ToCamelCase());
-        }
-        @:    this.Initialize();
-        @:}
-        @:@EmptyLine
-
-        @:/// <summary>
-        @:/// Initializes a new instance of the @Model.Name class.
-        @:/// </summary>
-        @:/// <param name='baseUri'>
-        @:/// Optional. The base URI of the service.
-        @:/// </param>
-        foreach (var param in parameters)
-        {
-        @:/// <param name='@(param.Name.ToCamelCase())'>
-        @:/// Required. @(param.Documentation)
-        @:/// </param>
-        }
-        @:/// <param name='handlers'>
-        @:/// Optional. The delegating handlers to add to the http client pipeline.
-        @:/// </param>
-        @:public @(Model.Name)(Uri baseUri, @(Model.RequiredConstructorParameters), params DelegatingHandler[] handlers) : this(handlers)
-        @:{
-        @:    if (baseUri == null)
-        @:    {
-        @:        throw new ArgumentNullException("baseUri");
-        @:    }
-        foreach (var param in parameters)
-        {
-        @:    if (@(param.Name.ToCamelCase()) == null)
-        @:    {
-        @:        throw new ArgumentNullException("@(param.Name.ToCamelCase())");
-        @:    }
-        }
-        @:    this.BaseUri = baseUri;
-        foreach (var param in parameters)
-        {
-        @:    this.@(param.Name) = @(param.Name.ToCamelCase());
-        }
-        @:}
-        @:@EmptyLine
-        }
-
-        /// <summary>
-        /// Initializes client properties.
-        /// </summary>
-        private void Initialize()
-        {
-        @foreach (var operation in Model.Operations)
-        {
-            @:this.@(operation.MethodGroupName) = new @(operation.MethodGroupType)(this);
-        }
-            this.BaseUri = new Uri("@Model.BaseUrl");
-        @foreach (var property in Model.Properties.Where(p => p.DefaultValue != null))
-        {
-            @:this.@(property.Name) = @(property.DefaultValue);
-        }
-
-        @if (Model.Properties.Any(p => "Credentials".Equals(p.Name, StringComparison.OrdinalIgnoreCase) &&
-            "ServiceClientCredentials".Equals(p.Type.Name, StringComparison.OrdinalIgnoreCase)))
-        {
-            @:if (this.Credentials != null)
-            @:{
-            @:    this.Credentials.InitializeServiceClient(this);
-            @:}
-        }
-            SerializationSettings = new JsonSerializerSettings
-            {
-                Formatting = Formatting.Indented,
-                DateFormatHandling = DateFormatHandling.IsoDateFormat,
-                DateTimeZoneHandling = DateTimeZoneHandling.Utc,
-                NullValueHandling = NullValueHandling.Ignore,
-                ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
-                ContractResolver = new ReadOnlyJsonContractResolver()
-            };
-            DeserializationSettings = new JsonSerializerSettings{
-                DateFormatHandling = DateFormatHandling.IsoDateFormat,
-                DateTimeZoneHandling = DateTimeZoneHandling.Utc,
-                NullValueHandling = NullValueHandling.Ignore,
-                ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
-                ContractResolver = new ReadOnlyJsonContractResolver()
-            };
-            @foreach (var polymorphicType in Model.ModelTypes.Where(t => t.PolymorphicDiscriminator != null))
-            {
-            @:SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<@(polymorphicType.Name)>("@(polymorphicType.PolymorphicDiscriminator)"));
-            @:DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<@(polymorphicType.Name)>("@(polymorphicType.PolymorphicDiscriminator)"));
-            }
-        }
-
-        @foreach (var method in Model.MethodTemplateModels)
-        {
-        @:@(Include(new MethodTemplate(), method))
-        @EmptyLine
-        @:
-        }
-    }
-}
+@using System
+@using Microsoft.Rest.Generator.CSharp
+@using Microsoft.Rest.Generator.CSharp.Templates
+@using Microsoft.Rest.Generator.Utilities
+@using System.Linq
+@inherits Microsoft.Rest.Generator.Template<Microsoft.Rest.Generator.CSharp.ServiceClientTemplateModel>
+@Header("// ")
+@EmptyLine
+namespace @Settings.Namespace
+{
+    using System;
+    using System.Linq;
+    using System.Collections.Generic;
+    using System.Net;
+    using System.Net.Http;
+    using System.Net.Http.Headers;
+    using System.Text;
+    using System.Text.RegularExpressions;
+    using System.Threading;
+    using System.Threading.Tasks;
+    using Microsoft.Rest;
+    using Microsoft.Rest.Serialization;
+    using Newtonsoft.Json;
+@foreach (var usingString in Model.Usings) {
+@:    using @usingString;
+}
+@EmptyLine
+    /// <summary>
+    @WrapComment("/// ", Model.Documentation.EscapeXmlComment())
+    /// </summary>
+    public partial class @Model.Name : ServiceClient<@Model.Name>, I@(Model.Name)
+    {
+        /// <summary>
+        /// The base URI of the service.
+        /// </summary>
+        public Uri BaseUri { get; set; }
+        @EmptyLine
+
+        /// <summary>
+        /// Gets or sets json serialization settings.
+        /// </summary>
+        public JsonSerializerSettings SerializationSettings { get; private set; }
+        @EmptyLine
+
+        /// <summary>
+        /// Gets or sets json deserialization settings.
+        /// </summary>
+        public JsonSerializerSettings DeserializationSettings { get; private set; }
+        @EmptyLine
+
+        @foreach (var property in Model.Properties)
+        {
+        @:/// <summary>
+        @:@WrapComment("/// ", property.Documentation.EscapeXmlComment())
+        @:/// </summary>
+        @:public @property.Type @property.Name { get; @(property.IsReadOnly ? "private " : "")set; }
+        @EmptyLine
+        }
+
+        @foreach (var operation in Model.Operations)
+        {
+        @:public virtual I@(operation.MethodGroupType) @(operation.MethodGroupName) { get; private set; }
+        @EmptyLine
+        }
+
+        /// <summary>
+        /// Initializes a new instance of the @Model.Name class.
+        /// </summary>
+        public @(Model.Name)() : base()
+        {
+            this.Initialize();
+        }
+        @EmptyLine
+        /// <summary>
+        /// Initializes a new instance of the @Model.Name class.
+        /// </summary>
+        /// <param name='handlers'>
+        /// Optional. The delegating handlers to add to the http client pipeline.
+        /// </param>
+        public @(Model.Name)(params DelegatingHandler[] handlers) : base(handlers)
+        {
+            this.Initialize();
+        }
+        @EmptyLine
+
+        /// <summary>
+        /// Initializes a new instance of the @Model.Name class.
+        /// </summary>
+        /// <param name='rootHandler'>
+        /// Optional. The http client handler used to handle http transport.
+        /// </param>
+        /// <param name='handlers'>
+        /// Optional. The delegating handlers to add to the http client pipeline.
+        /// </param>
+        public @(Model.Name)(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
+        {
+            this.Initialize();
+        }
+        @EmptyLine
+
+        /// <summary>
+        /// Initializes a new instance of the @Model.Name class.
+        /// </summary>
+        /// <param name='baseUri'>
+        /// Optional. The base URI of the service.
+        /// </param>
+        /// <param name='handlers'>
+        /// Optional. The delegating handlers to add to the http client pipeline.
+        /// </param>
+        public @(Model.Name)(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
+        {
+            if (baseUri == null)
+            {
+                throw new ArgumentNullException("baseUri");
+            }
+            this.Initialize();
+            this.BaseUri = baseUri;
+        }
+
+        @EmptyLine
+
+        /// <summary>
+        /// Initializes a new instance of the @Model.Name class.
+        /// </summary>
+        /// <param name='baseUri'>
+        /// Optional. The base URI of the service.
+        /// </param>
+        /// <param name='tokenProvider'>
+        /// Required. The token provider used to generate authentication token for all web api requests.
+        /// </param>
+        public @(Model.Name)(Uri baseUri, Vulcan.Security.ITokenProvider tokenProvider)
+            : this(baseUri, new DelegatingHandler[] {
+                new Vulcan.WebApi.Client.AuthenticatedMessageHandler(tokenProvider),
+                new Vulcan.WebApi.Client.ErrorMessageHandler()
+            })
+        {
+            if (baseUri == null)
+            {
+                throw new ArgumentNullException("baseUri");
+            }
+            this.Initialize();
+            this.BaseUri = baseUri;
+        }
+        @EmptyLine
+
+        @{var parameters = Model.Properties.Where(p => p.IsRequired && p.IsReadOnly);}
+        @if (parameters.Any())
+        {
+        @:/// <summary>
+        @:/// Initializes a new instance of the @Model.Name class.
+        @:/// </summary>
+        foreach (var param in parameters)
+        {
+        @:/// <param name='@(param.Name.ToCamelCase())'>
+        @:/// Required. @(param.Documentation)
+        @:/// </param>
+        }
+        @:/// <param name='handlers'>
+        @:/// Optional. The delegating handlers to add to the http client pipeline.
+        @:/// </param>
+        @:public @(Model.Name)(@(Model.RequiredConstructorParameters), params DelegatingHandler[] handlers) : this(handlers)
+        @:{
+        foreach (var param in parameters)
+        {
+        @:    if (@(param.Name.ToCamelCase()) == null)
+        @:    {
+        @:        throw new ArgumentNullException("@(param.Name.ToCamelCase())");
+        @:    }
+        }
+        foreach (var param in parameters)
+        {
+        @:    this.@(param.Name) = @(param.Name.ToCamelCase());
+        }
+        @:    this.Initialize();
+        @:}
+        @:@EmptyLine
+
+        @:/// <summary>
+        @:/// Initializes a new instance of the @Model.Name class.
+        @:/// </summary>
+        @:/// <param name='baseUri'>
+        @:/// Optional. The base URI of the service.
+        @:/// </param>
+        foreach (var param in parameters)
+        {
+        @:/// <param name='@(param.Name.ToCamelCase())'>
+        @:/// Required. @(param.Documentation)
+        @:/// </param>
+        }
+        @:/// <param name='handlers'>
+        @:/// Optional. The delegating handlers to add to the http client pipeline.
+        @:/// </param>
+        @:public @(Model.Name)(Uri baseUri, @(Model.RequiredConstructorParameters), params DelegatingHandler[] handlers) : this(handlers)
+        @:{
+        @:    if (baseUri == null)
+        @:    {
+        @:        throw new ArgumentNullException("baseUri");
+        @:    }
+        foreach (var param in parameters)
+        {
+        @:    if (@(param.Name.ToCamelCase()) == null)
+        @:    {
+        @:        throw new ArgumentNullException("@(param.Name.ToCamelCase())");
+        @:    }
+        }
+        @:    this.BaseUri = baseUri;
+        foreach (var param in parameters)
+        {
+        @:    this.@(param.Name) = @(param.Name.ToCamelCase());
+        }
+        @:}
+        @:@EmptyLine
+        }
+
+        /// <summary>
+        /// Initializes client properties.
+        /// </summary>
+        private void Initialize()
+        {
+            this.SetRetryPolicy(new Microsoft.Rest.TransientFaultHandling.RetryPolicy(new Microsoft.Rest.TransientFaultHandling.TransientErrorIgnoreStrategy(), 0));
+
+        @foreach (var operation in Model.Operations)
+        {
+            @:this.@(operation.MethodGroupName) = new @(operation.MethodGroupType)(this);
+        }
+            this.BaseUri = new Uri("@Model.BaseUrl");
+        @foreach (var property in Model.Properties.Where(p => p.DefaultValue != null))
+        {
+            @:this.@(property.Name) = @(property.DefaultValue);
+        }
+
+        @if (Model.Properties.Any(p => "Credentials".Equals(p.Name, StringComparison.OrdinalIgnoreCase) &&
+            "ServiceClientCredentials".Equals(p.Type.Name, StringComparison.OrdinalIgnoreCase)))
+        {
+            @:if (this.Credentials != null)
+            @:{
+            @:    this.Credentials.InitializeServiceClient(this);
+            @:}
+        }
+            SerializationSettings = new JsonSerializerSettings
+            {
+                Formatting = Formatting.Indented,
+                DateFormatHandling = DateFormatHandling.IsoDateFormat,
+                DateTimeZoneHandling = DateTimeZoneHandling.Utc,
+                NullValueHandling = NullValueHandling.Ignore,
+                ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
+                ContractResolver = new ReadOnlyJsonContractResolver()
+            };
+            DeserializationSettings = new JsonSerializerSettings{
+                DateFormatHandling = DateFormatHandling.IsoDateFormat,
+                DateTimeZoneHandling = DateTimeZoneHandling.Utc,
+                NullValueHandling = NullValueHandling.Ignore,
+                ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
+                ContractResolver = new ReadOnlyJsonContractResolver()
+            };
+            @foreach (var polymorphicType in Model.ModelTypes.Where(t => t.PolymorphicDiscriminator != null))
+            {
+            @:SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<@(polymorphicType.Name)>("@(polymorphicType.PolymorphicDiscriminator)"));
+            @:DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<@(polymorphicType.Name)>("@(polymorphicType.PolymorphicDiscriminator)"));
+            }
+        }
+
+        @foreach (var method in Model.MethodTemplateModels)
+        {
+        @:@(Include(new MethodTemplate(), method))
+        @EmptyLine
+        @:
+        }
+    }
+}


_Znear on consideration needs to be 1, and so max zoom is 300

--- EDDiscovery/3DMap/FormMap.cs
+++ EDDiscovery/3DMap/FormMap.cs
@@ -26,7 +26,7 @@
         public bool noWindowReposition { get; set; } = false;                       // set externally
         public TravelHistoryControl travelHistoryControl { get; set; } = null;      // set externally

-        const int HELP_VERSION = 2;         // increment this to force help onto the screen of users first time.
+        const int HELP_VERSION = 3;         // increment this to force help onto the screen of users first time.

         public EDDConfig.MapColoursClass MapColours { get; set; } = EDDConfig.Instance.MapColours;

@@ -40,44 +40,40 @@
         private List<IData3DSet> _datasets_bookedmarkedsystems;
         private List<IData3DSet> _datasets_notedsystems;

-        private const double ZoomMax = 500;
+        StarGrids _stargrids;                   // holds stars
+
+        StarNamesList _starnameslist;           // holds named stars
+        Timer _starnametimer = new Timer();
+
+        private AutoCompleteStringCollection _systemNames;
+
+        private ISystem _centerSystem;
+        private ISystem _homeSystem;
+        private ISystem _historySelection;
+        private ISystem _clickedSystem;         // left clicked on a system/bookmark system/noted system
+        private Vector3 _clickedposition;       // left clicked on a position
+
+        private bool _loaded = false;
+        private float _zoom = 1.0f;
+
+        private Vector3 _cameraPos = Vector3.Zero;
+        private Vector3 _cameraDir = Vector3.Zero;
+        private float _cameraFov = (float)(Math.PI / 2.0f);         // Camera, in radians, 180/2 = 90 degrees
+
+        private const double ZoomMax = 300;
         private const double ZoomMin = 0.01;
         private const double ZoomFact = 1.2589254117941672104239541063958;
-        private const double CameraSlewTime = 1.0;
-
-        StarGrids _stargrids;
-
-        //        List<SystemClassStarNames> _starnames = null;    // star list combines data base and travelled h
-        //        Dictionary<string, SystemClassStarNames> _starnamelookup; // and a dictionary to above since its so slow to do a search
-
-        private AutoCompleteStringCollection _systemNames;
-        private ISystem _centerSystem;
-        private ISystem _homeSystem;
-
-        private ISystem _clickedSystem;        // left clicked on a system/bookmark system/noted system
-        private Vector3 _clickedposition;                   // left clicked on a position
-
-        private ISystem _historySelection;
-        private bool _loaded = false;
-
-        private float _zoom = 1.0f;
-
-        private Vector3 _cameraPos = Vector3.Zero;
-        private Vector3 _cameraDir = Vector3.Zero;
-
+
         private Vector3 _cameraActionMovement = Vector3.Zero;
         private Vector3 _cameraActionRotation = Vector3.Zero;
-        private float _cameraFov = (float)(Math.PI / 2.0f);
-        private float _cameraSlewProgress = 1.0f;
+        private const double CameraSlewTime = 1.0;                  // Controls speed of slew
+        private float _cameraSlewProgress = 1.0f;                   // 0 -> 1 slew progress
         private Vector3 _cameraSlewPosition;

         private KeyboardActions _kbdActions = new KeyboardActions();
         private long _oldTickCount = DateTime.Now.Ticks / 10000;
         private int _ticks = 0;
-
-        StarNamesList _starnameslist;
-        Timer _starnametimer = new Timer();
-
+
         private Point _mouseStartRotate;
         private Point _mouseStartTranslateXY;
         private Point _mouseStartTranslateXZ;
@@ -85,8 +81,7 @@
         private Point _mouseHover;
         Timer _mousehovertick = new Timer();
         System.Windows.Forms.ToolTip _mousehovertooltip = null;
-
-
+
         private float _defaultZoom;
         private List<SystemClass> _referenceSystems { get; set; }
         public List<VisitedSystemsClass> _visitedSystems { get; set; }
@@ -497,10 +492,10 @@
             if (w == 0 || h == 0) return;

             if (toolStripButtonPerspective.Checked)
-            {
+            {                                                                   // Fov, perspective, znear, zfar
                 Matrix4 perspective = Matrix4.CreatePerspectiveFieldOfView(_cameraFov, (float)w / h, 1.0f, 1000000.0f);
                 GL.LoadMatrix(ref perspective);
-                _znear = 0.00000000000001f;     // very small positive value.. needed to be low so zoom=500 works.. may need revisiting
+                _znear = 1.0f;
             }
             else
             {


Slight reworking of tool tip text on pop outs to more closely match normal names

--- EDDiscovery/PopOutControl.cs
+++ EDDiscovery/PopOutControl.cs
@@ -104,10 +104,10 @@
             { new PopOutInfo( PopOuts.Route, "Route Finder", "RouteFinder", EDDiscovery.Properties.Resources.route, "Find Routes from star data") },
             { new PopOutInfo( PopOuts.Expedition, "Expedition", "Expedition", EDDiscovery.Properties.Resources.expedition, "Plan an Expedition") },
             { new PopOutInfo( PopOuts.Trilateration, "Trilateration", "Trilateration", EDDiscovery.Properties.Resources.triangulation, "Trilateration of stars with unknown positions") },
-            { new PopOutInfo( PopOuts.Spanel, "Summary Panel", "Spanel", EDDiscovery.Properties.Resources.spanel, "Display the travel system panel" , transparent: false ) },
-            { new PopOutInfo( PopOuts.Trippanel, "Trip Computer", "Trippanel", EDDiscovery.Properties.Resources.trippanel, "Display the trip computer" , transparent: false) },
-            { new PopOutInfo( PopOuts.NotePanel, "Notes", "NotePanel", EDDiscovery.Properties.Resources.notes, "Display current notes on a system" , transparent: false) },
-            { new PopOutInfo( PopOuts.RouteTracker, "Route Tracker", "RouteTracker", EDDiscovery.Properties.Resources.routetracker, "Display the route tracker", transparent: false) },
+            { new PopOutInfo( PopOuts.Spanel, "Summary Panel", "Spanel", EDDiscovery.Properties.Resources.spanel, "Display the summary panel overlay" , transparent: false ) },
+            { new PopOutInfo( PopOuts.Trippanel, "Trip Computer", "Trippanel", EDDiscovery.Properties.Resources.trippanel, "Display the trip computer overlay" , transparent: false) },
+            { new PopOutInfo( PopOuts.NotePanel, "Notes", "NotePanel", EDDiscovery.Properties.Resources.notes, "Display current notes on a system overlay" , transparent: false) },
+            { new PopOutInfo( PopOuts.RouteTracker, "Route Tracker", "RouteTracker", EDDiscovery.Properties.Resources.routetracker, "Display the route tracker overlay", transparent: false) },
             { new PopOutInfo( PopOuts.Grid, "The Grid", "TheGrid", EDDiscovery.Properties.Resources.grid, "Display the grid which allows other panels to be placed on it" , transparent:false) },
         };


[Glue] - New Project launcher now looks in new location for new project creator.

--- FRBDK/Glue/Glue/Projects/NewProjectHelper.cs
+++ FRBDK/Glue/Glue/Projects/NewProjectHelper.cs
@@ -47,11 +47,18 @@
                     break;
                 }
             }
-            const string newProjectCreatorLocation = @"..\..\..\..\NewProjectCreator\NewProjectCreator\bin\x86\Debug\NewProjectCreator.exe";
+            const string newProjectCreatorLocation = @"..\..\..\..\..\..\NewProjectCreator\NewProjectCreator\bin\x86\Debug\NewProjectCreator.exe";
             if (newProjectCreatorFile == null)
             {
                 newProjectCreatorFile = newProjectCreatorLocation;
             }
+
+
+            if (!File.Exists(newProjectCreatorFile))
+            {
+
+            }
+

             if (!File.Exists(newProjectCreatorFile))
             {


Fix tests for CpuEmulator

Fix tests for CpuEmulator

--- Codesignal/csharp/CpuEmulator/CpuEmulator.Emulator.Test/EmulatorTests.cs
+++ Codesignal/csharp/CpuEmulator/CpuEmulator.Emulator.Test/EmulatorTests.cs
@@ -46,12 +46,12 @@
 			{
 				"MOV 32,R00",
 				"MOV 1,R41",
-				"JZ 8",
-				"MOV R41,R42",
-				"ADD R41,R42",
+				"JZ 7",
+				"ADD R41,R41",
 				"DEC R00",
 				"JMP 3",
-				"NOP"
+				"NOP",
+				"MOV R41,R42"
 			});

 			Assert.Equal("0", result.ToString());


Simplify VorbisComment Remove tests

Simplify VorbisComment Remove tests

--- FlacLibSharp.Test.Core/VorbisCommentTests.cs
+++ FlacLibSharp.Test.Core/VorbisCommentTests.cs
@@ -126,32 +126,17 @@
         [TestMethod, TestCategory("VorbisCommentTests")]
         public void RemoveMethodShouldRemoveTag()
         {
-            var artist = "Aaron";
+            var vorbisComment = new VorbisComment();
+            vorbisComment["ARTIST"] = new VorbisCommentValues("Aaron");
+            vorbisComment.Remove("ARTIST");
+            Assert.IsTrue(vorbisComment.Artist.Count == 0, "Tag was not removed.");
+        }

-            string origFile = Path.Combine("Data", "testfile5.flac");
-            string newFile = Path.Combine("Data", "testfile5_temp.flac");
-            FileHelper.GetNewFile(origFile, newFile);
-
-            using (FlacFile file = new FlacFile(Path.Combine("Data", "testfile5_temp.flac")))
-            {
-                var vorbisComment = new VorbisComment();
-
-                vorbisComment["ARTIST"] = new VorbisCommentValues("Aaron");
-
-                file.Metadata.Add(vorbisComment);
-
-                file.Save();
-            }
-
-            using (FlacFile file = new FlacFile(Path.Combine("Data", "testfile5_temp.flac")))
-            {
-                var artistFromFile = file.VorbisComment.Artist;
-                Assert.AreEqual(artist, artistFromFile.Value, "Test data was not correctly written to file, test preparation failed.");
-
-                file.VorbisComment.Remove("ARTIST");
-                artistFromFile = file.VorbisComment.Artist;
-                Assert.IsTrue(artistFromFile.Count == 0, "Tag was not removed.");
-            }
+        [TestMethod, TestCategory("VorbisCommentTests")]
+        public void RemoveMethodShouldNotThrowErrorIfTagNotFound()
+        {
+            var vorbisComment = new VorbisComment();
+            vorbisComment.Remove("BLABLABLA");
         }
     }
 }


QuickAccessToolBar is now redrawn correctly

--- Fluent.Ribbon/Controls/QuickAccessToolBar.cs
+++ Fluent.Ribbon/Controls/QuickAccessToolBar.cs
@@ -546,11 +546,12 @@

         private void InvalidateMeasureOfTitleBar()
         {
-            var parentRibbon = RibbonControl.GetParentRibbon(this);
-
-            parentRibbon?.TitleBar?.InvalidateMeasure();
-
-            parentRibbon?.TitleBar?.UpdateLayout();
+            var titleBar = RibbonControl.GetParentRibbon(this)?.TitleBar
+                ?? UIHelper.GetParent<RibbonTitleBar>(this);
+
+            titleBar?.InvalidateMeasure();
+
+            titleBar?.UpdateLayout();
         }

         // Updates keys for keytip access


set zoneEmphasis to 0 if value!=null and value can not be resolved to int

--- Core/OfficeDevPnP.Core/Utilities/JsonConverters/EmphasisJsonConverter.cs
+++ Core/OfficeDevPnP.Core/Utilities/JsonConverters/EmphasisJsonConverter.cs
@@ -40,7 +40,7 @@
             if (value!=null)
             {
                 int zoneEmphasis = 0;
-                if (int.TryParse(value.ToString(), out zoneEmphasis));
+                int.TryParse(value.ToString(), out zoneEmphasis);
                 writer.WriteValue(zoneEmphasis);
             }
         }


BST to double linked list O(N)

BST to double linked list O(N)

--- ElementsOfProgrammingInterviews/BinaryTrees/bst_to_double_linked_list.cs
+++ ElementsOfProgrammingInterviews/BinaryTrees/bst_to_double_linked_list.cs
@@ -90,13 +90,36 @@
         return root;
     }

+    static Node ToDoubleLinkedBetter(Node root) {
+        Node prev = null;
+        LeftSide(root, ref prev);
+
+        Node right = null;
+        while (prev != null) {
+            Node left = prev.Left;
+            prev.Right = right;
+            right = prev;
+            prev = left;
+        }
+
+        return right;
+    }
+
+    static void LeftSide(Node root, ref Node previous) {
+        if (root == null) {
+            return;
+        }
+
+        LeftSide(root.Left, ref previous);
+        root.Left = previous;
+        previous = root;
+        LeftSide(root.Right, ref previous);
+    }
+
     static void Main() {
         Node root = Fill(1, 10);
         Console.WriteLine(String.Join(",", Inorder(root).Select(x => x.Value)));
-        root = ToDoubleLinked(root);
-        while (root.Left != null) {
-            root = root.Left;
-        }
+        root = ToDoubleLinkedBetter(root);

         Node it = root;
         while (it != null) {


Fix bug where GlobalItem saving hooks are called for empty item slots

--- patches/tModLoader/Terraria.ModLoader/ItemLoader.cs
+++ patches/tModLoader/Terraria.ModLoader/ItemLoader.cs
@@ -1448,6 +1448,10 @@

 		public static int NeedsGlobalCustomSaving(Item item)
 		{
+			if (item.type == 0)
+			{
+				return 0;
+			}
 			int numGlobalData = 0;
 			foreach (var hook in HookNeedsCustomSaving)
 			{


reduces nullable right recursion bug down by several rules

--- tests/Pliant.Tests.Unit/ParseEngineTests.cs
+++ tests/Pliant.Tests.Unit/ParseEngineTests.cs
@@ -610,28 +610,18 @@
         [TestMethod]
         public void ParseEngineShouldCreateSameParseTreeForNullableRightRecursiveRule()
         {
-            ProductionBuilder R = "R", E = "E", T = "T", F = "F", A = "A", C = "C";
+            ProductionBuilder R = "R", E = "E", F = "F";
             R.Definition =
-                E
-                | '^' + E
-                | E + '$'
-                | '^' + E + '$';
+                E;
             E.Definition =
-                T
-                | T + '|' + E
+                F
+                | F + '|' + E
                 | (_)null;
-            T.Definition =
-                F
-                | F + T;
             F.Definition =
-                A;
-            A.Definition =
-                C;
-            C.Definition =
                 new TerminalLexerRule(
                     new SetTerminal('a', 'b'), "[ab]");

-            var grammar = new GrammarBuilder(R, new[] { R, E, T, F, A, C})
+            var grammar = new GrammarBuilder(R, new[] { R, E, F})
                 .ToGrammar();

             var leoEngine = new ParseEngine(grammar, new ParseEngineOptions(optimizeRightRecursion: true));


Fix documentation on SecurityHeadersMiddleware

Fixes #29

--- src/NetEscapades.AspNetCore.SecurityHeaders/SecurityHeadersMiddleware.cs
+++ src/NetEscapades.AspNetCore.SecurityHeaders/SecurityHeadersMiddleware.cs
@@ -14,7 +14,7 @@
         private readonly ICustomHeaderService _service;

         /// <summary>
-        /// Instantiates a new <see cref="CustomHeadersMiddleware"/>.
+        /// Instantiates a new <see cref="SecurityHeadersMiddleware"/>.
         /// </summary>
         /// <param name="next">The next middleware in the pipeline.</param>
         /// <param name="service">An instance of <see cref="ICustomHeaderService"/>.</param>


Update OutputCacheFilter.cs

Update OutputCacheFilter.cs

--- src/Orchard.Web/Modules/Orchard.OutputCache/Filters/OutputCacheFilter.cs
+++ src/Orchard.Web/Modules/Orchard.OutputCache/Filters/OutputCacheFilter.cs
@@ -503,13 +503,13 @@
                     maxAge = TimeSpan.Zero;
                 }
                 response.Cache.SetCacheability(HttpCacheability.Public);
+                response.Cache.SetOmitVaryStar(true);
                 response.Cache.SetMaxAge(maxAge);
             }

             // Keeping this example for later usage.
             // response.DisableUserCache();
             // response.DisableKernelCache();
-            // response.Cache.SetOmitVaryStar(true);

             // An ETag is a string that uniquely identifies a specific version of a component.
             // We use the cache item to detect if it's a new one.
@@ -628,4 +628,4 @@
     public class ViewDataContainer : IViewDataContainer {
         public ViewDataDictionary ViewData { get; set; }
     }
-}+}


Remove unused namespaces.

Remove unused namespaces.

--- MeetU/MeetU/API/DbMonitorController.cs
+++ MeetU/MeetU/API/DbMonitorController.cs
@@ -1,8 +1,4 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Net;
-using System.Net.Http;
+using System.Linq;
 using System.Web.Http;
 using MeetU.Models;


modified:   MeetU/MeetU/Views/Meetups/Index.cshtml

--- MeetU/MeetU/Views/Meetups/Index.cshtml
+++ MeetU/MeetU/Views/Meetups/Index.cshtml
@@ -32,7 +32,7 @@

-                            {{ meetupView.meetup.description }}  |  {{ meetupView.sponsorUserName }} {{ ago(meetupView.meetup.createdAt) }}
+                            {{ meetupView.meetup.description }}  |  {{ meetupView.sponsorUserName }} {{ meetupView.meetup.date | date:'dd-MM-yyyy' }}

                             When
                             {{ meetupView.meetup.when |  date: "HH:mm" }} {{ meetupView.meetup.date | date:'dd-MM-yyyy' }}
@@ -43,7 +43,7 @@

-                                {{ cv.content }}   {{ cv.by }} {{ ago(cv.at) }}
+                                {{ cv.content }}   {{ cv.by }} {{ cv.at | date: 'dd-MM-yyyy' }}


TaskSample - FiveItemsAllHangExceptLastWhichMatchesAsyncReturns

--- projects/TaskSample/TaskSample.Test/FirstAsyncTest.cs
+++ projects/TaskSample/TaskSample.Test/FirstAsyncTest.cs
@@ -177,6 +177,39 @@
             task.Result.Should().Be("good 3");
         }

+        [Fact]
+        public void FiveItemsAllHangExceptLastWhichMatchesAsyncReturns()
+        {
+            List<Task> canceledTasks = new List<Task>();
+            Func<CancellationToken, Task<string>> hang = t =>
+            {
+                var current = new TaskCompletionSource<string>();
+                t.Register(() => current.SetCanceled());
+                Task<string> ct = current.Task;
+                canceledTasks.Add(ct);
+                return ct;
+            };
+            TaskCompletionSource<string> delayed = new TaskCompletionSource<string>();
+            IEnumerable<Func<CancellationToken, Task<string>>> funcs = new Func<CancellationToken, Task<string>>[]
+            {
+                hang,
+                hang,
+                hang,
+                hang,
+                t => delayed.Task
+            };
+
+            Task<string> task = funcs.FirstAsync(r => r.StartsWith("good", StringComparison.Ordinal));
+
+            task.IsCompleted.Should().BeFalse();
+
+            delayed.SetResult("good 1");
+
+            task.IsCompletedSuccessfully.Should().BeTrue();
+            task.Result.Should().Be("good 1");
+            canceledTasks.Should().OnlyContain(t => t.IsCanceled);
+        }
+
         private static void ShouldBeFaulted(Task task)
         {
             task.IsCompleted.Should().BeTrue();


- Fixing bug in linkPagesAvailable logic for GetPagedAsync

--- Mixer.Base/Services/RestServiceBase.cs
+++ Mixer.Base/Services/RestServiceBase.cs
@@ -71,6 +71,10 @@
                 }
                 HttpResponseMessage response = await this.GetAsync(currentRequestUri);

+                T[] pagedResults = await this.ProcessResponse<T[]>(response);
+                results.AddRange(pagedResults);
+                currentPage++;
+
                 if (linkPagesAvailable)
                 {
                     IEnumerable<string> linkValues;
@@ -87,14 +91,10 @@
                         }
                     }
                 }
-                else
+                else if (pagedResults.Count() > 0)
                 {
                     pageTotal++;
                 }
-
-                T[] pagedResults = await this.ProcessResponse<T[]>(response);
-                results.AddRange(pagedResults);
-                currentPage++;
             }

             return results;


Add tests

Add tests

--- src/Roslyn.Diagnostics.Analyzers/UnitTests/BlankLines/BlankLinesTests.cs
+++ src/Roslyn.Diagnostics.Analyzers/UnitTests/BlankLines/BlankLinesTests.cs
@@ -30,8 +30,9 @@
                 FixedCode = code,
             }.RunAsync();
         }
+
         [Fact]
-        public async Task TestMultipleBlankLineAtTopOfFile()
+        public async Task TestTwoBlankLineAtTopOfFile()
         {
             var code =
 @"[||]
@@ -47,5 +48,44 @@
                 FixedCode = fixedCode,
             }.RunAsync();
         }
+
+        [Fact]
+        public async Task TestThreeBlankLineAtTopOfFile()
+        {
+            var code =
+@"[||]
+
+
+// comment";
+            var fixedCode =
+@"
+// comment";
+
+            await new VerifyCS.Test()
+            {
+                TestCode = code,
+                FixedCode = fixedCode,
+            }.RunAsync();
+        }
+
+        [Fact]
+        public async Task TestFourBlankLineAtTopOfFile()
+        {
+            var code =
+@"[||]
+
+
+
+// comment";
+            var fixedCode =
+@"
+// comment";
+
+            await new VerifyCS.Test()
+            {
+                TestCode = code,
+                FixedCode = fixedCode,
+            }.RunAsync();
+        }
     }
 }


updated version to v1.7.4

updated version to v1.7.4

--- ModAnalyzer/Properties/AssemblyInfo.cs
+++ ModAnalyzer/Properties/AssemblyInfo.cs
@@ -51,5 +51,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("1.7.3.0")]
-[assembly: AssemblyFileVersion("1.7.3.0")]
+[assembly: AssemblyVersion("1.7.4.0")]
+[assembly: AssemblyFileVersion("1.7.4.0")]


Music Working + working  buttons

Music Working + working  buttons

--- MonsterClicker/MonsterClicker/Form1.cs
+++ MonsterClicker/MonsterClicker/Form1.cs
@@ -9,7 +9,7 @@
     using Exceptions;
     using Units;
     using Weapons;
-    using WMPLib;
+    using System.Media;

     public partial class Form1 : Form
     {
@@ -25,8 +25,9 @@
         private List<Unit> unitsList = new List<Unit>();
         private BigInteger monsterKills = 1;
         private Boss boss;
-        private WindowsMediaPlayer playerMusic = new WindowsMediaPlayer();
+        private System.Media.SoundPlayer playerMusic = new System.Media.SoundPlayer();
         ////This variable counts monster images and is used to get random image
+

         private int monsterImagesCount = 5;

@@ -58,8 +59,8 @@
             this.ninjasLabel.Hide();
             this.levelUpLabel.Hide();
             this.floatDamageLabel.Hide();
-            //back up music solution(it dosen't work)
-           //this.playerMusic.URL = @".\Resources\street.mp3";
+            playerMusic.SoundLocation = "../../Resources/street.wav";
+            this.playerMusic.Play();
         }
         ////Methods

@@ -419,21 +420,20 @@

         private void PlayNstop_CheckedChanged(object sender, EventArgs e)
         {
-            System.Media.SoundPlayer playerMusic = new System.Media.SoundPlayer();
-            playerMusic.SoundLocation = "../../Resources/street.wav";
-
-            if (playNstop.Checked)
-            {
-                playNstop.Text = "Stop";
-                playerMusic.Play();
-
-
-            }
-            else
-            {
-                playNstop.Text = "Play";
-                playerMusic.Stop();
-
+
+            {
+                if (playNstop.Checked)
+                {
+                    this.playerMusic.Play();
+                    playNstop.Text = "Stop";
+
+                }
+                else
+                {
+                    this.playerMusic.Stop();
+                    playNstop.Text = "Play";
+                }
+
             }
         }
     }


fix test

fix test

--- NBXplorer/DBriizeTransactionContext.cs
+++ NBXplorer/DBriizeTransactionContext.cs
@@ -69,7 +69,7 @@
 						}
 						// The action is setting the result, so no need of TrySetResult here
 					}
-					catch (OperationCanceledException ex) when (_Cancel.IsCancellationRequested)
+					catch (OperationCanceledException) when (_Cancel.IsCancellationRequested)
 					{
 						act.Item2.TrySetCanceled();
 						break;


Return empty array instead of throwing if GetDeviceIDs finds no device

--- NOpenCL/UnsafeNativeMethods.Devices.cs
+++ NOpenCL/UnsafeNativeMethods.Devices.cs
@@ -22,9 +22,11 @@
         public static ClDeviceID[] GetDeviceIDs(ClPlatformID platform, DeviceType deviceType)
         {
             uint required;
-            ErrorHandler.ThrowOnFailure(clGetDeviceIDs(platform, deviceType, 0, null, out required));
-            if (required == 0)
+            ErrorCode result = clGetDeviceIDs(platform, deviceType, 0, null, out required);
+            if (result == ErrorCode.DeviceNotFound && required == 0)
                 return new ClDeviceID[0];
+
+            ErrorHandler.ThrowOnFailure(result);

             ClDeviceID[] devices = new ClDeviceID[required];
             uint actual;


fix: Route issue. Fixes #38

fix: Route issue. Fixes #38

- Update character route as it requires an empty place after the character Id to route to the correct location

--- NeuroLinker/Helpers/MalRouteBuilder.cs
+++ NeuroLinker/Helpers/MalRouteBuilder.cs
@@ -28,11 +28,15 @@
         }

         /// <summary>
-        /// Get url for retrieving an Anime's cast
+        /// Get url for retrieving an Anime`s cast
+        /// /// <remarks>
+        /// The placeholder is required because of the way Mal does routing. Thank to Raven for pointing out that the actual value does not matter
+        /// </remarks>
         /// </summary>
         /// <param name="id">MAL Id</param>
         /// <returns>Anime cast URL</returns>
-        public static string AnimeCastUrl(int id) => $"{Parts.Root}/{Parts.Anime}/{id}/{Parts.Characters}";
+        public static string AnimeCastUrl(int id) =>
+            $"{Parts.Root}/{Parts.Anime}/{id}/{Parts.Placeholder}/{Parts.Characters}";

         /// <summary>
         /// Get url for retrieving a character's page
@@ -178,6 +182,11 @@
             /// </summary>
             public const string People = "people";

+            /// <summary>
+            /// Just a placeholder
+            /// </summary>
+            public const string Placeholder = "x";
+
             #endregion
         }
     }


Added some comments.

Added some comments.

--- CallMeMaybe/Maybe.cs
+++ CallMeMaybe/Maybe.cs
@@ -334,12 +334,27 @@

         #region Equality

+        /// <summary>
+        /// Explicit implementation of the <see cref="IEquatable{T}.Equals(T)"/> method,
+        /// to compare this with other <see cref="Maybe{T}"/>s of the same type.
+        /// </summary>
         bool IEquatable<Maybe<T>>.Equals(Maybe<T> other)
         {
             return Equals(other);
         }

-
+        /// <summary>
+        /// Checks whether another object represents the same <see cref="Maybe{T}"/>
+        /// value as this one.
+        /// <remarks>`.Equals(null)` will always return false, since <see cref="Maybe{T}"/>s
+        /// are not null. It's incorrect to check them against a null value. Use <see cref="HasValue"/>
+        /// instead.</remarks>
+        /// </summary>
+        /// <param name="obj">An object to compare with this.</param>
+        /// <returns>
+        /// True if the other object is a <see cref="Maybe{T}"/>, and has the
+        /// same value (or non-value status) as this one. False otherwise.
+        /// </returns>
         public override bool Equals(object obj)
         {
             // Maybe values never equal `null`--that's sort of the point.
@@ -369,6 +384,10 @@
             return false;
         }

+        /// <summary>
+        /// Implementation of <see cref="Object.GetHashCode"/>
+        /// </summary>
+        /// <returns></returns>
         public override int GetHashCode()
         {
             unchecked
@@ -377,11 +396,25 @@
             }
         }

+        /// <summary>
+        /// Implementation of the equality operator when comparing two <see cref="Maybe{T}"/> objects
+        /// of the same type.
+        /// </summary>
+        /// <returns>
+        /// True if the objects have the same value or non-value status. False otherwise.
+        /// </returns>
         public static bool operator ==(Maybe<T> left, Maybe<T> right)
         {
             return left.Equals(right);
         }

+        /// <summary>
+        /// Implementation of the equality operator when comparing two <see cref="Maybe{T}"/> objects
+        /// of the same type.
+        /// </summary>
+        /// <returns>
+        /// False if the objects have the same value or non-value status. True otherwise.
+        /// </returns>
         public static bool operator !=(Maybe<T> left, Maybe<T> right)
         {
             return !left.Equals(right);


Made GetPartCommands IEnumerable

Made GetPartCommands IEnumerable

--- chapter5/CreateTablesTest/WidgetScmDataAccess/ScmContext.cs
+++ chapter5/CreateTablesTest/WidgetScmDataAccess/ScmContext.cs
@@ -97,12 +97,13 @@
       }
     }

-    public PartCommand[] GetPartCommands()
+    public IEnumerable<PartCommand> GetPartCommands()
     {
       var command = connection.CreateCommand();
       command.CommandText = @"SELECT
           Id, PartTypeId, PartCount, Command
-        FROM PartCommand";
+        FROM PartCommand
+        ORDER BY Id";
       var reader = command.ExecuteReader();
       var partCommands = new List<PartCommand>();
       while (reader.Read())


Sort room connection endpoints list alphabetically for now

--- FormulaEdit/FormulaEdit/MainForm.Designer.cs
+++ FormulaEdit/FormulaEdit/MainForm.Designer.cs
@@ -456,6 +456,7 @@
             this.RoomConnectionEndpointListBox.Location = new System.Drawing.Point(151, 64);
             this.RoomConnectionEndpointListBox.Name = "RoomConnectionEndpointListBox";
             this.RoomConnectionEndpointListBox.Size = new System.Drawing.Size(339, 134);
+            this.RoomConnectionEndpointListBox.Sorted = true;
             this.RoomConnectionEndpointListBox.TabIndex = 4;
             this.RoomConnectionEndpointListBox.SelectedIndexChanged += new System.EventHandler(this.RoomConnectionEndpointListBox_SelectedIndexChanged);
             //


Now only one temp data file is created at a time.

git-tfs-id: [https://tfs.codeplex.com:443/tfs/TFS06]$/51degrees;C75354

--- FoundationV3/Mobile/Detection/WebProvider.cs
+++ FoundationV3/Mobile/Detection/WebProvider.cs
@@ -113,6 +113,12 @@
                     Guid.NewGuid()));
         }

+        private static DateTime GetDataFileDate(FileInfo fileInfo)
+        {
+            var dataset = StreamFactory.Create(fileInfo.FullName);
+            return dataset.Published;
+        }
+
         /// <summary>
         /// Copies the source data file for use with a stream provider.
         /// </summary>
@@ -120,15 +126,39 @@
         private static string GetTempWorkingFile()
         {
             string tempFileName = null;
-            var file = new FileInfo(Manager.BinaryFilePath);
-            if (file.Exists)
-            {
-                // Create a working temp file in the App_Data folder to enable the source
-                // file to be updated without stopping the web site.
+            var masterFile = new FileInfo(Manager.BinaryFilePath);
+            if (masterFile.Exists)
+            {
+                // Get the publish date of the master data file.
+                var masterDate = GetDataFileDate(masterFile);
+
+                // Check if there are any other tmp files.
+                var fileNames = Directory.GetFiles(Mobile.Configuration.Support.GetFilePath("~/App_Data"));
+                foreach (var fileName in fileNames)
+                {
+                    var file = new FileInfo(fileName);
+                    if(file.FullName != masterFile.FullName &&
+                    file.Name.StartsWith(masterFile.Name) &&
+                        file.Extension == "tmp")
+                    {
+                        // Check if temp file matches date of the master file.
+                        try
+                        {
+                            var tempDate = GetDataFileDate(file);
+                            if (tempDate == masterDate)
+                                return fileName;
+                        }
+                        catch { } // Exception may occur if file is not a 51Degrees file, no action is needed.
+                    }
+                }
+
+                // No suitable temp file was found, create one in the
+                //App_Data folder to enable the source file to be updated
+                // without stopping the web site.
                 tempFileName = GetTempFileName();

                 // Copy the file to enable other processes to update it.
-                File.Copy(file.FullName, tempFileName);
+                File.Copy(masterFile.FullName, tempFileName);
             }
             return tempFileName;
         }


[Modify] Edit it

[Modify] Edit it

--- websocket-sharp/Net/WebHeaderCollection.cs
+++ websocket-sharp/Net/WebHeaderCollection.cs
@@ -1467,11 +1467,16 @@
     }

     /// <summary>
-    /// Gets an array of header values stored in the specified <paramref name="header"/>.
+    /// Get the values of the header with the specified name in the collection.
     /// </summary>
     /// <returns>
-    /// An array of <see cref="string"/> that receives the header values if found;
-    /// otherwise, <see langword="null"/>.
+    ///   <para>
+    ///   An array of <see cref="string"/> that receives the values of
+    ///   the header.
+    ///   </para>
+    ///   <para>
+    ///   <see langword="null"/> if not present.
+    ///   </para>
     /// </returns>
     /// <param name="header">
     /// A <see cref="string"/> that represents the name of the header to find.


Added LayoutSymbol overload returning new layout

--- Circuit/Component.cs
+++ Circuit/Component.cs
@@ -80,6 +80,13 @@
         /// </summary>
         /// <param name="S"></param>
         public abstract void LayoutSymbol(SymbolLayout Sym);
+
+        public SymbolLayout LayoutSymbol()
+        {
+            SymbolLayout layout = new SymbolLayout();
+            LayoutSymbol(layout);
+            return layout;
+        }

         public virtual XElement Serialize()
         {