WebServiceTarget - JsonPost with support for single nameless parameter

--- src/NLog/Targets/WebServiceTarget.cs
+++ src/NLog/Targets/WebServiceTarget.cs
@@ -323,7 +323,7 @@
             DoInvoke(parameters, continuation, request, begin, getStream);
         }

-        internal void DoInvoke(object[] parameters, AsyncContinuation continuation, HttpWebRequest request, Func<AsyncCallback, IAsyncResult> beginFunc,
+        internal void DoInvoke(object[] parameters, AsyncContinuation continuation, HttpWebRequest request, Func<AsyncCallback, IAsyncResult> beginFunc,
             Func<IAsyncResult, Stream> getStreamFunc)
         {
             Stream postPayload = null;
@@ -490,7 +490,8 @@
             using (var targetBuilder = OptimizeBufferReuse ? ReusableLayoutBuilder.Allocate() : ReusableLayoutBuilder.None)
             {
                 StringBuilder sb = targetBuilder.Result ?? new StringBuilder();
-                BuildWebServiceQueryParameters(parameterValues, sb);
+                UrlHelper.EscapeEncodingFlag encodingFlags = UrlHelper.GetUriStringEncodingFlags(EscapeDataNLogLegacy, false, EscapeDataRfc3986);
+                BuildWebServiceQueryParameters(parameterValues, sb, encodingFlags);
                 queryParameters = sb.ToString();
             }

@@ -509,10 +510,8 @@
             return builder.Uri;
         }

-        private void BuildWebServiceQueryParameters(object[] parameterValues, StringBuilder sb)
-        {
-            UrlHelper.EscapeEncodingFlag encodingFlags = UrlHelper.GetUriStringEncodingFlags(EscapeDataNLogLegacy, false, EscapeDataRfc3986);
-
+        private void BuildWebServiceQueryParameters(object[] parameterValues, StringBuilder sb, UrlHelper.EscapeEncodingFlag encodingFlags)
+        {
             string separator = string.Empty;
             for (int i = 0; i < Parameters.Count; i++)
             {
@@ -607,18 +606,9 @@

             protected override string ContentType => "application/x-www-form-urlencoded";

-            protected override string Separator => "&";
-
-            protected override void AppendFormattedParameter(StringBuilder builder, MethodCallParameter parameter, object value)
-            {
-                builder.Append(parameter.Name);
-                builder.Append('=');
-
-                string parameterValue = XmlHelper.XmlConvertToString(value);
-                if (!string.IsNullOrEmpty(parameterValue))
-                {
-                    UrlHelper.EscapeDataEncode(parameterValue, builder, _encodingFlags);
-                }
+            protected override void WriteStringContent(StringBuilder builder, object[] parameterValues)
+            {
+                Target.BuildWebServiceQueryParameters(parameterValues, builder, _encodingFlags);
             }
         }

@@ -633,24 +623,29 @@

             protected override string ContentType => "application/json";

-            protected override string Separator => ",";
-
-            protected override void BeginFormattedMessage(StringBuilder builder)
-            {
-                builder.Append('{');
-            }
-
-            protected override void EndFormattedMessage(StringBuilder builder)
-            {
-                builder.Append('}');
-            }
-
-            protected override void AppendFormattedParameter(StringBuilder builder, MethodCallParameter parameter, object value)
-            {
-                builder.Append('"');
-                builder.Append(parameter.Name);
-                builder.Append("\":");
-                JsonConverter.SerializeObject(value, builder);
+            protected override void WriteStringContent(StringBuilder builder, object[] parameterValues)
+            {
+                if (Target.Parameters.Count == 1 && string.IsNullOrEmpty(Target.Parameters[0].Name) && parameterValues[0] is string)
+                {
+                    // JsonPost with single nameless parameter means complex JsonLayout
+                    builder.Append((string)parameterValues[0]);
+                }
+                else
+                {
+                    builder.Append("{");
+                    string separator = string.Empty;
+                    for (int i = 0; i < Target.Parameters.Count; ++i)
+                    {
+                        var parameter = Target.Parameters[i];
+                        builder.Append(separator);
+                        builder.Append('"');
+                        builder.Append(parameter.Name);
+                        builder.Append("\":");
+                        JsonConverter.SerializeObject(parameterValues[i], builder);
+                        separator = ",";
+                    }
+                    builder.Append('}');
+                }
             }
         }

@@ -733,35 +728,13 @@
                 _encodingPreamble = target.Encoding.GetPreamble();
             }

-            protected abstract string Separator { get; }
-
-            protected virtual void BeginFormattedMessage(StringBuilder builder)
-            {
-            }
-
-            protected abstract void AppendFormattedParameter(StringBuilder builder, MethodCallParameter parameter, object value);
-
-            protected virtual void EndFormattedMessage(StringBuilder builder)
-            {
-            }
-
             protected override void WriteContent(MemoryStream ms, object[] parameterValues)
             {
                 lock (_reusableStringBuilder)
                 {
                     using (var targetBuilder = _reusableStringBuilder.Allocate())
                     {
-                        bool first = true;
-                        BeginFormattedMessage(targetBuilder.Result);
-                        for (int i = 0; i < Target.Parameters.Count; i++)
-                        {
-                            if (!first)
-                                targetBuilder.Result.Append(Separator);
-                            else
-                                first = false;
-                            AppendFormattedParameter(targetBuilder.Result, Target.Parameters[i], parameterValues[i]);
-                        }
-                        EndFormattedMessage(targetBuilder.Result);
+                        WriteStringContent(targetBuilder.Result, parameterValues);

                         using (var transformBuffer = _reusableEncodingBuffer.Allocate())
                         {
@@ -772,6 +745,8 @@
                     }
                 }
             }
+
+            protected abstract void WriteStringContent(StringBuilder sb, object[] parameterValues);
         }

         private class HttpPostXmlDocumentFormatter : HttpPostXmlFormatterBase


Added XML comments and more constructors for ProtoDataStream.

--- src/ProtoBuf.Data/ProtoDataStream.cs
+++ src/ProtoBuf.Data/ProtoDataStream.cs
@@ -25,7 +25,7 @@
     /// to <see cref="Read"/>). Useful for scenarios like WCF where you cannot
     /// write to the output stream directly.
     ///</summary>
-    /// <remarks>Not guaranteed to be thread safe.</remarks>
+    ///<remarks>Not guaranteed to be thread safe.</remarks>
     public class ProtoDataStream : Stream
     {
         public const int DefaultBufferSize = 80 * 1024;
@@ -43,6 +43,45 @@
         private SubItemToken currentResultToken;
         private bool readerIsClosed;

+        /// <summary>
+        /// Initializes a new instance of the <see cref="ProtoDataStream"/> class.
+        /// </summary>
+        /// <param name="dataSet">The <see cref="DataSet"/>who's contents to serialize.</param>
+        /// <param name="bufferSize">Buffer size to use when serializing rows.
+        /// You should not need to change this unless you have exceptionally
+        /// large rows or an exceptionally high number of columns.</param>
+        public ProtoDataStream(
+            DataSet dataSet,
+            int bufferSize = DefaultBufferSize)
+            : this(dataSet.CreateDataReader(),
+                   new ProtoDataWriterOptions(),
+                   bufferSize)
+        {
+        }
+
+        /// <summary>
+        /// Initializes a new instance of the <see cref="ProtoDataStream"/> class.
+        /// </summary>
+        /// <param name="dataSet">The <see cref="DataSet"/>who's contents to serialize.</param>
+        /// <param name="options"><see cref="ProtoDataWriterOptions"/> specifying any custom serialization options.</param>
+        /// <param name="bufferSize">Buffer size to use when serializing rows.
+        /// You should not need to change this unless you have exceptionally
+        /// large rows or an exceptionally high number of columns.</param>
+        public ProtoDataStream(
+            DataSet dataSet,
+            ProtoDataWriterOptions options,
+            int bufferSize = DefaultBufferSize)
+            : this(dataSet.CreateDataReader(), options, bufferSize)
+        {
+        }
+
+        /// <summary>
+        /// Initializes a new instance of the <see cref="ProtoDataStream"/> class.
+        /// </summary>
+        /// <param name="dataTable">The <see cref="DataTable"/>who's contents to serialize.</param>
+        /// <param name="bufferSize">Buffer size to use when serializing rows.
+        /// You should not need to change this unless you have exceptionally
+        /// large rows or an exceptionally high number of columns.</param>
         public ProtoDataStream(
             DataTable dataTable,
             int bufferSize = DefaultBufferSize)
@@ -52,13 +91,42 @@
         {
         }

-        public ProtoDataStream(DataTable dataTable,
-            ProtoDataWriterOptions options, int bufferSize = DefaultBufferSize)
-            : this(dataTable.CreateDataReader(), options, bufferSize) { }
-
+        /// <summary>
+        /// Initializes a new instance of the <see cref="ProtoDataStream"/> class.
+        /// </summary>
+        /// <param name="dataTable">The <see cref="DataTable"/>who's contents to serialize.</param>
+        /// <param name="options"><see cref="ProtoDataWriterOptions"/> specifying any custom serialization options.</param>
+        /// <param name="bufferSize">Buffer size to use when serializing rows.
+        /// You should not need to change this unless you have exceptionally
+        /// large rows or an exceptionally high number of columns.</param>
+        public ProtoDataStream(
+            DataTable dataTable,
+            ProtoDataWriterOptions options,
+            int bufferSize = DefaultBufferSize)
+            : this(dataTable.CreateDataReader(), options, bufferSize)
+        {
+        }
+
+        /// <summary>
+        /// Initializes a new instance of the <see cref="ProtoDataStream"/> class.
+        /// </summary>
+        /// <param name="reader">The <see cref="IDataReader"/>who's contents to serialize.</param>
+        /// <param name="bufferSize">Buffer size to use when serializing rows.
+        /// You should not need to change this unless you have exceptionally
+        /// large rows or an exceptionally high number of columns.</param>
         public ProtoDataStream(IDataReader reader, int bufferSize = DefaultBufferSize)
-            : this(reader, new ProtoDataWriterOptions(), bufferSize) { }
-
+            : this(reader, new ProtoDataWriterOptions(), bufferSize)
+        {
+        }
+
+        /// <summary>
+        /// Initializes a new instance of the <see cref="ProtoDataStream"/> class.
+        /// </summary>
+        /// <param name="reader">The <see cref="IDataReader"/>who's contents to serialize.</param>
+        /// <param name="options"><see cref="ProtoDataWriterOptions"/> specifying any custom serialization options.</param>
+        /// <param name="bufferSize">Buffer size to use when serializing rows.
+        /// You should not need to change this unless you have exceptionally
+        /// large rows or an exceptionally high number of columns.</param>
         public ProtoDataStream(
             IDataReader reader,
             ProtoDataWriterOptions options,


TypedReference の問題、修正掛かってた

TypedReference の問題、修正掛かってた

--- Demo/2017/Csharp7_2-1012/ConsoleApp1/SpanSafety.cs
+++ Demo/2017/Csharp7_2-1012/ConsoleApp1/SpanSafety.cs
@@ -44,14 +44,12 @@
                 await Task.Delay(1);
                 s2[0] = 1;
             }
-#endif

             // 余談: TypedReference 型も、今思えば、分類としては ref struct になるんだけど
-            // TypedReference が出来た当時にはこの概念がなかったのと、今更破壊的変更してまで TypedReference に safety ルール適用するほど需要がないので、そのままらしい
-
+            // C# 7.1 まで、仕様漏れでまずい状態だったらしい
             TypedReference tr = __makeref(x);
-
-            Func<int> a2 = () => __refvalue(tr, int); // 本来、まずい。要はコンパイラーの仕様漏れ
+            Func<int> a2 = tr.GetHashCode; // C# 7.1 まではコンパイルできてた。本来、まずい。要はコンパイラーの仕様漏れ
+#endif
         }

         #region C# 7.0 で参照戻り値追加


Version Bump

Version Bump

--- letsencrypt-win-simple/Properties/AssemblyInfo.cs
+++ letsencrypt-win-simple/Properties/AssemblyInfo.cs
@@ -35,5 +35,5 @@
 // by using the '*' as shown below:
 // [assembly: AssemblyVersion("1.0.*")]

-[assembly: AssemblyVersion("1.8.9.*")]
-[assembly: AssemblyFileVersion("1.8.9.2")]+[assembly: AssemblyVersion("1.9.0.*")]
+[assembly: AssemblyFileVersion("1.9.0.1")]


Updated valid bank codes

Updated valid bank codes


Exam Projects update

Exam Projects update

--- NUM1/Program.cs
+++ NUM1/Program.cs
@@ -15,19 +15,19 @@
             var excluding = char.Parse(Console.ReadLine());
             int cnt = 0;

-            for (var i = firstLetter; i <= secondLetter; i++)
+            for (var o = firstLetter; o <= secondLetter; o++)
             {
                 for (var j = firstLetter; j <= secondLetter; j++)
                 {
                     for (var k = firstLetter; k <= secondLetter; k++)
                     {
-                        if (excluding == i
+                        if (excluding == o
                             || excluding == j
                             || excluding == k)
                         {
                             continue;
                         }
-                        Console.Write($"{i}{j}{k} ");
+                        Console.Write($"{o}{j}{k} ");
                         cnt++;
                     }
                 }


git-svn-id: 21cdf44b51306c1f0753fc51e774ecf5fc1851ba@1842 a61f9e97-bd4c-0410-8c65-85b29eaa70ff

--- Dorian/Gorgon/Gorgon.Graphics/IO/GorgonCodecTGA.cs
+++ Dorian/Gorgon/Gorgon.Graphics/IO/GorgonCodecTGA.cs
@@ -1062,7 +1062,7 @@
 			var scanSize = (int)(stream.Length - stream.Position);
 			byte* endScan = (byte*)stream.PositionPointerUnsafe + scanSize;

-			int opaqueLineCount = image.Settings.Height;
+			int opaqueLineCount = 0;
 			for (int y = 0; y < image.Settings.Height; y++)
 			{
 				bool setOpaque;
@@ -1079,7 +1079,7 @@

 				if ((setOpaque) && (SetOpaqueIfZeroAlpha))
 				{
-					opaqueLineCount--;
+					opaqueLineCount++;
 				}

 				if ((conversionFlags & TGAConversionFlags.InvertY) != TGAConversionFlags.InvertY)
@@ -1102,6 +1102,7 @@
 			for (int y = 0; y < image.Settings.Height; y++)
 			{
 				CopyScanline(destPtr, buffer.PitchInformation.RowPitch, destPtr, buffer.PitchInformation.RowPitch, image.Settings.Format, ImageBitFlags.OpaqueAlpha);
+				destPtr += buffer.PitchInformation.RowPitch;
 			}
 		}


Make sure we save queries where appropriate even if they return cached results (http://meta.stackoverflow.com/q/107076)

--- App/StackExchange.DataExplorer/Helpers/QueryRunner.cs
+++ App/StackExchange.DataExplorer/Helpers/QueryRunner.cs
@@ -191,16 +191,24 @@
             return json;
         }

-        public static string GetCachedResults(ParsedQuery query, Site site)
-        {
-            CachedResult row = Current.DB.CachedResults
-                .Where(result => result.QueryHash == query.ExecutionHash && result.SiteId == site.Id)
-                .FirstOrDefault();
-            string results = null;
-            if (row != null)
-            {
-                results = row.Results;
-            }
+        public static QueryResults GetCachedResults(ParsedQuery query, Site site)
+        {
+            CachedResult cache = Current.DB.Query<Models.CachedResult>(
+                "SELECT * FROM CachedResults WHERE QueryHash = @hash AND SiteId = @siteId",
+                new
+                {
+                    hash = query.ExecutionHash,
+                    siteId = site.Id
+                }
+            ).FirstOrDefault();
+
+            QueryResults results = null;
+
+            if (cache != null && cache.Results != null)
+            {
+                results = QueryResults.FromJson(cache.Results);
+            }
+
             return results;
         }

@@ -503,23 +511,26 @@
         public static string GetJson(ParsedQuery parsedQuery, Site site, User user, bool IncludeExecutionPlan)
         {
             DBContext db = Current.DB;
-            UpdateSavedQuery(user, parsedQuery);
-
-            var cachedJson = GetCachedResults(parsedQuery, site);
-            if (cachedJson != null)
+
+            var cache = GetCachedResults(parsedQuery, site);
+
+            VerifyQueryState(parsedQuery, cache, user);
+
+            if (cache != null)
             {
                 if (!IncludeExecutionPlan)
                 {
-                    return cachedJson;
+                    return cache.ToJson();
                 }
                 else
                 {
                     var plan = GetCachedPlan(parsedQuery, site);
+
                     if (plan != null)
                     {
-                        var queryResults = QueryResults.FromJson(cachedJson);
-                        queryResults.ExecutionPlan = plan.Plan;
-                        return queryResults.ToJson();
+                        cache.ExecutionPlan = plan.Plan;
+
+                        return cache.ToJson();
                     }
                 }
             }
@@ -527,10 +538,12 @@
             QueryResults results = ExecuteNonCached(parsedQuery, site, user, IncludeExecutionPlan);

             string json = results.ToJson();
-            if (cachedJson == null)
+
+            if (cache == null)
             {
                 AddResultToCache(json, parsedQuery, site, db, IncludeExecutionPlan);
             }
+
             if (IncludeExecutionPlan)
             {
                 db.CachedPlans.InsertOnSubmit(new CachedPlan()
@@ -546,6 +559,97 @@

             // well there is an annoying XSS condition here
             return json.Replace("/", "\\/");
+        }
+
+        /// <summary>
+        /// Verifies that the cached set of results are correct for this particular query,
+        /// addressing the case where many queries may produce the same execution SQL, but may
+        /// have differing parameter names.
+        /// </summary>
+        /// <param name="parsedQuery">The current query that produces the results in the
+        /// cache</param>
+        /// <param name="cache">The cached results for a query semantically equivalent to the
+        /// provided one</param>
+        /// <param name="user"></param>
+        private static void VerifyQueryState(ParsedQuery parsedQuery, QueryResults cache, User user)
+        {
+            Query query = Current.DB.Query<Query>(
+                "SELECT * FROM Queries WHERE QueryHash = @hash",
+                new
+                {
+                    hash = parsedQuery.Hash
+                }
+            ).FirstOrDefault();
+
+            // Check if the parsed query is actually responsible for this cache
+            if (cache != null)
+            {
+                int id;
+
+                // If the query doesn't exist, now is the only time it'll get created since it
+                // corresponds to a pre-existing cache result (but isn't actually what generated
+                // the result set)
+                if (query == null)
+                {
+                    id = (int)Current.DB.Query<decimal>(@"
+                        INSERT INTO Queries(
+                            CreatorId, CreatorIP, FirstRun, Name,
+                            Description, QueryBody, QueryHash, Views
+                        ) VALUES(
+                            @CreatorId, @CreatorIP, @FirstRun, @Name,
+                            @Description, @QueryBody, @QueryHash, @Views
+                        )
+
+                        SELECT SCOPE_IDENTITY()",
+                        new
+                        {
+                            CreatorId = user.IsAnonymous ? (int?)null : user.Id,
+                            CreatorIP = user.IPAddress,
+                            FirstRun = DateTime.UtcNow,
+                            Name = parsedQuery.Name,
+                            Description = parsedQuery.Description,
+                            QueryBody = parsedQuery.RawSql,
+                            QueryHash = parsedQuery.Hash,
+                            Views = 0
+                        }
+                    ).First();
+                }
+                else
+                {
+                    id = query.Id;
+                }
+
+                // Update the cache's query ID to lie to the client that these results came from
+                // this specific query
+                if (id != cache.QueryId)
+                {
+                    cache.QueryId = id;
+                }
+            }
+
+            // Update the important bits of the query if we didn't just insert it, provided that
+            // the user isn't anonymous.
+            if (query != null && !user.IsAnonymous)
+            {
+                // Save ourselves the trouble of updating if nothing's changed
+                if (query.Name != parsedQuery.Name || query.Description != parsedQuery.Description || query.QueryBody != query.QueryBody)
+                {
+                    Current.DB.Execute(@"
+                        UPDATE Queries SET
+                            Name = @name,
+                            Description = @description,
+                            QueryBody = @sql
+                        WHERE QueryHash = @hash",
+                        new
+                        {
+                            name = parsedQuery.Name,
+                            description = parsedQuery.Description,
+                            sql = parsedQuery.RawSql,
+                            hash = parsedQuery.Hash
+                        }
+                    );
+                }
+            }
         }

         /// <summary>
@@ -571,29 +675,6 @@
                 CreationDate = DateTime.UtcNow
             };
             db.CachedResults.InsertOnSubmit(cache);
-        }
-
-        /// <summary>
-        /// Updates a saved query if it exists and the user is not anonymous.
-        /// </summary>
-        private static void UpdateSavedQuery(User user, ParsedQuery parsedQuery)
-        {
-            DBContext db = Current.DB;
-
-            // update the query if its not anon
-            if (!user.IsAnonymous)
-            {
-                Query query = db.Queries
-                    .Where(q => q.QueryHash == parsedQuery.Hash)
-                    .FirstOrDefault();
-                if (query != null)
-                {
-                    query.Description = parsedQuery.Description;
-                    query.Name = parsedQuery.Name;
-                    query.QueryBody = parsedQuery.RawSql;
-                    db.SubmitChanges();
-                }
-            }
         }

         private static void ProcessMagicColumns(QueryResults results, SqlConnection cnn)


Hook up enter keypress to login action in LoginPrompt

--- EndlessClient/ControlSets/LoginPromptControlSet.cs
+++ EndlessClient/ControlSets/LoginPromptControlSet.cs
@@ -102,18 +102,20 @@

 		private XNATextBox GetLoginUserNameTextBox()
 		{
-			return new XNATextBox(new Rectangle(402, 322, 140, _textBoxTextures[0].Height), _textBoxTextures, Constants.FontSize08)
+			var textBox = new XNATextBox(new Rectangle(402, 322, 140, _textBoxTextures[0].Height), _textBoxTextures, Constants.FontSize08)
 			{
 				MaxChars = 16,
 				DefaultText = "Username",
 				LeftPadding = 4,
 				DrawOrder = _personPicture.DrawOrder + 2
 			};
+			textBox.OnEnterPressed += DoLogin;
+			return textBox;
 		}

 		private XNATextBox GetLoginPasswordTextBox()
 		{
-			return new XNATextBox(new Rectangle(402, 358, 140, _textBoxTextures[0].Height), _textBoxTextures, Constants.FontSize08)
+			var textBox = new XNATextBox(new Rectangle(402, 358, 140, _textBoxTextures[0].Height), _textBoxTextures, Constants.FontSize08)
 			{
 				MaxChars = 12,
 				PasswordBox = true,
@@ -121,6 +123,8 @@
 				DefaultText = "Password",
 				DrawOrder = _personPicture.DrawOrder + 2
 			};
+			textBox.OnEnterPressed += DoLogin;
+			return textBox;
 		}

 		private XNAButton GetLoginAccountButton()


deleted some legacy code

deleted some legacy code

--- platform/wp7/RhoRubyLib/rubyext/RhoDatabase.cs
+++ platform/wp7/RhoRubyLib/rubyext/RhoDatabase.cs
@@ -91,7 +91,6 @@
                                 if (colNames == null)
                                     colNames = getOrigColNames(rows);

-                                String f = rows.getRubyValueByIdx(nCol).ToString();
                                 row.Add(colNames[nCol], MutableString.Create(rows.getRubyValueByIdx(nCol).ToString()));
                             }
                             retArr.Add(row);


Add Average Disease Freq. :mask: close #19 ; will not implement filter as it is biome only related.

--- src/TabInfo.cs
+++ src/TabInfo.cs
@@ -71,23 +71,24 @@
                     stringBuilder.AppendLine(
                         $"Tiles with Roads: {PrepareLanding.Instance.TileFilter.AllTilesWithRoad.Count}");

-                stringBuilder.AppendLine("Biomes: (number of tiles)");
+                stringBuilder.AppendLine("Biomes:");
                 var biomes = _gameData.DefData.BiomeDefs;
-
-                //var biomeNames = biomes.Select(biome => biome.LabelCap).ToList();
-                //var longestBiomeName = biomeNames.Aggregate("", (max, cur) => max.Length > cur.Length ? max : cur).Length;

                 foreach (var biome in biomes)
                 {
+                    stringBuilder.AppendLine($"    * {biome.LabelCap}");
                     var count = _gameData.WorldData.NumberOfTilesByBiome[biome];
-                    //stringBuilder.AppendLine($"    {biome.LabelCap.PadRight(longestBiomeName)} ➠ {count}");
-                    stringBuilder.AppendLine($"    {biome.LabelCap} ➠ {count}");
+                    stringBuilder.AppendLine($"        - Number of Tiles ➠ {count}");
+                    stringBuilder.AppendLine($"        - {"AverageDiseaseFrequency".Translate()} ➠ {(RimWorld.GenDate.DaysPerYear / biome.diseaseMtbDays):F1} {"PerYear".Translate()}");
                 }
             }

             /*
              * Highest / lowest value for all characteristics.
              */
+
+            var separator = "-".Repeat(80);
+            stringBuilder.AppendLine($"\n{separator}\nWorld Records\n{separator}");

             foreach (var characteristicData in _gameData.WorldData.WorldCharacteristics)
             {


priceStreaming changed

priceStreaming changed

--- src/priceStreaming.cs
+++ src/priceStreaming.cs
@@ -31,6 +31,11 @@
     public class getAuthorizationChallengeRequest
     {
         public string user { get; set; }
+
+        public getAuthorizationChallengeRequest(String user)
+        {
+            this.user = user;
+        }
     }

     public class getAuthorizationChallengeResponse
@@ -43,6 +48,12 @@
     {
         public string user { get; set; }
         public string challengeresp { get; set; }
+
+        public getAuthorizationTokenRequest(String user, String challengeresp)
+        {
+            this.user = user;
+            this.challengeresp = challengeresp;
+        }
     }

     public class getAuthorizationTokenResponse
@@ -53,10 +64,24 @@

     public class getPriceRequest
     {
-        public string        user { get; set; }
-        public string        token { get; set; }
-        public List<string>  security { get; set; }
-        public List<string>  tinterface { get; set; }
+        public string user { get; set; }
+        public string token { get; set; }
+        public List<string> security { get; set; }
+        public List<string> tinterface { get; set; }
+        public String granularity { get; set; }
+        public int levels { get; set; }
+        public int interval { get; set; }
+
+        public getPriceRequest(String user, String token, List<String> security, List<String> tinterface, String granularity, int levels, int interval)
+        {
+            this.user = user;
+            this.token = token;
+            this.security = security;
+            this.tinterface = tinterface;
+            this.granularity = granularity;
+            this.levels = levels;
+            this.interval = interval;
+        }
     }

     public class getPriceResponse
@@ -121,25 +146,6 @@
                    client.DownloadFile(ssl_cert, "ssl.cert");
                 }
                 certificate1 = new X509Certificate("ssl.cert");
-
-
-                /*
-                var webRequest = WebRequest.Create(ssl_cert);
-
-                var response2 = webRequest.GetResponse();
-                var content = response2.GetResponseStream();
-                var reader = new StreamReader(content);
-                var strContent = reader.ReadToEnd();
-                X509Certificate2 cert3 = new X509Certificate2(new String(reader));
-
-                HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://mail.google.com");
-                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
-                response.Close();
-                X509Certificate cert = request.ServicePoint.Certificate;
-                X509Certificate2 cert2 = new X509Certificate2(cert);
-                //X509Certificate2UI.DisplayCertificate(cert2);
-                 */
-
             }

             // get challenge
@@ -154,8 +160,7 @@
             using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
             {
                 hftRequest request = new hftRequest();
-                request.getAuthorizationChallenge = new getAuthorizationChallengeRequest();
-                request.getAuthorizationChallenge.user = user;
+                request.getAuthorizationChallenge = new getAuthorizationChallengeRequest(user);
                 streamWriter.WriteLine(serializer.Serialize(request));
             }
             httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
@@ -192,7 +197,7 @@
             challengeresp = challengeresp.Replace("-", "");

             // get token with challenge response
-            httpWebRequest = (HttpWebRequest)WebRequest.Create(domain + ":" + authentication_port + url_token);
+            httpWebRequest = (HttpWebRequest)WebRequest.Create(domain + "2:" + authentication_port + url_token);
             serializer = new JavaScriptSerializer();
             httpWebRequest.ContentType = "application/json";
             httpWebRequest.Method = "POST";
@@ -203,9 +208,7 @@
             using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
             {
                 hftRequest request = new hftRequest();
-                request.getAuthorizationToken = new getAuthorizationTokenRequest();
-                request.getAuthorizationToken.user = user;
-                request.getAuthorizationToken.challengeresp = challengeresp;
+                request.getAuthorizationToken = new getAuthorizationTokenRequest(user, challengeresp);
                 streamWriter.WriteLine(serializer.Serialize(request));
             }
             httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
@@ -236,11 +239,7 @@
             {
                 hftRequest request = new hftRequest();

-                request.getPrice            = new getPriceRequest();
-                request.getPrice.user       = user;
-                request.getPrice.token      = token;
-                request.getPrice.security   = new List<string> { "EUR_USD", "GBP_USD" };
-                request.getPrice.tinterface = new List<string> { "TI1" };
+                request.getPrice = new getPriceRequest(user, token, new List<string> { "EUR_USD", "GBP_USD" }, null, "tob", 1, interval);
                 streamWriter.WriteLine(serializer.Serialize(request));
             }

@@ -286,10 +285,9 @@
         {
             try
             {
-                Console.WriteLine("GETTING");
                 foreach (var row in File.ReadAllLines("config.properties"))
                 {
-                    Console.WriteLine(row);
+                    //Console.WriteLine(row);
                     if ("url-stream".Equals(row.Split('=')[0]))
                     {
                         url_stream = row.Split('=')[1];


Make MethodCall Sender optional for now (needed for p2p)

--- src/Wrapper.cs
+++ src/Wrapper.cs
@@ -45,7 +45,10 @@
 			Interface = (string)message.Header.Fields[FieldCode.Interface];
 			Member = (string)message.Header.Fields[FieldCode.Member];
 			Destination = (string)message.Header.Fields[FieldCode.Destination];
-			Sender = (string)message.Header.Fields[FieldCode.Sender];
+			//TODO: filled by the bus so reliable, but not the case for p2p
+			//so we make it optional here, but this needs some more thought
+			if (message.Header.Fields.ContainsKey (FieldCode.Sender))
+				Sender = (string)message.Header.Fields[FieldCode.Sender];
 #if PROTO_REPLY_SIGNATURE
 			//TODO: note that an empty ReplySignature should really be treated differently to the field not existing!
 			if (message.Header.Fields.ContainsKey (FieldCode.ReplySignature))


Build script (fix path toward git repository)

--- src/build.cake
+++ src/build.cake
@@ -103,18 +103,18 @@
 			var newReleaseNotePath = @"..\doc\release-notes\v" + nextVersion + ".md";
 			MoveFile(ReleaseNotesPath, newReleaseNotePath);

-			GitAdd(".", newReleaseNotePath);
-			GitRemove(".", false, ReleaseNotesPath);
-			var releaseNoteCommit = GitCommit(".", @"Git-tfs release bot", "no-reply@git-tfs.com", "Prepare release " + tag);
+			GitAdd("..", newReleaseNotePath);
+			GitRemove("..", false, ReleaseNotesPath);
+			var releaseNoteCommit = GitCommit("..", @"Git-tfs release bot", "no-reply@git-tfs.com", "Prepare release " + tag);
 			Information("Release note commit created:" + releaseNoteCommit.Sha);

 			ReleaseNotesPath = newReleaseNotePath;
-			GitPush(".", githubAccount, githubToken, "master");
+			GitPush("..", githubAccount, githubToken, "master");
 		}
 		if(!IsMinorRelease)
 		{
-			GitTag(".", tag);
-			GitPushRef(".", githubAccount, githubToken, "origin", "refs/tags/" + tag);
+			GitTag("..", tag);
+			GitPushRef("..", githubAccount, githubToken, "origin", "refs/tags/" + tag);
 		}
 	}
 	else


Added property metadata tests.

Added property metadata tests.

--- tests/Avalonia.Base.UnitTests/AvaloniaObjectTests_Metadata.cs
+++ tests/Avalonia.Base.UnitTests/AvaloniaObjectTests_Metadata.cs
@@ -1,5 +1,4 @@
-using System.Linq;
-using System.Reactive.Linq;
+using System.Runtime.CompilerServices;
 using Xunit;

 namespace Avalonia.Base.UnitTests
@@ -9,28 +8,101 @@
         public AvaloniaObjectTests_Metadata()
         {
             // Ensure properties are registered.
-            AvaloniaProperty p;
-            p = Class1.FooProperty;
-            p = Class2.BarProperty;
-            p = AttachedOwner.AttachedProperty;
+            RuntimeHelpers.RunClassConstructor(typeof(Class1).TypeHandle);
+            RuntimeHelpers.RunClassConstructor(typeof(Class2).TypeHandle);
+            RuntimeHelpers.RunClassConstructor(typeof(Class3).TypeHandle);
+        }
+
+        public class StyledProperty : AvaloniaObjectTests_Metadata
+        {
+            [Fact]
+            public void Default_Value_Can_Be_Overridden_In_Derived_Class()
+            {
+                var baseValue = Class1.StyledProperty.GetDefaultValue(typeof(Class1));
+                var derivedValue = Class1.StyledProperty.GetDefaultValue(typeof(Class2));
+
+                Assert.Equal("foo", baseValue);
+                Assert.Equal("bar", derivedValue);
+            }
+
+            [Fact]
+            public void Default_Value_Can_Be_Overridden_In_AddOwnered_Property()
+            {
+                var baseValue = Class1.StyledProperty.GetDefaultValue(typeof(Class1));
+                var addOwneredValue = Class1.StyledProperty.GetDefaultValue(typeof(Class3));
+
+                Assert.Equal("foo", baseValue);
+                Assert.Equal("baz", addOwneredValue);
+            }
+        }
+
+        public class DirectProperty : AvaloniaObjectTests_Metadata
+        {
+            [Fact]
+            public void Unset_Value_Can_Be_Overridden_In_Derived_Class()
+            {
+                var baseValue = Class1.DirectProperty.GetUnsetValue(typeof(Class1));
+                var derivedValue = Class1.DirectProperty.GetUnsetValue(typeof(Class2));
+
+                Assert.Equal("foo", baseValue);
+                Assert.Equal("bar", derivedValue);
+            }
+
+            [Fact]
+            public void Unset_Value_Can_Be_Overridden_In_AddOwnered_Property()
+            {
+                var baseValue = Class1.DirectProperty.GetUnsetValue(typeof(Class1));
+                var addOwneredValue = Class3.DirectProperty.GetUnsetValue(typeof(Class3));
+
+                Assert.Equal("foo", baseValue);
+                Assert.Equal("baz", addOwneredValue);
+            }
         }

         private class Class1 : AvaloniaObject
         {
-            public static readonly StyledProperty<string> FooProperty =
-                AvaloniaProperty.Register<Class1, string>("Foo");
+            public static readonly StyledProperty<string> StyledProperty =
+                AvaloniaProperty.Register<Class1, string>("Styled", "foo");
+
+            public static readonly DirectProperty<Class1, string> DirectProperty =
+                AvaloniaProperty.RegisterDirect<Class1, string>("Styled", o => o.Direct, unsetValue: "foo");
+
+            private string _direct;
+
+            public string Direct
+            {
+                get => _direct;
+            }
         }

         private class Class2 : Class1
         {
-            public static readonly StyledProperty<string> BarProperty =
-                AvaloniaProperty.Register<Class2, string>("Bar");
+            static Class2()
+            {
+                StyledProperty.OverrideDefaultValue<Class2>("bar");
+                DirectProperty.OverrideMetadata<Class2>(new DirectPropertyMetadata<string>("bar"));
+            }
         }

-        private class AttachedOwner
+        private class Class3 : AvaloniaObject
         {
-            public static readonly AttachedProperty<string> AttachedProperty =
-                AvaloniaProperty.RegisterAttached<AttachedOwner, Class1, string>("Attached");
+            public static readonly StyledProperty<string> StyledProperty =
+                Class1.StyledProperty.AddOwner<Class3>();
+
+            public static readonly DirectProperty<Class3, string> DirectProperty =
+                Class1.DirectProperty.AddOwner<Class3>(o => o.Direct, unsetValue: "baz");
+
+            private string _direct;
+
+            static Class3()
+            {
+                StyledProperty.OverrideDefaultValue<Class3>("baz");
+            }
+
+            public string Direct
+            {
+                get => _direct;
+            }
         }
     }
 }


- fixed broken onewaytests

- fixed broken onewaytests

--- tests/ServiceStack.WebHost.Endpoints.Tests/SendOneWayTests.cs
+++ tests/ServiceStack.WebHost.Endpoints.Tests/SendOneWayTests.cs
@@ -20,7 +20,6 @@
 namespace ServiceStack.WebHost.Endpoints.Tests
 {
     [Route("/onewayrequest", "DELETE")]
-    [DataContract]
     public class DeleteOneWayRequest : IReturnVoid
     {
         public string Prefix { get; set; }
@@ -31,6 +30,7 @@
     [DataContract]
     public class PostOneWayRequest : IReturnVoid
     {
+        [DataMember]
         public string Prefix { get; set; }

         [DataMember(Name = "some-title")]
@@ -67,7 +67,7 @@
         {

             public OneWayServiceAppHostHttpListener()
-                : base("Cors Feature Tests", typeof(OneWayService).Assembly) { }
+                : base("", typeof(OneWayService).Assembly) { }

             public override void Configure(Funq.Container container)
             {


Remove stupid warning

Remove stupid warning

--- Assets/Plugins/GoogleAnalyticsV4/GoogleAnalyticsV4.cs
+++ Assets/Plugins/GoogleAnalyticsV4/GoogleAnalyticsV4.cs
@@ -119,11 +119,11 @@
     }

     if (UncaughtExceptionReporting) {
-#if UNITY_5
+//#if UNITY_5
       Application.logMessageReceived += HandleException;
-#else
-      Application.RegisterLogCallback (HandleException);
-#endif
+//#else
+//      Application.RegisterLogCallback (HandleException);
+//#endif
       if (GoogleAnalyticsV4.belowThreshold(logLevel, GoogleAnalyticsV4.DebugMode.VERBOSE)) {
         Debug.Log("Enabling uncaught exception reporting.");
       }


Update FDK version

Update FDK version

--- FDK/SoftFX.Extended.Net/Properties/AssemblyInfo.cs
+++ FDK/SoftFX.Extended.Net/Properties/AssemblyInfo.cs
@@ -39,5 +39,5 @@
 // You can specify all the values or you can default the Build and Revision Numbers
 // by using the '*' as shown below:
 // [assembly: AssemblyVersion("1.0.*")]
-[assembly: AssemblyVersion("1.18.24.0")]
-[assembly: AssemblyFileVersion("1.18.24.0")]
+[assembly: AssemblyVersion("1.18.25.0")]
+[assembly: AssemblyFileVersion("1.18.25.0")]


Additional test for RemoveRange by predicate on MongoDbSet

--- tests/MongoFramework.Tests/MongoDbSetTests.cs
+++ tests/MongoFramework.Tests/MongoDbSetTests.cs
@@ -14,6 +14,7 @@

 			[Required]
 			public string RequiredField { get; set; }
+			public bool BooleanField { get; set; }
 		}

 		[TestMethod, ExpectedException(typeof(ValidationException))]
@@ -190,5 +191,37 @@
 			dbSet.SaveChanges();
 			Assert.IsFalse(dbSet.Any(m => m.RequiredField == "SuccessfullyRemoveEntityById"));
 		}
+
+		[TestMethod]
+		public void SuccessfullyRemoveRangeByPredicate()
+		{
+			var dbSet = new MongoDbSet<MongoDbSetValidationModel>();
+			dbSet.SetConnection(TestConfiguration.GetConnection());
+
+			var entities = new[]
+			{
+				new MongoDbSetValidationModel
+				{
+					RequiredField = "SuccessfullyRemoveRangeByPredicate"
+				},
+				new MongoDbSetValidationModel
+				{
+					RequiredField = "SuccessfullyRemoveRangeByPredicate",
+					BooleanField = true
+				}
+			};
+
+			dbSet.AddRange(entities);
+			dbSet.SaveChanges();
+
+			dbSet.SetConnection(TestConfiguration.GetConnection());
+
+			dbSet.RemoveRange(e => e.BooleanField);
+
+			Assert.AreEqual(2, dbSet.Count(m => m.RequiredField == "SuccessfullyRemoveRangeByPredicate"));
+			dbSet.SaveChanges();
+			Assert.AreEqual(1, dbSet.Count(m => m.RequiredField == "SuccessfullyRemoveRangeByPredicate"));
+			Assert.IsNotNull(dbSet.FirstOrDefault(m => m.Id == entities[0].Id));
+		}
 	}
 }


Add Redcard System

Add Redcard System

--- GPX02_Client/Assets/Code/Networking/NetworkPeer.cs
+++ GPX02_Client/Assets/Code/Networking/NetworkPeer.cs
@@ -13,6 +13,9 @@

 	public string PlayerName = string.Empty;
 	public NetworkPlayer OwningPlayer;
+
+    public int RedCards = 0;
+    public static int MaxRedCards = 3;

 	public class SpawnInfo
 	{
@@ -54,6 +57,17 @@
     {

 	}
+
+    // security API
+    protected void AddRedCard()
+    {
+        RedCards++;
+        if (RedCards >= MaxRedCards)
+        {
+            Debug.Log("Max red cards hit for " + PlayerName + " : " + OwningPlayer.guid);
+            Network.CloseConnection(OwningPlayer, true);
+        }
+    }

 	// client API

@@ -112,6 +126,12 @@
 	[RPC]
 	void ServerHail(string magic, string name, NetworkMessageInfo info)
 	{
+        if (Status != Statuses.Raw)
+        {
+            AddRedCard();
+            return;
+        }
+
 		Debug.Log(info.sender.guid + " sent hail: " + magic);
 		if (NetworkConnector.Connector.Server.PeerConnect(this))
 		{
@@ -125,6 +145,12 @@
 	[RPC]
 	void ServerRequestSpawn (NetworkMessageInfo info)
 	{
+        if (Status != Statuses.Accepted && Status != Statuses.Dead)
+        {
+            AddRedCard();
+            return;
+        }
+
 		NetworkConnector.Connector.Server.GetSpawnInfo(this);
 		networkView.RPC("ClientSpawn", info.sender, this.LastSpawn.SpawnLocation);
 	}
@@ -132,6 +158,40 @@
     [RPC]
     void ServerReceiveChatMessage(int recipient, string message, NetworkMessageInfo info)
     {
+        if (Status == Statuses.Raw)
+        {
+            AddRedCard();
+            return;
+        }
+
         NetworkConnector.Connector.Server.PeerSentChat(this, recipient, message);
     }
+}
+
+public class TestBehavor : MonoBehaviour
+{
+    public Transform playerPrefab;
+    public ArrayList playerScripts = new ArrayList();
+
+    void OnServerInitialized()
+    {
+        SpawnPlayer(Network.player);
+    }
+
+    void OnPlayerConnected(NetworkPlayer player)
+    {
+        SpawnPlayer(player);
+    }
+
+    void SpawnPlayer(NetworkPlayer player)
+    {
+        string tempPlayerString = player.ToString();
+        int playerNumber = Convert.ToInt32(tempPlayerString);
+
+        Transform newPlayerTransform = (Transform)Network.Instantiate(playerPrefab, transform.position, transform.rotation, playerNumber);
+        playerScripts.Add(newPlayerTransform.GetComponent("cubeMoveAuthoritative"));
+
+        NetworkView theNetworkView = newPlayerTransform.networkView;
+        theNetworkView.RPC("SetPlayer", RPCMode.AllBuffered, player);
+    }
 }


Remove a leftover code block and adds a proper null check

--- Assets/MapzenGo/Models/Factories/LanduseFactory.cs
+++ Assets/MapzenGo/Models/Factories/LanduseFactory.cs
@@ -29,49 +29,50 @@
                 var buildingCorners = new List<Vector3>();
                 Building building = null;
                 var bb = geo["geometry"]["coordinates"].list[0]; //this is wrong but cant fix it now
-                if (bb == null ||bb.list == null)
+                if (bb == null || bb.list == null)
                 {
-                    int x = 5;
-                }
-                for (int i = 0; i < bb.list.Count - 1; i++)
-                {
-                    var c = bb.list[i];
-                    var dotMerc = GM.LatLonToMeters(c[1].f, c[0].f);
-                    var localMercPos = new Vector2(dotMerc.x - tileMercPos.x, dotMerc.y - tileMercPos.y);
-                    buildingCorners.Add(localMercPos.ToVector3xz());
-                }

-                if (buildingCorners.Any())
-                {
-                    try
+
+                    for (int i = 0; i < bb.list.Count - 1; i++)
                     {
-                        building = new GameObject("Parks").AddComponent<Building>();
-                        var verts = new List<Vector3>();
-                        var indices = new List<int>();
-                        var mesh = building.GetComponent<MeshFilter>().mesh;
+                        var c = bb.list[i];
+                        var dotMerc = GM.LatLonToMeters(c[1].f, c[0].f);
+                        var localMercPos = new Vector2(dotMerc.x - tileMercPos.x, dotMerc.y - tileMercPos.y);
+                        buildingCorners.Add(localMercPos.ToVector3xz());
+                    }

-                        var buildingCenter = buildingCorners.Aggregate((acc, cur) => acc + cur)/buildingCorners.Count;
-                        for (int i = 0; i < buildingCorners.Count; i++)
+                    if (buildingCorners.Any())
+                    {
+                        try
                         {
-                            //using corner position relative to building center
-                            buildingCorners[i] = buildingCorners[i] - buildingCenter;
+                            building = new GameObject("Parks").AddComponent<Building>();
+                            var verts = new List<Vector3>();
+                            var indices = new List<int>();
+                            var mesh = building.GetComponent<MeshFilter>().mesh;
+
+                            var buildingCenter = buildingCorners.Aggregate((acc, cur) => acc + cur)/
+                                                 buildingCorners.Count;
+                            for (int i = 0; i < buildingCorners.Count; i++)
+                            {
+                                //using corner position relative to building center
+                                buildingCorners[i] = buildingCorners[i] - buildingCenter;
+                            }
+
+                            building.transform.localPosition = buildingCenter;
+                            SetProperties(geo, building);
+                            CreateMesh(buildingCorners, _settings, ref verts, ref indices);
+
+                            mesh.vertices = verts.ToArray();
+                            mesh.triangles = indices.ToArray();
+                            mesh.RecalculateNormals();
+                            mesh.RecalculateBounds();
                         }
-
-                        building.transform.localPosition = buildingCenter;
-                        SetProperties(geo, building);
-                        CreateMesh(buildingCorners, _settings, ref verts, ref indices);
-
-                        mesh.vertices = verts.ToArray();
-                        mesh.triangles = indices.ToArray();
-                        mesh.RecalculateNormals();
-                        mesh.RecalculateBounds();
-                    }
-                    catch (Exception ex)
-                    {
-                        Debug.Log(ex);
+                        catch (Exception ex)
+                        {
+                            Debug.Log(ex);
+                        }
                     }
                 }
-
                 yield return building;
             }
         }


BuildingFactory: Add Retail, and EXAGERATION factor to make buildings stand out more.

--- Assets/Scripts/MapzenGoWrappers/BuildingFactory.cs
+++ Assets/Scripts/MapzenGoWrappers/BuildingFactory.cs
@@ -20,9 +20,10 @@

         bfs.SettingsBuildings = new System.Collections.Generic.List<BuildingSettings> {
             createBuildingSettings(BuildingType.Hospital, 16, 16, "Hospital"),
-            createBuildingSettings(BuildingType.School, 5, 5, "University"),
+            createBuildingSettings(BuildingType.School, 10, 10, "University"),
             createBuildingSettings(BuildingType.Residential, 7, 7, "Residential"),
             createBuildingSettings(BuildingType.Industrial, 4, 8, "Industrial"),
+            createBuildingSettings(BuildingType.Retail, 4, 10, "Commercial"),
             createBuildingSettings(BuildingType.Commercial, 4, 10, "Commercial"),
             createBuildingSettings(BuildingType.University, 12, 12, "University")
         };
@@ -33,11 +34,12 @@

     protected BuildingSettings createBuildingSettings(BuildingType type, int min, int max, string material)
     {
+        const int EXAGERATION_FACTOR = 2;
         var bs = new BuildingSettings();
         bs.Type = type;
         bs.Material = (Material)Resources.Load(material, typeof(Material));
-        bs.MinimumBuildingHeight = min;
-        bs.MaximumBuildingHeight = max;
+        bs.MinimumBuildingHeight = EXAGERATION_FACTOR * min;
+        bs.MaximumBuildingHeight = EXAGERATION_FACTOR * max;
         bs.IsVolumetric = true;
         return bs;
     }


fix: use a proper variable name for timezone in ChargebackLookupCreator.cs

--- BBR-ChargebackModel-CLI/ChargebackLookupCreator.cs
+++ BBR-ChargebackModel-CLI/ChargebackLookupCreator.cs
@@ -50,7 +50,7 @@
             LookupEntry[,,] chargebackLookup = CreateLookupEntries(values);

             // Figure out the timezone used
-            var tz = TimeZoneInfo.FindSystemTimeZoneById(model.TimezoneForChargeback);
+            var timezoneUsed = TimeZoneInfo.FindSystemTimeZoneById(model.TimezoneForChargeback);

             var startDate = model.EffectiveFrom;
             var endDate = model.EffectiveTo;
@@ -71,7 +71,7 @@
                     var lookup = chargebackLookup[dow, hod, usageType];

                     // Set up the effective range
-                    var effectiveFrom = TimeZoneInfo.ConvertTimeToUtc(currentDate, tz);
+                    var effectiveFrom = TimeZoneInfo.ConvertTimeToUtc(currentDate, timezoneUsed);

                     outputList.Add(new LookupRow
                     {


Delete remote branbch before local

Delete remote branbch before local

--- GitMind/Features/Branches/Private/BranchService.cs
+++ GitMind/Features/Branches/Private/BranchService.cs
@@ -284,19 +284,20 @@
 		{
 			using (progress.ShowDialog())
 			{
+				if (isRemote)
+				{
+					progress.SetText($"Deleting remote branch {branch.Name} ...");
+					await DeleteBranchImplAsync(branch, true, IsForce);
+				}
+
 				if (isLocal)
 				{
 					progress.SetText($"Deleting local branch {branch.Name} ...");
 					await DeleteBranchImplAsync(branch, false, IsForce);
-				}
-
-				if (isRemote)
-				{
-					progress.SetText($"Deleting remote branch {branch.Name} ...");
-					await DeleteBranchImplAsync(branch, true, IsForce);
-				}
-			}
-		}
+				}
+			}
+		}
+

 		private async Task DeleteBranchImplAsync(Branch branch, bool isRemote, bool isForce)
 		{


Changes are made to the Alerts list before calling events

--- CanadaAlertSystem/CanadaAlertSystem/AlertSystem.cs
+++ CanadaAlertSystem/CanadaAlertSystem/AlertSystem.cs
@@ -161,11 +161,11 @@
                     if (matching != null)
                     {
                         new_alert = false;
-                        this.OnAlertUpdated(new AlertUpdatedEventArgs(matching, alert));

                         this.Alerts.Remove(matching);
                         this.Alerts.Add(alert);

+                        this.OnAlertUpdated(new AlertUpdatedEventArgs(matching, alert));
                         break;
                     }// End of if
                 }// End of foreach


Add atomic checkmate test

Add atomic checkmate test

This fails right now. I still need to implement the no-suicide-moves
check, but I added this test already.

--- ChessDotNet.Variants.Tests/AtomicChessGameTests.cs
+++ ChessDotNet.Variants.Tests/AtomicChessGameTests.cs
@@ -76,5 +76,26 @@
             Assert.AreEqual("King exploded", status.EventExplanation);
             Assert.AreEqual(Player.White, status.PlayerWhoCausedEvent);
         }
+
+        [Test]
+        public void TestCheckmate()
+        {
+            Piece[][] board = new Piece[8][]
+            {
+                new[] { o, kb, o, o, o, o, o, o },
+                new[] { o, o, o, o, o, o, o, qw },
+                new[] { o, o, o, o, o, o, o, o },
+                new[] { o, o, o, o, o, o, o, o },
+                new[] { o, o, o, o, o, o, o, o },
+                new[] { o, o, o, o, o, o, o, o },
+                new[] { o, o, o, o, o, o, o, o },
+                new[] { o, o, o, o, kw, o, o, o }
+            };
+            AtomicChessGame game = new AtomicChessGame(board, Player.White);
+            game.ApplyMove(new Move("H7", "B7", Player.White), true);
+            GameStatus status = game.Status;
+            Assert.AreEqual(GameEvent.Checkmate, status.Event);
+            Assert.AreEqual(Player.White, status.PlayerWhoCausedEvent);
+        }
     }
 }


fixed failing test case

fixed failing test case

--- src/Tests/HelpCenter/ArticleTests.cs
+++ src/Tests/HelpCenter/ArticleTests.cs
@@ -115,9 +115,12 @@
         [Test]
         public void CanGetArticlesSortedInASection()
         {
-            var section = api.HelpCenter.Sections.GetSections().Sections[0];
-            var articlesAscending = api.HelpCenter.Articles.GetArticlesBySectionId(section.Id.Value, ArticleSideLoadOptionsEnum.None, new ArticleSortingOptions() { SortBy = ArticleSortEnum.Title });
-            var articlesDescending = api.HelpCenter.Articles.GetArticlesBySectionId(section.Id.Value, ArticleSideLoadOptionsEnum.None, new ArticleSortingOptions() { SortBy = ArticleSortEnum.Title, SortOrder = ArticleSortOrderEnum.Desc });
+            var section = api.HelpCenter.Sections.GetSections().Sections[1];
+
+            var articlesAscending = api.HelpCenter.Articles.GetArticlesBySectionId(section.Id.Value, ArticleSideLoadOptionsEnum.None,
+                new ArticleSortingOptions() { SortBy = ArticleSortEnum.Title });
+            var articlesDescending = api.HelpCenter.Articles.GetArticlesBySectionId(section.Id.Value, ArticleSideLoadOptionsEnum.None,
+                new ArticleSortingOptions() { SortBy = ArticleSortEnum.Title, SortOrder = ArticleSortOrderEnum.Desc });

             Assert.IsTrue(articlesAscending.Articles[0].Title != articlesDescending.Articles[0].Title);
         }


Moved GUIOpen check from onDestroy() to Start()

--- KSPRemoteLaunch/KSPRemoteLaunch/RemoteLaunchGUI.cs
+++ KSPRemoteLaunch/KSPRemoteLaunch/RemoteLaunchGUI.cs
@@ -285,7 +285,8 @@

             if (hasRunOnce && !LaunchDriver.hasLoadedGameChanged())
             {
-                addWindows();
+                if(showGUI)
+                    addWindows();
                 //RenderingManager.AddToPostDrawQueue(3, new Callback(drawGUI));//open GUI

                 //KSP will always revert to the default site for the selected editor
@@ -411,11 +412,11 @@

         void onDestroy()
         {
-            if(!showGUI)
-                RenderingManager.AddToPostDrawQueue(3, new Callback(drawGUI));//open the GUI
-            showGUI = true;
+            removeWindows();
+            /*
             RenderingManager.RemoveFromPostDrawQueue(3, new Callback(drawGUI)); //close the GUI
             RenderingManager.RemoveFromPostDrawQueue(4, new Callback(drawErrorGUI)); //close the GUI
+             * */
         }
     }


Fix version description.

Fix version description.

--- Libraries/Sources/Views/Controls/VersionControl.cs
+++ Libraries/Sources/Views/Controls/VersionControl.cs
@@ -203,7 +203,7 @@
         ///
         /* ----------------------------------------------------------------- */
         [Browsable(false)]
-        public string Platform => string.Format("{0}{1}Microsoft .NET Framework {2}{3}",
+        public string Platform => string.Format("{0}{1}CLR {2}{3}",
             Environment.OSVersion,
             Environment.NewLine,
             Environment.Version,


Fix learning.

Fix learning.

--- Code2Xml.Objects.Tests/Learning/LearningExperiment.cs
+++ Code2Xml.Objects.Tests/Learning/LearningExperiment.cs
@@ -226,7 +226,7 @@
                     Path.Combine(
                             projectPath ?? "",
                             GetType().Name + Code2XmlConstants.LearningCacheExtension));
-            if (true || string.IsNullOrEmpty(projectPath) || !cacheFile.Exists) {
+            if (string.IsNullOrEmpty(projectPath) || !cacheFile.Exists) {
                 var allAsts = allPaths.Select(
                         path => Generator.GenerateTreeFromCode(new FileInfo(path), null, true));
                 var seedAsts = seedPaths.Select(


Fixed typo

Fixed typo

--- MobileHymnal/MobileHymnal/Screens/Selector.xaml.cs
+++ MobileHymnal/MobileHymnal/Screens/Selector.xaml.cs
@@ -70,7 +70,7 @@
             _model.MaxHymnNumber = _model.SelectedSongbook.Title.Length;
         }

-        private void hymnalPickedChanged(object sender, EventArgs e)
+        private void HymnalPickedChanged(object sender, EventArgs e)
         {
             SetHymnNumberMax();
         }


Fix TryXxx method possible throw exceptions.

--- src/VirtualDesktop/VirtualDesktop.cs
+++ src/VirtualDesktop/VirtualDesktop.cs
@@ -326,13 +326,17 @@
     {
         InitializeIfNeeded();

-        var id = SafeInvoke(() => _provider.ApplicationViewCollection
-            .GetViewForHwnd(hWnd)
-            .GetAppUserModelId());
-        if (id != null)
-        {
-            appUserModelId = id;
+        try
+        {
+            appUserModelId = _provider.ApplicationViewCollection
+                .GetViewForHwnd(hWnd)
+                .GetAppUserModelId();
             return true;
+        }
+        catch (Exception ex)
+        {
+            Debug.WriteLine($"{nameof(TryGetAppUserModelId)} failed.");
+            Debug.WriteLine(ex);
         }

         appUserModelId = "";


Handle system wide installs of chrome

Handle system wide installs of chrome

--- Admo/Utilities/SoftwareUtils.cs
+++ Admo/Utilities/SoftwareUtils.cs
@@ -9,9 +9,17 @@

         public static string GetChromeVersion()
         {
-            var path = Registry.GetValue(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe", "", null);
-            if (path != null)
-                return FileVersionInfo.GetVersionInfo(path.ToString()).FileVersion;
+            //Handle both system wide and user installs of chrome
+            var pathLocal = Registry.GetValue(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe", "", null);
+            var pathMachine = Registry.GetValue(@"HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe", "", null);
+            if (pathLocal != null)
+            {
+                return FileVersionInfo.GetVersionInfo(pathLocal.ToString()).FileVersion;
+            }
+            if (pathMachine != null)
+            {
+                return FileVersionInfo.GetVersionInfo(pathMachine.ToString()).FileVersion;
+            }
             return String.Empty;
         }
     }


Add method to create empty CustomGrid

Add method to create empty CustomGrid

--- Corale.Colore/Razer/Keyboard/Effects/CustomGrid.cs
+++ Corale.Colore/Razer/Keyboard/Effects/CustomGrid.cs
@@ -134,6 +134,16 @@
         }

         /// <summary>
+        /// Creates a new empty <see cref="CustomGrid" /> struct.
+        /// </summary>
+        /// <returns>An instance of <see cref="CustomGrid" />
+        /// filled with the color black.</returns>
+        public static CustomGrid Create()
+        {
+            return new CustomGrid(Color.Black);
+        }
+
+        /// <summary>
         /// Clears the colors from the grid, setting them to <see cref="Color.Black" />.
         /// </summary>
         public void Clear()


wip WS-850. Rethrow exception

wip WS-850. Rethrow exception

--- PalasoUIWindowsForms/Keyboarding/Keyman6Adaptor.cs
+++ PalasoUIWindowsForms/Keyboarding/Keyman6Adaptor.cs
@@ -82,9 +82,14 @@
 			{
 				InnerKeyman6Wrapper.Deactivate();
 			}
-			catch (Exception)
-			{
-				Palaso.Reporting.NonFatalErrorDialog.Show("There was a problem deactivating keyman 6.");
+			catch (Exception e)
+			{
+				throw e;
+				// wip cjp: See WS-850 Identify the exception and maybe catch once per session, or advise re IPA problem.
+				// IPA keyboard 1.1.5 seems to work for MD, IPA keyboard V1.2 causes an exception to be thrown in Keyman 6.x
+				// Plan is to release this to identify the exception, then catch and discard.
+//                string error = string.Format("There was a problem deactivating keyman 6.\r\n{0}", e);
+//                Palaso.Reporting.NonFatalErrorDialog.Show(error);
 			}
 		}

@@ -230,4 +235,4 @@
 			return null;
 		}
 	}
-}+}


Use SetAndInvalidateMesh

Use SetAndInvalidateMesh

- Issue MatterHackers/MCCentral#2473
Subtract operation now roundtrips, sometimes has wrong mesh

--- PartPreviewWindow/View3D/Actions/SubtractEditor.cs
+++ PartPreviewWindow/View3D/Actions/SubtractEditor.cs
@@ -202,7 +202,8 @@
 							var inverse = keep.WorldMatrix();
 							inverse.Invert();
 							transformedKeep.Transform(inverse);
-							keep.Mesh = transformedKeep;
+
+							keep.SetAndInvalidateMesh(transformedKeep);
 							view3DWidget.Invalidate();

 							percentCompleted += amountPerOperation;


(MG2): alternative encryption (#81)

(MG2): alternative encryption (#81)

--- ArcFormats/Valkyria/ImageMG2.cs
+++ ArcFormats/Valkyria/ImageMG2.cs
@@ -23,6 +23,7 @@
 // IN THE SOFTWARE.
 //

+using System;
 using System.ComponentModel.Composition;
 using System.IO;
 using System.Windows.Media;
@@ -32,8 +33,15 @@
 {
     internal class Mg2MetaData : ImageMetaData
     {
-        public int ImageLength;
-        public int AlphaLength;
+        public int          ImageLength;
+        public int          AlphaLength;
+        public IMg2Scheme   Scheme;
+    }
+
+    internal interface IMg2Scheme
+    {
+        Mg2EncryptedStream CreateStream (Stream main, int offset, int length);
+        ImageData CreateImage (BitmapSource bitmap, ImageMetaData info);
     }

     [Export(typeof(ImageFormat))]
@@ -42,6 +50,8 @@
         public override string         Tag { get { return "MG2"; } }
         public override string Description { get { return "Valkyria image format"; } }
         public override uint     Signature { get { return 0x4F43494D; } } // 'MICO'
+
+        static readonly IMg2Scheme[] KnownSchemes = { new Mg2SchemeV1(), new Mg2SchemeV2() };

         public override ImageMetaData ReadMetaData (IBinaryStream file)
         {
@@ -49,38 +59,46 @@
             if (!header.AsciiEqual (4, "CG01"))
                 return null;
             int length = header.ToInt32 (8);
-            using (var input = new Mg2EncryptedStream (file.AsStream, 0x10, length))
-            using (var png = new BinaryStream (input, file.Name))
+            foreach (var scheme in KnownSchemes)
             {
-                var info = Png.ReadMetaData (png);
-                if (null == info)
-                    return null;
-                return new Mg2MetaData
+                using (var input = scheme.CreateStream (file.AsStream, 0x10, length))
+                using (var png = new BinaryStream (input, file.Name))
                 {
-                    Width = info.Width,
-                    Height = info.Height,
-                    OffsetX = info.OffsetX,
-                    OffsetY = info.OffsetY,
-                    BPP = info.BPP,
-                    ImageLength = length,
-                    AlphaLength = header.ToInt32 (12)
-                };
+                    var info = Png.ReadMetaData (png);
+                    if (null == info)
+                        continue;
+                    return new Mg2MetaData
+                    {
+                        Width = info.Width,
+                        Height = info.Height,
+                        OffsetX = info.OffsetX,
+                        OffsetY = info.OffsetY,
+                        BPP = info.BPP,
+                        ImageLength = length,
+                        AlphaLength = header.ToInt32 (12),
+                        Scheme = scheme,
+                    };
+                }
             }
+            return null;
         }

         public override ImageData Read (IBinaryStream file, ImageMetaData info)
         {
             var meta = (Mg2MetaData)info;
+            var frame = ReadBitmapSource (file.AsStream, meta);
+            return meta.Scheme.CreateImage (frame, meta);
+        }
+
+        BitmapSource ReadBitmapSource (Stream file, Mg2MetaData meta)
+        {
             BitmapSource frame;
-            using (var input = new Mg2EncryptedStream (file.AsStream, 0x10, meta.ImageLength))
+            using (var input = meta.Scheme.CreateStream (file, 0x10, meta.ImageLength))
             {
                 var decoder = new PngBitmapDecoder (input, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
                 frame = decoder.Frames[0];
                 if (0 == meta.AlphaLength)
-                {
-                    frame.Freeze();
-                    return new ImageData (frame, info);
-                }
+                    return frame;
             }
             if (frame.Format.BitsPerPixel != 32)
                 frame = new FormatConvertedBitmap (frame, PixelFormats.Bgr32, null, 0);
@@ -88,12 +106,14 @@
             var pixels = new byte[stride * (int)meta.Height];
             frame.CopyPixels (pixels, stride, 0);

-            using (var input = new Mg2EncryptedStream (file.AsStream, 0x10+meta.ImageLength, meta.AlphaLength))
+            using (var input = meta.Scheme.CreateStream (file, 0x10+meta.ImageLength, meta.AlphaLength))
             {
                 var decoder = new PngBitmapDecoder (input, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
                 BitmapSource alpha_frame = decoder.Frames[0];
                 if (alpha_frame.PixelWidth != frame.PixelWidth || alpha_frame.PixelHeight != frame.PixelHeight)
-                    return ImageData.Create (info, PixelFormats.Bgr32, null, pixels, stride);
+                    return BitmapSource.Create ((int)meta.Width, (int)meta.Height,
+                                                ImageData.DefaultDpiX, ImageData.DefaultDpiY,
+                                                PixelFormats.Bgr32, null, pixels, stride);

                 alpha_frame = new FormatConvertedBitmap (alpha_frame, PixelFormats.Gray8, null, 0);
                 var alpha = new byte[alpha_frame.PixelWidth * alpha_frame.PixelHeight];
@@ -104,7 +124,9 @@
                 {
                     pixels[dst] = alpha[src++];
                 }
-                return ImageData.Create (info, PixelFormats.Bgra32, null, pixels, stride);
+                return BitmapSource.Create ((int)meta.Width, (int)meta.Height,
+                                            ImageData.DefaultDpiX, ImageData.DefaultDpiY,
+                                            PixelFormats.Bgra32, null, pixels, stride);
             }
         }

@@ -117,11 +139,23 @@
     internal class Mg2EncryptedStream : StreamRegion
     {
         readonly int    m_threshold;
-
-        public Mg2EncryptedStream (Stream main, int offset, int length)
+        readonly byte   m_key;
+
+        protected Mg2EncryptedStream (Stream main, int offset, int length, int threshold, byte key)
             : base (main, offset, length, true)
         {
-            m_threshold = length / 5;
+            m_threshold = threshold;
+            m_key = key;
+        }
+
+        public static Mg2EncryptedStream CreateV1 (Stream main, int offset, int length)
+        {
+            return new Mg2EncryptedStream (main, offset, length, length / 5, 0);
+        }
+
+        public static Mg2EncryptedStream CreateV2 (Stream main, int offset, int length)
+        {
+            return new Mg2EncryptedStream (main, offset, length, Math.Min (25, length), (byte)length);
         }

         public override int Read (byte[] buffer, int offset, int count)
@@ -129,7 +163,7 @@
             int pos = (int)Position;
             int read = base.Read (buffer, offset, count);
             for (int i = 0; i < read && pos < m_threshold; ++i)
-                buffer[offset+i] ^= (byte)pos++;
+                buffer[offset+i] ^= (byte)(m_key + pos++);
             return read;
         }

@@ -138,8 +172,37 @@
             long pos = Position;
             int b = base.ReadByte();
             if (b != -1 && pos < m_threshold)
-                b ^= (byte)pos;
+                b ^= (byte)(m_key + pos);
             return b;
         }
     }
+
+    internal class Mg2SchemeV1 : IMg2Scheme
+    {
+        public Mg2EncryptedStream CreateStream (Stream main, int offset, int length)
+        {
+            return Mg2EncryptedStream.CreateV1 (main, offset, length);
+        }
+
+        public ImageData CreateImage (BitmapSource frame, ImageMetaData info)
+        {
+            frame.Freeze();
+            return new ImageData (frame, info);
+        }
+    }
+
+    internal class Mg2SchemeV2 : IMg2Scheme
+    {
+        public Mg2EncryptedStream CreateStream (Stream main, int offset, int length)
+        {
+            return Mg2EncryptedStream.CreateV2 (main, offset, length);
+        }
+
+        public ImageData CreateImage (BitmapSource frame, ImageMetaData info)
+        {
+            frame = new TransformedBitmap (frame, new ScaleTransform { ScaleY = -1 });
+            frame.Freeze();
+            return new ImageData (frame, info);
+        }
+    }
 }


Fix logging verification in tests (#2795)

--- test/Kestrel.Core.Tests/Http2ConnectionTests.cs
+++ test/Kestrel.Core.Tests/Http2ConnectionTests.cs
@@ -3434,7 +3434,7 @@

             Assert.Equal(TaskStatus.RanToCompletion, _connection.ProcessRequestsAsync(new DummyApplication(_noopApplication)).Status);

-            var logMessage = _logger.Messages.Single();
+            var logMessage = _logger.Messages.Single(m => m.LogLevel >= LogLevel.Information);

             Assert.Equal(LogLevel.Information, logMessage.LogLevel);
             Assert.Equal("Connection id \"(null)\" request processing ended abnormally.", logMessage.Message);
@@ -3449,7 +3449,7 @@

             Assert.Equal(TaskStatus.RanToCompletion, _connection.ProcessRequestsAsync(new DummyApplication(_noopApplication)).Status);

-            var logMessage = _logger.Messages.Single();
+            var logMessage = _logger.Messages.Single(m => m.LogLevel >= LogLevel.Information);

             Assert.Equal(LogLevel.Warning, logMessage.LogLevel);
             Assert.Equal(CoreStrings.RequestProcessingEndError, logMessage.Message);


[]비어있는 배열 파싱 에러 수정.

[]비어있는 배열 파싱 에러 수정.

--- Assets/CloudBread/CloudBread.cs
+++ Assets/CloudBread/CloudBread.cs
@@ -111,9 +111,9 @@
         {
             if (CBSetting.useEncrypt || text_.Contains(_aseEncryptDefineHeader))
             {
-                return CBAuthentication.AES_decrypt(CBTool.GetElementValueFromJson(_aseEncryptDefine, text_));
-            }
-            return text_;
+                return CBAuthentication.AES_decrypt(CBTool.GetElementValueFromJson(_aseEncryptDefine, text_).Trim());
+            }
+            return text_.Trim();
         }

         // json 배열을 감싸는 리스트를 사용할것인가?
@@ -148,22 +148,32 @@
                             }
                             else // 배열.
                             {
-                                string text = receiveText.Remove(receiveText.Length - 2).Remove(0, 1);
-                                string[] list = System.Text.RegularExpressions.Regex.Split(text, "},");
-                                T[] tList = new T[list.Length];
-                                for (int i = 0; i < list.Length; ++i)
+                                int start = receiveText.IndexOf("[")+1;
+                                int end = receiveText.LastIndexOf("]");
+                                string receiveData = receiveText.Substring(start, end - start);
+
+                                if (!string.IsNullOrEmpty(receiveData))
                                 {
-                                    // }, 로 split시에 맨뒤에 있는 항목은 }가 없음.
-                                    // 그래서 www.text의 맨뒤에서 하나 더 제거한상태로 전체 객체가 뒤에 }가 없게 처리.
-                                    //tList[i] = JsonUtility.FromJson<T>(list[i].EndsWith("}") ? list[i] : list[i]+"}");
-                                    tList[i] = JsonUtility.FromJson<T>(list[i] + "}");
+                                    // }, 로 split시에 맨뒤에 있는 항목은 }가 없음. 맨뒤에 } 제거한상태로 각 객체가 뒤에 }가 없게 처리.
+                                    receiveData = receiveData.Substring(0, receiveData.LastIndexOf("}"));
+                                    string[] list = System.Text.RegularExpressions.Regex.Split(receiveData, "},");
+                                    T[] tList = new T[list.Length];
+                                    for (int i = 0; i < list.Length; ++i)
+                                    {
+                                        //tList[i] = JsonUtility.FromJson<T>(list[i].EndsWith("}") ? list[i] : list[i]+"}");
+                                        tList[i] = JsonUtility.FromJson<T>(list[i] + "}");
+                                    }
+                                    callback_(tList);
                                 }
-                                callback_(tList);
+                                else
+                                {
+                                    callback_(null);
+                                }
                             }
                         }
                         catch (System.Exception e)
                         {
-                            string errorMessage = string.Format("{0}\nurl\n{1}\nwww.text\n{2}\n{3}", "ERROR : Json Parse.", www.url, www.text, e);
+                            string errorMessage = string.Format("{0}\nurl\n{1}\nwww.text\n{2}\ndata\n{3}\n{4}", "ERROR : Json Parse.", www.url, www.text, receiveText, e);
                             if (null != errorCallback_)
                             {
                                 errorCallback_(errorMessage);
@@ -207,7 +217,7 @@
                             //Debug.Log(errorMessage);
                             if (null != errorCallback_)
                             {
-                                string errorMessage = string.Format("{0}\nurl\n{1}\nwww.text\n{2}\n{3}", "ERROR : Json Parse.", www.url, www.text, e);
+                                string errorMessage = string.Format("{0}\nurl\n{1}\nwww.text\n{2}\ndata\n{3}\n{4}", "ERROR : Json Parse.", www.url, www.text, receiveText, e);
                                 errorCallback_(errorMessage);
                             }
                         }


* Fixed memory leak with AudioClip objects.

--- Assets/Watson/Data/DataTypes.cs
+++ Assets/Watson/Data/DataTypes.cs
@@ -14,7 +14,10 @@
 * limitations under the License.
 *
 */
+
+
 using IBM.Watson.DataModels;
+using IBM.Watson.Utilities;
 using IBM.Watson.Widgets;
 using UnityEngine;


ChannelStation

ChannelStation


peform cast to FUNC or ACTION to replace slower calls to .DynamicInvoke() with better-performing .Invoke() calls


Handled error with initializing multidimensional arrays

--- src/SME/ProcessMetadata.cs
+++ src/SME/ProcessMetadata.cs
@@ -58,7 +58,10 @@
                 if (t.IsArray)
                 {
                     var arraysource = (Array)source;
-                    var target = Array.CreateInstance(t.GetElementType(), arraysource.Length);
+                    int[] lengths = new int[arraysource.Rank];
+                    for (int i = 0; i < arraysource.Rank; i++)
+                        lengths[i] = arraysource.GetLength(i);
+                    var target = Array.CreateInstance(t.GetElementType(), lengths);
                     Array.Copy(arraysource, target, arraysource.Length);
                     Initialization[fi.Name] = target;
                 }


Replace format builtin test to workaround Mono arabic percent character issue.

--- Cottle.Test/src/Builtins/BuiltinFunctionsTester.cs
+++ Cottle.Test/src/Builtins/BuiltinFunctionsTester.cs
@@ -46,7 +46,7 @@
 		[Test]
 		[TestCase ("format(1339936496, 'd:yyyy-MM-dd HH:mm:ss')", "2012-06-17 12:34:56")]
 		[TestCase ("format(0.165, 'n:e3', 'en-US')", "1.650e-001")]
-		[TestCase ("format(0.165, 'n:p2', 'fr-FR')", "16,50 %")]
+		[TestCase ("format(4.165, 'n:c', 'fr-FR')", "4,17 €")]
 		[TestCase ("format(1, 'b:n2')", "True")]
 		public void FunctionFormat (string expression, string expected)
 		{


filter transformations

filter transformations

--- DbShell.Driver.Common/FilterParser/FilterParser.cs
+++ DbShell.Driver.Common/FilterParser/FilterParser.cs
@@ -9,8 +9,19 @@

 namespace DbShell.Driver.Common.FilterParser
 {
+    public enum FilterLineTransformation
+    {
+        IsOneOf,
+        BeginsWithOneOf,
+        EndsWithOneOf,
+        ContainsOneOf,
+        None
+    }
+
     public class FilterParser
     {
+        public const string LineTransformPrefix = "$LINE_TRANSFORM$=";
+
         public enum ExpressionType
         {
             Number,
@@ -94,8 +105,21 @@
             return ExpressionType.None;
         }

+        public static FilterLineTransformation GetExpressionTransformation(string expression)
+        {
+            if (expression != null && expression.StartsWith(LineTransformPrefix))
+            {
+                string[] exprs = expression.Split(new char[] {'\n'}, 2);
+                string tran = exprs[0].Trim().Substring(LineTransformPrefix.Length);
+                return (FilterLineTransformation) Enum.Parse(typeof (FilterLineTransformation), tran);
+            }
+            return FilterLineTransformation.None;
+        }
+
         public static DmlfConditionBase ParseFilterExpression(DbTypeBase type, DmlfExpression columnValue, string expression)
         {
+            expression = TransformExpression(expression);
+
             switch (GetExpressionType(type))
             {
                 case ExpressionType.Number:
@@ -111,5 +135,37 @@
                 RightExpr = new DmlfStringExpression { Value = expression },
             };
         }
+
+        private static string TransformExpression(string expression)
+        {
+            var tran = GetExpressionTransformation(expression);
+            switch (tran)
+            {
+                case FilterLineTransformation.IsOneOf:
+                    return TrasnformLines(expression, line => String.Format("='{0}'", line));
+                case FilterLineTransformation.ContainsOneOf:
+                    return TrasnformLines(expression, line => String.Format("'{0}'", line));
+                case FilterLineTransformation.BeginsWithOneOf:
+                    return TrasnformLines(expression, line => String.Format("^'{0}'", line));
+                case FilterLineTransformation.EndsWithOneOf:
+                    return TrasnformLines(expression, line => String.Format("$'{0}'", line));
+            }
+            return expression;
+        }
+
+        private static string TrasnformLines(string expression, Func<string, string> func)
+        {
+            var sb = new StringBuilder();
+            bool first = true;
+            foreach (string line in expression.Split('\n'))
+            {
+                if (!first)
+                {
+                    sb.AppendLine(func(line.Trim()));
+                }
+                first = false;
+            }
+            return sb.ToString();
+        }
     }
 }


Refactor Network Monitor bytes to text

Refactor Network Monitor bytes to text

--- DesktopWidgets/Widgets/LatencyMonitor/ViewModel.cs
+++ DesktopWidgets/Widgets/LatencyMonitor/ViewModel.cs
@@ -133,12 +133,12 @@
             if (Settings.ShowDownloadUsage)
             {
                 stringBuilder.Append(
-                    $" {StringHelper.BytesToString(downloadUsage, Settings.BandwidthDecimalPlaces).PadLeft(Settings.BandwidthPadding, ' ')}");
+                    $" {BytesToReadableString(downloadUsage, Settings.BandwidthDecimalPlaces).PadLeft(Settings.BandwidthPadding, ' ')}");
             }
             if (Settings.ShowUploadUsage)
             {
                 stringBuilder.Append(
-                    $" {StringHelper.BytesToString(uploadUsage, Settings.BandwidthDecimalPlaces).PadLeft(Settings.BandwidthPadding, ' ')}");
+                    $" {BytesToReadableString(uploadUsage, Settings.BandwidthDecimalPlaces).PadLeft(Settings.BandwidthPadding, ' ')}");
             }
             stringBuilder.Append($" {reply.RoundtripTime.ToString().PadLeft(Settings.LatencyPadding, '0')}ms");
             if (Settings.ShowStatus)
@@ -165,5 +165,56 @@
             base.OnClose();
             _scanLatency = false;
         }
+
+        // https://stackoverflow.com/a/11124118
+        private static string BytesToReadableString(long bytes, int decimalPlaces)
+        {
+            if (bytes <= 0)
+            {
+                return "0B";
+            }
+
+            string suffix;
+            double readable;
+            if (bytes >= 0x1000000000000000) // Exabyte.
+            {
+                suffix = "EB";
+                readable = (bytes >> 50);
+            }
+            else if (bytes >= 0x4000000000000) // Petabyte.
+            {
+                suffix = "PB";
+                readable = (bytes >> 40);
+            }
+            else if (bytes >= 0x10000000000) // Terabyte.
+            {
+                suffix = "TB";
+                readable = (bytes >> 30);
+            }
+            else if (bytes >= 0x40000000) // Gigabyte.
+            {
+                suffix = "GB";
+                readable = (bytes >> 20);
+            }
+            else if (bytes >= 0x100000) // Megabyte.
+            {
+                suffix = "MB";
+                readable = (bytes >> 10);
+            }
+            else if (bytes >= 0x400) // Kilobyte.
+            {
+                suffix = "KB";
+                readable = bytes;
+            }
+            else
+            {
+                return bytes.ToString("0B"); // Byte.
+            }
+
+            // Divide by 1024 to get fractional value.
+            readable = Math.Round(readable / 1024, decimalPlaces);
+
+            return readable.ToString("0") + suffix;
+        }
     }
 }


git-svn-id: 21cdf44b51306c1f0753fc51e774ecf5fc1851ba@1113 a61f9e97-bd4c-0410-8c65-85b29eaa70ff

--- Dorian/Examples/Gorgon.Graphics/Boinger/Program.cs
+++ Dorian/Examples/Gorgon.Graphics/Boinger/Program.cs
@@ -267,12 +267,12 @@
 			// Note that we're rendering here but not flipping the buffer (the 'false' parameter).  This just delays the page
 			// flipping until later.  Technically, we don't need to do this here because it's the last thing we're doing, but
 			// if we had more rendering to do after, we'd have to flip manually.
-			_2D.Render();
+			_2D.Render(false);
 			_2D.End2D();

 			// Now we flip our buffers.
 			// We need to this or we won't see anything.
-			//_swap.Flip();
+			_swap.Flip();

 			return true;
 		}


Use screen space distance tolerances for the mouse down handler

This is similar to the hover point changes in ccac61c7, and makes the shape tools much more usable when zoomed in

--- Pinta.Tools/Editable/EditEngines/BaseEditEngine.cs
+++ Pinta.Tools/Editable/EditEngines/BaseEditEngine.cs
@@ -687,97 +687,72 @@
 			OrganizedPointCollection.FindClosestPoint (SEngines, current_point,
 			    out closestShapeIndex, out closestPointIndex, out closestPoint, out closestDistance);

-			bool clickedOnControlPoint = false;
-
-			// TODO - this should be replaced with the screen space tests from the MoveHandle
-			double currentClickRange = ShapeClickStartingRange + BrushWidth;
-
-			//Determine if the closest ControlPoint is within the expected click range.
-			if (closestControlPoint != null && closestCPDistance < currentClickRange) {
-				//User clicked directly on a ControlPoint on a shape.
-
-				clicked_without_modifying = true;
-
-				SelectedPointIndex = closestCPIndex;
-				SelectedShapeIndex = closestCPShapeIndex;
-
-				clickedOnControlPoint = true;
-			} else if (closestDistance < currentClickRange) //Determine if the user clicked close enough to a shape.
-			  {
-				//User clicked on a generated point on a shape.
-
-				List<ControlPoint> controlPoints = SEngines[closestShapeIndex].ControlPoints;
-
-				//Note: compare the currentPoint's distance here because it's the actual mouse position.
-				if (controlPoints.Count > closestPointIndex && current_point.Distance (controlPoints[closestPointIndex].Position) < currentClickRange) {
-					//User clicked on a control point (on the "previous order" side of the point).
-
-					clicked_without_modifying = true;
-
-					SelectedPointIndex = closestPointIndex;
-					SelectedShapeIndex = closestShapeIndex;
-
-					clickedOnControlPoint = true;
-				} else if (closestPointIndex > 0) {
-					if (current_point.Distance (controlPoints[closestPointIndex - 1].Position) < currentClickRange) {
-						//User clicked on a control point (on the "following order" side of the point).
-
-						clicked_without_modifying = true;
-
-						SelectedPointIndex = closestPointIndex - 1;
-						SelectedShapeIndex = closestShapeIndex;
-
-						clickedOnControlPoint = true;
-					} else if (controlPoints.Count > 0 && current_point.Distance (controlPoints[controlPoints.Count - 1].Position) < currentClickRange) {
-						//User clicked on a control point (on the "following order" side of the point).
-
-						clicked_without_modifying = true;
-
-						SelectedPointIndex = closestPointIndex - 1;
-						SelectedShapeIndex = closestShapeIndex;
-
-						clickedOnControlPoint = true;
-					}
-				}
-
-				//Check for clicking on a non-control point. Don't do anything here if right clicked.
-				if (!changing_tension && !clickedOnControlPoint && closestShapeIndex > -1 && closestPointIndex > -1 && SEngines.Count > closestShapeIndex) {
-					//User clicked on a non-control point on a shape.
-
-					//Determine if the currently active tool matches the clicked on shape's corresponding tool, and if not, switch to it.
-					if (ActivateCorrespondingTool (closestShapeIndex, true) != null) {
-						//Pass on the event and its data to the newly activated tool.
-						PintaCore.Tools.DoMouseDown (document, e);
-
-						//Don't do anything else here once the tool is switched and the event is passed on.
-						return;
-					}
-
-					//The currently active tool matches the clicked on shape's corresponding tool.
-
-					//Only create a new shape if the user isn't holding the control key down.
-					if (!ctrlKey) {
-						//Create a new ShapesModifyHistoryItem so that the adding of a control point can be undone.
-						doc.History.PushNewItem (new ShapesModifyHistoryItem (this, owner.Icon, ShapeName + " " + Translations.GetString ("Point Added")));
-
-						controlPoints.Insert (closestPointIndex,
-							new ControlPoint (new PointD (current_point.X, current_point.Y), DefaultMidPointTension));
-					}
-
-					//These should be set after creating the history item.
-					SelectedPointIndex = closestPointIndex;
-					SelectedShapeIndex = closestShapeIndex;
-
-					ShapeEngine? activeEngine = ActiveShapeEngine;
-
-					if (activeEngine != null) {
-						UpdateToolbarSettings (activeEngine);
-					}
+			bool clicked_control_point = false;
+			bool clicked_generated_point = false;
+			{
+				var current_window_point = PintaCore.Workspace.CanvasPointToWindow(current_point);
+				var test_handle = new MoveHandle();
+
+				// Check if the user is directly clicking on a control point.
+				if (closestControlPoint != null)
+				{
+					test_handle.CanvasPosition = closestControlPoint.Position;
+					clicked_control_point = test_handle.ContainsPoint(current_window_point);
+					if (clicked_control_point)
+					{
+						SelectedPointIndex = closestCPIndex;
+						SelectedShapeIndex = closestCPShapeIndex;
+					}
+				}
+
+				// Otherwise, the user might have clicked on a generated point.
+				if (!clicked_control_point)
+				{
+					test_handle.CanvasPosition = closestPoint;
+					clicked_generated_point = test_handle.ContainsPoint(current_window_point);
+				}
+			}
+
+			clicked_without_modifying = clicked_control_point;
+
+			if (!changing_tension && clicked_generated_point)
+			{
+				//Determine if the currently active tool matches the clicked on shape's corresponding tool, and if not, switch to it.
+				if (ActivateCorrespondingTool(closestShapeIndex, true) != null)
+				{
+					//Pass on the event and its data to the newly activated tool.
+					PintaCore.Tools.DoMouseDown(document, e);
+
+					//Don't do anything else here once the tool is switched and the event is passed on.
+					return;
+				}
+
+				//The currently active tool matches the clicked on shape's corresponding tool.
+
+				//Only create a new shape if the user isn't holding the control key down.
+				if (!ctrlKey)
+				{
+					//Create a new ShapesModifyHistoryItem so that the adding of a control point can be undone.
+					doc.History.PushNewItem(new ShapesModifyHistoryItem(this, owner.Icon, ShapeName + " " + Translations.GetString("Point Added")));
+
+					SEngines[closestShapeIndex].ControlPoints.Insert(closestPointIndex,
+						new ControlPoint(new PointD(current_point.X, current_point.Y), DefaultMidPointTension));
+				}
+
+				//These should be set after creating the history item.
+				SelectedPointIndex = closestPointIndex;
+				SelectedShapeIndex = closestShapeIndex;
+
+				ShapeEngine? activeEngine = ActiveShapeEngine;
+
+				if (activeEngine != null)
+				{
+					UpdateToolbarSettings(activeEngine);
 				}
 			}

 			//Create a new shape if the user control + clicks on a shape or if the user simply clicks outside of any shapes.
-			if (!changing_tension && (ctrlKey || (closestCPDistance >= currentClickRange && closestDistance >= currentClickRange))) {
+			if (!changing_tension && (ctrlKey || (!clicked_control_point && !clicked_generated_point))) {
 				//Verify that the user clicked inside the image bounds or that the user is
 				//holding the Ctrl key (to ignore the Image bounds and draw on the edge).
 				if ((point.X == shape_origin.X && point.Y == shape_origin.Y) || ctrlKey) {
@@ -796,7 +771,7 @@
 						doc.Layers.CurrentUserLayer.Surface.Clone (), doc.Layers.CurrentUserLayer, SelectedPointIndex, SelectedShapeIndex, false));

 					//Create the shape, add its starting points, and add it to SEngines.
-					SEngines.Add (CreateShape (ctrlKey, clickedOnControlPoint, prevSelPoint));
+					SEngines.Add (CreateShape (ctrlKey, clicked_control_point, prevSelPoint));

 					//Select the new shape.
 					SelectedShapeIndex = SEngines.Count - 1;
@@ -810,7 +785,7 @@

 					StorePreviousSettings ();
 				}
-			} else if (clickedOnControlPoint) {
+			} else if (clicked_control_point) {
 				//Since the user is not creating a new shape or control point but rather modifying an existing control point, it should be determined
 				//whether the currently active tool matches the clicked on shape's corresponding tool, and if not, switch to it.
 				if (ActivateCorrespondingTool (SelectedShapeIndex, true) != null) {
@@ -831,7 +806,7 @@
 			}

 			//Determine if the user right clicks outside of any shapes (neither on their control points nor on their generated points).
-			if ((closestCPDistance >= currentClickRange && closestDistance >= currentClickRange) && changing_tension) {
+			if ((!clicked_control_point && !clicked_generated_point) && changing_tension) {
 				clicked_without_modifying = true;
 			}


add missing [Serializable] to Chain.Where dialog

--- CSharp/Library/Dialogs/Chain.cs
+++ CSharp/Library/Dialogs/Chain.cs
@@ -547,6 +547,7 @@
             }
         }

+        [Serializable]
         private sealed class WhereDialog<T> : IDialog<T>
         {
             public readonly IDialog<T> Antecedent;


Changed 'average member rating' label to 'average rating'

--- CVGS/Views/Games/Details.cshtml
+++ CVGS/Views/Games/Details.cshtml
@@ -75,7 +75,7 @@
                 @Html.DisplayFor(model => model.Cost)

-                Average Member Rating
+                Average Rating

                 @if (Model.REVIEWs.Count > 0)


added new numeric values to IsTrue function

--- CalcLang/Interpreter/Runtime.cs
+++ CalcLang/Interpreter/Runtime.cs
@@ -114,10 +114,14 @@
                 return (bool)value;
             if (value is int)
                 return (int)value != 0;
+            if (value is long)
+                return (long)value != 0;
             if (Equals(value, NullValue))
                 return false;
             if (value is double)
                 return (double)value != 0;
+            if (value is decimal)
+                return (decimal)value != 0;
             return value != null;
         }


Changed the share message

Changed the share message

--- Portable/ViewModels/DonationResultPageViewModel.cs
+++ Portable/ViewModels/DonationResultPageViewModel.cs
@@ -40,8 +40,7 @@
             CrossShare.Current.Share(new ShareMessage
             {
                 Title = "Doná Uruguay!",
-                Text = $"Acabo de donar{institutionNameOrEmpty} a través de Doná. ¡Vos también podes donar! Descargala de Google Play. Visitá nuestra página http://fb.com/donauruguay",
-                Url = "http://play.google.com/store/apps/details?id=donauruguay"
+                Text = $"Acabo de donar{institutionNameOrEmpty} a través de Doná. ¡Vos también podes donar! http://fb.com/donauruguay"
             });
         }


Tune margins

Tune margins

--- PrinterControls/ControlWidgets/MovementControls.cs
+++ PrinterControls/ControlWidgets/MovementControls.cs
@@ -132,7 +132,6 @@
 				}
 			};

-
 			jogControls = new JogControls(new XYZColors());
 			jogControls.Margin = new BorderDouble(0);

@@ -140,7 +139,7 @@
 			{
 				HAnchor = HAnchor.ParentLeftRight,
 				VAnchor = VAnchor.FitToChildren,
-				Padding = new BorderDouble(3, 5, 3, 0)
+				Padding = new BorderDouble(3, 0)
 			};

 			manualControlsLayout.AddChild(CreateDisableableContainer(GetHomeButtonBar()));
@@ -149,7 +148,10 @@

 			manualControlsLayout.AddChild(CreateSeparatorLine());
 			manualControlsLayout.AddChild(CreateDisableableContainer(GetHWDestinationBar()));
-			manualControlsLayout.AddChild(CreateSeparatorLine());
+
+			var separator = CreateSeparatorLine();
+			separator.Margin = new BorderDouble(0, 0, 0, 5);
+			manualControlsLayout.AddChild(separator);

 			movementControlsGroupBox.AddChild(manualControlsLayout);


修改日志细节

修改日志细节

--- ChromeAutoUpdate/UdpListener.cs
+++ ChromeAutoUpdate/UdpListener.cs
@@ -334,7 +334,7 @@
                                                 new IPEndPoint(IPAddress.Parse(n["ip"].ToString()),
                                                 (int)n["port"]
                                                 )));
-                                                log("find新节点"+ n["uid"].ToString() + n["ip"].ToString());
+                                                log("find新节点 "+ n["uid"].ToString() + ":" + n["ip"].ToString());
                                             }
                                             else
                                             {


manually rewrite request

manually rewrite request

--- src/TerrainFlow/Startup.cs
+++ src/TerrainFlow/Startup.cs
@@ -58,16 +58,19 @@
         {
             loggerFactory.AddConsole();
             loggerFactory.AddDebug();
-
+
             Trace.Listeners.Add(new AzureApplicationLogTraceListener());
-
-            app.UseForwardedHeaders(new ForwardedHeadersOptions
-            {
-                ForwardedHeaders = ForwardedHeaders.All
-            });

             // Add the platform handler to the request pipeline.
             app.UseIISPlatformHandler();
+
+            app.Use(async (context, next) =>
+            {
+                Console.WriteLine("X-Forwarded-Proto: " + context.Request.Headers["X -Forwarded-Proto"]);
+                context.Request.IsHttps = true;
+                context.Request.Scheme = "https";
+                await next.Invoke();
+            });

             app.UseCookieAuthentication(new CookieAuthenticationOptions
             {