Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Use ticks instead of milliseconds for time calculation
using System; using System.Diagnostics; namespace OpenSage { public sealed class GameTimer : IDisposable { private readonly Stopwatch _stopwatch; private double _startTime; private double _lastUpdate; public GameTime CurrentGameTime { get; private set; } public GameTimer() { _stopwatch = new Stopwatch(); } private double GetTimeNow() => _stopwatch.ElapsedMilliseconds; public void Start() { _stopwatch.Start(); Reset(); } public void Update() { var now = GetTimeNow(); var deltaTime = now - _lastUpdate; _lastUpdate = now; CurrentGameTime = new GameTime( TimeSpan.FromMilliseconds(now - _startTime), TimeSpan.FromMilliseconds(deltaTime)); } public void Reset() { _lastUpdate = GetTimeNow(); _startTime = _lastUpdate; } public void Dispose() { _stopwatch.Stop(); } } public readonly struct GameTime { public readonly TimeSpan TotalGameTime; public readonly TimeSpan ElapsedGameTime; public GameTime(in TimeSpan totalGameTime, in TimeSpan elapsedGameTime) { TotalGameTime = totalGameTime; ElapsedGameTime = elapsedGameTime; } } }
using System; using System.Diagnostics; namespace OpenSage { public sealed class GameTimer : IDisposable { private readonly Stopwatch _stopwatch; private long _startTime; private long _lastUpdate; public GameTime CurrentGameTime { get; private set; } public GameTimer() { _stopwatch = new Stopwatch(); } private long GetTimeNow() => _stopwatch.ElapsedTicks; public void Start() { _stopwatch.Start(); Reset(); } public void Update() { var now = GetTimeNow(); var deltaTime = now - _lastUpdate; _lastUpdate = now; CurrentGameTime = new GameTime( TimeSpan.FromTicks(now - _startTime), TimeSpan.FromTicks(deltaTime)); } public void Reset() { _lastUpdate = GetTimeNow(); _startTime = _lastUpdate; } public void Dispose() { _stopwatch.Stop(); } } public readonly struct GameTime { public readonly TimeSpan TotalGameTime; public readonly TimeSpan ElapsedGameTime; public GameTime(in TimeSpan totalGameTime, in TimeSpan elapsedGameTime) { TotalGameTime = totalGameTime; ElapsedGameTime = elapsedGameTime; } } }
Comment out unused variables for now
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Game.Beatmaps; using osu.Game.Rulesets.Catch.Objects; using System.Collections.Generic; using System; using osu.Game.Rulesets.Objects.Types; using osu.Game.Rulesets.Beatmaps; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Osu.UI; namespace osu.Game.Rulesets.Catch.Beatmaps { internal class CatchBeatmapConverter : BeatmapConverter<CatchBaseHit> { protected override IEnumerable<Type> ValidConversionTypes { get; } = new[] { typeof(IHasXPosition) }; protected override IEnumerable<CatchBaseHit> ConvertHitObject(HitObject obj, Beatmap beatmap) { var distanceData = obj as IHasDistance; var repeatsData = obj as IHasRepeats; var endTimeData = obj as IHasEndTime; var curveData = obj as IHasCurve; yield return new Fruit { StartTime = obj.StartTime, Position = ((IHasXPosition)obj).X / OsuPlayfield.BASE_SIZE.X }; } } }
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Game.Beatmaps; using osu.Game.Rulesets.Catch.Objects; using System.Collections.Generic; using System; using osu.Game.Rulesets.Objects.Types; using osu.Game.Rulesets.Beatmaps; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Osu.UI; namespace osu.Game.Rulesets.Catch.Beatmaps { internal class CatchBeatmapConverter : BeatmapConverter<CatchBaseHit> { protected override IEnumerable<Type> ValidConversionTypes { get; } = new[] { typeof(IHasXPosition) }; protected override IEnumerable<CatchBaseHit> ConvertHitObject(HitObject obj, Beatmap beatmap) { /*var distanceData = obj as IHasDistance; var repeatsData = obj as IHasRepeats; var endTimeData = obj as IHasEndTime; var curveData = obj as IHasCurve;*/ yield return new Fruit { StartTime = obj.StartTime, Position = ((IHasXPosition)obj).X / OsuPlayfield.BASE_SIZE.X }; } } }
Add progress example to command line program
using System; using ArduinoUploader; namespace ArduinoSketchUploader { /// <summary> /// The ArduinoSketchUploader can upload a compiled (Intel) HEX file directly to an attached Arduino. /// </summary> internal class Program { private enum StatusCodes { Success, ArduinoUploaderException, GeneralRuntimeException } private static void Main(string[] args) { var commandLineOptions = new CommandLineOptions(); if (!CommandLine.Parser.Default.ParseArguments(args, commandLineOptions)) return; var options = new ArduinoSketchUploaderOptions { PortName = commandLineOptions.PortName, FileName = commandLineOptions.FileName, ArduinoModel = commandLineOptions.ArduinoModel }; var uploader = new ArduinoUploader.ArduinoSketchUploader(options); try { uploader.UploadSketch(); Environment.Exit((int)StatusCodes.Success); } catch (ArduinoUploaderException) { Environment.Exit((int)StatusCodes.ArduinoUploaderException); } catch (Exception ex) { UploaderLogger.LogError(string.Format("Unexpected exception: {0}!", ex.Message), ex); Environment.Exit((int)StatusCodes.GeneralRuntimeException); } } } }
using System; using ArduinoUploader; using NLog; namespace ArduinoSketchUploader { /// <summary> /// The ArduinoSketchUploader can upload a compiled (Intel) HEX file directly to an attached Arduino. /// </summary> internal class Program { private static readonly Logger logger = LogManager.GetLogger("ArduinoSketchUploader"); private enum StatusCodes { Success, ArduinoUploaderException, GeneralRuntimeException } private static void Main(string[] args) { var commandLineOptions = new CommandLineOptions(); if (!CommandLine.Parser.Default.ParseArguments(args, commandLineOptions)) return; var options = new ArduinoSketchUploaderOptions { PortName = commandLineOptions.PortName, FileName = commandLineOptions.FileName, ArduinoModel = commandLineOptions.ArduinoModel }; var progress = new Progress<double>(p => logger.Info("{0:F1}%", p * 100)); var uploader = new ArduinoUploader.ArduinoSketchUploader(options, progress); try { uploader.UploadSketch(); Environment.Exit((int)StatusCodes.Success); } catch (ArduinoUploaderException) { Environment.Exit((int)StatusCodes.ArduinoUploaderException); } catch (Exception ex) { UploaderLogger.LogError(string.Format("Unexpected exception: {0}!", ex.Message), ex); Environment.Exit((int)StatusCodes.GeneralRuntimeException); } } } }
Add Dequeue<T>(int count) for dequeue specified items in Queue<T> by count when enumberate
using System; using System.Collections.Generic; using System.Net; using System.Threading; using System.Threading.Tasks; namespace TirkxDownloader.Framework { public static class Extension { public static async Task<HttpWebResponse> GetResponseAsync(this HttpWebRequest request, CancellationToken ct) { using (ct.Register(() => request.Abort(), useSynchronizationContext: false)) { try { var response = await request.GetResponseAsync(); ct.ThrowIfCancellationRequested(); return (HttpWebResponse)response; } catch (WebException webEx) { if (ct.IsCancellationRequested) { throw new OperationCanceledException(webEx.Message, webEx, ct); } throw; } } } } }
using System; using System.Collections.Generic; using System.Net; using System.Threading; using System.Threading.Tasks; namespace TirkxDownloader.Framework { public static class Extension { public static async Task<HttpWebResponse> GetResponseAsync(this HttpWebRequest request, CancellationToken ct) { using (ct.Register(() => request.Abort(), useSynchronizationContext: false)) { try { var response = await request.GetResponseAsync(); ct.ThrowIfCancellationRequested(); return (HttpWebResponse)response; } catch (WebException webEx) { if (ct.IsCancellationRequested) { throw new OperationCanceledException(webEx.Message, webEx, ct); } throw; } } } public static T[] Dequeue<T>(this Queue<T> queue, int count) { T[] list = new T[count]; for (int i = 0; i < count; i++) { list[i] = queue.Dequeue(); } return list; } } }
Add change handling for effects section
// 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.Bindables; using osu.Game.Beatmaps.ControlPoints; using osu.Game.Graphics.UserInterfaceV2; namespace osu.Game.Screens.Edit.Timing { internal class EffectSection : Section<EffectControlPoint> { private LabelledSwitchButton kiai; private LabelledSwitchButton omitBarLine; [BackgroundDependencyLoader] private void load() { Flow.AddRange(new[] { kiai = new LabelledSwitchButton { Label = "Kiai Time" }, omitBarLine = new LabelledSwitchButton { Label = "Skip Bar Line" }, }); } protected override void OnControlPointChanged(ValueChangedEvent<EffectControlPoint> point) { if (point.NewValue != null) { kiai.Current = point.NewValue.KiaiModeBindable; omitBarLine.Current = point.NewValue.OmitFirstBarLineBindable; } } protected override EffectControlPoint CreatePoint() { var reference = Beatmap.Value.Beatmap.ControlPointInfo.EffectPointAt(SelectedGroup.Value.Time); return new EffectControlPoint { KiaiMode = reference.KiaiMode, OmitFirstBarLine = reference.OmitFirstBarLine }; } } }
// 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.Bindables; using osu.Game.Beatmaps.ControlPoints; using osu.Game.Graphics.UserInterfaceV2; namespace osu.Game.Screens.Edit.Timing { internal class EffectSection : Section<EffectControlPoint> { private LabelledSwitchButton kiai; private LabelledSwitchButton omitBarLine; [BackgroundDependencyLoader] private void load() { Flow.AddRange(new[] { kiai = new LabelledSwitchButton { Label = "Kiai Time" }, omitBarLine = new LabelledSwitchButton { Label = "Skip Bar Line" }, }); } protected override void OnControlPointChanged(ValueChangedEvent<EffectControlPoint> point) { if (point.NewValue != null) { kiai.Current = point.NewValue.KiaiModeBindable; kiai.Current.BindValueChanged(_ => ChangeHandler?.SaveState()); omitBarLine.Current = point.NewValue.OmitFirstBarLineBindable; omitBarLine.Current.BindValueChanged(_ => ChangeHandler?.SaveState()); } } protected override EffectControlPoint CreatePoint() { var reference = Beatmap.Value.Beatmap.ControlPointInfo.EffectPointAt(SelectedGroup.Value.Time); return new EffectControlPoint { KiaiMode = reference.KiaiMode, OmitFirstBarLine = reference.OmitFirstBarLine }; } } }
Use canned document service by default.
namespace WorkoutWotch.UI.Android { using Services.ExerciseDocument; using WorkoutWotch.Services.Contracts.Audio; using WorkoutWotch.Services.Contracts.ExerciseDocument; using WorkoutWotch.Services.Contracts.Speech; using WorkoutWotch.Services.Android.Audio; using WorkoutWotch.Services.Android.Speech; using Services.Android.ExerciseDocument; public sealed class AndroidCompositionRoot : CompositionRoot { private readonly MainActivity mainActivity; public AndroidCompositionRoot(MainActivity mainActivity) { this.mainActivity = mainActivity; } protected override IAudioService CreateAudioService() => new AudioService(); protected override IExerciseDocumentService CreateExerciseDocumentService() => // just used canned data - useful for getting you up and running quickly //new CannedExerciseDocumentService(); // comment the above lines and uncomment this line if you want to use an iCloud-based document service new GoogleDriveExerciseDocumentService( this.loggerService.Value, this.mainActivity); protected override ISpeechService CreateSpeechService() => new SpeechService(); } }
namespace WorkoutWotch.UI.Android { using Services.ExerciseDocument; using WorkoutWotch.Services.Contracts.Audio; using WorkoutWotch.Services.Contracts.ExerciseDocument; using WorkoutWotch.Services.Contracts.Speech; using WorkoutWotch.Services.Android.Audio; using WorkoutWotch.Services.Android.Speech; using Services.Android.ExerciseDocument; public sealed class AndroidCompositionRoot : CompositionRoot { private readonly MainActivity mainActivity; public AndroidCompositionRoot(MainActivity mainActivity) { this.mainActivity = mainActivity; } protected override IAudioService CreateAudioService() => new AudioService(); protected override IExerciseDocumentService CreateExerciseDocumentService() => // just used canned data - useful for getting you up and running quickly new CannedExerciseDocumentService(); // comment the above lines and uncomment this line if you want to use an iCloud-based document service //new GoogleDriveExerciseDocumentService( // this.loggerService.Value, // this.mainActivity); protected override ISpeechService CreateSpeechService() => new SpeechService(); } }
Move TokenEnvironmentVariable to constant string
using System; namespace AppHarbor.Commands { public class LoginCommand : ICommand { private readonly AccessTokenFetcher _accessTokenFetcher; private readonly EnvironmentVariableConfiguration _environmentVariableConfiguration; public LoginCommand(AccessTokenFetcher accessTokenFetcher, EnvironmentVariableConfiguration environmentVariableConfiguration) { _accessTokenFetcher = accessTokenFetcher; _environmentVariableConfiguration = environmentVariableConfiguration; } public void Execute(string[] arguments) { if (_environmentVariableConfiguration.Get("AppHarborToken", EnvironmentVariableTarget.User) != null) { throw new CommandException("You're already logged in"); } Console.WriteLine("Username:"); var username = Console.ReadLine(); Console.WriteLine("Password:"); var password = Console.ReadLine(); } } }
using System; namespace AppHarbor.Commands { public class LoginCommand : ICommand { private const string TokenEnvironmentVariable = "AppHarborToken"; private readonly AccessTokenFetcher _accessTokenFetcher; private readonly EnvironmentVariableConfiguration _environmentVariableConfiguration; public LoginCommand(AccessTokenFetcher accessTokenFetcher, EnvironmentVariableConfiguration environmentVariableConfiguration) { _accessTokenFetcher = accessTokenFetcher; _environmentVariableConfiguration = environmentVariableConfiguration; } public void Execute(string[] arguments) { if (_environmentVariableConfiguration.Get(TokenEnvironmentVariable, EnvironmentVariableTarget.User) != null) { throw new CommandException("You're already logged in"); } Console.WriteLine("Username:"); var username = Console.ReadLine(); Console.WriteLine("Password:"); var password = Console.ReadLine(); } } }
Add more tests to TestSuite
using Arkivverket.Arkade.Core; using Arkivverket.Arkade.Tests; using FluentAssertions; using Xunit; namespace Arkivverket.Arkade.Test.Core { public class TestSuiteTest { [Fact] public void ShouldReturnOneError() { var testSuite = new TestSuite(); var testRun = new TestRun("test with error", TestType.Content); testRun.Add(new TestResult(ResultType.Error, new Location(""), "feil")); testSuite.AddTestRun(testRun); testSuite.FindNumberOfErrors().Should().Be(1); } } }
using Arkivverket.Arkade.Core; using Arkivverket.Arkade.Tests; using FluentAssertions; using Xunit; namespace Arkivverket.Arkade.Test.Core { public class TestSuiteTest { private readonly TestResult _testResultWithError = new TestResult(ResultType.Error, new Location(""), "feil"); private readonly TestResult _testResultWithSuccess = new TestResult(ResultType.Success, new Location(""), "feil"); [Fact] public void FindNumberOfErrorsShouldReturnOneError() { var testSuite = new TestSuite(); var testRun = new TestRun("test with error", TestType.Content); testRun.Add(new TestResult(ResultType.Error, null, "feil")); testSuite.AddTestRun(testRun); testSuite.FindNumberOfErrors().Should().Be(1); } [Fact] public void FindNumberOfErrorsShouldReturnTwoErrors() { TestSuite testSuite = CreateTestSuite(_testResultWithError, _testResultWithError, _testResultWithSuccess); testSuite.FindNumberOfErrors().Should().Be(2); } [Fact] public void FindNumberOfErrorsShouldZeroErrorsWhenNoTestResults() { TestSuite testSuite = CreateTestSuite(null); testSuite.FindNumberOfErrors().Should().Be(0); } [Fact] public void FindNumberOfErrorsShouldZeroErrorsWhenOnlySuccessResults() { TestSuite testSuite = CreateTestSuite(_testResultWithSuccess, _testResultWithSuccess); testSuite.FindNumberOfErrors().Should().Be(0); } private static TestSuite CreateTestSuite(params TestResult[] testResults) { var testSuite = new TestSuite(); var testRun = new TestRun("test with error", TestType.Content); if (testResults != null) { foreach (var testResult in testResults) { testRun.Add(testResult); } } testSuite.AddTestRun(testRun); return testSuite; } } }
Add UserIDFromDeployedItem and UserIDsFromBuildingPrivilege - Courtesy of @strykes aka Reneb
using System; using System.Collections.Generic; using System.Linq; using Oxide.Core.Libraries; using Oxide.Core.Plugins; namespace Oxide.Rust.Libraries { /// <summary> /// A library containing utility shortcut functions for rust /// </summary> public class Rust : Library { /// <summary> /// Returns if this library should be loaded into the global namespace /// </summary> public override bool IsGlobal { get { return false; } } /// <summary> /// Returns the UserID for the specified connection as a string /// </summary> /// <param name="connection"></param> /// <returns></returns> [LibraryFunction("UserIDFromConnection")] public string UserIDFromConnection(Network.Connection connection) { return connection.userid.ToString(); } /// <summary> /// Returns the UserID for the specified player as a string /// </summary> /// <param name="connection"></param> /// <returns></returns> [LibraryFunction("UserIDFromPlayer")] public string UserIDFromPlayer(BasePlayer player) { return player.userID.ToString(); } } }
using System; using System.Collections.Generic; using System.Linq; using Oxide.Core.Libraries; using Oxide.Core.Plugins; namespace Oxide.Rust.Libraries { /// <summary> /// A library containing utility shortcut functions for rust /// </summary> public class Rust : Library { /// <summary> /// Returns if this library should be loaded into the global namespace /// </summary> public override bool IsGlobal { get { return false; } } /// <summary> /// Returns the UserID for the specified connection as a string /// </summary> /// <param name="connection"></param> /// <returns></returns> [LibraryFunction("UserIDFromConnection")] public string UserIDFromConnection(Network.Connection connection) { return connection.userid.ToString(); } /// <summary> /// Returns the UserIDs for the specified building privilege as an array /// </summary> /// <param name="privilege"></param> /// <returns></returns> [LibraryFunction("UserIDsFromBuildingPrivilege")] public Array UserIDsFromBuildingPrivlidge(BuildingPrivlidge buildingpriv) { List<string> list = new List<string>(); foreach (ProtoBuf.PlayerNameID eid in buildingpriv.authorizedPlayers) { list.Add(eid.userid.ToString()); } return list.ToArray(); } /// <summary> /// Returns the UserID for the specified deployed item as a string /// </summary> /// <param name="item"></param> /// <returns></returns> [LibraryFunction("UserIDFromDeployedItem")] public string UserIDFromDeployedItem(DeployedItem DeployedItem) { return DeployedItem.deployerUserID.ToString(); } /// <summary> /// Returns the UserID for the specified player as a string /// </summary> /// <param name="connection"></param> /// <returns></returns> [LibraryFunction("UserIDFromPlayer")] public string UserIDFromPlayer(BasePlayer player) { return player.userID.ToString(); } } }
Add shortcut of canvas width scaling by up/down arrow key
using UniRx; using UnityEngine; using UnityEngine.UI; public class CanvasWidthScalePresenter : MonoBehaviour { [SerializeField] CanvasEvents canvasEvents; [SerializeField] Slider canvasWidthScaleController; NotesEditorModel model; void Awake() { model = NotesEditorModel.Instance; model.OnLoadedMusicObservable.First().Subscribe(_ => Init()); } void Init() { model.CanvasWidth = canvasEvents.MouseScrollWheelObservable .Where(_ => KeyInput.CtrlKey()) .Select(delta => model.CanvasWidth.Value * (1 + delta)) .Select(x => x / (model.Audio.clip.samples / 100f)) .Select(x => Mathf.Clamp(x, 0.1f, 2f)) .Merge(canvasWidthScaleController.OnValueChangedAsObservable() .DistinctUntilChanged()) .Select(x => model.Audio.clip.samples / 100f * x) .ToReactiveProperty(); } }
using UniRx; using UniRx.Triggers; using UnityEngine; using UnityEngine.UI; public class CanvasWidthScalePresenter : MonoBehaviour { [SerializeField] CanvasEvents canvasEvents; [SerializeField] Slider canvasWidthScaleController; NotesEditorModel model; void Awake() { model = NotesEditorModel.Instance; model.OnLoadedMusicObservable.First().Subscribe(_ => Init()); } void Init() { model.CanvasWidth = canvasEvents.MouseScrollWheelObservable .Where(_ => KeyInput.CtrlKey()) .Merge(this.UpdateAsObservable().Where(_ => Input.GetKey(KeyCode.UpArrow)).Select(_ => 0.1f)) .Merge(this.UpdateAsObservable().Where(_ => Input.GetKey(KeyCode.DownArrow)).Select(_ => -0.1f)) .Select(delta => model.CanvasWidth.Value * (1 + delta)) .Select(x => x / (model.Audio.clip.samples / 100f)) .Select(x => Mathf.Clamp(x, 0.1f, 2f)) .Merge(canvasWidthScaleController.OnValueChangedAsObservable() .DistinctUntilChanged()) .Select(x => model.Audio.clip.samples / 100f * x) .ToReactiveProperty(); } }
Add space for readability in the exception messages.
namespace SqlStreamStore.Infrastructure { using SqlStreamStore.Imports.Ensure.That; internal static class EnsureThatExtensions { internal static Param<string> DoesNotStartWith(this Param<string> param, string s) { if (!Ensure.IsActive) { return param; } if (param.Value.StartsWith(s)) { throw ExceptionFactory.CreateForParamValidation(param, $"Must not start with{s}"); } return param; } } }
namespace SqlStreamStore.Infrastructure { using SqlStreamStore.Imports.Ensure.That; internal static class EnsureThatExtensions { internal static Param<string> DoesNotStartWith(this Param<string> param, string s) { if (!Ensure.IsActive) { return param; } if (param.Value.StartsWith(s)) { throw ExceptionFactory.CreateForParamValidation(param, $"Must not start with {s}"); } return param; } } }
Work around problem in casting int to double.
// ----------------------------------------------------------------------- // <copyright file="GridSplitterStyle.cs" company="Steven Kirk"> // Copyright 2014 MIT Licence. See licence.md for more information. // </copyright> // ----------------------------------------------------------------------- namespace Perspex.Themes.Default { using System.Linq; using Perspex.Controls; using Perspex.Controls.Presenters; using Perspex.Media; using Perspex.Styling; public class GridSplitterStyle : Styles { public GridSplitterStyle() { this.AddRange(new[] { new Style(x => x.OfType<GridSplitter>()) { Setters = new[] { new Setter(GridSplitter.TemplateProperty, ControlTemplate.Create<GridSplitter>(this.Template)), new Setter(GridSplitter.WidthProperty, 4), }, }, }); } private Control Template(GridSplitter control) { Border border = new Border { [~Border.BackgroundProperty] = control[~GridSplitter.BackgroundProperty], }; return border; } } }
// ----------------------------------------------------------------------- // <copyright file="GridSplitterStyle.cs" company="Steven Kirk"> // Copyright 2014 MIT Licence. See licence.md for more information. // </copyright> // ----------------------------------------------------------------------- namespace Perspex.Themes.Default { using Perspex.Controls; using Perspex.Styling; using System.Linq; public class GridSplitterStyle : Styles { public GridSplitterStyle() { this.AddRange(new[] { new Style(x => x.OfType<GridSplitter>()) { Setters = new[] { new Setter(GridSplitter.TemplateProperty, ControlTemplate.Create<GridSplitter>(this.Template)), new Setter(GridSplitter.WidthProperty, 4.0), }, }, }); } private Control Template(GridSplitter control) { Border border = new Border { [~Border.BackgroundProperty] = control[~GridSplitter.BackgroundProperty], }; return border; } } }
Add sample path to the lookup names
// 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.Collections.Generic; using osu.Framework.Graphics; using osu.Game.Audio; using osu.Game.Storyboards.Drawables; namespace osu.Game.Storyboards { public class StoryboardSampleInfo : IStoryboardElement, ISampleInfo { public string Path { get; } public bool IsDrawable => true; public double StartTime { get; } public int Volume { get; } public StoryboardSampleInfo(string path, double time, int volume) { Path = path; StartTime = time; Volume = volume; } public Drawable CreateDrawable() => new DrawableStoryboardSample(this); } }
// 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.Collections.Generic; using osu.Framework.Graphics; using osu.Game.Audio; using osu.Game.Storyboards.Drawables; namespace osu.Game.Storyboards { public class StoryboardSampleInfo : IStoryboardElement, ISampleInfo { public string Path { get; } public bool IsDrawable => true; public double StartTime { get; } public int Volume { get; } public IEnumerable<string> LookupNames => new[] { // Try first with the full name, then attempt with no path Path, System.IO.Path.ChangeExtension(Path, null), }; public StoryboardSampleInfo(string path, double time, int volume) { Path = path; StartTime = time; Volume = volume; } public Drawable CreateDrawable() => new DrawableStoryboardSample(this); } }
Revert "Only test that the program compiles until we can parse top-level arrays"
using System; using System.IO; namespace test { class Program { static void Main(string[] args) { var path = args[0]; // var json = File.ReadAllText(path); // var qt = QuickType.TopLevel.FromJson(json); } } }
using System; using System.IO; namespace test { class Program { static void Main(string[] args) { var path = args[0]; var json = File.ReadAllText(path); var qt = QuickType.TopLevel.FromJson(json); } } }
Change AssemblyCopyright from ACAXLabs to ACAExpress
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("LibSlyBroadcast")] [assembly: AssemblyProduct("LibSlyBroadcast")] [assembly: AssemblyCopyright("Copyright © ACAXLabs 2016")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("LibSlyBroadcast")] [assembly: AssemblyProduct("LibSlyBroadcast")] [assembly: AssemblyCopyright("Copyright © ACAExpress.com, Inc 2016")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
Return the values of variables in the program as well as variables in the query
using LogicalShift.Reason.Api; using LogicalShift.Reason.Unification; using System; using System.Collections.Generic; using System.Linq; namespace LogicalShift.Reason { /// <summary> /// Helper methods for performing unification /// </summary> public static class BasicUnification { /// <summary> /// Returns the possible ways that a query term can unify with a program term /// </summary> public static IBindings Unify(this ILiteral query, ILiteral program, IBindings bindings = null) { var simpleUnifier = new SimpleUnifier(); var freeVariables = new HashSet<ILiteral>(); // Run the unifier try { var queryFreeVars = simpleUnifier.QueryUnifier.Compile(query, bindings); simpleUnifier.PrepareToRunProgram(); simpleUnifier.ProgramUnifier.Compile(program, bindings); freeVariables.UnionWith(queryFreeVars); } catch (InvalidOperationException) { // No results // TODO: really should report failure in a better way return null; } // Retrieve the unified value for the program var result = simpleUnifier.UnifiedValue(query.UnificationKey ?? query); // If the result was valid, return as the one value from this function if (result != null) { var variableBindings = freeVariables.ToDictionary(variable => variable, variable => simpleUnifier.UnifiedValue(variable)); return new BasicBinding(result, variableBindings); } else { return null; } } } }
using LogicalShift.Reason.Api; using LogicalShift.Reason.Unification; using System; using System.Collections.Generic; using System.Linq; namespace LogicalShift.Reason { /// <summary> /// Helper methods for performing unification /// </summary> public static class BasicUnification { /// <summary> /// Returns the possible ways that a query term can unify with a program term /// </summary> public static IBindings Unify(this ILiteral query, ILiteral program, IBindings bindings = null) { var simpleUnifier = new SimpleUnifier(); var freeVariables = new HashSet<ILiteral>(); // Run the unifier try { var queryFreeVars = simpleUnifier.QueryUnifier.Compile(query, bindings); simpleUnifier.PrepareToRunProgram(); var programFreeVars = simpleUnifier.ProgramUnifier.Compile(program, bindings); freeVariables.UnionWith(queryFreeVars); freeVariables.UnionWith(programFreeVars); } catch (InvalidOperationException) { // No results // TODO: really should report failure in a better way return null; } // Retrieve the unified value for the program var result = simpleUnifier.UnifiedValue(query.UnificationKey ?? query); // If the result was valid, return as the one value from this function if (result != null) { var variableBindings = freeVariables.ToDictionary(variable => variable, variable => simpleUnifier.UnifiedValue(variable)); return new BasicBinding(result, variableBindings); } else { return null; } } } }
Make the login button more noticeable
@using Anlab.Core.Domain @using Microsoft.AspNetCore.Http @inject SignInManager<User> SignInManager @inject UserManager<User> UserManager @if (User.Identity.IsAuthenticated) { var user = await UserManager.GetUserAsync(User); <form class="flexer" asp-area="" asp-controller="Account" asp-action="Logout" method="post" id="logoutForm"> <p><a asp-area="" asp-controller="Profile" asp-action="Index" title="Manage">Hello @user.Name!</a></p> <button type="submit" class="btn-hollow">Log out</button> </form> } else { <p><a asp-area="" asp-controller="Account" asp-action="Login">Log in</a></p> }
@using Anlab.Core.Domain @using Microsoft.AspNetCore.Http @inject SignInManager<User> SignInManager @inject UserManager<User> UserManager @if (User.Identity.IsAuthenticated) { var user = await UserManager.GetUserAsync(User); <form class="flexer" asp-area="" asp-controller="Account" asp-action="Logout" method="post" id="logoutForm"> <p><a asp-area="" asp-controller="Profile" asp-action="Index" title="Manage">Hello @user.Name!</a></p> <button type="submit" class="btn-hollow">Log out</button> </form> } else { <p><a class="btn btn-primary" asp-area="" asp-controller="Account" asp-action="Login">Log in</a></p> }
Update tests to match new constructor
// 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.Containers; using osu.Game.Beatmaps; using osu.Game.Screens.Ranking.Expanded; namespace osu.Game.Tests.Visual.Ranking { public class TestSceneStarRatingDisplay : OsuTestScene { public TestSceneStarRatingDisplay() { Child = new FillFlowContainer { Anchor = Anchor.Centre, Origin = Anchor.Centre, Children = new Drawable[] { new StarRatingDisplay(new BeatmapInfo { StarDifficulty = 1.23 }), new StarRatingDisplay(new BeatmapInfo { StarDifficulty = 2.34 }), new StarRatingDisplay(new BeatmapInfo { StarDifficulty = 3.45 }), new StarRatingDisplay(new BeatmapInfo { StarDifficulty = 4.56 }), new StarRatingDisplay(new BeatmapInfo { StarDifficulty = 5.67 }), new StarRatingDisplay(new BeatmapInfo { StarDifficulty = 6.78 }), new StarRatingDisplay(new BeatmapInfo { StarDifficulty = 10.11 }), } }; } } }
// 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.Containers; using osu.Game.Beatmaps; using osu.Game.Screens.Ranking.Expanded; namespace osu.Game.Tests.Visual.Ranking { public class TestSceneStarRatingDisplay : OsuTestScene { public TestSceneStarRatingDisplay() { Child = new FillFlowContainer { Anchor = Anchor.Centre, Origin = Anchor.Centre, Children = new Drawable[] { new StarRatingDisplay(new StarDifficulty(1.23, 0)), new StarRatingDisplay(new StarDifficulty(2.34, 0)), new StarRatingDisplay(new StarDifficulty(3.45, 0)), new StarRatingDisplay(new StarDifficulty(4.56, 0)), new StarRatingDisplay(new StarDifficulty(5.67, 0)), new StarRatingDisplay(new StarDifficulty(6.78, 0)), new StarRatingDisplay(new StarDifficulty(10.11, 0)), } }; } } }
Divide weapon arc by half
/* ** Project ShiftDrive ** (C) Mika Molenkamp, 2016. */ using System; using Microsoft.Xna.Framework; namespace ShiftDrive { /// <summary> /// Represents the maximum weapon size that a mount can hold. /// </summary> internal enum MountSize { Small = 1, Medium = 2, Large = 3 } /// <summary> /// Represents an attachment point for a weapon. /// </summary> internal sealed class WeaponMount { public Vector2 Offset; public Vector2 Position; public float Bearing; public float Arc; public float OffsetMag; public MountSize Size; public static WeaponMount FromLua(IntPtr L, int tableidx) { LuaAPI.luaL_checktype(L, tableidx, LuaAPI.LUA_TTABLE); WeaponMount ret = new WeaponMount(); LuaAPI.lua_getfield(L, tableidx, "position"); LuaAPI.lua_checkfieldtype(L, tableidx, "position", -1, LuaAPI.LUA_TTABLE); ret.Offset = LuaAPI.lua_tovec2(L, -1); ret.OffsetMag = -ret.Offset.Length(); LuaAPI.lua_pop(L, 1); ret.Bearing = LuaAPI.luaH_gettablefloat(L, tableidx, "bearing"); ret.Arc = LuaAPI.luaH_gettablefloat(L, tableidx, "arc"); ret.Size = (MountSize)LuaAPI.luaH_gettableint(L, tableidx, "size"); return ret; } } }
/* ** Project ShiftDrive ** (C) Mika Molenkamp, 2016. */ using System; using Microsoft.Xna.Framework; namespace ShiftDrive { /// <summary> /// Represents the maximum weapon size that a mount can hold. /// </summary> internal enum MountSize { Small = 1, Medium = 2, Large = 3 } /// <summary> /// Represents an attachment point for a weapon. /// </summary> internal sealed class WeaponMount { public Vector2 Offset; public Vector2 Position; public float Bearing; public float Arc; public float OffsetMag; public MountSize Size; public static WeaponMount FromLua(IntPtr L, int tableidx) { LuaAPI.luaL_checktype(L, tableidx, LuaAPI.LUA_TTABLE); WeaponMount ret = new WeaponMount(); LuaAPI.lua_getfield(L, tableidx, "position"); LuaAPI.lua_checkfieldtype(L, tableidx, "position", -1, LuaAPI.LUA_TTABLE); ret.Offset = LuaAPI.lua_tovec2(L, -1); ret.OffsetMag = -ret.Offset.Length(); LuaAPI.lua_pop(L, 1); ret.Bearing = LuaAPI.luaH_gettablefloat(L, tableidx, "bearing"); ret.Arc = LuaAPI.luaH_gettablefloat(L, tableidx, "arc") / 2f; ret.Size = (MountSize)LuaAPI.luaH_gettableint(L, tableidx, "size"); return ret; } } }
Print the sha which was excluded from version calculation
using System; using System.Collections.Generic; using System.Linq; using GitVersion.VersionCalculation.BaseVersionCalculators; namespace GitVersion.VersionFilters { public class ShaVersionFilter : IVersionFilter { private readonly IEnumerable<string> shas; public ShaVersionFilter(IEnumerable<string> shas) { if (shas == null) throw new ArgumentNullException("shas"); this.shas = shas; } public bool Exclude(BaseVersion version, out string reason) { if (version == null) throw new ArgumentNullException("version"); reason = null; if (version.BaseVersionSource != null && shas.Any(sha => version.BaseVersionSource.Sha.StartsWith(sha, StringComparison.OrdinalIgnoreCase))) { reason = "Source was ignored due to commit having been excluded by configuration"; return true; } return false; } } }
using System; using System.Collections.Generic; using System.Linq; using GitVersion.VersionCalculation.BaseVersionCalculators; namespace GitVersion.VersionFilters { public class ShaVersionFilter : IVersionFilter { private readonly IEnumerable<string> shas; public ShaVersionFilter(IEnumerable<string> shas) { if (shas == null) throw new ArgumentNullException("shas"); this.shas = shas; } public bool Exclude(BaseVersion version, out string reason) { if (version == null) throw new ArgumentNullException("version"); reason = null; if (version.BaseVersionSource != null && shas.Any(sha => version.BaseVersionSource.Sha.StartsWith(sha, StringComparison.OrdinalIgnoreCase))) { reason = $"Sha {version.BaseVersionSource.Sha} was ignored due to commit having been excluded by configuration"; return true; } return false; } } }
Remove unnecessary check for SharpZipLib dll.
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; namespace IronFoundry.Container { public class ContainerHostDependencyHelper { const string ContainerHostAssemblyName = "IronFoundry.Container.Host"; readonly Assembly containerHostAssembly; public ContainerHostDependencyHelper() { this.containerHostAssembly = GetContainerHostAssembly(); } public virtual string ContainerHostExe { get { return ContainerHostAssemblyName + ".exe"; } } public virtual string ContainerHostExePath { get { return containerHostAssembly.Location; } } static Assembly GetContainerHostAssembly() { return Assembly.ReflectionOnlyLoad(ContainerHostAssemblyName); } public virtual IReadOnlyList<string> GetContainerHostDependencies() { return EnumerateLocalReferences(containerHostAssembly).ToList(); } IEnumerable<string> EnumerateLocalReferences(Assembly assembly) { foreach (var referencedAssemblyName in assembly.GetReferencedAssemblies()) { var referencedAssembly = Assembly.ReflectionOnlyLoad(referencedAssemblyName.FullName); if (!referencedAssembly.GlobalAssemblyCache) { yield return referencedAssembly.Location; if (!referencedAssembly.Location.Contains("ICSharpCode.SharpZipLib.dll")) foreach (var nestedReferenceFilePath in EnumerateLocalReferences(referencedAssembly)) yield return nestedReferenceFilePath; } } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; namespace IronFoundry.Container { public class ContainerHostDependencyHelper { const string ContainerHostAssemblyName = "IronFoundry.Container.Host"; readonly Assembly containerHostAssembly; public ContainerHostDependencyHelper() { this.containerHostAssembly = GetContainerHostAssembly(); } public virtual string ContainerHostExe { get { return ContainerHostAssemblyName + ".exe"; } } public virtual string ContainerHostExePath { get { return containerHostAssembly.Location; } } static Assembly GetContainerHostAssembly() { return Assembly.ReflectionOnlyLoad(ContainerHostAssemblyName); } public virtual IReadOnlyList<string> GetContainerHostDependencies() { return EnumerateLocalReferences(containerHostAssembly).ToList(); } IEnumerable<string> EnumerateLocalReferences(Assembly assembly) { foreach (var referencedAssemblyName in assembly.GetReferencedAssemblies()) { var referencedAssembly = Assembly.ReflectionOnlyLoad(referencedAssemblyName.FullName); if (!referencedAssembly.GlobalAssemblyCache) { yield return referencedAssembly.Location; foreach (var nestedReferenceFilePath in EnumerateLocalReferences(referencedAssembly)) yield return nestedReferenceFilePath; } } } } }
Set RemoteEndPoint for UDP connections
using System; using System.Buffers; using System.Net; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; using SuperSocket.ProtoBase; namespace SuperSocket.Channel { public class UdpPipeChannel<TPackageInfo> : VirtualChannel<TPackageInfo>, IChannelWithSessionIdentifier { private Socket _socket; private IPEndPoint _remoteEndPoint; public UdpPipeChannel(Socket socket, IPipelineFilter<TPackageInfo> pipelineFilter, ChannelOptions options, IPEndPoint remoteEndPoint) : this(socket, pipelineFilter, options, remoteEndPoint, $"{remoteEndPoint.Address}:{remoteEndPoint.Port}") { } public UdpPipeChannel(Socket socket, IPipelineFilter<TPackageInfo> pipelineFilter, ChannelOptions options, IPEndPoint remoteEndPoint, string sessionIdentifier) : base(pipelineFilter, options) { _socket = socket; _remoteEndPoint = remoteEndPoint; SessionIdentifier = sessionIdentifier; } public string SessionIdentifier { get; } protected override void Close() { WriteEOFPackage(); } protected override ValueTask<int> FillPipeWithDataAsync(Memory<byte> memory, CancellationToken cancellationToken) { throw new NotSupportedException(); } protected override async ValueTask<int> SendOverIOAsync(ReadOnlySequence<byte> buffer, CancellationToken cancellationToken) { var total = 0; foreach (var piece in buffer) { total += await _socket.SendToAsync(GetArrayByMemory<byte>(piece), SocketFlags.None, _remoteEndPoint); } return total; } } }
using System; using System.Buffers; using System.Net; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; using SuperSocket.ProtoBase; namespace SuperSocket.Channel { public class UdpPipeChannel<TPackageInfo> : VirtualChannel<TPackageInfo>, IChannelWithSessionIdentifier { private Socket _socket; public UdpPipeChannel(Socket socket, IPipelineFilter<TPackageInfo> pipelineFilter, ChannelOptions options, IPEndPoint remoteEndPoint) : this(socket, pipelineFilter, options, remoteEndPoint, $"{remoteEndPoint.Address}:{remoteEndPoint.Port}") { } public UdpPipeChannel(Socket socket, IPipelineFilter<TPackageInfo> pipelineFilter, ChannelOptions options, IPEndPoint remoteEndPoint, string sessionIdentifier) : base(pipelineFilter, options) { _socket = socket; RemoteEndPoint = remoteEndPoint; SessionIdentifier = sessionIdentifier; } public string SessionIdentifier { get; } protected override void Close() { WriteEOFPackage(); } protected override ValueTask<int> FillPipeWithDataAsync(Memory<byte> memory, CancellationToken cancellationToken) { throw new NotSupportedException(); } protected override async ValueTask<int> SendOverIOAsync(ReadOnlySequence<byte> buffer, CancellationToken cancellationToken) { var total = 0; foreach (var piece in buffer) { total += await _socket.SendToAsync(GetArrayByMemory<byte>(piece), SocketFlags.None, RemoteEndPoint); } return total; } } }
Remove Cache From Print Version
using Mazzimo.Models; using Mazzimo.Repositories; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace Mazzimo.Controllers { public class HomeController : Controller { IPostRepository _postRepo; IResumeRepository _cvRepo; public HomeController(IPostRepository postRepo, IResumeRepository cvRepo) { _postRepo = postRepo; _cvRepo = cvRepo; } public ActionResult Index() { var post = _postRepo.GetFirst(); if (post == null) post = _postRepo.GetIntroductionPost(); return View(post); } public ActionResult Cv(string id) { var cv = _cvRepo.GetResumeFromLanguageCode(id); if (cv == null) return HttpNotFound(); ViewBag.Id = id; return View(cv); } public ActionResult CvPrint(string id) { var cv = _cvRepo.GetResumeFromLanguageCode(id); if (cv == null) return HttpNotFound(); Response.Cache.SetExpires(DateTime.Now.AddYears(1)); Response.Cache.SetCacheability(HttpCacheability.Public); return View(cv); } public ActionResult Post(string id) { var post = _postRepo.GetById(id); if (post == null) return HttpNotFound(); return View(post); } } }
using Mazzimo.Models; using Mazzimo.Repositories; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace Mazzimo.Controllers { public class HomeController : Controller { IPostRepository _postRepo; IResumeRepository _cvRepo; public HomeController(IPostRepository postRepo, IResumeRepository cvRepo) { _postRepo = postRepo; _cvRepo = cvRepo; } public ActionResult Index() { var post = _postRepo.GetFirst(); if (post == null) post = _postRepo.GetIntroductionPost(); return View(post); } public ActionResult Cv(string id) { var cv = _cvRepo.GetResumeFromLanguageCode(id); if (cv == null) return HttpNotFound(); ViewBag.Id = id; return View(cv); } public ActionResult CvPrint(string id) { var cv = _cvRepo.GetResumeFromLanguageCode(id); if (cv == null) return HttpNotFound(); return View(cv); } public ActionResult Post(string id) { var post = _postRepo.GetById(id); if (post == null) return HttpNotFound(); return View(post); } } }
Call correct overload of log.FatalAsync
extern alias pcl; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.UI.Xaml; namespace MetroLog { public static class GlobalCrashHandler { public static void Configure() { Application.Current.UnhandledException += App_UnhandledException; } private static async void App_UnhandledException(object sender, UnhandledExceptionEventArgs e) { // unbind we're going to re-enter and don't want to loop... Application.Current.UnhandledException -= App_UnhandledException; // say we've handled this one. this allows our FATAL write to complete. e.Handled = true; // go... var log = (ILoggerAsync)pcl::MetroLog.LogManagerFactory.DefaultLogManager.GetLogger<Application>(); await log.FatalAsync("The application crashed: " + e.Message, e.Exception); // if we're aborting, fake a suspend to flush the targets... await LazyFlushManager.FlushAllAsync(new LogWriteContext()); // abort the app here... Application.Current.Exit(); } } }
extern alias pcl; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.UI.Xaml; namespace MetroLog { public static class GlobalCrashHandler { public static void Configure() { Application.Current.UnhandledException += App_UnhandledException; } private static async void App_UnhandledException(object sender, UnhandledExceptionEventArgs e) { // unbind we're going to re-enter and don't want to loop... Application.Current.UnhandledException -= App_UnhandledException; // say we've handled this one. this allows our FATAL write to complete. e.Handled = true; // go... var log = (ILoggerAsync)pcl::MetroLog.LogManagerFactory.DefaultLogManager.GetLogger<Application>(); await log.FatalAsync("The application crashed: " + e.Message, e); // if we're aborting, fake a suspend to flush the targets... await LazyFlushManager.FlushAllAsync(new LogWriteContext()); // abort the app here... Application.Current.Exit(); } } }
Make convlayer tests more complete
using NUnit.Framework; namespace ConvNetSharp.Tests { [TestFixture] public class ConvLayerTests { [Test] public void GradientWrtInputCheck() { const int inputWidth = 10; const int inputHeight = 10; const int inputDepth = 2; // Create layer const int filterWidth = 3; const int filterHeight = 3; const int filterCount = 2; var layer = new ConvLayer(filterWidth, filterHeight, filterCount); GradientCheckTools.GradientCheck(layer, inputWidth, inputHeight, inputDepth); } [Test] public void GradientWrtParametersCheck() { const int inputWidth = 10; const int inputHeight = 10; const int inputDepth = 2; // Create layer const int filterWidth = 3; const int filterHeight = 3; const int filterCount = 2; var layer = new ConvLayer(filterWidth, filterHeight, filterCount); GradientCheckTools.GradienWrtParameterstCheck(inputWidth, inputHeight, inputDepth, layer); } } }
using NUnit.Framework; namespace ConvNetSharp.Tests { [TestFixture] public class ConvLayerTests { [Test] public void GradientWrtInputCheck() { const int inputWidth = 30; const int inputHeight = 30; const int inputDepth = 2; // Create layer const int filterWidth = 3; const int filterHeight = 3; const int filterCount = 5; var layer = new ConvLayer(filterWidth, filterHeight, filterCount) { Stride = 2}; GradientCheckTools.GradientCheck(layer, inputWidth, inputHeight, inputDepth); } [Test] public void GradientWrtParametersCheck() { const int inputWidth = 10; const int inputHeight = 10; const int inputDepth = 2; // Create layer const int filterWidth = 3; const int filterHeight = 3; const int filterCount = 2; var layer = new ConvLayer(filterWidth, filterHeight, filterCount) { Stride = 2 }; GradientCheckTools.GradienWrtParameterstCheck(inputWidth, inputHeight, inputDepth, layer); } } }
Fix insane oversight in `SynchronizationContext` implementation
// 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.Threading; #nullable enable namespace osu.Framework.Threading { /// <summary> /// A synchronisation context which posts all continuatiuons to a scheduler instance. /// </summary> internal class SchedulerSynchronizationContext : SynchronizationContext { private readonly Scheduler scheduler; public SchedulerSynchronizationContext(Scheduler scheduler) { this.scheduler = scheduler; } public override void Post(SendOrPostCallback d, object? state) => scheduler.Add(() => d(state), 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.Threading; #nullable enable namespace osu.Framework.Threading { /// <summary> /// A synchronisation context which posts all continuatiuons to a scheduler instance. /// </summary> internal class SchedulerSynchronizationContext : SynchronizationContext { private readonly Scheduler scheduler; public SchedulerSynchronizationContext(Scheduler scheduler) { this.scheduler = scheduler; } public override void Send(SendOrPostCallback d, object? state) => scheduler.Add(() => d(state), false); public override void Post(SendOrPostCallback d, object? state) => scheduler.Add(() => d(state), true); } }
Fix wrong type for linkbuttons
using System; using System.Web.UI.WebControls; namespace R7.HelpDesk { public partial class AdminSettings { protected Panel pnlAdminSettings; protected Panel pnlAdministratorRole; protected Panel pnlUploFilesPath; protected Panel pnlTagsAdmin; protected Panel pnlRoles; protected Button btnAddNew; protected Button btnUpdate; protected HyperLink lnkAdminRole; protected HyperLink lnkUploFilesPath; protected HyperLink lnkTagsAdmin; protected HyperLink lnkRoles; protected DropDownList ddlAdminRole; protected TextBox txtUploadedFilesPath; protected DropDownList ddlUploadPermission; protected TreeView tvCategories; protected Label lblAdminRole; protected Label lblUploadedFilesPath; protected TextBox txtCategoryID; protected DropDownList ddlParentCategory; protected TextBox txtCategory; protected CheckBox chkRequesterVisible; protected CheckBox chkSelectable; protected TextBox txtParentCategoryID; protected Button btnDelete; protected Label lblTagError; protected Label lblRoleError; protected DropDownList ddlRole; protected ListView lvRoles; } }
using System; using System.Web.UI.WebControls; namespace R7.HelpDesk { public partial class AdminSettings { protected Panel pnlAdminSettings; protected Panel pnlAdministratorRole; protected Panel pnlUploFilesPath; protected Panel pnlTagsAdmin; protected Panel pnlRoles; protected Button btnAddNew; protected Button btnUpdate; protected LinkButton lnkAdminRole; protected LinkButton lnkUploFilesPath; protected LinkButton lnkTagsAdmin; protected LinkButton lnkRoles; protected DropDownList ddlAdminRole; protected TextBox txtUploadedFilesPath; protected DropDownList ddlUploadPermission; protected TreeView tvCategories; protected Label lblAdminRole; protected Label lblUploadedFilesPath; protected TextBox txtCategoryID; protected DropDownList ddlParentCategory; protected TextBox txtCategory; protected CheckBox chkRequesterVisible; protected CheckBox chkSelectable; protected TextBox txtParentCategoryID; protected Button btnDelete; protected Label lblTagError; protected Label lblRoleError; protected DropDownList ddlRole; protected ListView lvRoles; } }
Fix bug with slow loading high scores
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using CodeBreaker.Core; using CodeBreaker.Core.Storage; using Microsoft.EntityFrameworkCore; namespace CodeBreaker.WebApp.Storage { public class ScoreStore : IScoreStore { private readonly CodeBreakerDbContext _dbContext; public ScoreStore(CodeBreakerDbContext dbContext) { _dbContext = dbContext; } public async Task<Score[]> GetScores(int page, int size) { return (await _dbContext.Scores.ToListAsync()) .OrderBy(s => s.Attempts) .ThenBy(s => s.Duration) .Skip(page * size).Take(size) .ToArray(); } public async Task SaveScore(Score score) { await _dbContext.Scores.AddAsync(score); await _dbContext.SaveChangesAsync(); } public Task<bool> ScoreExists(Guid gameId) { return _dbContext.Scores.AnyAsync(s => s.GameId == gameId); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using CodeBreaker.Core; using CodeBreaker.Core.Storage; using Microsoft.EntityFrameworkCore; namespace CodeBreaker.WebApp.Storage { public class ScoreStore : IScoreStore { private readonly CodeBreakerDbContext _dbContext; public ScoreStore(CodeBreakerDbContext dbContext) { _dbContext = dbContext; } public Task<Score[]> GetScores(int page, int size) { return _dbContext.Scores .OrderBy(s => s.Attempts) .ThenBy(s => s.Duration) .Skip(page * size).Take(size) .ToArrayAsync(); } public async Task SaveScore(Score score) { await _dbContext.Scores.AddAsync(score); await _dbContext.SaveChangesAsync(); } public Task<bool> ScoreExists(Guid gameId) { return _dbContext.Scores.AnyAsync(s => s.GameId == gameId); } } }
Check for active connections in each iteration
using System; using System.Linq; using System.Net.NetworkInformation; namespace HttpMock.Integration.Tests { internal static class PortHelper { internal static int FindLocalAvailablePortForTesting() { IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties(); var activeTcpConnections = properties.GetActiveTcpConnections(); const int minPort = 1024; var random = new Random(); var maxPort = 64000; var randomPort = random.Next(minPort, maxPort); while (activeTcpConnections.Any(a => a.LocalEndPoint.Port == randomPort)) { randomPort = random.Next(minPort, maxPort); } return randomPort; } } }
using System; using System.Linq; using System.Net; using System.Net.NetworkInformation; namespace HttpMock.Integration.Tests { internal static class PortHelper { internal static int FindLocalAvailablePortForTesting() { const int minPort = 1024; var random = new Random(); var maxPort = 64000; var randomPort = random.Next(minPort, maxPort); while (IsPortInUse(randomPort)) { randomPort = random.Next(minPort, maxPort); } return randomPort; } private static bool IsPortInUse(int randomPort) { var properties = IPGlobalProperties.GetIPGlobalProperties(); return properties.GetActiveTcpConnections().Any(a => a.LocalEndPoint.Port == randomPort) && properties.GetActiveTcpListeners().Any( a=> a.Port == randomPort); } } }
Switch over support commands from using the query class
using System.Data; using System.Linq; namespace ZocMonLib { public class StorageCommandsSupport : IStorageCommandsSupport { public string SelectCurrentReduceStatus(IDbConnection conn) { var result = DatabaseSqlHelper.CreateListWithConnection<bool>(conn, StorageCommandsSqlServerQuery.CurrentlyReducingSql); if (result.Any()) return result.First() ? "1" : "0"; return ""; } public void UpdateCurrentReduceStatus(string value, IDbConnection conn) { DatabaseSqlHelper.ExecuteNonQueryWithConnection(conn, StorageCommandsSqlServerQuery.UpdateReducingSql, new { IsReducing = value == "1" }); } } }
using System.Data; using System.Linq; namespace ZocMonLib { public class StorageCommandsSupport : IStorageCommandsSupport { public string SelectCurrentReduceStatus(IDbConnection conn) { const string sql = @"SELECT TOP(1) IsReducing FROM Settings"; var result = DatabaseSqlHelper.Query<bool>(conn, sql); if (result.Any()) return result.First() ? "1" : "0"; return ""; } public void UpdateCurrentReduceStatus(string value, IDbConnection conn) { //TODO this doesn't take into account if it doesn't exist const string sql = @"UPDATE Settings SET IsReducing = @isReducing"; DatabaseSqlHelper.Execute(conn, sql, param: new { isReducing = value == "1" }); } } }
Fix documentation confusion in a similar way to r3a00fecf9d42.
// Copyright 2013 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using System; namespace NodaTime.Annotations { /// <summary> /// Indicates that a type is immutable. Some members of this type /// allow state to be visibly changed. /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)] internal sealed class MutableAttribute : Attribute { } }
// Copyright 2013 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using System; namespace NodaTime.Annotations { /// <summary> /// Indicates that a type is mutable. Some members of this type /// allow state to be visibly changed. /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)] internal sealed class MutableAttribute : Attribute { } }
Add all operating system in the platform resolver
// Copyright (c) 2014-2020 Sarin Na Wangkanai, All Rights Reserved. // The Apache v2. See License.txt in the project root for license information. using Wangkanai.Detection.Extensions; using Wangkanai.Detection.Models; namespace Wangkanai.Detection.Services { public class PlatformService : IPlatformService { public Processor Processor { get; } public OperatingSystem OperatingSystem { get; } public PlatformService(IUserAgentService userAgentService) { var userAgent = userAgentService.UserAgent; Processor = ParseProcessor(userAgent); OperatingSystem = ParseOperatingSystem(userAgent); } private static OperatingSystem ParseOperatingSystem(UserAgent agent) { if (agent.Contains(OperatingSystem.Android)) return OperatingSystem.Android; if (agent.Contains(OperatingSystem.Windows)) return OperatingSystem.Windows; if (agent.Contains(OperatingSystem.Mac)) return OperatingSystem.Mac; return OperatingSystem.Others; } private static Processor ParseProcessor(UserAgent agent) { if (agent.Contains(Processor.ARM)) return Processor.ARM; if (agent.Contains(Processor.x86)) return Processor.x86; if (agent.Contains(Processor.x64)) return Processor.x64; return Processor.Others; } } }
// Copyright (c) 2014-2020 Sarin Na Wangkanai, All Rights Reserved. // The Apache v2. See License.txt in the project root for license information. using Wangkanai.Detection.Extensions; using Wangkanai.Detection.Models; namespace Wangkanai.Detection.Services { public class PlatformService : IPlatformService { public Processor Processor { get; } public OperatingSystem OperatingSystem { get; } public PlatformService(IUserAgentService userAgentService) { var userAgent = userAgentService.UserAgent; Processor = ParseProcessor(userAgent); OperatingSystem = ParseOperatingSystem(userAgent); } private static OperatingSystem ParseOperatingSystem(UserAgent agent) { if (agent.Contains(OperatingSystem.Android)) return OperatingSystem.Android; if (agent.Contains(OperatingSystem.Windows)) return OperatingSystem.Windows; if (agent.Contains(OperatingSystem.Mac)) return OperatingSystem.Mac; if (agent.Contains(OperatingSystem.iOS)) return OperatingSystem.iOS; if (agent.Contains(OperatingSystem.Linux)) return OperatingSystem.Linux; return OperatingSystem.Others; } private static Processor ParseProcessor(UserAgent agent) { if (agent.Contains(Processor.ARM)) return Processor.ARM; if (agent.Contains(Processor.x86)) return Processor.x86; if (agent.Contains(Processor.x64)) return Processor.x64; return Processor.Others; } } }
Simplify fetching the temporary path
// Automatically generated by Opus v0.50 namespace CopyTest1 { class CopySingleFileTest : FileUtilities.CopyFile { public CopySingleFileTest() { this.SetRelativePath(this, "data", "testfile.txt"); this.UpdateOptions += delegate(Opus.Core.IModule module, Opus.Core.Target target) { FileUtilities.ICopyFileOptions options = module.Options as FileUtilities.ICopyFileOptions; if (null != options) { if (target.HasPlatform(Opus.Core.EPlatform.OSX)) { options.DestinationDirectory = "/tmp"; } else if (target.HasPlatform(Opus.Core.EPlatform.Unix)) { options.DestinationDirectory = "/tmp"; } else if (target.HasPlatform(Opus.Core.EPlatform.Windows)) { options.DestinationDirectory = @"c:/temp"; } } }; } } class CopyMultipleFileTest : FileUtilities.CopyFileCollection { public CopyMultipleFileTest() { this.Include(this, "data", "*"); } } class CopyDirectoryTest : FileUtilities.CopyDirectory { public CopyDirectoryTest() { this.Include(this, "data"); } } }
// Automatically generated by Opus v0.50 namespace CopyTest1 { class CopySingleFileTest : FileUtilities.CopyFile { public CopySingleFileTest() { this.SetRelativePath(this, "data", "testfile.txt"); this.UpdateOptions += delegate(Opus.Core.IModule module, Opus.Core.Target target) { FileUtilities.ICopyFileOptions options = module.Options as FileUtilities.ICopyFileOptions; if (null != options) { options.DestinationDirectory = System.IO.Path.GetTempPath(); } }; } } class CopyMultipleFileTest : FileUtilities.CopyFileCollection { public CopyMultipleFileTest() { this.Include(this, "data", "*"); } } class CopyDirectoryTest : FileUtilities.CopyDirectory { public CopyDirectoryTest() { this.Include(this, "data"); } } }
Set app version to 3.0.0
using System; using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("EVE-O Preview")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("EVE-O Preview")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("04f08f8d-9e98-423b-acdb-4effb31c0d35")] [assembly: AssemblyVersion("2.2.0.0")] [assembly: AssemblyFileVersion("2.2.0.0")] [assembly: CLSCompliant(true)]
using System; using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("EVE-O Preview")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("EVE-O Preview")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("04f08f8d-9e98-423b-acdb-4effb31c0d35")] [assembly: AssemblyVersion("3.0.0.0")] [assembly: AssemblyFileVersion("3.0.0.0")] [assembly: CLSCompliant(true)]
Fix the not registered fare deal options.
using System; using Diskordia.Columbus.Bots.FareDeals; using Diskordia.Columbus.Bots.FareDeals.SingaporeAirlines; using Diskordia.Columbus.Common; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace Diskordia.Columbus.Bots { public static class BotsExtensions { public static IServiceCollection AddFareDealBots(this IServiceCollection services, IConfiguration configuration) { if(services == null) { throw new ArgumentNullException(nameof(services)); } if (configuration == null) { throw new ArgumentNullException(nameof(configuration)); } services.AddTransient<IFareDealScanService, SingaporeAirlinesFareDealService>(); services.Configure<SingaporeAirlinesOptions>(configuration.GetSection("FareDealScan:SingaporeAirlines")); return services; } } }
using System; using Diskordia.Columbus.Bots.FareDeals; using Diskordia.Columbus.Bots.FareDeals.SingaporeAirlines; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace Diskordia.Columbus.Bots { public static class BotsExtensions { public static IServiceCollection AddFareDealBots(this IServiceCollection services, IConfiguration configuration) { if(services == null) { throw new ArgumentNullException(nameof(services)); } if (configuration == null) { throw new ArgumentNullException(nameof(configuration)); } services.AddTransient<IFareDealScanService, SingaporeAirlinesFareDealService>(); services.Configure<SingaporeAirlinesOptions>(configuration.GetSection("FareDealScan:SingaporeAirlines")); services.Configure<FareDealScanOptions>(configuration.GetSection("FareDealScan")); return services; } } }
Throw Exception if arg < 0 using Throw Expression
using System; using System.Linq; namespace FibCSharp { class Program { static void Main(string[] args) { var max = 50; Enumerable.Range(0, int.MaxValue) .Select(Fib) .TakeWhile(x => x <= max) .ToList() .ForEach(Console.WriteLine); } static int Fib(int arg) => arg == 0 ? 0 : arg == 1 ? 1 : Fib(arg - 2) + Fib(arg - 1); } }
using System; using System.Linq; namespace FibCSharp { class Program { static void Main(string[] args) { var max = 50; Enumerable.Range(0, int.MaxValue) .Select(Fib) .TakeWhile(x => x <= max) .ToList() .ForEach(Console.WriteLine); } static int Fib(int arg) => arg < 0 ? throw new Exception("Argument must be >= 0") : arg == 0 ? 0 : arg == 1 ? 1 : Fib(arg - 2) + Fib(arg - 1); } }
Split ModuleOutput tests to separate asserts
using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace T4TS.Tests { [TestClass] public class ModuleOutputAppenderTests { [TestMethod] public void ModuleOutputAppenderRespectsCompatibilityVersion() { var sb = new StringBuilder(); var module = new TypeScriptModule { QualifiedName = "Foo" }; var settings = new Settings(); var appender = new ModuleOutputAppender(sb, 0, settings); settings.CompatibilityVersion = new Version(0, 8, 3); appender.AppendOutput(module); Assert.IsTrue(sb.ToString().StartsWith("module")); sb.Clear(); settings.CompatibilityVersion = new Version(0, 9, 0); appender.AppendOutput(module); Assert.IsTrue(sb.ToString().StartsWith("declare module")); sb.Clear(); settings.CompatibilityVersion = null; appender.AppendOutput(module); Assert.IsTrue(sb.ToString().StartsWith("declare module")); } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace T4TS.Tests { [TestClass] public class ModuleOutputAppenderTests { [TestMethod] public void TypescriptVersion083YieldsModule() { var sb = new StringBuilder(); var module = new TypeScriptModule { QualifiedName = "Foo" }; var appender = new ModuleOutputAppender(sb, 0, new Settings { CompatibilityVersion = new Version(0, 8, 3) }); appender.AppendOutput(module); Assert.IsTrue(sb.ToString().StartsWith("module ")); } [TestMethod] public void TypescriptVersion090YieldsDeclareModule() { var sb = new StringBuilder(); var module = new TypeScriptModule { QualifiedName = "Foo" }; var appender = new ModuleOutputAppender(sb, 0, new Settings { CompatibilityVersion = new Version(0, 9, 0) }); appender.AppendOutput(module); Assert.IsTrue(sb.ToString().StartsWith("declare module ")); } [TestMethod] public void DefaultTypescriptVersionYieldsDeclareModule() { var sb = new StringBuilder(); var module = new TypeScriptModule { QualifiedName = "Foo" }; var appender = new ModuleOutputAppender(sb, 0, new Settings { CompatibilityVersion = null }); appender.AppendOutput(module); Assert.IsTrue(sb.ToString().StartsWith("declare module ")); } } }
Change version up to 0.5.1
using UnityEngine; using System.Reflection; [assembly: AssemblyVersion("0.5.0.*")] public class Loader : MonoBehaviour { /// <summary> /// DebugUI prefab to instantiate. /// </summary> [SerializeField] private GameObject _debugUI; /// <summary> /// ModalDialog prefab to instantiate. /// </summary> [SerializeField] private GameObject _modalDialog; /// <summary> /// MainMenu prefab to instantiate. /// </summary> [SerializeField] private GameObject _mainMenu; /// <summary> /// InGameUI prefab to instantiate. /// </summary> [SerializeField] private GameObject _inGameUI; /// <summary> /// SoundManager prefab to instantiate. /// </summary> [SerializeField] private GameObject _soundManager; /// <summary> /// GameManager prefab to instantiate. /// </summary> [SerializeField] private GameObject _gameManager; protected void Awake() { // Check if the instances have already been assigned to static variables or they are still null. if (DebugUI.Instance == null) { Instantiate(_debugUI); } if (ModalDialog.Instance == null) { Instantiate(_modalDialog); } if (MainMenu.Instance == null) { Instantiate(_mainMenu); } if (InGameUI.Instance == null) { Instantiate(_inGameUI); } if (SoundManager.Instance == null) { Instantiate(_soundManager); } if (GameManager.Instance == null) { Instantiate(_gameManager); } } }
using UnityEngine; using System.Reflection; [assembly: AssemblyVersion("0.5.1.*")] public class Loader : MonoBehaviour { /// <summary> /// DebugUI prefab to instantiate. /// </summary> [SerializeField] private GameObject _debugUI; /// <summary> /// ModalDialog prefab to instantiate. /// </summary> [SerializeField] private GameObject _modalDialog; /// <summary> /// MainMenu prefab to instantiate. /// </summary> [SerializeField] private GameObject _mainMenu; /// <summary> /// InGameUI prefab to instantiate. /// </summary> [SerializeField] private GameObject _inGameUI; /// <summary> /// SoundManager prefab to instantiate. /// </summary> [SerializeField] private GameObject _soundManager; /// <summary> /// GameManager prefab to instantiate. /// </summary> [SerializeField] private GameObject _gameManager; protected void Awake() { // Check if the instances have already been assigned to static variables or they are still null. if (DebugUI.Instance == null) { Instantiate(_debugUI); } if (ModalDialog.Instance == null) { Instantiate(_modalDialog); } if (MainMenu.Instance == null) { Instantiate(_mainMenu); } if (InGameUI.Instance == null) { Instantiate(_inGameUI); } if (SoundManager.Instance == null) { Instantiate(_soundManager); } if (GameManager.Instance == null) { Instantiate(_gameManager); } } }
Handle iOS memory alerts and free any memory we can
// 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 CoreGraphics; using UIKit; namespace osu.Framework.iOS { internal class GameViewController : UIViewController { public override bool PrefersStatusBarHidden() => true; public override UIRectEdge PreferredScreenEdgesDeferringSystemGestures => UIRectEdge.All; public override void ViewWillTransitionToSize(CGSize toSize, IUIViewControllerTransitionCoordinator coordinator) { coordinator.AnimateAlongsideTransition(_ => { }, _ => UIView.AnimationsEnabled = true); UIView.AnimationsEnabled = false; base.ViewWillTransitionToSize(toSize, coordinator); (View as IOSGameView)?.RequestResizeFrameBuffer(); } } }
// 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 CoreGraphics; using UIKit; namespace osu.Framework.iOS { internal class GameViewController : UIViewController { public override bool PrefersStatusBarHidden() => true; public override UIRectEdge PreferredScreenEdgesDeferringSystemGestures => UIRectEdge.All; public override void DidReceiveMemoryWarning() { base.DidReceiveMemoryWarning(); SixLabors.ImageSharp.Configuration.Default.MemoryAllocator.ReleaseRetainedResources(); GC.Collect(); } public override void ViewWillTransitionToSize(CGSize toSize, IUIViewControllerTransitionCoordinator coordinator) { coordinator.AnimateAlongsideTransition(_ => { }, _ => UIView.AnimationsEnabled = true); UIView.AnimationsEnabled = false; base.ViewWillTransitionToSize(toSize, coordinator); (View as IOSGameView)?.RequestResizeFrameBuffer(); } } }
Fix help text to use Debug output
// Copyright 2021 Maintainers of NUKE. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.Collections.Generic; using System.Linq; namespace Nuke.Common.Execution { internal class HandleHelpRequestsAttribute : BuildExtensionAttributeBase, IOnBuildInitialized { public void OnBuildInitialized( NukeBuild build, IReadOnlyCollection<ExecutableTarget> executableTargets, IReadOnlyCollection<ExecutableTarget> executionPlan) { if (build.Help || executionPlan.Count == 0) { Host.Information(HelpTextService.GetTargetsText(build.ExecutableTargets)); Host.Information(HelpTextService.GetParametersText(build)); } if (build.Plan) ExecutionPlanHtmlService.ShowPlan(build.ExecutableTargets); if (build.Help || executionPlan.Count == 0 || build.Plan) Environment.Exit(exitCode: 0); } } }
// Copyright 2021 Maintainers of NUKE. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.Collections.Generic; using System.Linq; namespace Nuke.Common.Execution { internal class HandleHelpRequestsAttribute : BuildExtensionAttributeBase, IOnBuildInitialized { public void OnBuildInitialized( NukeBuild build, IReadOnlyCollection<ExecutableTarget> executableTargets, IReadOnlyCollection<ExecutableTarget> executionPlan) { if (build.Help || executionPlan.Count == 0) { Host.Debug(HelpTextService.GetTargetsText(build.ExecutableTargets)); Host.Debug(HelpTextService.GetParametersText(build)); } if (build.Plan) ExecutionPlanHtmlService.ShowPlan(build.ExecutableTargets); if (build.Help || executionPlan.Count == 0 || build.Plan) Environment.Exit(exitCode: 0); } } }
Allow legacy score to be constructed even if replay file is missing
// 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.Linq; using osu.Framework.IO.Stores; using osu.Game.Beatmaps; using osu.Game.Rulesets; using osu.Game.Scoring.Legacy; namespace osu.Game.Scoring { public class LegacyDatabasedScore : Score { public LegacyDatabasedScore(ScoreInfo score, RulesetStore rulesets, BeatmapManager beatmaps, IResourceStore<byte[]> store) { ScoreInfo = score; var replayFilename = score.Files.First(f => f.Filename.EndsWith(".osr", StringComparison.InvariantCultureIgnoreCase)).FileInfo.StoragePath; using (var stream = store.GetStream(replayFilename)) Replay = new DatabasedLegacyScoreDecoder(rulesets, beatmaps).Parse(stream).Replay; } } }
// 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.Linq; using osu.Framework.IO.Stores; using osu.Game.Beatmaps; using osu.Game.Rulesets; using osu.Game.Scoring.Legacy; namespace osu.Game.Scoring { public class LegacyDatabasedScore : Score { public LegacyDatabasedScore(ScoreInfo score, RulesetStore rulesets, BeatmapManager beatmaps, IResourceStore<byte[]> store) { ScoreInfo = score; var replayFilename = score.Files.FirstOrDefault(f => f.Filename.EndsWith(".osr", StringComparison.InvariantCultureIgnoreCase))?.FileInfo.StoragePath; if (replayFilename == null) return; using (var stream = store.GetStream(replayFilename)) Replay = new DatabasedLegacyScoreDecoder(rulesets, beatmaps).Parse(stream).Replay; } } }
Fix PCL implementation of Reset
using System; using System.Threading; #if PORTABLE using System.Threading.Tasks; #endif namespace Polly.Utilities { /// <summary> /// Time related delegates used to improve testability of the code /// </summary> public static class SystemClock { /// <summary> /// Allows the setting of a custom Thread.Sleep implementation for testing. /// By default this will be a call to <see cref="Thread.Sleep(TimeSpan)"/> /// </summary> #if !PORTABLE public static Action<TimeSpan> Sleep = Thread.Sleep; #endif #if PORTABLE public static Action<TimeSpan> Sleep = timespan => new ManualResetEvent(false).WaitOne(timespan); #endif /// <summary> /// Allows the setting of a custom DateTime.UtcNow implementation for testing. /// By default this will be a call to <see cref="DateTime.UtcNow"/> /// </summary> public static Func<DateTime> UtcNow = () => DateTime.UtcNow; /// <summary> /// Resets the custom implementations to their defaults. /// Should be called during test teardowns. /// </summary> public static void Reset() { #if !PORTABLE Sleep = Thread.Sleep; #endif #if PORTABLE Sleep = async span => await Task.Delay(span); #endif UtcNow = () => DateTime.UtcNow; } } }
using System; using System.Threading; namespace Polly.Utilities { /// <summary> /// Time related delegates used to improve testability of the code /// </summary> public static class SystemClock { #if !PORTABLE /// <summary> /// Allows the setting of a custom Thread.Sleep implementation for testing. /// By default this will be a call to <see cref="M:Thread.Sleep"/> /// </summary> public static Action<TimeSpan> Sleep = Thread.Sleep; #endif #if PORTABLE /// <summary> /// Allows the setting of a custom Thread.Sleep implementation for testing. /// By default this will be a call to <see cref="M:ManualResetEvent.WaitOne"/> /// </summary> public static Action<TimeSpan> Sleep = timespan => new ManualResetEvent(false).WaitOne(timespan); #endif /// <summary> /// Allows the setting of a custom DateTime.UtcNow implementation for testing. /// By default this will be a call to <see cref="DateTime.UtcNow"/> /// </summary> public static Func<DateTime> UtcNow = () => DateTime.UtcNow; /// <summary> /// Resets the custom implementations to their defaults. /// Should be called during test teardowns. /// </summary> public static void Reset() { #if !PORTABLE Sleep = Thread.Sleep; #endif #if PORTABLE Sleep = timeSpan => new ManualResetEvent(false).WaitOne(timeSpan); #endif UtcNow = () => DateTime.UtcNow; } } }
Add Path property to exception
using System; using System.Text; using Microsoft.AspNetCore.Http; namespace Hellang.Middleware.SpaFallback { public class SpaFallbackException : Exception { private const string Fallback = nameof(SpaFallbackExtensions.UseSpaFallback); private const string StaticFiles = "UseStaticFiles"; private const string Mvc = "UseMvc"; public SpaFallbackException(PathString path) : base(GetMessage(path)) { } private static string GetMessage(PathString path) => new StringBuilder() .AppendLine($"The {Fallback} middleware failed to provide a fallback response for path '{path}' because no middleware could handle it.") .AppendLine($"Make sure {Fallback} is placed before any middleware that is supposed to provide the fallback response. This is typically {StaticFiles} or {Mvc}.") .AppendLine($"If you're using {StaticFiles}, make sure the file exists on disk and that the middleware is configured correctly.") .AppendLine($"If you're using {Mvc}, make sure you have a controller and action method that can handle '{path}'.") .ToString(); } }
using System; using System.Text; using Microsoft.AspNetCore.Http; namespace Hellang.Middleware.SpaFallback { public class SpaFallbackException : Exception { private const string Fallback = nameof(SpaFallbackExtensions.UseSpaFallback); private const string StaticFiles = "UseStaticFiles"; private const string Mvc = "UseMvc"; public SpaFallbackException(PathString path) : base(GetMessage(path)) { Path = path; } public PathString Path { get; } private static string GetMessage(PathString path) => new StringBuilder() .AppendLine($"The {Fallback} middleware failed to provide a fallback response for path '{path}' because no middleware could handle it.") .AppendLine($"Make sure {Fallback} is placed before any middleware that is supposed to provide the fallback response. This is typically {StaticFiles} or {Mvc}.") .AppendLine($"If you're using {StaticFiles}, make sure the file exists on disk and that the middleware is configured correctly.") .AppendLine($"If you're using {Mvc}, make sure you have a controller and action method that can handle '{path}'.") .ToString(); } }
Remove forced height for testing
@* * Copyright (c) gestaoaju.com.br - All rights reserved. * Licensed under MIT (https://github.com/gestaoaju/commerce/blob/master/LICENSE). *@ @{ Layout = "~/Views/Shared/_AppLayout.cshtml"; } @section scripts { <script type="text/javascript" src="/js/overview.min.js" asp-append-version="true"></script> } <div class="page-title"> Título da página </div> <div class="page-content"> Conteúdo da página <strong>Comercial</strong> <div style="height:1000px;"></div> </div>
@* * Copyright (c) gestaoaju.com.br - All rights reserved. * Licensed under MIT (https://github.com/gestaoaju/commerce/blob/master/LICENSE). *@ @{ Layout = "~/Views/Shared/_AppLayout.cshtml"; } @section scripts { <script type="text/javascript" src="/js/overview.min.js" asp-append-version="true"></script> } <div class="page-title"> Título da página </div> <div class="page-content"> Conteúdo da página <strong>Comercial</strong> </div>
Add google analytics tracking code.
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>@ViewBag.Title</title> @Styles.Render("~/Content/css") @Scripts.Render("~/bundles/modernizr") </head> <body> <div class="container body-content"> @RenderBody() <hr /> <footer> <p>&copy; @DateTime.Now.Year - <a href="http://ivaz.com">Ivan Zlatev</a></p> </footer> </div> @Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/bootstrap") @RenderSection("scripts", required: false) </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>@ViewBag.Title</title> @Styles.Render("~/Content/css") @Scripts.Render("~/bundles/modernizr") </head> <body> <div class="container body-content"> @RenderBody() <hr /> <footer> <p>&copy; @DateTime.Now.Year - <a href="http://ivaz.com">Ivan Zlatev</a></p> </footer> </div> @Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/bootstrap") @RenderSection("scripts", required: false) <script> (function (i, s, o, g, r, a, m) { i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () { (i[r].q = i[r].q || []).push(arguments) }, i[r].l = 1 * new Date(); a = s.createElement(o), m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m) })(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga'); ga('create', 'UA-19302892-3', 'playlistexporter.azurewebsites.net'); ga('send', 'pageview'); </script> </body> </html>
Correct test for TeamCity status
using System.Collections.Generic; using System.Linq; using Fake; using Machine.Specifications; namespace Test.FAKECore { public class when_encapsuting_strings { It should_encapsulate_without_special_chars = () => TeamCityHelper.EncapsulateSpecialChars("Total 47, Failures 1, NotRun 0, Inconclusive 0, Skipped 0") .ShouldEqual("Total 47, Failures 1, NotRun 0, Inconclusive 0, Skipped 0"); } public class when_creating_buildstatus { It should_encapsulate_special_chars = () => TeamCityHelper.buildStatus("FAILURE", "Total 47, Failures 1, NotRun 0, Inconclusive 0, Skipped 0") .ShouldEqual("##teamcity[buildStatus 'FAILURE' text='Total 47, Failures 1, NotRun 0, Inconclusive 0, Skipped 0']"); } }
using System.Collections.Generic; using System.Linq; using Fake; using Machine.Specifications; namespace Test.FAKECore { public class when_encapsuting_strings { It should_encapsulate_without_special_chars = () => TeamCityHelper.EncapsulateSpecialChars("Total 47, Failures 1, NotRun 0, Inconclusive 0, Skipped 0") .ShouldEqual("Total 47, Failures 1, NotRun 0, Inconclusive 0, Skipped 0"); } public class when_creating_buildstatus { It should_encapsulate_special_chars = () => TeamCityHelper.buildStatus("FAILURE", "Total 47, Failures 1, NotRun 0, Inconclusive 0, Skipped 0") .ShouldEqual("##teamcity[buildStatus status='FAILURE' text='Total 47, Failures 1, NotRun 0, Inconclusive 0, Skipped 0']"); } }
Format contribution info as annotation
--- Title: Documentation --- <p> We gladly accept your contributions. If there is something that you would like to add then you can edit the content directly on GitHub. </p> @foreach(IDocument child in Model.DocumentList(Keys.Children).OrderBy(x => x.Get<int>(DocsKeys.Order, 1000))) { <h1>@(child.String(Keys.Title))</h1> if(child.ContainsKey(DocsKeys.Description)) { <p>@Html.Raw(child.String(DocsKeys.Description))</p> } @Html.Partial("_ChildPages", child) }
--- Title: Documentation --- <div class="alert alert-info"> <p> We gladly accept your contributions. If there is something that you would like to add then you can edit the content directly on GitHub. </p> </div> @foreach(IDocument child in Model.DocumentList(Keys.Children).OrderBy(x => x.Get<int>(DocsKeys.Order, 1000))) { <h1>@(child.String(Keys.Title))</h1> if(child.ContainsKey(DocsKeys.Description)) { <p>@Html.Raw(child.String(DocsKeys.Description))</p> } @Html.Partial("_ChildPages", child) }
Add required defaults for tests
using System; using System.Collections.Generic; using UnityEngine; namespace Bugsnag.Unity.Tests { public class TestConfiguration : IConfiguration { public TimeSpan MaximumLogsTimePeriod { get; set; } public Dictionary<LogType, int> MaximumTypePerTimePeriod { get; set; } public TimeSpan UniqueLogsTimePeriod { get; set; } public string ApiKey { get; set; } public int MaximumBreadcrumbs { get; set; } public string ReleaseStage { get; set; } public string AppVersion { get; set; } public Uri Endpoint { get; set; } public string PayloadVersion { get; set; } public Uri SessionEndpoint { get; set; } public string SessionPayloadVersion { get; set; } public string Context { get; set; } public LogType NotifyLevel { get; set; } public bool AutoNotify { get; set; } } }
using System; using System.Collections.Generic; using UnityEngine; namespace Bugsnag.Unity.Tests { public class TestConfiguration : IConfiguration { public TimeSpan MaximumLogsTimePeriod { get; set; } = TimeSpan.FromSeconds(1); public Dictionary<LogType, int> MaximumTypePerTimePeriod { get; set; } public TimeSpan UniqueLogsTimePeriod { get; set; } = TimeSpan.FromSeconds(5); public string ApiKey { get; set; } public int MaximumBreadcrumbs { get; set; } public string ReleaseStage { get; set; } public string AppVersion { get; set; } public Uri Endpoint { get; set; } public string PayloadVersion { get; set; } public Uri SessionEndpoint { get; set; } public string SessionPayloadVersion { get; set; } public string Context { get; set; } public LogType NotifyLevel { get; set; } public bool AutoNotify { get; set; } } }
Add time measurement in Main, fix output
using System; 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}", project.Name); foreach (var kv in project.Formulae) { var isSatisfied = kv.Key.Check(kv.Value); var symbol = isSatisfied ? "|=" : "|/="; ForegroundColor = isSatisfied ? ConsoleColor.Green : ConsoleColor.Red; WriteLine($"{kv.Value} {symbol} {kv.Key}"); } ResetColor(); } } }
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."); } } }
Remove publicly exposed Vertices property
using System; using System.Collections.Generic; namespace Graph { /// <summary> /// Represents a graph. /// </summary> /// <typeparam name="V">The vertex type.</typeparam> /// <typeparam name="E">The edge type.</typeparam> public interface IGraph<V, E> : IEquatable<IGraph<V, E>> where E: IEdge<V> { /// <summary> /// The graph's vertices. /// </summary> ISet<V> Vertices { get; } /// <summary> /// Attempts to add an edge to the graph. /// </summary> /// <param name="edge"> /// The edge. /// </param> /// <param name="allowNewVertices"> /// Iff true, add vertices in the edge which aren't yet in the graph /// to the graph's vertex set. /// </param> /// <returns> /// True if the edge was successfully added (the definition of /// "success" may vary from implementation to implementation). /// </returns> /// <exception cref="InvalidOperationException"> /// Thrown if the edge contains at least one edge not in the graph, /// and allowNewVertices is set to false. /// </exception> bool TryAddEdge(E edge, bool allowNewVertices = false); /// <summary> /// Attempts to remove an edge from the graph. /// </summary> /// <param name="edge">The edge.</param> /// <returns> /// True if the edge was successfully removed, false otherwise. /// </returns> bool TryRemoveEdge(E edge); } }
using System; using System.Collections.Generic; namespace Graph { /// <summary> /// Represents a graph. /// </summary> /// <typeparam name="V">The vertex type.</typeparam> /// <typeparam name="E">The edge type.</typeparam> public interface IGraph<V, E> : IEquatable<IGraph<V, E>> where E: IEdge<V> { /// <summary> /// Attempts to add an edge to the graph. /// </summary> /// <param name="edge"> /// The edge. /// </param> /// <param name="allowNewVertices"> /// Iff true, add vertices in the edge which aren't yet in the graph /// to the graph's vertex set. /// </param> /// <returns> /// True if the edge was successfully added (the definition of /// "success" may vary from implementation to implementation). /// </returns> /// <exception cref="InvalidOperationException"> /// Thrown if the edge contains at least one edge not in the graph, /// and allowNewVertices is set to false. /// </exception> bool TryAddEdge(E edge, bool allowNewVertices = false); /// <summary> /// Attempts to remove an edge from the graph. /// </summary> /// <param name="edge">The edge.</param> /// <returns> /// True if the edge was successfully removed, false otherwise. /// </returns> bool TryRemoveEdge(E edge); } }
Add Google Analytics tracking for changing results mode
@using CkanDotNet.Api.Model @using CkanDotNet.Web.Models @using CkanDotNet.Web.Models.Helpers @using System.Collections.Specialized @model PackageSearchResultsModel @{ var routeValues = RouteHelper.RouteFromParameters(Html.ViewContext); // Remove the page number from the route values since we are doing client-side // pagination in the table mode RouteHelper.UpdateRoute(routeValues, "page", null); } <div class="results-mode"> @if (Model.DisplayMode == ResultsDisplayMode.Table) { <a class="mode" href="@Url.Action("Index", "Search", RouteHelper.UpdateRoute(routeValues, "mode", "list"))">List</a><span class="mode active">Table</span> } else { <span class="mode active">List</span><a class="mode" href="@Url.Action("Index", "Search", RouteHelper.UpdateRoute(routeValues, "mode", "table"))">Table</a> } </div>
@using CkanDotNet.Api.Model @using CkanDotNet.Web.Models @using CkanDotNet.Web.Models.Helpers @using System.Collections.Specialized @model PackageSearchResultsModel @{ var routeValues = RouteHelper.RouteFromParameters(Html.ViewContext); // Remove the page number from the route values since we are doing client-side // pagination in the table mode RouteHelper.UpdateRoute(routeValues, "page", null); } <div class="results-mode"> @if (Model.DisplayMode == ResultsDisplayMode.Table) { <a class="mode" href="@Url.Action("Index", "Search", RouteHelper.UpdateRoute(routeValues, "mode", "list"))">List</a><span class="mode active">Table</span> } else { <span class="mode active">List</span><a class="mode" href="@Url.Action("Index", "Search", RouteHelper.UpdateRoute(routeValues, "mode", "table"))">Table</a> } </div> @if (SettingsHelper.GetGoogleAnalyticsEnabled()) { <script language="javascript"> $('.mode').click(function () { var mode = $(this).text(); _gaq.push([ '_trackEvent', 'Search', 'Mode', mode]); }); </script> }
Fix to alarm not triggering correctly
namespace Raccoon.Components { public class Alarm : Component { public Alarm(uint interval, System.Action action) { NextActivationTimer = Interval = interval; Action = action; } public System.Action Action { get; set; } public uint Timer { get; private set; } public uint NextActivationTimer { get; private set; } public uint Interval { get; set; } public uint RepeatTimes { get; set; } = uint.MaxValue; public uint RepeatCount { get; private set; } public override void Update(int delta) { Timer += (uint) delta; if (Timer < NextActivationTimer) { return; } Action(); if (RepeatCount < RepeatTimes) { RepeatCount++; NextActivationTimer += Interval; } } public override void Render() { } public override void DebugRender() { } public void Reset() { RepeatCount = 0; Timer = 0; NextActivationTimer = Interval; } } }
namespace Raccoon.Components { public class Alarm : Component { public Alarm(uint interval, System.Action action) { NextActivationTimer = Interval = interval; Action = action; } public System.Action Action { get; set; } public uint Timer { get; private set; } public uint NextActivationTimer { get; private set; } public uint Interval { get; set; } public uint RepeatTimes { get; set; } = uint.MaxValue; public uint TriggeredCount { get; private set; } public override void Update(int delta) { Timer += (uint) delta; if (TriggeredCount > RepeatTimes || Timer < NextActivationTimer) { return; } Action(); TriggeredCount++; NextActivationTimer += Interval; } public override void Render() { } public override void DebugRender() { } public void Reset() { TriggeredCount = 0; Timer = 0; NextActivationTimer = Interval; } } }
Revert "Added incoming_webhook to Access Token Response"
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SlackAPI { [RequestPath("oauth.access")] public class AccessTokenResponse : Response { public string access_token; public string scope; public string team_name; public string team_id { get; set; } public BotTokenResponse bot; public IncomingWebhook incoming_webhook { get; set; } } public class BotTokenResponse { public string emoji; public string image_24; public string image_32; public string image_48; public string image_72; public string image_192; public bool deleted; public UserProfile icons; public string id; public string name; public string bot_user_id; public string bot_access_token; } public class IncomingWebhook { public string channel { get; set; } public string channel_id { get; set; } public string configuration_url { get; set; } public string url { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SlackAPI { [RequestPath("oauth.access")] public class AccessTokenResponse : Response { public string access_token; public string scope; public string team_name; public string team_id { get; set; } public BotTokenResponse bot; } public class BotTokenResponse { public string emoji; public string image_24; public string image_32; public string image_48; public string image_72; public string image_192; public bool deleted; public UserProfile icons; public string id; public string name; public string bot_user_id; public string bot_access_token; } }
Fix Error entity not contain RawJson
using System; using Mastodot.Entities; using Mastodot.Exceptions; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Mastodot.Utils.JsonConverters { internal class ErrorThrowJsonConverter<T> : JsonConverter { public override bool CanConvert(Type objectType) { return true; } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (objectType.Name.StartsWith("IEnumerable")) { JArray jArray = JArray.Load(reader); return jArray.ToObject<T>(); } JObject jObject = JObject.Load(reader); if (jObject["error"] != null) { Error error = jObject.ToObject<Error>(); var exception = new DeserializeErrorException($"Cant deserialize response, Type {objectType}") { Error = error }; throw exception; } return jObject.ToObject<T>(); } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { serializer.Serialize(writer, value); } } }
using System; using Mastodot.Entities; using Mastodot.Exceptions; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Mastodot.Utils.JsonConverters { internal class ErrorThrowJsonConverter<T> : JsonConverter { public override bool CanConvert(Type objectType) { return true; } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (objectType.Name.StartsWith("IEnumerable")) { JArray jArray = JArray.Load(reader); return jArray.ToObject<T>(); } JObject jObject = JObject.Load(reader); if (jObject["error"] != null) { Error error = jObject.ToObject<Error>(); error.RawJson = jObject.ToString(); var exception = new DeserializeErrorException($"Cant deserialize response, Type {objectType}") { Error = error }; throw exception; } return jObject.ToObject<T>(); } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { serializer.Serialize(writer, value); } } }
Add a test for IterateAsync
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Linq; using Microsoft.Xunit.Performance; using Xunit; namespace SimplePerfTests { public class Document { private string _text; public Document(string text) { _text = text; } public void Format() { _text = _text.ToUpper(); } public override string ToString() { return _text; } } public class FormattingTests { private static IEnumerable<object[]> MakeArgs(params object[] args) { return args.Select(arg => new object[] { arg }); } public static IEnumerable<object[]> FormatCurlyBracesMemberData = MakeArgs( new Document("Hello, world!") ); [Benchmark] [MemberData(nameof(FormatCurlyBracesMemberData))] public static void FormatCurlyBracesTest(Document document) { Benchmark.Iterate(document.Format); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Xunit.Performance; using Xunit; namespace SimplePerfTests { public class Document { private string _text; public Document(string text) { _text = text; } public void Format() { _text = _text.ToUpper(); } public Task FormatAsync() { Format(); return Task.CompletedTask; } public override string ToString() { return _text; } } public class FormattingTests { private static IEnumerable<object[]> MakeArgs(params object[] args) { return args.Select(arg => new object[] { arg }); } public static IEnumerable<object[]> FormatCurlyBracesMemberData = MakeArgs( new Document("Hello, world!") ); [Benchmark] [MemberData(nameof(FormatCurlyBracesMemberData))] public static void FormatCurlyBracesTest(Document document) { Benchmark.Iterate(document.Format); } [Benchmark] [MemberData(nameof(FormatCurlyBracesMemberData))] public static async Task FormatCurlyBracesTestAsync(Document document) { await Benchmark.IterateAsync(() => document.FormatAsync()); } } }
Add better test coverage of `SettingsPanel`
// 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.Framework.Allocation; using osu.Framework.Graphics.Containers; using osu.Game.Overlays; namespace osu.Game.Tests.Visual.Settings { [TestFixture] public class TestSceneSettingsPanel : OsuTestScene { private readonly SettingsPanel settings; private readonly DialogOverlay dialogOverlay; public TestSceneSettingsPanel() { settings = new SettingsOverlay { State = { Value = Visibility.Visible } }; Add(dialogOverlay = new DialogOverlay { Depth = -1 }); } [BackgroundDependencyLoader] private void load() { Dependencies.Cache(dialogOverlay); Add(settings); } } }
// 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.Framework.Allocation; using osu.Framework.Graphics.Containers; using osu.Framework.Testing; using osu.Game.Overlays; namespace osu.Game.Tests.Visual.Settings { [TestFixture] public class TestSceneSettingsPanel : OsuTestScene { private SettingsPanel settings; private DialogOverlay dialogOverlay; [SetUpSteps] public void SetUpSteps() { AddStep("create settings", () => { settings?.Expire(); Add(settings = new SettingsOverlay { State = { Value = Visibility.Visible } }); }); } [Test] public void ToggleVisibility() { AddWaitStep("wait some", 5); AddToggleStep("toggle editor visibility", visible => settings.ToggleVisibility()); } [BackgroundDependencyLoader] private void load() { Add(dialogOverlay = new DialogOverlay { Depth = -1 }); Dependencies.Cache(dialogOverlay); } } }
Update interface for ignored request policy
using System; namespace Glimpse.Agent.Web { public class IIgnoredRequestPolicy { } }
using System; namespace Glimpse.Agent.Web { public interface IIgnoredRequestPolicy { bool ShouldIgnore(IContext context); } }
Test case for calling try read with null values
using System; using Microsoft.BizTalk.Message.Interop; using Microsoft.VisualStudio.TestTools.UnitTesting; using Winterdom.BizTalk.PipelineTesting; namespace BizTalkComponents.Utils.Tests.UnitTests { [TestClass] public class ContextExtensionTests { private IBaseMessage _testMessage; [TestInitialize] public void InitializeTest() { _testMessage = MessageHelper.Create("<test></test>"); _testMessage.Context.Promote(new ContextProperty("http://testuri.org#SourceProperty"), "Value"); } [TestMethod] public void TryReadValidTest() { object val; Assert.IsTrue(_testMessage.Context.TryRead(new ContextProperty("http://testuri.org#SourceProperty"), out val)); Assert.AreEqual("Value", val.ToString()); } [TestMethod] public void TryReadInValidTest() { object val; Assert.IsFalse(_testMessage.Context.TryRead(new ContextProperty("http://testuri.org#NonExisting"), out val)); } } }
using System; using Microsoft.BizTalk.Message.Interop; using Microsoft.VisualStudio.TestTools.UnitTesting; using Winterdom.BizTalk.PipelineTesting; namespace BizTalkComponents.Utils.Tests.UnitTests { [TestClass] public class ContextExtensionTests { private IBaseMessage _testMessage; [TestInitialize] public void InitializeTest() { _testMessage = MessageHelper.Create("<test></test>"); _testMessage.Context.Promote(new ContextProperty("http://testuri.org#SourceProperty"), "Value"); } [TestMethod] public void TryReadValidTest() { object val; Assert.IsTrue(_testMessage.Context.TryRead(new ContextProperty("http://testuri.org#SourceProperty"), out val)); Assert.AreEqual("Value", val.ToString()); } [TestMethod] public void TryReadInValidTest() { object val; Assert.IsFalse(_testMessage.Context.TryRead(new ContextProperty("http://testuri.org#NonExisting"), out val)); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void TryReadInValidArgumentTest() { object val; _testMessage.Context.TryRead(null, out val); } } }
Put constructor initializers on their own line
// <copyright file="TJException.cs" company="Autonomic Systems, Quamotion"> // Copyright (c) Autonomic Systems. All rights reserved. // Copyright (c) Quamotion. All rights reserved. // </copyright> using System; namespace TurboJpegWrapper { // ReSharper disable once InconsistentNaming /// <summary> /// Exception thrown then internal error in the underlying turbo jpeg library is occured. /// </summary> public class TJException : Exception { /// <summary> /// Creates new instance of the <see cref="TJException"/> class. /// </summary> /// <param name="error">Error message from underlying turbo jpeg library.</param> public TJException(string error) : base(error) { } } }
// <copyright file="TJException.cs" company="Autonomic Systems, Quamotion"> // Copyright (c) Autonomic Systems. All rights reserved. // Copyright (c) Quamotion. All rights reserved. // </copyright> using System; namespace TurboJpegWrapper { // ReSharper disable once InconsistentNaming /// <summary> /// Exception thrown then internal error in the underlying turbo jpeg library is occured. /// </summary> public class TJException : Exception { /// <summary> /// Creates new instance of the <see cref="TJException"/> class. /// </summary> /// <param name="error">Error message from underlying turbo jpeg library.</param> public TJException(string error) : base(error) { } } }
Make sure the model isn't lost when navigating to/from the contact picker
using MobileKidsIdApp.Services; using System.Threading.Tasks; using System.Windows.Input; using Xamarin.Forms; using MobileKidsIdApp.Models; namespace MobileKidsIdApp.ViewModels { public class BasicDetails : ViewModelBase<Models.ChildDetails> { private ContactInfo _contact; public ICommand ChangeContactCommand { get; private set; } public BasicDetails(Models.ChildDetails details) { ChangeContactCommand = new Command(async () => { ContactInfo contact = await DependencyService.Get<IContactPicker>().GetSelectedContactInfo(); if (contact == null) { //Do nothing, user must have cancelled. } else { _contact = contact; Model.ContactId = contact.Id; //Only overwrite name fields if they were blank. if (string.IsNullOrEmpty(Model.FamilyName)) Model.FamilyName = contact.FamilyName; if (string.IsNullOrEmpty(Model.AdditionalName)) Model.AdditionalName = contact.AdditionalName; if (string.IsNullOrEmpty(Model.GivenName)) Model.GivenName = contact.GivenName; OnPropertyChanged(nameof(Contact)); } }); Model = details; } protected override async Task<ChildDetails> DoInitAsync() { _contact = await DependencyService.Get<IContactPicker>().GetContactInfoForId(Model.ContactId); return Model; } public ContactInfo Contact { get { return _contact; } } } }
using MobileKidsIdApp.Services; using System.Threading.Tasks; using System.Windows.Input; using Xamarin.Forms; using MobileKidsIdApp.Models; namespace MobileKidsIdApp.ViewModels { public class BasicDetails : ViewModelBase<Models.ChildDetails> { private ContactInfo _contact; public ICommand ChangeContactCommand { get; private set; } public BasicDetails(Models.ChildDetails details) { ChangeContactCommand = new Command(async () => { PrepareToShowModal(); ContactInfo contact = await DependencyService.Get<IContactPicker>().GetSelectedContactInfo(); if (contact == null) { //Do nothing, user must have cancelled. } else { _contact = contact; Model.ContactId = contact.Id; //Only overwrite name fields if they were blank. if (string.IsNullOrEmpty(Model.FamilyName)) Model.FamilyName = contact.FamilyName; if (string.IsNullOrEmpty(Model.AdditionalName)) Model.AdditionalName = contact.AdditionalName; if (string.IsNullOrEmpty(Model.GivenName)) Model.GivenName = contact.GivenName; OnPropertyChanged(nameof(Contact)); } }); Model = details; } protected override async Task<ChildDetails> DoInitAsync() { _contact = await DependencyService.Get<IContactPicker>().GetContactInfoForId(Model.ContactId); return Model; } public ContactInfo Contact { get { return _contact; } } } }
Update copyright year in template
<!DOCTYPE html> <html> <head> <title>@ViewData["Title"]</title> <link rel="icon" type="image/png" href="favicon.png"> <meta name="viewport" content="width=device-width,initial-scale=1"> <link rel="stylesheet" href="~/style.css"/> </head> <body> <div class="container"> <header> <nav class="navbar navbar-default"> <a class="navbar-brand" href="~/"><img src="images/logo-transparent-dark.svg"/></a> <ul class="nav navbar-nav"> <li><a href="~/">Logs</a></li> <li><a href="~/resources">Resources</a> </ul> </nav> </header> <div id="main" role="main"> @RenderBody() </div> <footer>© 2014&ndash;2018 <a href="https://github.com/codingteam/codingteam.org.ru">codingteam</a></footer> </div> </body> </html>
<!DOCTYPE html> <html> <head> <title>@ViewData["Title"]</title> <link rel="icon" type="image/png" href="favicon.png"> <meta name="viewport" content="width=device-width,initial-scale=1"> <link rel="stylesheet" href="~/style.css"/> </head> <body> <div class="container"> <header> <nav class="navbar navbar-default"> <a class="navbar-brand" href="~/"><img src="images/logo-transparent-dark.svg"/></a> <ul class="nav navbar-nav"> <li><a href="~/">Logs</a></li> <li><a href="~/resources">Resources</a> </ul> </nav> </header> <div id="main" role="main"> @RenderBody() </div> <footer>© 2019 <a href="https://github.com/codingteam/codingteam.org.ru">codingteam</a></footer> </div> </body> </html>
Remove ignore attribute from now fixed test scene
// 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 NUnit.Framework; using osu.Framework.Extensions.IEnumerableExtensions; using osu.Framework.Graphics.Containers; using osu.Framework.Screens; using osu.Framework.Testing; using osu.Game.Screens.Play.HUD; using osu.Game.Skinning; using osu.Game.Tests.Visual; using osuTK; namespace osu.Game.Rulesets.Catch.Tests { [TestFixture] public class TestSceneCatchPlayerLegacySkin : LegacySkinPlayerTestScene { protected override Ruleset CreatePlayerRuleset() => new CatchRuleset(); [Test] [Ignore("HUD components broken, remove when fixed.")] public void TestLegacyHUDComboCounterHidden([Values] bool withModifiedSkin) { if (withModifiedSkin) { AddStep("change component scale", () => Player.ChildrenOfType<LegacyScoreCounter>().First().Scale = new Vector2(2f)); AddStep("update target", () => Player.ChildrenOfType<SkinnableTargetContainer>().ForEach(LegacySkin.UpdateDrawableTarget)); AddStep("exit player", () => Player.Exit()); CreateTest(null); } AddAssert("legacy HUD combo counter hidden", () => { return Player.ChildrenOfType<LegacyComboCounter>().All(c => !c.ChildrenOfType<Container>().Single().IsPresent); }); } } }
// 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 NUnit.Framework; using osu.Framework.Extensions.IEnumerableExtensions; using osu.Framework.Graphics.Containers; using osu.Framework.Screens; using osu.Framework.Testing; using osu.Game.Screens.Play.HUD; using osu.Game.Skinning; using osu.Game.Tests.Visual; using osuTK; namespace osu.Game.Rulesets.Catch.Tests { [TestFixture] public class TestSceneCatchPlayerLegacySkin : LegacySkinPlayerTestScene { protected override Ruleset CreatePlayerRuleset() => new CatchRuleset(); [Test] public void TestLegacyHUDComboCounterHidden([Values] bool withModifiedSkin) { if (withModifiedSkin) { AddStep("change component scale", () => Player.ChildrenOfType<LegacyScoreCounter>().First().Scale = new Vector2(2f)); AddStep("update target", () => Player.ChildrenOfType<SkinnableTargetContainer>().ForEach(LegacySkin.UpdateDrawableTarget)); AddStep("exit player", () => Player.Exit()); CreateTest(null); } AddAssert("legacy HUD combo counter hidden", () => { return Player.ChildrenOfType<LegacyComboCounter>().All(c => c.ChildrenOfType<Container>().Single().Alpha == 0f); }); } } }
Fix create BitmapDecoder with async file stream.
using System; using System.IO; using System.Runtime.InteropServices; namespace JemlemlacuLemjakarbabo { class Program { static void Main(string[] args) { CheckHResult(UnsafeNativeMethods.WICCodec.CreateImagingFactory(UnsafeNativeMethods.WICCodec.WINCODEC_SDK_VERSION, out var pImagingFactory)); using var fs = new FileStream("image.jpg", FileMode.Open, FileAccess.Read, FileShare.Read, 4096, FileOptions.Asynchronous); Guid vendorMicrosoft = new Guid(MILGuidData.GUID_VendorMicrosoft); UInt32 metadataFlags = (uint)WICMetadataCacheOptions.WICMetadataCacheOnDemand; CheckHResult ( UnsafeNativeMethods.WICImagingFactory.CreateDecoderFromFileHandle ( pImagingFactory, fs.SafeFileHandle, ref vendorMicrosoft, metadataFlags, out var decoder ) ); } static void CheckHResult(int hr) { if (hr < 0) { Exception exceptionForHR = Marshal.GetExceptionForHR(hr, (IntPtr)(-1)); throw exceptionForHR; } } } }
using System; using System.IO; using System.Runtime.InteropServices; using Microsoft.Win32.SafeHandles; namespace JemlemlacuLemjakarbabo { class Program { static void Main(string[] args) { CheckHResult(UnsafeNativeMethods.WICCodec.CreateImagingFactory(UnsafeNativeMethods.WICCodec.WINCODEC_SDK_VERSION, out var pImagingFactory)); using var fs = new FileStream("image.jpg", FileMode.Open, FileAccess.Read, FileShare.Read, 4096, FileOptions.Asynchronous); var stream = fs; SafeFileHandle safeFilehandle System.IO.FileStream filestream = stream as System.IO.FileStream; try { if (filestream.IsAsync is false) { safeFilehandle = filestream.SafeFileHandle; } else { // If Filestream is async that doesn't support IWICImagingFactory_CreateDecoderFromFileHandle_Proxy, then revert to old code path. safeFilehandle = null; } } catch { // If Filestream doesn't support SafeHandle then revert to old code path. // See https://github.com/dotnet/wpf/issues/4355 safeFilehandle = null; } Guid vendorMicrosoft = new Guid(MILGuidData.GUID_VendorMicrosoft); UInt32 metadataFlags = (uint)WICMetadataCacheOptions.WICMetadataCacheOnDemand; CheckHResult ( UnsafeNativeMethods.WICImagingFactory.CreateDecoderFromFileHandle ( pImagingFactory, fs.SafeFileHandle, ref vendorMicrosoft, metadataFlags, out var decoder ) ); } static void CheckHResult(int hr) { if (hr < 0) { Exception exceptionForHR = Marshal.GetExceptionForHR(hr, (IntPtr)(-1)); throw exceptionForHR; } } } }
Remove extra loadImage callback until we discuss it
using System.Runtime.InteropServices; using System.Windows.Forms; using ExcelDna.Integration.CustomUI; namespace Ribbon { [ComVisible(true)] public class RibbonController : ExcelRibbon { public override string GetCustomUI(string RibbonID) { return @" <customUI xmlns='http://schemas.microsoft.com/office/2006/01/customui' loadImage='LoadImage'> <ribbon> <tabs> <tab id='tab1' label='My Tab'> <group id='group1' label='My Group'> <button id='button1' label='My Button' onAction='OnButtonPressed'/> </group > </tab> </tabs> </ribbon> </customUI>"; } public void OnButtonPressed(IRibbonControl control) { MessageBox.Show("Hello from control " + control.Id); DataWriter.WriteData(); } } }
using System.Runtime.InteropServices; using System.Windows.Forms; using ExcelDna.Integration.CustomUI; namespace Ribbon { [ComVisible(true)] public class RibbonController : ExcelRibbon { public override string GetCustomUI(string RibbonID) { return @" <customUI xmlns='http://schemas.microsoft.com/office/2006/01/customui'> <ribbon> <tabs> <tab id='tab1' label='My Tab'> <group id='group1' label='My Group'> <button id='button1' label='My Button' onAction='OnButtonPressed'/> </group > </tab> </tabs> </ribbon> </customUI>"; } public void OnButtonPressed(IRibbonControl control) { MessageBox.Show("Hello from control " + control.Id); DataWriter.WriteData(); } } }
Test Refactor, consolidate Evaluate Add tests
namespace ClojSharp.Core.Tests { using System; using System.Collections.Generic; using System.Linq; using System.Text; using ClojSharp.Core.Compiler; using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] public class EvaluateTests { private Machine machine; [TestInitialize] public void Setup() { this.machine = new Machine(); } [TestMethod] public void EvaluateInteger() { Assert.AreEqual(123, this.Evaluate("123", null)); } [TestMethod] public void EvaluateSymbolInContext() { Context context = new Context(); context.SetValue("one", 1); Assert.AreEqual(1, this.Evaluate("one", context)); } [TestMethod] public void EvaluateAddTwoIntegers() { Assert.AreEqual(3, this.Evaluate("(+ 1 2)", this.machine.RootContext)); } [TestMethod] public void EvaluateAddThreeIntegers() { Assert.AreEqual(6, this.Evaluate("(+ 1 2 3)", this.machine.RootContext)); } [TestMethod] public void EvaluateOneInteger() { Assert.AreEqual(5, this.Evaluate("(+ 5)", this.machine.RootContext)); } [TestMethod] public void EvaluateNoInteger() { Assert.AreEqual(0, this.Evaluate("(+)", this.machine.RootContext)); } private object Evaluate(string text, Context context) { Parser parser = new Parser(text); var expr = parser.ParseExpression(); Assert.IsNull(parser.ParseExpression()); return this.machine.Evaluate(expr, context); } } }
namespace ClojSharp.Core.Tests { using System; using System.Collections.Generic; using System.Linq; using System.Text; using ClojSharp.Core.Compiler; using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] public class EvaluateTests { private Machine machine; [TestInitialize] public void Setup() { this.machine = new Machine(); } [TestMethod] public void EvaluateInteger() { Assert.AreEqual(123, this.Evaluate("123", null)); } [TestMethod] public void EvaluateSymbolInContext() { Context context = new Context(); context.SetValue("one", 1); Assert.AreEqual(1, this.Evaluate("one", context)); } [TestMethod] public void EvaluateAdd() { Assert.AreEqual(3, this.Evaluate("(+ 1 2)", this.machine.RootContext)); Assert.AreEqual(6, this.Evaluate("(+ 1 2 3)", this.machine.RootContext)); Assert.AreEqual(5, this.Evaluate("(+ 5)", this.machine.RootContext)); Assert.AreEqual(0, this.Evaluate("(+)", this.machine.RootContext)); } private object Evaluate(string text, Context context) { Parser parser = new Parser(text); var expr = parser.ParseExpression(); Assert.IsNull(parser.ParseExpression()); return this.machine.Evaluate(expr, context); } } }
Reset live tokens value when it can not be saved
using System; using System.Diagnostics; using StreamCompanionTypes.DataTypes; using StreamCompanionTypes.Enums; namespace OsuMemoryEventSource { public class LiveToken { public IToken Token { get; set; } public Func<object> Updater; public bool IsLazy { get; set; } protected Lazy<object> Lazy = new Lazy<object>(); public LiveToken(IToken token, Func<object> updater) { Token = token; Updater = updater; _ = Lazy.Value; } public void Update(OsuStatus status = OsuStatus.All) { if (!Token.CanSave(status) || Updater == null) { return; } if (IsLazy) { if (Lazy.IsValueCreated) { Token.Value = Lazy = new Lazy<object>(Updater); } } else { Token.Value = Updater(); } } } }
using System; using System.Diagnostics; using StreamCompanionTypes.DataTypes; using StreamCompanionTypes.Enums; namespace OsuMemoryEventSource { public class LiveToken { public IToken Token { get; set; } public Func<object> Updater; public bool IsLazy { get; set; } protected Lazy<object> Lazy = new Lazy<object>(); public LiveToken(IToken token, Func<object> updater) { Token = token; Updater = updater; _ = Lazy.Value; } public void Update(OsuStatus status = OsuStatus.All) { if (!Token.CanSave(status) || Updater == null) { Token.Reset(); return; } if (IsLazy) { if (Lazy.IsValueCreated) { Token.Value = Lazy = new Lazy<object>(Updater); } } else { Token.Value = Updater(); } } } }
Enable overriding of settings via command line arguments in the formats: /SettingName=value /SettingName:value
// Copyright 2007-2010 The Apache Software Foundation. // // 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. namespace dropkick.Settings { using System; using System.IO; using Magnum.Configuration; public class SettingsParser { public T Parse<T>(FileInfo file, string commandLine, string environment) where T : new() { return (T)Parse(typeof (T), file, commandLine, environment); } public object Parse(Type t, FileInfo file, string commandLine, string environment) { var binder = ConfigurationBinderFactory.New(c => { //c.AddJsonFile("global.conf"); //c.AddJsonFile("{0}.conf".FormatWith(environment)); //c.AddJsonFile(file.FullName); var content = File.ReadAllText(file.FullName); c.AddJson(content); //c.AddCommandLine(commandLine); }); object result = binder.Bind(t); return result; } } }
// Copyright 2007-2010 The Apache Software Foundation. // // 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. namespace dropkick.Settings { using System; using System.IO; using Magnum.Configuration; public class SettingsParser { public T Parse<T>(FileInfo file, string commandLine, string environment) where T : new() { return (T)Parse(typeof (T), file, commandLine, environment); } public object Parse(Type t, FileInfo file, string commandLine, string environment) { var binder = ConfigurationBinderFactory.New(c => { //c.AddJsonFile("global.conf"); //c.AddJsonFile("{0}.conf".FormatWith(environment)); //c.AddJsonFile(file.FullName); var content = File.ReadAllText(file.FullName); c.AddJson(content); c.AddCommandLine(commandLine); }); object result = binder.Bind(t); return result; } } }
Put performance test into separate method in console.
using System; using System.Collections.Generic; using Arango.Client; using Arango.fastJSON; namespace Arango.ConsoleTests { class Program { public static void Main(string[] args) { var performance = new Performance(); //performance.TestSimpleSequentialHttpPostRequests(); //performance.TestRestSharpHttpPostRequests(); //performance.TestSimpleParallelHttpPostRequests(); performance.Dispose(); Console.Write("Press any key to continue . . . "); Console.ReadKey(true); } } }
using System; using System.Collections.Generic; using Arango.Client; using Arango.fastJSON; namespace Arango.ConsoleTests { class Program { public static void Main(string[] args) { //PerformanceTests(); Console.Write("Press any key to continue . . . "); Console.ReadKey(true); } static void PerformanceTests() { var performance = new Performance(); //performance.TestSimpleSequentialHttpPostRequests(); //performance.TestRestSharpHttpPostRequests(); //performance.TestSimpleParallelHttpPostRequests(); performance.Dispose(); } } }
Fix "rate app" button in the about page.
// Copyright (c) PocketCampus.Org 2014-15 // See LICENSE file for more details // File author: Solal Pirelli using System; using Windows.ApplicationModel; using Windows.System; namespace PocketCampus.Main.Services { public sealed class AppRatingService : IAppRatingService { public async void RequestRating() { await Launcher.LaunchUriAsync( new Uri( "ms-windows-store:REVIEW?PFN=" + Package.Current.Id.FamilyName ) ); } } }
// Copyright (c) PocketCampus.Org 2014-15 // See LICENSE file for more details // File author: Solal Pirelli using System; using Windows.System; namespace PocketCampus.Main.Services { public sealed class AppRatingService : IAppRatingService { private const string AppId = "28f8300e-8a84-4e3e-8d68-9a07c5b2a83a"; public async void RequestRating() { // FRAMEWORK BUG: This seems to be the only correct way to do it. // Despite MSDN documentation, other ways (e.g. reviewapp without appid, or REVIEW?PFN=) open Xbox Music... await Launcher.LaunchUriAsync( new Uri( "ms-windows-store:reviewapp?appid=" + AppId, UriKind.Absolute ) ); } } }
Make the SUTA edit text form bigger
@model BatteryCommander.Web.Commands.UpdateSUTARequest @using (Html.BeginForm("Edit", "SUTA", new { Model.Id }, FormMethod.Post, true, new { @class = "form-horizontal", role = "form" })) { @Html.AntiForgeryToken() @Html.ValidationSummary() <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.Body.Supervisor) @Html.DropDownListFor(model => model.Body.Supervisor, (IEnumerable<SelectListItem>)ViewBag.Supervisors) </div> <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.Body.StartDate) @Html.EditorFor(model => model.Body.StartDate) </div> <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.Body.EndDate) @Html.EditorFor(model => model.Body.EndDate) </div> <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.Body.Reasoning) @Html.TextAreaFor(model => model.Body.Reasoning, new { cols="40", rows="5" }) </div> <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.Body.MitigationPlan) @Html.TextAreaFor(model => model.Body.MitigationPlan, new { cols="40", rows="5" }) </div> <button type="submit">Save</button> }
@model BatteryCommander.Web.Commands.UpdateSUTARequest @using (Html.BeginForm("Edit", "SUTA", new { Model.Id }, FormMethod.Post, true, new { @class = "form-horizontal", role = "form" })) { @Html.AntiForgeryToken() @Html.ValidationSummary() <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.Body.Supervisor) @Html.DropDownListFor(model => model.Body.Supervisor, (IEnumerable<SelectListItem>)ViewBag.Supervisors) </div> <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.Body.StartDate) @Html.EditorFor(model => model.Body.StartDate) </div> <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.Body.EndDate) @Html.EditorFor(model => model.Body.EndDate) </div> <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.Body.Reasoning) @Html.TextAreaFor(model => model.Body.Reasoning, new { cols="40", rows="5" }) </div> <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.Body.MitigationPlan) @Html.TextAreaFor(model => model.Body.MitigationPlan, new { cols="40", rows="5" }) </div> <button type="submit">Save</button> }
Add tag for Scene logs; Code alignment;
using UnityEngine; using System.Collections; namespace UDBase.Components.Log { public class LogTags { public const int Common = 1; public const int UI = 2; string[] _names = new string[]{"Common", "UI"}; public virtual string GetName(int index) { switch( index ) { case Common: { return "Common"; } case UI: { return "UI"; } } return "Unknown"; } public virtual string[] GetNames() { return _names; } } }
using UnityEngine; using System.Collections; namespace UDBase.Components.Log { public class LogTags { public const int Common = 1; public const int UI = 2; public const int Scene = 3; string[] _names = new string[]{"Common", "UI", "Scene"}; public virtual string GetName(int index) { switch( index ) { case Common : return "Common"; case UI : return "UI"; case Scene : return "Scene"; } return "Unknown"; } public virtual string[] GetNames() { return _names; } } }
Fix of LocalChecker sometimes loopback could be already part of dictionary throwing exception on duplicate add.
using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; namespace Nowin { public class IpIsLocalChecker : IIpIsLocalChecker { readonly Dictionary<IPAddress, bool> _dict; public IpIsLocalChecker() { var host = Dns.GetHostEntry(Dns.GetHostName()); _dict=host.AddressList.Where( a => a.AddressFamily == AddressFamily.InterNetwork || a.AddressFamily == AddressFamily.InterNetworkV6). ToDictionary(p => p, p => true); _dict.Add(IPAddress.Loopback,true); _dict.Add(IPAddress.IPv6Loopback,true); } public bool IsLocal(IPAddress address) { return _dict.ContainsKey(address); } } }
using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; namespace Nowin { public class IpIsLocalChecker : IIpIsLocalChecker { readonly Dictionary<IPAddress, bool> _dict; public IpIsLocalChecker() { var host = Dns.GetHostEntry(Dns.GetHostName()); _dict = host.AddressList.Where( a => a.AddressFamily == AddressFamily.InterNetwork || a.AddressFamily == AddressFamily.InterNetworkV6). ToDictionary(p => p, p => true); _dict[IPAddress.Loopback] = true; _dict[IPAddress.IPv6Loopback] = true; } public bool IsLocal(IPAddress address) { return _dict.ContainsKey(address); } } }
Change logger type for NLog error messages to be based on exception if possible
using System; using System.Collections.Generic; using System.Diagnostics; using FubuCore; using FubuCore.Descriptions; using FubuCore.Logging; using FubuCore.Util; using NLog; using Logger = NLog.Logger; namespace FubuMVC.NLog { public class NLogListener : ILogListener { private readonly Cache<Type, Logger> _logger; public NLogListener() { _logger = new Cache<Type, Logger>(x => LogManager.GetLogger(x.FullName)); } public bool IsDebugEnabled { get { return true; } } public bool IsInfoEnabled { get { return true; } } public void Debug(string message) { DebugMessage(message); } public void DebugMessage(object message) { _logger[message.GetType()].Debug(Description.For(message)); } public void Error(string message, Exception ex) { _logger[message.GetType()].ErrorException(message, ex); } public void Error(object correlationId, string message, Exception ex) { Error(message, ex); } public void Info(string message) { InfoMessage(message); } public void InfoMessage(object message) { _logger[message.GetType()].Info(Description.For(message)); } public bool ListensFor(Type type) { return true; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using FubuCore; using FubuCore.Descriptions; using FubuCore.Logging; using FubuCore.Util; using NLog; using Logger = NLog.Logger; namespace FubuMVC.NLog { public class NLogListener : ILogListener { private readonly Cache<Type, Logger> _logger; public NLogListener() { _logger = new Cache<Type, Logger>(x => LogManager.GetLogger(x.FullName)); } public bool IsDebugEnabled { get { return true; } } public bool IsInfoEnabled { get { return true; } } public void Debug(string message) { DebugMessage(message); } public void DebugMessage(object message) { _logger[message.GetType()].Debug(Description.For(message)); } public void Error(string message, Exception ex) { var loggerType = ex != null ? ex.GetType() : message.GetType(); _logger[loggerType].ErrorException(message, ex); } public void Error(object correlationId, string message, Exception ex) { Error(message, ex); } public void Info(string message) { InfoMessage(message); } public void InfoMessage(object message) { _logger[message.GetType()].Info(Description.For(message)); } public bool ListensFor(Type type) { return true; } } }
Add warmup attribute to test runner factory
namespace Moya.Runner.Factories { using System; using System.Collections.Generic; using Attributes; using Exceptions; using Extensions; using Moya.Utility; using Runners; public class TestRunnerFactory : ITestRunnerFactory { private readonly IDictionary<Type, Type> attributeTestRunnerMapping = new Dictionary<Type, Type> { { typeof(StressAttribute), typeof(StressTestRunner) } }; public ITestRunner GetTestRunnerForAttribute(Type type) { if (!Reflection.TypeIsMoyaAttribute(type)) { throw new MoyaException("Unable to provide moya test runner for type {0}".FormatWith(type)); } Type typeOfTestRunner = attributeTestRunnerMapping[type]; ITestRunner instance = (ITestRunner)Activator.CreateInstance(typeOfTestRunner); ITestRunner timerDecoratedInstance = new TimerDecorator(instance); return timerDecoratedInstance; } } }
namespace Moya.Runner.Factories { using System; using System.Collections.Generic; using Attributes; using Exceptions; using Extensions; using Moya.Utility; using Runners; public class TestRunnerFactory : ITestRunnerFactory { private readonly IDictionary<Type, Type> attributeTestRunnerMapping = new Dictionary<Type, Type> { { typeof(StressAttribute), typeof(StressTestRunner) }, { typeof(WarmupAttribute), typeof(WarmupTestRunner) }, }; public ITestRunner GetTestRunnerForAttribute(Type type) { if (!Reflection.TypeIsMoyaAttribute(type)) { throw new MoyaException("Unable to provide moya test runner for type {0}".FormatWith(type)); } Type typeOfTestRunner = attributeTestRunnerMapping[type]; ITestRunner instance = (ITestRunner)Activator.CreateInstance(typeOfTestRunner); ITestRunner timerDecoratedInstance = new TimerDecorator(instance); return timerDecoratedInstance; } } }
Fix title of match song select
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using osu.Game.Online.Multiplayer; using osu.Game.Screens.Multi; namespace osu.Game.Screens.Select { public class MatchSongSelect : SongSelect, IMultiplayerScreen { public Action<PlaylistItem> Selected; public string ShortTitle => "song selection"; protected override bool OnStart() { var item = new PlaylistItem { Beatmap = Beatmap.Value.BeatmapInfo, Ruleset = Ruleset.Value, RulesetID = Ruleset.Value.ID ?? 0 }; item.RequiredMods.AddRange(SelectedMods.Value); Selected?.Invoke(item); if (IsCurrentScreen) Exit(); return true; } } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using Humanizer; using osu.Game.Online.Multiplayer; using osu.Game.Screens.Multi; namespace osu.Game.Screens.Select { public class MatchSongSelect : SongSelect, IMultiplayerScreen { public Action<PlaylistItem> Selected; public string ShortTitle => "song selection"; public override string Title => ShortTitle.Humanize(); protected override bool OnStart() { var item = new PlaylistItem { Beatmap = Beatmap.Value.BeatmapInfo, Ruleset = Ruleset.Value, RulesetID = Ruleset.Value.ID ?? 0 }; item.RequiredMods.AddRange(SelectedMods.Value); Selected?.Invoke(item); if (IsCurrentScreen) Exit(); return true; } } }
Use correct lookup type to ensure username based lookups always prefer username
// 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.Users; using osu.Game.Rulesets; namespace osu.Game.Online.API.Requests { public class GetUserRequest : APIRequest<User> { private readonly string userIdentifier; public readonly RulesetInfo Ruleset; /// <summary> /// Gets the currently logged-in user. /// </summary> public GetUserRequest() { } /// <summary> /// Gets a user from their ID. /// </summary> /// <param name="userId">The user to get.</param> /// <param name="ruleset">The ruleset to get the user's info for.</param> public GetUserRequest(long? userId = null, RulesetInfo ruleset = null) { this.userIdentifier = userId.ToString(); Ruleset = ruleset; } /// <summary> /// Gets a user from their username. /// </summary> /// <param name="username">The user to get.</param> /// <param name="ruleset">The ruleset to get the user's info for.</param> public GetUserRequest(string username = null, RulesetInfo ruleset = null) { this.userIdentifier = username; Ruleset = ruleset; } protected override string Target => userIdentifier != null ? $@"users/{userIdentifier}/{Ruleset?.ShortName}" : $@"me/{Ruleset?.ShortName}"; } }
// 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.Users; using osu.Game.Rulesets; namespace osu.Game.Online.API.Requests { public class GetUserRequest : APIRequest<User> { private readonly string lookup; public readonly RulesetInfo Ruleset; private readonly LookupType lookupType; /// <summary> /// Gets the currently logged-in user. /// </summary> public GetUserRequest() { } /// <summary> /// Gets a user from their ID. /// </summary> /// <param name="userId">The user to get.</param> /// <param name="ruleset">The ruleset to get the user's info for.</param> public GetUserRequest(long? userId = null, RulesetInfo ruleset = null) { lookup = userId.ToString(); lookupType = LookupType.Id; Ruleset = ruleset; } /// <summary> /// Gets a user from their username. /// </summary> /// <param name="username">The user to get.</param> /// <param name="ruleset">The ruleset to get the user's info for.</param> public GetUserRequest(string username = null, RulesetInfo ruleset = null) { lookup = username; lookupType = LookupType.Username; Ruleset = ruleset; } protected override string Target => lookup != null ? $@"users/{lookup}/{Ruleset?.ShortName}?k={lookupType.ToString().ToLower()}" : $@"me/{Ruleset?.ShortName}"; private enum LookupType { Id, Username } } }
Replace two xml comment instances of 'OmitOnRecursionGuard' with 'RecursionGuard'
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Ploeh.AutoFixture.Kernel; namespace Ploeh.AutoFixture { /// <summary> /// Decorates an <see cref="ISpecimenBuilder" /> with a /// <see cref="OmitOnRecursionGuard" />. /// </summary> public class OmitOnRecursionBehavior : ISpecimenBuilderTransformation { /// <summary> /// Decorates the supplied <see cref="ISpecimenBuilder" /> with an /// <see cref="OmitOnRecursionGuard"/>. /// </summary> /// <param name="builder">The builder to decorate.</param> /// <returns> /// <paramref name="builder" /> decorated with an /// <see cref="RecursionGuard" />. /// </returns> public ISpecimenBuilder Transform(ISpecimenBuilder builder) { if (builder == null) throw new ArgumentNullException("builder"); return new RecursionGuard(builder, new OmitOnRecursionHandler()); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Ploeh.AutoFixture.Kernel; namespace Ploeh.AutoFixture { /// <summary> /// Decorates an <see cref="ISpecimenBuilder" /> with a /// <see cref="RecursionGuard" />. /// </summary> public class OmitOnRecursionBehavior : ISpecimenBuilderTransformation { /// <summary> /// Decorates the supplied <see cref="ISpecimenBuilder" /> with an /// <see cref="RecursionGuard"/>. /// </summary> /// <param name="builder">The builder to decorate.</param> /// <returns> /// <paramref name="builder" /> decorated with an /// <see cref="RecursionGuard" />. /// </returns> public ISpecimenBuilder Transform(ISpecimenBuilder builder) { if (builder == null) throw new ArgumentNullException("builder"); return new RecursionGuard(builder, new OmitOnRecursionHandler()); } } }
Rename some classes to better match the service API.
using System; using System.Threading.Tasks; namespace DanTup.DartAnalysis { class VersionRequest : Request<Response<VersionResponse>> { public string method = "server.getVersion"; } class VersionResponse { public string version = null; } public static class VersionRequestImplementation { public static async Task<Version> GetServerVersion(this DartAnalysisService service) { var response = await service.Service.Send(new VersionRequest()); return Version.Parse(response.result.version); } } }
using System; using System.Threading.Tasks; namespace DanTup.DartAnalysis { class ServerVersionRequest : Request<Response<ServerVersionResponse>> { public string method = "server.getVersion"; } class ServerVersionResponse { public string version = null; } public static class ServerVersionRequestImplementation { public static async Task<Version> GetServerVersion(this DartAnalysisService service) { var response = await service.Service.Send(new ServerVersionRequest()); return Version.Parse(response.result.version); } } }
Add a non-generic object cache
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Threading.Tasks; namespace Microsoft.Fx.Portability { public interface IObjectCache<TObject> : IDisposable { TObject Value { get; } DateTimeOffset LastUpdated { get; } Task UpdateAsync(); } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Threading.Tasks; namespace Microsoft.Fx.Portability { public interface IObjectCache : IDisposable { Task UpdateAsync(); DateTimeOffset LastUpdated { get; } } public interface IObjectCache<TObject> : IObjectCache { TObject Value { get; } } }
Add Mouse Look Tracking to player character
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerMovement : MonoBehaviour { public float movementSpeed = 1.0f; // Use this for initialization void Start () { } // Update is called once per frame void Update () { var x = Input.GetAxis("Horizontal") * Time.deltaTime * movementSpeed; var z = Input.GetAxis("Vertical") * Time.deltaTime * movementSpeed; transform.Translate(x, 0, z); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerMovement : MonoBehaviour { public float movementSpeed = 1.0f; private bool isMovementLocked = false; // Use this for initialization void Start () { } // Update is called once per frame void Update () { look(); if (isMovementLocked) { movement(); } } private void look() { var ray = Camera.main.ScreenToWorldPoint(Input.mousePosition); Debug.DrawRay(Camera.main.transform.position, ray, Color.yellow); transform.LookAt(ray, new Vector3(0, 0, -1)); transform.eulerAngles = new Vector3(0, transform.eulerAngles.y, 0); } private void movement() { var x = Input.GetAxis("Horizontal") * Time.deltaTime * movementSpeed; var z = Input.GetAxis("Vertical") * Time.deltaTime * movementSpeed; transform.Translate(x, 0, z, Space.World); } }
Use property instead of member
using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using WalletWasabi.Backend.Models; using WalletWasabi.Interfaces; namespace WalletWasabi.WebClients.SmartBit { public class SmartBitExchangeRateProvider : IExchangeRateProvider { private SmartBitClient _client; public SmartBitExchangeRateProvider(SmartBitClient smartBitClient) { _client = smartBitClient; } public async Task<List<ExchangeRate>> GetExchangeRateAsync() { var rates = await _client.GetExchangeRatesAsync(CancellationToken.None); var rate = rates.Single(x => x.Code == "USD"); var exchangeRates = new List<ExchangeRate> { new ExchangeRate { Rate = rate.Rate, Ticker = "USD" }, }; return exchangeRates; } } }
using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using WalletWasabi.Backend.Models; using WalletWasabi.Interfaces; namespace WalletWasabi.WebClients.SmartBit { public class SmartBitExchangeRateProvider : IExchangeRateProvider { private SmartBitClient Client { get; } public SmartBitExchangeRateProvider(SmartBitClient smartBitClient) { Client = smartBitClient; } public async Task<List<ExchangeRate>> GetExchangeRateAsync() { var rates = await Client.GetExchangeRatesAsync(CancellationToken.None); var rate = rates.Single(x => x.Code == "USD"); var exchangeRates = new List<ExchangeRate> { new ExchangeRate { Rate = rate.Rate, Ticker = "USD" }, }; return exchangeRates; } } }
Make virtual tracks reeeeeeeaaally long
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using osu.Framework.Timing; namespace osu.Framework.Audio.Track { public class TrackVirtual : Track { private readonly StopwatchClock clock = new StopwatchClock(); private double seekOffset; public override bool Seek(double seek) { double current = CurrentTime; seekOffset = seek; lock (clock) clock.Restart(); if (Length > 0 && seekOffset > Length) seekOffset = Length; return current != seekOffset; } public override void Start() { lock (clock) clock.Start(); } public override void Reset() { lock (clock) clock.Reset(); seekOffset = 0; base.Reset(); } public override void Stop() { lock (clock) clock.Stop(); } public override bool IsRunning { get { lock (clock) return clock.IsRunning; } } public override bool HasCompleted { get { lock (clock) return base.HasCompleted || IsLoaded && !IsRunning && CurrentTime >= Length; } } public override double CurrentTime { get { lock (clock) return seekOffset + clock.CurrentTime; } } public override void Update() { lock (clock) { if (CurrentTime >= Length) Stop(); } } } }
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using osu.Framework.Timing; namespace osu.Framework.Audio.Track { public class TrackVirtual : Track { private readonly StopwatchClock clock = new StopwatchClock(); private double seekOffset; public TrackVirtual() { Length = double.MaxValue; } public override bool Seek(double seek) { double current = CurrentTime; seekOffset = seek; lock (clock) clock.Restart(); if (Length > 0 && seekOffset > Length) seekOffset = Length; return current != seekOffset; } public override void Start() { lock (clock) clock.Start(); } public override void Reset() { lock (clock) clock.Reset(); seekOffset = 0; base.Reset(); } public override void Stop() { lock (clock) clock.Stop(); } public override bool IsRunning { get { lock (clock) return clock.IsRunning; } } public override bool HasCompleted { get { lock (clock) return base.HasCompleted || IsLoaded && !IsRunning && CurrentTime >= Length; } } public override double CurrentTime { get { lock (clock) return seekOffset + clock.CurrentTime; } } public override void Update() { lock (clock) { if (CurrentTime >= Length) Stop(); } } } }
Make taskbar jump list show last part of path (folder name)
using System.Windows; using System.Windows.Shell; using GitMind.ApplicationHandling.SettingsHandling; namespace GitMind.Common { public class JumpListService { private static readonly int MaxTitleLength = 25; public void Add(string workingFolder) { JumpList jumpList = JumpList.GetJumpList(Application.Current) ?? new JumpList(); string title = workingFolder.Length < MaxTitleLength ? workingFolder : "..." + workingFolder.Substring(workingFolder.Length - MaxTitleLength); JumpTask jumpTask = new JumpTask(); jumpTask.Title = title; jumpTask.ApplicationPath = ProgramPaths.GetInstallFilePath(); jumpTask.Arguments = $"/d:\"{workingFolder}\""; jumpTask.IconResourcePath = ProgramPaths.GetInstallFilePath(); jumpTask.Description = workingFolder; jumpList.ShowRecentCategory = true; JumpList.AddToRecentCategory(jumpTask); JumpList.SetJumpList(Application.Current, jumpList); } } }
using System.IO; using System.Windows; using System.Windows.Shell; using GitMind.ApplicationHandling.SettingsHandling; namespace GitMind.Common { public class JumpListService { private static readonly int MaxTitleLength = 25; public void Add(string workingFolder) { JumpList jumpList = JumpList.GetJumpList(Application.Current) ?? new JumpList(); string folderName = Path.GetFileName(workingFolder) ?? workingFolder; string title = folderName.Length < MaxTitleLength ? folderName : folderName.Substring(0, MaxTitleLength) + "..."; JumpTask jumpTask = new JumpTask(); jumpTask.Title = title; jumpTask.ApplicationPath = ProgramPaths.GetInstallFilePath(); jumpTask.Arguments = $"/d:\"{workingFolder}\""; jumpTask.IconResourcePath = ProgramPaths.GetInstallFilePath(); jumpTask.Description = workingFolder; jumpList.ShowRecentCategory = true; JumpList.AddToRecentCategory(jumpTask); JumpList.SetJumpList(Application.Current, jumpList); } } }
Use the .Data propertry as opposed to GetData in this PartialView
@inherits UmbracoViewPage<BlockListModel> @using ContentModels = Umbraco.Web.PublishedModels; @using Umbraco.Core.Models.Blocks @{ if (Model?.Layout == null || !Model.Layout.Any()) { return; } } <div class="umb-block-list"> @foreach (var layout in Model.Layout) { if (layout?.Udi == null) { continue; } var data = Model.GetData(layout.Udi); @Html.Partial("BlockList/" + data.ContentType.Alias, (data, layout.Settings)) } </div>
@inherits UmbracoViewPage<BlockListModel> @using ContentModels = Umbraco.Web.PublishedModels; @using Umbraco.Core.Models.Blocks @{ if (Model?.Layout == null || !Model.Layout.Any()) { return; } } <div class="umb-block-list"> @foreach (var layout in Model.Layout) { if (layout?.Udi == null) { continue; } var data = layout.Data; @Html.Partial("BlockList/" + data.ContentType.Alias, (data, layout.Settings)) } </div>
Fix whitespace in team player stats view.
@model WuzlStats.ViewModels.Player.TeamPlayerStats <div class="panel panel-default"> <div class="panel-heading">Teams</div> <div class="panel-body"> <div class="row"> <div class="col-sm-4"> <label>Games played:</label> </div> <div class="col-sm-8"><span class="glyphicon glyphicon-thumbs-up"></span>@Model.WinsCount &nbsp;&nbsp; <span class="glyphicon glyphicon-thumbs-down"></span>@Model.LossesCount</div> </div> <div class="row"> <div class="col-sm-4"> <label>Favorite partner:</label> </div> <div class="col-sm-8">@Model.FavoritePartner</div> </div> <div class="row"> <div class="col-sm-4"> <label>Favorite team:</label> </div> <div class="col-sm-8">@Model.FavoriteTeam</div> </div> <div class="row"> <div class="col-sm-4"> <label>Favorite position:</label> </div> <div class="col-sm-8">@Model.FavoritePosition</div> </div> </div> </div>
@model WuzlStats.ViewModels.Player.TeamPlayerStats <div class="panel panel-default"> <div class="panel-heading">Teams</div> <div class="panel-body"> <div class="row"> <div class="col-sm-4"> <label>Games played:</label> </div> <div class="col-sm-8"><span class="glyphicon glyphicon-thumbs-up"></span> @Model.WinsCount &nbsp;&nbsp; <span class="glyphicon glyphicon-thumbs-down"></span> @Model.LossesCount</div> </div> <div class="row"> <div class="col-sm-4"> <label>Favorite partner:</label> </div> <div class="col-sm-8">@Model.FavoritePartner</div> </div> <div class="row"> <div class="col-sm-4"> <label>Favorite team:</label> </div> <div class="col-sm-8">@Model.FavoriteTeam</div> </div> <div class="row"> <div class="col-sm-4"> <label>Favorite position:</label> </div> <div class="col-sm-8">@Model.FavoritePosition</div> </div> </div> </div>
Make a tag V15.8.0 2017-05-22
using System.Web; using Newtonsoft.Json; using System; namespace TropoCSharp.Tropo { /// <summary> /// A utility class to render a Tropo object as JSON. /// </summary> public static class TropoJSONExtensions { public static void RenderJSON(this Tropo tropo, HttpResponse response) { tropo.Language = null; tropo.Voice = null; JsonSerializerSettings settings = new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore }; response.AddHeader("WebAPI-Lang-Ver", "CSharp V15.8.0 SNAPSHOT"); response.Write(JsonConvert.SerializeObject(tropo, Formatting.None, settings).Replace("\\", "").Replace("\"{", "{").Replace("}\"", "}")); } } }
using System.Web; using Newtonsoft.Json; using System; namespace TropoCSharp.Tropo { /// <summary> /// A utility class to render a Tropo object as JSON. /// </summary> public static class TropoJSONExtensions { public static void RenderJSON(this Tropo tropo, HttpResponse response) { tropo.Language = null; tropo.Voice = null; JsonSerializerSettings settings = new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore }; response.AddHeader("WebAPI-Lang-Ver", "CSharp V15.8.0 2017-05-22"); response.Write(JsonConvert.SerializeObject(tropo, Formatting.None, settings).Replace("\\", "").Replace("\"{", "{").Replace("}\"", "}")); } } }
Fix remaining game host regressions
// 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.Platform; namespace osu.Game.Tests { /// <summary> /// A headless host which cleans up before running (removing any remnants from a previous execution). /// </summary> public class CleanRunHeadlessGameHost : HeadlessGameHost { public CleanRunHeadlessGameHost(string gameName = @"", bool bindIPC = false, bool realtime = true) : base(gameName, bindIPC, realtime) { Storage.DeleteDirectory(string.Empty); } } }
// 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.Platform; namespace osu.Game.Tests { /// <summary> /// A headless host which cleans up before running (removing any remnants from a previous execution). /// </summary> public class CleanRunHeadlessGameHost : HeadlessGameHost { public CleanRunHeadlessGameHost(string gameName = @"", bool bindIPC = false, bool realtime = true) : base(gameName, bindIPC, realtime) { } protected override void SetupForRun() { base.SetupForRun(); Storage.DeleteDirectory(string.Empty); } } }
Switch to the Build<AppFunc> extension method - nicer syntax
using System; using System.Collections.Generic; using System.Threading.Tasks; using System.Windows; using Microsoft.Owin.Builder; using Owin; namespace CefSharp.Owin.Example.Wpf { //Shorthand for Owin pipeline func using AppFunc = Func<IDictionary<string, object>, Task>; /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); var appBuilder = new AppBuilder(); appBuilder.UseNancy(); var appFunc = (AppFunc)appBuilder.Build(typeof (AppFunc)); var settings = new CefSettings(); settings.RegisterOwinSchemeHandlerFactory("owin", appFunc); Cef.Initialize(settings); } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using System.Windows; using Microsoft.Owin.Builder; using Owin; namespace CefSharp.Owin.Example.Wpf { //Shorthand for Owin pipeline func using AppFunc = Func<IDictionary<string, object>, Task>; /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); var appBuilder = new AppBuilder(); appBuilder.UseNancy(); var appFunc = appBuilder.Build<AppFunc>(); var settings = new CefSettings(); settings.RegisterOwinSchemeHandlerFactory("owin", appFunc); Cef.Initialize(settings); } } }
Update error categories to match libgit2
namespace LibGit2Sharp.Core { internal enum GitErrorCategory { Unknown = -1, NoMemory, Os, Invalid, Reference, Zlib, Repository, Config, Regex, Odb, Index, Object, Net, Tag, Tree, Indexer, Ssl, Submodule, Thread, Stash, Checkout, FetchHead, Merge, Ssh, Filter, } }
namespace LibGit2Sharp.Core { internal enum GitErrorCategory { Unknown = -1, None, NoMemory, Os, Invalid, Reference, Zlib, Repository, Config, Regex, Odb, Index, Object, Net, Tag, Tree, Indexer, Ssl, Submodule, Thread, Stash, Checkout, FetchHead, Merge, Ssh, Filter, Revert, Callback, } }
Add tests for FY handling
using BatteryCommander.Web.Models; using System; using System.Collections.Generic; using Xunit; namespace BatteryCommander.Tests { public class FiscalYearTests { [Fact] public void Check_FY_2017_Start() { } } }
using BatteryCommander.Web.Models; using System; using System.Collections.Generic; using Xunit; using BatteryCommander.Web.Services; namespace BatteryCommander.Tests { public class FiscalYearTests { [Fact] public void Check_FY_2017_Start() { Assert.Equal(new DateTime(2016, 10, 1), FiscalYear.FY2017.Start()); } [Fact] public void Check_FY_2017_Next() { Assert.Equal(FiscalYear.FY2018, FiscalYear.FY2017.Next()); } [Fact] public void Check_FY_2017_End() { Assert.Equal(new DateTime(2017, 9, 30), FiscalYear.FY2017.End()); } } }
Add "Nominations" and "Updated" sorting criteria in beatmap listing
// 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 osu.Framework.Localisation; using osu.Game.Resources.Localisation.Web; namespace osu.Game.Overlays.BeatmapListing { public enum SortCriteria { [LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.ListingSearchSortingTitle))] Title, [LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.ListingSearchSortingArtist))] Artist, [LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.ListingSearchSortingDifficulty))] Difficulty, [LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.ListingSearchSortingRanked))] Ranked, [LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.ListingSearchSortingRating))] Rating, [LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.ListingSearchSortingPlays))] Plays, [LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.ListingSearchSortingFavourites))] Favourites, [LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.ListingSearchSortingRelevance))] Relevance } }
// 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 osu.Framework.Localisation; using osu.Game.Resources.Localisation.Web; namespace osu.Game.Overlays.BeatmapListing { public enum SortCriteria { [LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.ListingSearchSortingTitle))] Title, [LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.ListingSearchSortingArtist))] Artist, [LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.ListingSearchSortingDifficulty))] Difficulty, [LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.ListingSearchSortingUpdated))] Updated, [LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.ListingSearchSortingRanked))] Ranked, [LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.ListingSearchSortingRating))] Rating, [LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.ListingSearchSortingPlays))] Plays, [LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.ListingSearchSortingFavourites))] Favourites, [LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.ListingSearchSortingRelevance))] Relevance, [LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.ListingSearchSortingNominations))] Nominations, } }
Add "counter" keyword for key overlay setting
// 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.Localisation; using osu.Game.Configuration; using osu.Game.Localisation; namespace osu.Game.Overlays.Settings.Sections.Gameplay { public class HUDSettings : SettingsSubsection { protected override LocalisableString Header => GameplaySettingsStrings.HUDHeader; [BackgroundDependencyLoader] private void load(OsuConfigManager config) { Children = new Drawable[] { new SettingsEnumDropdown<HUDVisibilityMode> { LabelText = GameplaySettingsStrings.HUDVisibilityMode, Current = config.GetBindable<HUDVisibilityMode>(OsuSetting.HUDVisibilityMode) }, new SettingsCheckbox { LabelText = GameplaySettingsStrings.ShowDifficultyGraph, Current = config.GetBindable<bool>(OsuSetting.ShowProgressGraph) }, new SettingsCheckbox { LabelText = GameplaySettingsStrings.ShowHealthDisplayWhenCantFail, Current = config.GetBindable<bool>(OsuSetting.ShowHealthDisplayWhenCantFail), Keywords = new[] { "hp", "bar" } }, new SettingsCheckbox { LabelText = GameplaySettingsStrings.AlwaysShowKeyOverlay, Current = config.GetBindable<bool>(OsuSetting.KeyOverlay) }, }; } } }
// 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.Localisation; using osu.Game.Configuration; using osu.Game.Localisation; namespace osu.Game.Overlays.Settings.Sections.Gameplay { public class HUDSettings : SettingsSubsection { protected override LocalisableString Header => GameplaySettingsStrings.HUDHeader; [BackgroundDependencyLoader] private void load(OsuConfigManager config) { Children = new Drawable[] { new SettingsEnumDropdown<HUDVisibilityMode> { LabelText = GameplaySettingsStrings.HUDVisibilityMode, Current = config.GetBindable<HUDVisibilityMode>(OsuSetting.HUDVisibilityMode) }, new SettingsCheckbox { LabelText = GameplaySettingsStrings.ShowDifficultyGraph, Current = config.GetBindable<bool>(OsuSetting.ShowProgressGraph) }, new SettingsCheckbox { LabelText = GameplaySettingsStrings.ShowHealthDisplayWhenCantFail, Current = config.GetBindable<bool>(OsuSetting.ShowHealthDisplayWhenCantFail), Keywords = new[] { "hp", "bar" } }, new SettingsCheckbox { LabelText = GameplaySettingsStrings.AlwaysShowKeyOverlay, Current = config.GetBindable<bool>(OsuSetting.KeyOverlay), Keywords = new[] { "counter" }, }, }; } } }
Allow combining lifetime scope tags
using System; using Autofac.Builder; using Hangfire.Annotations; namespace Hangfire { /// <summary> /// Adds registration syntax to the <see cref="Autofac.ContainerBuilder"/> type. /// </summary> public static class RegistrationExtensions { /// <summary> /// Share one instance of the component within the context of a single /// processing background job instance. /// </summary> /// <typeparam name="TLimit">Registration limit type.</typeparam> /// <typeparam name="TActivatorData">Activator data type.</typeparam> /// <typeparam name="TStyle">Registration style.</typeparam> /// <param name="registration">The registration to configure.</param> /// <returns>A registration builder allowing further configuration of the component.</returns> /// <exception cref="ArgumentNullException"> /// Thrown when <paramref name="registration"/> is <see langword="null"/>. /// </exception> public static IRegistrationBuilder<TLimit, TActivatorData, TStyle> InstancePerBackgroundJob<TLimit, TActivatorData, TStyle>( [NotNull] this IRegistrationBuilder<TLimit, TActivatorData, TStyle> registration) { if (registration == null) throw new ArgumentNullException("registration"); return registration.InstancePerMatchingLifetimeScope(AutofacJobActivator.LifetimeScopeTag); } } }
using System; using System.Linq; using Autofac.Builder; using Hangfire.Annotations; namespace Hangfire { /// <summary> /// Adds registration syntax to the <see cref="Autofac.ContainerBuilder"/> type. /// </summary> public static class RegistrationExtensions { /// <summary> /// Share one instance of the component within the context of a single /// processing background job instance. /// </summary> /// <typeparam name="TLimit">Registration limit type.</typeparam> /// <typeparam name="TActivatorData">Activator data type.</typeparam> /// <typeparam name="TStyle">Registration style.</typeparam> /// <param name="registration">The registration to configure.</param> /// <param name="lifetimeScopeTags">Additional tags applied for matching lifetime scopes.</param> /// <returns>A registration builder allowing further configuration of the component.</returns> /// <exception cref="ArgumentNullException"> /// Thrown when <paramref name="registration"/> is <see langword="null"/>. /// </exception> public static IRegistrationBuilder<TLimit, TActivatorData, TStyle> InstancePerBackgroundJob<TLimit, TActivatorData, TStyle>( [NotNull] this IRegistrationBuilder<TLimit, TActivatorData, TStyle> registration, params object[] lifetimeScopeTags) { if (registration == null) throw new ArgumentNullException("registration"); var tags = new[] { AutofacJobActivator.LifetimeScopeTag }.Concat(lifetimeScopeTags).ToArray(); return registration.InstancePerMatchingLifetimeScope(tags); } } }
Add ctor to pipe the http factory
using System; using System.Collections.Generic; namespace website_performance.Entities { public class Robots { private readonly List<Uri> _sitemaps = new List<Uri>(); public Robots(string url) { if (Uri.TryCreate(url, UriKind.Absolute, out var robotsUrl)) Url = robotsUrl; else throw new UriFormatException($"Fail to parse URL \"{url}\""); } public Uri Url { get; } public IReadOnlyCollection<Uri> Sitemaps => _sitemaps; public void AddSitemap(string sitemapUrl) { if (Uri.TryCreate(sitemapUrl, UriKind.Absolute, out var sitemap)) { if (_sitemaps.Contains(sitemap) == false) _sitemaps.Add(sitemap); } else { throw new UriFormatException($"Fail to parse URL \"{sitemapUrl}\""); } } // New code public void GeneratePerformanceReport() { throw new NotImplementedException(); } } }
using System; using System.Collections.Generic; using website_performance.Infrastructure; namespace website_performance.Entities { public class Robots { private readonly IHttpMessageHandlerFactory _httpMessageHandlerFactory; private readonly List<Uri> _sitemaps = new List<Uri>(); public Robots(string url) { if (Uri.TryCreate(url, UriKind.Absolute, out var robotsUrl)) Url = robotsUrl; else throw new UriFormatException($"Fail to parse URL \"{url}\""); } public Robots(string url, IHttpMessageHandlerFactory httpMessageHandlerFactory) { _httpMessageHandlerFactory = httpMessageHandlerFactory ?? throw new ArgumentNullException(nameof(httpMessageHandlerFactory)); if (Uri.TryCreate(url, UriKind.Absolute, out var robotsUrl)) Url = robotsUrl; else throw new UriFormatException($"Fail to parse URL \"{url}\""); } public Uri Url { get; } public IReadOnlyCollection<Uri> Sitemaps => _sitemaps; public void AddSitemap(string sitemapUrl) { if (Uri.TryCreate(sitemapUrl, UriKind.Absolute, out var sitemap)) { if (_sitemaps.Contains(sitemap) == false) _sitemaps.Add(sitemap); } else { throw new UriFormatException($"Fail to parse URL \"{sitemapUrl}\""); } } // New code public void GeneratePerformanceReport() { throw new NotImplementedException(); } } }
Update existing documentation for season ids.
namespace TraktApiSharp.Objects.Get.Shows.Seasons { using Newtonsoft.Json; /// <summary> /// A collection of ids for various web services for a Trakt season. /// </summary> public class TraktSeasonIds { /// <summary> /// The Trakt numeric id for the season. /// </summary> [JsonProperty(PropertyName = "trakt")] public int Trakt { get; set; } /// <summary> /// The numeric id for the season from thetvdb.com /// </summary> [JsonProperty(PropertyName = "tvdb")] public int? Tvdb { get; set; } /// <summary> /// The numeric id for the season from themoviedb.org /// </summary> [JsonProperty(PropertyName = "tmdb")] public int? Tmdb { get; set; } /// <summary> /// The numeric id for the season from tvrage.com /// </summary> [JsonProperty(PropertyName = "tvrage")] public int? TvRage { get; set; } /// <summary> /// Tests, if at least one id has been set. /// </summary> [JsonIgnore] public bool HasAnyId => Trakt > 0 || Tvdb > 0 || Tvdb > 0 || TvRage > 0; } }
namespace TraktApiSharp.Objects.Get.Shows.Seasons { using Newtonsoft.Json; /// <summary>A collection of ids for various web services, including the Trakt id, for a Trakt season.</summary> public class TraktSeasonIds { /// <summary>Gets or sets the Trakt numeric id.</summary> [JsonProperty(PropertyName = "trakt")] public int Trakt { get; set; } /// <summary>Gets or sets the numeric id from thetvdb.com</summary> [JsonProperty(PropertyName = "tvdb")] public int? Tvdb { get; set; } /// <summary>Gets or sets the numeric id from themoviedb.org</summary> [JsonProperty(PropertyName = "tmdb")] public int? Tmdb { get; set; } /// <summary>Gets or sets the numeric id from tvrage.com</summary> [JsonProperty(PropertyName = "tvrage")] public int? TvRage { get; set; } /// <summary>Returns, whether any id has been set.</summary> [JsonIgnore] public bool HasAnyId => Trakt > 0 || Tvdb > 0 || Tvdb > 0 || TvRage > 0; } }
Set the the game width and height to the console window size or to a maximum value.
using SnakeApp.Models; using System; namespace SnakeApp.Controllers { public class GameController { public void StartNewGame() { PrepareConsole(); var game = new Game(80, 25, 5, 100); game.StartAsync(); ConsoleKeyInfo userInput = new ConsoleKeyInfo(); do { userInput = Console.ReadKey(true); game.ReceiveInput(userInput.Key); } while (userInput.Key != ConsoleKey.Q); RestoreConsole(); } private void PrepareConsole() { // getting the current cursor visibility is not supported on linux, so just hide then restore it Console.Clear(); Console.CursorVisible = false; } private void RestoreConsole() { Console.Clear(); Console.CursorVisible = true; } } }
using SnakeApp.Models; using System; namespace SnakeApp.Controllers { public class GameController { private byte MAX_WIDTH = 80; private byte MAX_HEIGHT = 25; public void StartNewGame() { PrepareConsole(); var game = new Game(Math.Min((byte)(Console.WindowWidth - 1), MAX_WIDTH), Math.Min((byte)(Console.WindowHeight - 1), MAX_HEIGHT), 5, 100); game.StartAsync(); ConsoleKeyInfo userInput = new ConsoleKeyInfo(); do { userInput = Console.ReadKey(true); game.ReceiveInput(userInput.Key); } while (userInput.Key != ConsoleKey.Q); RestoreConsole(); } private void PrepareConsole() { // getting the current cursor visibility is not supported on linux, so just hide then restore it Console.Clear(); Console.CursorVisible = false; } private void RestoreConsole() { Console.Clear(); Console.CursorVisible = true; } } }
Fix an endless feedback loop
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE namespace osu.Game.Screens.Select { public class MatchSongSelect : SongSelect { protected override bool OnSelectionFinalised() { Exit(); return true; } } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE namespace osu.Game.Screens.Select { public class MatchSongSelect : SongSelect { protected override bool OnSelectionFinalised() { Schedule(() => { // needs to be scheduled else we enter an infinite feedback loop. if (IsCurrentScreen) Exit(); }); return true; } } }
Fix no build option in dotnet test task
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.DotNet.Cli.Build { public class DotNetTest : DotNetTool { protected override string Command { get { return "test"; } } protected override string Args { get { return $"{GetProjectPath()} {GetConfiguration()} {GetLogger()} {GetNoBuild()}"; } } public string Configuration { get; set; } public string Logger { get; set; } public string ProjectPath { get; set; } public bool NoBuild { get; set; } private string GetConfiguration() { if (!string.IsNullOrEmpty(Configuration)) { return $"--configuration {Configuration}"; } return null; } private string GetLogger() { if (!string.IsNullOrEmpty(Logger)) { return $"--logger:{Logger}"; } return null; } private string GetProjectPath() { if (!string.IsNullOrEmpty(ProjectPath)) { return $"{ProjectPath}"; } return null; } private string GetNoBuild() { if (NoBuild) { return "--noBuild"; } return null; } } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.DotNet.Cli.Build { public class DotNetTest : DotNetTool { protected override string Command { get { return "test"; } } protected override string Args { get { return $"{GetProjectPath()} {GetConfiguration()} {GetLogger()} {GetNoBuild()}"; } } public string Configuration { get; set; } public string Logger { get; set; } public string ProjectPath { get; set; } public bool NoBuild { get; set; } private string GetConfiguration() { if (!string.IsNullOrEmpty(Configuration)) { return $"--configuration {Configuration}"; } return null; } private string GetLogger() { if (!string.IsNullOrEmpty(Logger)) { return $"--logger:{Logger}"; } return null; } private string GetProjectPath() { if (!string.IsNullOrEmpty(ProjectPath)) { return $"{ProjectPath}"; } return null; } private string GetNoBuild() { if (NoBuild) { return "--no-build"; } return null; } } }
Reduce default access token expiration timespan
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. using System; using Microsoft.Owin.Infrastructure; using Microsoft.Owin.Security.Infrastructure; namespace Microsoft.Owin.Security.OAuth { public class OAuthAuthorizationServerOptions : AuthenticationOptions { public OAuthAuthorizationServerOptions() : base("Bearer") { AuthorizationCodeExpireTimeSpan = TimeSpan.FromMinutes(5); AccessTokenExpireTimeSpan = TimeSpan.FromDays(14); SystemClock = new SystemClock(); } public string AuthorizeEndpointPath { get; set; } public string TokenEndpointPath { get; set; } public IOAuthAuthorizationServerProvider Provider { get; set; } public ISecureDataFormat<AuthenticationTicket> AuthorizationCodeFormat { get; set; } public ISecureDataFormat<AuthenticationTicket> AccessTokenFormat { get; set; } public ISecureDataFormat<AuthenticationTicket> RefreshTokenFormat { get; set; } public TimeSpan AuthorizationCodeExpireTimeSpan { get; set; } public TimeSpan AccessTokenExpireTimeSpan { get; set; } public IAuthenticationTokenProvider AuthorizationCodeProvider { get; set; } public IAuthenticationTokenProvider AccessTokenProvider { get; set; } public IAuthenticationTokenProvider RefreshTokenProvider { get; set; } public bool AuthorizeEndpointDisplaysError { get; set; } public ISystemClock SystemClock { get; set; } } }
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. using System; using Microsoft.Owin.Infrastructure; using Microsoft.Owin.Security.Infrastructure; namespace Microsoft.Owin.Security.OAuth { public class OAuthAuthorizationServerOptions : AuthenticationOptions { public OAuthAuthorizationServerOptions() : base("Bearer") { AuthorizationCodeExpireTimeSpan = TimeSpan.FromMinutes(5); AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(20); SystemClock = new SystemClock(); } public string AuthorizeEndpointPath { get; set; } public string TokenEndpointPath { get; set; } public IOAuthAuthorizationServerProvider Provider { get; set; } public ISecureDataFormat<AuthenticationTicket> AuthorizationCodeFormat { get; set; } public ISecureDataFormat<AuthenticationTicket> AccessTokenFormat { get; set; } public ISecureDataFormat<AuthenticationTicket> RefreshTokenFormat { get; set; } public TimeSpan AuthorizationCodeExpireTimeSpan { get; set; } public TimeSpan AccessTokenExpireTimeSpan { get; set; } public IAuthenticationTokenProvider AuthorizationCodeProvider { get; set; } public IAuthenticationTokenProvider AccessTokenProvider { get; set; } public IAuthenticationTokenProvider RefreshTokenProvider { get; set; } public bool AuthorizeEndpointDisplaysError { get; set; } public ISystemClock SystemClock { get; set; } } }
Use correct order of equality assertion for better error message (xUnit analyzer)
using System; using System.Collections.Generic; using System.Linq; using AvsAnLib.Internals; using WikipediaAvsAnTrieExtractor; using Xunit; namespace WikipediaAvsAnTrieExtractorTest { public class TriePrefixIncrementorTest { [Fact] public void BasicIncrementWorks() { var node = new Node(); IncrementPrefixExtensions.IncrementPrefix(ref node, true, "test", 0); Assert.Equal(NodeSerializer.Serialize(node), @"(0:1)t(0:1)te(0:1)tes(0:1)test(0:1)test (0:1)" ); } [Fact] public void IncrementWithSharedPrefixWorks() { var node = new Node(); IncrementPrefixExtensions.IncrementPrefix(ref node, true, "test", 0); IncrementPrefixExtensions.IncrementPrefix(ref node, true, "taste", 0); Assert.Equal(NodeSerializer.Serialize(node), @"(0:2)t(0:2)ta(0:1)tas(0:1)tast(0:1)taste(0:1)taste (0:1)te(0:1)tes(0:1)test(0:1)test (0:1)"); } } }
using System; using System.Collections.Generic; using System.Linq; using AvsAnLib.Internals; using WikipediaAvsAnTrieExtractor; using Xunit; namespace WikipediaAvsAnTrieExtractorTest { public class TriePrefixIncrementorTest { [Fact] public void BasicIncrementWorks() { var node = new Node(); IncrementPrefixExtensions.IncrementPrefix(ref node, true, "test", 0); Assert.Equal(@"(0:1)t(0:1)te(0:1)tes(0:1)test(0:1)test (0:1)" , NodeSerializer.Serialize(node)); } [Fact] public void IncrementWithSharedPrefixWorks() { var node = new Node(); IncrementPrefixExtensions.IncrementPrefix(ref node, true, "test", 0); IncrementPrefixExtensions.IncrementPrefix(ref node, true, "taste", 0); Assert.Equal(@"(0:2)t(0:2)ta(0:1)tas(0:1)tast(0:1)taste(0:1)taste (0:1)te(0:1)tes(0:1)test(0:1)test (0:1)", NodeSerializer.Serialize(node)); } } }