Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Test using a disposed plugin
namespace ServiceBus.AttachmentPlugin.Tests { using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Azure.ServiceBus; using Microsoft.Azure.ServiceBus.Core; using Xunit; public class When_reusing_plugin { [Fact] public void Should_throw_if_plugin_was_disposed() { var client = new FakeClientEntity("fake", string.Empty, RetryPolicy.Default); var configuration = new AzureStorageAttachmentConfiguration( connectionStringProvider: AzureStorageEmulatorFixture.ConnectionStringProvider, containerName: "attachments", messagePropertyToIdentifyAttachmentBlob: "attachment-id"); var registeredPlugin = AzureStorageAttachmentExtensions.RegisterAzureStorageAttachmentPlugin(client, configuration); ((IDisposable)registeredPlugin).Dispose(); Assert.ThrowsAsync<ObjectDisposedException>(() => registeredPlugin.BeforeMessageSend(null)); Assert.ThrowsAsync<ObjectDisposedException>(() => registeredPlugin.AfterMessageReceive(null)); } class FakeClientEntity : ClientEntity { public FakeClientEntity(string clientTypeName, string postfix, RetryPolicy retryPolicy) : base(clientTypeName, postfix, retryPolicy) { RegisteredPlugins = new List<ServiceBusPlugin>(); } public override void RegisterPlugin(ServiceBusPlugin serviceBusPlugin) { RegisteredPlugins.Add(serviceBusPlugin); } public override void UnregisterPlugin(string serviceBusPluginName) { var toRemove = RegisteredPlugins.First(x => x.Name == serviceBusPluginName); RegisteredPlugins.Remove(toRemove); } public override TimeSpan OperationTimeout { get; set; } public override IList<ServiceBusPlugin> RegisteredPlugins { get; } protected override Task OnClosingAsync() { throw new NotImplementedException(); } } } }
Add class accidentally omitted from last commit
// Copyright (c) 2017 SIL International // This software is licensed under the MIT license (http://opensource.org/licenses/MIT) using System; namespace LfMerge.Core.MongoConnector { /// Reimplementations of some PHP functions that turn out to be useful in the MongoConnector class public static class PseudoPhp { /// PHP's uniqid() is used in identifying comment replies, so we need to sort-of reimplement it here. /// But since uniqid() really just returns the current Unix timestamp in a specific string format, /// I changed its name to reflect what it *really* does. /// /// Note: this function is deterministic, so that it will be easily testable. In most common usage /// you'll want to pass DateTime.UtcNow as input here. public static string NonUniqueIdFromDateTime(DateTime timestamp) { TimeSpan sinceEpoch = timestamp - MagicValues.UnixEpoch; long seconds = sinceEpoch.Ticks / TimeSpan.TicksPerSecond; long ticks = sinceEpoch.Ticks % TimeSpan.TicksPerSecond; long microseconds = (ticks / 10) % 0x100000; // PHP only uses five hex digits of the microseconds value return seconds.ToString("x8") + microseconds.ToString("x5"); } internal static string LastUniqueId = "0000000000000"; public static string UniqueIdFromDateTime(DateTime timestamp) { string result = NonUniqueIdFromDateTime(timestamp); while (String.CompareOrdinal(result, LastUniqueId) <= 0) { timestamp = timestamp.AddTicks(10); // 10 ticks = 1 microsecond result = NonUniqueIdFromDateTime(timestamp); } LastUniqueId = result; return result; } } }
Add benchmark for stream extensions
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.IO; using BenchmarkDotNet.Attributes; using osu.Framework.Extensions; namespace osu.Framework.Benchmarks { [MemoryDiagnoser] public class BenchmarkStreamExtensions { private MemoryStream memoryStream; [Params(100, 10000, 1000000)] public int Length { get; set; } [GlobalSetup] public void GlobalSetup() { byte[] array = new byte[Length]; var random = new Random(42); random.NextBytes(array); memoryStream = new MemoryStream(array); } [Benchmark] public byte[] ReadAllBytesToArray() { return memoryStream.ReadAllBytesToArray(); } } }
Add add Michelin wmts sample
using System.Linq; using System.Net.Http; using BruTile.Wmts; using Mapsui.Layers; using Mapsui.UI; namespace Mapsui.Samples.Common.Maps { public class WmtsMichelinSample : ISample { public string Name => "5 WMTS Michelin"; public string Category => "Data"; public void Setup(IMapControl mapControl) { mapControl.Map = CreateMap(); } public static Map CreateMap() { var map = new Map(); map.Layers.Add(CreateLayer()); return map; } public static ILayer CreateLayer() { using (var httpClient = new HttpClient()) using (var response = httpClient.GetStreamAsync("https://bertt.github.io/wmts/capabilities/michelin.xml").Result) { var tileSource = WmtsParser.Parse(response).First(); return new TileLayer(tileSource) { Name = tileSource.Name }; } } } }
Remove duplicates from sorted array II
// https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/ // // Follow up for "Remove Duplicates": // What if duplicates are allowed at most twice? // // For example, // Given sorted array nums = [1,1,1,2,2,3], // // Your function should return length = 5, // with the first five elements of nums being 1, 1, 2, 2 and 3. // It doesn't matter what you leave beyond the new length. // https://leetcode.com/submissions/detail/53326968/ // // // Submission Details // 164 / 164 test cases passed. // Status: Accepted // Runtime: 496 ms // // Submitted: 0 minutes ago public class Solution { public int RemoveDuplicates(int[] nums) { if (nums.Length < 3) { return nums.Length; } var write = 0; for (var i = 0; i < nums.Length; i++) { if (write < 2 || nums[i] > nums[write - 2]) { nums[write++] = nums[i]; } } return write; } }
Define common Complex dialog interface
using System; using System.Collections.Generic; using System.Text; namespace IronAHK.Rusty { interface IComplexDialoge { string MainText { get; set; } string Subtext { get; set; } string Title { get; set; } #region Form //DialogResult ShowDialog(); void Show(); void Close(); void Dispose(); bool Visible { get; set; } bool TopMost { get; set; } #region Invokable bool InvokeRequired { get; } object Invoke(Delegate Method, params object[] obj); object Invoke(Delegate Method); #endregion #endregion } }
Add separate test for stateful multiplayer client
// 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.Testing; using osu.Game.Tests.Visual.Multiplayer; using osu.Game.Users; namespace osu.Game.Tests.OnlinePlay { [HeadlessTest] public class StatefulMultiplayerClientTest : MultiplayerTestScene { [Test] public void TestUserAddedOnJoin() { var user = new User { Id = 33 }; AddRepeatStep("add user multiple times", () => Client.AddUser(user), 3); AddAssert("room has 2 users", () => Client.Room?.Users.Count == 2); } [Test] public void TestUserRemovedOnLeave() { var user = new User { Id = 44 }; AddStep("add user", () => Client.AddUser(user)); AddAssert("room has 2 users", () => Client.Room?.Users.Count == 2); AddRepeatStep("remove user multiple times", () => Client.RemoveUser(user), 3); AddAssert("room has 1 user", () => Client.Room?.Users.Count == 1); } } }
Implement tests for Commands interface, tests include lazy loading and "not supported command" -test.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Xunit; namespace SCPI.Tests { public class Commands_Tests { [Fact] public void HasSupportedCommands() { // Arrange var commands = new Commands(); // Act var names = commands.Names(); // Assert Assert.NotEmpty(names); } [Fact] public void LazyLoadingWorks() { // Arrange var commands = new Commands(); var names = commands.Names(); // Act var cmd1 = commands.Get(names.ElementAt(0)); var cmd2 = commands.Get(names.ElementAt(0)); // Assert Assert.Equal(cmd1, cmd2); } [Fact] public void QueryNotSupportedCommand() { // Arrange var commands = new Commands(); // Act Assert.Throws<InvalidOperationException>(() => commands.Get("NOT_SUPPORTED")); // Assert } } }
Add test coverage of TransactionalCommitComponent
// 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 NUnit.Framework; using osu.Game.Screens.Edit; namespace osu.Game.Tests.Editing { [TestFixture] public class TransactionalCommitComponentTest { private TestHandler handler; [SetUp] public void SetUp() { handler = new TestHandler(); } [Test] public void TestCommitTransaction() { Assert.That(handler.StateUpdateCount, Is.EqualTo(0)); handler.BeginChange(); Assert.That(handler.StateUpdateCount, Is.EqualTo(0)); handler.EndChange(); Assert.That(handler.StateUpdateCount, Is.EqualTo(1)); } [Test] public void TestSaveOutsideOfTransactionTriggersUpdates() { Assert.That(handler.StateUpdateCount, Is.EqualTo(0)); handler.SaveState(); Assert.That(handler.StateUpdateCount, Is.EqualTo(1)); handler.SaveState(); Assert.That(handler.StateUpdateCount, Is.EqualTo(2)); } [Test] public void TestEventsFire() { int transactionBegan = 0; int transactionEnded = 0; int stateSaved = 0; handler.TransactionBegan += () => transactionBegan++; handler.TransactionEnded += () => transactionEnded++; handler.SaveStateTriggered += () => stateSaved++; handler.BeginChange(); Assert.That(transactionBegan, Is.EqualTo(1)); handler.EndChange(); Assert.That(transactionEnded, Is.EqualTo(1)); Assert.That(stateSaved, Is.EqualTo(0)); handler.SaveState(); Assert.That(stateSaved, Is.EqualTo(1)); } [Test] public void TestSaveDuringTransactionDoesntTriggerUpdate() { Assert.That(handler.StateUpdateCount, Is.EqualTo(0)); handler.BeginChange(); handler.SaveState(); Assert.That(handler.StateUpdateCount, Is.EqualTo(0)); handler.EndChange(); Assert.That(handler.StateUpdateCount, Is.EqualTo(1)); } [Test] public void TestEndWithoutBeginThrows() { handler.BeginChange(); handler.EndChange(); Assert.That(() => handler.EndChange(), Throws.TypeOf<InvalidOperationException>()); } private class TestHandler : TransactionalCommitComponent { public int StateUpdateCount { get; private set; } protected override void UpdateState() { StateUpdateCount++; } } } }
Fix using portable directory separator character
using Microsoft.AspNet.Builder; using Microsoft.AspNet.Hosting; using Microsoft.Extensions.DependencyInjection; using IdentityServer3.Core.Configuration; using IdentityServer.Configuration; using System.Security.Cryptography.X509Certificates; using Microsoft.Extensions.PlatformAbstractions; using Microsoft.Extensions.Logging; using Serilog; namespace IdentityServer { public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddDataProtection(); } public void Configure(IApplicationBuilder app, IApplicationEnvironment env, ILoggerFactory loggerFactory) { Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .WriteTo.LiterateConsole() .CreateLogger(); loggerFactory.AddConsole(); loggerFactory.AddDebug(); app.UseIISPlatformHandler(); var certFile = env.ApplicationBasePath + "\\idsrv3test.pfx"; var idsrvOptions = new IdentityServerOptions { Factory = new IdentityServerServiceFactory() .UseInMemoryUsers(Users.Get()) .UseInMemoryClients(Clients.Get()) .UseInMemoryScopes(Scopes.Get()), SigningCertificate = new X509Certificate2(certFile, "idsrv3test"), RequireSsl = false }; app.UseIdentityServer(idsrvOptions); } public static void Main(string[] args) => WebApplication.Run<Startup>(args); } }
using Microsoft.AspNet.Builder; using Microsoft.AspNet.Hosting; using Microsoft.Extensions.DependencyInjection; using IdentityServer3.Core.Configuration; using IdentityServer.Configuration; using System.Security.Cryptography.X509Certificates; using Microsoft.Extensions.PlatformAbstractions; using Microsoft.Extensions.Logging; using Serilog; namespace IdentityServer { public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddDataProtection(); } public void Configure(IApplicationBuilder app, IApplicationEnvironment env, ILoggerFactory loggerFactory) { Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .WriteTo.LiterateConsole() .CreateLogger(); loggerFactory.AddConsole(); loggerFactory.AddDebug(); app.UseIISPlatformHandler(); var certFile = env.ApplicationBasePath + $"{System.IO.Path.DirectorySeparatorChar}idsrv3test.pfx"; var idsrvOptions = new IdentityServerOptions { Factory = new IdentityServerServiceFactory() .UseInMemoryUsers(Users.Get()) .UseInMemoryClients(Clients.Get()) .UseInMemoryScopes(Scopes.Get()), SigningCertificate = new X509Certificate2(certFile, "idsrv3test"), RequireSsl = false }; app.UseIdentityServer(idsrvOptions); } public static void Main(string[] args) => WebApplication.Run<Startup>(args); } }
Add interface for a migration
using System.Threading.Tasks; namespace RapidCore.Migration { /// <summary> /// Defines a migration /// </summary> public interface IMigration { /// <summary> /// Code that is run when upgrading the environment /// </summary> Task UpgradeAsync(IMigrationContext context); /// <summary> /// Code that is run when downgrading (or rolling back) the environment /// </summary> Task DowngradeAsync(IMigrationContext context); string Name { get; } } }
Update the l\paths in the server side of the resource
using System; using System.Collections.Generic; namespace Glimpse.Core2.Framework { public class GlimpseMetadata { public GlimpseMetadata() { plugins = new Dictionary<string, PluginMetadata>(); } public string version{ get; set; } public IDictionary<string,PluginMetadata> plugins { get; set; } } public class PluginMetadata { public string DocumentationUri { get; set; } public bool HasMetadata { get { return !string.IsNullOrEmpty(DocumentationUri); } } } }
using System; using System.Collections.Generic; namespace Glimpse.Core2.Framework { public class GlimpseMetadata { public GlimpseMetadata() { plugins = new Dictionary<string, PluginMetadata>(); //TODO: this is really bad... Nik needs to work on how we want to do this. Version numbers need to be taken intoaccount too paths = new { history = "History", paging = "Pager", ajax = "Ajax", config = "Config", logo = "/Glimpse.axd?n=logo.png&Version=1.0.0", sprite = "/Glimpse.axd?n=sprite.png&Version=1.0.0", popup = "test-popup.html" }; } public string version { get; set; } public IDictionary<string,PluginMetadata> plugins { get; set; } public object paths { get; set; } } public class PluginMetadata { public string DocumentationUri { get; set; } public bool HasMetadata { get { return !string.IsNullOrEmpty(DocumentationUri); } } } }
Use this instead of LocaleType
using System; using System.Data; using System.Globalization; namespace NHibernate.Type { /// <summary> /// CultureInfoType. /// </summary> public class CultureInfoType : ImmutableType, ILiteralType { public override object Get(IDataReader rs, string name) { string str = (string) NHibernate.String.Get(rs, name); if (str == null) { return null; } else { return new CultureInfo(str); } } public override void Set(IDbCommand cmd, object value, int index) { NHibernate.String.Set(cmd, value.ToString(), index); } public override DbType SqlType { get { return NHibernate.String.SqlType; } } public override string ToXML(object value) { return value.ToString(); } public override System.Type ReturnedClass { get { return typeof(CultureInfo); } } public override bool Equals(object x, object y) { return (x==y); //??? } public override string Name { get { return "CultureInfo"; } } public string ObjectToSQLString(object value) { return ( (ILiteralType) NHibernate.String ).ObjectToSQLString( value.ToString() ); } } }
Add support for UIViews in section headers and footers.
using System; using System.Drawing; using System.Linq; using MonoTouch.UIKit; using MonoTouch.Dialog; namespace Sample { public partial class AppDelegate { public void DemoHeadersFooters () { var section = new Section () { HeaderView = new UIImageView (UIImage.FromFile ("caltemplate.png")), FooterView = new UISwitch (new RectangleF (0, 0, 80, 30)), }; // Fill in some data var linqRoot = new RootElement ("LINQ source"){ from x in new string [] { "one", "two", "three" } select new Section (x) { from y in "Hello:World".Split (':') select (Element) new StringElement (y) } }; section.Add (new RootElement ("Desert", new RadioGroup ("desert", 0)){ new Section () { new RadioElement ("Ice Cream", "desert"), new RadioElement ("Milkshake", "desert"), new RadioElement ("Chocolate Cake", "desert") }, }); var root = new RootElement ("Headers and Footers") { section, new Section () { linqRoot } }; var dvc = new DialogViewController (root, true); navigation.PushViewController (dvc, true); } } }
Add Orchard.Tags.TagsCloud "no data" message
@using Orchard.Tags.Models <ul class="tag-cloud"> @foreach (TagCount tagCount in Model.TagCounts) { <li class="tag-cloud-tag tag-cloud-tag-@tagCount.Bucket"> @Html.ActionLink(tagCount.TagName, "Search", "Home", new { area = "Orchard.Tags", tagName = tagCount.TagName }, null ) </li> } </ul>
@using Orchard.Tags.Models <ul class="tag-cloud"> @if (((IEnumerable<object>)Model.TagCounts).Any()) { foreach (TagCount tagCount in Model.TagCounts) { <li class="tag-cloud-tag tag-cloud-tag-@tagCount.Bucket"> @Html.ActionLink(tagCount.TagName, "Search", "Home", new { area = "Orchard.Tags", tagName = tagCount.TagName }, null ) </li> } } else { <li> @T("There are no tags to display.") </li> } </ul>
Fix the solution not building after a fresh clone.
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyCompany("The Git Development Community")] [assembly: AssemblyCopyright("Copyright © 2009 The GitSharp Team")] [assembly: ComVisible(false)] #if DEBUG [assembly: AssemblyConfiguration("Debug")] #else [assembly: AssemblyConfiguration("Release")] #endif
Add class to relay progress reporting For use whenever directly implementing IReportProgress is impossible
using System; using System.Collections.Generic; using System.Text; namespace SkyEditor.Core.Utilities { /// <summary> /// A basic implementation of <see cref="IReportProgress"/> that can be used to relay progress reporting when a function's parent class cannot implement this interface. /// </summary> public class ProgressReportToken : IReportProgress { public event EventHandler<ProgressReportedEventArgs> ProgressChanged; public event EventHandler Completed; public float Progress { get { return _progress; } set { _progress = value; ProgressChanged?.Invoke(this, new ProgressReportedEventArgs() { IsIndeterminate = IsIndeterminate, Message = Message, Progress = Progress }); } } private float _progress; public string Message { get { return _message; } set { _message = value; ProgressChanged?.Invoke(this, new ProgressReportedEventArgs() { IsIndeterminate = IsIndeterminate, Message = Message, Progress = Progress }); } } private string _message; public bool IsIndeterminate { get { return _isIndeterminate; } set { _isIndeterminate = value; ProgressChanged?.Invoke(this, new ProgressReportedEventArgs() { IsIndeterminate = IsIndeterminate, Message = Message, Progress = Progress }); } } private bool _isIndeterminate; public bool IsCompleted { get { return _isCompleted; } set { _isCompleted = value; Completed?.Invoke(this, new EventArgs()); } } private bool _isCompleted; } }
Remove colour properties and rely on parent
// 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.Graphics.Colour; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Sprites; namespace osu.Framework.Graphics.Shapes { public class Circle : CircularContainer { private readonly Box fill; public SRGBColour FillColour { get { return fill.Colour; } set { fill.Colour = value; } } public ColourInfo FillColourInfo { get { return fill.ColourInfo; } set { fill.ColourInfo = value; } } public Circle() { Masking = true; AddInternal(fill = new Box() { RelativeSizeAxes = Axes.Both, }); } } }
// 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.Graphics.Colour; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Sprites; namespace osu.Framework.Graphics.Shapes { public class Circle : CircularContainer { private readonly Box fill; public Circle() { Masking = true; AddInternal(fill = new Box() { RelativeSizeAxes = Axes.Both, }); } } }
Add missing new test board target class
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using SignTestInterface; using winusbdotnet; namespace SignControl { class TargetTestBoard : ISignTarget { public TargetTestBoard() { TestBoard = null; foreach(var dev in SignTest.Enumerate()) { try { TestBoard = new SignTest(dev); break; } catch { } } if (TestBoard == null) throw new Exception("Unable to attach to a Sign Test board."); SignComponent[] c = new SignComponent[1]; c[0] = new SignComponent() { X = 0, Y = 0, Width = 32, Height = 32 }; CurrentConfig = new SignConfiguration(c); // Initialize test board. TestBoard.SetMode(SignTest.DeviceMode.On); TestBoard.SetMode(SignTest.DeviceMode.FpgaActive); } SignTest TestBoard; SignConfiguration CurrentConfig; public bool SupportsConfiguration(SignConfiguration configuration) { return true; } public void ApplyConfiguration(SignConfiguration configuration) { CurrentConfig = configuration; } public void SendImage(Bitmap signImage) { SignConfiguration config = CurrentConfig; // For each element in the configuration, render it. for (int i = 0; i < config.Components.Length; i++ ) { SignComponent c = config.Components[i]; uint[] elementData = new uint[32 * 32]; for(int y=0;y<32;y++) { for(int x=0;x<32;x++) { elementData[x + y * 32] = (uint)signImage.GetPixel(x + c.X, y + c.Y).ToArgb(); } } TestBoard.SendImage32x32(i, elementData); } } public SignConfiguration CurrentConfiguration() { return CurrentConfig; } public string SignName { get { return "Test Board"; } } } }
Add new tests for Unified Label
using System; using System.Collections.Generic; using System.Linq; using System.Text; using CocosSharp; namespace tests { public class LabelFNTColorAndOpacity : AtlasDemoNew { float m_time; CCLabel label1, label2, label3; public LabelFNTColorAndOpacity() { m_time = 0; Color = new CCColor3B(128, 128, 128); Opacity = 255; label1 = new CCLabel("Label1", "fonts/bitmapFontTest2.fnt"); // testing anchors label1.AnchorPoint = CCPoint.AnchorLowerLeft; AddChild(label1, 0, (int)TagSprite.kTagBitmapAtlas1); var fade = new CCFadeOut (1.0f); var fade_in = fade.Reverse(); label1.RepeatForever ( fade, fade_in); // VERY IMPORTANT // color and opacity work OK because bitmapFontAltas2 loads a BMP image (not a PNG image) // If you want to use both opacity and color, it is recommended to use NON premultiplied images like BMP images // Of course, you can also tell XCode not to compress PNG images, but I think it doesn't work as expected label2 = new CCLabel("Label2", "fonts/bitmapFontTest2.fnt"); // testing anchors label2.AnchorPoint = CCPoint.AnchorMiddle; label2.Color = CCColor3B.Red; AddChild(label2, 0, (int)TagSprite.kTagBitmapAtlas2); label2.RepeatForever( new CCTintTo (1, 255, 0, 0), new CCTintTo (1, 0, 255, 0), new CCTintTo (1, 0, 0, 255)); label3 = new CCLabel("Label3", "fonts/bitmapFontTest2.fnt"); // testing anchors label3.AnchorPoint = CCPoint.AnchorUpperRight; AddChild(label3, 0, (int)TagSprite.kTagBitmapAtlas3); base.Schedule(step); } protected override void AddedToScene() { base.AddedToScene(); var visibleRect = VisibleBoundsWorldspace; label1.Position = visibleRect.LeftBottom(); label2.Position = visibleRect.Center(); label3.Position = visibleRect.RightTop(); } public virtual void step(float dt) { m_time += dt; string stepString; stepString = string.Format("{0,2:f2} Test j", m_time); label1.Text = stepString; label2.Text = stepString; label3.Text = stepString; } public override string title() { return "New Label + .FNT file"; } public override string subtitle() { return "Testing opacity + tint"; } } }
Add test for Ignore attribute
using System.Collections.Generic; using System.Linq; using NUnit.Framework; using SQLite.Net.Attributes; #if __WIN32__ using SQLitePlatformTest = SQLite.Net.Platform.Win32.SQLitePlatformWin32; #elif WINDOWS_PHONE using SQLitePlatformTest = SQLite.Net.Platform.WindowsPhone8.SQLitePlatformWP8; #elif __WINRT__ using SQLitePlatformTest = SQLite.Net.Platform.WinRT.SQLitePlatformWinRT; #elif __IOS__ using SQLitePlatformTest = SQLite.Net.Platform.XamarinIOS.SQLitePlatformIOS; #elif __ANDROID__ using SQLitePlatformTest = SQLite.Net.Platform.XamarinAndroid.SQLitePlatformAndroid; #else using SQLitePlatformTest = SQLite.Net.Platform.Generic.SQLitePlatformGeneric; #endif namespace SQLite.Net.Tests { [TestFixture] public class IgnoredTest { public class DummyClass { [PrimaryKey, AutoIncrement] public int Id { get; set; } public string Foo { get; set; } public string Bar { get; set; } [Attributes.Ignore] public List<string> Ignored { get; set; } } [Test] public void NullableFloat() { var db = new SQLiteConnection(new SQLitePlatformTest(), TestPath.GetTempFileName()); // if the Ignored property is not ignore this will cause an exception db.CreateTable<DummyClass>(); } } }
Add a docs module to the sample project.
using Mango; using Mango.Templates.Minge; namespace MangoProject { public class Docs : MangoModule { public static void GettingStarted (MangoContext context) { } public static void Api (MangoContext context) { } } }
Add example source code for Sense Hat connecting to Azure IoT Hub.
using System; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; // The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 namespace DemoSenseHat { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class MainPage : Page { private DispatcherTimer timer = new DispatcherTimer(); private Emmellsoft.IoT.Rpi.SenseHat.ISenseHat hat; private Microsoft.Azure.Devices.Client.DeviceClient device; private const string DeviceConnectionString = "HostName=prelab.azure-devices.net;DeviceId=spi;SharedAccessKey=n8wt6OghOciC5hiaBVOwmfUTuASJTywS7gy4t1ad2Ec="; public MainPage() { this.InitializeComponent(); timer.Interval = TimeSpan.FromSeconds(1); timer.Tick += Timer_Tick; device = Microsoft.Azure.Devices.Client.DeviceClient.CreateFromConnectionString(DeviceConnectionString); InitThings(); this.Unloaded += MainPage_Unloaded; } private async void InitThings() { hat = await Emmellsoft.IoT.Rpi.SenseHat.SenseHatFactory.GetSenseHat(); await device.OpenAsync(); hat.Display.Fill(Windows.UI.Colors.Navy); hat.Display.Update(); timer.Start(); } private int msgid = 100; private void Timer_Tick(object sender, object e) { lbl.Text = DateTime.Now.ToString("T"); hat.Sensors.HumiditySensor.Update(); if (hat.Sensors.Humidity.HasValue && hat.Sensors.Temperature.HasValue) { device.SendEventAsync(ToMessage(new { MessageId = ++msgid, DeviceId = "spi", Temperature = hat.Sensors.Temperature.Value, Humidity = hat.Sensors.Humidity.Value, })); } } private Microsoft.Azure.Devices.Client.Message ToMessage(object data) { var jsonText = Newtonsoft.Json.JsonConvert.SerializeObject(data); var dataBuffer = System.Text.UTF8Encoding.UTF8.GetBytes(jsonText); return new Microsoft.Azure.Devices.Client.Message(dataBuffer); } private async void MainPage_Unloaded(object sender, RoutedEventArgs e) { await device.CloseAsync(); device.Dispose(); } } }
Use two newlines in exception message to better match Power Assert.NET
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Linq.Expressions; namespace ExpressionToCodeLib { public static class PAssert { public static void IsTrue(Expression<Func<bool>> assertion) { That(assertion,"PAssert.IsTrue failed for:"); } public static void That(Expression<Func<bool>> assertion, string msg = null) { if (!assertion.Compile()()) throw new PAssertFailedException((msg ?? "PAssert.That failed for:") + "\n" + ExpressionToCode.AnnotatedToCode(assertion.Body)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Linq.Expressions; namespace ExpressionToCodeLib { public static class PAssert { public static void IsTrue(Expression<Func<bool>> assertion) { That(assertion,"PAssert.IsTrue failed for:"); } public static void That(Expression<Func<bool>> assertion, string msg = null) { if (!assertion.Compile()()) throw new PAssertFailedException((msg ?? "PAssert.That failed for:") + "\n\n" + ExpressionToCode.AnnotatedToCode(assertion.Body)); } } }
Fix off by one error.
using System; using System.Collections.Generic; using System.Linq; namespace csmacnz.Coveralls { public class CoverageFileBuilder { private readonly string _filePath; private readonly Dictionary<int,int> _coverage = new Dictionary<int, int>(); public CoverageFileBuilder(string filePath) { if (string.IsNullOrWhiteSpace(filePath)) { throw new ArgumentException("filePath"); } _filePath = filePath; } public void RecordCovered(int lineNumber) { _coverage[lineNumber] = 1; } public void RecordUnCovered(int lineNumber) { _coverage[lineNumber] = 0; } public CoverageFile CreateFile() { var length = _coverage.Any() ? _coverage.Max(c => c.Key) + 1 : 1; var coverage = Enumerable.Range(0, length) .Select(index => _coverage.ContainsKey(index) ? (int?) _coverage[index] : null) .ToArray(); return new CoverageFile(_filePath, new string[0], coverage); } } }
using System; using System.Collections.Generic; using System.Linq; namespace csmacnz.Coveralls { public class CoverageFileBuilder { private readonly string _filePath; private readonly Dictionary<int,int> _coverage = new Dictionary<int, int>(); public CoverageFileBuilder(string filePath) { if (string.IsNullOrWhiteSpace(filePath)) { throw new ArgumentException("filePath"); } _filePath = filePath; } public void RecordCovered(int lineNumber) { _coverage[lineNumber-1] = 1; } public void RecordUnCovered(int lineNumber) { _coverage[lineNumber-1] = 0; } public CoverageFile CreateFile() { var length = _coverage.Any() ? _coverage.Max(c => c.Key) + 1 : 1; var coverage = Enumerable.Range(0, length) .Select(index => _coverage.ContainsKey(index) ? (int?) _coverage[index] : null) .ToArray(); return new CoverageFile(_filePath, new string[0], coverage); } } }
Add test to make sure the algorithm is passed down in time
// 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.Allocation; using osu.Framework.Testing; using osu.Game.Rulesets.Mania.Mods; using osu.Game.Rulesets.Mania.Objects.Drawables; using osu.Game.Rulesets.UI.Scrolling; using osu.Game.Rulesets.UI.Scrolling.Algorithms; using osu.Game.Tests.Visual; namespace osu.Game.Rulesets.Mania.Tests.Mods { public class TestSceneManiaModConstantSpeed : ModTestScene { protected override Ruleset CreatePlayerRuleset() => new ManiaRuleset(); [Test] public void TestConstantScroll() => CreateModTest(new ModTestData { Mod = new ManiaModConstantSpeed(), PassCondition = () => { var hitObject = Player.ChildrenOfType<DrawableManiaHitObject>().FirstOrDefault(); return hitObject?.Dependencies.Get<IScrollingInfo>().Algorithm is ConstantScrollAlgorithm; } }); } }
Add google-cloud-resource-prefix header for Datastore calls
// Copyright 2016, Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Google.Api.Gax.Grpc; namespace Google.Datastore.V1 { // Partial methods on DatastoreClientImpl to set appropriate client headers. public partial class DatastoreClientImpl { private const string ResourcePrefixHeader = "google-cloud-resource-prefix"; private const string ResourcePrefixHeaderValuePrefix = "projects/"; partial void ModifyAllocateIdsRequest(ref AllocateIdsRequest request, ref CallSettings settings) { settings = settings.WithHeader(ResourcePrefixHeader, "projects/" + request.ProjectId); } partial void ModifyBeginTransactionRequest(ref BeginTransactionRequest request, ref CallSettings settings) { settings = settings.WithHeader(ResourcePrefixHeader, "projects/" + request.ProjectId); } partial void ModifyCommitRequest(ref CommitRequest request, ref CallSettings settings) { settings = settings.WithHeader(ResourcePrefixHeader, "projects/" + request.ProjectId); } partial void ModifyLookupRequest(ref LookupRequest request, ref CallSettings settings) { settings = settings.WithHeader(ResourcePrefixHeader, "projects/" + request.ProjectId); } partial void ModifyRollbackRequest(ref RollbackRequest request, ref CallSettings settings) { settings = settings.WithHeader(ResourcePrefixHeader, "projects/" + request.ProjectId); } partial void ModifyRunQueryRequest(ref RunQueryRequest request, ref CallSettings settings) { settings = settings.WithHeader(ResourcePrefixHeader, "projects/" + request.ProjectId); } } }
Add tool to display all external dependencies, with versions
// Copyright 2020 Google LLC // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Google.Cloud.Tools.Common; using System; using System.Collections.Generic; using System.Linq; namespace Google.Cloud.Tools.ReleaseManager; internal class ShowExternalDependenciesCommand : CommandBase { public ShowExternalDependenciesCommand() : base("show-external-dependencies", "Shows all versions of external dependencies") { } protected override void ExecuteImpl(string[] args) { var catalog = ApiCatalog.Load(); DisplayDependencies("Production", api => api.Dependencies); DisplayDependencies("Test", api => api.TestDependencies); void DisplayDependencies(string name, Func<ApiMetadata, SortedDictionary<string, string>> dependenciesSelector) { var dependencies = catalog.Apis.SelectMany(dependenciesSelector) .Where(pair => !catalog.TryGetApi(pair.Key, out _)) .OrderBy(pair => pair.Key) .GroupBy(pair => pair.Key, pair => pair.Value); Console.WriteLine($"{name} dependencies:"); foreach (var dependency in dependencies) { var package = dependency.Key; var versions = dependency.Distinct(); Console.WriteLine($"{package}: {string.Join(",", versions)}"); } Console.WriteLine(); } } }
Add proof of concept components list
// 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.Diagnostics; using System.Linq; using NUnit.Framework; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Graphics.Containers; using osu.Game.Graphics.Sprites; using osu.Game.Rulesets; using osu.Game.Rulesets.Osu; using osu.Game.Screens.Play.HUD; using osuTK; namespace osu.Game.Tests.Visual.Gameplay { public class TestSceneSkinEditorComponentsList : SkinnableTestScene { [Test] public void TestToggleEditor() { AddStep("show available components", () => { SetContents(() => { FillFlowContainer fill; var scroll = new OsuScrollContainer { RelativeSizeAxes = Axes.Both, Child = fill = new FillFlowContainer { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, Width = 0.5f, Direction = FillDirection.Vertical, Spacing = new Vector2(20) } }; var skinnableTypes = typeof(OsuGame).Assembly.GetTypes().Where(t => typeof(ISkinnableComponent).IsAssignableFrom(t)).ToArray(); foreach (var type in skinnableTypes) { try { fill.Add(new OsuSpriteText { Text = type.Name }); var instance = (Drawable)Activator.CreateInstance(type); Debug.Assert(instance != null); instance.Anchor = Anchor.TopCentre; instance.Origin = Anchor.TopCentre; var container = new Container { RelativeSizeAxes = Axes.X, Height = 100, Children = new[] { instance } }; switch (instance) { case IScoreCounter score: score.Current.Value = 133773; break; case IComboCounter combo: combo.Current.Value = 727; break; } fill.Add(container); } catch { } } return scroll; }); }); } protected override Ruleset CreateRulesetForSkinProvider() => new OsuRuleset(); } }
Test case for store (no-GC) value type to static field
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // using System; struct TestValue { public int a; public short b; public long c; } // This test stores a primitive (no-GC fields) value type to a static field // and checks if the contents are correct. class StaticValueField { const int Pass = 100; const int Fail = -1; static TestValue sField; public static void Init() { TestValue v = new TestValue(); v.a = 100; v.b = 200; v.c = 300; sField = v; } public static int Main() { Init(); if (sField.a == 100 && sField.b == 200 && sField.c == 300) { return Pass; } return Fail; } }
Define a math class in the standard library
namespace System { /// <summary> /// Defines common mathematical functions and operations. /// </summary> public static class Math { public const double PI = 3.14159265358979; } }
Add models for User feedback.
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using CompetitionPlatform.Data.AzureRepositories.Users; namespace CompetitionPlatform.Models { public class FeedbackViewModel : IUserFeedbackData { public string Email { get; set; } [Required] [Display(Name = "Your name")] public string Name { get; set; } [Required] [Display(Name = "Your feedback")] public string Feedback { get; set; } public DateTime Created { get; set; } } public class FeedbackListViewModel { public IEnumerable<IUserFeedbackData> FeedbackList { get; set; } } }
Change assembly version to 1.9.0.0
// // Copyright (c) Microsoft. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Microsoft Azure Graph RBAC Library")] [assembly: AssemblyDescription("Provides Microsoft Azure Graph RBAC access.")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.9.0.0")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Microsoft Azure .NET SDK")] [assembly: AssemblyCopyright("Copyright (c) Microsoft Corporation")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")]
// // Copyright (c) Microsoft. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Microsoft Azure Graph RBAC Library")] [assembly: AssemblyDescription("Provides Microsoft Azure Graph RBAC access.")] [assembly: AssemblyVersion("1.9.0.0")] [assembly: AssemblyFileVersion("1.9.0.0")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Microsoft Azure .NET SDK")] [assembly: AssemblyCopyright("Copyright (c) Microsoft Corporation")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")]
Add event args for product rating
using System; namespace ZobShop.ModelViewPresenter.Product.Details.RateProduct { public class RateProductEventArgs : EventArgs { public RateProductEventArgs(int rating, string content, int productId, string authorId) { this.Rating = rating; this.Content = content; this.ProductId = productId; this.AuthorId = authorId; } public int Rating { get; set; } public string Content { get; set; } public int ProductId { get; set; } public string AuthorId { get; set; } } }
Add a compilation root as a container for individual compilation units created by parsing each file.
using System.Collections.Generic; namespace slang.Compilation { public class CompilationRoot { public CompilationRoot (CompilationMetadata metadata) { CompilationUnits = new List<CompilationUnit> (); Metadata = metadata; } public List<CompilationUnit> CompilationUnits { get; private set; } public CompilationMetadata Metadata { get; private set; } } }
Add some tests for KeyboardDevice.
using Avalonia.Input.Raw; using Avalonia.Interactivity; using Moq; using Xunit; namespace Avalonia.Input.UnitTests { public class KeyboardDeviceTests { [Fact] public void Keypresses_Should_Be_Sent_To_Root_If_No_Focused_Element() { var target = new KeyboardDevice(); var root = new Mock<IInputRoot>(); target.ProcessRawEvent( new RawKeyEventArgs( target, 0, root.Object, RawKeyEventType.KeyDown, Key.A, RawInputModifiers.None)); root.Verify(x => x.RaiseEvent(It.IsAny<KeyEventArgs>())); } [Fact] public void Keypresses_Should_Be_Sent_To_Focused_Element() { var target = new KeyboardDevice(); var focused = new Mock<IInputElement>(); var root = Mock.Of<IInputRoot>(); target.SetFocusedElement( focused.Object, NavigationMethod.Unspecified, InputModifiers.None); target.ProcessRawEvent( new RawKeyEventArgs( target, 0, root, RawKeyEventType.KeyDown, Key.A, RawInputModifiers.None)); focused.Verify(x => x.RaiseEvent(It.IsAny<KeyEventArgs>())); } [Fact] public void TextInput_Should_Be_Sent_To_Root_If_No_Focused_Element() { var target = new KeyboardDevice(); var root = new Mock<IInputRoot>(); target.ProcessRawEvent( new RawTextInputEventArgs( target, 0, root.Object, "Foo")); root.Verify(x => x.RaiseEvent(It.IsAny<TextInputEventArgs>())); } [Fact] public void TextInput_Should_Be_Sent_To_Focused_Element() { var target = new KeyboardDevice(); var focused = new Mock<IInputElement>(); var root = Mock.Of<IInputRoot>(); target.SetFocusedElement( focused.Object, NavigationMethod.Unspecified, InputModifiers.None); target.ProcessRawEvent( new RawTextInputEventArgs( target, 0, root, "Foo")); focused.Verify(x => x.RaiseEvent(It.IsAny<TextInputEventArgs>())); } } }
Add empty viewer for .so and .dylib files
using System.Collections.Generic; using System.Windows.Controls; using NuGetPackageExplorer.Types; namespace PackageExplorer { [PackageContentViewerMetadata(100, ".so", ".dylib")] internal class NativeLibraryFileViewer : IPackageContentViewer { public object GetView(IPackageContent selectedFile, IReadOnlyList<IPackageContent> peerFiles) { return new Grid(); } } }
Add a lint rule that checks for correctness of view definitions.
using System; using System.Collections.Generic; using System.Data; using System.Linq; using Dapper; using SJP.Schematic.Core; namespace SJP.Schematic.Lint.Rules { public class InvalidViewDefinitionRule : Rule { public InvalidViewDefinitionRule(IDbConnection connection, RuleLevel level) : base(RuleTitle, level) { Connection = connection ?? throw new ArgumentNullException(nameof(connection)); } protected IDbConnection Connection { get; } public override IEnumerable<IRuleMessage> AnalyseDatabase(IRelationalDatabase database) { if (database == null) throw new ArgumentNullException(nameof(database)); var dialect = database.Dialect; if (dialect == null) throw new ArgumentException("The dialect on the given database is null.", nameof(database)); return database.Views.SelectMany(v => AnalyseView(dialect, v)).ToList(); } protected IEnumerable<IRuleMessage> AnalyseView(IDatabaseDialect dialect, IRelationalDatabaseView view) { if (dialect == null) throw new ArgumentNullException(nameof(dialect)); if (view == null) throw new ArgumentNullException(nameof(view)); try { var quotedViewName = dialect.QuoteName(view.Name); var query = "select 1 as tmp from " + quotedViewName; var result = Connection.ExecuteScalar(query); return Enumerable.Empty<IRuleMessage>(); } catch { var messageText = $"The view { view.Name } was unable to be queried. This may indicate an incorrect view definition."; var ruleMessage = new RuleMessage(RuleTitle, Level, messageText); return new[] { ruleMessage }; } } private const string RuleTitle = "Invalid view definition."; } }
Add some query unit test
using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Collections; using System.Collections.Generic; using System.Text; using System.Reflection; using System.Text.RegularExpressions; using LiteDB.Engine; namespace LiteDB.Tests.Query { [TestClass] public class Where_Tests { private LiteEngine db; private BsonDocument[] person; [TestInitialize] public void Init() { db = new LiteEngine(); person = DataGen.Person().ToArray(); db.Insert("person", person); db.EnsureIndex("col", "age"); } [TestCleanup] public void CleanUp() { db.Dispose(); } [TestMethod] public void Query_Where_With_Parameter() { var r0 = person .Where(x => x["state"] == "FL") .ToArray(); var r1 = db.Query("person") .Where("state = @0", "FL") .ToArray(); Assert.AreEqual(r0.Length, r1.Length); } [TestMethod] public void Query_Multi_Where() { var r0 = person .Where(x => x["age"] >= 10 && x["age"] <= 40) .Where(x => x["name"].AsString.StartsWith("Ge")) .ToArray(); var r1 = db.Query("person") .Where("age BETWEEN 10 AND 40") .Where("name LIKE 'Ge%'") .ToArray(); Assert.AreEqual(r0.Length, r1.Length); } [TestMethod] public void Query_Single_Where_With_And() { var r0 = person .Where(x => x["age"] == 25 && x["active"].AsBoolean) .ToArray(); var r1 = db.Query("person") .Where("age = 25 AND active = true") .ToArray(); Assert.AreEqual(r0.Length, r1.Length); } [TestMethod] public void Query_Single_Where_With_Or_And_In() { var r0 = person .Where(x => x["age"] == 25 || x["age"] == 26 || x["age"] == 27) .ToArray(); var r1 = db.Query("person") .Where("age = 25 OR age = 26 OR age = 27") .ToArray(); var r2 = db.Query("person") .Where("age IN [25, 26, 27]") .ToArray(); Assert.AreEqual(r0.Length, r1.Length); Assert.AreEqual(r1.Length, r2.Length); } } }
Fix the issues with the persistentId and vessels dissapearing, etc
using Harmony; using LmpCommon.Enums; // ReSharper disable All namespace LmpClient.Harmony { /// <summary> /// This harmony patch is intended to always assign a persistentID and NEVER use the persistent id of the .craft file /// </summary> [HarmonyPatch(typeof(ShipConstruct))] [HarmonyPatch("LoadShip")] [HarmonyPatch(new[] { typeof(ConfigNode), typeof(uint) })] public class ShipConstruct_LoadShip { [HarmonyPrefix] private static void PrefixLoadShip(ConfigNode root, ref uint persistentID) { if (MainSystem.NetworkState < ClientState.Connected) return; if (persistentID == 0) { persistentID = FlightGlobals.GetUniquepersistentId(); foreach (var part in root.GetNodes("PART")) { part.SetValue("persistentId", FlightGlobals.GetUniquepersistentId(), false); } } } } }
Make movement better, still not the best
namespace Engine { public class Vector { public readonly int _x; public readonly int _y; public Vector(int x, int y) { _x = x; _y = y; } } }
Add tests for ITraktHttpRequest interface.
namespace TraktApiSharp.Tests.Experimental.Requests.Interfaces { using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Linq; using System.Net.Http; using TraktApiSharp.Experimental.Requests.Interfaces; [TestClass] public class ITraktHttpRequestTests { [TestMethod] public void TestITraktHttpRequestIsInterface() { typeof(ITraktHttpRequest).IsInterface.Should().BeTrue(); } [TestMethod] public void TestITraktHttpRequestHasMethodProperty() { var methodPropertyInfo = typeof(ITraktHttpRequest).GetProperties() .Where(p => p.Name == "Method") .FirstOrDefault(); methodPropertyInfo.CanRead.Should().BeTrue(); methodPropertyInfo.CanWrite.Should().BeFalse(); methodPropertyInfo.PropertyType.Should().Be(typeof(HttpMethod)); } } }
Add test coverage of editor sample playback
// 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.Graphics.Audio; using osu.Framework.Testing; using osu.Game.Rulesets; using osu.Game.Rulesets.Osu; using osu.Game.Rulesets.Osu.Objects.Drawables; namespace osu.Game.Tests.Visual.Editing { public class TestSceneEditorSamplePlayback : EditorTestScene { protected override Ruleset CreateEditorRuleset() => new OsuRuleset(); [Test] public void TestSlidingSampleStopsOnSeek() { DrawableSlider slider = null; DrawableSample[] samples = null; AddStep("get first slider", () => { slider = Editor.ChildrenOfType<DrawableSlider>().OrderBy(s => s.HitObject.StartTime).First(); samples = slider.ChildrenOfType<DrawableSample>().ToArray(); }); AddStep("start playback", () => EditorClock.Start()); AddUntilStep("wait for slider sliding then seek", () => { if (!slider.Tracking.Value) return false; if (!samples.Any(s => s.Playing)) return false; EditorClock.Seek(20000); return true; }); AddAssert("slider samples are not playing", () => samples.Length == 5 && samples.All(s => s.Played && !s.Playing)); } } }
Copy of other project to get started.
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("PPWCode.Vernacular.Exceptions.I")] [assembly: AssemblyDescription("Main code of the PPWCode Exceptions Vernacular")] [assembly: AssemblyConfiguration("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("a96a19e0-b3e8-4181-a2be-9518870d63d8")]
Add use of tag-helpers instead of razor elements. Remove useless displayfor.
@model eShopWeb.ViewModels.PaginationInfo <div class="esh-pager"> <div class="container"> <article class="esh-pager-wrapper row"> <nav> <a class="esh-pager-item esh-pager-item--navigable @Model.Previous" id="Previous" href="@Url.Action("Index","Catalog", new { page = Model.ActualPage -1 })" aria-label="Previous"> Previous </a> <span class="esh-pager-item"> Showing @Html.DisplayFor(modelItem => modelItem.ItemsPerPage) of @Html.DisplayFor(modelItem => modelItem.TotalItems) products - Page @(Model.ActualPage + 1) - @Html.DisplayFor(x => x.TotalPages) </span> <a class="esh-pager-item esh-pager-item--navigable @Model.Next" id="Next" href="@Url.Action("Index","Catalog", new { page = Model.ActualPage + 1 })" aria-label="Next"> Next </a> </nav> </article> </div> </div>
@model eShopWeb.ViewModels.PaginationInfo <div class="esh-pager"> <div class="container"> <article class="esh-pager-wrapper row"> <nav> <a class="esh-pager-item esh-pager-item--navigable @Model.Previous" id="Previous" asp-controller="Catalog" asp-action="Index" asp-route-page="@(Model.ActualPage -1)" aria-label="Previous"> Previous </a> <span class="esh-pager-item"> Showing @Model.ItemsPerPage of @Model.TotalItems products - Page @(Model.ActualPage + 1) - @Model.TotalPages </span> <a class="esh-pager-item esh-pager-item--navigable @Model.Next" id="Next" asp-controller="Catalog" asp-action="Index" asp-route-page="@(Model.ActualPage + 1)" aria-label="Next"> Next </a> </nav> </article> </div> </div>
Add Unit Test for Report Training Provider Command Handler
using MediatR; using Moq; using NServiceBus; using NUnit.Framework; using SFA.DAS.EmployerAccounts.Commands.ReportTrainingProvider; using SFA.DAS.EmployerAccounts.Configuration; using SFA.DAS.NLog.Logger; using SFA.DAS.Notifications.Messages.Commands; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SFA.DAS.EmployerAccounts.UnitTests.Commands.ReportTrainingProvider { public class WhenReportingATrainingProvider { private ReportTrainingProviderCommandHandler _handler; private Mock<ILog> _logger; private Mock<IMessageSession> _publisher; private EmployerAccountsConfiguration _configuration; private ReportTrainingProviderCommand _validCommand; [SetUp] public void Arrange() { _logger = new Mock<ILog>(); _publisher = new Mock<IMessageSession>(); _configuration = new EmployerAccountsConfiguration { ReportTrainingProviderEmailAddress = "Report@TrainingProvider.com" }; _handler = new ReportTrainingProviderCommandHandler(_publisher.Object, _logger.Object, _configuration); _validCommand = new ReportTrainingProviderCommand("EmployerEmail@dfe.com", DateTime.Now, "TrainingProvider", "TrainingProviderName", DateTime.Now.AddHours(-1)); } [Test] public void ThenAnExceptionIsThrownIfThereIsNoEmailAddressInTheConfiguration() { //Arrange _configuration.ReportTrainingProviderEmailAddress = ""; //Act Assert Assert.ThrowsAsync<ArgumentNullException>(async () => await _handler.Handle(_validCommand)); } [Test] public void ThenAnEmailCommandIsSentWhenAValidCommandIsReceived() { //Arrange var tokens = new Dictionary<string, string>() { {"employer_email", _validCommand.EmployerEmailAddress }, {"email_reported_date", _validCommand.EmailReportedDate.ToString("g") }, {"training_provider", _validCommand.TrainingProvider }, {"training_provider_name", _validCommand.TrainingProviderName }, {"invitation_email_sent_date", _validCommand.InvitationEmailSentDate.ToString("g") }, }; //Act _handler.Handle(_validCommand); //Assert _publisher.Verify(s => s.Send(It.Is<SendEmailCommand>(x => x.Tokens.OrderBy(u => u.Key).SequenceEqual(tokens.OrderBy(t => t.Key)) && x.RecipientsAddress == _configuration.ReportTrainingProviderEmailAddress && x.TemplateId == "ReportTrainingProviderNotification" ), It.IsAny<SendOptions>())); } } }
Add example for storing a private key in a file
using System; using NSec.Cryptography; using System.Collections.Generic; using Xunit; namespace NSec.Tests.Examples { public static class ExportImport { [Fact] public static void ExportImportNSecPrivateKey() { // fake System.IO.File var File = new Dictionary<string, byte[]>(); { #region ExportImport: Export var algorithm = SignatureAlgorithm.Ed25519; var creationParameters = new KeyCreationParameters { ExportPolicy = KeyExportPolicies.AllowPlaintextArchiving }; // create a new key using (var key = new Key(algorithm, creationParameters)) { // export it var blob = key.Export(KeyBlobFormat.NSecPrivateKey); File.WriteAllBytes("myprivatekey.nsec", blob); } #endregion } { #region ExportImport: Import var algorithm = SignatureAlgorithm.Ed25519; var blob = File.ReadAllBytes("myprivatekey.nsec"); // re-import it using (var key = Key.Import(algorithm, blob, KeyBlobFormat.NSecPrivateKey)) { var signature = algorithm.Sign(key, /*{*/new byte[0]/*}*/); } #endregion } } private static void WriteAllBytes(this Dictionary<string, byte[]> dictionary, string key, byte[] value) { dictionary[key] = value; } private static byte[] ReadAllBytes(this Dictionary<string, byte[]> dictionary, string key) { return dictionary[key]; } } }
Add abstract hit object application 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; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Testing; using osu.Framework.Timing; using osu.Game.Beatmaps; using osu.Game.Beatmaps.ControlPoints; using osu.Game.Rulesets.Objects.Drawables; using osu.Game.Rulesets.Taiko.Objects; using osu.Game.Rulesets.UI.Scrolling; using osu.Game.Tests.Visual; namespace osu.Game.Rulesets.Taiko.Tests { public abstract class HitObjectApplicationTestScene : OsuTestScene { [Cached(typeof(IScrollingInfo))] private ScrollingTestContainer.TestScrollingInfo info = new ScrollingTestContainer.TestScrollingInfo { Direction = { Value = ScrollingDirection.Left }, TimeRange = { Value = 1000 }, }; private ScrollingHitObjectContainer hitObjectContainer; [SetUpSteps] public void SetUp() => AddStep("create SHOC", () => Child = hitObjectContainer = new ScrollingHitObjectContainer { RelativeSizeAxes = Axes.X, Height = 200, Anchor = Anchor.Centre, Origin = Anchor.Centre, Clock = new FramedClock(new StopwatchClock()) }); protected void AddHitObject(Func<DrawableHitObject> hitObject) => AddStep("add to SHOC", () => hitObjectContainer.Add(hitObject.Invoke())); protected void RemoveHitObject(Func<DrawableHitObject> hitObject) => AddStep("remove from SHOC", () => hitObjectContainer.Remove(hitObject.Invoke())); protected TObject PrepareObject<TObject>(TObject hitObject) where TObject : TaikoHitObject { hitObject.ApplyDefaults(new ControlPointInfo(), new BeatmapDifficulty()); return hitObject; } } }
Change color of components to highlight them.
//ASynchronous template //----------------------------------------------------------------------------------- // PCB-Investigator Automation Script // Created on 01.03.2016 // Autor support@easylogix.de // www.pcb-investigator.com // SDK online reference http://www.pcb-investigator.com/sites/default/files/documents/InterfaceDocumentation/Index.html // SDK http://www.pcb-investigator.com/en/sdk-participate // // Asynchronous script to highlight selection of CMPs. //----------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Text; using PCBI.Plugin; using PCBI.Plugin.Interfaces; using System.Windows.Forms; using System.Drawing; using PCBI.Automation; using System.IO; using System.Drawing.Drawing2D; using System.Threading; using PCBI.MathUtils; namespace PCBIScript { public class PScript : IPCBIScriptASync { public PScript() { } static List<ICMPObject> firstSelectionToHighlight; public void Execute(IPCBIWindow parent) { //fill code here code IStep step = parent.GetCurrentStep(); bool onOff = false; if (step == null) return; firstSelectionToHighlight = step.GetSelectedCMPs(); step.ClearSelection(); parent.IColorsetting.IfDrawOnlySelectedTransparencyNotSelectedCMPs = 50; parent.IColorsetting.ShowPinNumbers = false; IAutomation.RealTimeDrawing = false; while (true) { Thread.Sleep(1000); parent.IColorsetting.DrawOnlySelectedElements = false; parent.IColorsetting.DrawOnlySelectedCMPs = false; foreach (ICMPObject objSel in firstSelectionToHighlight) { if (onOff) { objSel.ObjectColorTemporary(Color.Red); } else objSel.ObjectColorTemporary(Color.Empty); } onOff = !onOff; parent.UpdateView(); if (isDisposed) break; } } bool isDisposed = false; public void Dispose() { isDisposed = true; //? set back? parent.IColorsetting.DrawOnlySelectedElements = false; if (firstSelectionToHighlight != null) { foreach (ICMPObject objSel in firstSelectionToHighlight) { objSel.ObjectColorTemporary(Color.Empty); } } } } }
Add NStoolbarItem.cs which now supports an Activated event
// // NSToolbarItem.cs: Support for the NSToolbarItem class // // Author: // Johan Hammar // using System; using MonoMac.ObjCRuntime; using MonoMac.Foundation; namespace MonoMac.AppKit { public partial class NSToolbarItem { public event EventHandler Activated { add { Target = ActionDispatcher.SetupAction (Target, value); Action = ActionDispatcher.Action; } remove { ActionDispatcher.RemoveAction (Target, value); } } } }
Fix missing files for release 3.7.4.2704
namespace Patagames.Pdf.Net.Controls.WinForms { /// <summary> /// Represents the scaling options of the page for printing /// </summary> public enum PrintSizeMode { /// <summary> /// Fit page /// </summary> Fit, /// <summary> /// Actual size /// </summary> ActualSize, /// <summary> /// Custom scale /// </summary> CustomScale } }
Add base implementation for agent bus
using System; using System.Collections.Generic; using System.Reactive.Linq; using System.Reactive.Subjects; using System.Reflection; namespace Glimpse.Agent { public class DefaultMessageAgentBus : IMessageAgentBus { private readonly ISubject<IMessage> _subject; // TODO: Review if we care about unifying which thread message is published on // and which thread it is recieved on. If so need to use IScheduler. public DefaultMessageAgentBus() { _subject = new BehaviorSubject<IMessage>(null); } public IObservable<T> Listen<T>() where T : IMessage { return ListenIncludeLatest<T>().Skip(1); } public IObservable<T> ListenIncludeLatest<T>() where T : IMessage { return _subject .Where(msg => typeof(T).GetTypeInfo().IsAssignableFrom(msg.GetType().GetTypeInfo())) .Select(msg => (T)msg); } public IObservable<IMessage> ListenAll() { return ListenAllIncludeLatest().Skip(1); } public IObservable<IMessage> ListenAllIncludeLatest() { return _subject; } public void SendMessage(IMessage message) { _subject.OnNext(message); } } }
Add a Player test scene that uses a legacy skin
// 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.Audio; using osu.Framework.IO.Stores; using osu.Game.Skinning; using osu.Game.Tests.Visual; namespace osu.Game.Rulesets.Catch.Tests { [TestFixture] public class TestSceneCatchPlayerLegacySkin : PlayerTestScene { private ISkinSource legacySkinSource; protected override TestPlayer CreatePlayer(Ruleset ruleset) => new SkinProvidingPlayer(legacySkinSource); [BackgroundDependencyLoader] private void load(AudioManager audio, OsuGameBase game) { var legacySkin = new DefaultLegacySkin(new NamespacedResourceStore<byte[]>(game.Resources, "Skins/Legacy"), audio); legacySkinSource = new SkinProvidingContainer(legacySkin); } protected override Ruleset CreatePlayerRuleset() => new CatchRuleset(); public class SkinProvidingPlayer : TestPlayer { private readonly ISkinSource skinSource; public SkinProvidingPlayer(ISkinSource skinSource) { this.skinSource = skinSource; } protected override IReadOnlyDependencyContainer CreateChildDependencies(IReadOnlyDependencyContainer parent) { var dependencies = new DependencyContainer(base.CreateChildDependencies(parent)); dependencies.CacheAs(skinSource); return dependencies; } } } }
Add snippets for Offset type
// Copyright 2018 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 NUnit.Framework; using System; namespace NodaTime.Demo { public class OffsetDemo { [Test] public void ConstructionFromHours() { Offset offset = Snippet.For(Offset.FromHours(1)); Assert.AreEqual(3600, offset.Seconds); } [Test] public void ConstructionFromHoursAndMinutes() { Offset offset = Snippet.For(Offset.FromHoursAndMinutes(1, 1)); Assert.AreEqual(3660, offset.Seconds); } [Test] public void ConstructionFromSeconds() { Offset offset = Snippet.For(Offset.FromSeconds(450)); Assert.AreEqual(450, offset.Seconds); } [Test] public void ConstructionFromMilliseconds() { Offset offset = Snippet.For(Offset.FromMilliseconds(1200)); Assert.AreEqual(1, offset.Seconds); Assert.AreEqual(1000, offset.Milliseconds); } [Test] public void ConstructionFromTicks() { Offset offset = Snippet.For(Offset.FromTicks(15_000_000)); Assert.AreEqual(10_000_000, offset.Ticks); Assert.AreEqual(1, offset.Seconds); } [Test] public void ConstructionFromNanoseconds() { Offset offset = Snippet.For(Offset.FromNanoseconds(1_200_000_000)); Assert.AreEqual(1, offset.Seconds); Assert.AreEqual(1_000_000_000, offset.Nanoseconds); } [Test] public void ConstructionFromTimeSpan() { var timespan = TimeSpan.FromHours(1.5); Offset offset = Snippet.For(Offset.FromTimeSpan(timespan)); Assert.AreEqual(5400, offset.Seconds); } [Test] public void Plus() { var offset = Offset.FromSeconds(100); var offset2 = Offset.FromSeconds(150); var expected = Offset.FromSeconds(250); var actual = Snippet.For(offset.Plus(offset2)); Assert.AreEqual(expected, actual); } [Test] public void Minus() { var offset = Offset.FromSeconds(100); var offset2 = Offset.FromSeconds(120); var expected = Offset.FromSeconds(-20); var actual = Snippet.For(offset.Minus(offset2)); Assert.AreEqual(expected, actual); } [Test] public void ToTimeSpan() { var offset = Offset.FromSeconds(120); var actual = Snippet.For(offset.ToTimeSpan()); var expected = TimeSpan.FromSeconds(120); Assert.AreEqual(expected, actual); } } }
Add Maverick Sevmont as author
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using System.Web; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class MaverickSevmont : IAmACommunityMember { public string FirstName => "Maverick"; public string LastName => "Sevmont"; public string ShortBioOrTagLine => "Yet another PowerShell nerd"; public string StateOrRegion => "Mexico City, Mexico"; public string EmailAddress => "sevmont@gmail.com"; public string TwitterHandle => ""; public string GravatarHash => "d121a69f0572374af7efcc407160efc9"; public string GitHubHandle => "mavericksevmont"; public GeoPosition Position => new GeoPosition(19.432608, -99.133209); public Uri WebSite => new Uri("https://tech.mavericksevmont.com"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://tech.mavericksevmont.com/blog/feed/"); } } } }
Add RFC 7693 test vectors
using System; using NSec.Cryptography; using Xunit; namespace NSec.Tests.Rfc { public static class Blake2Tests { public static readonly TheoryData<string, string> Rfc7693TestVectors = new TheoryData<string, string> { { "616263", "ba80a53f981c4d0d6a2797b69f12f6e94c212f14685ac4b74b12bb6fdbffa2d17d87c5392aab792dc252d5de4533cc9518d38aa8dbf1925ab92386edd4009923" }, }; [Theory] [MemberData(nameof(Rfc7693TestVectors))] public static void TestRfc7693(string msg, string hash) { var a = new Blake2(); var expected = hash.DecodeHex(); var actual = a.Hash(msg.DecodeHex(), expected.Length); Assert.Equal(expected, actual); } } }
Test to verify type name handling on newtonsoft using additional converter
namespace MassTransit.Tests.Serialization { using System; using System.Linq; using System.Threading.Tasks; using MassTransit.Testing; using Microsoft.Extensions.DependencyInjection; using Newtonsoft.Json; using NUnit.Framework; [TestFixture] public class When_using_type_name_handling_auto { [Test] public async Task Should_properly_deserialize_the_message() { await using var provider = new ServiceCollection() .AddMassTransitTestHarness(x => { x.AddHandler(async (SampleMessage message) => { }); x.UsingInMemory((context, cfg) => { var typeNameHandlingConverter = new TypeNameHandlingConverter(TypeNameHandling.Auto); cfg.ConfigureNewtonsoftJsonSerializer(settings => { settings.Converters.Add(typeNameHandlingConverter); return settings; }); cfg.ConfigureNewtonsoftJsonDeserializer(settings => { settings.Converters.Add(typeNameHandlingConverter); return settings; }); cfg.UseNewtonsoftJsonSerializer(); cfg.ConfigureEndpoints(context); }); }) .BuildServiceProvider(true); var harness = provider.GetTestHarness(); await harness.Start(); await harness.Bus.Publish(new SampleMessage { EventId = "667" }); Assert.That(await harness.Consumed.Any<SampleMessage>(), Is.True); IReceivedMessage<SampleMessage> context = harness.Consumed.Select<SampleMessage>().First(); Assert.That(context.Context.Message.EventId, Is.EqualTo("667")); } public class SampleMessage { public string EventId { get; set; } } class TypeNameHandlingConverter : JsonConverter { readonly JsonSerializer _serializer; public TypeNameHandlingConverter(TypeNameHandling typeNameHandling) { _serializer = new JsonSerializer { TypeNameHandling = typeNameHandling }; } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { _serializer.Serialize(writer, value); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { return _serializer.Deserialize(reader, objectType); } public override bool CanConvert(Type objectType) { return !IsMassTransitOrSystemType(objectType); } static bool IsMassTransitOrSystemType(Type objectType) { return objectType.Assembly == typeof(IConsumer).Assembly || // MassTransit.Abstractions objectType.Assembly == typeof(MassTransitBus).Assembly || // MassTransit objectType.Assembly.IsDynamic || objectType.Assembly == typeof(object).Assembly; } } } }
Remove dupes, keep lexicographic order, take 1 - wrong
// http://careercup.com/question?id=5758790009880576 // // Given a string with lowercase chars, delete the repeated // letters and only leave one but with the optimal // lexicographic order using System; using System.Collections.Generic; using System.Linq; using System.Text; static class Program { static String DeDup(this String s) { var hash = new Dictionary<char, int>(); for (int i = 0; i < s.Length; i++) { if (!hash.ContainsKey(s[i])) { hash[s[i]] = i; } } StringBuilder result = new StringBuilder(); for (var c = 'a'; c < 'z'; c++) { if (hash.ContainsKey(c)) { result.Append(c); } } return result.ToString(); } static void Main() { new [] { Tuple.Create("bcabc", "abc"), Tuple.Create("cbacdcbc", "acdb") }.ToList().ForEach(x => { if (x.Item1.DeDup() != x.Item2) { throw new Exception(String.Format("You're not good enough, look : {0}={1}", x.Item1, x.Item1.DeDup())); } }); Console.WriteLine("All appears to be well"); } }
Use this script to test the physics
using UnityEngine; public class NudgeMe : MonoBehaviour { public float xDir = 1000; public float yDir = 1000; // Update is called once per frame void Update () { if(Input.GetKey (KeyCode.Space)){ this.gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector2(xDir,yDir)); } } }
Make the sample have good coding :-)
// mcs -pkg:gtkhtml-sharp -pkg:gtk-sharp gtk-html-sample.cs using Gtk; using System; using System.IO; class HTMLSample { static int Main (string [] args) { HTML html; Window win; Application.Init (); html = new HTML (); win = new Window ("Test"); win.Add (html); HTMLStream s = html.Begin ("text/html"); if (args.Length > 0){ StreamReader r = new StreamReader (File.OpenRead (args [0])); s.Write (r.ReadToEnd ()); } else { s.Write ("<html><body>"); s.Write ("Hello world!"); } html.End (s, HTMLStreamStatus.Ok); win.ShowAll (); Application.Run (); return 0; } }
// mcs -pkg:gtkhtml-sharp -pkg:gtk-sharp gtk-html-sample.cs using Gtk; using System; using System.IO; class HTMLSample { static int Main (string [] args) { HTML html; Window win; Application.Init (); html = new HTML (); win = new Window ("Test"); win.Add (html); HTMLStream s = html.Begin ("text/html"); if (args.Length > 0) { using (StreamReader r = File.OpenText (args [0])) s.Write (r.ReadToEnd ()); } else { s.Write ("<html><body>"); s.Write ("Hello world!"); } html.End (s, HTMLStreamStatus.Ok); win.ShowAll (); Application.Run (); return 0; } }
Call Dispose on the messageConsumer and add a Guid to the message payload.
using System; using FluentAssertions; using Paramore.Brighter.MessagingGateway.Kafka; using Xunit; namespace Paramore.Brighter.Tests.MessagingGateway.Kafka { [Trait("Category", "KAFKA")] public class KafkaMessageProducerSendTests : IDisposable { private const string QueueName = "test"; private const string Topic = "test"; private IAmAMessageProducer _messageProducer; private IAmAMessageConsumer _messageConsumer; private Message _message; public KafkaMessageProducerSendTests() { var gatewayConfiguration = new KafkaMessagingGatewayConfiguration { Name = "paramore.brighter", BootStrapServers = new[] { "localhost:9092" } }; _messageProducer = new KafkaMessageProducerFactory(gatewayConfiguration).Create(); _messageConsumer = new KafkaMessageConsumerFactory(gatewayConfiguration).Create(QueueName, Topic, false, 10, false); var messageGuid = Guid.NewGuid(); var messageBodyData = "test content {" + messageGuid + "}"; _message = new Message(new MessageHeader(messageGuid, Topic, MessageType.MT_COMMAND), new MessageBody(messageBodyData)); } [Fact] public void When_posting_a_message_via_the_messaging_gateway() { _messageConsumer.Receive(30000); //Need to receive to subscribe to feed, before we send a message. This returns an empty message we discard _messageProducer.Send(_message); var sentMessage = _messageConsumer.Receive(30000); var messageBody = sentMessage.Body.Value; _messageConsumer.Acknowledge(sentMessage); //_should_send_a_message_via_restms_with_the_matching_body messageBody.Should().Be(_message.Body.Value); //_should_have_an_empty_pipe_after_acknowledging_the_message } public void Dispose() { _messageConsumer.Dispose(); _messageProducer.Dispose(); } } }
Add util classes to deal with specific claims.
using A2BBCommon; using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; namespace A2BBAPI.Utils { public static class ClaimsUtils { #region Nested classes /// <summary> /// Holder for authorized user claims. /// </summary> public class ClaimsHolder { /// <summary> /// The name claim. /// </summary> public string Name { get; set; } /// <summary> /// The subject claim. /// </summary> public string Sub { get; set; } } #endregion #region Public static methods /// <summary> /// Validate principal for identity server call. /// </summary> /// <returns>An holder class with useful user claims.</returns> public static ClaimsHolder ValidateUserClaimForIdSrvCall(ClaimsPrincipal principal) { var subClaim = principal.Claims.FirstOrDefault(c => c.Type == "sub"); if (subClaim == null || String.IsNullOrWhiteSpace(subClaim.Value)) { throw new RestReturnException(Constants.RestReturn.ERR_INVALID_SUB_CLAIM); } var name = principal.Identity.Name; if (name == null || String.IsNullOrWhiteSpace(name)) { throw new RestReturnException(Constants.RestReturn.ERR_INVALID_NAME_CLAIM); } return new ClaimsHolder { Name = name, Sub = subClaim.Value }; } #endregion } }
Add missing tests for write lock
using Xunit; namespace RdbmsEventStore.Tests { public class WriteLockTests { [Fact] public void SameIdCannotEnterLockSimultaneously() { var mutex = new WriteLock<int>(); var lock1 = mutex.Aquire(1); var lock2 = mutex.Aquire(1); Assert.True(lock1.AsTask().IsCompleted); Assert.False(lock2.AsTask().IsCompleted); } [Fact] public void DifferentIdsCanEnterLockSimultaneously() { var mutex = new WriteLock<int>(); var lock1 = mutex.Aquire(1); var lock2 = mutex.Aquire(2); Assert.True(lock1.AsTask().IsCompleted, "First stream could not enter locked path."); Assert.True(lock2.AsTask().IsCompleted, "Second stream could not enter locked path."); } } }
Move directions and orientations into global enums
public enum Side : byte { Right, Left, Top, Bottom }; public enum Position : byte { TopLeft, TopCenter, TopRight, MiddleLeft, MiddleCenter, MiddleRight, BottomLeft, BottomCenter, BottomRight }
Add placeholder test to avoid build warnings
// Copyright 2021 Google LLC // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Xunit; namespace Google.Cloud.ApigeeConnect.V1.Tests { // No tests are currently generated for ConnectionServiceClient and TetherClient as all the methods // are paginated or streaming. This causes a warning when building, so this placeholder test // just effectively suppresses this warning. If we ever generate actual tests, this // class can be removed. public class PlaceholderTest { [Fact] public void Placeholder() => Assert.Equal(5, 5); } }
Add Servant Controller with retrieval and creation endpoints
using Microsoft.AspNetCore.Mvc; using StoryGenerator.Domain; using StoryGenerator.Persistance; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace StoryGenerator.Controllers { [Route("api/servants")] public class ServantController : Controller { private ServantRepository ServantRepository; public ServantController() { ServantRepository = new ServantRepository(); } [HttpGet("{id}")] public dynamic GetServantById(int id) { var servant = ServantRepository.GetServantById(id); if(servant != null) { return servant; } else { return NoContent(); } } [HttpPost] public dynamic SaveServant([FromBody] Servant servant) { ServantRepository.SaveServant(servant); return "Servant has been created"; } } }
Add a test for fruit randomness
// 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.Bindables; using osu.Game.Rulesets.Catch.Objects; using osu.Game.Rulesets.Catch.Objects.Drawables; using osu.Game.Tests.Visual; namespace osu.Game.Rulesets.Catch.Tests { public class TestSceneFruitRandomness : OsuTestScene { [Test] public void TestFruitRandomness() { Bindable<int> randomSeed = new Bindable<int>(); TestDrawableFruit drawableFruit; TestDrawableBanana drawableBanana; Add(new TestDrawableCatchHitObjectSpecimen(drawableFruit = new TestDrawableFruit(new Fruit()) { RandomSeed = { BindTarget = randomSeed } }) { X = -200 }); Add(new TestDrawableCatchHitObjectSpecimen(drawableBanana = new TestDrawableBanana(new Banana()) { RandomSeed = { BindTarget = randomSeed } })); float fruitRotation = 0; float bananaRotation = 0; float bananaScale = 0; AddStep("set random seed to 0", () => { drawableFruit.HitObject.StartTime = 500; randomSeed.Value = 0; fruitRotation = drawableFruit.InnerRotation; bananaRotation = drawableBanana.InnerRotation; bananaScale = drawableBanana.InnerScale; }); AddStep("change random seed", () => { randomSeed.Value = 10; }); AddAssert("fruit rotation is changed", () => drawableFruit.InnerRotation != fruitRotation); AddAssert("banana rotation is changed", () => drawableBanana.InnerRotation != bananaRotation); AddAssert("banana scale is changed", () => drawableBanana.InnerScale != bananaScale); AddStep("reset random seed", () => { randomSeed.Value = 0; }); AddAssert("rotation and scale restored", () => drawableFruit.InnerRotation == fruitRotation && drawableBanana.InnerRotation == bananaRotation && drawableBanana.InnerScale == bananaScale); AddStep("change start time", () => { drawableFruit.HitObject.StartTime = 1000; }); AddAssert("random seed is changed", () => randomSeed.Value == 1000); AddSliderStep("random seed", 0, 100, 0, x => randomSeed.Value = x); } private class TestDrawableFruit : DrawableFruit { public float InnerRotation => ScaleContainer.Rotation; public TestDrawableFruit(Fruit h) : base(h) { } } private class TestDrawableBanana : DrawableBanana { public float InnerRotation => ScaleContainer.Rotation; public float InnerScale => ScaleContainer.Scale.X; public TestDrawableBanana(Banana h) : base(h) { } } } }
Add tests for enumerable formatting ComplexObjectToPseudoCode
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ExpressionToCodeLib; using Xunit; namespace ExpressionToCodeTest { public class EnumerableFormattingTest { [Fact] public void ShortArraysRenderedCompletely() { Assert.Equal("new[] {1, 2, 3}", ObjectToCode.ComplexObjectToPseudoCode(new[] { 1, 2, 3 })); } [Fact] public void ShortEnumerablesRenderedCompletely() { Assert.Equal("{1, 2, 3}", ObjectToCode.ComplexObjectToPseudoCode(Enumerable.Range(1, 3))); } [Fact] public void LongEnumerablesBreakAfter10() { Assert.Equal("{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...}", ObjectToCode.ComplexObjectToPseudoCode(Enumerable.Range(1, 13))); } [Fact] public void LongArraysBreakAfter10() { Assert.Equal("new[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...}", ObjectToCode.ComplexObjectToPseudoCode(Enumerable.Range(1, 13).ToArray())); } } }
Add extension search method for game object collection.
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Infusion.LegacyApi { public static class GameObjectCollectionExtensions { public static IEnumerable<GameObject> OfType(this IEnumerable<GameObject> objects, ModelId type) => objects.Where(o => o.Type == type); public static IEnumerable<GameObject> OfType(this IEnumerable<GameObject> objects, ModelId[] types) => objects.Where(o => types.Contains(o.Type)); public static IEnumerable<GameObject> OfColor(this IEnumerable<GameObject> gameObjects, Color? color) => gameObjects.Where(o => { if (o is Item i) return i.Color == color; if (o is Mobile m) return m.Color == color; return false; }); public static IEnumerable<GameObject> OnGround(this IEnumerable<GameObject> objects) => objects.Where(o => o.IsOnGround); public static IEnumerable<GameObject> OrderByDistance(this IEnumerable<GameObject> objects) => objects.OrderBy(o => o.GetDistance(UO.Me.Location)); public static IEnumerable<GameObject> OrderByDistance(this IEnumerable<GameObject> objects, Location3D referenceLocation) => objects.OrderBy(o => o.GetDistance(referenceLocation)); public static IEnumerable<GameObject> MaxDistance(this IEnumerable<GameObject> objects, ushort maxDistance) => objects.Where(o => o.GetDistance(UO.Me.Location) <= maxDistance); public static IEnumerable<GameObject> MaxDistance(this IEnumerable<GameObject> objects, Location2D referenceLocation, ushort maxDistance) => objects.Where(o => o.GetDistance(referenceLocation) <= maxDistance); public static IEnumerable<GameObject> MaxDistance(this IEnumerable<GameObject> objects, Location3D referenceLocation, ushort maxDistance) => MaxDistance(objects, (Location2D)referenceLocation, maxDistance); public static IEnumerable<GameObject> MinDistance(this IEnumerable<GameObject> objects, Location2D referenceLocation, ushort minDistance) => objects.Where(o => o.GetDistance(referenceLocation) >= minDistance); public static IEnumerable<GameObject> MinDistance(this IEnumerable<GameObject> objects, ushort minDistance) => objects.Where(o => o.GetDistance(UO.Me.Location) >= minDistance); } }
Add new attribute for authorization.
using System; using Bibliotheca.Server.Mvc.Middleware.Authorization.SecureTokenAuthentication; using Bibliotheca.Server.Mvc.Middleware.Authorization.UserTokenAuthentication; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Authorization; namespace Bibliotheca.Server.Mvc.Middleware.Authorization { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)] public class UserAuthorizeAttribute : AuthorizeAttribute { public UserAuthorizeAttribute() : base($"{SecureTokenSchema.Name}, {UserTokenSchema.Name}, {JwtBearerDefaults.AuthenticationScheme}") { } } }
Add custom listbox item class
using System.Windows.Controls; using System.Windows.Forms; namespace food_tracker { public class FoodBoxItem : ListBoxItem { public int calories { get; set; } public int fats { get; set; } public int saturatedFat { get; set; } public int carbohydrates { get; set; } public int sugar { get; set; } public int protein { get; set; } public int salt { get; set; } public string name { get; set; } public FoodBoxItem() : base() { } public FoodBoxItem(int cals, int fats, int satFat, int carbs, int sugars, int protein, int salt, string name) { this.name = name; this.calories = cals; this.fats = fats; this.salt = salt; this.saturatedFat = satFat; this.carbohydrates = carbs; this.sugar = sugars; this.protein = protein; } public override string ToString() { return name; } } }
Define the log levels supported by the abstract logging API.
using System; using System.Collections.Generic; using System.Text; namespace Nohros.Logging { /// <summary> /// The supported logging levels. Not all loggin libraries support all the levels and when is /// the case the related <see cref="ILogger"/> object will always return false for the /// Is"LogLevel"Enabled. /// </summary> public enum LogLevel { /// <summary> /// All logging levels. /// </summary> All = 0, /// <summary> /// A TRACE logging level. /// </summary> Trace = 1, /// <summary> /// A DEBUG logging level. /// </summary> Debug = 2, /// <summary> /// A INFO loggin level. /// </summary> Info = 3, /// <summary> /// A WARN logging level. /// </summary> Warn = 4, /// <summary> /// A ERROR logging level. /// </summary> Error = 5, /// <summary> /// A FATAL logging level. /// </summary> Fatal = 6, /// <summary> /// Do not log anything. /// </summary> Off = 7 } }
Add dedicated class for listing application credits
using System.Collections.Generic; namespace ShopifySharp.Filters { public class ApplicationCreditListFilter : ListFilter { public string Fields { get; set; } public override IEnumerable<KeyValuePair<string, object>> ToQueryParameters() { return base.ToQueryParameters(); } } }
Add basic structure for HSV colour picker part
// 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.Bindables; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; namespace osu.Framework.Graphics.UserInterface { /// <summary> /// Control that allows for specifying a colour using the hue-saturation-value (HSV) colour model. /// </summary> public abstract class HSVColourPicker : CompositeDrawable, IHasCurrentValue<Colour4> { private readonly BindableWithCurrent<Colour4> current = new BindableWithCurrent<Colour4>(); public Bindable<Colour4> Current { get => current.Current; set => current.Current = value; } private readonly Box background; private readonly SaturationValueSelector saturationValueSelector; private readonly HueSelector hueSelector; protected HSVColourPicker() { AutoSizeAxes = Axes.Both; InternalChildren = new Drawable[] { background = new Box { RelativeSizeAxes = Axes.Both }, new FillFlowContainer { Direction = FillDirection.Vertical, Children = new Drawable[] { saturationValueSelector = CreateSaturationValueSelector(), hueSelector = CreateHueSelector() } } }; } /// <summary> /// Creates the control to be used for interactively selecting the hue of the target colour. /// </summary> protected abstract HueSelector CreateHueSelector(); /// <summary> /// Creates the control to be used for interactively selecting the saturation and value of the target colour. /// </summary> protected abstract SaturationValueSelector CreateSaturationValueSelector(); protected override void LoadComplete() { base.LoadComplete(); saturationValueSelector.Hue.BindTo(hueSelector.Hue); saturationValueSelector.Hue.BindValueChanged(_ => updateCurrent()); saturationValueSelector.Saturation.BindValueChanged(_ => updateCurrent()); saturationValueSelector.Value.BindValueChanged(_ => updateCurrent(), true); } private void updateCurrent() { Current.Value = Colour4.FromHSV(saturationValueSelector.Hue.Value, saturationValueSelector.Saturation.Value, saturationValueSelector.Value.Value); } public abstract class SaturationValueSelector : CompositeDrawable { public Bindable<float> Hue { get; } = new BindableFloat { MinValue = 0, MaxValue = 1 }; public Bindable<float> Saturation { get; } = new BindableFloat { MinValue = 0, MaxValue = 1 }; public Bindable<float> Value { get; } = new BindableFloat { MinValue = 0, MaxValue = 1 }; } public abstract class HueSelector : CompositeDrawable { public Bindable<float> Hue { get; } = new BindableFloat { MinValue = 0, MaxValue = 1 }; } } }
Add car move event arguments
// CarMovedEventArgs.cs // <copyright file="CarMovedEventArgs.cs"> This code is protected under the MIT License. </copyright> namespace Tron.EventArgs { /// <summary> /// The event arguments for when the timer changes. /// </summary> public class CarMovedEventArgs : System.EventArgs { /// <summary> /// Initializes a new instance of the <see cref="CarMovedEventArgs" /> class. /// </summary> /// <param name="id"> The car's id number. </param> /// <param name="x"> The car's x position. </param> /// <param name="y"> The car's y position. </param> public CarMovedEventArgs(int id, int x, int y) { this.ID = id; this.X = x; this.Y = y; } /// <summary> /// Gets or sets the car's id number. /// </summary> public int ID { get; set; } /// <summary> /// Gets or sets the car's new x position. /// </summary> public int X { get; set; } /// <summary> /// Gets or sets the car's new y position. /// </summary> public int Y { get; set; } } }
Add Html extension method for Kendo grid.
namespace SupportMe.Web.Infrastructure.HtmlHelpers { using System; using System.Linq.Expressions; using System.Web.Mvc; using Kendo.Mvc.UI; using Kendo.Mvc.UI.Fluent; public static class KendoHelpers { public static GridBuilder<T> FullFeaturedGrid<T>( this HtmlHelper helper, string controllerName, Expression<Func<T, object>> modelIdExpression, Action<GridColumnFactory<T>> columns = null) where T : class { if (columns == null) { columns = cols => { cols.AutoGenerate(true); cols.Command(c => c.Edit()); cols.Command(c => c.Destroy()); }; } return helper.Kendo() .Grid<T>() .Name("grid") .Columns(columns) .ColumnMenu() .Pageable(page => page.Refresh(true)) .Sortable() .Groupable() .Filterable() .Editable(edit => edit.Mode(GridEditMode.PopUp)) .ToolBar(toolbar => toolbar.Create()) .DataSource(data => data .Ajax() .Model(m => m.Id(modelIdExpression)) .Read(read => read.Action("Read", controllerName)) .Create(create => create.Action("Create", controllerName)) .Update(update => update.Action("Update", controllerName)) .Destroy(destroy => destroy.Action("Destroy", controllerName))); } } }
Add an interface for scrubbing rollbar data.
using Valetude.Rollbar; namespace Nancy.Rollbar.Api { public interface IRollbarDataScrubber{ RollbarData ScrubRollbarData(RollbarData data); } }
Convert a MusicBrainz date into a DateTime object
/* -*- Mode: csharp; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: t -*- */ /*************************************************************************** * Utilities.cs * * Copyright (C) 2005 Novell * Written by Aaron Bockover (aaron@aaronbock.net) ****************************************************************************/ /* THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW: * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ using System; namespace MusicBrainz { public class Utilities { public static DateTime StringToDateTime(string musicBrainzDate) { if(musicBrainzDate == null || musicBrainzDate == String.Empty) { return DateTime.MinValue; } // because the DateTime parser is *slow* string [] parts = musicBrainzDate.Split('-'); if(parts.Length < 3) { return DateTime.MinValue; } try { return new DateTime( Convert.ToInt32(parts[0]), // year Convert.ToInt32(parts[1]), // month Convert.ToInt32(parts[2]) // day ); } catch(Exception) { return DateTime.MinValue; } } } }
Add initial page permission enums.
using System; namespace MitternachtWeb.Models { [Flags] public enum BotPagePermissions { None = 0b00, ReadBotConfig = 0b01, WriteBotConfig = 0b11, } [Flags] public enum GuildPagePermissions { None = 0b_0000_0000, ReadGuildConfig = 0b_0000_0001, WriteGuildConfig = 0b_0000_0011, } }
Add unit test for strongly connected components.
 namespace CSparse.Tests.Ordering { using CSparse.Double; using CSparse.Ordering; using NUnit.Framework; using System; public class TestStronglyConnectedComponents { [Test] public void TestScc() { // https://en.wikipedia.org/wiki/Strongly_connected_component // // Adjacency list of directed graph with 8 nodes: // // [1] -> 2 // [2] -> 3 -> 5 -> 6 // [3] -> 4 -> 7 // [4] -> 3 -> 8 // [5] -> 1 -> 6 // [6] -> 7 // [7] -> 6 // [8] -> 4 -> 7 // // Adjacency matrix: var A = SparseMatrix.OfRowMajor(8, 8, new double[8 * 8] { 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1 }); int n = A.ColumnCount; var scc = StronglyConnectedComponents.Generate(A); var r = new int[] { 0, 3, 6, 8 }; var p = new int[] { 0, 1, 4, 2, 3, 7, 5, 6 }; Assert.AreEqual(scc.Blocks, 3); CollectionAssert.AreEqual(scc.BlockPointers, r); CollectionAssert.AreEqual(scc.Indices, p); } } }
Add more SDL2 native functions
// 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.Numerics; using System.Runtime.InteropServices; using osu.Framework.Graphics; using Veldrid.Sdl2; // ReSharper disable InconsistentNaming namespace osu.Framework.Platform { public unsafe class Sdl2Functions { [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void SDL_GL_GetDrawableSize_t(SDL_Window window, int* w, int* h); private static readonly SDL_GL_GetDrawableSize_t s_glGetDrawableSize = Sdl2Native.LoadFunction<SDL_GL_GetDrawableSize_t>("SDL_GL_GetDrawableSize"); public static Vector2 SDL_GL_GetDrawableSize(SDL_Window window) { int w, h; s_glGetDrawableSize(window, &w, &h); return new Vector2(w, h); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void SDL_GetWindowBordersSize_t(SDL_Window window, int* top, int* left, int* bottom, int* right); private static readonly SDL_GetWindowBordersSize_t s_glGetWindowBordersSize = Sdl2Native.LoadFunction<SDL_GetWindowBordersSize_t>("SDL_GetWindowBordersSize"); public static MarginPadding SDL_GetWindowBordersSize(SDL_Window window) { int top, left, bottom, right; s_glGetWindowBordersSize(window, &top, &left, &bottom, &right); return new MarginPadding { Top = top, Left = left, Bottom = bottom, Right = right }; } } }
Add command line project loading
using System; using System.ComponentModel; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using Confuser.Core.Project; using ConfuserEx.ViewModel; namespace ConfuserEx { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); var app = new AppVM(); app.Project = new ProjectVM(new ConfuserProject()); app.FileName = "Unnamed.crproj"; app.Tabs.Add(new ProjectTabVM(app)); app.Tabs.Add(new SettingsTabVM(app)); app.Tabs.Add(new ProtectTabVM(app)); app.Tabs.Add(new AboutTabVM(app)); DataContext = app; } void OpenMenu(object sender, RoutedEventArgs e) { var btn = (Button)sender; ContextMenu menu = btn.ContextMenu; menu.PlacementTarget = btn; menu.Placement = PlacementMode.MousePoint; menu.IsOpen = true; } protected override void OnClosing(CancelEventArgs e) { base.OnClosing(e); e.Cancel = !((AppVM)DataContext).OnWindowClosing(); } } }
using System; using System.ComponentModel; using System.IO; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Xml; using Confuser.Core.Project; using ConfuserEx.ViewModel; namespace ConfuserEx { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); var app = new AppVM(); app.Project = new ProjectVM(new ConfuserProject()); app.FileName = "Unnamed.crproj"; app.Tabs.Add(new ProjectTabVM(app)); app.Tabs.Add(new SettingsTabVM(app)); app.Tabs.Add(new ProtectTabVM(app)); app.Tabs.Add(new AboutTabVM(app)); LoadProj(app); DataContext = app; } void OpenMenu(object sender, RoutedEventArgs e) { var btn = (Button)sender; ContextMenu menu = btn.ContextMenu; menu.PlacementTarget = btn; menu.Placement = PlacementMode.MousePoint; menu.IsOpen = true; } void LoadProj(AppVM app) { var args = Environment.GetCommandLineArgs(); if (args.Length != 2 || !File.Exists(args[1])) return; string fileName = args[1]; try { var xmlDoc = new XmlDocument(); xmlDoc.Load(fileName); var proj = new ConfuserProject(); proj.Load(xmlDoc); app.Project = new ProjectVM(proj); app.FileName = fileName; } catch { MessageBox.Show("Invalid project!", "ConfuserEx", MessageBoxButton.OK, MessageBoxImage.Error); } } protected override void OnClosing(CancelEventArgs e) { base.OnClosing(e); e.Cancel = !((AppVM)DataContext).OnWindowClosing(); } } }
Embed assembly info and version
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("https://github.com/thekid/inotify-win")] [assembly: AssemblyDescription("A port of the inotifywait tool for Windows")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Timm Friebe")] [assembly: AssemblyProduct("inotify-win")] [assembly: AssemblyCopyright("Copyright © 2012 - 2014 Timm Friebe")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("1.5.0.1")] [assembly: ComVisible(false)] [assembly: Guid("4254314b-ae21-4e2f-ba52-d6f3d83a86b5")]
Add notes on the alert model
namespace BatteryCommander.Web.Models { public class Alert { // Id // SentAt // Recipients - IDs? - Pull Phone, Email from Soldier entity // Format - SMS? Email? Phone? // Message / Content // Status - Open, Closed -- Only one open at a time, all responses will be attributed to that alert // Responses - FROM, CONTENT // Request Ack T/F? // What about sending a short-URL to acknowledge receipt? https://abcd.red-leg-dev.com/Alert/{id}/Acknowledge // User enters name/identifying info, accessible from phones, can provide more context // OR, each user gets a custom URL based on receipient hash so that we don't even need more than a big ACK button? } }
Add tests for Project Resources.
using System.Collections.Generic; using DigitalOcean.API.Clients; using DigitalOcean.API.Http; using DigitalOcean.API.Models.Requests; using DigitalOcean.API.Models.Responses; using NSubstitute; using RestSharp; using Xunit; namespace DigitalOcean.API.Tests.Clients { public class ProjectResourcesClientTest { [Fact] public void CorrectRequestForGetResources() { var factory = Substitute.For<IConnection>(); var client = new ProjectResourcesClient(factory); client.GetResources("project:abc123"); var parameters = Arg.Is<List<Parameter>>(list => (string)list[0].Value == "project:abc123"); factory.Received().GetPaginated<ProjectResource>("projects/{project_id}/resources", parameters, "resources"); } [Fact] public void CorrectRequestForGetDefaultResources() { var factory = Substitute.For<IConnection>(); var client = new ProjectResourcesClient(factory); client.GetDefaultResources(); factory.Received().GetPaginated<ProjectResource>("projects/default/resources", null, "resources"); } [Fact] public void CorrectRequestForAssignResources() { var factory = Substitute.For<IConnection>(); var client = new ProjectResourcesClient(factory); var resources = new AssignResourceNames() { Resources = new List<string>() { "do:droplet:9001", "do:droplet:9002" } }; client.AssignResources("project:abc123", resources); var parameters = Arg.Is<List<Parameter>>(list => (string)list[0].Value == "project:abc123"); factory.Received().ExecuteRequest<List<ProjectResource>>("projects/{project_id}/resources", parameters, resources, "resources", Method.POST); } [Fact] public void CorrectRequestForAssignDefaultResources() { var factory = Substitute.For<IConnection>(); var client = new ProjectResourcesClient(factory); var resources = new AssignResourceNames() { Resources = new List<string>() { "do:droplet:9001", "do:droplet:9002" } }; client.AssignDefaultResources(resources); factory.Received().ExecuteRequest<List<ProjectResource>>("projects/default/resources", null, resources, "resources", Method.POST); } } }
Add EventStore implementation of IEventStore.
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Xml.Serialization; using EventStore.ClientAPI; namespace Edument.CQRS { // An implementation of IEventStore in terms of EventStore, available from // http://geteventstore.com/ public class ESEventStore : IEventStore { private IEventStoreConnection conn = EventStoreConnection .Create(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1113)); public ESEventStore() { conn.Connect(); } public IEnumerable LoadEventsFor<TAggregate>(Guid id) { StreamEventsSlice currentSlice; var nextSliceStart = StreamPosition.Start; do { currentSlice = conn.ReadStreamEventsForward(id.ToString(), nextSliceStart, 200, false); foreach (var e in currentSlice.Events) yield return Deserialize(e.Event.EventType, e.Event.Data); nextSliceStart = currentSlice.NextEventNumber; } while (!currentSlice.IsEndOfStream); } private object Deserialize(string typeName, byte[] data) { var ser = new XmlSerializer(Type.GetType(typeName)); var ms = new MemoryStream(data); ms.Seek(0, SeekOrigin.Begin); return ser.Deserialize(ms); } public void SaveEventsFor<TAggregate>(Guid? id, int eventsLoaded, ArrayList newEvents) { // Establish the aggregate ID to save the events under and ensure they // all have the correct ID. if (newEvents.Count == 0) return; Guid aggregateId = id ?? GetAggregateIdFromEvent(newEvents[0]); foreach (var e in newEvents) if (GetAggregateIdFromEvent(e) != aggregateId) throw new InvalidOperationException( "Cannot save events reporting inconsistent aggregate IDs"); var expected = eventsLoaded == 0 ? ExpectedVersion.NoStream : eventsLoaded - 1; conn.AppendToStream(aggregateId.ToString(), expected, newEvents .Cast<dynamic>() .Select(e => new EventData(e.Id, e.GetType().AssemblyQualifiedName, false, Serialize(e), null))); } private Guid GetAggregateIdFromEvent(object e) { var idField = e.GetType().GetField("Id"); if (idField == null) throw new Exception("Event type " + e.GetType().Name + " is missing an Id field"); return (Guid)idField.GetValue(e); } private byte[] Serialize(object obj) { var ser = new XmlSerializer(obj.GetType()); var ms = new MemoryStream(); ser.Serialize(ms, obj); ms.Seek(0, SeekOrigin.Begin); return ms.ToArray(); } } }
Add a unit test for the new reserve-whitespace behavior
//---------------------------------------------------------------------- // // Copyright (c) Microsoft Corporation. // All rights reserved. // // This code is licensed under the MIT License. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files(the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and / or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions : // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // //------------------------------------------------------------------------------ using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.WsTrust; using System.IO; using System.Xml.Linq; namespace Test.ADAL.NET.Unit { [TestClass] [DeploymentItem("WsTrustResponse.xml")] public class WsTrustTests { [TestMethod] [TestCategory("WsTrustTests")] public void TestCreateFromResponseDocument_WhenInputContainsWhitespace_ShouldPreserveWhitespace() { string sample = File.ReadAllText("WsTrustResponse.xml"); string characteristic = "\n <saml:Assertion"; StringAssert.Contains(sample, characteristic); WsTrustResponse resp = WsTrustResponse.CreateFromResponseDocument( XDocument.Parse(sample, LoadOptions.PreserveWhitespace), WsTrustVersion.WsTrust2005); StringAssert.Contains(resp.Token, characteristic); } } }
Fix for FAR in sample app
using System; using System.Collections.Generic; using Caliburn.Micro; using CM.HelloUniversal.Views; using CM.HelloUniversal.ViewModels; using Windows.ApplicationModel.Activation; using Windows.UI.Xaml.Controls; namespace CM.HelloUniversal { public sealed partial class App { private WinRTContainer container; public App() { InitializeComponent(); } protected override void Configure() { MessageBinder.SpecialValues.Add("$clickeditem", c => ((ItemClickEventArgs)c.EventArgs).ClickedItem); container = new WinRTContainer(); container.RegisterWinRTServices(); container.PerRequest<MainViewModel>(); } protected override void PrepareViewFirst(Frame rootFrame) { container.RegisterNavigationService(rootFrame); } protected override void OnLaunched(LaunchActivatedEventArgs args) { if (args.PreviousExecutionState == ApplicationExecutionState.Running) return; DisplayRootView<MainView>(); } protected override object GetInstance(Type service, string key) { return container.GetInstance(service, key); } protected override IEnumerable<object> GetAllInstances(Type service) { return container.GetAllInstances(service); } protected override void BuildUp(object instance) { container.BuildUp(instance); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using Caliburn.Micro; using CM.HelloUniversal.Views; using CM.HelloUniversal.ViewModels; using Windows.ApplicationModel.Activation; using Windows.UI.Xaml.Controls; namespace CM.HelloUniversal { public sealed partial class App { private WinRTContainer container; public App() { InitializeComponent(); } protected override void Configure() { MessageBinder.SpecialValues.Add("$clickeditem", c => ((ItemClickEventArgs)c.EventArgs).ClickedItem); container = new WinRTContainer(); container.RegisterWinRTServices(); container.PerRequest<MainViewModel>(); PrepareViewFirst(); } protected override void PrepareViewFirst(Frame rootFrame) { container.RegisterNavigationService(rootFrame); } protected override void OnLaunched(LaunchActivatedEventArgs args) { Initialize(); if (args.PreviousExecutionState == ApplicationExecutionState.Running) return; if (RootFrame.Content == null) DisplayRootView<MainView>(); } protected override object GetInstance(Type service, string key) { return container.GetInstance(service, key); } protected override IEnumerable<object> GetAllInstances(Type service) { return container.GetAllInstances(service); } protected override void BuildUp(object instance) { container.BuildUp(instance); } } }
Add basic support for outputing on the fly updates
using System; using NUnit.Framework.Api; using System.Xml.Linq; using System.IO; namespace GuiUnit { public class XmlTestListener : ITestListener { TextWriter Writer { get; set; } public XmlTestListener (TextWriter writer) { Writer = writer; } public void TestStarted (ITest test) { if (test.HasChildren) Write (new XElement ("suite-started", new XAttribute ("name", test.FullName))); else Write (new XElement ("test-started", new XAttribute ("name", test.FullName))); } public void TestFinished (ITestResult result) { if (result.Test.HasChildren) Write (new XElement ("suite-finished", new XAttribute ("name", result.Test.FullName), new XAttribute ("result", ToXmlString (result.ResultState)))); else Write (new XElement ("test-finished", new XAttribute ("name", result.Test.FullName), new XAttribute ("result", ToXmlString (result.ResultState)))); } public void TestOutput (TestOutput testOutput) { // Ignore } object ToXmlString (ResultState resultState) { if (resultState == ResultState.Success) return "Success"; else if (resultState == ResultState.Inconclusive) return "Inconclusive"; else if (resultState == ResultState.Ignored) return "Ignored"; else return "Failure"; } void Write (XElement element) { try { Writer.WriteLine (element.ToString ()); } catch { } } } }
Make metadata accessible without reflection
#region Apache License // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you 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. // #endregion namespace log4net { /// <summary> /// Provides information about the environment the assembly has /// been built for. /// </summary> public sealed class AssemblyInfo { /// <summary>Version of the assembly</summary> public const string Version = "1.2.11"; /// <summary>Version of the framework targeted</summary> #if NET_1_1 public const decimal TargetFrameworkVersion = 1.1M; #elif NET_4_0 public const decimal TargetFrameworkVersion = 4.0M; #elif NET_2_0 || NETCF_2_0 || MONO_2_0 #if !CLIENT_PROFILE public const decimal TargetFrameworkVersion = 2.0M; #else public const decimal TargetFrameworkVersion = 3.5M; #endif // Client Profile #else public const decimal TargetFrameworkVersion = 1.0M; #endif /// <summary>Type of framework targeted</summary> #if CLI public const string TargetFramework = "CLI Compatible Frameworks"; #elif NET public const string TargetFramework = ".NET Framework"; #elif NETCF public const string TargetFramework = ".NET Compact Framework"; #elif MONO public const string TargetFramework = "Mono"; #elif SSCLI public const string TargetFramework = "Shared Source CLI"; #else public const string TargetFramework = "Unknown"; #endif /// <summary>Does it target a client profile?</summary> #if !CLIENT_PROFILE public const bool ClientProfile = false; #else public const bool ClientProfile = true; #endif /// <summary> /// Identifies the version and target for this assembly. /// </summary> public static string Info { get { return string.Format("Apache log4net version {0} compiled for {1}{2} {3}", Version, TargetFramework, /* Can't use ClientProfile && true ? " Client Profile" : or the compiler whines about unreachable expressions */ #if !CLIENT_PROFILE string.Empty, #else " Client Profile", #endif TargetFrameworkVersion); } } } }
Add simple step which allow using delegates for defining steps
using System; using System.Threading.Tasks; using NCrawler.Interfaces; namespace NCrawler { /// <summary> /// Implementation of pipeline steps which allow steps definition using simple functions /// </summary> public class SimpleStep : IPipelineStep { private Func<ICrawler, PropertyBag, Task> worker; public SimpleStep(Action worker) : this((crawler, properties) => worker()) { } public SimpleStep(Action<ICrawler> worker) : this((crawler, properties) => worker(crawler)) { } public SimpleStep(Action<ICrawler, PropertyBag> worker) : this((crawler, properties) => { worker(crawler, properties); return Task.CompletedTask; }) { } public SimpleStep(Func<Task> worker) : this((crawler, properties) => worker()) { } public SimpleStep(Func<ICrawler, Task> worker) : this((crawler, properties) => worker(crawler)) { } public SimpleStep(Func<ICrawler, PropertyBag, Task> worker) => this.worker = worker ?? throw new ArgumentNullException(nameof(worker)); public Task ProcessAsync(ICrawler crawler, PropertyBag propertyBag) { return this.worker(crawler, propertyBag); } } }
Add zone marker to fix exceptions in inspectcode
using JetBrains.Application.BuildScript.Application.Zones; using JetBrains.ReSharper.Feature.Services.ExternalSources; namespace JetBrains.ReSharper.Plugins.Unity.Feature.Services.ExternalSources { [ZoneMarker] public class ZoneMarker : IRequire<ExternalSourcesZone> { } }
Add Command to Edit Profiles
using CLImber; using SetIPLib; using System; using System.Linq; using System.Net; namespace SetIPCLI { [CommandClass("edit", ShortDescription = "Updates a profile with the specified information. Updated info is specified using options: --ip=xxx.xxx.xxx.xxx")] class EditProfile { private Profile _editingProfile; private IPAddress _ip = null; [CommandOption("ip")] public IPAddress IP { get { return _ip ?? _editingProfile?.IP; } set { _ip = value; } } private IPAddress _subnet = null; [CommandOption("subnet")] public IPAddress Subnet { get { return _subnet ?? _editingProfile?.Subnet; } set { _subnet = value; } } private IPAddress _gateway = null; [CommandOption("gw")] [CommandOption("gateway")] public IPAddress Gateway { get { return _gateway ?? _editingProfile?.Gateway; } set { _gateway = value; } } private IPAddress _dns = null; [CommandOption("dns")] public IPAddress DNS { get { return _dns ?? _editingProfile?.DNSServers.DefaultIfEmpty(IPAddress.Any).FirstOrDefault(); } set { _dns = value; } } private string _name = null; [CommandOption("name")] public string Name { get { return _name ?? _editingProfile?.Name; } set { _name = value; } } [CommandOption("dhcp")] public bool DHCP { get; set; } = false; private readonly IProfileStore _store; public EditProfile(IProfileStore profileStore) { _store = profileStore; } [CommandHandler(ShortDescription = "Update a profile with new values.")] public void Edit(string profileName) { var profiles = _store.Retrieve().ToList(); var possibleProfiles = profiles.Where(p => p.Name.Equals(profileName, StringComparison.OrdinalIgnoreCase)); if (possibleProfiles.Count() != 1) { return; } _editingProfile = possibleProfiles.First(); Profile newProfile; if (DHCP) { newProfile = Profile.CreateDHCPProfile(Name); } if (DNS != IPAddress.Any) { newProfile = Profile.CreateStaticProfile(Name, IP, Subnet, Gateway, new IPAddress[] { DNS }); } if (Gateway != IPAddress.Any) { newProfile = Profile.CreateStaticProfile(Name, IP, Subnet, Gateway); } else { newProfile = Profile.CreateStaticProfile(Name, IP, Subnet); } profiles.Remove(_editingProfile); profiles.Add(newProfile); _store.Store(profiles); } } }
Add class for David OBrien
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using System.Web; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class DavidOBrien : IFilterMyBlogPosts, IAmAMicrosoftMVP { public string FirstName => "David"; public string LastName => "O'Brien"; public string ShortBioOrTagLine => "is a Microsoft MVP, DevOps Consultant/Engineer, do AWS and a lot of Cloud."; public string StateOrRegion => "Melbourne, Australia"; public string EmailAddress => "me@david-obrien.net"; public string TwitterHandle => "david_obrien"; public string GravatarHash => "c93bbf72255d38bab70895eb7c0b3f99"; public Uri WebSite => new Uri("https://david-obrien.net/"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://david-obrien.net/feed.xml"); } } public string GitHubHandle => "davidobrien1985"; public bool Filter(SyndicationItem item) { return item.Categories.Where(i => i.Name.Equals("powershell", StringComparison.OrdinalIgnoreCase)).Any(); } DateTime IAmAMicrosoftMVP.FirstAwarded => new DateTime(2012, 10, 1); } }
Use a different generic type variable name that does not conflict with the parent one.
using System.Collections.Generic; using System.Linq; using CppSharp.Passes; namespace CppSharp { /// <summary> /// This class is used to build passes that will be run against the AST /// that comes from C++. /// </summary> public class PassBuilder<T> { public List<T> Passes { get; private set; } public Driver Driver { get; private set; } public PassBuilder(Driver driver) { Passes = new List<T>(); Driver = driver; } /// <summary> /// Adds a new pass to the builder. /// </summary> public void AddPass(T pass) { Passes.Add(pass); } /// <summary> /// Finds a previously-added pass of the given type. /// </summary> public T FindPass<T>() where T : TranslationUnitPass { return Passes.OfType<T>().Select(pass => pass as T).FirstOrDefault(); } } }
using System.Collections.Generic; using System.Linq; using CppSharp.Passes; namespace CppSharp { /// <summary> /// This class is used to build passes that will be run against the AST /// that comes from C++. /// </summary> public class PassBuilder<T> { public List<T> Passes { get; private set; } public Driver Driver { get; private set; } public PassBuilder(Driver driver) { Passes = new List<T>(); Driver = driver; } /// <summary> /// Adds a new pass to the builder. /// </summary> public void AddPass(T pass) { Passes.Add(pass); } /// <summary> /// Finds a previously-added pass of the given type. /// </summary> public U FindPass<U>() where U : TranslationUnitPass { return Passes.OfType<U>().Select(pass => pass as U).FirstOrDefault(); } } }
Test was added for ExceptionDescription
namespace Skeleton.Web.Tests.Conventions.Responses { using System; using Web.Conventions.Responses; using Xunit; public class ExceptionDescriptionTests { [Fact] public void ShouldCollectInformation() { // Given const string message = "<Message>"; const string innerMessage = "<Inner_Message>"; void Action() { void InnerAction() => throw new ArgumentException(innerMessage); try { InnerAction(); } catch (Exception e) { throw new InvalidOperationException(message, e); } } //When Exception exception = null; try { Action(); } catch (Exception e) { exception = e; } var exceptionStringDescription = new ExceptionDescription(exception).ToString(); // Then Assert.Contains(message, exceptionStringDescription, StringComparison.InvariantCultureIgnoreCase); Assert.Contains(exception.GetType().ToString(), exceptionStringDescription, StringComparison.InvariantCultureIgnoreCase); Assert.Contains(exception.StackTrace, exceptionStringDescription, StringComparison.InvariantCultureIgnoreCase); Assert.Contains(innerMessage, exceptionStringDescription, StringComparison.InvariantCultureIgnoreCase); Assert.Contains(exception.InnerException.GetType().ToString(), exceptionStringDescription, StringComparison.InvariantCultureIgnoreCase); Assert.Contains(exception.InnerException.StackTrace, exceptionStringDescription, StringComparison.InvariantCultureIgnoreCase); } } }
Set root view controller for window
using System; using CoreGraphics; using UIKit; using Foundation; namespace TableEditing { [Register ("AppDelegate")] public class AppDelegate : UIApplicationDelegate { #region -= main =- public static void Main (string[] args) { try { UIApplication.Main (args, null, "AppDelegate"); } catch (Exception e) { Console.WriteLine (e.ToString ()); } } #endregion #region -= declarations and properties =- protected UIWindow window; protected TableEditing.Screens.HomeScreen iPhoneHome; #endregion public override bool FinishedLaunching (UIApplication app, NSDictionary options) { //---- create our window window = new UIWindow (UIScreen.MainScreen.Bounds); window.MakeKeyAndVisible (); //---- create the home screen iPhoneHome = new TableEditing.Screens.HomeScreen (); iPhoneHome.View.Frame = new CGRect (0, UIApplication.SharedApplication.StatusBarFrame.Height, UIScreen.MainScreen.ApplicationFrame.Width, UIScreen.MainScreen.ApplicationFrame.Height); window.AddSubview (iPhoneHome.View); return true; } } }
using System; using CoreGraphics; using UIKit; using Foundation; namespace TableEditing { [Register ("AppDelegate")] public class AppDelegate : UIApplicationDelegate { #region -= main =- public static void Main (string[] args) { try { UIApplication.Main (args, null, "AppDelegate"); } catch (Exception e) { Console.WriteLine (e.ToString ()); } } #endregion #region -= declarations and properties =- protected UIWindow window; protected TableEditing.Screens.HomeScreen iPhoneHome; #endregion public override bool FinishedLaunching (UIApplication app, NSDictionary options) { //---- create our window window = new UIWindow (UIScreen.MainScreen.Bounds); window.MakeKeyAndVisible (); //---- create the home screen iPhoneHome = new TableEditing.Screens.HomeScreen (); iPhoneHome.View.Frame = new CGRect (0, UIApplication.SharedApplication.StatusBarFrame.Height, UIScreen.MainScreen.ApplicationFrame.Width, UIScreen.MainScreen.ApplicationFrame.Height); var navigationController = new UINavigationController (iPhoneHome); window.RootViewController = navigationController; window.MakeKeyAndVisible (); return true; } } }
Use "silent" install (no prompts) when running optional auto apply update
using Certify.Locales; using System.Threading.Tasks; using System.Windows; using System.Windows.Input; namespace Certify.UI.Utils { public class UpdateCheckUtils { public async Task<Models.UpdateCheck> UpdateWithDownload() { Mouse.OverrideCursor = Cursors.Wait; var updateCheck = await new Management.Util().DownloadUpdate(); if (!string.IsNullOrEmpty(updateCheck.UpdateFilePath)) { if (MessageBox.Show(SR.Update_ReadyToApply, ConfigResources.AppName, MessageBoxButton.YesNoCancel) == MessageBoxResult.Yes) { // file has been downloaded and verified System.Diagnostics.Process p = new System.Diagnostics.Process(); p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; p.StartInfo.FileName = updateCheck.UpdateFilePath; p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardError = true; p.Start(); //stop certify.service /*ServiceController service = new ServiceController("ServiceName"); service.Stop(); service.WaitForStatus(ServiceControllerStatus.Stopped);*/ Application.Current.Shutdown(); } } Mouse.OverrideCursor = Cursors.Arrow; return updateCheck; } } }
using Certify.Locales; using System.Threading.Tasks; using System.Windows; using System.Windows.Input; namespace Certify.UI.Utils { public class UpdateCheckUtils { public async Task<Models.UpdateCheck> UpdateWithDownload() { Mouse.OverrideCursor = Cursors.Wait; var updateCheck = await new Management.Util().DownloadUpdate(); if (!string.IsNullOrEmpty(updateCheck.UpdateFilePath)) { if (MessageBox.Show(SR.Update_ReadyToApply, ConfigResources.AppName, MessageBoxButton.YesNoCancel) == MessageBoxResult.Yes) { // file has been downloaded and verified System.Diagnostics.Process p = new System.Diagnostics.Process(); p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; p.StartInfo.FileName = updateCheck.UpdateFilePath; p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardError = true; p.StartInfo.Arguments = "/SILENT"; p.Start(); //stop certify.service /*ServiceController service = new ServiceController("ServiceName"); service.Stop(); service.WaitForStatus(ServiceControllerStatus.Stopped);*/ Application.Current.Shutdown(); } } Mouse.OverrideCursor = Cursors.Arrow; return updateCheck; } } }
Fix issue with persisting DateTime
using System; namespace Tellurium.VisualAssertions.Screenshots.Utils { static class DateTimeExtensions { public static DateTime TrimToMiliseconds(this DateTime dateTime) { return Trim(dateTime, TimeSpan.TicksPerMillisecond); } static DateTime Trim(DateTime date, long roundTicks) { return new DateTime(date.Ticks - date.Ticks % roundTicks); } } }
Add test to verify library class visability
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Stranne.BooliLib.Models; using Xunit; namespace Stranne.BooliLib.Tests { public class LibraryVisabilityTest { private readonly IEnumerable<Type> _publicClasses = new List<Type> { typeof(BooliService), typeof(IBooliService), typeof(Address), typeof(Area), typeof(AreaSearchOption), typeof(BaseObjectSearchOptions), typeof(BaseResult), typeof(BaseSearchOptions), typeof(BooliResult<,>), typeof(BoxCoordinates), typeof(Dimension), typeof(Distance), typeof(IBooliId), typeof(ListedObject), typeof(ListedSearchOption), typeof(LocationResult), typeof(Position), typeof(PositionResult), typeof(Region), typeof(SoldObject), typeof(SoldSearchOption), typeof(Source) }; [Fact] public void VerifyPublicClasses() { var publicClasses = new List<Type>(_publicClasses); var booliLibAssembly = typeof(BooliService).GetTypeInfo().Assembly; booliLibAssembly.GetTypes() .Where(type => type.GetTypeInfo().IsPublic) .ToList() .ForEach(type => { Assert.Contains(type, publicClasses); publicClasses.Remove(type); }); Assert.Empty(publicClasses); } [Fact] public void VerifyBooliServiceClassVariables() { Assert.True(new BooliService(TestConstants.CallerId, TestConstants.Key).BaseService.GetType().GetTypeInfo().IsNotPublic); } } }