Adjust default SpreadsThreadPool worker count and optionally default TP count

--- src/Spreads.Core/Threading/SpreadsThreadPool.cs
+++ src/Spreads.Core/Threading/SpreadsThreadPool.cs
@@ -489,7 +489,6 @@
         [MethodImpl(MethodImplOptions.AggressiveInlining)]
         public void Enqueue(Action<object> callback, ExecutionContext exCtx, object state, bool forceGlobal)
         {
-
             ThreadPoolWorkQueueThreadLocals tl = null;
             if (!forceGlobal)
             {
@@ -749,18 +748,40 @@
     /// </summary>
     public class SpreadsThreadPool
     {
-        public static readonly SpreadsThreadPool Default = new SpreadsThreadPool(
-            new ThreadPoolSettings(Environment.ProcessorCount, "DefaultSpinningThreadPool"));
+        // it's shared and there is a cmment from MSFT that the number should
+        // be larger than intuition tells. By default ThreadPool has number
+        // of workers equals to processor count.
+        public static readonly int DefaultDedicatedWorkerThreads =
+            1 * 16 + 1 * 8 + Environment.ProcessorCount * 4;
+
+        // Without accessing this namespace and class it is not created
+        private static SpreadsThreadPool _default;
+
+        public static SpreadsThreadPool Default
+        {
+            [MethodImpl(MethodImplOptions.AggressiveInlining)]
+            get
+            {
+                // This is not thread safe and has side effects. Should be accessed on startup.
+                return _default ?? (_default = new SpreadsThreadPool(
+                    new ThreadPoolSettings(DefaultDedicatedWorkerThreads,
+                        "DefaultSpinningThreadPool"), true));
+            }
+        }

         internal readonly ThreadPoolWorkQueue workQueue;
         public ThreadPoolSettings Settings { get; }
         private readonly PoolWorker[] _workers;

-        public SpreadsThreadPool(ThreadPoolSettings settings)
+        public SpreadsThreadPool(ThreadPoolSettings settings, bool adjustDefaultThreadpool = false)
         {
             workQueue = new ThreadPoolWorkQueue(this);
             Settings = settings;
             _workers = Enumerable.Range(1, settings.NumThreads).Select(workerId => new PoolWorker(this, workerId)).ToArray();
+            if (adjustDefaultThreadpool)
+            {
+                ThreadPool.SetMinThreads(settings.NumThreads, settings.NumThreads);
+            }
         }

         [MethodImpl(MethodImplOptions.AggressiveInlining)]
@@ -915,11 +936,11 @@
                 // on MoveNextAsync. On machines with small (v)CPUs count there could be a lot of
                 // activity on IO threads or other threads, but that could wait until we are
                 // performing actual calculations. We use Thread.Sleep(0) in UnfairSemaphore
-                // that yields only to threads with the same priority - this is good for this
+                // that yields only to threads with the same priority - this is good for this
                 // case - threads from this pool will continue to do work until they have it.
-                // Note that we do not stick to the pool threads and could often jump to the
-                // normal ThreadPool or start waiting from it. That's OK because if we have
-                // data available then those threads will just execute calculations. If they
+                // Note that we do not stick to the pool threads and could often jump to the
+                // normal ThreadPool or start waiting from it. That's OK because if we have
+                // data available then those threads will just execute calculations. If they
                 // have to wait then we should wake consumers from higher-priority threads.
                 // Try: thread.Priority = Thread.CurrentThread.Priority + 1;


Add Insert Admin Logic [#136384749]

Add Insert Admin Logic [#136384749]

--- revashare-svc-webapi/revashare-svc-webapi.Logic/AdminLogic.cs
+++ revashare-svc-webapi/revashare-svc-webapi.Logic/AdminLogic.cs
@@ -17,6 +17,14 @@
         #region Admin CRUD Methods
         public bool InsertAdmin(UserDTO adminToAdd)
         {
+            /*var newAdmin = UserMapper.mapToUserDAO(adminToAdd);
+
+            if(dataClient.AddAdmin(newAdmin))
+            {
+                return true;
+            }
+
+            return false;*/
             return true;
         }


Fixed bug where calls into procedures (i.e. not implementations) weren't being printed so instruction statistics would be missing.

--- src/Symbooglix/Executor/CallGrindFilePrinter.cs
+++ src/Symbooglix/Executor/CallGrindFilePrinter.cs
@@ -1,4 +1,5 @@
 using System;
+using System.Collections.Generic;
 using Microsoft.Boogie;
 using System.IO;
 using System.Linq;
@@ -119,10 +120,19 @@

         protected void Print(Implementation impl)
         {
-            TW.WriteLine("# Statistics for {0}", impl.Name);
-            TW.WriteLine("fn={0}", impl.Name);
+            Print(impl.Proc);

-            var proc = impl.Proc;
+            foreach (var bb in impl.Blocks)
+            {
+                Print(bb, impl);
+            }
+        }
+
+        protected void Print(Procedure proc)
+        {
+            TW.WriteLine("# Statistics for {0}", proc.Name);
+            TW.WriteLine("fn={0}", proc.Name);
+
             TW.WriteLine("# Requires statements Start");
             foreach (var requires in proc.Requires)
             {
@@ -135,11 +145,6 @@
                 PrintCostLine(ensures.tok.line, ensures.GetInstructionStatistics());
             }
             TW.WriteLine("# Ensures statements End");
-
-            foreach (var bb in impl.Blocks)
-            {
-                Print(bb, impl);
-            }
         }

         public void Print(TextWriter TW)
@@ -155,9 +160,17 @@
             TW.WriteLine("fl={0}", this.PathToProgram);

             // FIXME: Walk up callgraph instead
+            var printedImplementationsWithProcedures = new HashSet<Procedure>();
             foreach (var impl in TheProgram.TopLevelDeclarations.OfType<Implementation>())
             {
                 Print(impl);
+                printedImplementationsWithProcedures.Add(impl.Proc);
+            }
+
+            // Print Procedures that haven't been printed yet. This can happen when calling into a procedure instead of an implementation
+            foreach (var proc in TheProgram.TopLevelDeclarations.OfType<Procedure>().Where( p => ! printedImplementationsWithProcedures.Contains(p)))
+            {
+                Print(proc);
             }
         }
     }


Fix threshold for PInvoke path in Buffer.Memmove

Threshold for PInvoke path in Buffer.Memmove was way too low. I suspect it was tuned based on the debug builds. I have updated it to be
at the lower end of the break-even point range, based on measurements on several different types of hardware. The best improvements are
on i7-3520M: 64-byte aligned memory blocks - 35% faster, 128 byte aligned memory blocks - 17% faster.

Also:
- Delete misleading comment about PInvoke overhead
- Add comment related to #430

--- src/System.Private.CoreLib/src/System/Buffer.cs
+++ src/System.Private.CoreLib/src/System/Buffer.cs
@@ -261,6 +261,9 @@
             // This is portable version of memcpy. It mirrors what the hand optimized assembly versions of memcpy typically do.
             //

+#if ALIGN_ACCESS
+#error Needs porting for ALIGN_ACCESS (https://github.com/dotnet/corert/issues/430)
+#else // ALIGN_ACCESS
             switch (len)
             {
                 case 0:
@@ -383,9 +386,7 @@
             }

             // P/Invoke into the native version for large lengths.
-            // On desktop, we only PInvoke for lengths >= 512. Since the overhead of a PInvoke is cheaper here,
-            // we are able to PInvoke for smaller copy workloads (length >= 50) and still get a benefit.
-            if (len >= 50)
+            if (len >= 200)
             {
                 _Memmove(dest, src, len);
                 return;
@@ -461,6 +462,7 @@
             }
             if ((len & 1) != 0)
                 *dest = *src;
+#endif // ALIGN_ACCESS
         }

         // Non-inlinable wrapper around the QCall that avoids poluting the fast path


Fix serialization test for Inner hits

Fix serialization test for Inner hits

This commit adds a version property to the expected JSON
structure, to match the fluent and object initializer
calls

--- src/Tests/Search/Request/InnerHitsUsageTests.cs
+++ src/Tests/Search/Request/InnerHitsUsageTests.cs
@@ -284,7 +284,8 @@
 						}
 					}
 				}
-			}
+			},
+			version = true
 		};

 		protected override Func<SearchDescriptor<King>, ISearchRequest> Fluent => s => s


Removing dead logging (#4019)

Removing dead logging (#4019)

--- src/WebJobs.Script/Rpc/LanguageWorkerChannel.cs
+++ src/WebJobs.Script/Rpc/LanguageWorkerChannel.cs
@@ -88,14 +88,6 @@
                 .Where(msg => msg.MessageType == MsgType.RpcLog)
                 .Subscribe(Log));

-            _eventSubscriptions.Add(_eventManager.OfType<RpcEvent>()
-                .Where(msg => msg.WorkerId == _workerId)
-                    .Subscribe(msg =>
-                    {
-                        var jsonMsg = JsonConvert.SerializeObject(msg, LanguageWorkerChannelUtilities.VerboseSerializerSettings);
-                        _userLogsConsoleLogger.LogDebug(jsonMsg);
-                    }));
-
             _eventSubscriptions.Add(_eventManager.OfType<FileEvent>()
                 .Where(msg => Config.Extensions.Contains(Path.GetExtension(msg.FileChangeArguments.FullPath)))
                 .Throttle(TimeSpan.FromMilliseconds(300)) // debounce


Added Rows property to BasePickListControl.

--- src/Xomega.Framework/Web/BasePickListControl.cs
+++ src/Xomega.Framework/Web/BasePickListControl.cs
@@ -253,5 +253,33 @@
         public Button btn_RemoveAll;

         #endregion
+
+        #region Properties
+
+        /// <summary>
+        /// Number of visible rows.
+        /// </summary>
+        public int Rows { get; set; }
+
+        /// <summary>
+        /// Default number of visible rows.
+        /// </summary>
+        public static int DefaultRows = 5;
+
+        #endregion
+
+        #region Events
+
+        /// <summary>
+        /// Control initialization handler.
+        /// </summary>
+        /// <param name="e">EventArgs object.</param>
+        protected override void OnInit(EventArgs e)
+        {
+            base.OnInit(e);
+            lbx_Items.Rows = lbx_Selection.Rows = Rows > 0 ? Rows : DefaultRows;
+        }
+
+        #endregion
     }
 }


Add page up and page down input codes

Add page up and page down input codes

--- tterm/Ui/TerminalControl.cs
+++ tterm/Ui/TerminalControl.cs
@@ -360,6 +360,12 @@
                 case Key.End:
                     text = Construct(1, 'F');
                     break;
+                case Key.PageUp:
+                    text = $"{C0.ESC}[5~";
+                    break;
+                case Key.PageDown:
+                    text = $"{C0.ESC}[6~";
+                    break;
                 case Key.Return:
                     text = C0.CR.ToString();
                     break;


Missed semicolon in last commit

Missed semicolon in last commit

--- Assets/Scripts/Player.cs
+++ Assets/Scripts/Player.cs
@@ -67,7 +67,7 @@
     {
         if(FadeUI==null)
         {
-            Debug.LogError("Fading in and out might be broken. Check your player object to make sure you have a correct reference set!")
+            Debug.LogError("Fading in and out might be broken. Check your player object to make sure you have a correct reference set!");
         }
     }


Adding APIs: 1. PromptForInput (msg, initial input) 2. PromptForInput (msg, input array) 3. PromptForInput_searchable (msg, input array) 4. GetPassword

--- AutoPrompt/AutoPrompt.cs
+++ AutoPrompt/AutoPrompt.cs
@@ -1,15 +1,23 @@
 using System;
 using System.Collections.Generic;
 using System.IO;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;

 namespace rohankapoor.AutoPrompt
 {
     public class AutoPrompt
     {
-        // Used to get path from command prompt
+        #region Public APIs
+
+        /// <summary>
+        /// Used to get path from command prompt. Starts by showing available directories
+        /// Press:
+        ///      Up Arrow to go to next file or directory
+        ///      Down Arrow to go to previous file or directory
+        ///      '\' to navigate into current directory
+        ///      Any key to list matching files and directory. The search criteria is 'begins with'. Eg, When 'W' is pressed in C:\, the prompt will auto fill with 'Windows' as the closest match. The search is case sensitive
+        /// </summary>
+        /// <param name="message">Message that appears on the prompt. For eg, Enter Value:</param>
+        /// <returns>Full path of the file or directory selected</returns>
         public static string GetPath(string message)
         {
             string[] options = Environment.GetLogicalDrives();
@@ -154,6 +162,306 @@
             return userInput;
         }

+        /// <summary>
+        /// Asks the user for input, with a default input value already set
+        /// </summary>
+        /// <param name="message">Message that appears on the prompt. For eg, Enter Value:</param>
+        /// <param name="initialInput">The value prefilled. Eg, "22 Jump Street" prefilled if prompt is to accept address</param>
+        /// <returns>User entered string or 'initialInput' if no edits were made</returns>
+        public static string PromptForInput(string message, string initialInput)
+        {
+            string userInput = initialInput;
+
+            ConsoleKeyInfo KeyInfo;
+
+            Console.Write(message);
+            Console.Write(initialInput);
+
+            do
+            {
+                // Getting a Key from console
+                KeyInfo = Console.ReadKey(true);
+
+                if (Char.IsLetterOrDigit(KeyInfo.KeyChar) || Char.IsSymbol(KeyInfo.KeyChar)
+                    || Char.IsPunctuation(KeyInfo.KeyChar) || Char.IsPunctuation(KeyInfo.KeyChar)
+                    || Char.IsWhiteSpace(KeyInfo.KeyChar))
+                {
+                    // If its a Letter or Digit, echo to screen, add to Input String
+                    Console.Write(KeyInfo.KeyChar);
+
+                    userInput += KeyInfo.KeyChar;
+                }
+                else if (!userInput.Equals(String.Empty) && KeyInfo.Key == ConsoleKey.Backspace)
+                {
+                    //User hit back space
+
+                    // Erasing on Console
+                    Console.Write("\b" + " " + "\b");
+
+                    // Erasing in Input String
+                    if (!String.IsNullOrEmpty(userInput))
+                    {
+                        userInput = userInput.Substring(0, userInput.Length - 1);
+                    }
+                }
+            }
+            while (KeyInfo.Key != ConsoleKey.Enter);
+
+            return userInput.Trim();
+        }
+
+        /// <summary>
+        /// Accepts user input by displaying options. The input is editable as well
+        /// Press:
+        ///     Up Arrow to go to next option
+        ///     Down Arrow to go to previous option
+        /// </summary>
+        /// <param name="message">Message that appears on the prompt. For eg, Enter Value:</param>
+        /// <param name="options">List of values. Eg {Mr, Mrs, Ms} can be passed if prompt if for salutation. User can switch between these values by pressing up/down arrow OR enter something like Dr or Er and hit enter</param>
+        /// <returns>User entered string or one of the string in 'options' choosen by the user</returns>
+        public static string PromptForInput(string message, string[] options)
+        {
+            int OptionCount = options.Length;
+            int CurrentOptionDisplayedIndex = 0;
+            string UserInput = options[0];
+
+            ConsoleKeyInfo KeyInfo;
+
+            Console.Write(message + options[0]);
+
+            do
+            {
+                KeyInfo = Console.ReadKey(true);
+
+                if (Char.IsLetterOrDigit(KeyInfo.KeyChar) || Char.IsSymbol(KeyInfo.KeyChar)
+                    || Char.IsPunctuation(KeyInfo.KeyChar) || Char.IsPunctuation(KeyInfo.KeyChar)
+                    || Char.IsWhiteSpace(KeyInfo.KeyChar))
+                {
+                    Console.Write(KeyInfo.KeyChar);
+
+                    UserInput += KeyInfo.KeyChar;
+                }
+                else if (!UserInput.Equals(String.Empty) && KeyInfo.Key == ConsoleKey.Backspace)
+                {
+                    Console.Write("\b" + " " + "\b");
+
+                    if (!String.IsNullOrEmpty(UserInput))
+                    {
+                        UserInput = UserInput.Substring(0, UserInput.Length - 1);
+                    }
+                }
+                else if (KeyInfo.Key == ConsoleKey.UpArrow || KeyInfo.Key == ConsoleKey.DownArrow)
+                {
+                    // We have to display another option
+
+                    // Erase on screen and in UserInput string
+                    for (int UserInputIndex = 0; UserInputIndex < UserInput.Length; UserInputIndex++)
+                    {
+                        Console.Write("\b" + " " + "\b");
+                    }
+
+                    // Display new option
+                    if (KeyInfo.Key == ConsoleKey.UpArrow)
+                    {
+                        if (CurrentOptionDisplayedIndex > 0)
+                        {
+                            CurrentOptionDisplayedIndex--;
+                        }
+                        else
+                        {
+                            CurrentOptionDisplayedIndex = OptionCount - 1;
+                        }
+                    }
+                    else if (KeyInfo.Key == ConsoleKey.DownArrow)
+                    {
+                        if (CurrentOptionDisplayedIndex < OptionCount - 1)
+                        {
+                            CurrentOptionDisplayedIndex++;
+                        }
+                        else
+                        {
+                            CurrentOptionDisplayedIndex = 0;
+                        }
+                    }
+
+                    // Show the new option
+                    Console.Write(options[CurrentOptionDisplayedIndex]);
+
+                    // Set new user input
+                    UserInput = options[CurrentOptionDisplayedIndex];
+                }
+            }
+            while (KeyInfo.Key != ConsoleKey.Enter);
+
+            return UserInput.Substring(0, UserInput.Length - 1);
+        }
+
+        /// <summary>
+        /// Accepts user input by displaying options. The options are autofilled with matches from key press. This is like auto suggest for a text box
+        /// Press:
+        ///     Up Arrow to go to next option
+        ///     Down Arrow to go to previous option
+        ///     Any key to list closest matching option. The search criteria is 'begins with'. Eg, When 'C' is pressed and options is a list of US states, then 'California' is set to as choosen option. The search is case sensitive
+        /// </summary>
+        /// <param name="message">Message that appears on the prompt. For eg, Enter Value:</param>
+        /// <param name="options">Input options that the user can choose from using up-down arrow or type to get to</param>
+        /// <returns>User entered string or one of the string in 'options' choosen by the user</returns>
+        public static string PromptForInput_Searchable(string message, string[] options)
+        {
+            int OptionCount = options.Length;
+            int CurrentOptionDisplayedIndex = 0;
+            string UserInput = options[0];
+
+            ConsoleKeyInfo KeyInfo;
+
+            Console.Write(message + options[0]);
+
+            do
+            {
+                KeyInfo = Console.ReadKey(true);
+
+                if (Char.IsLetterOrDigit(KeyInfo.KeyChar) || Char.IsSymbol(KeyInfo.KeyChar)
+                    || Char.IsPunctuation(KeyInfo.KeyChar) || Char.IsPunctuation(KeyInfo.KeyChar)
+                    || Char.IsWhiteSpace(KeyInfo.KeyChar))
+                {
+                    Console.Write(KeyInfo.KeyChar);
+
+                    UserInput += KeyInfo.KeyChar;
+
+                    // Performing Closest Search
+                    int FoundIndex = -1;
+                    int OptionIndex = 0;
+                    foreach (string Option in options)
+                    {
+                        if (Option.ToLower().StartsWith(UserInput.ToLower()))
+                        {
+                            FoundIndex = OptionIndex;
+
+                            /* Display that Option */
+                            /* Erasing Old */
+                            for (int UserInputIndex = 0; UserInputIndex < UserInput.Length; UserInputIndex++)
+                            {
+                                Console.Write("\b" + " " + "\b");
+                            }
+
+                            /* display new */
+                            UserInput = options[FoundIndex];
+                            CurrentOptionDisplayedIndex = FoundIndex;
+
+                            Console.Write(options[CurrentOptionDisplayedIndex]);
+
+                            break;
+                        }
+                        OptionIndex++;
+                    }
+                    // Closest search ends
+                }
+                else if (!UserInput.Equals(String.Empty) && KeyInfo.Key == ConsoleKey.Backspace)
+                {
+                    Console.Write("\b" + " " + "\b");
+
+                    if (!string.IsNullOrEmpty(UserInput))
+                    {
+                        UserInput = UserInput.Substring(0, UserInput.Length - 1);
+                    }
+                }
+                else if (!UserInput.Equals(String.Empty) && KeyInfo.Key == ConsoleKey.Delete)
+                {
+                    // Erase it all
+                    for (int UserInputIndex = 0; UserInputIndex < UserInput.Length; UserInputIndex++)
+                    {
+                        Console.Write("\b" + " " + "\b");
+                    }
+
+                    // Set UserInput to Empty
+                    UserInput = "";
+
+                }
+                else if (KeyInfo.Key == ConsoleKey.UpArrow || KeyInfo.Key == ConsoleKey.DownArrow)
+                {
+                    // Display another option
+
+                    // Erase on screen and in UserInput string
+                    for (int UserInputIndex = 0; UserInputIndex < UserInput.Length; UserInputIndex++)
+                    {
+                        Console.Write("\b" + " " + "\b");
+                    }
+
+                    // Display new option
+                    if (KeyInfo.Key == ConsoleKey.UpArrow)
+                    {
+                        if (CurrentOptionDisplayedIndex > 0)
+                            CurrentOptionDisplayedIndex--;
+                        else
+                            CurrentOptionDisplayedIndex = OptionCount - 1;
+
+                    }
+                    else if (KeyInfo.Key == ConsoleKey.DownArrow)
+                    {
+                        if (CurrentOptionDisplayedIndex < OptionCount - 1)
+                            CurrentOptionDisplayedIndex++;
+                        else
+                            CurrentOptionDisplayedIndex = 0;
+                    }
+
+                    // Show new option
+                    Console.Write(options[CurrentOptionDisplayedIndex]);
+
+                    // Set new user input
+                    UserInput = options[CurrentOptionDisplayedIndex];
+                }
+            }
+            while (KeyInfo.Key != ConsoleKey.Enter);
+
+            return UserInput;
+        }
+
+        /// <summary>
+        /// Gets a password without displaying it on screen. Input is masked by *s
+        /// </summary>
+        /// <param name="message">Message that appears on the prompt. For eg, Enter Value:</param>
+        /// <returns>The password entered by the user</returns>
+        public static string GetPassword(string message)
+        {
+            Console.Write(message);
+
+            string PasswordString = "";
+            ConsoleKeyInfo KeyInfo;
+
+            do
+            {
+                // Getting a Key from console
+                KeyInfo = Console.ReadKey(true);
+
+                if (Char.IsLetterOrDigit(KeyInfo.KeyChar))
+                {
+                    // If its a Letter or Digit, echo * to screen, add to Input String
+                    Console.Write("*");
+                    PasswordString += KeyInfo.KeyChar;
+                }
+                else if (PasswordString != String.Empty && KeyInfo.Key == ConsoleKey.Backspace)
+                {
+                    // User hit back space
+
+                    // Erasing on Console
+                    Console.Write("\b" + " " + "\b");
+
+                    // Erasing in Input String
+                    if (!string.IsNullOrEmpty(PasswordString))
+                    {
+                        PasswordString = PasswordString.Substring(0, PasswordString.Length - 1);
+                    }
+                }
+            }
+            while (KeyInfo.Key != ConsoleKey.Enter);
+
+            return PasswordString;
+        }
+
+        #endregion
+
+        #region Utils
+
         private static void Erase(string userInput)
         {
             for (int i = 0; i < userInput.Length; i++)
@@ -182,5 +490,7 @@

             return result;
         }
+
+        #endregion
     }
 }


Update Program.c

Update Program.c

Update try catch

--- AwsEC2Sample1/Program.cs
+++ AwsEC2Sample1/Program.cs
@@ -260,18 +260,30 @@
                 Console.WriteLine();
             }

+            // delete Security Group
             if (!string.IsNullOrEmpty(secGroupId)) {
-                Console.WriteLine("Delete SecurityGroup " + secGroupId);
-                DeleteSecurityGroupRequest delSecGroupReq = new DeleteSecurityGroupRequest();
-                delSecGroupReq.GroupId = secGroupId;
-                DeleteSecurityGroupResponse delSecGroupResp = ec2Client.DeleteSecurityGroup(delSecGroupReq);
-            }
-
-            DeleteInstanceProfile();
+                try
+                {
+                    Console.WriteLine("Delete SecurityGroup " + secGroupId);
+                    DeleteSecurityGroupRequest delSecGroupReq = new DeleteSecurityGroupRequest();
+                    delSecGroupReq.GroupId = secGroupId;
+                    DeleteSecurityGroupResponse delSecGroupResp = ec2Client.DeleteSecurityGroup(delSecGroupReq);
+                }
+                catch (Exception ex)
+                {
+                    Console.WriteLine(ex.ToString());
+                    Console.WriteLine();
+                }
+            }
+
+            Thread.Sleep(1000);
+
             Console.WriteLine("Delete Instance Profile created for sample.");
+            DeleteInstanceProfile();

             Console.WriteLine("Instance terminated, push enter to exit the program");
             Console.Read();
+
         }

         /// <summary>


[Core] Issue #58. PrebuiltTool documentation

--- Bam.Core/PreBuiltTool.cs
+++ Bam.Core/PreBuiltTool.cs
@@ -30,7 +30,8 @@
 namespace Bam.Core
 {
     /// <summary>
-    /// A tool is a module in the usual sense, so that it can be added into the dependency tree
+    /// A prebuilt tool is a module that has been built outside of Bam, but can still be included
+    /// as a dependency in the build.
     /// </summary>
     public abstract class PreBuiltTool :
         Module,
@@ -52,25 +53,49 @@
         }
             #endif

-        public abstract Settings CreateDefaultSettings<T>(T module) where T : Module;
+        /// <summary>
+        /// Create an instance of the default settings for the tool associated with the module.
+        /// </summary>
+        /// <returns>The default settings.</returns>
+        /// <param name="module">Module.</param>
+        /// <typeparam name="T">The 1st type parameter.</typeparam>
+        public abstract Settings
+        CreateDefaultSettings<T>(
+            T module) where T : Module;

+        /// <summary>
+        /// Get the environment variables to be injected into the run of the tool.
+        /// </summary>
+        /// <value>The environment variables.</value>
         public System.Collections.Generic.Dictionary<string, TokenizedStringArray> EnvironmentVariables
         {
             get;
             private set;
         }

+        /// <summary>
+        /// Get the array of environment variable names to inherit from the parent environment.
+        /// </summary>
+        /// <value>The inherited environment variables.</value>
         public StringArray InheritedEnvironmentVariables
         {
             get;
             private set;
         }

+        /// <summary>
+        /// Get the executable name for the prebuilt tool.
+        /// </summary>
+        /// <value>The executable.</value>
         public abstract TokenizedString Executable
         {
             get;
         }

+        /// <summary>
+        /// Default to no extra initial arguments. Virtual to allow overriding.
+        /// </summary>
+        /// <value>The initial arguments.</value>
         public virtual TokenizedStringArray InitialArguments
         {
             get
@@ -79,6 +104,10 @@
             }
         }

+        /// <summary>
+        /// Prebuilt tool does not support response files by default. Virtual to allow overiding.
+        /// </summary>
+        /// <value>The use response file option.</value>
         public virtual string UseResponseFileOption
         {
             get
@@ -87,6 +116,10 @@
             }
         }

+        /// <summary>
+        /// No execution needed to update the prebuilt tool.
+        /// </summary>
+        /// <param name="context">Context.</param>
         protected override void
         ExecuteInternal(
             ExecutionContext context)
@@ -94,6 +127,10 @@
             // by default, a PreBuiltTool's execution does nothing as it's on disk
         }

+        /// <summary>
+        /// No execution policy required for a prebuilt tool.
+        /// </summary>
+        /// <param name="mode">Mode.</param>
         protected override void
         GetExecutionPolicy(
             string mode)
@@ -101,6 +138,9 @@
             // by default, the execution policy of a PreBuiltTool is to do nothing as it's on disk
         }

+        /// <summary>
+        /// Confirm that the prebuilt executable exists.
+        /// </summary>
         public override void
         Evaluate()
         {


Delete pay_success.aspx.cs

Delete pay_success.aspx.cs

--- pay_success.aspx.cs
+++ pay_success.aspx.cs
@@ -1,127 +0,0 @@
-using BridgePG;
-using System;
-using System.Collections.Generic;
-using System.Collections.Specialized;
-using System.Configuration;
-
-using System.Web;
-using System.Web.UI;
-using System.Web.UI.WebControls;
-
-namespace WebApplication2
-{
-    public partial class pay_success : System.Web.UI.Page
-    {
-        public string bridgeResponseMessage = "Error ", drcResponse = "Error", walletResponseMessage = "", merchant_txn = "", merchant_txn_date_time = "", csc_txn = "";
-        protected void Page_Load(object sender, EventArgs e)
-        {
-            if (Session["logedin"] != "true") Response.Redirect("login.aspx", true);
-
-            NameValueCollection nvc = Request.Form;
-            if (!string.IsNullOrEmpty(nvc["walletResponseMessage"]))
-            {
-                walletResponseMessage = nvc["walletResponseMessage"];
-
-
-
-            }
-            if (!string.IsNullOrEmpty(nvc["bridgeResponseMessage"]))
-            {
-                bridgeResponseMessage = nvc["bridgeResponseMessage"];
-                Crypto.privateKey = ConfigurationManager.AppSettings["PRIVATE_KEY"];
-                Crypto.publicKey = ConfigurationManager.AppSettings["PUBLIC_KEY"];
-
-                drcResponse = Crypto.decrypt(bridgeResponseMessage, Crypto.privateKey, Crypto.publicKey, true);
-                string[] arr = drcResponse.Split("|".ToCharArray());
-
-                for (int i = 0; i < arr.Length; i++)
-                {
-                    string[] arr2 = arr[i].Split("=".ToCharArray());
-                    if (arr2[0] == "merchant_txn") merchant_txn = arr2[1];
-                    TextBoxmerchant_txn.Text = merchant_txn;
-                    if (arr2[0] == "merchant_txn_date_time") merchant_txn_date_time = arr2[1];
-                    TextBoxmerchant_txn_date_time.Text = merchant_txn_date_time;
-                    if (arr2[0] == "csc_txn") csc_txn = arr2[1];
-                    TextBoxcsc_txn.Text = csc_txn;
-                    if (arr2[0] == "merchant_id") TextBoxmerchant_id.Text = arr2[1];
-                    if (arr2[0] == "csc_id") TextBoxcsc_id.Text = arr2[1];
-                    if (arr2[0] == "product_id") TextBoxproduct_id.Text = arr2[1];
-                    if (arr2[0] == "txn_amount") TextBoxtxn_amount.Text = arr2[1];
-                    if (arr2[0] == "amount_parameter") TextBoxamount_parameter.Text = arr2[1];
-                    if (arr2[0] == "txn_mode") TextBoxtxn_mode.Text = arr2[1];
-                    if (arr2[0] == "txn_type") TextBoxtxn_type.Text = arr2[1];
-                    if (arr2[0] == "merchant_receipt_no") TextBoxmerchant_receipt_no.Text = arr2[1];
-                    if (arr2[0] == "csc_share_amount") TextBoxcsc_share_amount.Text = arr2[1];
-
-                }
-
-
-
-            }
-
-
-
-
-
-        }
-
-        protected void ButtonTransaction_enquiry_Click(object sender, EventArgs e)
-        {
-            bridgeResponseMessage = "";
-            drcResponse = "Response Transaction Enquiry: " + BridgePGUtil.transaction_enquiry(TextBoxmerchant_id.Text, TextBoxmerchant_txn.Text);
-
-        }
-
-        protected void ButtonTransaction_Status_Click(object sender, EventArgs e)
-        {
-            bridgeResponseMessage = "";
-            drcResponse = "Response Transaction Status: " + BridgePGUtil.transaction_status(TextBoxmerchant_id.Text, TextBoxmerchant_txn.Text, TextBoxcsc_txn.Text);
-
-        }
-
-        protected void Buttonrefund_log_Click(object sender, EventArgs e)
-        {
-            try
-            {
-                bridgeResponseMessage = "";
-                string res = BridgePGUtil.refund_log(TextBoxmerchant_id.Text, TextBoxmerchant_txn.Text, TextBoxcsc_txn.Text, "1", "2", "3", "4", "5", "6", "7");
-                drcResponse = "Response Refund Log: " + res;
-                //merchant_id=10001|merchant_reference=2|refund_reference=761727416093012174120821|response_status=Success
-                try
-                {
-                    string[] arr = res.Split("|".ToCharArray());
-                    if (arr[3].Split("=".ToCharArray())[1] == "Success")
-                    {
-                        TextBoxrefund_reference.Text = arr[2].Split("=".ToCharArray())[1];
-
-                    }
-                }
-                catch (Exception)
-                {
-                    drcResponse = res;
-
-                }
-            }
-            catch (Exception ex)
-            {
-                drcResponse = ex.Message;
-            }
-
-        }
-
-        protected void Buttonrefund_status_Click(object sender, EventArgs e)
-        {
-            bridgeResponseMessage = "";
-            if(TextBoxrefund_reference.Text.Length>0)
-            drcResponse = "Response Refund Status: " + BridgePGUtil.refund_status(TextBoxmerchant_id.Text, TextBoxmerchant_txn.Text, TextBoxcsc_txn.Text,TextBoxrefund_reference.Text);
-
-        }
-
-        protected void Buttonrecon_log_Click(object sender, EventArgs e)
-        {
-            bridgeResponseMessage = "";
-            drcResponse = "Response Recon Log  Status: " + BridgePGUtil.recon_log(TextBoxmerchant_id.Text, TextBoxmerchant_txn.Text, TextBoxcsc_txn.Text, TextBoxcsc_id.Text, TextBoxproduct_id.Text, TextBoxtxn_amount.Text, TextBoxmerchant_txn_date_time.Text, "Success", "R" + TextBoxmerchant_txn.Text.ToString());
-
-        }
-    }
-}


Программа изменена: теперь показывается реальная текущая погода на улице

--- tdd/tdd/Companion.cs
+++ tdd/tdd/Companion.cs
@@ -16,7 +16,10 @@
             else if (words == "Пока")
                 return replySymbols + "Пока!";
             else if (words == "Покажи погоду")
-                return replySymbols + "Сейчас на улице: ";
+            {
+                WeatherMaker wm = new WeatherMaker();
+                return replySymbols + "Сейчас на улице: " + wm.getCurTemperatureByCityID(1510853);
+            }
             return replySymbols + "Привет!";
         }
     }


simplified server ip

simplified server ip

--- peer/peer/server.cs
+++ peer/peer/server.cs
@@ -386,13 +386,13 @@

                         //put my ip in srcIP

-                        IPAddress [] ip = Dns.GetHostAddresses(Dns.GetHostName());
-                        if (ip.Length > 0)
-                        {
-                            msg.srcIP = ip[0];
-                        }
+                        //IPAddress [] ip = Dns.GetHostAddresses(Dns.GetHostName());
+                        //if (ip.Length > 0)
+                        //{
+                        msg.srcIP = Program.p2p.myAddress;
+                        //}

-                        Console.WriteLine("in server process. Command is {0} and srcIP is {1}", msg.command, msg.srcIP);
+                        Console.WriteLine("in server process. Command is {0}. peer ip is {2} and srcIP is {1}", msg.command, msg.srcIP, msg.peerIP);
                         Program.p2p.clientQueue.Add(msg);
 //                        AsyncUserToken relayToken;   // = (AsyncUserToken)e.UserToken;
 //                        int msgLen = e.BytesTransferred;


Minor naming fix in TaskExtension

Minor naming fix in TaskExtension

--- Extensions/TaskExtensions.cs
+++ Extensions/TaskExtensions.cs
@@ -6,9 +6,9 @@
 {
     public static class TaskExtensions
     {
-        public static Task DeleteAfterTime(this IDeletable message, int seconds = 0, int minutes = 0, int hours = 0, int days = 0) => message.DeleteAfterSeconds(new TimeSpan(seconds, minutes, hours, days));
-        public static Task DeleteAfterSeconds(this IDeletable message, double seconds) => message.DeleteAfterSeconds(TimeSpan.FromSeconds(seconds));
-        public static Task DeleteAfterSeconds(this IDeletable message, TimeSpan timeSpan)
+        public static Task DeleteAfterTime(this IDeletable message, int seconds = 0, int minutes = 0, int hours = 0, int days = 0) => message.DeleteAfterTimeSpan(new TimeSpan(seconds, minutes, hours, days));
+        public static Task DeleteAfterSeconds(this IDeletable message, double seconds) => message.DeleteAfterTimeSpan(TimeSpan.FromSeconds(seconds));
+        public static Task DeleteAfterTimeSpan(this IDeletable message, TimeSpan timeSpan)
         {
             return Task.Delay(timeSpan).ContinueWith(async _ => await message.DeleteAsync());
         }
@@ -17,7 +17,7 @@
         public static Task DeleteAfterSeconds<T>(this Task<T> task, double seconds, bool awaitDeletion = false) where T : IDeletable => task.DeleteAfterTimeSpan(TimeSpan.FromSeconds(seconds), awaitDeletion);
         public static Task DeleteAfterTimeSpan<T>(this Task<T> task, TimeSpan timeSpan, bool awaitDeletion = false) where T : IDeletable
         {
-            var deletion = Task.Run(async () => await (await task).DeleteAfterSeconds(timeSpan));
+            var deletion = Task.Run(async () => await (await task).DeleteAfterTimeSpan(timeSpan));
             return awaitDeletion ? deletion : task;
         }
     }


Decreasing SW rendering quality and adding documentation.

--- Rotate3D/SolidWorks.cs
+++ Rotate3D/SolidWorks.cs
@@ -8,6 +8,9 @@
 using SwConst;

 namespace Rotate3D {
+    /// <summary>
+    /// Interfaces with SolidWorks using the COM API.
+    /// </summary>
     class SolidWorks {
         private static ISldWorks app = new SldWorks.SldWorks();

@@ -15,16 +18,17 @@
         private ModelDocExtension extension;
         private ModelView view;

+        /// <summary>
+        /// Creates a new SolidWorks connector to the currently active document in SolidWorks.
+        /// </summary>
         public SolidWorks() {
             try {
                 this.modelDoc  = (ModelDoc2)app.ActiveDoc;
                 this.extension = this.modelDoc.Extension;
                 this.view      = (ModelView)this.modelDoc.ActiveView;

-                //app.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swPerformanceRemoveDetailDuringZoomPanRotate, true);
-                //app.SetUserPreferenceIntegerValue((int)swUserPreferenceToggle_e.swPerformanceRemoveDetailDuringZoomPanRotate, true);
-                //this.view.DisplayMode = (int)swViewDisplayMode_e.swViewDisplayMode_Faceted;
-                //app.SetUserPreferenceIntegerValue((int)swUserPreferenceIntegerValue_e.swEdgesTangentEdgeDisplay, (int)swEdgesTangentEdgeDisplay_e.swEdgesTangentEdgeDisplayRemoved);
+                // Set lower quality for quicker rendering
+                this.view.DisplayMode = (int)swViewDisplayMode_e.swViewDisplayMode_Shaded;
             }
             catch (Exception e) {
                 MessageBox.Show("Error connecting to SolidWorks:\r\n" + e, "Kinect Demo", MessageBoxButton.OK, MessageBoxImage.Error);
@@ -32,32 +36,48 @@
             }
         }

+        /// <summary>
+        /// Call before gripping, to pause SolidWorks dynamics.
+        /// </summary>
         public void PreRender() {
             this.view.StopDynamics();
-            //this.modelDoc.SetTessellationQuality(0);
-            //this.modelDoc.GraphicsRedraw2();
         }

+        /// <summary>
+        /// Call after gripping, to restart SolidWorks dynamics.
+        /// </summary>
         public void PostRender() {
             this.view.StartDynamics();
         }

+        /// <summary>
+        /// Zoom the SolidWorks view to fit.
+        /// </summary>
         public void ZoomToFit() {
             this.modelDoc.ViewZoomtofit2();
         }

+        /// <summary>
+        /// Rotate the camera around the center of the model by the specified angles.
+        /// </summary>
+        /// <param name="xAngle">The relative horizontal rotation, in radians.</param>
+        /// <param name="yAngle">The relative vertical rotation, in radians.</param>
         public void AdjustViewAngle(double xAngle, double yAngle) {
-            // flip y for input
+            // Flip y for input
             yAngle *= -1;

             this.view.RotateAboutCenter(yAngle, xAngle);
         }

+        /// <summary>
+        /// Zoom the camera by the specified amount.
+        /// </summary>
+        /// <param name="zDist">The zoom factor (1.0 is no zooming).</param>
         public void AdjustZoom(double zDist) {
-            // invert z for input
+            // Invert z for input
             zDist *= -1;

-            // convert to a factor
+            // Convert to a factor relative to 1.0
             zDist += 1;

             this.view.ZoomByFactor(zDist);


Update separator violation logic

Update separator violation logic

--- Rules/UseWhitespace.cs
+++ Rules/UseWhitespace.cs
@@ -159,44 +159,41 @@
             }
         }

+        private bool IsSeparator(Token token)
+        {
+            return token.Kind == TokenKind.Comma || token.Kind == TokenKind.Semi;
+        }
         private IEnumerable<DiagnosticRecord> FindSeparatorViolations(TokenOperations tokenOperations)
         {
             Func<LinkedListNode<Token>, bool> predicate = node =>
             {
                 return node.Next != null
+                    && node.Next.Value.Kind != TokenKind.NewLine
+                    && node.Next.Value.Kind != TokenKind.EndOfInput // semicolon can be followed by end of input
                     && !IsPreviousTokenApartByWhitespace(node.Next);
             };

-            Func<Token, ErrorKind, DiagnosticRecord> getDiagnosticRecord = (token, errKind) =>
-            {
-                return new DiagnosticRecord(
-                    GetError(errKind),
-                    token.Extent,
-                    GetName(),
-                    GetDiagnosticSeverity(),
-                    token.Extent.File,
-                    null,
-                    null);
-            };
-
-            foreach (var tokenNode in tokenOperations.GetTokenNodes(TokenKind.Comma).Where(predicate))
-            {
-                yield return getDiagnosticRecord(tokenNode.Value, ErrorKind.SeparatorComma);
-            }
-
-            foreach (var tokenNode in tokenOperations.GetTokenNodes(TokenKind.Semi).Where(predicate))
-            {
-                // semi-colon can be followed by newline or end of input
-                if (tokenNode.Next.Value.Kind == TokenKind.EndOfInput
-                    || tokenNode.Next.Value.Kind == TokenKind.NewLine)
-                {
-                    continue;
-                }
-
-                yield return getDiagnosticRecord(tokenNode.Value, ErrorKind.SeparatorSemi);
-            }
-        }
-
+            // TODO replace semi-colon with semicolon
+            // TODO update separator error string
+            foreach (var tokenNode in tokenOperations.GetTokenNodes(IsSeparator).Where(predicate))
+            {
+                yield return getDiagnosticRecord(
+                    tokenNode.Value,
+                    tokenNode.Value.Kind == TokenKind.Comma ? ErrorKind.SeparatorComma : ErrorKind.SeparatorSemi);
+            }
+        }
+
+        private DiagnosticRecord getDiagnosticRecord(Token token, ErrorKind errKind)
+        {
+            return new DiagnosticRecord(
+                GetError(errKind),
+                token.Extent,
+                GetName(),
+                GetDiagnosticSeverity(),
+                token.Extent.File,
+                null,
+                null);
+        }

         private bool IsKeyword(Token token)
         {


Update CachedImage.cs

Update CachedImage.cs

--- source/FFImageLoading.Forms/CachedImage.cs
+++ source/FFImageLoading.Forms/CachedImage.cs
@@ -16,8 +16,8 @@
     /// </summary>
     public class CachedImage : View
     {
-        static bool? _isDesignModeEnabled = null;
-        static bool IsDesignModeEnabled
+        private static bool? _isDesignModeEnabled = null;
+        protected static bool IsDesignModeEnabled
         {
             get
             {
@@ -25,7 +25,6 @@
                 if (!_isDesignModeEnabled.HasValue)
                 {
                     var type = typeof(Image).GetTypeInfo().Assembly.GetType("Xamarin.Forms.DesignMode");
-
                     if (type == null)
                     {
                         _isDesignModeEnabled = true;
@@ -675,26 +674,13 @@
         /// <summary>
         /// Reloads the image.
         /// </summary>
-        public void ReloadImage()
-        {
-            if (InternalReloadImage != null && Source != null)
-            {
-                InternalReloadImage();
-            }
-        }
+        public void ReloadImage() => InternalReloadImage?.Invoke();

         internal Action InternalCancel;
-
         /// <summary>
         /// Cancels image loading tasks
         /// </summary>
-        public void Cancel()
-        {
-            if (InternalCancel != null)
-            {
-                InternalCancel();
-            }
-        }
+        public void Cancel() => InternalCancel?.Invoke();

         internal Func<GetImageAsJpgArgs, Task<byte[]>> InternalGetImageAsJPG;


Make OptionVerifyProvider read-only

Make OptionVerifyProvider read-only

--- source/Htc.Vita.Core/Runtime/IpcChannel.cs
+++ source/Htc.Vita.Core/Runtime/IpcChannel.cs
@@ -12,7 +12,7 @@

         public abstract class Client
         {
-            public static string OptionVerifyProvider = "option_verify_provider";
+            public static readonly string OptionVerifyProvider = "option_verify_provider";

             private static Dictionary<string, Client> Instances { get; } = new Dictionary<string, Client>();
             private static Type _defaultType = typeof(NamedPipeIpcChannel.Client);


Fixed access denied crash in link junk search

--- source/UninstallTools/Junk/ShortcutJunk.cs
+++ source/UninstallTools/Junk/ShortcutJunk.cs
@@ -24,16 +24,30 @@
             _links = links;
         }

+        private static IEnumerable<string> GetLnkFilesSafe(CSIDL directory, SearchOption option)
+        {
+            try
+            {
+                return Directory.GetFiles(WindowsTools.GetEnvironmentPath(directory), "*.lnk", option);
+            }
+            catch (Exception ex)
+            {
+                Console.WriteLine(ex);
+                Debug.Fail(ex.ToString());
+            }
+            return Enumerable.Empty<string>();
+        }
+
         public static IEnumerable<JunkNode> FindAllJunk(IEnumerable<ApplicationUninstallerEntry> targets, IEnumerable<ApplicationUninstallerEntry> other)
         {
             var syspath = WindowsTools.GetEnvironmentPath(CSIDL.CSIDL_WINDOWS);

             var results = new List<Shortcut>();
             foreach (var linkFilename in
-                Directory.GetFiles(WindowsTools.GetEnvironmentPath(CSIDL.CSIDL_PROGRAMS), "*.lnk", SearchOption.AllDirectories)
-                .Concat(Directory.GetFiles(WindowsTools.GetEnvironmentPath(CSIDL.CSIDL_COMMON_PROGRAMS), "*.lnk", SearchOption.AllDirectories))
-                .Concat(Directory.GetFiles(WindowsTools.GetEnvironmentPath(CSIDL.CSIDL_DESKTOPDIRECTORY), "*.lnk", SearchOption.TopDirectoryOnly))
-                .Concat(Directory.GetFiles(WindowsTools.GetEnvironmentPath(CSIDL.CSIDL_COMMON_DESKTOPDIRECTORY), "*.lnk", SearchOption.TopDirectoryOnly))
+                GetLnkFilesSafe(CSIDL.CSIDL_PROGRAMS, SearchOption.AllDirectories)
+                .Concat(GetLnkFilesSafe(CSIDL.CSIDL_COMMON_PROGRAMS, SearchOption.AllDirectories))
+                .Concat(GetLnkFilesSafe(CSIDL.CSIDL_DESKTOPDIRECTORY, SearchOption.TopDirectoryOnly))
+                .Concat(GetLnkFilesSafe(CSIDL.CSIDL_COMMON_DESKTOPDIRECTORY, SearchOption.TopDirectoryOnly))
                 .Distinct())
             {
                 try
@@ -45,8 +59,9 @@

                     results.Add(new Shortcut(linkFilename, target));
                 }
-                catch
+                catch (Exception ex)
                 {
+                    Console.WriteLine(ex);
                     Debug.Fail("Failed to resolve shortcut " + linkFilename);
                 }
             }


Replace `CutOrDeleteSelection` with new implementation

Here's the new behavior for all deletion without selected text related operations:
- if caret is in editable area, no change in behavior.
- if caret is in active prompt area, move caret to the closest location first.
- if caret is in other readonly area, do nothing.

Here's the new behavior for all deletion with selected text related operations:
- if the selection overlaps with editable area, caret will be moved to a position in
  editable area that is closest to it's original position.
- Otherwise, do nothing (and preserve the selection).

Deletion related operations including:
- Delete (and TypeChar)
- Backspace
- Return and BreakLine
- Paste
- Cut

--- src/InteractiveWindow/Editor/InteractiveWindow.UIThreadOnly.cs
+++ src/InteractiveWindow/Editor/InteractiveWindow.UIThreadOnly.cs
@@ -579,7 +579,10 @@
             {
                 if (!TextView.Selection.IsEmpty)
                 {
-                    CutOrDeleteSelectionThenMoveCaret(isCut: false);
+                    if (CutOrDeleteSelection(isCut: false))
+                    {
+                        MoveCaretToClosestEditableBuffer();
+                    }
                 }
                 else if (IsInActivePrompt(TextView.Caret.Position.BufferPosition))
                 {
@@ -1186,9 +1189,9 @@
                     return false;
                 }

-                // always has a span following prompt.
+                Debug.Assert(index + 1 < sourceSpans.Count);
                 var followingSpan = sourceSpans[index + 1];
-                // if the following span is in editable buffer, then the prompt must be active.
+                // if the following span is editable, then the prompt is active.
                 return GetPositionInBuffer(followingSpan.Start, editableBuffer) != null;
             }

@@ -2148,7 +2151,10 @@
                 bool handled = false;
                 if (!TextView.Selection.IsEmpty)
                 {
-                    CutOrDeleteSelectionThenMoveCaret(isCut: false);
+                    if (CutOrDeleteSelection(isCut: false))
+                    {
+                        MoveCaretToClosestEditableBuffer();
+                    }
                     handled = true;
                 }
                 else if (IsInActivePrompt(TextView.Caret.Position.BufferPosition))
@@ -2298,15 +2304,17 @@
             {
                 if (!TextView.Selection.IsEmpty)
                 {
-                    CutOrDeleteSelectionThenMoveCaret(isCut: true);
+                    if (CutOrDeleteSelection(isCut: true))
+                    {
+                        MoveCaretToClosestEditableBuffer();
+                    }
                     return;
                 }

                 var caretPosition = TextView.Caret.Position.BufferPosition;

                 // don't cut and move caret if it's in readonly buffer (except in active prompt)
-                if (GetPositionInLanguageBuffer(caretPosition) != null ||
-                    GetPositionInStandardInputBuffer(caretPosition) != null ||
+                if (MapToEditableBuffer(caretPosition) != null ||
                     IsInActivePrompt(caretPosition))
                 {
                     CutOrDeleteCurrentLine(isCut: true);
@@ -2326,33 +2334,25 @@
             }

             /// <summary>
-            /// If any of currently selected text is editable, then deletes editable selection, optionally saves it to the clipboard
-            /// and moves caret to closest location in editable buffer. Otherwise do nothing (and preserve selection).
+            /// If any of currently selected text is editable, then deletes editable selection, optionally saves it
+            /// to the clipboard. Otherwise do nothing (and preserve selection).
             /// </summary>
-            private void CutOrDeleteSelectionThenMoveCaret(bool isCut)
+            private bool CutOrDeleteSelection(bool isCut)
             {
                 if (!TextView.Selection.IsEmpty)
                 {
                     if (TextView.Selection.Mode == TextSelectionMode.Stream ?
                             IsSteamSelectionInEditableBuffer(TextView.Selection) :
                             ReduceBoxSelectionToEditableBox())
-                    {
-                        CutOrDeleteSelection(isCut: false);
-                        MoveCaretToClosestEditableBuffer();
-                    }
-                }
-            }
-
-            /// <summary>
-            /// Deletes currently selected text from the language buffer and optionally saves it to the clipboard.
-            /// </summary>
-            private void CutOrDeleteSelection(bool isCut)
-            {
-                CutOrDelete(TextView.Selection.SelectedSpans, isCut);
-
-                // if the selection spans over prompts the prompts remain selected, so clear manually:
-                TextView.Selection.Clear();
-            }
+                    {
+                        CutOrDelete(TextView.Selection.SelectedSpans, isCut);
+                        // if the selection spans over prompts the prompts remain selected, so clear manually:
+                        TextView.Selection.Clear();
+                        return true;
+                    }
+                }
+                return false;
+            }

             private void CutOrDelete(IEnumerable<SnapshotSpan> projectionSpans, bool isCut)
             {
@@ -2495,7 +2495,10 @@
                 {
                     if (TextView.Selection.Mode == TextSelectionMode.Stream || ReduceBoxSelectionToEditableBox())
                     {
-                        CutOrDeleteSelectionThenMoveCaret(isCut: false);
+                        if (CutOrDeleteSelection(isCut: false))
+                        {
+                            MoveCaretToClosestEditableBuffer();
+                        }
                         handled = true;
                     }
                 }
@@ -2661,7 +2664,10 @@

                 if (!TextView.Selection.IsEmpty)
                 {
-                    CutOrDeleteSelectionThenMoveCaret(isCut: false);
+                    if (CutOrDeleteSelection(isCut: false))
+                    {
+                        MoveCaretToClosestEditableBuffer();
+                    }
                 }
                 else if (IsInActivePrompt(TextView.Caret.Position.BufferPosition))
                 {


More doc comments

More doc comments

--- src/Logging/Logging.AzureAppServices/src/BlobLoggerProvider.cs
+++ src/Logging/Logging.AzureAppServices/src/BlobLoggerProvider.cs
@@ -41,7 +41,7 @@
         /// Creates a new instance of <see cref="BlobLoggerProvider"/>
         /// </summary>
         /// <param name="blobReferenceFactory">The container to store logs to.</param>
-        /// <param name="options"></param>
+        /// <param name="options">Options to be used in creating a logger.</param>
         internal BlobLoggerProvider(
             IOptionsMonitor<AzureBlobLoggerOptions> options,
             Func<string, ICloudAppendBlob> blobReferenceFactory) :


Added second unit test

Added second unit test

--- src/NJsonSchema.Tests/Generation/AnnotationsGenerationTests.cs
+++ src/NJsonSchema.Tests/Generation/AnnotationsGenerationTests.cs
@@ -84,5 +84,29 @@
   }
 }", json);
         }
+
+        [JsonSchema(JsonObjectType.Array, ArrayItem = typeof(string))]
+        public class ArrayModel<T> : List<T>
+        {
+        }
+
+        [TestMethod]
+        public void When_class_has_array_item_type_defined_then_schema_has_this_item_type2()
+        {
+            //// Arrange
+            var schema = JsonSchema4.FromType<ArrayModel<string>>();
+
+            //// Act
+            var json = schema.ToJson();
+
+            //// Assert
+            Assert.AreEqual(@"{
+  ""$schema"": ""http://json-schema.org/draft-04/schema#"",
+  ""type"": ""array"",
+  ""items"": {
+    ""type"": ""string""
+  }
+}", json);
+        }
     }
 }


Some code cleanup

Some code cleanup

--- src/proj/EventStore.Persistence.SqlPersistence/SqlDialects/OracleNativeDialect.cs
+++ src/proj/EventStore.Persistence.SqlPersistence/SqlDialects/OracleNativeDialect.cs
@@ -82,7 +82,7 @@

         private string AddOuterTrailingCommitSequence(string query)
         {
-            return (query.TrimEnd(new char[] { ';' }) + "\r\n" + OracleNativeStatements.AddCommitSequence);
+            return (query.TrimEnd(new[] { ';' }) + "\r\n" + OracleNativeStatements.AddCommitSequence);
         }
         public override IDbStatement BuildStatement(System.Transactions.TransactionScope scope, System.Data.IDbConnection connection, System.Data.IDbTransaction transaction)
         {
@@ -97,10 +97,8 @@
         }
         private static string ExtractOrderBy(ref string query)
         {
-            var result = String.Empty;
-
-            var orderByIndex = query.IndexOf("ORDER BY");
-            result = query.Substring(orderByIndex).Replace(";", String.Empty);
+	        var orderByIndex = query.IndexOf("ORDER BY", StringComparison.Ordinal);
+            string result = query.Substring(orderByIndex).Replace(";", String.Empty);
             query = query.Substring(0, orderByIndex);

             return result;
@@ -113,7 +111,7 @@
         {
             query = RemovePaging(query);
             if (query.EndsWith(";"))
-                query = query.TrimEnd(new char[] { ';' });
+                query = query.TrimEnd(new[] { ';' });
             var value = OracleNativeStatements.LimitedQueryFormat.FormatWith(query);
             return value;
         }
@@ -127,7 +125,7 @@

             var orderBy = ExtractOrderBy(ref query);

-            var fromIndex = query.IndexOf("FROM ");
+            var fromIndex = query.IndexOf("FROM ", StringComparison.Ordinal);
             var from = query.Substring(fromIndex);

             var select = query.Substring(0, fromIndex);


Split a really long WriteLine into a Write & WriteLine.

--- Cheers/Cheers/Program.cs
+++ Cheers/Cheers/Program.cs
@@ -42,7 +42,8 @@
                 {
                     convertedBirthday = convertedBirthday.AddYears(1);
                 }
-                Console.WriteLine("Awesome! Your birthday is in " + convertedBirthday.Subtract(today).Days + " days! Happy Birthday in advance!");
+                Console.Write("Awesome! Your birthday is in " + convertedBirthday.Subtract(today).Days);
+                Console.WriteLine(" days! Happy Birthday in advance!");
             }
             Console.WriteLine("Press any key to exit.");
             Console.ReadKey();


exception test

exception test

--- Clients/P3D/P3DPlayer.cs
+++ Clients/P3D/P3DPlayer.cs
@@ -15,7 +15,7 @@
 using PokeD.Core.Packets.Shared;
 using PokeD.Core.Packets.Trade;
 using PokeD.Core.Wrappers;
-
+using PokeD.Server.Exceptions;
 using PokeD.Server.IO;

 namespace PokeD.Server.Clients.P3D
@@ -148,7 +148,16 @@
             int id;
             if (P3DPacket.TryParseID(data, out id))
             {
+                if(id >= PlayerResponse.Packets.Length)
+                    throw new P3DPlayerException($"ID {id} >= Packets.Length");
+
                 var packet = PlayerResponse.Packets[id]();
+                if (packet == null)
+                {
+                    //Logger.Log(LogType.Warning, $"Packet with ID {id} is null");
+                    throw new P3DPlayerException($"Packet with ID {id} is null");
+                    //return;
+                }

                 if (packet.TryParseData(data))
                 {


Fixed crash when type is null while deserializing commands

--- CommandPalette/Config.cs
+++ CommandPalette/Config.cs
@@ -142,7 +142,13 @@
                     assembly = PluginHelper.PluginAssemblies[assemblyName];
                 }

-                var type = assembly.GetType(commandElement.Attribute(PLUGIN_TYPE_ATTRIBUTE_NAME).Value);
+                var type = assembly.GetType(commandElement.Attribute(PLUGIN_TYPE_ATTRIBUTE_NAME).Value);
+                if (type == null)
+                {
+                    Console.WriteLine($"Plugin '{assemblyName}' given type is null");
+                    config.UndeserializableCommands.Add(commandElement);
+                    continue;
+                }
                 var cmdSerializer = new XmlSerializer(type);
                 using (var fs = new StringReader(commandElement.ToString()))
                 {


Improve documentation around HandlerMappings

--- src/Noobot.Core/MessagingPipeline/Middleware/HandlerMapping.cs
+++ src/Noobot.Core/MessagingPipeline/Middleware/HandlerMapping.cs
@@ -8,17 +8,10 @@
 {
     public class HandlerMapping
     {
-        public HandlerMapping()
-        {
-            ValidHandles = new IValidHandle[0];
-            MessageShouldTargetBot = true;
-            VisibleInHelp = true;
-        }
-
         /// <summary>
-        /// The various handles of different types
+        /// Valid handles to match on for incomming text, e.g. match exactly on "Hello"
         /// </summary>
-        public IValidHandle[] ValidHandles { get; set; }
+        public IValidHandle[] ValidHandles { get; set; } = new IValidHandle[0];

         /// <summary>
         /// Description of what this handle does. This appears in the "help" function.
@@ -26,7 +19,7 @@
         public string Description { get; set; }

         /// <summary>
-        /// This is what code is run when a handle has been matched.
+        /// The function that is evaluated on a matched handle
         /// </summary>
         public Func<IncomingMessage, IValidHandle, IEnumerable<ResponseMessage>> EvaluatorFunc { get; set; }

@@ -38,11 +31,11 @@
         /// <summary>
         /// Defaults to "True". If set to false then any message is considered, even if it isn't targeted at the bot. e.g. @noobot or a private channel
         /// </summary>
-        public bool MessageShouldTargetBot { get; set; }
+        public bool MessageShouldTargetBot { get; set; } = true;

         /// <summary>
         /// Defaults to "True". Set to false to hide these commands in the help command.
         /// </summary>
-        public bool VisibleInHelp { get; set; }
+        public bool VisibleInHelp { get; set; } = true;
     }
 }


- FlowDirection in Fluent.ContextMenu has been fixed

--- Fluent/Fluent/ContextMenu.cs
+++ Fluent/Fluent/ContextMenu.cs
@@ -321,6 +321,7 @@
             binding.Source = this;
             MenuBar.SetBinding(ContextMenuBar.ResizeModeProperty, binding);
             MenuBar.ParentContextMenu = this;
+            MenuBar.FlowDirection = FlowDirection;

             // Preventing ribbon popup closing
             popup.Child = MenuBar;


Preventing deferred execution of Linq queries in Media

--HG--
branch : 1.x

--- src/Orchard.Web/Modules/Orchard.Media/Services/MediaService.cs
+++ src/Orchard.Web/Modules/Orchard.Media/Services/MediaService.cs
@@ -64,7 +64,7 @@
                     Size = folder.GetSize(),
                     LastUpdated = folder.GetLastUpdated(),
                     MediaPath = folder.GetPath()
-                }).Where(f => !f.Name.Equals("RecipeJournal", StringComparison.OrdinalIgnoreCase));
+                }).Where(f => !f.Name.Equals("RecipeJournal", StringComparison.OrdinalIgnoreCase)).ToList();
         }

         /// <summary>
@@ -80,7 +80,7 @@
                     LastUpdated = file.GetLastUpdated(),
                     Type = file.GetFileType(),
                     FolderName = relativePath
-                });
+                }).ToList();
         }

         /// <summary>


PowerOutage quick implementation that pass system tests!

The key thing was that the graph does not contains loops. This simplify
the problem a lot and allows a quick implementation with a simple tree
traversal. Very cool

--- SRM-144/PowerOutage.cs
+++ SRM-144/PowerOutage.cs
@@ -38,10 +38,9 @@
         }
     }

-    private int weight = 0;
-    private int bestWeight = int.MaxValue;
-    private int[] visitedNodes;
+    private int highestWeight = 0;
     private HashSet<Edge> visitedEdges;
+    private HashSet<Edge> highestEdges;

     public int estimateTimeOut(int[] fromJunction, int[] toJunction, int[] ductLength)
     {
@@ -50,57 +49,50 @@
         for (int i = 0; i < fromJunction.Length; i++)
         {
             graph.AddEdge(new Edge(fromJunction[i], toJunction[i], ductLength[i]));
-            graph.AddEdge(new Edge(toJunction[i], fromJunction[i], ductLength[i]));
         }

         visitedEdges = new HashSet<Edge>();
-        visitedNodes = new int[50];
-
-        for (int i = 0; i < 50; i++)
-        {
-            visitedNodes[i] = fromJunction.Union(toJunction).Contains(i) ? 0 : 2;
-        }

         Traverse(graph, 0);

-        return bestWeight;
+        // Read the problem statement carefully! The key part is that "the graph will never contain a loop".
+        // This simplify the problem a lot and allows a quick implementation with a simple tree traversal.
+
+        // This calculate the cost of visiting all the edges 2 times...
+        int result = graph.Adj.SelectMany(hashSet => hashSet).Sum(edge => 2*edge.Weight);
+
+        // but the the path with the highest sum will be done only once and at the end!
+        return result - highestEdges.Sum(x => x.Weight);
     }

     private void Traverse(Graph graph, int p)
     {
-        if (weight > bestWeight)
-            return;
-
-        if (visitedNodes.All(x => x > 0))
+        if (graph.Adj[p].Count == 0)
         {
-            if (weight < bestWeight) bestWeight = weight;
-            return;
+            int weight = visitedEdges.Sum(x => x.Weight);
+            if (weight > highestWeight)
+            {
+                highestEdges = new HashSet<Edge>(visitedEdges);
+                highestWeight = weight;
+            }
         }

-        foreach (var edge in graph.Adj[p].Except(visitedEdges))
+        foreach (var edge in graph.Adj[p])
         {
-            weight += edge.Weight;
             visitedEdges.Add(edge);
-            visitedNodes[edge.From]++;
-            visitedNodes[edge.To]++;
-
             Traverse(graph, edge.To);
-
-            weight -= edge.Weight;
             visitedEdges.Remove(edge);
-            visitedNodes[edge.From]--;
-            visitedNodes[edge.To]--;
         }
     }

 // BEGIN CUT HERE
     public static void Main(String[] args) {
         try  {
-            eq(0,(new PowerOutage()).estimateTimeOut(new int[] {0}, new int[] {1}, new int[] {10}),10);
-            eq(1,(new PowerOutage()).estimateTimeOut(new int[] {0,1,0}, new int[] {1,2,3}, new int[] {10,10,10}),40);
-            eq(2,(new PowerOutage()).estimateTimeOut(new int[] {0,0,0,1,4}, new int[] {1,3,4,2,5}, new int[] {10,10,100,10,5}),165);
-            eq(3,(new PowerOutage()).estimateTimeOut(new int[] {0,0,0,1,4,4,6,7,7,7,20}, new int[] {1,3,4,2,5,6,7,20,9,10,31}, new int[] {10,10,100,10,5,1,1,100,1,1,5}),281);
-            eq(4,(new PowerOutage()).estimateTimeOut(new int[] {0,0,0,0,0}, new int[] {1,2,3,4,5}, new int[] {100,200,300,400,500}),2500);
+            eq(0, (new PowerOutage()).estimateTimeOut(new int[] { 0 }, new int[] { 1 }, new int[] { 10 }), 10);
+            eq(1, (new PowerOutage()).estimateTimeOut(new int[] { 0, 1, 0 }, new int[] { 1, 2, 3 }, new int[] { 10, 10, 10 }), 40);
+            eq(2, (new PowerOutage()).estimateTimeOut(new int[] { 0, 0, 0, 1, 4 }, new int[] { 1, 3, 4, 2, 5 }, new int[] { 10, 10, 100, 10, 5 }), 165);
+            eq(3, (new PowerOutage()).estimateTimeOut(new int[] { 0, 0, 0, 1, 4, 4, 6, 7, 7, 7, 20 }, new int[] { 1, 3, 4, 2, 5, 6, 7, 20, 9, 10, 31 }, new int[] { 10, 10, 100, 10, 5, 1, 1, 100, 1, 1, 5 }), 281);
+            eq(4, (new PowerOutage()).estimateTimeOut(new int[] { 0, 0, 0, 0, 0 }, new int[] { 1, 2, 3, 4, 5 }, new int[] { 100, 200, 300, 400, 500 }), 2500);
             eq(5, (new PowerOutage()).estimateTimeOut(
                 new int[] {0, 0, 1, 1, 0, 2, 3, 5, 0, 8, 4, 0, 7, 11, 0, 7, 4, 1, 10, 0, 14, 1, 14, 2, 5, 22, 17, 20, 11, 4, 9, 17, 22, 22, 11, 34},
                 new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36},


#19971: Adding TrimEnd token

#19971: Adding TrimEnd token

Work Item: 19971

--- src/Orchard.Web/Modules/Orchard.Tokens/Providers/TextTokens.cs
+++ src/Orchard.Web/Modules/Orchard.Tokens/Providers/TextTokens.cs
@@ -14,6 +14,7 @@
             context.For("Text", T("Text"), T("Tokens for text strings"))
                 .Token("Limit:*", T("Limit:<text length>[,<ellipsis>]"), T("Limit text to specified length and append an optional ellipsis text."))
                 .Token("Format:*", T("Format:<text format>"), T("Optional format specifier (e.g. foo{0}bar). See format strings at Standard Formats and Custom Formats"), "DateTime")
+                .Token("TrimEnd:*", T("TrimEnd:<chars|number>"), T("Trims the specified characters or number of them from the end of the string."), "Text")
                 .Token("UrlEncode", T("Url Encode"), T("Encodes a URL string."), "Text")
                 .Token("HtmlEncode", T("Html Encode"), T("Encodes an HTML string."), "Text")
                 .Token("LineEncode", T("Line Encode"), T("Replaces new lines with
 tags."))
@@ -38,6 +39,7 @@
                 .Token(
                     token => token.StartsWith("Format:", StringComparison.OrdinalIgnoreCase) ? token.Substring("Format:".Length) : null,
                     (token, d) => String.Format(d,token))
+                .Token(token => token.StartsWith("TrimEnd:", StringComparison.OrdinalIgnoreCase) ? token.Substring("TrimEnd:".Length) : null, TrimEnd)
                 .Token("UrlEncode", HttpUtility.UrlEncode)
                 .Token("HtmlEncode", HttpUtility.HtmlEncode)
                 .Token("LineEncode", text => text.Replace(System.Environment.NewLine, "
"))
@@ -45,7 +47,21 @@

         }

-        private string Limit(string token, string param) {
+        private static string TrimEnd(string token, string param) {
+            if (String.IsNullOrEmpty(param)) {
+                return token;
+            }
+
+            int n;
+            if (!int.TryParse(param, out n)) {
+                return token.TrimEnd(param.ToCharArray());
+            }
+
+            n = Math.Max(0, n); // prevent negative numbers
+            return token.Substring(0, token.Length - n);
+        }
+
+        private static string Limit(string token, string param) {
             if(String.IsNullOrEmpty(token)) {
                 return String.Empty;
             }


Minor update to samples

Minor update to samples

--- Samples/Samples/App.cs
+++ Samples/Samples/App.cs
@@ -8,21 +8,24 @@
     public class App : Application {

         public App() {
+            Notification.DefaultTitle = "Test Title";
+
             this.MainPage = new ContentPage {
                 Content = new StackLayout {
                     VerticalOptions = LayoutOptions.Center,
                     Children = {
                         new Button {
+                            Text = "Set Badge",
+                            Command = new Command(() => Notifications.Instance.Badge = 1)
+                        },
+                        new Button {
                             Text = "Press This & Exit App within 10 seconds",
-                            Command = new Command(() => {
-                                Notifications.Instance.Badge = 4;
-                                Notifications.Instance.Send(
-                                    "Test Message",
-                                    "Hello from the ACR Sample Notification App",
-                                    null,
-                                    TimeSpan.FromSeconds(10)
-                                );
-                            })
+                            Command = new Command(() =>
+                                Notifications.Instance.Send(new Notification()
+                                    .SetMessage("Hello from the ACR Sample Notification App")
+                                    .SetSchedule(TimeSpan.FromSeconds(10))
+                                )
+                            )
                         },
                         new Button {
                             Text = "Cancel All Notifications",


Swapped Activator.CreateInstance for TypeDescriptor.GetConverter as this is better handled.

--- src/Our.Umbraco.Ditto/Extensions/PublishedContentExtensions.cs
+++ src/Our.Umbraco.Ditto/Extensions/PublishedContentExtensions.cs
@@ -210,7 +210,7 @@
                                     var converterAttr = propertyInfo.GetCustomAttribute<TypeConverterAttribute>();
                                     if (converterAttr != null)
                                     {
-                                        var converter = Activator.CreateInstance(Type.GetType(converterAttr.ConverterTypeName)) as TypeConverter;
+                                        var converter = TypeDescriptor.GetConverter(Type.GetType(converterAttr.ConverterTypeName)) as TypeConverter;
                                         propertyInfo.SetValue(instance, converter.ConvertFrom(propertyValue), null);
                                     }
                                     else


Remove redundant argument from POST action. Note: is there a point to this post to then just redirect?

--- src/SFA.DAS.EmployerAccounts.Web/Controllers/HomeController.cs
+++ src/SFA.DAS.EmployerAccounts.Web/Controllers/HomeController.cs
@@ -140,7 +140,7 @@

         [HttpPost]
         [Route("whatYoullNeed")]
-        public ActionResult WhatYoullNeed(int? choice)
+        public ActionResult WhatYoullNeedPost()
         {
             return RedirectToAction(ControllerConstants.RegisterUserActionName);
         }


Small typo fix

Small typo fix

--- GConsole/Scripts/GConsole.cs
+++ GConsole/Scripts/GConsole.cs
@@ -281,7 +281,7 @@
         }
         else
         {
-            return "Help not found for " + Color(param, "33EE33")";
+            return "Help not found for " + Color(param, "33EE33");
         }
     }


Simplified deserialization ApiConnection (maybe it's more efficient even)

--- Genius/Http/ApiConnection.cs
+++ Genius/Http/ApiConnection.cs
@@ -43,8 +43,8 @@
                     return
                         new HttpResponse<Annotation>
                         {
-                            Meta = JsonConvert.DeserializeObject<Meta>(jsonMeta.ToString()),
-                            Response = JsonConvert.DeserializeObject<Annotation>(jsonResponse.ToString())
+                            Meta = jsonMeta.ToObject<Meta>(),
+                            Response = jsonResponse.ToObject<Annotation>()
                         };
                 }
             }
@@ -77,8 +77,8 @@
                     return
                         new HttpResponse<T>
                         {
-                            Meta = JsonConvert.DeserializeObject<Meta>(jsonMeta.ToString()),
-                            Response = JsonConvert.DeserializeObject<T>(jsonResponse.ToString())
+                            Meta = jsonMeta.ToObject<Meta>(),
+                            Response = jsonResponse.ToObject<T>()
                         };
                 }
             }
@@ -104,8 +104,8 @@
                     return
                         new HttpResponse<T>
                         {
-                            Meta = JsonConvert.DeserializeObject<Meta>(jsonMeta.ToString()),
-                            Response = JsonConvert.DeserializeObject<T>(jsonResponse.ToString())
+                            Meta = jsonMeta.ToObject<Meta>(),
+                            Response = jsonResponse.ToObject<T>()
                         };
                 }
             }
@@ -139,8 +139,8 @@
                     return
                         new HttpResponse<T>
                         {
-                            Meta = JsonConvert.DeserializeObject<Meta>(jsonMeta.ToString()),
-                            Response = JsonConvert.DeserializeObject<T>(jsonResponse.ToString())
+                            Meta = jsonMeta.ToObject<Meta>(),
+                            Response = jsonResponse.ToObject<T>()
                         };
                 }
             }
@@ -170,8 +170,8 @@
                     return
                         new HttpResponse<T>
                         {
-                            Meta = JsonConvert.DeserializeObject<Meta>(jsonMeta.ToString()),
-                            Response = JsonConvert.DeserializeObject<T>(jsonResponse.ToString())
+                            Meta = jsonMeta.ToObject<Meta>(),
+                            Response = jsonResponse.ToObject<T>()
                         };
                 }
             }


Correctly update worker button and labels.

--- client/SmartFighter/Form.cs
+++ client/SmartFighter/Form.cs
@@ -7,7 +7,13 @@
     public partial class App : Form {
         private Connector connector;
         private BackgroundWorker apiWorker;
-        private BackgroundWorker hookWorker;
+        private BackgroundWorker connectorWorker;
+
+        private enum WorkerState {
+            Stopped,
+            Running,
+            Stopping,
+        };

         public App() {
             InitializeComponent();
@@ -17,30 +23,30 @@
             Config.load();

             connector = new Connector();
-            hookWorker = new BackgroundWorker();
-            hookWorker.WorkerSupportsCancellation = true;
-            hookWorker.DoWork += connector.run;
-            hookWorker.RunWorkerCompleted += (sender, args) => onConnectorExit((bool)args.Result);
-            connectorLabel.Text = "Running";
-            hookWorker.RunWorkerAsync();
+            connectorWorker = new BackgroundWorker();
+            connectorWorker.WorkerSupportsCancellation = true;
+            connectorWorker.DoWork += connector.run;
+            connectorWorker.RunWorkerCompleted += (sender, args) => onConnectorExit((bool)args.Result);
+            updateWorkerState(WorkerState.Running, connectorButton, connectorLabel);
+            connectorWorker.RunWorkerAsync();

             apiWorker = new BackgroundWorker();
             apiWorker.WorkerSupportsCancellation = true;
             apiWorker.DoWork += ApiQueue.run;
             apiWorker.RunWorkerCompleted += (sender, args) => onApiQueueExit();
-            apiLabel.Text = "Running";
+            updateWorkerState(WorkerState.Running, apiButton, apiLabel);
             apiWorker.RunWorkerAsync();
         }

         private void onConnectorExit(bool isSuccess) {
-            connectorLabel.Text = "Stopped";
+            updateWorkerState(WorkerState.Stopped, connectorButton, connectorLabel);
             if (!isSuccess) {
                 appendToLogs("Connector ended with errors.");
             }
         }

         private void onApiQueueExit() {
-            apiLabel.Text = "Stopped";
+            updateWorkerState(WorkerState.Stopped, apiButton, apiLabel);
         }

         public void appendToLogs(string message) {
@@ -52,26 +58,42 @@
         }

         private void connectorButton_Click(object sender, EventArgs e) {
-            if (hookWorker.CancellationPending) {
-                connectorLabel.Text = "Stopping...";
-            } else if (hookWorker.IsBusy) {
-                connectorLabel.Text = "Stopping...";
-                hookWorker.CancelAsync();
-            } else {
-                connectorLabel.Text = "Running";
-                hookWorker.RunWorkerAsync();
+            toggleWorkerState(connectorWorker, connectorButton, connectorLabel);
+        }
+
+        private void apiButton_Click(object sender, EventArgs e) {
+            toggleWorkerState(apiWorker, apiButton, apiLabel);
+        }
+
+        private void toggleWorkerState(BackgroundWorker worker, Button button, Label label) {
+            if (!worker.CancellationPending) {
+                if (worker.IsBusy) {
+                    updateWorkerState(WorkerState.Stopping, button, label);
+                    worker.CancelAsync();
+                } else {
+                    updateWorkerState(WorkerState.Running, button, label);
+                    worker.RunWorkerAsync();
+                }
             }
         }

-        private void apiButton_Click(object sender, EventArgs e) {
-            if (apiWorker.CancellationPending) {
-                apiLabel.Text = "Stopping...";
-            } else if (apiWorker.IsBusy) {
-                apiLabel.Text = "Stopping...";
-                apiWorker.CancelAsync();
-            } else {
-                apiLabel.Text = "Running";
-                apiWorker.RunWorkerAsync();
+        private void updateWorkerState(WorkerState state, Button button, Label label) {
+            switch (state) {
+                case WorkerState.Running:
+                    button.Text = "Stop";
+                    button.Enabled = true;
+                    label.Text = "Running";
+                    break;
+                case WorkerState.Stopping:
+                    button.Text = "Stop";
+                    button.Enabled = false;
+                    label.Text = "Stopping...";
+                    break;
+                case WorkerState.Stopped:
+                    button.Text = "Start";
+                    button.Enabled = true;
+                    label.Text = "Stopped";
+                    break;
             }
         }


Fix header

Fix header

--- ConektaSDK/Connection.cs
+++ ConektaSDK/Connection.cs
@@ -26,7 +26,7 @@
 			HttpRequestMessage requestMessage = new HttpRequestMessage (HttpMethod.Post, Conekta.BaseUri + EndPoint);

 			requestMessage.Headers.Authorization = new AuthenticationHeaderValue ("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:", Conekta.PublicKey))));
-			requestMessage.Headers.Add ("Acept", "application/vnd.conekta-v" + Conekta.ApiVersion + "+json");
+			requestMessage.Headers.Add ("Accept", "application/vnd.conekta-v" + Conekta.ApiVersion + "+json");

 			if(Platform == "Android")
 				requestMessage.Headers.Add ("Conekta-Client-User-Agent", @"{""agent"": ""Conekta Android SDK""}");


move some logics to new method

move some logics to new method


MeidoBot: Split out function from CommandFooter

Also update some formatting.


AutofacObjectBuilder: move more reflection to constructor

--- NsqSharp/Bus/Configuration/BuiltIn/AutofacObjectBuilder.cs
+++ NsqSharp/Bus/Configuration/BuiltIn/AutofacObjectBuilder.cs
@@ -16,9 +16,12 @@
         private readonly MethodInfo _registerInstanceMethod;
         private readonly MethodInfo _registerTypeMethod;
         private readonly MethodInfo _createRegistrationMethod;
-        private readonly MethodInfo _getComponentRegistryProperty;
+
         private readonly MethodInfo _tryResolveMethod;
         private readonly MethodInfo _resolveMethod;
+
+        private readonly object _componentRegistry;
+        private readonly MethodInfo _registerMethod;

         /// <summary>
         /// Initializes a new instance of the <see cref="AutofacObjectBuilder"/> class.
@@ -32,13 +35,20 @@

             _container = container;

+            //  Reference: https://groups.google.com/forum/#!topic/autofac/9OptOgmGqrQ
+
+            // get _container.ComponentRegistry getter
             var containerType = _container.GetType();
             var componentRegistryProperty = containerType.GetProperty("ComponentRegistry");
             if (componentRegistryProperty == null)
                 throw new Exception("Container.ComponentRegistry property not found");
-            _getComponentRegistryProperty = componentRegistryProperty.GetGetMethod();
-            if (_getComponentRegistryProperty == null)
+            var getComponentRegistryProperty = componentRegistryProperty.GetGetMethod();
+            if (getComponentRegistryProperty == null)
                 throw new Exception("Container.ComponentRegistry property getter not found");
+            _componentRegistry = getComponentRegistryProperty.Invoke(_container, null);
+            var componentRegistryType = _componentRegistry.GetType();
+            _registerMethod = componentRegistryType.GetMethods()
+                                  .Single(p => p.Name == "Register" && p.GetParameters().Length == 1);

             var autofacAssembly = _container.GetType().Assembly;

@@ -137,17 +147,12 @@
                 object componentRegistration = _registerTypeMethod.Invoke(null, new[] { containerBuilder, type });

                 // _container.ComponentRegistry.Register(componentRegistration.CreateRegistration());
-                var componentRegistry = _getComponentRegistryProperty.Invoke(_container, null);
-                var componentRegistryType = componentRegistry.GetType();
-                var registerMethod = componentRegistryType.GetMethods()
-                                        .Single(p => p.Name == "Register" && p.GetParameters().Length == 1);
-
                 var componentRegistrationType = componentRegistration.GetType();
                 var createRegistrationMethod = _createRegistrationMethod.MakeGenericMethod(
                                                    componentRegistrationType.GenericTypeArguments
                                                );
-                var registration = createRegistrationMethod.Invoke(componentRegistry, new[] { componentRegistration });
-                registerMethod.Invoke(componentRegistry, new[] { registration });
+                var registration = createRegistrationMethod.Invoke(_componentRegistry, new[] { componentRegistration });
+                _registerMethod.Invoke(_componentRegistry, new[] { registration });

                 // return _container.Resolve(type);
                 var result = _resolveMethod.Invoke(null, new[] { _container, type });
@@ -166,25 +171,20 @@
             lock (_containerLocker)
             {
                 // Autofac equivalent:
-                //   var cb = new ContainerBuilder().RegisterInstance(instance).As<T>();
-                //   _container.ComponentRegistry.Register(cb.CreateRegistration());
+                //   var componentRegistration = new ContainerBuilder().RegisterInstance<T>(instance)();
+                //   _container.ComponentRegistry.Register(componentRegistration.CreateRegistration());

                 var containerBuilder = Activator.CreateInstance(_containerBuilderType);
                 var registerInstanceMethod = _registerInstanceMethod.MakeGenericMethod(typeof(T));
                 var componentRegistration = registerInstanceMethod.Invoke(null, new[] { containerBuilder, instance });
-
-                var componentRegistry = _getComponentRegistryProperty.Invoke(_container, null);
-                var componentRegistryType = componentRegistry.GetType();
-                var registerMethod = componentRegistryType.GetMethods()
-                    .Single(p => p.Name == "Register" && p.GetParameters().Length == 1);

                 var componentRegistrationType = componentRegistration.GetType();

                 var createRegistrationMethod = _createRegistrationMethod.MakeGenericMethod(
                                                    componentRegistrationType.GenericTypeArguments
                                                );
-                var registration = createRegistrationMethod.Invoke(componentRegistry, new[] { componentRegistration });
-                registerMethod.Invoke(componentRegistry, new[] { registration });
+                var registration = createRegistrationMethod.Invoke(_componentRegistry, new[] { componentRegistration });
+                _registerMethod.Invoke(_componentRegistry, new[] { registration });
             }
         }
     }


change GetTextureModule processing

change GetTextureModule processing

--- OpenSim/Region/ClientStack/Linden/Caps/GetTextureModule.cs
+++ OpenSim/Region/ClientStack/Linden/Caps/GetTextureModule.cs
@@ -53,6 +53,14 @@
     [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "GetTextureModule")]
     public class GetTextureModule : INonSharedRegionModule
     {
+
+        struct aPollRequest
+        {
+            public PollServiceTextureEventArgs thepoll;
+            public UUID reqID;
+            public Hashtable request;
+        }
+
         private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

         private Scene m_scene;
@@ -64,8 +72,8 @@
         private Dictionary<UUID, string> m_capsDict = new Dictionary<UUID, string>();
         private static Thread[] m_workerThreads = null;

-        private static OpenMetaverse.BlockingQueue<PollServiceTextureEventArgs> m_queue =
-                new OpenMetaverse.BlockingQueue<PollServiceTextureEventArgs>();
+        private static OpenMetaverse.BlockingQueue<aPollRequest> m_queue =
+                new OpenMetaverse.BlockingQueue<aPollRequest>();

         #region ISharedRegionModule Members

@@ -104,7 +112,7 @@
                             String.Format("TextureWorkerThread{0}", i),
                             ThreadPriority.Normal,
                             false,
-                            true,
+                            false,
                             null,
                             int.MaxValue);
                 }
@@ -129,7 +137,8 @@
         ~GetTextureModule()
         {
             foreach (Thread t in m_workerThreads)
-                t.Abort();
+                Watchdog.AbortThread(t.ManagedThreadId);
+
         }

         private class PollServiceTextureEventArgs : PollServiceEventArgs
@@ -142,7 +151,12 @@
             private Scene m_scene;

             public PollServiceTextureEventArgs(UUID pId, Scene scene) :
-                    base(null, null, null, null, pId, 30000)
+                    base(null, null, null, null, pId, int.MaxValue)
+                // this should never timeout
+                // each request must be processed and return a response
+                // noevents can possible be use for nice shutdown, but not sure now
+                // the execution will provide a proper response even if it fails
+
             {
                 m_scene = scene;

@@ -164,13 +178,15 @@

                 Request = (x, y) =>
                 {
-                    y["RequestID"] = x.ToString();
-                    lock (requests)
-                        requests.Add(y);
-
-                    m_queue.Enqueue(this);
+                    aPollRequest reqinfo = new aPollRequest();
+                    reqinfo.thepoll = this;
+                    reqinfo.reqID = x;
+                    reqinfo.request = y;
+
+                    m_queue.Enqueue(reqinfo);
                 };

+                // this should never happen except possible on shutdown
                 NoEvents = (x, y) =>
                 {
                     lock (requests)
@@ -191,27 +207,14 @@
                 };
             }

-            public void Process()
+            public void Process(aPollRequest requestinfo)
             {
                 Hashtable response;
-                Hashtable request = null;
-
-                try
-                {
-                    lock (requests)
-                    {
-                        request = requests[0];
-                        requests.RemoveAt(0);
-                    }
-                }
-                catch
-                {
-                    return;
-                }
-
-                UUID requestID = new UUID(request["RequestID"].ToString());
+
+                UUID requestID = requestinfo.reqID;

                 // If the avatar is gone, don't bother to get the texture
+
                 if (m_scene.GetScenePresence(Id) == null)
                 {
                     response = new Hashtable();
@@ -228,7 +231,7 @@
                     return;
                 }

-                response = m_getTextureHandler.Handle(request);
+                response = m_getTextureHandler.Handle(requestinfo.request);
                 lock (responses)
                     responses[requestID] = response;
             }
@@ -275,11 +278,10 @@
         {
             while (true)
             {
-                PollServiceTextureEventArgs args = m_queue.Dequeue();
-
-                args.Process();
+                aPollRequest poolreq = m_queue.Dequeue();
+
+                poolreq.thepoll.Process(poolreq);
             }
         }
     }
-
 }


Launch build

Launch build

--- OpenXMLSDK.UnitTests/ReportEngine/ReportEngineUnitTests.cs
+++ OpenXMLSDK.UnitTests/ReportEngine/ReportEngineUnitTests.cs
@@ -12,4 +12,3 @@
         }
     }
 }
-


UnitTests: Add missing clause which fixes osx/linux builds.

--- test/BaristaLabs.BaristaCore.Tests/JavaScript/ICommonWindowsScriptEngine_Facts.cs
+++ test/BaristaLabs.BaristaCore.Tests/JavaScript/ICommonWindowsScriptEngine_Facts.cs
@@ -373,6 +373,9 @@
         [Fact]
         public void JsCanGetPropertyIdFromName()
         {
+            if (CommonWindowsEngine == null)
+                return;
+
             using (var runtimeHandle = Engine.JsCreateRuntime(JavaScriptRuntimeAttributes.None, null))
             {
                 using (var contextHandle = Engine.JsCreateContext(runtimeHandle))
@@ -389,6 +392,9 @@
         [Fact]
         public void JsCanGetNameFromPropertyId()
         {
+            if (CommonWindowsEngine == null)
+                return;
+
             using (var runtimeHandle = Engine.JsCreateRuntime(JavaScriptRuntimeAttributes.None, null))
             {
                 using (var contextHandle = Engine.JsCreateContext(runtimeHandle))


remove Beta 1 note

remove Beta 1 note

--- API/BooksODataService/BooksODataService/Startup.cs
+++ API/BooksODataService/BooksODataService/Startup.cs
@@ -9,8 +9,6 @@
 using Microsoft.Extensions.Configuration;
 using Microsoft.Extensions.DependencyInjection;
 using Microsoft.OData.Edm;
-
-// OData Beta 1 docu http://odata.github.io/WebApi/#14-01-netcore-beta1

 namespace BooksODataService
 {


Making panes slightly less transparent

Making panes slightly less transparent

--- Ao3TrackReader/Ao3TrackReader/Controls/PaneView.cs
+++ Ao3TrackReader/Ao3TrackReader/Controls/PaneView.cs
@@ -37,7 +37,7 @@
         {
             TranslationX = old_width = 480;
             WidthRequest = old_width;
-            BackgroundColor = Ao3TrackReader.Resources.Colors.Alt.Trans.High;
+            BackgroundColor = Ao3TrackReader.Resources.Colors.Alt.Trans.VeryHigh;
             //IsVisible = false;
         }


Use the cluster id of the user when fetched the cluster coordinators.

The cluster coordinators were not shown in the list of commitments when
the user belonged to a cluster other than id 1.

--- crisischeckin/crisicheckinweb/Controllers/HomeController.cs
+++ crisischeckin/crisicheckinweb/Controllers/HomeController.cs
@@ -87,8 +87,10 @@
             var commitments = (person != null) ?
                 _volunteerSvc.RetrieveCommitments(person.Id, true) :
                 new List<Commitment>().AsEnumerable();
-
-            var clusterCoordinators = _clusterCoordinatorService.GetAllCoordinatorsForCluster(1).ToList();
+
+            var clusterCoordinators = (person != null && person.ClusterId.HasValue) ?
+                _clusterCoordinatorService.GetAllCoordinatorsForCluster(person.ClusterId.Value).ToList() :
+                new List<ClusterCoordinator>().AsEnumerable();

             var model = new VolunteerViewModel
             {