Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Simplify check and fix for new DynamicGetter
using System; using Structurizer.Extensions; namespace Structurizer.Schemas { public class StructureProperty : IStructureProperty { private readonly DynamicGetter _getter; public string Name { get; } public string Path { get; } public Type DataType { get; } public IStructureProperty Parent { get; } public bool IsRootMember { get; } public bool IsEnumerable { get; } public bool IsElement { get; } public Type ElementDataType { get; } public StructureProperty(StructurePropertyInfo info, DynamicGetter getter) { _getter = getter; Parent = info.Parent; Name = info.Name; DataType = info.DataType; IsRootMember = info.Parent == null; var isSimpleOrValueType = DataType.IsSimpleType() || DataType.IsValueType; IsEnumerable = !isSimpleOrValueType && DataType.IsEnumerableType(); IsElement = Parent != null && (Parent.IsElement || Parent.IsEnumerable); ElementDataType = IsEnumerable ? DataType.GetEnumerableElementType() : null; Path = PropertyPathBuilder.BuildPath(this); } public virtual object GetValue(object item) => _getter.GetValue(item); } }
using System; using Structurizer.Extensions; namespace Structurizer.Schemas { public class StructureProperty : IStructureProperty { private readonly DynamicGetter _getter; public string Name { get; } public string Path { get; } public Type DataType { get; } public IStructureProperty Parent { get; } public bool IsRootMember { get; } public bool IsEnumerable { get; } public bool IsElement { get; } public Type ElementDataType { get; } public StructureProperty(StructurePropertyInfo info, DynamicGetter getter) { _getter = getter; Parent = info.Parent; Name = info.Name; DataType = info.DataType; IsRootMember = info.Parent == null; IsEnumerable = !DataType.IsSimpleType() && DataType.IsEnumerableType(); IsElement = Parent != null && (Parent.IsElement || Parent.IsEnumerable); ElementDataType = IsEnumerable ? DataType.GetEnumerableElementType() : null; Path = PropertyPathBuilder.BuildPath(this); } public object GetValue(object item) => _getter(item); } }
Fix for the NotEmpty method.
// Copyright 2009 Jeffrey Cameron // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Concordion.Internal.Util { public class Check { public static void IsTrue(bool expression, string message, params object[] args) { if (!expression) { throw new Exception(String.Format(message, args)); } } public static void IsFalse(bool expression, string message, params object[] args) { IsTrue(!expression, message, args); } public static void NotNull(object obj, string message, params object[] args) { IsTrue(obj != null, message, args); } public static void NotEmpty(string str, string message, params object[] args) { IsTrue(String.IsNullOrEmpty(str), message, args); } } }
// Copyright 2009 Jeffrey Cameron // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Concordion.Internal.Util { public class Check { public static void IsTrue(bool expression, string message, params object[] args) { if (!expression) { throw new Exception(String.Format(message, args)); } } public static void IsFalse(bool expression, string message, params object[] args) { IsTrue(!expression, message, args); } public static void NotNull(object obj, string message, params object[] args) { IsTrue(obj != null, message, args); } public static void NotEmpty(string str, string message, params object[] args) { IsTrue(!String.IsNullOrEmpty(str), message, args); } } }
Add messageBack to action types.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Microsoft.Bot.Connector { public class ActionTypes { /// <summary> /// Client will open given url in the built-in browser. /// </summary> public const string OpenUrl = "openUrl"; /// <summary> /// Client will post message to bot, so all other participants will see that was posted to the bot and who posted this. /// </summary> public const string ImBack = "imBack"; /// <summary> /// Client will post message to bot privately, so other participants inside conversation will not see that was posted. /// </summary> public const string PostBack = "postBack"; /// <summary> /// playback audio container referenced by url /// </summary> public const string PlayAudio = "playAudio"; /// <summary> /// playback video container referenced by url /// </summary> public const string PlayVideo = "playVideo"; /// <summary> /// show image referenced by url /// </summary> public const string ShowImage = "showImage"; /// <summary> /// download file referenced by url /// </summary> public const string DownloadFile = "downloadFile"; /// <summary> /// Signin button /// </summary> public const string Signin = "signin"; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Microsoft.Bot.Connector { public class ActionTypes { /// <summary> /// Client will open given url in the built-in browser. /// </summary> public const string OpenUrl = "openUrl"; /// <summary> /// Client will post message to bot, so all other participants will see that was posted to the bot and who posted this. /// </summary> public const string ImBack = "imBack"; /// <summary> /// Client will post message to bot privately, so other participants inside conversation will not see that was posted. /// </summary> public const string PostBack = "postBack"; /// <summary> /// playback audio container referenced by url /// </summary> public const string PlayAudio = "playAudio"; /// <summary> /// playback video container referenced by url /// </summary> public const string PlayVideo = "playVideo"; /// <summary> /// show image referenced by url /// </summary> public const string ShowImage = "showImage"; /// <summary> /// download file referenced by url /// </summary> public const string DownloadFile = "downloadFile"; /// <summary> /// Signin button /// </summary> public const string Signin = "signin"; /// <summary> /// Post message to bot /// </summary> public const string MessageBack = "messageBack"; } }
Enable nullable and don't bother null checking at every read.
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.IO; namespace osu.Framework.Audio.Callbacks { /// <summary> /// Implementation of <see cref="IFileProcedures"/> that supports reading from a <see cref="Stream"/>. /// </summary> public class DataStreamFileProcedures : IFileProcedures { private readonly Stream dataStream; public DataStreamFileProcedures(Stream data) { dataStream = data; } public void Close(IntPtr user) { } public long Length(IntPtr user) { if (dataStream?.CanSeek != true) return 0; try { return dataStream.Length; } catch { return 0; } } public unsafe int Read(IntPtr buffer, int length, IntPtr user) { if (dataStream?.CanRead != true) return 0; try { return dataStream.Read(new Span<byte>((void*)buffer, length)); } catch { return 0; } } public bool Seek(long offset, IntPtr user) { if (dataStream?.CanSeek != true) return false; try { return dataStream.Seek(offset, SeekOrigin.Begin) == offset; } catch { return false; } } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.IO; #nullable enable namespace osu.Framework.Audio.Callbacks { /// <summary> /// Implementation of <see cref="IFileProcedures"/> that supports reading from a <see cref="Stream"/>. /// </summary> public class DataStreamFileProcedures : IFileProcedures { private readonly Stream dataStream; public DataStreamFileProcedures(Stream data) { dataStream = data; } public void Close(IntPtr user) { } public long Length(IntPtr user) { if (!dataStream.CanSeek) return 0; try { return dataStream.Length; } catch { return 0; } } public unsafe int Read(IntPtr buffer, int length, IntPtr user) { if (!dataStream.CanRead) return 0; try { return dataStream.Read(new Span<byte>((void*)buffer, length)); } catch { return 0; } } public bool Seek(long offset, IntPtr user) { if (!dataStream.CanSeek) return false; try { return dataStream.Seek(offset, SeekOrigin.Begin) == offset; } catch { return false; } } } }
Add an error message if opening the log file fails.
using System.Diagnostics; namespace Microsoft.Build.Logging.StructuredLogger { public class BinaryLog { public static Build ReadBuild(string filePath) { var eventSource = new BinaryLogReplayEventSource(); byte[] sourceArchive = null; eventSource.OnBlobRead += (kind, bytes) => { if (kind == BinaryLogRecordKind.SourceArchive) { sourceArchive = bytes; } }; StructuredLogger.SaveLogToDisk = false; StructuredLogger.CurrentBuild = null; var structuredLogger = new StructuredLogger(); structuredLogger.Parameters = "build.buildlog"; structuredLogger.Initialize(eventSource); var sw = Stopwatch.StartNew(); eventSource.Replay(filePath); var elapsed = sw.Elapsed; var build = StructuredLogger.CurrentBuild; StructuredLogger.CurrentBuild = null; build.SourceFilesArchive = sourceArchive; // build.AddChildAtBeginning(new Message { Text = "Elapsed: " + elapsed.ToString() }); return build; } } }
using System.Diagnostics; namespace Microsoft.Build.Logging.StructuredLogger { public class BinaryLog { public static Build ReadBuild(string filePath) { var eventSource = new BinaryLogReplayEventSource(); byte[] sourceArchive = null; eventSource.OnBlobRead += (kind, bytes) => { if (kind == BinaryLogRecordKind.SourceArchive) { sourceArchive = bytes; } }; StructuredLogger.SaveLogToDisk = false; StructuredLogger.CurrentBuild = null; var structuredLogger = new StructuredLogger(); structuredLogger.Parameters = "build.buildlog"; structuredLogger.Initialize(eventSource); var sw = Stopwatch.StartNew(); eventSource.Replay(filePath); var elapsed = sw.Elapsed; var build = StructuredLogger.CurrentBuild; StructuredLogger.CurrentBuild = null; if (build == null) { build = new Build() { Succeeded = false }; build.AddChild(new Error() { Text = "Error when opening the file: " + filePath }); } build.SourceFilesArchive = sourceArchive; // build.AddChildAtBeginning(new Message { Text = "Elapsed: " + elapsed.ToString() }); return build; } } }
Add diagnostic try-catch blocks to MorphInto()
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Zermelo.App.UWP.Helpers { static class ObservableCollectionExtensions { public static void MorphInto<TSource>(this ObservableCollection<TSource> first, IReadOnlyList<TSource> second) { var add = second.Except(first); var remove = first.Except(second); foreach (var i in remove) first.Remove(i); foreach (var i in add) first.Add(i); // If there are any changes to first, make sure it's in // the same order as second. if (add.Count() > 0 || remove.Count() > 0) for (int i = 0; i < second.Count(); i++) first.Move(first.IndexOf(second.ElementAt(i)), i); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Zermelo.App.UWP.Helpers { static class ObservableCollectionExtensions { public static void MorphInto<TSource>(this ObservableCollection<TSource> first, IReadOnlyList<TSource> second) { var add = second.Except(first); var remove = first.Except(second); // TODO: Remove the diagnostic try-catch blocks, when #12 is fixed try { foreach (var i in remove) first.Remove(i); } catch (InvalidOperationException ex) { throw new Exception("Exception in the Remove loop.", ex); } try { foreach (var i in add) first.Add(i); } catch (InvalidOperationException ex) { throw new Exception("Exception in the Add loop.", ex); } try { // If there are any changes to first, make sure it's in // the same order as second. if (add.Count() > 0 || remove.Count() > 0) for (int i = 0; i < second.Count(); i++) first.Move(first.IndexOf(second.ElementAt(i)), i); } catch (InvalidOperationException ex) { throw new Exception("Exception in the reordering loop.", ex); } } } }
Add giftcard method to list of methods
namespace Mollie.Api.Models { /// <summary> /// Payment method /// </summary> public enum Method { ideal, creditcard, mistercash, sofort, banktransfer, directdebit, belfius, kbc, bitcoin, paypal, paysafecard, } }
namespace Mollie.Api.Models { /// <summary> /// Payment method /// </summary> public enum Method { ideal, creditcard, mistercash, sofort, banktransfer, directdebit, belfius, kbc, bitcoin, paypal, paysafecard, giftcard, } }
Make the shuffle more noticable.
using System; using System.Collections.ObjectModel; using ReactiveUI; namespace BindingTest.ViewModels { public class MainWindowViewModel : ReactiveObject { private string _simpleBinding = "Simple Binding"; public MainWindowViewModel() { Items = new ObservableCollection<TestItem> { new TestItem { StringValue = "Foo" }, new TestItem { StringValue = "Bar" }, new TestItem { StringValue = "Baz" }, }; ShuffleItems = ReactiveCommand.Create(); ShuffleItems.Subscribe(_ => { var r = new Random(); Items[r.Next(Items.Count)] = Items[r.Next(Items.Count)]; }); } public ObservableCollection<TestItem> Items { get; } public ReactiveCommand<object> ShuffleItems { get; } public string SimpleBinding { get { return _simpleBinding; } set { this.RaiseAndSetIfChanged(ref _simpleBinding, value); } } } }
using System; using System.Collections.ObjectModel; using ReactiveUI; namespace BindingTest.ViewModels { public class MainWindowViewModel : ReactiveObject { private string _simpleBinding = "Simple Binding"; public MainWindowViewModel() { Items = new ObservableCollection<TestItem> { new TestItem { StringValue = "Foo" }, new TestItem { StringValue = "Bar" }, new TestItem { StringValue = "Baz" }, }; ShuffleItems = ReactiveCommand.Create(); ShuffleItems.Subscribe(_ => { var r = new Random(); Items[1] = Items[r.Next(Items.Count)]; }); } public ObservableCollection<TestItem> Items { get; } public ReactiveCommand<object> ShuffleItems { get; } public string SimpleBinding { get { return _simpleBinding; } set { this.RaiseAndSetIfChanged(ref _simpleBinding, value); } } } }
Set size for the fields on contact form
using System.ComponentModel.DataAnnotations; using Newtonsoft.Json.Linq; namespace CmsEngine.Application.Helpers.Email { public class ContactForm { [Required] [DataType(DataType.EmailAddress)] public string From { get; set; } [DataType(DataType.EmailAddress)] public string To { get; set; } [Required] public string Subject { get; set; } [Required] public string Message { get; set; } public ContactForm() { } public ContactForm(string to, string subject, string message) { To = to; Subject = subject; Message = message; } public override string ToString() { var jsonResult = new JObject( new JProperty("From", From), new JProperty("To", To), new JProperty("Subject", Subject), new JProperty("Message", Message) ); return jsonResult.ToString(); } } }
using System.ComponentModel.DataAnnotations; using Newtonsoft.Json.Linq; namespace CmsEngine.Application.Helpers.Email { public class ContactForm { [Required] [DataType(DataType.EmailAddress)] public string From { get; set; } [DataType(DataType.EmailAddress)] public string To { get; set; } [Required] [MaxLength(150)] public string Subject { get; set; } [Required] [MaxLength(500)] public string Message { get; set; } public ContactForm() { } public ContactForm(string to, string subject, string message) { To = to; Subject = subject; Message = message; } public override string ToString() { var jsonResult = new JObject( new JProperty("From", From), new JProperty("To", To), new JProperty("Subject", Subject), new JProperty("Message", Message) ); return jsonResult.ToString(); } } }
Disable 2nd sandbox test by default
using System; namespace ClosedXML_Sandbox { internal class Program { private static void Main(string[] args) { Console.WriteLine("Running {0}", nameof(PerformanceRunner.OpenTestFile)); PerformanceRunner.TimeAction(PerformanceRunner.OpenTestFile); Console.WriteLine(); Console.WriteLine("Running {0}", nameof(PerformanceRunner.RunInsertTable)); PerformanceRunner.TimeAction(PerformanceRunner.RunInsertTable); Console.WriteLine(); Console.WriteLine("Press any key to continue"); Console.ReadKey(); } } }
using System; namespace ClosedXML_Sandbox { internal static class Program { private static void Main(string[] args) { Console.WriteLine("Running {0}", nameof(PerformanceRunner.OpenTestFile)); PerformanceRunner.TimeAction(PerformanceRunner.OpenTestFile); Console.WriteLine(); // Disable this block by default - I don't use it often #if false Console.WriteLine("Running {0}", nameof(PerformanceRunner.RunInsertTable)); PerformanceRunner.TimeAction(PerformanceRunner.RunInsertTable); Console.WriteLine(); #endif Console.WriteLine("Press any key to continue"); Console.ReadKey(); } } }
Increment version number to 1.3.5.0
namespace formulate.meta { /// <summary> /// Constants relating to Formulate itself (i.e., does not /// include constants used by Formulate). /// </summary> public class Constants { /// <summary> /// This is the version of Formulate. It is used on /// assemblies and during the creation of the /// installer package. /// </summary> /// <remarks> /// Do not reformat this code. A grunt task reads this /// version number with a regular expression. /// </remarks> public const string Version = "1.3.4.0"; /// <summary> /// The name of the Formulate package. /// </summary> public const string PackageName = "Formulate"; /// <summary> /// The name of the Formulate package, in camel case. /// </summary> public const string PackageNameCamelCase = "formulate"; } }
namespace formulate.meta { /// <summary> /// Constants relating to Formulate itself (i.e., does not /// include constants used by Formulate). /// </summary> public class Constants { /// <summary> /// This is the version of Formulate. It is used on /// assemblies and during the creation of the /// installer package. /// </summary> /// <remarks> /// Do not reformat this code. A grunt task reads this /// version number with a regular expression. /// </remarks> public const string Version = "1.3.5.0"; /// <summary> /// The name of the Formulate package. /// </summary> public const string PackageName = "Formulate"; /// <summary> /// The name of the Formulate package, in camel case. /// </summary> public const string PackageNameCamelCase = "formulate"; } }
Revert "Make all strings in loaded TdfNodes lowercase"
namespace TAUtil.Tdf { using System.Collections.Generic; public class TdfNodeAdapter : ITdfNodeAdapter { private readonly Stack<TdfNode> nodeStack = new Stack<TdfNode>(); public TdfNodeAdapter() { this.RootNode = new TdfNode(); this.nodeStack.Push(this.RootNode); } public TdfNode RootNode { get; private set; } public void BeginBlock(string name) { name = name.ToLowerInvariant(); TdfNode n = new TdfNode(name); this.nodeStack.Peek().Keys[name] = n; this.nodeStack.Push(n); } public void AddProperty(string name, string value) { name = name.ToLowerInvariant(); value = value.ToLowerInvariant(); this.nodeStack.Peek().Entries[name] = value; } public void EndBlock() { this.nodeStack.Pop(); } } }
namespace TAUtil.Tdf { using System.Collections.Generic; public class TdfNodeAdapter : ITdfNodeAdapter { private readonly Stack<TdfNode> nodeStack = new Stack<TdfNode>(); public TdfNodeAdapter() { this.RootNode = new TdfNode(); this.nodeStack.Push(this.RootNode); } public TdfNode RootNode { get; private set; } public void BeginBlock(string name) { TdfNode n = new TdfNode(name); this.nodeStack.Peek().Keys[name] = n; this.nodeStack.Push(n); } public void AddProperty(string name, string value) { this.nodeStack.Peek().Entries[name] = value; } public void EndBlock() { this.nodeStack.Pop(); } } }
Add private constructor to singleton class
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; namespace tweetz5.Utilities.Translate { public class TranslationService { public readonly static TranslationService Instance = new TranslationService(); public ITranslationProvider TranslationProvider { get; set; } public event EventHandler LanguageChanged; public CultureInfo CurrentLanguage { get { return Thread.CurrentThread.CurrentUICulture; } set { if (value.Equals(Thread.CurrentThread.CurrentUICulture) == false) { Thread.CurrentThread.CurrentUICulture = value; OnLanguageChanged(); } } } private void OnLanguageChanged() { if (LanguageChanged != null) { LanguageChanged(this, EventArgs.Empty); } } public IEnumerable<CultureInfo> Languages { get { return (TranslationProvider != null) ? TranslationProvider.Languages : Enumerable.Empty<CultureInfo>(); } } public object Translate(string key) { if (TranslationProvider != null) { var translatedValue = TranslationProvider.Translate(key); if (translatedValue != null) { return translatedValue; } } return string.Format("!{0}!", key); } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; namespace tweetz5.Utilities.Translate { public class TranslationService { public readonly static TranslationService Instance = new TranslationService(); public ITranslationProvider TranslationProvider { get; set; } public event EventHandler LanguageChanged; private TranslationService() { } public CultureInfo CurrentLanguage { get { return Thread.CurrentThread.CurrentUICulture; } set { if (value.Equals(Thread.CurrentThread.CurrentUICulture) == false) { Thread.CurrentThread.CurrentUICulture = value; OnLanguageChanged(); } } } private void OnLanguageChanged() { if (LanguageChanged != null) { LanguageChanged(this, EventArgs.Empty); } } public IEnumerable<CultureInfo> Languages { get { return (TranslationProvider != null) ? TranslationProvider.Languages : Enumerable.Empty<CultureInfo>(); } } public object Translate(string key) { if (TranslationProvider != null) { var translatedValue = TranslationProvider.Translate(key); if (translatedValue != null) { return translatedValue; } } return string.Format("!{0}!", key); } } }
Add null checks for MethodReplacer
using System.Collections.Generic; using System.Reflection; using System.Reflection.Emit; namespace Harmony { public static class Transpilers { public static IEnumerable<CodeInstruction> MethodReplacer(this IEnumerable<CodeInstruction> instructions, MethodBase from, MethodBase to, OpCode? callOpcode = null) { foreach (var instruction in instructions) { var method = instruction.operand as MethodBase; if (method == from) { instruction.opcode = callOpcode ?? OpCodes.Call; instruction.operand = to; } yield return instruction; } } public static IEnumerable<CodeInstruction> DebugLogger(this IEnumerable<CodeInstruction> instructions, string text) { yield return new CodeInstruction(OpCodes.Ldstr, text); yield return new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(FileLog), nameof(FileLog.Log))); foreach (var instruction in instructions) yield return instruction; } // more added soon } }
using System; using System.Collections.Generic; using System.Reflection; using System.Reflection.Emit; namespace Harmony { public static class Transpilers { public static IEnumerable<CodeInstruction> MethodReplacer(this IEnumerable<CodeInstruction> instructions, MethodBase from, MethodBase to, OpCode? callOpcode = null) { if (from == null) throw new ArgumentException("Unexpected null argument", nameof(from)); if (to == null) throw new ArgumentException("Unexpected null argument", nameof(to)); foreach (var instruction in instructions) { var method = instruction.operand as MethodBase; if (method == from) { instruction.opcode = callOpcode ?? OpCodes.Call; instruction.operand = to; } yield return instruction; } } public static IEnumerable<CodeInstruction> DebugLogger(this IEnumerable<CodeInstruction> instructions, string text) { yield return new CodeInstruction(OpCodes.Ldstr, text); yield return new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(FileLog), nameof(FileLog.Log))); foreach (var instruction in instructions) yield return instruction; } // more added soon } }
Correct detection of scrape requests
using System; using System.Collections.Generic; using System.Text; using MonoTorrent.BEncoding; using System.Net; namespace MonoTorrent.Tracker.Listeners { public class ManualListener : ListenerBase { private bool running; public override bool Running { get { return running; } } public override void Start() { running = true; } public override void Stop() { running = false; } public BEncodedValue Handle(string rawUrl, IPAddress remoteAddress) { if (rawUrl == null) throw new ArgumentNullException("rawUrl"); if (remoteAddress == null) throw new ArgumentOutOfRangeException("remoteAddress"); bool isScrape = rawUrl.StartsWith("/scrape", StringComparison.OrdinalIgnoreCase); return Handle(rawUrl, remoteAddress, isScrape); } } }
using System; using System.Collections.Generic; using System.Text; using MonoTorrent.BEncoding; using System.Net; namespace MonoTorrent.Tracker.Listeners { public class ManualListener : ListenerBase { private bool running; public override bool Running { get { return running; } } public override void Start() { running = true; } public override void Stop() { running = false; } public BEncodedValue Handle(string rawUrl, IPAddress remoteAddress) { if (rawUrl == null) throw new ArgumentNullException("rawUrl"); if (remoteAddress == null) throw new ArgumentOutOfRangeException("remoteAddress"); rawUrl = rawUrl.Substring(rawUrl.LastIndexOf('/')); bool isScrape = rawUrl.StartsWith("/scrape", StringComparison.OrdinalIgnoreCase); return Handle(rawUrl, remoteAddress, isScrape); } } }
Add square matrix multiplication test case.
using NUnit.Framework; namespace Algorithms.Collections.Tests { [TestFixture] public class SquareMatrixTests { } }
using System.Collections.Generic; using System.Globalization; using System.Text; using NUnit.Framework; namespace Algorithms.Collections.Tests { [TestFixture] public class SquareMatrixTests { [TestCaseSource("GetTestCases")] public void Multiply(TestCase testCase) { int[,] result = SquareMatrix.Multiply(testCase.Left, testCase.Right, (x, y) => x + y, (x, y) => x * y); CollectionAssert.AreEqual(result, testCase.Product); } public IEnumerable<TestCase> GetTestCases() { return new[] { new TestCase { Left = new[,] {{1, 2}, {3, 4}}, Right = new[,] {{4, 3}, {2, 1}}, Product = new[,] {{8, 5}, {20, 13}}, }, }; } public class TestCase { public int[,] Left { get; set; } public int[,] Right { get; set; } public int[,] Product { get; set; } public override string ToString() { return string.Format("{{Left={0}, Right={1}, Product={2}}}", RenderMatrix(Left), RenderMatrix(Right), RenderMatrix(Product)); } private static string RenderMatrix(int[,] matrix) { var builder = new StringBuilder(); builder.Append("{"); for (int row = 0; row < matrix.GetLength(0); row++) { if (row != 0) builder.Append(","); builder.Append("{"); for (int column = 0; column < matrix.GetLength(1); column++) { if (column != 0) builder.Append(","); builder.Append(matrix[row, column]); } builder.Append("}"); } builder.Append("}"); return builder.ToString(); } private static string RenderRow(int row, int[,] matrix, int padding) { var builder = new StringBuilder(); if (row < matrix.GetLength(row)) { for (int column = 0; column < matrix.GetLength(1); column++) builder.Append(matrix[row, column].ToString(CultureInfo.InvariantCulture).PadLeft(padding)); } return builder.ToString(); } } } }
Convert seconds to actual minutes (works up to an hour...)
using UnityEngine; using UnityEngine.UI; public class LeaderboardEntry : MonoBehaviour { [SerializeField] private Text _name; [SerializeField] private Text _time; [SerializeField] private Text _penality; public void SetInfo(Score score) { _name.text = score.Name; _time.text = score.Time.ToString(); _penality.text = score.Penality.ToString(); } }
using UnityEngine; using UnityEngine.UI; public class LeaderboardEntry : MonoBehaviour { [SerializeField] private Text _name; [SerializeField] private Text _time; [SerializeField] private Text _penality; public void SetInfo(Score score) { _name.text = score.Name; var time = score.Time; _time.text = string.Format("{0}:{1:00}", time / 60, time % 60); _penality.text = score.Penality.ToString(); } }
Revert "Something new from Peter"
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestingApplication { class Program { static void Main(string[] args) { Console.WriteLine("Hello World\nPress any key to close..."); Console.WriteLine("Added some text"); Console.WriteLine("Something new from Peter"); Console.ReadKey(); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestingApplication { class Program { static void Main(string[] args) { Console.WriteLine("Hello World\nPress any key to close..."); Console.WriteLine("Added some text"); Console.ReadKey(); } } }
Add support for listing invoice items via invoice and pending
namespace Stripe { using Newtonsoft.Json; public class InvoiceItemListOptions : ListOptionsWithCreated { [JsonProperty("customer")] public string CustomerId { get; set; } } }
namespace Stripe { using Newtonsoft.Json; public class InvoiceItemListOptions : ListOptionsWithCreated { [JsonProperty("customer")] public string CustomerId { get; set; } [JsonProperty("invoice")] public string InvoiceId { get; set; } [JsonProperty("pending")] public bool? Pending { get; set; } } }
Set adminModeTriggerer back to 180 seconds
using UnityEngine; using System.Collections; using System.Collections.Generic; public class AdminModeTriggerer : MonoBehaviour { private const float WAIT_TIME = 10f; public ActionBase AdminModeAction; public void Initialize() { StartCoroutine(WaitThenEnterAdminMode()); } public IEnumerator WaitThenEnterAdminMode() { yield return new WaitForSeconds(WAIT_TIME); AdminModeAction.Act(); } }
using UnityEngine; using System.Collections; using System.Collections.Generic; public class AdminModeTriggerer : MonoBehaviour { private const float WAIT_TIME = 180f; public ActionBase AdminModeAction; public void Initialize() { StartCoroutine(WaitThenEnterAdminMode()); } public IEnumerator WaitThenEnterAdminMode() { yield return new WaitForSeconds(WAIT_TIME); AdminModeAction.Act(); } }
Save ip after recording, check ip on index, version 1.0
<div class="span7"> <div id="button" class="tile quadro triple-vertical bg-lightPink bg-active-lightBlue" style="padding:10px; text-align: center;"> Your number is... <br /><br /> <span class="COUNT">@(Model)!!!</span><br /><br /> Click this pink square to record a three second video of you saying <strong>@Model</strong> in your language of choice.<br /><br /> Make yourself comfortable and get ready to join A Thousand Counts.<br /><br /> 3, 2, 1, COUNT! </div> </div>
<div class="span7"> <div id="button" class="tile quadro triple-vertical bg-lightPink bg-active-lightBlue" style="padding:10px; text-align: center;"> Your number is... <br /><br /> <span class="COUNT">@(Model)!!!</span><br /><br /> Click this pink square to record a three second video of you saying <strong>@Model</strong> in your language of choice.<br /><br /> If you don't like your number please hit refresh.<br /><br /> Make yourself comfortable and get ready to join A Thousand Counts.<br /><br /> 3, 2, 1, COUNT! </div> </div>
Fix new object was added into collection instead of the one we made just above.
using System.Collections.ObjectModel; using System.ComponentModel; namespace ProjectCDA.Data { public class DataSource : INotifyPropertyChanged { private ObservableCollection<TwoPages> _Schedule; public DataSource() { AddSomeDummyData(); } public ObservableCollection<TwoPages> Schedule { get { return _Schedule; } set { if (value != _Schedule) { _Schedule = value; PropertyChanged(this, new PropertyChangedEventArgs("Schedule")); } } } public event PropertyChangedEventHandler PropertyChanged = delegate { }; private void AddSomeDummyData() { ObservableCollection<TwoPages> TmpSchedule = new ObservableCollection<TwoPages>(); for(int i=0; i<20; i++) { TwoPages pages = new TwoPages(); pages.ID = i.ToString(); pages.RightPage = i % 5 != 3; TmpSchedule.Add(new TwoPages()); } Schedule = TmpSchedule; } } }
using System.Collections.ObjectModel; using System.ComponentModel; namespace ProjectCDA.Data { public class DataSource : INotifyPropertyChanged { private ObservableCollection<TwoPages> _Schedule; public DataSource() { AddSomeDummyData(); } public ObservableCollection<TwoPages> Schedule { get { return _Schedule; } set { if (value != _Schedule) { _Schedule = value; PropertyChanged(this, new PropertyChangedEventArgs("Schedule")); } } } public event PropertyChangedEventHandler PropertyChanged = delegate { }; private void AddSomeDummyData() { ObservableCollection<TwoPages> TmpSchedule = new ObservableCollection<TwoPages>(); for(int i=0; i<20; i++) { TwoPages pages = new TwoPages(); pages.ID = i.ToString(); pages.RightPage = i % 5 != 3; TmpSchedule.Add(pages); } Schedule = TmpSchedule; } } }
Enable suggestions for types in reference assemblies by default
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.SymbolSearch { internal static class SymbolSearchOptions { private const string LocalRegistryPath = @"Roslyn\Features\SymbolSearch\"; public static readonly Option<bool> Enabled = new Option<bool>( nameof(SymbolSearchOptions), nameof(Enabled), defaultValue: true, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + nameof(Enabled))); public static PerLanguageOption<bool> SuggestForTypesInReferenceAssemblies = new PerLanguageOption<bool>(nameof(SymbolSearchOptions), nameof(SuggestForTypesInReferenceAssemblies), defaultValue: false, storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.SuggestForTypesInReferenceAssemblies")); public static PerLanguageOption<bool> SuggestForTypesInNuGetPackages = new PerLanguageOption<bool>(nameof(SymbolSearchOptions), nameof(SuggestForTypesInNuGetPackages), defaultValue: false, storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.SuggestForTypesInNuGetPackages")); } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.SymbolSearch { internal static class SymbolSearchOptions { private const string LocalRegistryPath = @"Roslyn\Features\SymbolSearch\"; public static readonly Option<bool> Enabled = new Option<bool>( nameof(SymbolSearchOptions), nameof(Enabled), defaultValue: true, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + nameof(Enabled))); public static PerLanguageOption<bool> SuggestForTypesInReferenceAssemblies = new PerLanguageOption<bool>(nameof(SymbolSearchOptions), nameof(SuggestForTypesInReferenceAssemblies), defaultValue: true, storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.SuggestForTypesInReferenceAssemblies")); public static PerLanguageOption<bool> SuggestForTypesInNuGetPackages = new PerLanguageOption<bool>(nameof(SymbolSearchOptions), nameof(SuggestForTypesInNuGetPackages), defaultValue: false, storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.SuggestForTypesInNuGetPackages")); } }
Add autofocus to AccessCode entry so invalid entry will force focus onto the input field
@model SFA.DAS.EmployerUsers.Web.Models.AccessCodeViewModel <h1 class="heading-large">Register</h1> @if (!Model.Valid) { <div class="error" style="margin-bottom: 10px;"> <p class="error-message"> Invalid Code </p> </div> } <form method="post"> <fieldset> <legend class="visuallyhidden">Access code for user registration</legend> <div class="form-group"> <label class="form-label" for="AccessCode">Access Code</label> <input class="form-control" id="AccessCode" name="AccessCode"> </div> </fieldset> <button type="submit" class="button">Activate Account</button> </form>
@model SFA.DAS.EmployerUsers.Web.Models.AccessCodeViewModel @{ var invalidAttributes = Model.Valid ? "aria-invalid=\"true\" aria-labeledby=\"invalidMessage\"" : ""; } <h1 class="heading-large">Register</h1> @if (!Model.Valid) { <div id="invalidMessage" class="error" style="margin-bottom: 10px;"> <p class="error-message"> Invalid Code </p> </div> } <form method="post"> <fieldset> <legend class="visuallyhidden">Access code for user registration</legend> <div class="form-group"> <label class="form-label" for="AccessCode">Access Code</label> <input @invalidAttributes autofocus="autofocus" aria-required="true" class="form-control" id="AccessCode" name="AccessCode"> </div> </fieldset> <button type="submit" class="button">Activate Account</button> </form>
Use CloudFlare CF-Connecting-IP to access user ip address
using Infra.Authentications; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Net; using System.Security.Claims; using System.Threading; using Infra.Events; namespace Infra.Authentications.Identity.Services { public class Authenticator : IAuthenticator { public Authenticator(IEnumerable<IAuthenticationObserver> monitors) { Monitors = monitors; } IEnumerable<IAuthenticationObserver> Monitors { get; } public IPAddress ClientIP { get { IPAddress address; if (IPAddress.TryParse(HttpContext.Current.Request.UserHostAddress, out address)) return address; return IPAddress.None; } } public string ImpersonatorId { get { if (!IsAuthenticated) return null; return Identity.GetImpersonatorId(); } } public string UserId { get { if (!IsAuthenticated) return null; foreach (var monitor in Monitors) monitor.Observe(this); return Identity.Name; } } ClaimsPrincipal Principal => Thread.CurrentPrincipal as ClaimsPrincipal; ClaimsIdentity Identity => Principal?.Identity as ClaimsIdentity; bool IsAuthenticated => Identity?.IsAuthenticated ?? false; } }
using Infra.Authentications; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Net; using System.Security.Claims; using System.Threading; using Infra.Events; namespace Infra.Authentications.Identity.Services { public class Authenticator : IAuthenticator { public Authenticator(IEnumerable<IAuthenticationObserver> monitors) { Monitors = monitors; } IEnumerable<IAuthenticationObserver> Monitors { get; } public IPAddress ClientIP { get { IPAddress address; if (IPAddress.TryParse(HttpContext.Current.Request.Headers.GetValues("CF-Connecting-IP").FirstOrDefault(), out address)) return address; return IPAddress.None; } } public string ImpersonatorId { get { if (!IsAuthenticated) return null; return Identity.GetImpersonatorId(); } } public string UserId { get { if (!IsAuthenticated) return null; foreach (var monitor in Monitors) monitor.Observe(this); return Identity.Name; } } ClaimsPrincipal Principal => Thread.CurrentPrincipal as ClaimsPrincipal; ClaimsIdentity Identity => Principal?.Identity as ClaimsIdentity; bool IsAuthenticated => Identity?.IsAuthenticated ?? false; } }
Add extension method for StatefulModel.MultipleDisposable.
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace MetroTrilithon.Lifetime { public static class DisposableExtensions { /// <summary> /// <see cref="IDisposable"/> オブジェクトを、指定した <see cref="IDisposableHolder.CompositeDisposable"/> に追加します。 /// </summary> public static T AddTo<T>(this T disposable, IDisposableHolder obj) where T : IDisposable { if (obj == null) { disposable.Dispose(); return disposable; } obj.CompositeDisposable.Add(disposable); return disposable; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using StatefulModel; namespace MetroTrilithon.Lifetime { public static class DisposableExtensions { /// <summary> /// <see cref="IDisposable"/> オブジェクトを、指定した <see cref="IDisposableHolder.CompositeDisposable"/> に追加します。 /// </summary> public static T AddTo<T>(this T disposable, IDisposableHolder obj) where T : IDisposable { if (obj == null) { disposable.Dispose(); } else { obj.CompositeDisposable.Add(disposable); } return disposable; } public static T AddTo<T>(this T disposable, MultipleDisposable obj) where T : IDisposable { if (obj == null) { disposable.Dispose(); } else { obj.Add(disposable); } return disposable; } } }
Add check if a file supports animations
using System.Globalization; namespace Agens.Stickers { public static class StickerEditorUtility { /// <summary> /// Checks the file extension of a filename /// </summary> /// <param name="fileName">filename with extension or full path of a file</param> /// <returns>True if the file type is supported for stickers</returns> public static bool HasValidFileExtension(string fileName) { var s = fileName.ToLower(CultureInfo.InvariantCulture); return s.EndsWith(".png") || s.EndsWith(".gif") || s.EndsWith(".jpg") || s.EndsWith(".jpeg"); } /// <summary> /// Creates a readable string in Bytes or KiloBytes of a file /// 1 kB is 1000B in this case /// </summary> /// <param name="size">File size in byte</param> /// <returns>File size with fitting units</returns> public static string GetFileSizeString(long size) { if (size < 1000) { return size.ToString() + "B"; } else { return (size / 1000L).ToString() + " kB"; } } } }
using System.Globalization; namespace Agens.Stickers { public static class StickerEditorUtility { /// <summary> /// Checks the file extension of a filename /// </summary> /// <param name="fileName">filename with extension or full path of a file</param> /// <returns>True if the file type is supported for stickers</returns> public static bool HasValidFileExtension(string fileName) { var s = fileName.ToLower(CultureInfo.InvariantCulture); return s.EndsWith(".png") || s.EndsWith(".gif") || s.EndsWith(".jpg") || s.EndsWith(".jpeg"); } /// <summary> /// Creates a readable string in Bytes or KiloBytes of a file /// 1 kB is 1000B in this case /// </summary> /// <param name="size">File size in byte</param> /// <returns>File size with fitting units</returns> public static string GetFileSizeString(long size) { if (size < 1000) { return size.ToString() + "B"; } else { return (size / 1000L).ToString() + " kB"; } } /// <summary> /// Checks if the filetype is an animated file or not. /// Supported file checks: .gif /// </summary> /// <param name="filePath">Path to the file or filename</param> /// <returns>True if the file type supports animations</returns> public static bool IsAnimatedTexture(string filePath) { var s = filePath.ToLower(CultureInfo.InvariantCulture); return s.EndsWith(".gif"); } } }
Fix catch block in Main
using System; using System.Diagnostics; using CIV.Formats; using static System.Console; namespace CIV { [Flags] enum ExitCodes : int { Success = 0, FileNotFound = 1, ParsingFailed = 2, VerificationFailed = 4 } class Program { static void Main(string[] args) { try { var project = new Caal().Load(args[0]); VerifyAll(project); } catch (System.IO.FileNotFoundException ex) { ForegroundColor = ConsoleColor.Red; WriteLine(ex.Message); ResetColor(); Environment.Exit((int)ExitCodes.FileNotFound); } } static void VerifyAll(Caal project) { WriteLine("Loaded project {0}. Starting verification...", project.Name); var sw = new Stopwatch(); sw.Start(); foreach (var kv in project.Formulae) { Write($"{kv.Value} |= {kv.Key}..."); Out.Flush(); var isSatisfied = kv.Key.Check(kv.Value); ForegroundColor = isSatisfied ? ConsoleColor.Green : ConsoleColor.Red; var result = isSatisfied ? "Success!" : "Failure"; Write($"\t{result}"); WriteLine(); ResetColor(); } sw.Stop(); WriteLine($"Completed in {sw.Elapsed.TotalMilliseconds} ms."); } } }
using System; using System.Diagnostics; using CIV.Formats; using CIV.Common; using static System.Console; namespace CIV { [Flags] enum ExitCodes : int { Success = 0, FileNotFound = 1, ParsingFailed = 2, VerificationFailed = 4 } class Program { static void Main(string[] args) { try { var project = new Caal().Load(args[0]); VerifyAll(project); } catch (Exception ex) { ForegroundColor = ConsoleColor.Red; WriteLine("An error has occurred:"); WriteLine(ex.Message); ResetColor(); Environment.Exit((int)ExitCodes.FileNotFound); } } static void VerifyAll(Caal project) { WriteLine("Loaded project {0}. Starting verification...", project.Name); var sw = new Stopwatch(); sw.Start(); foreach (var kv in project.Formulae) { Write($"{kv.Value} |= {kv.Key}..."); Out.Flush(); var isSatisfied = kv.Key.Check(kv.Value); ForegroundColor = isSatisfied ? ConsoleColor.Green : ConsoleColor.Red; var result = isSatisfied ? "Success!" : "Failure"; Write($"\t{result}"); WriteLine(); ResetColor(); } sw.Stop(); WriteLine($"Completed in {sw.Elapsed.TotalMilliseconds} ms."); } } }
Use `&times;` for close button
@if (ViewData.ModelState.Any(x => x.Value.Errors.Any())) { <div class="alert alert-error"> <a class="close" data-dismiss="alert">�</a> @Html.ValidationSummary(true) </div> }
@if (ViewData.ModelState.Any(x => x.Value.Errors.Any())) { <div class="alert alert-error"> <a class="close" data-dismiss="alert">&times;/a> @Html.ValidationSummary(true) </div> }
Work on copy periodic wizard
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using LifeTimeV3.BL.LifeTimeDiagram; namespace LifeTimeV3.LifeTimeDiagram.CopyPeriodicDialog { public partial class FormCopyPeriodicDialog : Form { #region properties public LifeTimeDiagramEditor.LifeTimeElement Object { get; set; } public List<LifeTimeDiagramEditor.LifeTimeElement> MultipliedObjectsCollection { get { return _multipliedObjects; } } #endregion #region fields private List<LifeTimeDiagramEditor.LifeTimeElement> _multipliedObjects = new List<LifeTimeDiagramEditor.LifeTimeElement>(); #endregion #region constructor public FormCopyPeriodicDialog() { InitializeComponent(); } #endregion #region private private void buttonCancel_Click(object sender, EventArgs e) { DialogResult = DialogResult.Cancel; } #endregion } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using LifeTimeV3.BL.LifeTimeDiagram; namespace LifeTimeV3.LifeTimeDiagram.CopyPeriodicDialog { public partial class FormCopyPeriodicDialog : Form { #region properties public LifeTimeDiagramEditor.LifeTimeElement Object { get; set; } public List<LifeTimeDiagramEditor.LifeTimeElement> MultipliedObjectsCollection { get { return _multipliedObjects; } } public enum PeriodBaseEnum { Days, Month, Years}; /// <summary> /// Base unit of the period (every [Period] [Day/Month/Year]) /// </summary> public PeriodBaseEnum PeriodBase { get; set; } /// <summary> /// Period (every x [BaseUnit]) /// </summary> public int Period { get; set; } /// <summary> /// Ammount of copies to add /// </summary> public int AmmountOfCopies { get; set; } /// <summary> /// Limit until copies are made /// </summary> public DateTime LimitForAddingCopies { get; set; } /// <summary> /// Switch to use either Limit or Ammount for adding copies /// </summary> public bool UseLimitForAddingCopies { get; set; } #endregion #region fields private List<LifeTimeDiagramEditor.LifeTimeElement> _multipliedObjects = new List<LifeTimeDiagramEditor.LifeTimeElement>(); #endregion #region constructor public FormCopyPeriodicDialog() { InitializeComponent(); } #endregion #region private private void buttonCancel_Click(object sender, EventArgs e) { DialogResult = DialogResult.Cancel; } #endregion } }
Add hold note tail judgement.
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE namespace osu.Game.Rulesets.Mania.Judgements { public class HoldNoteTailJudgement : ManiaJudgement { /// <summary> /// Whether the hold note has been released too early and shouldn't give full score for the release. /// </summary> public bool HasBroken; } }
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE namespace osu.Game.Rulesets.Mania.Judgements { public class HoldNoteTailJudgement : ManiaJudgement { /// <summary> /// Whether the hold note has been released too early and shouldn't give full score for the release. /// </summary> public bool HasBroken; public override int NumericResultForScore(ManiaHitResult result) { switch (result) { default: return base.NumericResultForScore(result); case ManiaHitResult.Great: case ManiaHitResult.Perfect: return base.NumericResultForScore(HasBroken ? ManiaHitResult.Good : result); } } public override int NumericResultForAccuracy(ManiaHitResult result) { switch (result) { default: return base.NumericResultForAccuracy(result); case ManiaHitResult.Great: case ManiaHitResult.Perfect: return base.NumericResultForAccuracy(HasBroken ? ManiaHitResult.Good : result); } } } }
Fix two properties to be string as expected on PaymentMethodDetails
namespace Stripe { using Newtonsoft.Json; using Stripe.Infrastructure; public class ChargePaymentMethodDetailsCardPresentReceipt : StripeEntity { [JsonProperty("application_cryptogram")] public string ApplicationCryptogram { get; set; } [JsonProperty("application_preferred_name")] public string ApplicationPreferredName { get; set; } [JsonProperty("authorization_code")] public string AuthorizationCode { get; set; } [JsonProperty("authorization_response_code")] public long AuthorizationResponseCode { get; set; } [JsonProperty("cardholder_verification_method")] public long CardholderVerificationMethod { get; set; } [JsonProperty("dedicated_file_name")] public string DedicatedFileName { get; set; } [JsonProperty("terminal_verification_results")] public string TerminalVerificationResults { get; set; } [JsonProperty("transaction_status_information")] public string TransactionStatusInformation { get; set; } } }
namespace Stripe { using Newtonsoft.Json; using Stripe.Infrastructure; public class ChargePaymentMethodDetailsCardPresentReceipt : StripeEntity { [JsonProperty("application_cryptogram")] public string ApplicationCryptogram { get; set; } [JsonProperty("application_preferred_name")] public string ApplicationPreferredName { get; set; } [JsonProperty("authorization_code")] public string AuthorizationCode { get; set; } [JsonProperty("authorization_response_code")] public string AuthorizationResponseCode { get; set; } [JsonProperty("cardholder_verification_method")] public string CardholderVerificationMethod { get; set; } [JsonProperty("dedicated_file_name")] public string DedicatedFileName { get; set; } [JsonProperty("terminal_verification_results")] public string TerminalVerificationResults { get; set; } [JsonProperty("transaction_status_information")] public string TransactionStatusInformation { get; set; } } }
Document nullability of seasonal backgrounds
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Game.Online.API.Requests.Responses; namespace osu.Game.Configuration { /// <summary> /// Stores global per-session statics. These will not be stored after exiting the game. /// </summary> public class SessionStatics : InMemoryConfigManager<Static> { protected override void InitialiseDefaults() { Set(Static.LoginOverlayDisplayed, false); Set(Static.MutedAudioNotificationShownOnce, false); Set<APISeasonalBackgrounds>(Static.SeasonalBackgrounds, null); } } public enum Static { LoginOverlayDisplayed, MutedAudioNotificationShownOnce, SeasonalBackgrounds, } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Game.Online.API.Requests.Responses; namespace osu.Game.Configuration { /// <summary> /// Stores global per-session statics. These will not be stored after exiting the game. /// </summary> public class SessionStatics : InMemoryConfigManager<Static> { protected override void InitialiseDefaults() { Set(Static.LoginOverlayDisplayed, false); Set(Static.MutedAudioNotificationShownOnce, false); Set<APISeasonalBackgrounds>(Static.SeasonalBackgrounds, null); } } public enum Static { LoginOverlayDisplayed, MutedAudioNotificationShownOnce, /// <summary> /// Info about seasonal backgrounds available fetched from API - see <see cref="APISeasonalBackgrounds"/>. /// Value under this lookup can be <c>null</c> if there are no backgrounds available (or API is not reachable). /// </summary> SeasonalBackgrounds, } }
Revert assembly info change in uwp project

using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("ValueConverters.UWP")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Thomas Galliker")] [assembly: AssemblyProduct("ValueConverters.UWP")] [assembly: AssemblyCopyright("Copyright © 2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: ComVisible(false)]
Implement realtime match song select
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Game.Screens.Select; namespace osu.Game.Screens.Multi.RealtimeMultiplayer { public class RealtimeMatchSongSelect : SongSelect { protected override BeatmapDetailArea CreateBeatmapDetailArea() { throw new System.NotImplementedException(); } protected override bool OnStart() { throw new System.NotImplementedException(); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Linq; using Humanizer; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Screens; using osu.Game.Online.Multiplayer; using osu.Game.Online.RealtimeMultiplayer; using osu.Game.Screens.Select; namespace osu.Game.Screens.Multi.RealtimeMultiplayer { public class RealtimeMatchSongSelect : SongSelect, IMultiplayerSubScreen { public string ShortTitle => "song selection"; public override string Title => ShortTitle.Humanize(); [Resolved(typeof(Room), nameof(Room.Playlist))] private BindableList<PlaylistItem> playlist { get; set; } [Resolved] private StatefulMultiplayerClient client { get; set; } protected override bool OnStart() { var item = new PlaylistItem(); item.Beatmap.Value = Beatmap.Value.BeatmapInfo; item.Ruleset.Value = Ruleset.Value; item.RequiredMods.Clear(); item.RequiredMods.AddRange(Mods.Value.Select(m => m.CreateCopy())); // If the client is already in a room, update via the client. // Otherwise, update the playlist directly in preparation for it to be submitted to the API on match creation. if (client.Room != null) client.ChangeSettings(item: item); else { playlist.Clear(); playlist.Add(item); } this.Exit(); return true; } protected override BeatmapDetailArea CreateBeatmapDetailArea() => new PlayBeatmapDetailArea(); } }
Change max supported version constants
namespace Pdelvo.Minecraft.Protocol.Helper { /// <summary> /// /// </summary> /// <remarks></remarks> public static class ProtocolInformation { /// <summary> /// /// </summary> public const int MinSupportedClientVersion = 22; /// <summary> /// /// </summary> public const int MaxSupportedClientVersion = 46; /// <summary> /// /// </summary> public const int MinSupportedServerVersion = 22; /// <summary> /// /// </summary> public const int MaxSupportedServerVersion = 46; } }
namespace Pdelvo.Minecraft.Protocol.Helper { /// <summary> /// /// </summary> /// <remarks></remarks> public static class ProtocolInformation { /// <summary> /// /// </summary> public const int MinSupportedClientVersion = 22; /// <summary> /// /// </summary> public const int MaxSupportedClientVersion = 47; /// <summary> /// /// </summary> public const int MinSupportedServerVersion = 22; /// <summary> /// /// </summary> public const int MaxSupportedServerVersion = 47; } }
Fix issue where Security Scheme responses are not parsed correctly.
using System.Collections.Generic; using Raml.Parser.Expressions; namespace Raml.Parser.Builders { public class SecuritySchemeDescriptorBuilder { public SecuritySchemeDescriptor Build(IDictionary<string, object> dynamicRaml, string defaultMediaType) { var descriptor = new SecuritySchemeDescriptor(); if (dynamicRaml.ContainsKey("headers")) descriptor.Headers = new ParametersBuilder((IDictionary<string, object>)dynamicRaml["headers"]).GetAsDictionary(); if (dynamicRaml.ContainsKey("queryParameters")) descriptor.QueryParameters = new ParametersBuilder((IDictionary<string, object>)dynamicRaml["queryParameters"]).GetAsDictionary(); if (dynamicRaml.ContainsKey("responses")) descriptor.Responses = new ResponsesBuilder((IDictionary<string, object>)dynamicRaml["responses"]).GetAsDictionary(defaultMediaType); return descriptor; } } }
using System.Collections.Generic; using System.Dynamic; using System.Linq; using Raml.Parser.Expressions; namespace Raml.Parser.Builders { public class SecuritySchemeDescriptorBuilder { public SecuritySchemeDescriptor Build(IDictionary<string, object> dynamicRaml, string defaultMediaType) { var descriptor = new SecuritySchemeDescriptor(); if (dynamicRaml.ContainsKey("headers")) descriptor.Headers = new ParametersBuilder((IDictionary<string, object>)dynamicRaml["headers"]).GetAsDictionary(); if (dynamicRaml.ContainsKey("queryParameters")) descriptor.QueryParameters = new ParametersBuilder((IDictionary<string, object>)dynamicRaml["queryParameters"]).GetAsDictionary(); var responsesNest = ((object[])dynamicRaml["responses"]).ToList().Cast<ExpandoObject>() ; var responses = responsesNest.ToDictionary(k => ((IDictionary<string, object>)k)["code"].ToString(), v => (object)v); if (dynamicRaml.ContainsKey("responses")) descriptor.Responses = new ResponsesBuilder(responses).GetAsDictionary(defaultMediaType); return descriptor; } } }
Use 'nameof' when throwing ArgumentOutOfRangeException
using System; using UnityEngine; using UnityEngine.Assertions; namespace Alensia.Core.Common { public enum Axis { X, Y, Z, InverseX, InverseY, InverseZ } public static class AxisExtensions { public static Vector3 Of(this Axis axis, Transform transform) { Assert.IsNotNull(transform, "transform != null"); switch (axis) { case Axis.X: return transform.right; case Axis.Y: return transform.up; case Axis.Z: return transform.forward; case Axis.InverseX: return transform.right * -1; case Axis.InverseY: return transform.up * -1; case Axis.InverseZ: return transform.forward * -1; default: throw new ArgumentOutOfRangeException(); } } public static Vector3 Direction(this Axis axis) { switch (axis) { case Axis.X: return Vector3.right; case Axis.Y: return Vector3.up; case Axis.Z: return Vector3.forward; case Axis.InverseX: return Vector3.right * -1; case Axis.InverseY: return Vector3.up * -1; case Axis.InverseZ: return Vector3.forward * -1; default: throw new ArgumentOutOfRangeException(); } } } }
using System; using UnityEngine; using UnityEngine.Assertions; namespace Alensia.Core.Common { public enum Axis { X, Y, Z, InverseX, InverseY, InverseZ } public static class AxisExtensions { public static Vector3 Of(this Axis axis, Transform transform) { Assert.IsNotNull(transform, "transform != null"); switch (axis) { case Axis.X: return transform.right; case Axis.Y: return transform.up; case Axis.Z: return transform.forward; case Axis.InverseX: return transform.right * -1; case Axis.InverseY: return transform.up * -1; case Axis.InverseZ: return transform.forward * -1; default: throw new ArgumentOutOfRangeException(nameof(axis)); } } public static Vector3 Direction(this Axis axis) { switch (axis) { case Axis.X: return Vector3.right; case Axis.Y: return Vector3.up; case Axis.Z: return Vector3.forward; case Axis.InverseX: return Vector3.right * -1; case Axis.InverseY: return Vector3.up * -1; case Axis.InverseZ: return Vector3.forward * -1; default: throw new ArgumentOutOfRangeException(nameof(axis)); } } } }
Replace Theory with multiple Fact tests
using Xunit; public class AcronymTest { [Fact] public void Empty_string_abbreviated_to_empty_string() { Assert.Equal(string.Empty, Acronym.Abbreviate(string.Empty)); } [Theory(Skip = "Remove to run test")] [InlineData("Portable Network Graphics", "PNG")] [InlineData("Ruby on Rails", "ROR")] [InlineData("HyperText Markup Language", "HTML")] [InlineData("First In, First Out", "FIFO")] [InlineData("PHP: Hypertext Preprocessor", "PHP")] [InlineData("Complementary metal-oxide semiconductor", "CMOS")] public void Phrase_abbreviated_to_acronym(string phrase, string expected) { Assert.Equal(expected, Acronym.Abbreviate(phrase)); } }
using Xunit; public class AcronymTest { [Fact] public void Basic() { Assert.Equal("PNG", Acronym.Abbreviate("Portable Network Graphics")); } [Fact(Skip = "Remove to run test")] public void Lowercase_words() { Assert.Equal("ROR", Acronym.Abbreviate("Ruby on Rails")); } [Fact(Skip = "Remove to run test")] public void Camelcase() { Assert.Equal("HTML", Acronym.Abbreviate("HyperText Markup Language")); } [Fact(Skip = "Remove to run test")] public void Punctuation() { Assert.Equal("FIFO", Acronym.Abbreviate("First In, First Out")); } [Fact(Skip = "Remove to run test")] public void All_caps_words() { Assert.Equal("PHP", Acronym.Abbreviate("PHP: Hypertext Preprocessor")); } [Fact(Skip = "Remove to run test")] public void NonAcronymAllCapsWord() { Assert.Equal("GIMP", Acronym.Abbreviate("GNU Image Manipulation Program")); } [Fact(Skip = "Remove to run test")] public void Hyphenated() { Assert.Equal("CMOS", Acronym.Abbreviate("Complementary metal-oxide semiconductor")); } }
Fix parent child index type
using System; namespace Foundatio.Repositories.Elasticsearch.Configuration { public interface IChildIndexType : IIndexType { string ParentPath { get; } } public interface IChildIndexType<T> : IChildIndexType { string GetParentId(T document); } public class ChildIndexType<T> : IndexTypeBase<T>, IChildIndexType<T> where T : class { protected readonly Func<T, string> _getParentId; public ChildIndexType(string parentPath, Func<T, string> getParentId, string name = null, IIndex index = null): base(index, name) { if (_getParentId == null) throw new ArgumentNullException(nameof(getParentId)); ParentPath = parentPath; _getParentId = getParentId; } public string ParentPath { get; } public virtual string GetParentId(T document) { return _getParentId(document); } } }
using System; namespace Foundatio.Repositories.Elasticsearch.Configuration { public interface IChildIndexType : IIndexType { string ParentPath { get; } } public interface IChildIndexType<T> : IChildIndexType { string GetParentId(T document); } public class ChildIndexType<T> : IndexTypeBase<T>, IChildIndexType<T> where T : class { protected readonly Func<T, string> _getParentId; public ChildIndexType(string parentPath, Func<T, string> getParentId, string name = null, IIndex index = null): base(index, name) { if (getParentId == null) throw new ArgumentNullException(nameof(getParentId)); ParentPath = parentPath; _getParentId = getParentId; } public string ParentPath { get; } public virtual string GetParentId(T document) { return _getParentId(document); } } }
Disable .sav tests for now
using System; using System.Collections.Generic; using System.IO; using OpenSage.Data; using OpenSage.Data.Sav; using OpenSage.Mods.Generals; using Veldrid; using Xunit; namespace OpenSage.Tests.Data.Sav { public class SaveFileTests { private static readonly string RootFolder = Path.Combine(Environment.CurrentDirectory, "Data", "Sav", "Assets"); [Theory] [MemberData(nameof(GetSaveFiles))] public void CanLoadSaveFiles(string relativePath) { var rootFolder = InstalledFilesTestData.GetInstallationDirectory(SageGame.CncGenerals); var installation = new GameInstallation(new GeneralsDefinition(), rootFolder); Platform.Start(); using (var game = new Game(installation, GraphicsBackend.Direct3D11)) { var fullPath = Path.Combine(RootFolder, relativePath); using (var stream = File.OpenRead(fullPath)) { SaveFile.LoadFromStream(stream, game); } } Platform.Stop(); } public static IEnumerable<object[]> GetSaveFiles() { foreach (var file in Directory.GetFiles(RootFolder, "*.sav", SearchOption.AllDirectories)) { var relativePath = file.Substring(RootFolder.Length + 1); yield return new object[] { relativePath }; } } } }
using System; using System.Collections.Generic; using System.IO; using OpenSage.Data; using OpenSage.Data.Sav; using OpenSage.Mods.Generals; using Veldrid; using Xunit; namespace OpenSage.Tests.Data.Sav { public class SaveFileTests { private static readonly string RootFolder = Path.Combine(Environment.CurrentDirectory, "Data", "Sav", "Assets"); [Theory(Skip = "Not working yet")] [MemberData(nameof(GetSaveFiles))] public void CanLoadSaveFiles(string relativePath) { var rootFolder = InstalledFilesTestData.GetInstallationDirectory(SageGame.CncGenerals); var installation = new GameInstallation(new GeneralsDefinition(), rootFolder); Platform.Start(); using (var game = new Game(installation, GraphicsBackend.Direct3D11)) { var fullPath = Path.Combine(RootFolder, relativePath); using (var stream = File.OpenRead(fullPath)) { SaveFile.LoadFromStream(stream, game); } } Platform.Stop(); } public static IEnumerable<object[]> GetSaveFiles() { foreach (var file in Directory.GetFiles(RootFolder, "*.sav", SearchOption.AllDirectories)) { var relativePath = file.Substring(RootFolder.Length + 1); yield return new object[] { relativePath }; } } } }
Change IMapper visibility from private to protected
using System.Linq; using AutoMapper; using IObjectMapper = Abp.ObjectMapping.IObjectMapper; namespace Abp.AutoMapper { public class AutoMapperObjectMapper : IObjectMapper { private readonly IMapper _mapper; public AutoMapperObjectMapper(IMapper mapper) { _mapper = mapper; } public TDestination Map<TDestination>(object source) { return _mapper.Map<TDestination>(source); } public TDestination Map<TSource, TDestination>(TSource source, TDestination destination) { return _mapper.Map(source, destination); } public IQueryable<TDestination> ProjectTo<TDestination>(IQueryable source) { return _mapper.ProjectTo<TDestination>(source); } } }
using System.Linq; using AutoMapper; using IObjectMapper = Abp.ObjectMapping.IObjectMapper; namespace Abp.AutoMapper { public class AutoMapperObjectMapper : IObjectMapper { protected readonly IMapper _mapper; public AutoMapperObjectMapper(IMapper mapper) { _mapper = mapper; } public TDestination Map<TDestination>(object source) { return _mapper.Map<TDestination>(source); } public TDestination Map<TSource, TDestination>(TSource source, TDestination destination) { return _mapper.Map(source, destination); } public IQueryable<TDestination> ProjectTo<TDestination>(IQueryable source) { return _mapper.ProjectTo<TDestination>(source); } } }
Change log timestamps to utc for better performance
/* Copyright (c) 2017 Marcin Szeniak (https://github.com/Klocman/) Apache License Version 2.0 */ using System; using System.Diagnostics; using System.IO; using System.Text; namespace BulkCrapUninstaller { internal sealed class LogWriter : StreamWriter { public LogWriter(string path) : base(path, true, Encoding.UTF8) { } public static LogWriter StartLogging(string logPath) { try { // Limit log size to 100 kb var fileInfo = new FileInfo(logPath); if (fileInfo.Exists && fileInfo.Length > 1024 * 100) fileInfo.Delete(); // Create new log writer var logWriter = new LogWriter(logPath); // Make sure we can write to the file logWriter.WriteSeparator(); logWriter.WriteLine("Application startup"); logWriter.Flush(); Console.SetOut(logWriter); Console.SetError(logWriter); #if DEBUG Debug.Listeners.Add(new ConsoleTraceListener(false)); #endif return logWriter; } catch (Exception ex) { // Ignore logging errors Console.WriteLine(ex); return null; } } public void WriteSeparator() { base.WriteLine("--------------------------------------------------"); } public override void WriteLine(string value) { value = DateTime.Now.ToLongTimeString() + " - " + value; base.WriteLine(value); } } }
/* Copyright (c) 2017 Marcin Szeniak (https://github.com/Klocman/) Apache License Version 2.0 */ using System; using System.Diagnostics; using System.IO; using System.Text; namespace BulkCrapUninstaller { internal sealed class LogWriter : StreamWriter { public LogWriter(string path) : base(path, true, Encoding.UTF8) { } public static LogWriter StartLogging(string logPath) { try { // Limit log size to 100 kb var fileInfo = new FileInfo(logPath); if (fileInfo.Exists && fileInfo.Length > 1024 * 100) fileInfo.Delete(); // Create new log writer var logWriter = new LogWriter(logPath); // Make sure we can write to the file logWriter.WriteSeparator(); logWriter.WriteLine("Application startup"); logWriter.Flush(); Console.SetOut(logWriter); Console.SetError(logWriter); #if DEBUG Debug.Listeners.Add(new ConsoleTraceListener(false)); #endif return logWriter; } catch (Exception ex) { // Ignore logging errors Console.WriteLine(ex); return null; } } public void WriteSeparator() { base.WriteLine("--------------------------------------------------"); } public override void WriteLine(string value) { value = DateTime.UtcNow.ToLongTimeString() + " - " + value; base.WriteLine(value); } } }
Test broker listens on all IPs
using System; using WampSharp.Binding; using WampSharp.Fleck; using WampSharp.V2; using WampSharp.V2.MetaApi; namespace Adaptive.ReactiveTrader.MessageBroker { public class MessageBroker : IDisposable { private WampHost _router; public void Dispose() { _router.Dispose(); } public void Start() { _router = new WampHost(); var jsonBinding = new JTokenJsonBinding(); var msgPack = new JTokenMsgpackBinding(); _router.RegisterTransport(new FleckWebSocketTransport("ws://127.0.0.1:8080/ws"), jsonBinding, msgPack); _router.Open(); var realm = _router.RealmContainer.GetRealmByName("com.weareadaptive.reactivetrader"); realm.HostMetaApiService(); } } }
using System; using WampSharp.Binding; using WampSharp.Fleck; using WampSharp.V2; using WampSharp.V2.MetaApi; namespace Adaptive.ReactiveTrader.MessageBroker { public class MessageBroker : IDisposable { private WampHost _router; public void Dispose() { _router.Dispose(); } public void Start() { _router = new WampHost(); var jsonBinding = new JTokenJsonBinding(); var msgPack = new JTokenMsgpackBinding(); _router.RegisterTransport(new FleckWebSocketTransport("ws://0.0.0.0:8080/ws"), jsonBinding, msgPack); _router.Open(); var realm = _router.RealmContainer.GetRealmByName("com.weareadaptive.reactivetrader"); realm.HostMetaApiService(); } } }
Reorder to have video settings next to renderer
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Graphics; using osu.Framework.Graphics.Sprites; using osu.Framework.Localisation; using osu.Game.Localisation; using osu.Game.Overlays.Settings.Sections.Graphics; namespace osu.Game.Overlays.Settings.Sections { public class GraphicsSection : SettingsSection { public override LocalisableString Header => GraphicsSettingsStrings.GraphicsSectionHeader; public override Drawable CreateIcon() => new SpriteIcon { Icon = FontAwesome.Solid.Laptop }; public GraphicsSection() { Children = new Drawable[] { new LayoutSettings(), new RendererSettings(), new ScreenshotSettings(), new VideoSettings(), }; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Graphics; using osu.Framework.Graphics.Sprites; using osu.Framework.Localisation; using osu.Game.Localisation; using osu.Game.Overlays.Settings.Sections.Graphics; namespace osu.Game.Overlays.Settings.Sections { public class GraphicsSection : SettingsSection { public override LocalisableString Header => GraphicsSettingsStrings.GraphicsSectionHeader; public override Drawable CreateIcon() => new SpriteIcon { Icon = FontAwesome.Solid.Laptop }; public GraphicsSection() { Children = new Drawable[] { new LayoutSettings(), new RendererSettings(), new VideoSettings(), new ScreenshotSettings(), }; } } }
Add a touch more detail to the unsupported skin component exception
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; namespace osu.Game.Skinning { public class UnsupportedSkinComponentException : Exception { public UnsupportedSkinComponentException(ISkinComponent component) : base($@"Unsupported component type: {component.GetType()}(""{component.LookupName}"").") { } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; namespace osu.Game.Skinning { public class UnsupportedSkinComponentException : Exception { public UnsupportedSkinComponentException(ISkinComponent component) : base($@"Unsupported component type: {component.GetType()} (lookup: ""{component.LookupName}"").") { } } }
Hide F rank from beatmap overlay
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable disable using System.Collections.Generic; using System.Linq; using osu.Framework.Extensions; using osu.Framework.Localisation; using osu.Game.Resources.Localisation.Web; using osu.Game.Scoring; namespace osu.Game.Overlays.BeatmapListing { public class BeatmapSearchScoreFilterRow : BeatmapSearchMultipleSelectionFilterRow<ScoreRank> { public BeatmapSearchScoreFilterRow() : base(BeatmapsStrings.ListingSearchFiltersRank) { } protected override MultipleSelectionFilter CreateMultipleSelectionFilter() => new RankFilter(); private class RankFilter : MultipleSelectionFilter { protected override MultipleSelectionFilterTabItem CreateTabItem(ScoreRank value) => new RankItem(value); protected override IEnumerable<ScoreRank> GetValues() => base.GetValues().Reverse(); } private class RankItem : MultipleSelectionFilterTabItem { public RankItem(ScoreRank value) : base(value) { } protected override LocalisableString LabelFor(ScoreRank value) => value.GetLocalisableDescription(); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable disable using System.Collections.Generic; using System.Linq; using osu.Framework.Extensions; using osu.Framework.Localisation; using osu.Game.Resources.Localisation.Web; using osu.Game.Scoring; namespace osu.Game.Overlays.BeatmapListing { public class BeatmapSearchScoreFilterRow : BeatmapSearchMultipleSelectionFilterRow<ScoreRank> { public BeatmapSearchScoreFilterRow() : base(BeatmapsStrings.ListingSearchFiltersRank) { } protected override MultipleSelectionFilter CreateMultipleSelectionFilter() => new RankFilter(); private class RankFilter : MultipleSelectionFilter { protected override MultipleSelectionFilterTabItem CreateTabItem(ScoreRank value) => new RankItem(value); protected override IEnumerable<ScoreRank> GetValues() => base.GetValues().Where(r => r > ScoreRank.F).Reverse(); } private class RankItem : MultipleSelectionFilterTabItem { public RankItem(ScoreRank value) : base(value) { } protected override LocalisableString LabelFor(ScoreRank value) => value.GetLocalisableDescription(); } } }
Use predefined default size for embedded windows
// Copyright (c) The Perspex Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using Perspex.Win32.Interop; namespace Perspex.Win32 { public class EmbeddedWindowImpl : WindowImpl { private static readonly System.Windows.Forms.UserControl WinFormsControl = new System.Windows.Forms.UserControl(); public IntPtr Handle { get; private set; } protected override IntPtr CreateWindowOverride(ushort atom) { var hWnd = UnmanagedMethods.CreateWindowEx( 0, atom, null, (int)UnmanagedMethods.WindowStyles.WS_CHILD, UnmanagedMethods.CW_USEDEFAULT, UnmanagedMethods.CW_USEDEFAULT, UnmanagedMethods.CW_USEDEFAULT, UnmanagedMethods.CW_USEDEFAULT, WinFormsControl.Handle, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero); Handle = hWnd; return hWnd; } } }
// Copyright (c) The Perspex Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using Perspex.Win32.Interop; namespace Perspex.Win32 { public class EmbeddedWindowImpl : WindowImpl { private static readonly System.Windows.Forms.UserControl WinFormsControl = new System.Windows.Forms.UserControl(); public IntPtr Handle { get; private set; } protected override IntPtr CreateWindowOverride(ushort atom) { var hWnd = UnmanagedMethods.CreateWindowEx( 0, atom, null, (int)UnmanagedMethods.WindowStyles.WS_CHILD, 0, 0, 640, 480, WinFormsControl.Handle, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero); Handle = hWnd; return hWnd; } } }
Add the return date, and change the long time string to short date string.
@model IEnumerable<MMLibrarySystem.Models.BorrowRecord> @{ ViewBag.Title = "Borrowed Books"; } <table id="bookList"> <tr> <td> Book Number </td> <td> Title </td> <td> Borrowed By </td> <td> Borrowed Start From </td> <td> State </td> <td> Operation </td> </tr> @{ foreach (var item in Model) { <tr> <td>@item.Book.BookNumber </td> <td>@item.Book.BookType.Title </td> <td>@item.User.DisplayName </td> <td>@item.BorrowedDate </td> <td>@(item.IsCheckedOut ? "Checked Out" : "Borrow Accepted") </td> <td> @{ if (item.IsCheckedOut) { @Html.ActionLink("Return", "Return", "Admin", new { borrowId = @item.BorrowRecordId }, new { onclick = "return confirm('Are you sure to return this book?')" }) } else { @Html.ActionLink("Check Out", "CheckOut", "Admin", new { borrowId = @item.BorrowRecordId }, null) } } </td> </tr> } } </table>
@model IEnumerable<MMLibrarySystem.Models.BorrowRecord> @{ ViewBag.Title = "Borrowed Books"; } <table id="bookList"> <tr> <td> Book Number </td> <td> Title </td> <td> Borrowed By </td> <td> Borrowed Start From </td> <td> Return Data </td> <td> State </td> <td> Operation </td> </tr> @{ foreach (var item in Model) { <tr> <td>@item.Book.BookNumber </td> <td>@item.Book.BookType.Title </td> <td>@item.User.DisplayName </td> <td>@item.BorrowedDate.ToShortDateString() </td> <td>@item.BorrowedDate.AddDays(31).ToShortDateString() </td> <td>@(item.IsCheckedOut ? "Checked Out" : "Borrow Accepted") </td> <td> @{ if (item.IsCheckedOut) { @Html.ActionLink("Return", "Return", "Admin", new { borrowId = @item.BorrowRecordId }, new { onclick = "return confirm('Are you sure to return this book?')" }) } else { @Html.ActionLink("Check Out", "CheckOut", "Admin", new { borrowId = @item.BorrowRecordId }, null) } } </td> </tr> } } </table>
Print the texts of each row
using System; namespace Hangman { public class Table { public int Width; public int Spacing; public Row[] Rows; public Table(int width, int spacing, Row[] rows) { Width = width; Spacing = spacing; Rows = rows; } public string Draw() { return "Hello World"; } } }
using System; using System.Collections.Generic; using System.Text; namespace Hangman { public class Table { public int Width; public int Spacing; public Row[] Rows; public Table(int width, int spacing, Row[] rows) { Width = width; Spacing = spacing; Rows = rows; } public string Draw() { List<string> rowTexts = new List<string>(); foreach (var row in Rows) { rowTexts.Add(row.Text); } return String.Join("\n", rowTexts); } } }
Remove DisableTestParallelization on CI due to the same reason.
using Xunit; // This is a work-around for #11. // https://github.com/CXuesong/WikiClientLibrary/issues/11 [assembly:CollectionBehavior(DisableTestParallelization = true)]
using Xunit; // This is a work-around for #11. // https://github.com/CXuesong/WikiClientLibrary/issues/11 // We are using Bot Password on CI, which may naturally evade the issue. #if ENV_CI_BUILD [assembly:CollectionBehavior(DisableTestParallelization = true)] #endif
Modify DepartmentService to use new CrudService
using System; using System.Threading.Tasks; using AutoMapper; using Diploms.Core; using Diploms.Dto; using Diploms.Dto.Departments; namespace Diploms.Services.Departments { public class DepartmentsService { private readonly IRepository<Department> _repository; private readonly IMapper _mapper; public DepartmentsService(IRepository<Department> repository, IMapper mapper) { _repository = repository ?? throw new System.ArgumentNullException(nameof(repository)); _mapper = mapper ?? throw new System.ArgumentNullException(nameof(mapper)); } public async Task<OperationResult> Add(DepartmentEditDto model) { var result = new OperationResult(); try { var department = _mapper.Map<Department>(model); department.CreateDate = DateTime.UtcNow; _repository.Add(department); await _repository.SaveChanges(); } catch(Exception e) { result.Errors.Add(e.Message); } return result; } public async Task<OperationResult> Edit(DepartmentEditDto model) { var result = new OperationResult(); try { var department = _mapper.Map<Department>(model); department.ChangeDate = DateTime.UtcNow; _repository.Update(department); await _repository.SaveChanges(); } catch(Exception e) { result.Errors.Add(e.Message); } return result; } } }
using System; using System.Threading.Tasks; using AutoMapper; using Diploms.Core; using Diploms.Dto; using Diploms.Dto.Departments; namespace Diploms.Services.Departments { public class DepartmentsService : CrudService<Department, DepartmentEditDto, DepartmentEditDto, DepartmentEditDto> { public DepartmentsService(IRepository<Department> repository, IMapper mapper) : base(repository, mapper) { } } }
Allow redirect to returnUrl from login part
using System.Web.Mvc; using System.Web.Security; using N2.Templates.Mvc.Models.Parts; using N2.Templates.Mvc.Models; using N2.Web; namespace N2.Templates.Mvc.Controllers { [Controls(typeof(LoginItem))] public class LoginController : TemplatesControllerBase<LoginItem> { public override ActionResult Index() { var model = new LoginModel(CurrentItem) { LoggedIn = User.Identity.IsAuthenticated }; return View(model); } public ActionResult Login(string userName, string password, bool? remember) { if(Membership.ValidateUser(userName, password) || FormsAuthentication.Authenticate(userName, password)) { FormsAuthentication.SetAuthCookie(userName, remember ?? false); return RedirectToParentPage(); } else { ModelState.AddModelError("Login.Failed", CurrentItem.FailureText); } return ViewParentPage(); } public ActionResult Logout() { FormsAuthentication.SignOut(); return RedirectToParentPage(); } } }
using System.Web.Mvc; using System.Web.Security; using N2.Templates.Mvc.Models.Parts; using N2.Templates.Mvc.Models; using N2.Web; namespace N2.Templates.Mvc.Controllers { [Controls(typeof(LoginItem))] public class LoginController : TemplatesControllerBase<LoginItem> { public override ActionResult Index() { var model = new LoginModel(CurrentItem) { LoggedIn = User.Identity.IsAuthenticated }; return View(model); } public ActionResult Login(string userName, string password, bool? remember) { if(Membership.ValidateUser(userName, password) || FormsAuthentication.Authenticate(userName, password)) { FormsAuthentication.SetAuthCookie(userName, remember ?? false); if (string.IsNullOrEmpty(Request["returnUrl"])) return RedirectToParentPage(); else return Redirect(Request["returnUrl"]); } else { ModelState.AddModelError("Login.Failed", CurrentItem.FailureText); } return ViewParentPage(); } public ActionResult Logout() { FormsAuthentication.SignOut(); return RedirectToParentPage(); } } }
Kill projectiles after 2 seconds
using UnityEngine; using System.Collections; public class Projectile : MonoBehaviour { public float damage = 10; public float speed = 30; public Vector3 direction; // Use this for initialization void Start() { direction = direction.normalized * speed; } // Update is called once per frame void Update() { transform.Translate(direction.normalized * speed * Time.deltaTime); } void OnTriggerEnter(Collider other) { if (other.GetComponent<Enemy>() != null && other.GetComponent<Rigidbody>() != null) { other.GetComponent<Enemy>().Damage(damage); other.GetComponent<Rigidbody>().AddForce(direction.normalized * 200); } if (other.GetComponent<PlayerController>() == null) { GameObject.Destroy(this.gameObject); } } }
using UnityEngine; using System.Collections; public class Projectile : MonoBehaviour { public float lifetime = 2; private float age = 0; public float damage = 10; public float speed = 30; public Vector3 direction; // Use this for initialization void Start() { direction = direction.normalized * speed; } // Update is called once per frame void Update() { age += Time.deltaTime; if (age > lifetime) { Destroy(this.gameObject); } transform.Translate(direction.normalized * speed * Time.deltaTime); } void OnTriggerEnter(Collider other) { if (other.GetComponent<Enemy>() != null && other.GetComponent<Rigidbody>() != null) { other.GetComponent<Enemy>().Damage(damage); other.GetComponent<Rigidbody>().AddForce(direction.normalized * 200); } if (other.GetComponent<PlayerController>() == null) { GameObject.Destroy(this.gameObject); } } }
Support watching of arbitrary connections
// Copyright 2006 Alp Toker <alp@atoker.com> // This software is made available under the MIT License // See COPYING for details using System; //using GLib; //using Gtk; using NDesk.DBus; using NDesk.GLib; using org.freedesktop.DBus; namespace NDesk.DBus { //FIXME: this API needs review and de-unixification. It is horrid, but gets the job done. public static class BusG { static bool SystemDispatch (IOChannel source, IOCondition condition, IntPtr data) { Bus.System.Iterate (); return true; } static bool SessionDispatch (IOChannel source, IOCondition condition, IntPtr data) { Bus.Session.Iterate (); return true; } static bool initialized = false; public static void Init () { if (initialized) return; Init (Bus.System, SystemDispatch); Init (Bus.Session, SessionDispatch); initialized = true; } public static void Init (Connection conn, IOFunc dispatchHandler) { IOChannel channel = new IOChannel ((int)conn.Transport.SocketHandle); IO.AddWatch (channel, IOCondition.In, dispatchHandler); } //TODO: add public API to watch an arbitrary connection } }
// Copyright 2006 Alp Toker <alp@atoker.com> // This software is made available under the MIT License // See COPYING for details using System; //using GLib; //using Gtk; using NDesk.DBus; using NDesk.GLib; using org.freedesktop.DBus; namespace NDesk.DBus { //FIXME: this API needs review and de-unixification. It is horrid, but gets the job done. public static class BusG { static bool initialized = false; public static void Init () { if (initialized) return; Init (Bus.System); Init (Bus.Session); //TODO: consider starter bus? initialized = true; } public static void Init (Connection conn) { IOFunc dispatchHandler = delegate (IOChannel source, IOCondition condition, IntPtr data) { conn.Iterate (); return true; }; Init (conn, dispatchHandler); } public static void Init (Connection conn, IOFunc dispatchHandler) { IOChannel channel = new IOChannel ((int)conn.Transport.SocketHandle); IO.AddWatch (channel, IOCondition.In, dispatchHandler); } } }
Paste in some more CEF docs.
// Copyright © 2010-2014 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. namespace CefSharp { public interface ILifeSpanHandler { bool OnBeforePopup(IWebBrowser browser, string sourceUrl, string targetUrl, ref int x, ref int y, ref int width, ref int height); void OnBeforeClose(IWebBrowser browser); } }
// Copyright © 2010-2014 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. namespace CefSharp { public interface ILifeSpanHandler { /// <summary> /// Called before a popup window is created. /// </summary> /// <param name="browser">The IWebBrowser control this request is for.</param> /// <param name="sourceUrl">The URL of the HTML frame that launched this popup.</param> /// <param name="targetUrl">The URL of the popup content. (This may be empty/null)</param> /// <param name="x"></param> /// <param name="y"></param> /// <param name="width"></param> /// <param name="height"></param> /// <returns></returns> /// <remarks> /// CEF documentation: /// /// Called on the IO thread before a new popup window is created. The |browser| /// and |frame| parameters represent the source of the popup request. The /// |target_url| and |target_frame_name| values may be empty if none were /// specified with the request. The |popupFeatures| structure contains /// information about the requested popup window. To allow creation of the /// popup window optionally modify |windowInfo|, |client|, |settings| and /// |no_javascript_access| and return false. To cancel creation of the popup /// window return true. The |client| and |settings| values will default to the /// source browser's values. The |no_javascript_access| value indicates whether /// the new browser window should be scriptable and in the same process as the /// source browser. /// </remarks> bool OnBeforePopup(IWebBrowser browser, string sourceUrl, string targetUrl, ref int x, ref int y, ref int width, ref int height); /// <summary> /// Called before a CefBrowser window (either the main browser for IWebBrowser, /// or one of its children) /// </summary> /// <param name="browser"></param> void OnBeforeClose(IWebBrowser browser); } }
Add a null check to FlatProgressBar.brush
namespace TweetDick.Core.Controls { partial class FlatProgressBar { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { brush.Dispose(); if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { components = new System.ComponentModel.Container(); } #endregion } }
namespace TweetDick.Core.Controls { partial class FlatProgressBar { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (brush != null)brush.Dispose(); if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { components = new System.ComponentModel.Container(); } #endregion } }
Update library version to 1.3.6
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("GoogleMeasurementProtocol")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("GoogleMeasurementProtocol")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("64a833e9-803e-4d51-8820-ac631ff2c9a5")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // 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.3.5.0")] [assembly: AssemblyFileVersion("1.3.5.0")]
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("GoogleMeasurementProtocol")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("GoogleMeasurementProtocol")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("64a833e9-803e-4d51-8820-ac631ff2c9a5")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // 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.3.6.0")] [assembly: AssemblyFileVersion("1.3.6.0")]
Fix HitCircleLongCombo test stacking off-screen
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Game.Beatmaps; using osu.Game.Rulesets.Osu.Objects; using osu.Game.Tests.Visual; using osuTK; namespace osu.Game.Rulesets.Osu.Tests { [TestFixture] public class TestSceneHitCircleLongCombo : PlayerTestScene { public TestSceneHitCircleLongCombo() : base(new OsuRuleset()) { } protected override IBeatmap CreateBeatmap(RulesetInfo ruleset) { var beatmap = new Beatmap { BeatmapInfo = new BeatmapInfo { BaseDifficulty = new BeatmapDifficulty { CircleSize = 6 }, Ruleset = ruleset } }; for (int i = 0; i < 512; i++) beatmap.HitObjects.Add(new HitCircle { Position = new Vector2(256, 192), StartTime = i * 100 }); return beatmap; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Game.Beatmaps; using osu.Game.Rulesets.Osu.Objects; using osu.Game.Tests.Visual; using osuTK; namespace osu.Game.Rulesets.Osu.Tests { [TestFixture] public class TestSceneHitCircleLongCombo : PlayerTestScene { public TestSceneHitCircleLongCombo() : base(new OsuRuleset()) { } protected override IBeatmap CreateBeatmap(RulesetInfo ruleset) { var beatmap = new Beatmap { BeatmapInfo = new BeatmapInfo { BaseDifficulty = new BeatmapDifficulty { CircleSize = 6 }, Ruleset = ruleset } }; for (int i = 0; i < 512; i++) if (i % 32 < 20) beatmap.HitObjects.Add(new HitCircle { Position = new Vector2(256, 192), StartTime = i * 100 }); return beatmap; } } }
Add support for command line arguments to configuration
using System; using System.Text.RegularExpressions; namespace KillrVideo.Host.Config { /// <summary> /// Gets configuration values from environment variables. /// </summary> public class EnvironmentConfigurationSource : IHostConfigurationSource { private static readonly Regex MatchCaps = new Regex("[ABCDEFGHIJKLMNOPQRSTUVWXYZ]", RegexOptions.Singleline | RegexOptions.Compiled); public string GetConfigurationValue(string key) { key = ConfigKeyToEnvironmentVariableName(key); return Environment.GetEnvironmentVariable(key); } /// <summary> /// Utility method to convert a config key to an approriate environment variable name. /// </summary> private static string ConfigKeyToEnvironmentVariableName(string key) { key = MatchCaps.Replace(key, match => match.Index == 0 ? match.Value : $"_{match.Value}"); return $"KILLRVIDEO_{key.ToUpperInvariant()}"; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace KillrVideo.Host.Config { /// <summary> /// Gets configuration values from command line args and environment variables. /// </summary> public class EnvironmentConfigurationSource : IHostConfigurationSource { private static readonly Regex MatchCaps = new Regex("[ABCDEFGHIJKLMNOPQRSTUVWXYZ]", RegexOptions.Singleline | RegexOptions.Compiled); private readonly Lazy<IDictionary<string, string>> _commandLineArgs; public EnvironmentConfigurationSource() { _commandLineArgs = new Lazy<IDictionary<string,string>>(ParseCommandLineArgs); } public string GetConfigurationValue(string key) { // See if command line had it string val; if (_commandLineArgs.Value.TryGetValue(key, out val)) return val; // See if environment variables have it key = ConfigKeyToEnvironmentVariableName(key); return Environment.GetEnvironmentVariable(key); } private static IDictionary<string, string> ParseCommandLineArgs() { var results = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); // Get command line args but skip the first one which will be the process/executable name string[] args = Environment.GetCommandLineArgs().Skip(1).ToArray(); string argName = null; foreach (string arg in args) { // Do we have an argument? if (arg.StartsWith("-")) { // If we currently have an argName, assume it was a switch and just add TrueString as the value if (argName != null) results.Add(argName, bool.TrueString); argName = arg.TrimStart('-'); continue; } // Do we have an argument that doesn't have a previous arg name? if (argName == null) throw new InvalidOperationException($"Unknown command line argument {arg}"); // Add argument value under previously parsed arg name results.Add(argName, arg); argName = null; } return results; } /// <summary> /// Utility method to convert a config key to an approriate environment variable name. /// </summary> private static string ConfigKeyToEnvironmentVariableName(string key) { key = MatchCaps.Replace(key, match => match.Index == 0 ? match.Value : $"_{match.Value}"); return $"KILLRVIDEO_{key.ToUpperInvariant()}"; } } }
Remove unnecessary point type check
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Harlow { public class VectorPoint : VectorFeature { public VectorPoint(int numOfPoints, ShapeType shapeType) : base (numOfPoints, shapeType) { if (shapeType != ShapeType.Point) { Bbox = new double[4]; } this.Coordinates = new double[numOfPoints]; this.Properties = new Dictionary<string, string>(); } /// <summary> /// All of the points that make up the vector feature. /// Points don't have segments /// </summary> new public double[] Coordinates { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Harlow { public class VectorPoint : VectorFeature { public VectorPoint(int numOfPoints, ShapeType shapeType) : base (numOfPoints, shapeType) { this.Coordinates = new double[numOfPoints]; this.Properties = new Dictionary<string, string>(); } /// <summary> /// All of the points that make up the vector feature. /// Points don't have segments /// </summary> new public double[] Coordinates { get; set; } } }
Increment assembly version for new Nuget build.
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("MonoGameUtils")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MonoGameUtils")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("4ecedc75-1f2d-4915-9efe-368a5d104e41")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // 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.0.5.0")] [assembly: AssemblyFileVersion("1.0.5.0")]
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("MonoGameUtils")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MonoGameUtils")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("4ecedc75-1f2d-4915-9efe-368a5d104e41")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // 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.0.6.0")] [assembly: AssemblyFileVersion("1.0.6.0")]
Make explicit marker font semi-bold
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Game.Graphics; using osu.Game.Graphics.Sprites; namespace osu.Game.Overlays.BeatmapSet { public class ExplicitBeatmapPill : CompositeDrawable { public ExplicitBeatmapPill() { AutoSizeAxes = Axes.Both; } [BackgroundDependencyLoader(true)] private void load(OsuColour colours, OverlayColourProvider colourProvider) { InternalChild = new CircularContainer { Masking = true, AutoSizeAxes = Axes.Both, Children = new Drawable[] { new Box { RelativeSizeAxes = Axes.Both, Colour = colourProvider?.Background5 ?? colours.Gray2, }, new OsuSpriteText { Margin = new MarginPadding { Horizontal = 10f, Vertical = 2f }, Text = "EXPLICIT", Font = OsuFont.GetFont(size: 10, weight: FontWeight.Bold), Colour = OverlayColourProvider.Orange.Colour2, } } }; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Game.Graphics; using osu.Game.Graphics.Sprites; namespace osu.Game.Overlays.BeatmapSet { public class ExplicitBeatmapPill : CompositeDrawable { public ExplicitBeatmapPill() { AutoSizeAxes = Axes.Both; } [BackgroundDependencyLoader(true)] private void load(OsuColour colours, OverlayColourProvider colourProvider) { InternalChild = new CircularContainer { Masking = true, AutoSizeAxes = Axes.Both, Children = new Drawable[] { new Box { RelativeSizeAxes = Axes.Both, Colour = colourProvider?.Background5 ?? colours.Gray2, }, new OsuSpriteText { Margin = new MarginPadding { Horizontal = 10f, Vertical = 2f }, Text = "EXPLICIT", Font = OsuFont.GetFont(size: 10, weight: FontWeight.SemiBold), Colour = OverlayColourProvider.Orange.Colour2, } } }; } } }
Use new array indexing syntax
using System; using System.Collections.Generic; using System.IO; using System.Net; namespace PlaylistGrabber { public class Downloader { public string State { get; private set; } public int DownloadedFiles { get; private set; } public int TotalFiles { get; private set; } public void DownloadFiles(List<Uri> uris) { TotalFiles = uris.Count; foreach (var uri in uris) { DownloadFile(uri); DownloadedFiles++; } } private void DownloadFile(Uri uri) { State = $"Downloading {uri} ..."; var webClient = new WebClient(); var destinationPath = GetDestinationPath(uri); webClient.DownloadFile(uri, destinationPath); } private static string GetDestinationPath(Uri uri) { var parts = uri.ToString().Split('/'); var directoryName = parts[parts.Length - 2]; var fileName = parts[parts.Length - 1]; string destinationDirectory = $@"Z:\Downloads\{directoryName}"; // only creates dir if it doesn't already exist Directory.CreateDirectory(destinationDirectory); string destinationPath = $@"{destinationDirectory}\{fileName}"; if (File.Exists(destinationPath)) { File.Delete(destinationPath); } return destinationPath; } } }
using System; using System.Collections.Generic; using System.IO; using System.Net; namespace PlaylistGrabber { public class Downloader { public string State { get; private set; } public int DownloadedFiles { get; private set; } public int TotalFiles { get; private set; } public void DownloadFiles(List<Uri> uris) { TotalFiles = uris.Count; foreach (var uri in uris) { DownloadFile(uri); DownloadedFiles++; } } private void DownloadFile(Uri uri) { State = $"Downloading {uri} ..."; var webClient = new WebClient(); var destinationPath = GetDestinationPath(uri); webClient.DownloadFile(uri, destinationPath); } private static string GetDestinationPath(Uri uri) { var parts = uri.ToString().Split('/'); var directoryName = parts[^2]; var fileName = parts[^1]; string destinationDirectory = $@"Z:\Downloads\{directoryName}"; // only creates dir if it doesn't already exist Directory.CreateDirectory(destinationDirectory); string destinationPath = $@"{destinationDirectory}\{fileName}"; if (File.Exists(destinationPath)) { File.Delete(destinationPath); } return destinationPath; } } }
Revert "Quarantine all ProjectTemplate tests until dotnet new lock issue is resolved."
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.AspNetCore.E2ETesting; using Microsoft.AspNetCore.Testing; using Templates.Test.Helpers; using Xunit; [assembly: TestFramework("Microsoft.AspNetCore.E2ETesting.XunitTestFrameworkWithAssemblyFixture", "ProjectTemplates.Tests")] [assembly: Microsoft.AspNetCore.E2ETesting.AssemblyFixture(typeof(ProjectFactoryFixture))] [assembly: Microsoft.AspNetCore.E2ETesting.AssemblyFixture(typeof(SeleniumStandaloneServer))] [assembly: QuarantinedTest("Investigation pending in https://github.com/dotnet/aspnetcore/issues/21748")]
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.AspNetCore.E2ETesting; using Microsoft.AspNetCore.Testing; using Templates.Test.Helpers; using Xunit; [assembly: TestFramework("Microsoft.AspNetCore.E2ETesting.XunitTestFrameworkWithAssemblyFixture", "ProjectTemplates.Tests")] [assembly: Microsoft.AspNetCore.E2ETesting.AssemblyFixture(typeof(ProjectFactoryFixture))] [assembly: Microsoft.AspNetCore.E2ETesting.AssemblyFixture(typeof(SeleniumStandaloneServer))]
Fix regression due to starting in Part view without printer selection
using System.Threading; using System.Threading.Tasks; using MatterHackers.Agg.UI; using NUnit.Framework; namespace MatterHackers.MatterControl.Tests.Automation { [TestFixture, Category("MatterControl.UI.Automation"), RunInApplicationDomain] public class ShowTerminalButtonClickedOpensTerminal { [Test, Apartment(ApartmentState.STA)] public async Task ClickingShowTerminalButtonOpensTerminal() { await MatterControlUtilities.RunTest((testRunner) => { testRunner.CloseSignInAndPrinterSelect(); Assert.IsFalse(testRunner.WaitForName("TerminalWidget", 0.5), "Terminal Window should not exist"); testRunner.ClickByName("Terminal Sidebar"); testRunner.Delay(1); Assert.IsTrue(testRunner.WaitForName("TerminalWidget"), "Terminal Window should exists after Show Terminal button is clicked"); return Task.CompletedTask; }); } } }
using System.Threading; using System.Threading.Tasks; using MatterHackers.Agg.UI; using NUnit.Framework; namespace MatterHackers.MatterControl.Tests.Automation { [TestFixture, Category("MatterControl.UI.Automation"), RunInApplicationDomain] public class ShowTerminalButtonClickedOpensTerminal { [Test, Apartment(ApartmentState.STA)] public async Task ClickingShowTerminalButtonOpensTerminal() { await MatterControlUtilities.RunTest((testRunner) => { testRunner.AddAndSelectPrinter("Airwolf 3D", "HD"); Assert.IsFalse(testRunner.WaitForName("TerminalWidget", 0.5), "Terminal Window should not exist"); testRunner.ClickByName("Terminal Sidebar"); testRunner.Delay(1); Assert.IsTrue(testRunner.WaitForName("TerminalWidget"), "Terminal Window should exists after Show Terminal button is clicked"); return Task.CompletedTask; }); } } }
Fix bug where factory name hadn't been udpated
using Glimpse.Agent.Connection.Stream.Connection; using System; using System.Threading.Tasks; namespace Glimpse.Agent { public class WebSocketChannelSender : IChannelSender { private readonly IMessageConverter _messageConverter; private readonly IStreamHubProxyFactory _streamHubProxyFactory; private IStreamHubProxy _streamHubProxy; public WebSocketChannelSender(IMessageConverter messageConverter, IStreamHubProxyFactory streamHubProxyFactory) { _messageConverter = messageConverter; _streamHubProxyFactory = streamHubProxyFactory; _streamHubProxyFactory.Register("RemoteStreamMessagePublisherResource", x => _streamHubProxy = x); } public async Task PublishMessage(IMessage message) { // TODO: Probably not the best place to put this await _streamHubProxyFactory.Start(); var newMessage = _messageConverter.ConvertMessage(message); await _streamHubProxy.Invoke("HandleMessage", newMessage); } } }
using Glimpse.Agent.Connection.Stream.Connection; using System; using System.Threading.Tasks; namespace Glimpse.Agent { public class WebSocketChannelSender : IChannelSender { private readonly IMessageConverter _messageConverter; private readonly IStreamHubProxyFactory _streamHubProxyFactory; private IStreamHubProxy _streamHubProxy; public WebSocketChannelSender(IMessageConverter messageConverter, IStreamHubProxyFactory streamHubProxyFactory) { _messageConverter = messageConverter; _streamHubProxyFactory = streamHubProxyFactory; _streamHubProxyFactory.Register("WebSocketChannelReceiver", x => _streamHubProxy = x); } public async Task PublishMessage(IMessage message) { // TODO: Probably not the best place to put this await _streamHubProxyFactory.Start(); var newMessage = _messageConverter.ConvertMessage(message); await _streamHubProxy.Invoke("HandleMessage", newMessage); } } }
Fix tiny droplet scale factor
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; namespace osu.Game.Rulesets.Catch.Objects.Drawables { public class DrawableTinyDroplet : DrawableDroplet { public DrawableTinyDroplet(TinyDroplet h) : base(h) { } [BackgroundDependencyLoader] private void load() { ScaleContainer.Scale /= 2; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. namespace osu.Game.Rulesets.Catch.Objects.Drawables { public class DrawableTinyDroplet : DrawableDroplet { protected override float ScaleFactor => base.ScaleFactor / 2; public DrawableTinyDroplet(TinyDroplet h) : base(h) { } } }
Tidy up Start() function comment
using UnityEngine; using System.Collections; namespace Fungus { // Defines a camera view point. // The position and rotation are specified using the game object's transform, so this class // only specifies the ortographic view size. [ExecuteInEditMode] public class View : MonoBehaviour { public float viewSize = 0.5f; void Start() { // An empty Start() method is needed to display enable checkbox in editor } } }
using UnityEngine; using System.Collections; namespace Fungus { // Defines a camera view point. // The position and rotation are specified using the game object's transform, so this class // only specifies the ortographic view size. [ExecuteInEditMode] public class View : MonoBehaviour { public float viewSize = 0.5f; // An empty Start() method is needed to display enable checkbox in editor void Start() {} } }
Check if argument in projection provider attribute is a valid type
using System; namespace EnjoyCQRS.Attributes { [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public class ProjectionProviderAttribute : Attribute { public Type Provider { get; } public ProjectionProviderAttribute(Type provider) { Provider = provider; } } }
using System; using System.Reflection; using EnjoyCQRS.EventSource.Projections; namespace EnjoyCQRS.Attributes { [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public class ProjectionProviderAttribute : Attribute { public Type Provider { get; } public ProjectionProviderAttribute(Type provider) { if (provider == null) throw new ArgumentNullException(nameof(provider)); if (provider.IsAssignableFrom(typeof(IProjectionProvider))) throw new ArgumentException($"Provider should be inherited of {nameof(IProjectionProvider)}."); Provider = provider; } } }
Remove changes done to unrelated unit test
using Baseline; using Marten.Schema; using Marten.Services; using Marten.Testing.Documents; using Shouldly; using Xunit; namespace Marten.Testing { public class duplicate_fields_in_table_and_upsert_Tests : IntegratedFixture { [Fact] public void end_to_end() { theStore.Storage.MappingFor(typeof(User)).As<DocumentMapping>().DuplicateField("FirstName"); var store = DocumentStore.For(_ => { _.Connection("host=localhost;database=test;password=password1;username=postgres"); _.AutoCreateSchemaObjects = AutoCreate.CreateOrUpdate; _.Schema.For<User>() .Duplicate(u => u.FirstName); }); var user1 = new User { FirstName = "Byron", LastName = "Scott" }; using (var session = theStore.OpenSession()) { session.Store(user1); session.SaveChanges(); } var runner = theStore.Tenancy.Default.OpenConnection(); runner.QueryScalar<string>($"select first_name from mt_doc_user where id = '{user1.Id}'") .ShouldBe("Byron"); } } }
using Baseline; using Marten.Schema; using Marten.Services; using Marten.Testing.Documents; using Shouldly; using Xunit; namespace Marten.Testing { public class duplicate_fields_in_table_and_upsert_Tests : IntegratedFixture { [Fact] public void end_to_end() { theStore.Storage.MappingFor(typeof(User)).As<DocumentMapping>().DuplicateField("FirstName"); var user1 = new User { FirstName = "Byron", LastName = "Scott" }; using (var session = theStore.OpenSession()) { session.Store(user1); session.SaveChanges(); } var runner = theStore.Tenancy.Default.OpenConnection(); runner.QueryScalar<string>($"select first_name from mt_doc_user where id = '{user1.Id}'") .ShouldBe("Byron"); } } }
Fix more race conditions between tests
using System; using GitHub.Api; using GitHub.Primitives; using GitHub.Services; using GitHub.VisualStudio; using NSubstitute; using Xunit; public class SimpleApiClientFactoryTests { public class TheCreateMethod { [Fact] public void CreatesNewInstanceOfSimpleApiClient() { var program = new Program(); var enterpriseProbe = Substitute.For<IEnterpriseProbeTask>(); var wikiProbe = Substitute.For<IWikiProbe>(); var factory = new SimpleApiClientFactory( program, new Lazy<IEnterpriseProbeTask>(() => enterpriseProbe), new Lazy<IWikiProbe>(() => wikiProbe)); var client = factory.Create("https://github.com/github/visualstudio"); Assert.Equal("https://github.com/github/visualstudio", client.OriginalUrl); Assert.Equal(HostAddress.GitHubDotComHostAddress, client.HostAddress); Assert.Same(client, factory.Create("https://github.com/github/visualstudio")); // Tests caching. } } public class TheClearFromCacheMethod { [Fact] public void RemovesClientFromCache() { var program = new Program(); var enterpriseProbe = Substitute.For<IEnterpriseProbeTask>(); var wikiProbe = Substitute.For<IWikiProbe>(); var factory = new SimpleApiClientFactory( program, new Lazy<IEnterpriseProbeTask>(() => enterpriseProbe), new Lazy<IWikiProbe>(() => wikiProbe)); var client = factory.Create("https://github.com/github/visualstudio"); factory.ClearFromCache(client); Assert.NotSame(client, factory.Create("https://github.com/github/visualstudio")); } } }
using System; using GitHub.Api; using GitHub.Primitives; using GitHub.Services; using GitHub.VisualStudio; using NSubstitute; using Xunit; public class SimpleApiClientFactoryTests { public class TheCreateMethod { [Fact] public void CreatesNewInstanceOfSimpleApiClient() { const string url = "https://github.com/github/CreatesNewInstanceOfSimpleApiClient"; var program = new Program(); var enterpriseProbe = Substitute.For<IEnterpriseProbeTask>(); var wikiProbe = Substitute.For<IWikiProbe>(); var factory = new SimpleApiClientFactory( program, new Lazy<IEnterpriseProbeTask>(() => enterpriseProbe), new Lazy<IWikiProbe>(() => wikiProbe)); var client = factory.Create(url); Assert.Equal(url, client.OriginalUrl); Assert.Equal(HostAddress.GitHubDotComHostAddress, client.HostAddress); Assert.Same(client, factory.Create(url)); // Tests caching. } } public class TheClearFromCacheMethod { [Fact] public void RemovesClientFromCache() { const string url = "https://github.com/github/RemovesClientFromCache"; var program = new Program(); var enterpriseProbe = Substitute.For<IEnterpriseProbeTask>(); var wikiProbe = Substitute.For<IWikiProbe>(); var factory = new SimpleApiClientFactory( program, new Lazy<IEnterpriseProbeTask>(() => enterpriseProbe), new Lazy<IWikiProbe>(() => wikiProbe)); var client = factory.Create(url); factory.ClearFromCache(client); Assert.NotSame(client, factory.Create(url)); } } }
Replace default script methods with Update & FixedUpdate methods
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerController : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerController : MonoBehaviour { // Update is called before rendering a frame void Update () { } // FixedUpdate is called just before performing any physics calculations void FixedUpdate () { } }
Set default result count of a recipe to 1
using FactorioModBuilder.Models.Base; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FactorioModBuilder.Models.ProjectItems.Prototype { public class Recipe : TreeItem<Recipe> { public bool Enabled { get; set; } public int EnergyRequired { get; set; } public string Result { get; set; } public int ResultCount { get; set; } public Recipe(string name) : base(name) { } } }
using FactorioModBuilder.Models.Base; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FactorioModBuilder.Models.ProjectItems.Prototype { public class Recipe : TreeItem<Recipe> { public bool Enabled { get; set; } public int EnergyRequired { get; set; } public string Result { get; set; } public int ResultCount { get; set; } public Recipe(string name) : base(name) { this.ResultCount = 1; } } }
Update Assembly properties to version 2.0
using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle("HacknetPathfinder")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("${AuthorCopyright}")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion("1.0.*")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")]
using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle("HacknetPathfinder")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("${AuthorCopyright}")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion("2.0.*")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")]
Add test trace output to webforms page
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace WingtipToys { public partial class _Default : Page { protected void Page_Load(object sender, EventArgs e) { } private void Page_Error(object sender, EventArgs e) { // Get last error from the server. Exception exc = Server.GetLastError(); // Handle specific exception. if (exc is InvalidOperationException) { // Pass the error on to the error page. Server.Transfer("ErrorPage.aspx?handler=Page_Error%20-%20Default.aspx", true); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace WingtipToys { public partial class _Default : Page { protected void Page_Load(object sender, EventArgs e) { HttpContext.Current.Trace.Write("Something that happened in Load"); } protected void Page_Init(object sender, EventArgs e) { HttpContext.Current.Trace.Write("Something that happened in Init"); } protected void Page_Render(object sender, EventArgs e) { HttpContext.Current.Trace.Write("Something that happened in Render"); } protected void Page_SaveStateComplete(object sender, EventArgs e) { HttpContext.Current.Trace.Write("Something that happened in SaveStateComplete"); } protected void Page_SaveState(object sender, EventArgs e) { HttpContext.Current.Trace.Write("Something that happened in SaveState"); } protected void Page_PreRender(object sender, EventArgs e) { HttpContext.Current.Trace.Write("Something that happened in PreRender"); } protected void Page_PreRenderComplete(object sender, EventArgs e) { HttpContext.Current.Trace.Write("Something that happened in PreRenderComplete"); } protected override void OnInitComplete(EventArgs e) { HttpContext.Current.Trace.Write("Something that happened in InitComplete"); base.OnInitComplete(e); } protected override void OnPreInit(EventArgs e) { HttpContext.Current.Trace.Write("Something that happened in PreInit"); base.OnPreInit(e); } protected override void OnPreLoad(EventArgs e) { HttpContext.Current.Trace.Write("Something that happened in PreLoad"); base.OnPreLoad(e); } private void Page_Error(object sender, EventArgs e) { // Get last error from the server. Exception exc = Server.GetLastError(); // Handle specific exception. if (exc is InvalidOperationException) { // Pass the error on to the error page. Server.Transfer("ErrorPage.aspx?handler=Page_Error%20-%20Default.aspx", true); } } } }
Update version from 1.0.0.1 to 2.0.0.0
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Openpay")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Openpay")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("96e67616-0932-45bb-a06e-82c7683abc7c")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // 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.0.0.1")] [assembly: AssemblyFileVersion("1.0.0.1")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Openpay")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Openpay")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("96e67616-0932-45bb-a06e-82c7683abc7c")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("2.0.0.0")] [assembly: AssemblyFileVersion("2.0.0.0")]
Fix a bug in array extension
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace System { public static class ArrayExtension { public static int IndexOf<T>(this T[] me, T item) { for (int i = 0; i < me.Length; i++) if (me[i].Equals(item)) return i; return -1; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace System { public static class ArrayExtension { public static int IndexOf<T>(this T[] me, T item) { for (int i = 0; i < me.Length; i++) if (me[i]?.Equals(item) == true) return i; return -1; } } }
Simplify usage of the solver
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SketchSolve { public class Parameter { public double Value = 0; // true if the parameter is free to be adjusted by the // solver public bool free; public Parameter (double v, bool free=true) { Value = v; this.free = free; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SketchSolve { public class Parameter { public double Value = 0; public double Max = 1000; public double Min = -1000; // true if the parameter is free to be adjusted by the // solver public bool free; public Parameter (double v, bool free=true) { Value = v; this.free = free; } } }
Put in placeholders instead of a real username and password.
using System.Xml; using PropertyFeedSampleApp.PropertyFeed; namespace PropertyFeedSampleApp { class Program { static void Main(string[] args) { const string userName = "VACATION11"; const string password = "f33der1!"; using (var client = new DataReceiverServiceSoapClient()) { var supplierIds = client.GetValidRentalUnitIdsForExtract(new AuthHeader { UserName = userName, Password = password }, string.Empty, string.Empty, true); foreach (var supplierId in supplierIds) { var rentalUnitIds = client.GetValidRentalUnitIdsForExtract(new AuthHeader { UserName = userName, Password = password }, string.Empty, supplierId.ToString(), false); foreach (var rentalUnitId in rentalUnitIds) { //Some properties will return a lot of data. //Be sure to increase the MaxReceivedMessageSize property on the appropriate binding element in your config. //We suggest maxReceivedMessageSize="6553600" string dataExtract = client.DataExtract(new AuthHeader { UserName = userName, Password = password }, "STANDARD", string.Empty, string.Empty, rentalUnitId.ToString()); var propertyDoc = new XmlDocument(); propertyDoc.LoadXml(dataExtract); if (propertyDoc.DocumentElement.ChildNodes.Count == 0) { //The property is inactive, make it inactive in your system } else { //The property is active, cache the data in your system goto EndOfExample; } } } EndOfExample:; } } } }
using System.Xml; using PropertyFeedSampleApp.PropertyFeed; namespace PropertyFeedSampleApp { class Program { static void Main(string[] args) { //You should have been provided values for the following const string userName = "YOUR_USER_NAME"; const string password = "YOUR_PASSWORD"; using (var client = new DataReceiverServiceSoapClient()) { var supplierIds = client.GetValidRentalUnitIdsForExtract(new AuthHeader { UserName = userName, Password = password }, string.Empty, string.Empty, true); foreach (var supplierId in supplierIds) { var rentalUnitIds = client.GetValidRentalUnitIdsForExtract(new AuthHeader { UserName = userName, Password = password }, string.Empty, supplierId.ToString(), false); foreach (var rentalUnitId in rentalUnitIds) { //Some properties will return a lot of data. //Be sure to increase the MaxReceivedMessageSize property on the appropriate binding element in your config. //We suggest maxReceivedMessageSize="6553600" string dataExtract = client.DataExtract(new AuthHeader { UserName = userName, Password = password }, "STANDARD", string.Empty, string.Empty, rentalUnitId.ToString()); var propertyDoc = new XmlDocument(); propertyDoc.LoadXml(dataExtract); if (propertyDoc.DocumentElement.ChildNodes.Count == 0) { //The property is inactive, make it inactive in your system } else { //The property is active, cache the data in your system goto EndOfExample; } } } EndOfExample:; } } } }
Add error handling for auth response
using System.Collections.Specialized; using System.Web; using Microsoft.IdentityModel.Protocols; namespace Owin.Security.Keycloak.Models { internal class AuthorizationResponse : OidcBaseResponse { public string Code { get; private set; } public string State { get; private set; } public AuthorizationResponse(string query) { Init(HttpUtility.ParseQueryString(query)); } public AuthorizationResponse(NameValueCollection authResult) { Init(authResult); } protected new void Init(NameValueCollection authResult) { base.Init(authResult); Code = authResult.Get(OpenIdConnectParameterNames.Code); State = authResult.Get(OpenIdConnectParameterNames.State); } } }
using System; using System.Collections.Specialized; using System.Web; using Microsoft.IdentityModel.Protocols; namespace Owin.Security.Keycloak.Models { internal class AuthorizationResponse : OidcBaseResponse { public string Code { get; private set; } public string State { get; private set; } public AuthorizationResponse(string query) { Init(HttpUtility.ParseQueryString(query)); if (!Validate()) { throw new ArgumentException("Invalid query string used to instantiate an AuthorizationResponse"); } } public AuthorizationResponse(NameValueCollection authResult) { Init(authResult); } protected new void Init(NameValueCollection authResult) { base.Init(authResult); Code = authResult.Get(OpenIdConnectParameterNames.Code); State = authResult.Get(OpenIdConnectParameterNames.State); } public bool Validate() { return !string.IsNullOrWhiteSpace(Code) && !string.IsNullOrWhiteSpace(State); } } }
Hide .sln file from project tree
using System; using System.IO; using System.Linq; using Microsoft.VisualStudio.ProjectSystem.FileSystemMirroring.IO; namespace Microsoft.VisualStudio.R.Package.ProjectSystem { internal sealed class RMsBuildFileSystemFilter : IMsBuildFileSystemFilter { public bool IsFileAllowed(string relativePath, FileAttributes attributes) { return !attributes.HasFlag(FileAttributes.Hidden) && !HasExtension(relativePath, ".user", ".rxproj"); } public bool IsDirectoryAllowed(string relativePath, FileAttributes attributes) { return !attributes.HasFlag(FileAttributes.Hidden); } public void Seal() { } private static bool HasExtension(string filePath, params string[] possibleExtensions) { var extension = Path.GetExtension(filePath); return !string.IsNullOrEmpty(extension) && possibleExtensions.Any(pe => extension.Equals(pe, StringComparison.OrdinalIgnoreCase)); } } }
using System; using System.IO; using System.Linq; using Microsoft.VisualStudio.ProjectSystem.FileSystemMirroring.IO; namespace Microsoft.VisualStudio.R.Package.ProjectSystem { internal sealed class RMsBuildFileSystemFilter : IMsBuildFileSystemFilter { public bool IsFileAllowed(string relativePath, FileAttributes attributes) { return !attributes.HasFlag(FileAttributes.Hidden) && !HasExtension(relativePath, ".user", ".rxproj", ".sln"); } public bool IsDirectoryAllowed(string relativePath, FileAttributes attributes) { return !attributes.HasFlag(FileAttributes.Hidden); } public void Seal() { } private static bool HasExtension(string filePath, params string[] possibleExtensions) { var extension = Path.GetExtension(filePath); return !string.IsNullOrEmpty(extension) && possibleExtensions.Any(pe => extension.Equals(pe, StringComparison.OrdinalIgnoreCase)); } } }
Fix infinite loop when retrying a failing build number
#tool "nuget:?package=GitVersion.CommandLine" #addin "Cake.Yaml" public class ContextInfo { public string NugetVersion { get; set; } public string AssemblyVersion { get; set; } public GitVersion Git { get; set; } public string BuildVersion { get { return NugetVersion + "-" + Git.Sha; } } } ContextInfo _versionContext = null; public ContextInfo VersionContext { get { if(_versionContext == null) throw new Exception("The current context has not been read yet. Call ReadContext(FilePath) before accessing the property."); return _versionContext; } } public ContextInfo ReadContext(FilePath filepath) { _versionContext = DeserializeYamlFromFile<ContextInfo>(filepath); _versionContext.Git = GitVersion(); return _versionContext; } public void UpdateAppVeyorBuildVersionNumber() { if(!AppVeyor.IsRunningOnAppVeyor) { Information("Not running under AppVeyor"); return; } Information("Running under AppVeyor"); Information("Updating AppVeyor build version to " + VersionContext.BuildVersion); while(true) { int? increment = null; try { var version = VersionContext.BuildVersion; if(increment.HasValue) version += "-" + increment.Value; AppVeyor.UpdateBuildVersion(version); break; } catch { increment++; if(increment <= 10) continue; } } }
#tool "nuget:?package=GitVersion.CommandLine" #addin "Cake.Yaml" public class ContextInfo { public string NugetVersion { get; set; } public string AssemblyVersion { get; set; } public GitVersion Git { get; set; } public string BuildVersion { get { return NugetVersion + "-" + Git.Sha; } } } ContextInfo _versionContext = null; public ContextInfo VersionContext { get { if(_versionContext == null) throw new Exception("The current context has not been read yet. Call ReadContext(FilePath) before accessing the property."); return _versionContext; } } public ContextInfo ReadContext(FilePath filepath) { _versionContext = DeserializeYamlFromFile<ContextInfo>(filepath); _versionContext.Git = GitVersion(); return _versionContext; } public void UpdateAppVeyorBuildVersionNumber() { // if(!AppVeyor.IsRunningOnAppVeyor) // { // Information("Not running under AppVeyor"); // return; // } Information("Running under AppVeyor"); Information("Updating AppVeyor build version to " + VersionContext.BuildVersion); var increment = 0; while(increment < 10) { try { var version = VersionContext.BuildVersion; if(increment > 0) version += "-" + increment; AppVeyor.UpdateBuildVersion(version); break; } catch { increment++; } } }
Fix improper container configuration for service locator
namespace OctoHook { using Autofac; using Autofac.Extras.CommonServiceLocator; using Autofac.Integration.WebApi; using Microsoft.Practices.ServiceLocation; using OctoHook.CommonComposition; using Octokit; using Octokit.Internal; using System.Configuration; using System.Reflection; using System.Web; using System.Web.Http; public static class ContainerConfiguration { public static IContainer Configure(IWorkQueue queue) { IContainer container = null; var builder = new ContainerBuilder(); builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); builder.RegisterComponents(Assembly.GetExecutingAssembly()) .InstancePerRequest(); builder.Register<IGitHubClient>(c => new GitHubClient( new ProductHeaderValue("OctoHook"), new InMemoryCredentialStore( new Credentials(ConfigurationManager.AppSettings["GitHubToken"])))); builder.Register<IServiceLocator>(c => new AutofacServiceLocator(container)); builder.RegisterInstance(queue).SingleInstance(); container = builder.Build(); return container; } } }
namespace OctoHook { using Autofac; using Autofac.Extras.CommonServiceLocator; using Autofac.Integration.WebApi; using Microsoft.Practices.ServiceLocation; using OctoHook.CommonComposition; using Octokit; using Octokit.Internal; using System.Configuration; using System.Reflection; using System.Web; using System.Web.Http; public static class ContainerConfiguration { public static IContainer Configure(IWorkQueue queue) { IContainer container = null; var builder = new ContainerBuilder(); builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); builder.RegisterComponents(Assembly.GetExecutingAssembly()) .InstancePerRequest(); builder.Register<IGitHubClient>(c => new GitHubClient( new ProductHeaderValue("OctoHook"), new InMemoryCredentialStore( new Credentials(ConfigurationManager.AppSettings["GitHubToken"])))); builder.Register<IServiceLocator>(c => new AutofacServiceLocator(c)) .InstancePerRequest(); builder.RegisterInstance(queue).SingleInstance(); container = builder.Build(); return container; } } }
Verify exception message when application is not configured
using System.IO; using System.Text; using Moq; using Xunit; namespace AppHarbor.Tests { public class ApplicationConfigurationTest { public static string ConfigurationFile = Path.GetFullPath(".appharbor"); [Fact] public void ShouldReturnApplicationIdIfConfigurationFileExists() { var fileSystem = new Mock<IFileSystem>(); var applicationName = "bar"; var configurationFile = ConfigurationFile; var stream = new MemoryStream(Encoding.Default.GetBytes(applicationName)); fileSystem.Setup(x => x.OpenRead(configurationFile)).Returns(stream); var applicationConfiguration = new ApplicationConfiguration(fileSystem.Object); Assert.Equal(applicationName, applicationConfiguration.GetApplicationId()); } [Fact] public void ShouldThrowIfApplicationFileDoesNotExist() { var fileSystem = new InMemoryFileSystem(); var applicationConfiguration = new ApplicationConfiguration(fileSystem); Assert.Throws<ApplicationConfigurationException>(() => applicationConfiguration.GetApplicationId()); } } }
using System.IO; using System.Text; using Moq; using Xunit; namespace AppHarbor.Tests { public class ApplicationConfigurationTest { public static string ConfigurationFile = Path.GetFullPath(".appharbor"); [Fact] public void ShouldReturnApplicationIdIfConfigurationFileExists() { var fileSystem = new Mock<IFileSystem>(); var applicationName = "bar"; var configurationFile = ConfigurationFile; var stream = new MemoryStream(Encoding.Default.GetBytes(applicationName)); fileSystem.Setup(x => x.OpenRead(configurationFile)).Returns(stream); var applicationConfiguration = new ApplicationConfiguration(fileSystem.Object); Assert.Equal(applicationName, applicationConfiguration.GetApplicationId()); } [Fact] public void ShouldThrowIfApplicationFileDoesNotExist() { var fileSystem = new InMemoryFileSystem(); var applicationConfiguration = new ApplicationConfiguration(fileSystem); var exception = Assert.Throws<ApplicationConfigurationException>(() => applicationConfiguration.GetApplicationId()); Assert.Equal("Application is not configured", exception.Message); } } }
Change Russian to Русский for the language selector
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Wox.Core.i18n { internal static class AvailableLanguages { public static Language English = new Language("en", "English"); public static Language Chinese = new Language("zh-cn", "中文"); public static Language Chinese_TW = new Language("zh-tw", "中文(繁体)"); public static Language Russian = new Language("ru", "Russian"); public static List<Language> GetAvailableLanguages() { List<Language> languages = new List<Language> { English, Chinese, Chinese_TW, Russian, }; return languages; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Wox.Core.i18n { internal static class AvailableLanguages { public static Language English = new Language("en", "English"); public static Language Chinese = new Language("zh-cn", "中文"); public static Language Chinese_TW = new Language("zh-tw", "中文(繁体)"); public static Language Russian = new Language("ru", "Русский"); public static List<Language> GetAvailableLanguages() { List<Language> languages = new List<Language> { English, Chinese, Chinese_TW, Russian, }; return languages; } } }
Add ability to set loggerFactory for the ExceptionHandlerMiddleware
using System; using Microsoft.AspNetCore.Builder; namespace GlobalExceptionHandler.WebApi { public static class WebApiExceptionHandlingExtensions { [Obsolete("UseWebApiGlobalExceptionHandler is obsolete, use app.UseExceptionHandler().WithConventions(..) instead", true)] public static IApplicationBuilder UseWebApiGlobalExceptionHandler(this IApplicationBuilder app, Action<ExceptionHandlerConfiguration> configuration) { if (app == null) throw new ArgumentNullException(nameof(app)); if (configuration == null) throw new ArgumentNullException(nameof(configuration)); return app.UseExceptionHandler(new ExceptionHandlerOptions().SetHandler(configuration)); } public static IApplicationBuilder WithConventions(this IApplicationBuilder app) { return WithConventions(app, configuration => { }); } public static IApplicationBuilder WithConventions(this IApplicationBuilder app, Action<ExceptionHandlerConfiguration> configuration) { if (app == null) throw new ArgumentNullException(nameof(app)); if (configuration == null) throw new ArgumentNullException(nameof(configuration)); return app.UseExceptionHandler(new ExceptionHandlerOptions().SetHandler(configuration)); } } }
using System; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Diagnostics; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace GlobalExceptionHandler.WebApi { public static class WebApiExceptionHandlingExtensions { [Obsolete("UseWebApiGlobalExceptionHandler is obsolete, use app.UseExceptionHandler().WithConventions(..) instead", true)] public static IApplicationBuilder UseWebApiGlobalExceptionHandler(this IApplicationBuilder app, Action<ExceptionHandlerConfiguration> configuration) { if (app == null) throw new ArgumentNullException(nameof(app)); if (configuration == null) throw new ArgumentNullException(nameof(configuration)); return app.UseExceptionHandler(new ExceptionHandlerOptions().SetHandler(configuration)); } public static IApplicationBuilder WithConventions(this IApplicationBuilder app) { return WithConventions(app, configuration => { }); } public static IApplicationBuilder WithConventions(this IApplicationBuilder app, Action<ExceptionHandlerConfiguration> configuration) { if (app == null) throw new ArgumentNullException(nameof(app)); if (configuration == null) throw new ArgumentNullException(nameof(configuration)); return app.UseExceptionHandler(new ExceptionHandlerOptions().SetHandler(configuration)); } public static IApplicationBuilder WithConventions(this IApplicationBuilder app, Action<ExceptionHandlerConfiguration> configuration, ILoggerFactory loggerFactory) { if (app == null) throw new ArgumentNullException(nameof(app)); if (configuration == null) throw new ArgumentNullException(nameof(configuration)); if (loggerFactory == null) throw new ArgumentNullException(nameof(loggerFactory)); return app.UseMiddleware<ExceptionHandlerMiddleware>( Options.Create(new ExceptionHandlerOptions().SetHandler(configuration)), loggerFactory); } } }
Test for conversion to dynamic objects again
namespace AngleSharp.Scripting.CSharp.Tests { using NUnit.Framework; using System; using System.Threading.Tasks; [TestFixture] public class ConversionTests { [Test] [ExpectedException(typeof(ArgumentNullException))] public void ConvertCurrentDocumentOfFreshBrowsingContextWithoutDocumentShouldThrowException() { var context = BrowsingContext.New(); var document = context.GetDynamicDocument(); Assert.IsNotNull(document); } [Test] public async Task ConvertCurrentDocumentOfBrowsingContextShouldWork() { var url = "http://www.test.com/"; var context = BrowsingContext.New(); await context.OpenNewAsync(url); var document = context.GetDynamicDocument(); Assert.IsNotNull(document); } [Test] public async Task ConvertDocumentShouldResultInRightUrl() { var url = "http://www.test.com/"; var context = BrowsingContext.New(); var original = await context.OpenNewAsync(url); var document = original.ToDynamic(); Assert.IsNotNull(document); Assert.AreEqual(url, document.URL); } } }
namespace AngleSharp.Scripting.CSharp.Tests { using NUnit.Framework; using System; using System.Threading.Tasks; [TestFixture] public class ConversionTests { [Test] [ExpectedException(typeof(ArgumentNullException))] public void ConvertCurrentDocumentOfFreshBrowsingContextWithoutDocumentShouldThrowException() { var context = BrowsingContext.New(); var document = context.GetDynamicDocument(); Assert.IsNotNull(document); } [Test] public async Task ConvertCurrentDocumentOfBrowsingContextShouldWork() { var url = "http://www.test.com/"; var context = BrowsingContext.New(); await context.OpenNewAsync(url); var document = context.GetDynamicDocument(); Assert.IsNotNull(document); } [Test] public async Task ConvertDocumentShouldResultInRightUrl() { var url = "http://www.test.com/"; var context = BrowsingContext.New(); var original = await context.OpenNewAsync(url); var document = original.ToDynamic(); Assert.IsNotNull(document); Assert.AreEqual(url, document.URL); } [Test] public async Task ConvertDocumentShouldResultInEmptyBody() { var url = "http://www.test.com/"; var context = BrowsingContext.New(); var original = await context.OpenNewAsync(url); var document = original.ToDynamic(); Assert.IsNotNull(document); Assert.AreEqual(0, document.body.childElementCount); } } }
Fix bugs in windows phone forms renderer
using System; using Xamarin.Forms; using ZXing.Net.Mobile.Forms; using System.ComponentModel; using System.Reflection; using Xamarin.Forms.Platform.WinPhone; using ZXing.Net.Mobile.Forms.WindowsPhone; [assembly: ExportRenderer(typeof(ZXingScannerView), typeof(ZXingScannerViewRenderer))] namespace ZXing.Net.Mobile.Forms.WindowsPhone { //[Preserve(AllMembers = true)] public class ZXingScannerViewRenderer : ViewRenderer<ZXingScannerView, ZXing.Mobile.ZXingScannerControl> { public static void Init() { // Force the assembly to load } ZXingScannerView formsView; ZXing.Mobile.ZXingScannerControl zxingControl; protected override void OnElementChanged(ElementChangedEventArgs<ZXingScannerView> e) { formsView = Element; if (zxingControl == null) { zxingControl = new ZXing.Mobile.ZXingScannerControl(); zxingControl.UseCustomOverlay = false; formsView.InternalNativeScannerImplementation = zxingControl; base.SetNativeControl(zxingControl); } base.OnElementChanged(e); } } }
using System; using Xamarin.Forms; using ZXing.Net.Mobile.Forms; using System.ComponentModel; using System.Reflection; using Xamarin.Forms.Platform.WinPhone; using ZXing.Net.Mobile.Forms.WindowsPhone; [assembly: ExportRenderer(typeof(ZXingScannerView), typeof(ZXingScannerViewRenderer))] namespace ZXing.Net.Mobile.Forms.WindowsPhone { //[Preserve(AllMembers = true)] public class ZXingScannerViewRenderer : ViewRenderer<ZXingScannerView, ZXing.Mobile.ZXingScannerControl> { public static void Init() { // Force the assembly to load } ZXingScannerView formsView; ZXing.Mobile.ZXingScannerControl zxingControl; protected override void OnElementChanged(ElementChangedEventArgs<ZXingScannerView> e) { formsView = Element; if (zxingControl == null) { zxingControl = new ZXing.Mobile.ZXingScannerControl(); zxingControl.UseCustomOverlay = true; zxingControl.ContinuousScanning = true; formsView.InternalNativeScannerImplementation = zxingControl; base.SetNativeControl(zxingControl); } base.OnElementChanged(e); } } }
Set position in MemoryStream to 0, to ensure it can be read from later.
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OfficeDevPnP.Core.Extensions { public static class StreamExtensions { public static MemoryStream ToMemoryStream(this Stream source) { var stream = source as MemoryStream; if (stream != null) return stream; MemoryStream target = new MemoryStream(); const int bufSize = 65535; byte[] buf = new byte[bufSize]; int bytesRead = -1; while ((bytesRead = source.Read(buf, 0, bufSize)) > 0) target.Write(buf, 0, bytesRead); return target; } } }
using System.IO; namespace OfficeDevPnP.Core.Extensions { public static class StreamExtensions { public static MemoryStream ToMemoryStream(this Stream source) { var stream = source as MemoryStream; if (stream != null) return stream; var target = new MemoryStream(); const int bufSize = 65535; var buf = new byte[bufSize]; int bytesRead; while ((bytesRead = source.Read(buf, 0, bufSize)) > 0) target.Write(buf, 0, bytesRead); target.Position = 0; return target; } } }
Remove cert-test action to help diagnose issues in azure
using System; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Web.Mvc; using Microsoft.Azure; using SFA.DAS.EmployerUsers.WebClientComponents; namespace SFA.DAS.EmployerUsers.Web.Controllers { public class HomeController : ControllerBase { public ActionResult Index() { return View(); } public ActionResult CatchAll(string path) { return RedirectToAction("NotFound", "Error", new { path }); } [AuthoriseActiveUser] [Route("Login")] public ActionResult Login() { return RedirectToAction("Index"); } public ActionResult CertTest() { var certificatePath = string.Format(@"{0}\bin\DasIDPCert.pfx", AppDomain.CurrentDomain.BaseDirectory); var codeCert = new X509Certificate2(certificatePath, "idsrv3test"); X509Certificate2 storeCert; var store = new X509Store(StoreLocation.LocalMachine); store.Open(OpenFlags.ReadOnly); try { var thumbprint = CloudConfigurationManager.GetSetting("TokenCertificateThumbprint"); var certificates = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false); storeCert = certificates.Count > 0 ? certificates[0] : null; if (storeCert == null) { return Content($"Failed to load cert with thumbprint {thumbprint} from store"); } } finally { store.Close(); } var details = new StringBuilder(); details.AppendLine("Code cert"); details.AppendLine("-------------------------"); details.AppendLine($"FriendlyName: {codeCert.FriendlyName}"); details.AppendLine($"PublicKey: {codeCert.GetPublicKeyString()}"); details.AppendLine($"HasPrivateKey: {codeCert.HasPrivateKey}"); details.AppendLine($"Thumbprint: {codeCert.Thumbprint}"); details.AppendLine(); details.AppendLine("Store cert"); details.AppendLine("-------------------------"); details.AppendLine($"FriendlyName: {storeCert.FriendlyName}"); details.AppendLine($"PublicKey: {storeCert.GetPublicKeyString()}"); details.AppendLine($"HasPrivateKey: {storeCert.HasPrivateKey}"); details.AppendLine($"Thumbprint: {storeCert.Thumbprint}"); return Content(details.ToString(), "text/plain"); } } }
using System; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Web.Mvc; using Microsoft.Azure; using SFA.DAS.EmployerUsers.WebClientComponents; namespace SFA.DAS.EmployerUsers.Web.Controllers { public class HomeController : ControllerBase { public ActionResult Index() { return View(); } public ActionResult CatchAll(string path) { return RedirectToAction("NotFound", "Error", new { path }); } [AuthoriseActiveUser] [Route("Login")] public ActionResult Login() { return RedirectToAction("Index"); } } }
Add seed methods with test data
namespace App.Data.Migrations { using System.Data.Entity.Migrations; public sealed class Configuration : DbMigrationsConfiguration<AppDbContext> { public Configuration() { this.AutomaticMigrationsEnabled = true; this.AutomaticMigrationDataLossAllowed = true; // TODO: Remove in production } protected override void Seed(AppDbContext context) { } } }
namespace App.Data.Migrations { using System; using System.Collections.Generic; using System.Data.Entity.Migrations; using System.Linq; using Microsoft.AspNet.Identity; using App.Data.Models; public sealed class Configuration : DbMigrationsConfiguration<AppDbContext> { public Configuration() { this.AutomaticMigrationsEnabled = true; this.AutomaticMigrationDataLossAllowed = true; // TODO: Remove in production } protected override void Seed(AppDbContext context) { SeedUsers(context); SeedEntities(context); } private static void SeedUsers(AppDbContext context) { var passwordHash = new PasswordHasher(); var password = passwordHash.HashPassword("pass123"); var users = new List<User> { new User { UserName = "admin", Email = "admin@app.com", PasswordHash = password }, new User { UserName = "user", Email = "user@app.com", PasswordHash = password } }; foreach (var user in users) { context.Users.AddOrUpdate(u => u.UserName, user); } context.SaveChanges(); } private static void SeedEntities(AppDbContext context) { var posts = new List<Entity> { new Entity { Title = "Welcome", Content = "Hello world!", User = context.Users.FirstOrDefault(u => u.UserName == "admin"), DateCreated = new DateTime(2015, 09, 20) }, new Entity { Title = "Bye", Content = "Goodbye world!", User = context.Users.FirstOrDefault(u => u.UserName == "user"), DateCreated = new DateTime(2015, 09, 25) } }; foreach (var post in posts) { if (!context.Entities.Any(x => x.Title == post.Title)) { context.Entities.Add(post); } } } } }
Create server side API for single multiple answer question
using System.Collections.Generic; using Promact.Trappist.DomainModel.Models.Question; using System.Linq; using Promact.Trappist.DomainModel.DbContext; namespace Promact.Trappist.Repository.Questions { public class QuestionRepository : IQuestionRespository { private readonly TrappistDbContext _dbContext; public QuestionRepository(TrappistDbContext dbContext) { _dbContext = dbContext; } /// <summary> /// Get all questions /// </summary> /// <returns>Question list</returns> public List<SingleMultipleAnswerQuestion> GetAllQuestions() { var questions = _dbContext.SingleMultipleAnswerQuestion.ToList(); return questions; } /// <summary> /// Add single multiple answer question into SingleMultipleAnswerQuestion model /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <param name="singleMultipleAnswerQuestionOption"></param> public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption) { _dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion); _dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOption); _dbContext.SaveChanges(); } } }
using System.Collections.Generic; using Promact.Trappist.DomainModel.Models.Question; using System.Linq; using Promact.Trappist.DomainModel.DbContext; namespace Promact.Trappist.Repository.Questions { public class QuestionRepository : IQuestionRespository { private readonly TrappistDbContext _dbContext; public QuestionRepository(TrappistDbContext dbContext) { _dbContext = dbContext; } /// <summary> /// Get all questions /// </summary> /// <returns>Question list</returns> public List<SingleMultipleAnswerQuestion> GetAllQuestions() { var questions = _dbContext.SingleMultipleAnswerQuestion.ToList(); return questions; } /// <summary> /// Add single multiple answer question into SingleMultipleAnswerQuestion model /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <param name="singleMultipleAnswerQuestionOption"></param> public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption) { _dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion); _dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOption); _dbContext.SaveChanges(); } } }
Fix launch fleet command validator
using System; using Conreign.Contracts.Gameplay.Data; using Conreign.Core; using FluentValidation; namespace Conreign.Server.Gameplay.Validators { internal class LaunchFleetValidator : AbstractValidator<FleetData> { private readonly Map _map; private readonly Guid _senderId; public LaunchFleetValidator(Guid senderId, Map map) { _senderId = senderId; _map = map ?? throw new ArgumentNullException(nameof(map)); RuleFor(x => x.From) .NotEmpty() .Must(Exist) .Must(BelongToSender); RuleFor(x => x.To) .Must(Exist) .Must(NotBeTheSameAsFrom); RuleFor(x => x.Ships) .GreaterThan(0) .Must(BeEnoughShips); } private static bool NotBeTheSameAsFrom(FleetData fleet, int to) { return to != fleet.From; } private bool BeEnoughShips(FleetData fleet, int ships) { var availableShips = _map[fleet.From].Ships; return availableShips >= ships; } private bool Exist(int coordinate) { return _map.ContainsPlanet(coordinate); } private bool BelongToSender(int coordinate) { return _map[coordinate].OwnerId == _senderId; } } }
using System; using Conreign.Contracts.Gameplay.Data; using Conreign.Core; using FluentValidation; namespace Conreign.Server.Gameplay.Validators { internal class LaunchFleetValidator : AbstractValidator<FleetData> { private readonly Map _map; private readonly Guid _senderId; public LaunchFleetValidator(Guid senderId, Map map) { _senderId = senderId; _map = map ?? throw new ArgumentNullException(nameof(map)); RuleFor(x => x.From) .Must(Exist) .Must(BelongToSender); RuleFor(x => x.To) .Must(Exist) .Must(NotBeTheSameAsFrom); RuleFor(x => x.Ships) .GreaterThan(0) .Must(BeEnoughShips); } private static bool NotBeTheSameAsFrom(FleetData fleet, int to) { return to != fleet.From; } private bool BeEnoughShips(FleetData fleet, int ships) { var availableShips = _map[fleet.From].Ships; return availableShips >= ships; } private bool Exist(int coordinate) { return _map.ContainsPlanet(coordinate); } private bool BelongToSender(int coordinate) { return _map[coordinate].OwnerId == _senderId; } } }
Revert "make Doors list private, add getter"
using System.Collections.Generic; using UnityEngine; public class RoomDetails : MonoBehaviour { public int HorizontalSize; public int VerticalSize; private List<GameObject> Doors; void Start() { int doorIndex = 0; for(int i = 0; i < transform.childCount; i++) { GameObject child = transform.GetChild(i).gameObject; if (child.tag == "door") { Doors.Add(child); child.GetComponent<DoorDetails>().ID = doorIndex; doorIndex++; } } } public List<GameObject> GetDoors() { return Doors; } }
using System.Collections.Generic; using UnityEngine; public class RoomDetails : MonoBehaviour { public int HorizontalSize; public int VerticalSize; public List<GameObject> Doors; void Start() { int doorIndex = 0; for(int i = 0; i < transform.childCount; i++) { GameObject child = transform.GetChild(i).gameObject; if (child.tag == "door") { Doors.Add(child); child.GetComponent<DoorDetails>().ID = doorIndex; doorIndex++; } } } }
Add back missing OnHelpInvoked implementation which was removed
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using EntryPoint; using EntryPointTests.Helpers; namespace EntryPointTests.AppOptionModels { public class HelpWithRequiredArgsModel : BaseCliArguments { public HelpWithRequiredArgsModel() : base("APP_NAME") { } [Required] [OptionParameter( LongName = "param-required", ShortName = 'r')] [Help("PARAM_REQUIRED_HELP_STRING")] public int ParamRequired { get; set; } [OptionParameter(LongName = "param-2", ShortName = 'o')] [Help("PARAM_OPTIONAL_HELP_STRING")] public string StringOption { get; set; } [Required] [Operand(1)] public string OneOperand { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using EntryPoint; using EntryPointTests.Helpers; namespace EntryPointTests.AppOptionModels { public class HelpWithRequiredArgsModel : BaseCliArguments { public HelpWithRequiredArgsModel() : base("APP_NAME") { } [Required] [OptionParameter( LongName = "param-required", ShortName = 'r')] [Help("PARAM_REQUIRED_HELP_STRING")] public int ParamRequired { get; set; } [OptionParameter(LongName = "param-2", ShortName = 'o')] [Help("PARAM_OPTIONAL_HELP_STRING")] public string StringOption { get; set; } [Required] [Operand(1)] public string OneOperand { get; set; } public override void OnHelpInvoked(string helpText) { throw new HelpTriggeredSuccessException(); } } }
Change link to point to recruit dashboard
@model SFA.DAS.EmployerAccounts.Web.ViewModels.VacancyViewModel <section class="dashboard-section"> <h2 class="section-heading heading-large"> Your apprenticeship advert </h2> <p>You have created a vacancy for your apprenticeship.</p> <table class="responsive"> <tr> <th scope="row" class="tw-35"> Title </th> <td class="tw-65"> @(Model?.Title) </td> </tr> <tr> <th scope="row" class="tw-35"> Closing date </th> <td class="tw-65"> @(Model.ClosingDateText) </td> </tr> <tr> <th scope="row"> Status </th> <td> <strong class="govuk-tag govuk-tag--inactive">PENDING REVIEW</strong> </td> </tr> <tr> <th scope="row" class="tw-35"> Applications </th> <td class="tw-65"> <a href="/" class="govuk-link"> No applications yet</a> </td> </tr> </table> <p> <a href="@Model.ManageVacancyUrl" class="govuk-link">Go to your vacancy dashboard</a> </p> </section>
@model SFA.DAS.EmployerAccounts.Web.ViewModels.VacancyViewModel <section class="dashboard-section"> <h2 class="section-heading heading-large"> Your apprenticeship advert </h2> <p>You have created a vacancy for your apprenticeship.</p> <table class="responsive"> <tr> <th scope="row" class="tw-35"> Title </th> <td class="tw-65"> @(Model?.Title) </td> </tr> <tr> <th scope="row" class="tw-35"> Closing date </th> <td class="tw-65"> @(Model.ClosingDateText) </td> </tr> <tr> <th scope="row"> Status </th> <td> <strong class="govuk-tag govuk-tag--inactive">PENDING REVIEW</strong> </td> </tr> <tr> <th scope="row" class="tw-35"> Applications </th> <td class="tw-65"> <a href="/" class="govuk-link"> No applications yet</a> </td> </tr> </table> <p> <a href="@Url.EmployerRecruitAction()" class="govuk-link">Go to your vacancy dashboard</a> </p> </section>
Create hangfire sql objects extension method for ef core migration builder
using Bit.Data.Implementations; using System; namespace Microsoft.EntityFrameworkCore.Migrations { public static class MigrationBuilderExtensions { /// <summary> /// <seealso cref="SqlServerJsonLogStore"/> /// </summary> public static void CreateSqlServerJsonLogStoreTable(this MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Logs", columns: table => new { Id = table.Column<Guid>(nullable: false, defaultValueSql: "NEWSEQUENTIALID()"), Contents = table.Column<string>(nullable: false), Date = table.Column<DateTimeOffset>(nullable: false, defaultValueSql: "GETDATE()") }, constraints: table => { table.PrimaryKey("PK_Logs", x => x.Id); }); } } }
using Bit.Data.Implementations; using System; using System.IO; using System.Reflection; namespace Microsoft.EntityFrameworkCore.Migrations { public static class MigrationBuilderExtensions { /// <summary> /// <seealso cref="SqlServerJsonLogStore"/> /// </summary> public static void CreateSqlServerJsonLogStoreTable(this MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Logs", columns: table => new { Id = table.Column<Guid>(nullable: false, defaultValueSql: "NEWSEQUENTIALID()"), Contents = table.Column<string>(nullable: false), Date = table.Column<DateTimeOffset>(nullable: false, defaultValueSql: "GETDATE()") }, constraints: table => { table.PrimaryKey("PK_Logs", x => x.Id); }); } public static void CreateHangfireSqlObjects(this MigrationBuilder migrationBuilder) { using (Stream hangfireJobsDatabaseStream = Assembly.Load("Bit.Hangfire").GetManifestResourceStream("Bit.Hangfire.Hangfire-Database-Script.sql")) { using (StreamReader reader = new StreamReader(hangfireJobsDatabaseStream)) { string sql = reader.ReadToEnd(); migrationBuilder.Sql(sql); } } } } }
Update file version to 3.0.0.0
using System; namespace Xamarin.Forms.GoogleMaps.Internals { internal class ProductInformation { public const string Author = "amay077"; public const string Name = "Xamarin.Forms.GoogleMaps"; public const string Copyright = "Copyright © amay077. 2016 - 2018"; public const string Trademark = ""; public const string Version = "2.3.0.1"; } }
using System; namespace Xamarin.Forms.GoogleMaps.Internals { internal class ProductInformation { public const string Author = "amay077"; public const string Name = "Xamarin.Forms.GoogleMaps"; public const string Copyright = "Copyright © amay077. 2016 - 2018"; public const string Trademark = ""; public const string Version = "3.0.0.0"; } }
Store Tetris DS player name as string.
using System; using System.Collections.Generic; using System.Linq; using System.Web; using GamestatsBase; namespace Sample.tetrisds { /// <summary> /// Summary description for store /// </summary> public class store : GamestatsHandler { public store() : base("Wo3vqrDoL56sAdveYeC1", 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, "tetrisds", GamestatsRequestVersions.Version1, GamestatsResponseVersions.Version1) { } public override void ProcessGamestatsRequest(byte[] request, System.IO.MemoryStream response, string url, int pid, HttpContext context, GamestatsSession session) { byte[] nameBytes = FromUrlSafeBase64String(context.Request.QueryString["name"]); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using GamestatsBase; namespace Sample.tetrisds { /// <summary> /// Summary description for store /// </summary> public class store : GamestatsHandler { public store() : base("Wo3vqrDoL56sAdveYeC1", 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, "tetrisds", GamestatsRequestVersions.Version1, GamestatsResponseVersions.Version1) { } public override void ProcessGamestatsRequest(byte[] request, System.IO.MemoryStream response, string url, int pid, HttpContext context, GamestatsSession session) { byte[] nameBytes = FromUrlSafeBase64String(context.Request.QueryString["name"]); char[] nameChars = new char[nameBytes.Length >> 1]; Buffer.BlockCopy(nameBytes, 0, nameChars, 0, nameBytes.Length); String name = new String(nameChars); } } }