Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Add examples and unit tests for comparing structs.
using System; using System.Collections.Generic; using System.Linq; using Nito.Comparers; using Nito.Comparers.Util; using Xunit; namespace UnitTests { public class ComparableBase_Struct_DefaultComparerUnitTests { private struct Person : IComparable<Person>, IEquatable<Person>, IComparable { public static readonly IFullComparer<Person> DefaultComparer = ComparerBuilder.For<Person>().OrderBy(p => p.LastName).ThenBy(p => p.FirstName); public string FirstName { get; set; } public string LastName { get; set; } public override bool Equals(object obj) => ComparableImplementations.ImplementEquals(DefaultComparer, this, obj); public override int GetHashCode() => ComparableImplementations.ImplementGetHashCode(DefaultComparer, this); public int CompareTo(Person other) => ComparableImplementations.ImplementCompareTo(DefaultComparer, this, other); public bool Equals(Person other) => ComparableImplementations.ImplementEquals(DefaultComparer, this, other); public int CompareTo(object obj) => ComparableImplementations.ImplementCompareTo(DefaultComparer, this, obj); } private static readonly Person AbeAbrams = new Person { FirstName = "Abe", LastName = "Abrams" }; private static readonly Person JackAbrams = new Person { FirstName = "Jack", LastName = "Abrams" }; private static readonly Person WilliamAbrams = new Person { FirstName = "William", LastName = "Abrams" }; private static readonly Person CaseyJohnson = new Person { FirstName = "Casey", LastName = "Johnson" }; [Fact] public void ImplementsComparerDefault() { var list = new List<Person> { JackAbrams, CaseyJohnson, AbeAbrams, WilliamAbrams }; list.Sort(); Assert.Equal(new[] { AbeAbrams, JackAbrams, WilliamAbrams, CaseyJohnson }, list); } [Fact] public void ImplementsComparerDefault_Hash() { var set = new HashSet<Person> { JackAbrams, CaseyJohnson, AbeAbrams }; Assert.True(set.Contains(new Person { FirstName = AbeAbrams.FirstName, LastName = AbeAbrams.LastName })); Assert.False(set.Contains(WilliamAbrams)); } [Fact] public void ImplementsComparerDefault_NonGeneric() { var set = new System.Collections.ArrayList() { JackAbrams, CaseyJohnson, AbeAbrams }; Assert.True(set.Contains(new Person { FirstName = AbeAbrams.FirstName, LastName = AbeAbrams.LastName })); Assert.False(set.Contains(WilliamAbrams)); } } }
Reorder list - off by one
// https://leetcode.com/problems/reorder-list/ // // Given a singly linked list L: L0→L1→…→Ln-1→Ln, // reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→… // // You must do this in-place without altering the nodes' values. // // For example, // Given {1,2,3,4}, reorder it to {1,4,2,3}. using System; public class ListNode { public int val; public ListNode next; public ListNode(int x) { val = x; } public override String ToString() { return String.Format("{0} {1}", val, next == null ? String.Empty : next.ToString()); } } public class Solution { public void ReorderList(ListNode head) { if (head == null) { return; } var slow = head; var mid = new ListNode(0); mid.next = slow; var fast = head; while (fast != null && fast.next != null) { mid.next = slow; slow = slow.next; fast = fast.next.next; } mid.next.next = null; mid = slow; ListNode prev = null; while (slow != null) { var next = slow.next; slow.next = prev; prev = slow; slow = next; } mid = prev; while (mid != null) { var firstNext = head.next; var secondNext = mid.next; head.next = mid; mid.next = firstNext; head = firstNext; mid = secondNext; } } static void Main() { ListNode root = null; for (var i = 4; i >= 1; i--) { root = new ListNode(i) { next = root }; } Console.WriteLine(root); new Solution().ReorderList(root); Console.WriteLine(root); root = null; for (var i = 3; i >= 1; i--) { root = new ListNode(i) { next = root }; } Console.WriteLine(root); new Solution().ReorderList(root); Console.WriteLine(root); } }
Add unit test for compute max stack override.
using AsmResolver.DotNet.Builder; using AsmResolver.DotNet.Code.Cil; using AsmResolver.DotNet.Signatures; using AsmResolver.PE.DotNet.Cil; using AsmResolver.PE.DotNet.Metadata.Tables.Rows; using Xunit; namespace AsmResolver.DotNet.Tests.Builder { public class CilMethodBodySerializerTest { [Theory] [InlineData(false, true, 0)] [InlineData(false, false, 100)] [InlineData(false, null, 100)] [InlineData(true, true, 0)] [InlineData(true, false, 100)] [InlineData(true, null, 0)] public void ComputeMaxStackOnBuildOverride(bool computeMaxStack, bool? computeMaxStackOverride, int expectedMaxStack) { const int maxStack = 100; var module = new ModuleDefinition("SomeModule", KnownCorLibs.SystemPrivateCoreLib_v4_0_0_0); var main = new MethodDefinition( "Main", MethodAttributes.Public | MethodAttributes.Static, MethodSignature.CreateStatic(module.CorLibTypeFactory.Void)); main.CilMethodBody = new CilMethodBody(main) { ComputeMaxStackOnBuild = computeMaxStack, MaxStack = maxStack, Instructions = {new CilInstruction(CilOpCodes.Ret)}, LocalVariables = {new CilLocalVariable(module.CorLibTypeFactory.Int32)} // Force fat method body. }; module.GetOrCreateModuleType().Methods.Add(main); module.ManagedEntrypoint = main; var builder = new ManagedPEImageBuilder(new DotNetDirectoryFactory { MethodBodySerializer = new CilMethodBodySerializer { ComputeMaxStackOnBuildOverride = computeMaxStackOverride } }); var newImage = builder.CreateImage(module); var newModule = ModuleDefinition.FromImage(newImage); Assert.Equal(expectedMaxStack, newModule.ManagedEntrypointMethod.CilMethodBody.MaxStack); } } }
Add RenderTreeBuilder extension methods for "prevent default" and "stop bubbling"
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.AspNetCore.Components.Rendering; using Microsoft.AspNetCore.Components.RenderTree; namespace Microsoft.AspNetCore.Components.Web { /// <summary> /// Provides methods for building a collection of <see cref="RenderTreeFrame"/> entries. /// </summary> public static class RenderTreeBuilderExtensions { // The "prevent default" and "stop bubbling" flags behave like attributes, in that: // - you can have multiple of them on a given element (for separate events) // - you can add and remove them dynamically // - they are independent of other attributes (e.g., you can "stop bubbling" of a given // event type on an element that doesn't itself have a handler for that event) // As such, they are represented as attributes to give the right diffing behavior. // // As a private implementation detail, their internal representation is magic-named // attributes. This may change in the future. If we add support for multiple-same // -named-attributes-per-element (#14365), then we will probably also declare a new // AttributeType concept, and have specific attribute types for these flags, and // the "name" can simply be the name of the event being modified. /// <summary> /// Appends a frame representing an instruction to prevent the default action /// for a specified event. /// </summary> /// <param name="builder">The <see cref="RenderTreeBuilder"/>.</param> /// <param name="sequence">An integer that represents the position of the instruction in the source code.</param> /// <param name="eventName">The name of the event to be affected.</param> /// <param name="value">True if the default action is to be prevented, otherwise false.</param> public static void AddEventPreventDefaultAttribute(this RenderTreeBuilder builder, int sequence, string eventName, bool value) { builder.AddAttribute(sequence, $"__internal_preventDefault_{eventName}", value); } /// <summary> /// Appends a frame representing an instruction to stop the specified event from /// bubbling up beyond the current element. /// </summary> /// <param name="builder">The <see cref="RenderTreeBuilder"/>.</param> /// <param name="sequence">An integer that represents the position of the instruction in the source code.</param> /// <param name="eventName">The name of the event to be affected.</param> /// <param name="value">True if bubbling should stop bubbling here, otherwise false.</param> public static void AddEventStopBubblingAttribute(this RenderTreeBuilder builder, int sequence, string eventName, bool value) { builder.AddAttribute(sequence, $"__internal_stopBubbling_{eventName}", value); } } }
Add a TestCase for looong combos
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Game.Beatmaps; using osu.Game.Rulesets.Osu.Objects; using osuTK; namespace osu.Game.Rulesets.Osu.Tests { [TestFixture] public class TestCaseHitCircleLongCombo : Game.Tests.Visual.TestCasePlayer { public TestCaseHitCircleLongCombo() : base(new OsuRuleset()) { } protected override IBeatmap CreateBeatmap(Ruleset ruleset) { var beatmap = new Beatmap { BeatmapInfo = new BeatmapInfo { BaseDifficulty = new BeatmapDifficulty { CircleSize = 6 }, Ruleset = ruleset.RulesetInfo } }; for (int i = 0; i < 512; i++) beatmap.HitObjects.Add(new HitCircle { Position = new Vector2(256, 192), StartTime = i * 100 }); return beatmap; } } }
Fix comment on attribute ctor. bugid: 862
using System; namespace System.ComponentModel.DataAnnotations { /// <summary> /// Specifies that a data field value must /// fall within the specified range. /// </summary> [AttributeUsage(AttributeTargets.Property)] public class StringLengthAttribute : ValidationAttribute { private int _max; public StringLengthAttribute(int stringMaxLength) { _max = stringMaxLength; ErrorMessage = "Field length must not exceed maximum length."; } /// <summary> /// Validates the specified value with respect to /// the current validation attribute. /// </summary> /// <param name="value">Value of the object to validate.</param> /// <param name="validationContext">The context information about the validation operation.</param> protected override ValidationResult IsValid(object value, ValidationContext validationContext) { if (value != null && value.ToString().Length > _max) return new ValidationResult(this.ErrorMessage); else return null; } } }
using System; namespace System.ComponentModel.DataAnnotations { /// <summary> /// Specifies that a data field value must /// fall within the specified range. /// </summary> [AttributeUsage(AttributeTargets.Property)] public class StringLengthAttribute : ValidationAttribute { private int _max; /// <summary> /// Creates an instance of the attribute. /// </summary> /// <param name="stringMaxLength">Maximum string length allowed.</param> public StringLengthAttribute(int stringMaxLength) { _max = stringMaxLength; ErrorMessage = "Field length must not exceed maximum length."; } /// <summary> /// Validates the specified value with respect to /// the current validation attribute. /// </summary> /// <param name="value">Value of the object to validate.</param> /// <param name="validationContext">The context information about the validation operation.</param> protected override ValidationResult IsValid(object value, ValidationContext validationContext) { if (value != null && value.ToString().Length > _max) return new ValidationResult(this.ErrorMessage); else return null; } } }
Select everything outside of pcb profile
//Synchronous template //----------------------------------------------------------------------------------- // PCB-Investigator Automation Script // Created on 14.10.2015 // Autor Fabio Gruber // // Select all elements outside the board contour, e.g. to delete them. //----------------------------------------------------------------------------------- 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 PCBI.MathUtils; namespace PCBIScript { public class PScript : IPCBIScript { public PScript() { } public void Execute(IPCBIWindow Parent) { IStep step = Parent.GetCurrentStep(); IMatrix matrix = Parent.GetMatrix(); if (step == null) return; IODBObject profile = step.GetPCBOutlineAsODBObject(); foreach (string layerName in step.GetAllLayerNames()) { if (matrix.GetMatrixLayerType(layerName) == MatrixLayerType.Component) continue; //no component layer ILayer Layer = step.GetLayer(layerName); if (Layer is IODBLayer) { bool foundOne = false; IODBLayer layer = (IODBLayer)Layer; foreach (IODBObject obj in layer.GetAllLayerObjects()) { if (profile.IsPointOfSecondObjectIncluded(obj)) { //inside not relevant } else { obj.Select(true); foundOne = true; } } if (foundOne) Layer.EnableLayer(true); } } Parent.UpdateSelection(); Parent.UpdateView(); } } }
Transform repeat rules into a tree
using System.Linq; using slang.Lexing.Rules.Core; using slang.Lexing.Trees.Nodes; namespace slang.Lexing.Trees.Transformers { public static class RepeatRuleExtensions { public static Tree Transform (this Repeat rule) { var tree = rule.Value.Transform (); var transitions = tree.Root.Transitions; tree.Leaves .ToList () .ForEach (leaf => { transitions.ToList ().ForEach (transition => leaf.Transitions.Add (transition.Key, transition.Value)); leaf.Transitions [Character.Any] = new Transition (null, rule.TokenCreator); }); return tree; } } }
Remove duplicates from sorted list II
// https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/ // Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. // // For example, // Given 1->2->3->3->4->4->5, return 1->2->5. // Given 1->1->1->2->3, return 2->3. // // https://leetcode.com/submissions/detail/67082686/ // // Submission Details // 166 / 166 test cases passed. // Status: Accepted // Runtime: 171 ms // // Submitted: 9 hours, 19 minutes ago public class Solution { public ListNode DeleteDuplicates(ListNode head) { if (head == null || head.next == null) { return head; } if (head.val == head.next.val) { while (head.next != null && head.val == head.next.val) { head = head.next; } return DeleteDuplicates(head.next); } head.next = DeleteDuplicates(head.next); return head; } }
Add mock builder for CarsContextQuery
using System.Collections.Generic; using System.Linq; using PathFinder.Cars.DAL.Model; using PathFinder.Cars.WebApi.Queries; namespace CarsControllersTests { public class CarContextQueryMockBuilder { private readonly CarContextMock _fakeQuery; public CarContextQueryMockBuilder() { _fakeQuery = new CarContextMock(); } public ICarsContextQuery CarsContextQuery { get { return _fakeQuery; } } public CarContextQueryMockBuilder SetCars(IEnumerable<Car> cars) { _fakeQuery.Cars = new EnumerableQuery<Car>(cars); return this; } public CarContextQueryMockBuilder SetUsers(IEnumerable<User> users) { _fakeQuery.Users = new EnumerableQuery<User>(users); return this; } public CarContextQueryMockBuilder SetCarBrands(IEnumerable<CarBrand> carBrands) { _fakeQuery.CarBrands = new EnumerableQuery<CarBrand>(carBrands); return this; } public CarContextQueryMockBuilder SetCarColors(IEnumerable<CarColor> carColors) { _fakeQuery.CarColors = new EnumerableQuery<CarColor>(carColors); return this; } public CarContextQueryMockBuilder SetCarModels(IEnumerable<CarModel> carModels) { _fakeQuery.CarModels = new EnumerableQuery<CarModel>(carModels); return this; } } public class CarContextMock : ICarsContextQuery { public CarContextMock() { Users = new EnumerableQuery<User>(Enumerable.Empty<User>()); CarColors = new EnumerableQuery<CarColor>(Enumerable.Empty<CarColor>()); CarBrands = new EnumerableQuery<CarBrand>(Enumerable.Empty<CarBrand>()); CarModels = new EnumerableQuery<CarModel>(Enumerable.Empty<CarModel>()); Cars = new EnumerableQuery<Car>(Enumerable.Empty<Car>()); } public IOrderedQueryable<User> Users { get; set; } public IOrderedQueryable<CarBrand> CarBrands { get; set; } public IOrderedQueryable<CarColor> CarColors { get; set; } public IOrderedQueryable<CarModel> CarModels { get; set; } public IOrderedQueryable<Car> Cars { get; set; } } }
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); } } } }
Set Profil to fix Rectangle
//----------------------------------------------------------------------------------- // PCB-Investigator Automation Script // Created on 2014-04-24 // 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 // // Set Profil to fix Rectangle. // The example rectangle is fixed size with 15 Inch x 10 Inch, just change the newBounds rectangle to get the size your company needs. //----------------------------------------------------------------------------------- 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 PCBI.MathUtils; namespace PCBIScript { public class PScript : IPCBIScript { public PScript() { } public void Execute(IPCBIWindow parent) { IFilter filter = new IFilter(parent); IODBObject outlinePolygon = filter.CreateOutlinePolygon(); IStep parentStep = parent.GetCurrentStep(); ISurfaceSpecifics spec = (ISurfaceSpecifics)outlinePolygon.GetSpecifics(); spec.StartPolygon(false, new PointF()); RectangleF newBounds = new RectangleF(0, 0, 15000, 10000); //create 4 lines and add them to an contour polygon PointF leftUp = new PointF(newBounds.Left, newBounds.Top); PointF leftDown = new PointF(newBounds.Left, newBounds.Bottom); PointF rightUp = new PointF(newBounds.Right, newBounds.Top); PointF rightDown = new PointF(newBounds.Right, newBounds.Bottom); spec.AddLine(leftUp, rightUp); spec.AddLine(rightUp, rightDown); spec.AddLine(rightDown, leftDown); spec.AddLine(leftDown, leftUp); spec.EndPolygon(); //close the new contour parentStep.SetPCBOutline(spec); parent.UpdateView(); } public StartMethode GetStartMethode() { return StartMethode.Synchronous; } } }
Refactor var in Session to be consistent with rest of the plugins
using System.Collections.Generic; using Glimpse.AspNet.Extensions; using Glimpse.AspNet.Model; using Glimpse.Core.Extensibility; namespace Glimpse.AspNet.SerializationConverter { public class SessionModelConverter : SerializationConverter<List<SessionModel>> { public override object Convert(List<SessionModel> obj) { var result = new List<object[]> { new[] { "Key", "Value", "Type" } }; foreach (var item in obj) { result.Add(new[] { item.Key, item.Value, item.Type }); } return result; } } }
using System.Collections.Generic; using Glimpse.AspNet.Extensions; using Glimpse.AspNet.Model; using Glimpse.Core.Extensibility; using Glimpse.Core.Plugin.Assist; namespace Glimpse.AspNet.SerializationConverter { public class SessionModelConverter : SerializationConverter<List<SessionModel>> { public override object Convert(List<SessionModel> obj) { var root = new TabSection("Key", "Value", "Type"); foreach (var item in obj) { root.AddRow().Column(item.Key).Column(item.Value).Column(item.Type); } return root.Build(); } } }
Add unit tests for SingleDisposable.
using System; using System.Threading.Tasks; using Nito.AsyncEx; using System.Linq; using System.Threading; using System.Diagnostics.CodeAnalysis; using Xunit; namespace UnitTests { public class SingleDisposableUnitTests { [Fact] public void ConstructedWithNullContext_DisposeIsANoop() { var disposable = new DelegateSingleDisposable<object>(null, _ => { Assert.False(true, "Callback invoked"); }); disposable.Dispose(); } [Fact] public void ConstructedWithContext_DisposeReceivesThatContext() { var providedContext = new object(); object seenContext = null; var disposable = new DelegateSingleDisposable<object>(providedContext, context => { seenContext = context; }); disposable.Dispose(); Assert.Same(providedContext, seenContext); } [Fact] public void DisposeOnlyCalledOnce() { var counter = 0; var disposable = new DelegateSingleDisposable<object>(new object(), _ => { ++counter; }); disposable.Dispose(); disposable.Dispose(); Assert.Equal(1, counter); } private sealed class DelegateSingleDisposable<T>: SingleDisposable<T> where T : class { private readonly Action<T> _callback; public DelegateSingleDisposable(T context, Action<T> callback) : base(context) { _callback = callback; } protected override void Dispose(T context) { _callback(context); } } } }
Update website and copyright year.
using System; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyProduct("Harbour.RedisSessionStateStore")] [assembly: AssemblyCompany("http://www.adrianphinney.com")] [assembly: AssemblyCopyright("Copyright © Harbour Inc. 2012")] [assembly: AssemblyDescription("An ASP.NET Redis SessionStateStoreProvider.")] [assembly: ComVisible(false)]
using System; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyProduct("Harbour.RedisSessionStateStore")] [assembly: AssemblyCompany("http://github.com/TheCloudlessSky/Harbour.RedisSessionStateStore")] [assembly: AssemblyCopyright("Copyright © Harbour Inc. 2014")] [assembly: AssemblyDescription("An ASP.NET Redis SessionStateStoreProvider.")] [assembly: ComVisible(false)]
Select start page by default instead of root
using System; using N2.Web.UI.WebControls; namespace N2.Edit { [ToolbarPlugin("", "tpPreview", "{url}", ToolbarArea.Preview, Targets.Preview, "~/Edit/Img/Ico/Png/eye.png", 0, ToolTip = "edit", GlobalResourceClassName = "Toolbar")] [ControlPanelLink("cpAdminister", "~/edit/img/ico/png/application_side_tree.png", "~/edit/?selected={Selected.Path}", "Administer site", -50, ControlPanelState.Visible, Target = Targets.Top)] [ControlPanelSeparator(0, ControlPanelState.Visible)] public partial class Default : Web.EditPage { protected string SelectedPath = "/"; protected string SelectedUrl = "~/"; protected override void OnInit(EventArgs e) { try { SelectedPath = SelectedItem.Path; SelectedPath = Engine.EditManager.GetPreviewUrl(SelectedItem); } catch(Exception ex) { Trace.Write(ex.ToString()); Response.Redirect("install/begin/default.aspx"); } base.OnInit(e); } } }
using System; using N2.Web.UI.WebControls; namespace N2.Edit { [ToolbarPlugin("", "tpPreview", "{url}", ToolbarArea.Preview, Targets.Preview, "~/Edit/Img/Ico/Png/eye.png", 0, ToolTip = "edit", GlobalResourceClassName = "Toolbar")] [ControlPanelLink("cpAdminister", "~/edit/img/ico/png/application_side_tree.png", "~/edit/?selected={Selected.Path}", "Administer site", -50, ControlPanelState.Visible, Target = Targets.Top)] [ControlPanelSeparator(0, ControlPanelState.Visible)] public partial class Default : Web.EditPage { string selectedPath; string selectedUrl; public string SelectedPath { get { return selectedPath ?? "/"; } } public string SelectedUrl { get { return selectedUrl ?? "~/"; } } protected override void OnInit(EventArgs e) { try { selectedPath = SelectedItem.Path; selectedUrl = Engine.EditManager.GetPreviewUrl(SelectedItem); } catch(Exception ex) { Trace.Write(ex.ToString()); Response.Redirect("install/begin/default.aspx"); } base.OnInit(e); } } }
Add NorthEurope to location enum for Data Factories
// // Copyright (c) Microsoft and contributors. 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. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; namespace Microsoft.Azure.Management.DataFactories.Models { /// <summary> /// Data center location of the data factory. /// </summary> public static partial class Location { /// <summary> /// West US /// </summary> public const string WestUS = "westus"; } }
// // Copyright (c) Microsoft and contributors. 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. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; namespace Microsoft.Azure.Management.DataFactories.Models { /// <summary> /// Data center location of the data factory. /// </summary> public static partial class Location { /// <summary> /// West US /// </summary> public const string WestUS = "westus"; /// <summary> /// North Europe /// </summary> public const string NorthEurope = "northeurope"; } }
Add test asserting reconnect works.
using System.Threading.Tasks; using NUnit.Framework; using Robust.Client.Console; using Robust.Shared.Interfaces.Network; using Robust.Shared.IoC; namespace Content.IntegrationTests.Tests { [TestFixture] public class ReconnectTest : ContentIntegrationTest { [Test] public async Task Test() { var client = StartClient(); var server = StartServer(); await Task.WhenAll(client.WaitIdleAsync(), server.WaitIdleAsync()); // Connect. client.SetConnectTarget(server); client.Post(() => IoCManager.Resolve<IClientNetManager>().ClientConnect(null, 0, null)); // Run some ticks for the handshake to complete and such. for (var i = 0; i < 10; i++) { server.RunTicks(1); await server.WaitIdleAsync(); client.RunTicks(1); await client.WaitIdleAsync(); } await Task.WhenAll(client.WaitIdleAsync(), server.WaitIdleAsync()); client.Post(() => IoCManager.Resolve<IClientConsole>().ProcessCommand("disconnect")); // Run some ticks for the disconnect to complete and such. for (var i = 0; i < 5; i++) { server.RunTicks(1); await server.WaitIdleAsync(); client.RunTicks(1); await client.WaitIdleAsync(); } await Task.WhenAll(client.WaitIdleAsync(), server.WaitIdleAsync()); // Reconnect. client.SetConnectTarget(server); client.Post(() => IoCManager.Resolve<IClientNetManager>().ClientConnect(null, 0, null)); // Run some ticks for the handshake to complete and such. for (var i = 0; i < 10; i++) { server.RunTicks(1); await server.WaitIdleAsync(); client.RunTicks(1); await client.WaitIdleAsync(); } await Task.WhenAll(client.WaitIdleAsync(), server.WaitIdleAsync()); } } }
Add 'tabs' and header with converter on main page
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Data; namespace Postolego.Converters { public class TextDependentOnSelectedIndexConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { var invalue = (int)value; string text = ""; if(invalue < 1) { text = "UNREAD"; } else if(invalue == 1) { text = "ARCHIVE"; } else { text = "FAVORITES"; } return text; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { return null; } } }
Add an Rx-friendly HTTP downloader
using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Reactive.Linq; using System.Reactive.Subjects; using System.Text; namespace NSync.Core { public static class Http { /// <summary> /// Download data from an HTTP URL and insert the result into the /// cache. If the data is already in the cache, this returns /// a cached value. The URL itself is used as the key. /// </summary> /// <param name="url">The URL to download.</param> /// <param name="headers">An optional Dictionary containing the HTTP /// request headers.</param> /// <returns>The data downloaded from the URL.</returns> public static IObservable<byte[]> DownloadUrl(string url, Dictionary<string, string> headers = null) { var ret = makeWebRequest(new Uri(url), headers) .SelectMany(processAndCacheWebResponse) .Multicast(new AsyncSubject<byte[]>()); ret.Connect(); return ret; } static IObservable<byte[]> processAndCacheWebResponse(WebResponse wr) { var hwr = (HttpWebResponse)wr; if ((int)hwr.StatusCode >= 400) { return Observable.Throw<byte[]>(new WebException(hwr.StatusDescription)); } var ms = new MemoryStream(); hwr.GetResponseStream().CopyTo(ms); var ret = ms.ToArray(); return Observable.Return(ret); } static IObservable<WebResponse> makeWebRequest( Uri uri, Dictionary<string, string> headers = null, string content = null, int retries = 3, TimeSpan? timeout = null) { var request = Observable.Defer(() => { var hwr = WebRequest.Create(uri); if (headers != null) { foreach (var x in headers) { hwr.Headers[x.Key] = x.Value; } } if (content == null) { return Observable.FromAsyncPattern<WebResponse>(hwr.BeginGetResponse, hwr.EndGetResponse)(); } var buf = Encoding.UTF8.GetBytes(content); return Observable.FromAsyncPattern<Stream>(hwr.BeginGetRequestStream, hwr.EndGetRequestStream)() .SelectMany(x => Observable.FromAsyncPattern<byte[], int, int>(x.BeginWrite, x.EndWrite)(buf, 0, buf.Length)) .SelectMany(_ => Observable.FromAsyncPattern<WebResponse>(hwr.BeginGetResponse, hwr.EndGetResponse)()); }); return request.Timeout(timeout ?? TimeSpan.FromSeconds(15)).Retry(retries); } } }
Update lock to version 7.11
@using System.Configuration; @{ ViewBag.Title = "Login"; } <div id="root" style="width: 280px; margin: 40px auto;"> </div> @Html.AntiForgeryToken() <script src="https://cdn.auth0.com/js/lock-7.9.min.js"></script> <script> if (!window.location.origin) { window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port : ''); } var lock = new Auth0Lock('@ConfigurationManager.AppSettings["auth0:ClientId"]', '@ConfigurationManager.AppSettings["auth0:Domain"]'); var xsrf = document.getElementsByName("__RequestVerificationToken")[0].value; lock.show({ container: 'root' , callbackURL: window.location.origin + '/signin-auth0' , responseType: 'code' , authParams: { scope: 'openid name email', state: 'xsrf=' + xsrf + '&ru=' + '@ViewBag.ReturnUrl' } }); </script>
@using System.Configuration; @{ ViewBag.Title = "Login"; } <div id="root" style="width: 280px; margin: 40px auto;"> </div> @Html.AntiForgeryToken() <script src="https://cdn.auth0.com/js/lock-7.11.min.js"></script> <script> if (!window.location.origin) { window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port : ''); } var lock = new Auth0Lock('@ConfigurationManager.AppSettings["auth0:ClientId"]', '@ConfigurationManager.AppSettings["auth0:Domain"]'); var xsrf = document.getElementsByName("__RequestVerificationToken")[0].value; lock.show({ container: 'root' , callbackURL: window.location.origin + '/signin-auth0' , responseType: 'code' , authParams: { scope: 'openid name email', state: 'xsrf=' + xsrf + '&ru=' + '@ViewBag.ReturnUrl' } }); </script>
Add sorting order/layer comparison Also move comparer methods into a list
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System.Collections.Generic; using UnityEngine.EventSystems; namespace HoloToolkit.Unity { public class RaycastResultComparer : IComparer<RaycastResult> { public int Compare(RaycastResult left, RaycastResult right) { var result = CompareRaycastsByCanvasDepth(left, right); if (result != 0) { return result; } return CompareRaycastsByDistance(left, right); } private static int CompareRaycastsByCanvasDepth(RaycastResult left, RaycastResult right) { //Module is the graphic raycaster on the canvases. if (left.module.transform.IsParentOrChildOf(right.module.transform)) { return right.depth.CompareTo(left.depth); } return 0; } private static int CompareRaycastsByDistance(RaycastResult left, RaycastResult right) { return left.distance.CompareTo(right.distance); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System; using System.Collections.Generic; using UnityEngine.EventSystems; namespace HoloToolkit.Unity { public class RaycastResultComparer : IComparer<RaycastResult> { private static readonly List<Func<RaycastResult, RaycastResult, int>> Comparers = new List<Func<RaycastResult, RaycastResult, int>> { CompareRaycastsBySortingLayer, CompareRaycastsBySortingOrder, CompareRaycastsByCanvasDepth, CompareRaycastsByDistance, }; public int Compare(RaycastResult left, RaycastResult right) { for (var i = 0; i < Comparers.Count; i++) { var result = Comparers[i](left, right); if (result != 0) { return result; } } return 0; } private static int CompareRaycastsBySortingOrder(RaycastResult left, RaycastResult right) { //Higher is better return right.sortingOrder.CompareTo(left.sortingOrder); } private static int CompareRaycastsBySortingLayer(RaycastResult left, RaycastResult right) { //Higher is better return right.sortingLayer.CompareTo(left.sortingLayer); } private static int CompareRaycastsByCanvasDepth(RaycastResult left, RaycastResult right) { //Module is the graphic raycaster on the canvases. if (left.module.transform.IsParentOrChildOf(right.module.transform)) { //Higher is better return right.depth.CompareTo(left.depth); } return 0; } private static int CompareRaycastsByDistance(RaycastResult left, RaycastResult right) { //Lower is better return left.distance.CompareTo(right.distance); } } }
Add a default VS foregrounddispatcher
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.ComponentModel.Composition; using Microsoft.VisualStudio.Shell; namespace Microsoft.VisualStudio.LanguageServices.Razor { [Export(typeof(ForegroundDispatcher))] internal class VisualStudioForegroundDispatcher : ForegroundDispatcher { public override bool IsForegroundThread => ThreadHelper.CheckAccess(); } }
Create server side API for single multiple answer question
using Microsoft.AspNetCore.Mvc; using Promact.Trappist.DomainModel.Models.Question; using Promact.Trappist.Repository.Questions; using System; namespace Promact.Trappist.Core.Controllers { [Route("api/question")] public class QuestionsController : Controller { private readonly IQuestionRepository _questionsRepository; public QuestionsController(IQuestionRepository questionsRepository) { _questionsRepository = questionsRepository; } [HttpGet] /// <summary> /// Gets all questions /// </summary> /// <returns>Questions list</returns> public IActionResult GetQuestions() { var questions = _questionsRepository.GetAllQuestions(); return Json(questions); } [HttpPost] /// <summary> /// /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <returns></returns> public IActionResult AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion) { _questionsRepository.AddSingleMultipleAnswerQuestion(singleMultipleAnswerQuestion); return Ok(); } /// <summary> /// /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <returns></returns> public IActionResult AddSingleMultipleAnswerQuestionOption(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption) { _questionsRepository.AddSingleMultipleAnswerQuestionOption(singleMultipleAnswerQuestionOption); return Ok(); } } }
Remove error message giving away path location if not accessing from the local machine
namespace dotless.Core { using System.Web; using System.Web.SessionState; public class LessCssWithSessionHttpHandler : LessCssHttpHandler, IRequiresSessionState { } public class LessCssHttpHandler : LessCssHttpHandlerBase, IHttpHandler { public void ProcessRequest(HttpContext context) { try { var handler = Container.GetInstance<HandlerImpl>(); handler.Execute(); } catch (System.IO.FileNotFoundException ex) { context.Response.StatusCode = 404; context.Response.Write("/* File Not Found while parsing: " + ex.Message + " */"); context.Response.End(); } catch (System.IO.IOException ex) { context.Response.StatusCode = 500; context.Response.Write("/* Error in less parsing: " + ex.Message + " */"); context.Response.End(); } } public bool IsReusable { get { return true; } } } }
namespace dotless.Core { using System.Web; using System.Web.SessionState; public class LessCssWithSessionHttpHandler : LessCssHttpHandler, IRequiresSessionState { } public class LessCssHttpHandler : LessCssHttpHandlerBase, IHttpHandler { public void ProcessRequest(HttpContext context) { try { var handler = Container.GetInstance<HandlerImpl>(); handler.Execute(); } catch (System.IO.FileNotFoundException ex) { context.Response.StatusCode = 404; if (context.Request.IsLocal) { context.Response.Write("/* File Not Found while parsing: " + ex.Message + " */"); } else { context.Response.Write("/* Error Occurred. Consult log or view on local machine. */"); } context.Response.End(); } catch (System.IO.IOException ex) { context.Response.StatusCode = 500; if (context.Request.IsLocal) { context.Response.Write("/* Error in less parsing: " + ex.Message + " */"); } else { context.Response.Write("/* Error Occurred. Consult log or view on local machine. */"); } context.Response.End(); } } public bool IsReusable { get { return true; } } } }
Add a sanity check for exported types
using System.Linq; using NUnit.Framework; using ZeroLog.Tests.Support; namespace ZeroLog.Tests; [TestFixture] public class SanityChecks { [Test] public void should_export_expected_types() { // This test prevents mistakenly adding public types in the future. var publicTypes = new[] { "ZeroLog.Appenders.Appender", "ZeroLog.Appenders.ConsoleAppender", "ZeroLog.Appenders.DateAndSizeRollingFileAppender", "ZeroLog.Appenders.NoopAppender", "ZeroLog.Appenders.StreamAppender", "ZeroLog.Configuration.AppenderConfiguration", "ZeroLog.Configuration.LoggerConfiguration", "ZeroLog.Configuration.LogMessagePoolExhaustionStrategy", "ZeroLog.Configuration.RootLoggerConfiguration", "ZeroLog.Configuration.ZeroLogConfiguration", "ZeroLog.Formatting.FormattedLogMessage", "ZeroLog.Log", "ZeroLog.Log+DebugInterpolatedStringHandler", "ZeroLog.Log+ErrorInterpolatedStringHandler", "ZeroLog.Log+FatalInterpolatedStringHandler", "ZeroLog.Log+InfoInterpolatedStringHandler", "ZeroLog.Log+TraceInterpolatedStringHandler", "ZeroLog.Log+WarnInterpolatedStringHandler", "ZeroLog.LogLevel", "ZeroLog.LogManager", "ZeroLog.LogMessage", "ZeroLog.LogMessage+AppendInterpolatedStringHandler", "ZeroLog.UnmanagedFormatterDelegate`1", }; typeof(LogManager).Assembly .ExportedTypes .Select(i => i.FullName) .ShouldBeEquivalentTo(publicTypes); } }
Add missing file from code config branch
using System; using System.Collections.Generic; using System.Text; namespace Spring.Objects.Factory.Parsing { public interface IProblemReporter { void Fatal(Problem problem); void Warning(Problem problem); void Error(Problem problem); } }
Add simple snippet to get InformationalVersion
public static string GetProductVersion() { var attribute = (AssemblyVersionAttribute)Assembly .GetExecutingAssembly() .GetCustomAttributes( typeof(AssemblyVersionAttribute), true ) .Single(); return attribute.InformationalVersion; }
Update WriteJSONTest to initialize TiledNavMesh with non-null parameter
#region License /** * Copyright (c) 2013-2014 Robert Rouhani <robert.rouhani@gmail.com> and other contributors (see CONTRIBUTORS file). * Licensed under the MIT License - https://raw.github.com/Robmaister/SharpNav/master/LICENSE */ #endregion using System; using System.Collections; using System.Collections.Generic; using NUnit.Framework; using SharpNav; using SharpNav.Geometry; #if MONOGAME || XNA using Microsoft.Xna.Framework; #elif OPENTK using OpenTK; #elif SHARPDX using SharpDX; #elif UNITY3D using UnityEngine; #endif namespace SharpNavTests { [TestFixture] public class JSONTests { [Test] public void WriteJSONTest() { TiledNavMesh mesh = new TiledNavMesh(null); mesh.SaveJson("mesh.json"); } [Test] public void ReadJSONTest() { TiledNavMesh mesh = TiledNavMesh.LoadJson("mesh.json"); } } }
#region License /** * Copyright (c) 2013-2014 Robert Rouhani <robert.rouhani@gmail.com> and other contributors (see CONTRIBUTORS file). * Licensed under the MIT License - https://raw.github.com/Robmaister/SharpNav/master/LICENSE */ #endregion using System; using System.Collections; using System.Collections.Generic; using NUnit.Framework; using SharpNav; using SharpNav.Geometry; #if MONOGAME || XNA using Microsoft.Xna.Framework; #elif OPENTK using OpenTK; #elif SHARPDX using SharpDX; #elif UNITY3D using UnityEngine; #endif namespace SharpNavTests { [TestFixture] public class JSONTests { [Test] public void WriteJSONTest() { NavMeshGenerationSettings settings = NavMeshGenerationSettings.Default; CompactHeightfield heightField = new CompactHeightfield(new Heightfield( new BBox3(1, 1, 1, 5, 5, 5), settings), settings); PolyMesh polyMesh = new PolyMesh(new ContourSet(heightField, settings), 8); PolyMeshDetail polyMeshDetail = new PolyMeshDetail(polyMesh, heightField, settings); NavMeshBuilder buildData = new NavMeshBuilder(polyMesh, polyMeshDetail, new SharpNav.Pathfinding.OffMeshConnection[0], settings); TiledNavMesh mesh = new TiledNavMesh(buildData); mesh.SaveJson("mesh.json"); } [Test] public void ReadJSONTest() { TiledNavMesh mesh = TiledNavMesh.LoadJson("mesh.json"); } } }
Add a test for TwoDigitYearMax to KoreanCalendar
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace System.Globalization.Tests { public class KoreanCalendarTwoDigitYearMax { [Fact] public void TwoDigitYearMax() { Assert.Equal(4362, new KoreanCalendar().TwoDigitYearMax); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace System.Globalization.Tests { public class KoreanCalendarTwoDigitYearMax { [Fact] public void TwoDigitYearMax_Get() { Assert.Equal(4362, new KoreanCalendar().TwoDigitYearMax); } [Theory] [InlineData(99)] [InlineData(2016)] public void TwoDigitYearMax_Set(int newTwoDigitYearMax) { Calendar calendar = new KoreanCalendar(); calendar.TwoDigitYearMax = newTwoDigitYearMax; Assert.Equal(newTwoDigitYearMax, calendar.TwoDigitYearMax); } } }
Extend the Rotorz Tile System api
// This set of methods extends the most excellent Rotorz api. I built this set because, // while I love Rotorz, I find its method paramaters frustrating to use. Specifically, // I tend to send x coordinates first in my params, followed by y coordinates; while // Rotorz transposes this. It has lead to many crazy-making bugs in my code. // // These extensions also act as an interface to guarantee against future api changes, etc. using Rotorz.Tile; using System; using UnityEngine; namespace Matcha.Unity { public static class TileExtensions { public static void BulkEditBegin(this TileSystem map) { map.BeginBulkEdit(); } public static void BulkEditEnd(this TileSystem map) { map.EndBulkEdit(); } public static bool ClearTile(this TileSystem map, int x, int y) { return map.EraseTile(y, x); } public static TileData GetTileInfo(this TileSystem map, int x, int y) { return map.GetTile(y, x); } public static void RefreshNearbyTiles(this TileSystem map, int x, int y) { map.RefreshSurroundingTiles(y, x); } public static void RefreshTiles(this TileSystem map) { map.RefreshAllTiles(); } public static TileData PaintTile(this Brush brush, TileSystem map, int x, int y) { return brush.Paint(map, y, x); } // transform extensions for checking nearby tile data public static GameObject GetTileInfo(this Transform transform, TileSystem tileSystem, int xDirection, int yDirection) { // grabs tile info at a given transform: // x = 0, y = 0 will get you the tile the transform occupies // plus or minus x or y will get you tiles backwards, forwards, up or down var convertedX = (int)Math.Floor(transform.position.x); var convertedY = (int)Math.Ceiling(Math.Abs(transform.position.y)); TileData tile = tileSystem.GetTile(convertedY + yDirection, convertedX + xDirection); if (tile != null) { return tile.gameObject; } return null; } public static GameObject GetTileBelow(this Transform transform, TileSystem tileSystem, int direction) { var convertedX = (int)Math.Floor(transform.position.x); var convertedY = (int)Math.Floor(Math.Abs(transform.position.y)); TileData tile = tileSystem.GetTile(convertedY, convertedX + direction); if (tile != null) { return tile.gameObject; } return null; } } }
Change properties to inherit from declarations.
using System; using System.Collections.Generic; namespace Cxxi { /// <summary> /// Represents a C++ property. /// </summary> public class Property { public Property(string name, Declaration type) { Name = name; Type = type; } public string Name { get; set; } public Declaration Type { get; set; } public Method GetMethod { get; set; } public Method SetMethod { get; set; } } }
using System; using System.Collections.Generic; namespace Cxxi { /// <summary> /// Represents a C++ property. /// </summary> public class Property : Declaration { public Property(string name, Declaration type) { Name = name; Type = type; } public Declaration Type { get; set; } public Method GetMethod { get; set; } public Method SetMethod { get; set; } public override T Visit<T>(IDeclVisitor<T> visitor) { throw new NotImplementedException(); } } }
Move sort class to new file
 namespace ContractsWindow { public enum contractSortClass { Difficulty = 1, Expiration = 2, Acceptance = 3, Reward = 4, Type = 5, Planet = 6, } }
Add regression test for the pattern of using DHO proxy in `LifetimeManagementContainer`
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using NUnit.Framework; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Testing; using osu.Framework.Timing; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Objects.Drawables; using osu.Game.Rulesets.UI; using osu.Game.Tests.Visual; namespace osu.Game.Tests.Gameplay { [HeadlessTest] public class TestSceneProxyContainer : OsuTestScene { private HitObjectContainer hitObjectContainer; private ProxyContainer proxyContainer; private readonly ManualClock clock = new ManualClock(); [SetUp] public void SetUp() => Schedule(() => { Child = new Container { Children = new Drawable[] { hitObjectContainer = new HitObjectContainer(), proxyContainer = new ProxyContainer() }, Clock = new FramedClock(clock) }; clock.CurrentTime = 0; }); [Test] public void TestProxyLifetimeManagement() { AddStep("Add proxy drawables", () => { addProxy(new TestDrawableHitObject(1000)); addProxy(new TestDrawableHitObject(3000)); addProxy(new TestDrawableHitObject(5000)); }); AddStep($"time = 1000", () => clock.CurrentTime = 1000); AddAssert("One proxy is alive", () => proxyContainer.AliveChildren.Count == 1); AddStep($"time = 5000", () => clock.CurrentTime = 5000); AddAssert("One proxy is alive", () => proxyContainer.AliveChildren.Count == 1); AddStep($"time = 6000", () => clock.CurrentTime = 6000); AddAssert("No proxy is alive", () => proxyContainer.AliveChildren.Count == 0); } private void addProxy(DrawableHitObject drawableHitObject) { hitObjectContainer.Add(drawableHitObject); proxyContainer.AddProxy(drawableHitObject); } private class ProxyContainer : LifetimeManagementContainer { public IReadOnlyList<Drawable> AliveChildren => AliveInternalChildren; public void AddProxy(Drawable d) => AddInternal(d.CreateProxy()); } private class TestDrawableHitObject : DrawableHitObject { protected override double InitialLifetimeOffset => 100; public TestDrawableHitObject(double startTime) : base(new HitObject { StartTime = startTime }) { } protected override void UpdateInitialTransforms() { LifetimeEnd = LifetimeStart + 500; } } } }
Add a platform detection mechanism to use in tests
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Runtime.InteropServices; // TODO: This implementation is temporary until Environment.OSVersion is officially exposed, // at which point that should be used instead. internal static partial class Interop { internal enum OperatingSystem { Windows, Linux, OSX } internal static class PlatformDetection { internal static OperatingSystem OperatingSystem { get { return s_os.Value; } } private static readonly Lazy<OperatingSystem> s_os = new Lazy<OperatingSystem>(() => { if (Environment.NewLine != "\r\n") { unsafe { byte* buffer = stackalloc byte[8192]; // the size use with uname is platform specific; this should be large enough for any OS if (uname(buffer) == 0) { return Marshal.PtrToStringAnsi((IntPtr)buffer) == "Darwin" ? OperatingSystem.OSX : OperatingSystem.Linux; } } } return OperatingSystem.Windows; }); // not in src\Interop\Unix to avoiding pulling platform-dependent files into all projects [DllImport("libc")] private static extern unsafe uint uname(byte* buf); } }
Add extension methods for logging timings
using Serilog; namespace GitHub.Logging { public static class ILoggerExtensions { public static void Assert(this ILogger logger, bool condition, string messageTemplate) { if (!condition) { messageTemplate = "Assertion Failed: " + messageTemplate; #pragma warning disable Serilog004 // propertyValues might not be strings logger.Warning(messageTemplate); #pragma warning restore Serilog004 } } public static void Assert(this ILogger logger, bool condition, string messageTemplate, params object[] propertyValues) { if (!condition) { messageTemplate = "Assertion Failed: " + messageTemplate; #pragma warning disable Serilog004 // propertyValues might not be strings logger.Warning(messageTemplate, propertyValues); #pragma warning restore Serilog004 } } } }
using System; using System.Globalization; using System.Threading.Tasks; using Serilog; namespace GitHub.Logging { public static class ILoggerExtensions { public static void Assert(this ILogger logger, bool condition, string messageTemplate) { if (!condition) { messageTemplate = "Assertion Failed: " + messageTemplate; #pragma warning disable Serilog004 // propertyValues might not be strings logger.Warning(messageTemplate); #pragma warning restore Serilog004 } } public static void Assert(this ILogger logger, bool condition, string messageTemplate, params object[] propertyValues) { if (!condition) { messageTemplate = "Assertion Failed: " + messageTemplate; #pragma warning disable Serilog004 // propertyValues might not be strings logger.Warning(messageTemplate, propertyValues); #pragma warning restore Serilog004 } } public static void Time(this ILogger logger, string name, Action method) { var startTime = DateTime.Now; method(); logger.Information("{Name} took {Seconds} seconds", name, FormatSeconds(DateTime.Now - startTime)); } public static T Time<T>(this ILogger logger, string name, Func<T> method) { var startTime = DateTime.Now; var value = method(); logger.Information("{Name} took {Seconds} seconds", name, FormatSeconds(DateTime.Now - startTime)); return value; } public static async Task TimeAsync(this ILogger logger, string name, Func<Task> methodAsync) { var startTime = DateTime.Now; await methodAsync().ConfigureAwait(false); logger.Information("{Name} took {Seconds} seconds", name, FormatSeconds(DateTime.Now - startTime)); } public static async Task<T> TimeAsync<T>(this ILogger logger, string name, Func<Task<T>> methodAsync) { var startTime = DateTime.Now; var value = await methodAsync().ConfigureAwait(false); logger.Information("{Name} took {Seconds} seconds", name, FormatSeconds(DateTime.Now - startTime)); return value; } static string FormatSeconds(TimeSpan timeSpan) => timeSpan.TotalSeconds.ToString("0.##", CultureInfo.InvariantCulture); } }
Add a Task extension to handle timeouts
using System; using System.Threading; using System.Threading.Tasks; namespace CircuitBreaker.Net { // The following code is taken from "Crafting a Task.TimeoutAfter Method" post by Joe Hoag // http://blogs.msdn.com/b/pfxteam/archive/2011/11/10/10235834.aspx public static class TaskExtensions { public static Task TimeoutAfter(this Task task, int millisecondsTimeout) { // Short-circuit #1: infinite timeout or task already completed if (task.IsCompleted || (millisecondsTimeout == Timeout.Infinite)) { // Either the task has already completed or timeout will never occur. // No proxy necessary. return task; } // tcs.Task will be returned as a proxy to the caller TaskCompletionSource<VoidTypeStruct> tcs = new TaskCompletionSource<VoidTypeStruct>(); // Short-circuit #2: zero timeout if (millisecondsTimeout == 0) { // We've already timed out. tcs.SetException(new TimeoutException()); return tcs.Task; } // Set up a timer to complete after the specified timeout period Timer timer = new Timer( state => { // Recover your state information var myTcs = (TaskCompletionSource<VoidTypeStruct>)state; // Fault our proxy with a TimeoutException myTcs.TrySetException(new TimeoutException()); }, tcs, millisecondsTimeout, Timeout.Infinite); // Wire up the logic for what happens when source task completes task.ContinueWith( (antecedent, state) => { // Recover our state data var tuple = (Tuple<Timer, TaskCompletionSource<VoidTypeStruct>>)state; // Cancel the Timer tuple.Item1.Dispose(); // Marshal results to proxy MarshalTaskResults(antecedent, tuple.Item2); }, Tuple.Create(timer, tcs), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); return tcs.Task; } internal struct VoidTypeStruct { } internal static void MarshalTaskResults<TResult>( Task source, TaskCompletionSource<TResult> proxy) { switch (source.Status) { case TaskStatus.Faulted: proxy.TrySetException(source.Exception); break; case TaskStatus.Canceled: proxy.TrySetCanceled(); break; case TaskStatus.RanToCompletion: Task<TResult> castedSource = source as Task<TResult>; proxy.TrySetResult( castedSource == null ? default(TResult) : // source is a Task castedSource.Result); // source is a Task<TResult> break; } } } }
Add sample class with implementation of IComparable<>
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Recipe.ClassAndGeneric { /// <summary> /// Simple class that implements IComparable<> /// </summary> public class Square : IComparable<Square> { public Square() { } public Square(int height, int width) { this.Height = height; this.Width = width; } public int Height { get; set; } public int Width { get; set; } public int CompareTo(object obj) { Square square = obj as Square; if (square != null) { return CompareTo(square); } throw new ArgumentException("Both objects being compared must be of type Square"); } public override string ToString() => ($"Height:{this.Height} Width:{this.Width}"); public override bool Equals(object obj) { if (obj == null) { return false; } Square square = obj as Square; if (square != null) { return this.Height == square.Height; } return false; } public override int GetHashCode() { return this.Height.GetHashCode() | this.Width.GetHashCode(); } public static bool operator ==(Square x, Square y) => x.Equals(y); public static bool operator !=(Square x, Square y) => !(x == y); public static bool operator >(Square x, Square y) => (x.CompareTo(y) < 0); public static bool operator <(Square x, Square y) => (x.CompareTo(y) > 0); public int CompareTo(Square other) { long area1 = this.Height * this.Width; long area2 = other.Height * other.Width; if (area1 == area2) { return 0; } else if (area1 > area2) { return 1; } else if (area2 > area1) { return -1; } else { return -1; } } } }
Add class to auto-activate touch controls.
using UnityEngine; using UnityEngine.Assertions; [ExecuteInEditMode] public class AutoEnableTouchControls : BaseBehaviour { private GameObject canvasGo; private GameObject eventSystem; void Start() { canvasGo = gameObject.transform.Find("Canvas").gameObject; Assert.IsNotNull(canvasGo); eventSystem = gameObject.transform.Find("EventSystem").gameObject; Assert.IsNotNull(eventSystem); #if UNITY_STANDALONE canvasGo.SetActive(false); eventSystem.SetActive(false); #endif #if UNITY_IOS canvasGo.SetActive(true); eventSystem.SetActive(true); #endif } }
Add an extension method to the worksheet
using OfficeOpenXml; public static class WorksheetExtensions { public static string[,] ToStringArray(this ExcelWorksheet sheet) { string[,] answer = new string[sheet.Dimension.Rows, sheet.Dimension.Columns]; for (var rowNumber = 1; rowNumber <= sheet.Dimension.Rows; rowNumber++) { for (var columnNumber = 1; columnNumber <= sheet.Dimension.Columns; columnNumber++) { var cell = sheet.Cells[rowNumber, columnNumber].Value; if (cell == null) { answer[rowNumber -1, columnNumber -1] = ""; } else { answer[rowNumber - 1, columnNumber - 1] = cell.ToString(); } } } return answer; } }
Add Console abstraction for test suites
using Internal.ReadLine.Abstractions; using System; namespace ReadLine.Tests.Abstractions { internal class Console2 : IConsole { public int CursorLeft => _cursorLeft; public int CursorTop => _cursorTop; public int BufferWidth => _bufferWidth; public int BufferHeight => _bufferHeight; private int _cursorLeft; private int _cursorTop; private int _bufferWidth; private int _bufferHeight; public Console2() { _cursorLeft = 0; _cursorTop = 0; _bufferWidth = 100; _bufferHeight = 100; } public void SetBufferSize(int width, int height) { _bufferWidth = width; _bufferHeight = height; } public void SetCursorPosition(int left, int top) { _cursorLeft = left; _cursorTop = top; } public void Write(string value) { _cursorLeft += value.Length; } public void WriteLine(string value) { _cursorLeft += value.Length; } } }
Add test for changing data type (Thanks @prankaty )
using ClosedXML.Excel; using NUnit.Framework; using System; namespace ClosedXML_Tests.Excel.Cells { [TestFixture] public class DataTypeTests { [Test] public void ConvertNonNumericTextToNumberThrowsException() { using (var wb = new XLWorkbook()) { var ws = wb.Worksheets.Add("Sheet1"); var c = ws.Cell("A1"); c.Value = "ABC123"; Assert.Throws<ArgumentException>(() => c.DataType = XLDataType.Number); } } } }
Add basic benchmarks for Is and Class selectors.
using Avalonia.Controls; using Avalonia.Styling; using BenchmarkDotNet.Attributes; namespace Avalonia.Benchmarks.Styling { [MemoryDiagnoser] public class SelectorBenchmark { private readonly Control _notMatchingControl; private readonly Calendar _matchingControl; private readonly Selector _isCalendarSelector; private readonly Selector _classSelector; public SelectorBenchmark() { _notMatchingControl = new Control(); _matchingControl = new Calendar(); const string className = "selector-class"; _matchingControl.Classes.Add(className); _isCalendarSelector = Selectors.Is<Calendar>(null); _classSelector = Selectors.Class(null, className); } [Benchmark] public SelectorMatch IsSelector_NoMatch() { return _isCalendarSelector.Match(_notMatchingControl); } [Benchmark] public SelectorMatch IsSelector_Match() { return _isCalendarSelector.Match(_matchingControl); } [Benchmark] public SelectorMatch ClassSelector_NoMatch() { return _classSelector.Match(_notMatchingControl); } [Benchmark] public SelectorMatch ClassSelector_Match() { return _classSelector.Match(_matchingControl); } } }
Add type to represent range in a text file
using System; namespace Microsoft.Windows.PowerShell.ScriptAnalyzer { public class Range { public Position Start { get; } public Position End { get; } public Range(Position start, Position end) { if (start > end) { throw new ArgumentException("start position cannot be before end position."); } Start = new Position(start); End = new Position(end); } public Range(int startLineNumber, int startColumnNumber, int endLineNumber, int endColumnNumber) : this( new Position(startLineNumber, startColumnNumber), new Position(endLineNumber, endColumnNumber)) { } public Range(Range range) { if (range == null) { throw new ArgumentNullException(nameof(range)); } Start = new Position(range.Start); End = new Position(range.End); } public Range Shift(int lineDelta, int columnDelta) { var newStart = Start.Shift(lineDelta, columnDelta); var newEnd = End.Shift(lineDelta, Start.Line == End.Line ? columnDelta : 0); return new Range(newStart, newEnd); } public static Range Normalize(Range refRange, Range range) { if (refRange == null) { throw new ArgumentNullException(nameof(refRange)); } if (range == null) { throw new ArgumentNullException(nameof(range)); } if (refRange.Start > range.Start) { throw new ArgumentException("reference range should start before range"); } return range.Shift( 1 - refRange.Start.Line, range.Start.Line == refRange.Start.Line ? 1 - refRange.Start.Column : 0); } } }
Create audio source controller component
using UnityEngine; using System.Collections; namespace ATP.AnimationPathTools.AudioSourceControllerComponent { public class AudioSourceController : MonoBehaviour { private void Start() { } private void Update() { } } }
Add `RulesetStore` for use where realm is not present (ie. other projects)
// 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.Collections.Generic; using System.Linq; using osu.Framework.Extensions.ObjectExtensions; using osu.Framework.Platform; #nullable enable namespace osu.Game.Rulesets { public class AssemblyRulesetStore : RulesetStore { public override IEnumerable<RulesetInfo> AvailableRulesets => availableRulesets; private readonly List<RulesetInfo> availableRulesets = new List<RulesetInfo>(); public AssemblyRulesetStore(Storage? storage = null) : base(storage) { List<Ruleset> instances = LoadedAssemblies.Values .Select(r => Activator.CreateInstance(r) as Ruleset) .Where(r => r != null) .Select(r => r.AsNonNull()) .ToList(); // add all legacy rulesets first to ensure they have exclusive choice of primary key. foreach (var r in instances.Where(r => r is ILegacyRuleset)) availableRulesets.Add(new RulesetInfo(r.RulesetInfo.ShortName, r.RulesetInfo.Name, r.RulesetInfo.InstantiationInfo, r.RulesetInfo.OnlineID)); } } }
Fix for partial trust environments Assembly.GetExecutingAssembly() cannot be used in Partial trust environments Also linux type paths report file:// and not file:/// so substring(8) should not be used
using System; using System.Data; using System.Data.Common; using System.IO; using System.Reflection; namespace Simple.Data.Mysql { public static class MysqlConnectorHelper { private static DbProviderFactory _dbFactory; private static DbProviderFactory DbFactory { get { if (_dbFactory == null) _dbFactory = GetDbFactory(); return _dbFactory; } } public static IDbConnection CreateConnection(string connectionString) { var connection = DbFactory.CreateConnection(); connection.ConnectionString = connectionString; return connection; } public static DbDataAdapter CreateDataAdapter(string sqlCommand, IDbConnection connection) { var adapter = DbFactory.CreateDataAdapter(); var command = (DbCommand)connection.CreateCommand(); command.CommandText = sqlCommand; adapter.SelectCommand = command; return adapter; } private static DbProviderFactory GetDbFactory() { var mysqlAssembly = Assembly.LoadFile(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase.Substring(8)), "MySql.Data.dll")); var mysqlDbFactoryType = mysqlAssembly.GetType("MySql.Data.MySqlClient.MySqlClientFactory"); return (DbProviderFactory) Activator.CreateInstance(mysqlDbFactoryType); } } }
using System; using System.Data; using System.Data.Common; using System.IO; using System.Reflection; namespace Simple.Data.Mysql { public static class MysqlConnectorHelper { private static DbProviderFactory _dbFactory; private static DbProviderFactory DbFactory { get { if (_dbFactory == null) _dbFactory = GetDbFactory(); return _dbFactory; } } public static IDbConnection CreateConnection(string connectionString) { var connection = DbFactory.CreateConnection(); connection.ConnectionString = connectionString; return connection; } public static DbDataAdapter CreateDataAdapter(string sqlCommand, IDbConnection connection) { var adapter = DbFactory.CreateDataAdapter(); var command = (DbCommand)connection.CreateCommand(); command.CommandText = sqlCommand; adapter.SelectCommand = command; return adapter; } private static DbProviderFactory GetDbFactory() { var thisAssembly = typeof(MysqlSchemaProvider).Assembly; var path = thisAssembly.CodeBase.Replace("file:///", "").Replace("file://", "//"); path = Path.GetDirectoryName(path); if (path == null) throw new ArgumentException("Unrecognised assemblyFile."); var mysqlAssembly = Assembly.LoadFrom(Path.Combine(path, "MySql.Data.dll")); var mysqlDbFactoryType = mysqlAssembly.GetType("MySql.Data.MySqlClient.MySqlClientFactory"); return (DbProviderFactory)Activator.CreateInstance(mysqlDbFactoryType); } } }
Fix errors in log caused by no prevalues beind selected.
using System; using umbraco.DataLayer; namespace umbraco.editorControls { /// <summary> /// Summary description for cms.businesslogic.datatype.DefaultDataKeyValue. /// </summary> public class DefaultDataKeyValue : cms.businesslogic.datatype.DefaultData { public DefaultDataKeyValue(cms.businesslogic.datatype.BaseDataType DataType) : base(DataType) {} /// <summary> /// Ov /// </summary> /// <param name="d"></param> /// <returns></returns> public override System.Xml.XmlNode ToXMl(System.Xml.XmlDocument d) { // Get the value from string v = ""; try { IRecordsReader dr = SqlHelper.ExecuteReader("Select [value] from cmsDataTypeprevalues where id in (" + SqlHelper.EscapeString(Value.ToString()) + ")"); while (dr.Read()) { if (v.Length == 0) v += dr.GetString("value"); else v += "," + dr.GetString("value"); } dr.Close(); } catch {} return d.CreateCDataSection(v); } } }
using System; using umbraco.DataLayer; namespace umbraco.editorControls { /// <summary> /// Summary description for cms.businesslogic.datatype.DefaultDataKeyValue. /// </summary> public class DefaultDataKeyValue : cms.businesslogic.datatype.DefaultData { public DefaultDataKeyValue(cms.businesslogic.datatype.BaseDataType DataType) : base(DataType) {} /// <summary> /// Ov /// </summary> /// <param name="d"></param> /// <returns></returns> public override System.Xml.XmlNode ToXMl(System.Xml.XmlDocument d) { // Get the value from string v = ""; try { // Don't query if there's nothing to query for.. if (string.IsNullOrWhiteSpace(Value.ToString()) == false) { IRecordsReader dr = SqlHelper.ExecuteReader("Select [value] from cmsDataTypeprevalues where id in (@id)", SqlHelper.CreateParameter("id", Value.ToString())); while (dr.Read()) { if (v.Length == 0) v += dr.GetString("value"); else v += "," + dr.GetString("value"); } dr.Close(); } } catch {} return d.CreateCDataSection(v); } } }
Add index only drawer node
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel.Composition; using SlimDX; using SlimDX.Direct3D11; using VVVV.PluginInterfaces.V2; using VVVV.PluginInterfaces.V1; using FeralTic.DX11; using FeralTic.DX11.Resources; namespace VVVV.DX11.Nodes { [PluginInfo(Name = "IndexOnlyDrawer", Category = "DX11.Drawer", Version = "", Author = "vux")] public class DX11IndexOnlyDrawerNode : IPluginEvaluate, IDX11ResourceProvider { [Input("Geometry In", CheckIfChanged = true)] protected Pin<DX11Resource<DX11IndexedGeometry>> FInGeom; [Input("Enabled",DefaultValue=1)] protected IDiffSpread<bool> FInEnabled; [Output("Geometry Out")] protected ISpread<DX11Resource<DX11IndexedGeometry>> FOutGeom; bool invalidate = false; public void Evaluate(int SpreadMax) { invalidate = false; if (this.FInGeom.PluginIO.IsConnected) { this.FOutGeom.SliceCount = SpreadMax; for (int i = 0; i < SpreadMax; i++) { if (this.FOutGeom[i] == null) { this.FOutGeom[i] = new DX11Resource<DX11IndexedGeometry>(); } } invalidate = this.FInGeom.IsChanged || this.FInEnabled.IsChanged; if (invalidate) { this.FOutGeom.Stream.IsChanged = true; } } else { this.FOutGeom.SliceCount = 0; } } public void Update(IPluginIO pin, DX11RenderContext context) { Device device = context.Device; for (int i = 0; i < this.FOutGeom.SliceCount; i++) { if (this.FInEnabled[i] && this.FInGeom[i].Contains(context)) { DX11IndexedGeometry v = (DX11IndexedGeometry)this.FInGeom[i][context].ShallowCopy(); DX11PerVertexIndexedDrawer drawer = new DX11PerVertexIndexedDrawer(); v.AssignDrawer(drawer); this.FOutGeom[i][context] = v; } else { this.FOutGeom[i][context] = this.FInGeom[i][context]; } } } public void Destroy(IPluginIO pin, DX11RenderContext context, bool force) { //Not ownding resource eg: do nothing } } }
Test invalid filter type handling.
using System; using Xunit; using Pingu.Filters; namespace Pingu.Tests { public class FilterTests { [Fact] public void Get_filter_throws_for_invalid_filter_type() { var arex = Assert.Throws<ArgumentOutOfRangeException>(() => DefaultFilters.GetFilterForType((FilterType)11)); Assert.Equal("filter", arex.ParamName); } } }
Add some basic tests for tags
using FluentAssertions; using Xunit; namespace Okanshi.Test { public class TagTest { [Fact] public void Creating_a_new_tag_sets_the_correct_key() { var expectedKey = "key"; var tag = new Tag(expectedKey, "anything"); tag.Key.Should().Be(expectedKey); } [Fact] public void Creating_a_new_tag_sets_the_correct_value() { var expectedValue = "value"; var tag = new Tag("anything", expectedValue); tag.Value.Should().Be(expectedValue); } [Fact] public void Two_tags_with_the_same_key_and_value_should_be_equal() { var tag1 = new Tag("key", "value"); var tag2 = new Tag("key", "value"); tag1.Should().Be(tag2); } [Fact] public void Two_tags_with_the_same_key_and_value_should_have_same_hash() { var tag1Hash = new Tag("key", "value").GetHashCode(); var tag2Hash = new Tag("key", "value").GetHashCode(); tag1Hash.Should().Be(tag2Hash); } } }
Mark Height Components with region transgression
//----------------------------------------------------------------------------------- // PCB-Investigator Automation Script // Created on 16.06.2016 // Autor Fabio.Gruber // // Mark all components in max height regions of drc_comp layer. // This checks each cmp over the surfaces on relevant layer with drc_max_height attribute. //----------------------------------------------------------------------------------- // GUID markHeightRegionTransgression_635963030633639805 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 PCBI.MathUtils; namespace PCBIScript { public class PScript : IPCBIScript { public PScript() { } public void Execute(IPCBIWindow parent) { // IStep step = parent.GetCurrentStep(); if (step == null) return; string layernameTopHeightRestrictions = "drc_comp"; ICMPLayer topCMPLayer = step.GetCMPLayer(true); //for bottom change here to false ILayer HeightRestirctionLayer = step.GetLayer(layernameTopHeightRestrictions); // check each cmp for height restrictions foreach (ICMPObject cmp in topCMPLayer.GetAllLayerObjects()) { foreach (IODBObject surface in HeightRestirctionLayer.GetAllObjectInRectangle(cmp.Bounds)) { if (surface.IsPointOfSecondObjectIncluded(cmp, false)) //intersecting is ok? { //check height of cmp IAttributeElement attributeMaxHeight = null; foreach (IAttributeElement attribute in IAttribute.GetAllAttributes(surface)) { if (attribute.AttributeEnum == PCBI.FeatureAttributeEnum.drc_max_height) { attributeMaxHeight = attribute; break; } } if (attributeMaxHeight == null) continue; if (cmp.CompHEIGHT > (double)attributeMaxHeight.Value) //we know this attribute has double values { cmp.ObjectColorTemporary(Color.LightCoral); //change color to highlight cmps //surface.ObjectColorTemporary(Color.Wheat); surface.FreeText = "Check Height of " + cmp.Ref; break; } } } } topCMPLayer.EnableLayer(true); HeightRestirctionLayer.EnableLayer(true); parent.UpdateView(); } } }
Add new CoinView class for query coins
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using NBitcoin; using WalletWasabi.Helpers; using WalletWasabi.Models; namespace WalletWasabi.Gui.Models { public class CoinsView : IEnumerable<SmartCoin> { private IEnumerable<SmartCoin> _coins; public CoinsView(IEnumerable<SmartCoin> coins) { _coins = Guard.NotNull(nameof(coins), coins); } public CoinsView UnSpent() { return new CoinsView(_coins.Where(x=>x.Unspent && !x.SpentAccordingToBackend)); } public CoinsView Available() { return new CoinsView(_coins.Where(x=>!x.Unavailable)); } public CoinsView CoinJoinInProcess() { return new CoinsView(_coins.Where(x=>x.CoinJoinInProgress)); } public CoinsView Confirmed() { return new CoinsView(_coins.Where(x=>x.Confirmed)); } public CoinsView Unconfirmed() { return new CoinsView(_coins.Where(x=>!x.Confirmed)); } public CoinsView AtBlockHeight(Height height) { return new CoinsView(_coins.Where(x=>x.Height == height)); } public CoinsView SpentBy(uint256 txid) { return new CoinsView(_coins.Where(x => x.SpenderTransactionId == txid)); } public CoinsView ChildrenOf(SmartCoin coin) { return new CoinsView(_coins.Where(x => x.TransactionId == coin.SpenderTransactionId)); } public CoinsView DescendatOf(SmartCoin coin) { IEnumerable<SmartCoin> Generator(SmartCoin coin) { foreach(var child in ChildrenOf(coin)) { foreach(var childDescendat in ChildrenOf(child)) { yield return childDescendat; } yield return child; } } return new CoinsView(Generator(coin)); } public CoinsView FilterBy(Func<SmartCoin, bool> expression) { return new CoinsView(_coins.Where(expression)); } public CoinsView OutPoints(IEnumerable<TxoRef> outPoints) { return new CoinsView(_coins.Where(x=> outPoints.Any( y=> y == x.GetOutPoint()))); } public Money TotalAmount() { return _coins.Sum(x=>x.Amount); } public SmartCoin[] ToArray() { return _coins.ToArray(); } public IEnumerator<SmartCoin> GetEnumerator() { return _coins.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return _coins.GetEnumerator(); } } }
Implement unit tests for the StringPattern class
// Copyright 2015 Coinprism, Inc. // // 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 OpenChain.Ledger.Validation; using Xunit; namespace OpenChain.Ledger.Tests { public class StringPatternTests { [Fact] public void IsMatch_Success() { Assert.True(new StringPattern("name", PatternMatchingStrategy.Exact).IsMatch("name")); Assert.False(new StringPattern("name", PatternMatchingStrategy.Exact).IsMatch("name_suffix")); Assert.False(new StringPattern("name", PatternMatchingStrategy.Exact).IsMatch("nam")); Assert.False(new StringPattern("name", PatternMatchingStrategy.Exact).IsMatch("nams")); Assert.True(new StringPattern("name", PatternMatchingStrategy.Prefix).IsMatch("name")); Assert.True(new StringPattern("name", PatternMatchingStrategy.Prefix).IsMatch("name_suffix")); Assert.False(new StringPattern("name", PatternMatchingStrategy.Prefix).IsMatch("nam")); Assert.False(new StringPattern("name", PatternMatchingStrategy.Prefix).IsMatch("nams")); } } }
Convert to new Visual Studio project types
// This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0063:Use simple 'using' statement", Justification = "<Pending>", Scope = "member", Target = "~M:SimControl.TestUtils.Tests.DisposableTestAdapterTests.DisposableTestAdapter__CreateAndDispose__succeeds")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0063:Use simple 'using' statement", Justification = "<Pending>", Scope = "member", Target = "~M:SimControl.TestUtils.Tests.TempFilesTestAdapterTests.Create_temp_file__create_TempFilesTestAdapter__temp_file_is_deleted")]
Revert the Quickstart file which is deleted by mistake
/* * Copyright (c) 2018 Google Inc. * * 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. */ // [START quickstart] using Google.Apis.Auth.OAuth2; using Google.Apis.Services; using System; // Imports the Google Cloud Job Discovery client library using Google.Apis.JobService.v2; using Google.Apis.JobService.v2.Data; using System.Linq; namespace GoogleCloudSamples { public class QuickStart { public static void Main(string[] args) { // Authorize the client using Application Default Credentials. // See: https://developers.google.com/identity/protocols/application-default-credentials GoogleCredential credential = GoogleCredential.GetApplicationDefaultAsync().Result; // Specify the Service scope. if (credential.IsCreateScopedRequired) { credential = credential.CreateScoped(new[] { Google.Apis.JobService.v2.JobServiceService.Scope.Jobs }); } // Instantiate the Cloud Key Management Service API. JobServiceService jobServiceClient = new JobServiceService(new BaseClientService.Initializer { HttpClientInitializer = credential, GZipEnabled = false }); // List companies. ListCompaniesResponse result = jobServiceClient.Companies.List().Execute(); Console.WriteLine("Request Id: " + result.Metadata.RequestId); if (result.Companies != null) { Console.WriteLine("Companies: "); result.Companies.ToList().ForEach(company => Console.WriteLine(company.Name)); } else { Console.WriteLine("No companies found."); } } } } // [END quickstart]
Add error handling to default template
@inherits UmbracoViewPage<BlockListModel> @using Umbraco.Core.Models.Blocks @{ if (Model?.Layout == null || !Model.Layout.Any()) { return; } } <div class="umb-block-list"> @foreach (var layout in Model.Layout) { if (layout?.Udi == null) { continue; } var data = layout.Data; @Html.Partial("BlockList/Components/" + data.ContentType.Alias, layout) } </div>
@inherits UmbracoViewPage<BlockListModel> @using Umbraco.Core.Models.Blocks @{ if (Model?.Layout == null || !Model.Layout.Any()) { return; } } <div class="umb-block-list"> @foreach (var layout in Model.Layout) { if (layout?.Udi == null) { continue; } var data = layout.Data; try { @Html.Partial("BlockList/Components/" + data.ContentType.Alias, (data, layout.Settings)) } catch (Exception ex) { global::Umbraco.Core.Composing.Current.Logger.Error(typeof(BlockListModel), ex, "Could not display block list component for content type {0}", data?.ContentType?.Alias); } } </div>
Set the course directory as Content (for MSBuild)
using System; using System.Collections.Generic; using System.Text; namespace DotvvmAcademy.CourseFormat { public class MarkdownStepInfo { public string Path { get; } public string Moniker { get; } public string Name { get; } public string CodeTaskPath { get; } } }
Add file missed in bug fix 440109
// *********************************************************************** // Copyright (c) 2009 Charlie Poole // // 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. // *********************************************************************** // **************************************************************** // Generated by the NUnit Syntax Generator // // Command Line: __COMMANDLINE__ // // DO NOT MODIFY THIS FILE DIRECTLY // **************************************************************** using System; using System.Collections; using NUnit.Framework.Constraints; namespace NUnit.Framework { /// <summary> /// Helper class with properties and methods that supply /// a number of constraints used in Asserts. /// </summary> public class Contains { // $$GENERATE$$ $$STATIC$$ } }
Allow overriding default static files in theme
namespace Snow { using System; using System.Collections.Generic; using Nancy.Conventions; using Nancy.ViewEngines; public class SnowViewLocationConventions : IConvention { public static SnowSettings Settings { get; set; } public void Initialise(NancyConventions conventions) { ConfigureViewLocationConventions(conventions); } public Tuple<bool, string> Validate(NancyConventions conventions) { return Tuple.Create(true, string.Empty); } private static void ConfigureViewLocationConventions(NancyConventions conventions) { conventions.ViewLocationConventions = new List<Func<string, object, ViewLocationContext, string>> { (viewName, model, viewLocationContext) => Settings.PostsRaw.TrimEnd('/') + "/" + viewName, (viewName, model, viewLocationContext) => Settings.ThemesDir + Settings.Theme + "/" + Settings.LayoutsRaw.TrimEnd('/') + "/" + viewName, (viewName, model, viewLocationContext) => viewName }; } } }
namespace Snow { using System; using System.Collections.Generic; using Nancy.Conventions; using Nancy.ViewEngines; public class SnowViewLocationConventions : IConvention { public static SnowSettings Settings { get; set; } public void Initialise(NancyConventions conventions) { ConfigureViewLocationConventions(conventions); } public Tuple<bool, string> Validate(NancyConventions conventions) { return Tuple.Create(true, string.Empty); } private static void ConfigureViewLocationConventions(NancyConventions conventions) { conventions.ViewLocationConventions = new List<Func<string, object, ViewLocationContext, string>> { (viewName, model, viewLocationContext) => Settings.PostsRaw.TrimEnd('/') + "/" + viewName, (viewName, model, viewLocationContext) => Settings.ThemesDir + Settings.Theme + "/" + Settings.LayoutsRaw.TrimEnd('/') + "/" + viewName, (viewName, model, viewLocationContext) => Settings.ThemesDir + Settings.Theme + "/" + viewName, (viewName, model, viewLocationContext) => viewName, }; } } }
Add pushconsumer wrap to donet
using System; using System.Runtime.InteropServices; namespace RocketMQ.Interop { public static class PushConsumerWrap { [DllImport(ConstValues.RocketMQDriverDllName, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr CreatePushConsumer(string groupId); [DllImport(ConstValues.RocketMQDriverDllName, CallingConvention = CallingConvention.Cdecl)] public static extern int DestroyPushConsumer(IntPtr consumer); [DllImport(ConstValues.RocketMQDriverDllName, CallingConvention = CallingConvention.Cdecl)] public static extern int StartPushConsumer(IntPtr consumer); [DllImport(ConstValues.RocketMQDriverDllName, CallingConvention = CallingConvention.Cdecl)] public static extern int ShutdownPushConsumer(IntPtr consumer); [DllImport(ConstValues.RocketMQDriverDllName, CallingConvention = CallingConvention.Cdecl)] public static extern int SetPushConsumerGroupID(IntPtr consumer, string groupId); [DllImport(ConstValues.RocketMQDriverDllName, CallingConvention = CallingConvention.Cdecl)] public static extern int SetPushConsumerNameServerAddress(IntPtr consumer, string namesrv); [DllImport(ConstValues.RocketMQDriverDllName, CallingConvention = CallingConvention.Cdecl)] public static extern int SetPushConsumerSessionCredentials(IntPtr consumer, string accessKey, string secretKey, string channel); [DllImport(ConstValues.RocketMQDriverDllName, CallingConvention = CallingConvention.Cdecl)] public static extern int Subscribe(IntPtr consumer, string topic, string expression); [DllImport(ConstValues.RocketMQDriverDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "GetPushConsumerGroupID")] internal static extern IntPtr GetPushConsumerGroupIDInternal(IntPtr consumer); public static string GetPushConsumerGroupID(IntPtr consumer) { var ptr = GetPushConsumerGroupIDInternal(consumer); if (ptr == IntPtr.Zero) return string.Empty; return Marshal.PtrToStringAnsi(ptr); } [DllImport(ConstValues.RocketMQDriverDllName, CallingConvention = CallingConvention.Cdecl)] public static extern int RegisterMessageCallback( IntPtr consumer, [MarshalAs(UnmanagedType.FunctionPtr)] MessageCallBack pCallback ); public delegate int MessageCallBack(IntPtr consumer, IntPtr messageIntPtr); [DllImport(ConstValues.RocketMQDriverDllName, CallingConvention = CallingConvention.Cdecl)] public static extern int SetPushConsumerLogLevel(IntPtr consumer, CLogLevel level); } }
Add testing for auto-restart behaviour
// 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.Containers; using osu.Framework.Testing; using osu.Game.Rulesets; using osu.Game.Rulesets.Osu; using osu.Game.Rulesets.Osu.Mods; using osu.Game.Screens.Play; namespace osu.Game.Tests.Visual.Mods { public class TestSceneModFailCondition : ModTestScene { private bool restartRequested; protected override Ruleset CreatePlayerRuleset() => new OsuRuleset(); protected override TestPlayer CreateModPlayer(Ruleset ruleset) { var player = base.CreateModPlayer(ruleset); player.RestartRequested = () => restartRequested = true; return player; } protected override bool AllowFail => true; [SetUpSteps] public void SetUp() { AddStep("reset flag", () => restartRequested = false); } [Test] public void TestRestartOnFailDisabled() => CreateModTest(new ModTestData { Autoplay = false, Mod = new OsuModSuddenDeath(), PassCondition = () => !restartRequested && Player.ChildrenOfType<FailOverlay>().Single().State.Value == Visibility.Visible }); [Test] public void TestRestartOnFailEnabled() => CreateModTest(new ModTestData { Autoplay = false, Mod = new OsuModSuddenDeath { Restart = { Value = true } }, PassCondition = () => restartRequested && Player.ChildrenOfType<FailOverlay>().Single().State.Value == Visibility.Hidden }); } }
Add visual-only execution mode toggle 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 NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Configuration; using osu.Framework.Platform; namespace osu.Framework.Tests.Visual.Platform { [Ignore("This test does not cover correct GL context acquire/release when ran headless.")] public class TestSceneExecutionModes : FrameworkTestScene { private Bindable<ExecutionMode> executionMode; [BackgroundDependencyLoader] private void load(FrameworkConfigManager configManager) { executionMode = configManager.GetBindable<ExecutionMode>(FrameworkSetting.ExecutionMode); } [Test] public void ToggleModeSmokeTest() { AddRepeatStep("toggle execution mode", () => executionMode.Value = executionMode.Value == ExecutionMode.MultiThreaded ? ExecutionMode.SingleThread : ExecutionMode.MultiThreaded, 2); } } }
Create a new diagram example
using Aspose.Diagram; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CSharp.ProgrammersGuide.Load_Save_Convert { public class CreateNewVisio { public static void Run() { //ExStart:CreateNewVisio // The path to the documents directory. string dataDir = RunExamples.GetDataDir_LoadSaveConvert(); // initialize a Diagram class Diagram diagram = new Diagram(); // save diagram in the VSDX format diagram.Save(dataDir + "MyDiagram.vsdx", SaveFileFormat.VSDX); //ExEnd:CreateNewVisio } } }
Add test class with other attribute on method
using System.ComponentModel; using System.Threading.Tasks; using Refit; interface IFooWithOtherAttribute { [Get("/")] Task GetRoot(); [DisplayName("/")] Task PostRoot(); }
Annotate the test with ActiveIssue
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace System.Data.SqlClient.Tests { public class SqlConnectionBasicTests { [Fact] public void ConnectionTest() { Exception e = null; using (TestTdsServer server = TestTdsServer.StartTestServer()) { try { SqlConnection connection = new SqlConnection(server.ConnectionString); connection.Open(); } catch (Exception ce) { e = ce; } } Assert.Null(e); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace System.Data.SqlClient.Tests { public class SqlConnectionBasicTests { [Fact] [ActiveIssue(14017)] public void ConnectionTest() { Exception e = null; using (TestTdsServer server = TestTdsServer.StartTestServer()) { try { SqlConnection connection = new SqlConnection(server.ConnectionString); connection.Open(); } catch (Exception ce) { e = ce; } } Assert.Null(e); } } }
Add class to load client in private load context.
/* Copyright 2020 Jeffrey Sharp Permission to use, copy, modify, and distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ using System; using System.Reflection; using System.Runtime.Loader; using Path = System.IO.Path; #nullable enable namespace PSql { internal static class PSqlClient { private const string AssemblyPath = "PSql.Client.dll"; private static string LoadPath { get; } private static AssemblyLoadContext LoadContext { get; } private static Assembly Assembly { get; } static PSqlClient() { LoadPath = Path.GetDirectoryName(typeof(PSqlClient).Assembly.Location) ?? Environment.CurrentDirectory; LoadContext = new AssemblyLoadContext(nameof(PSqlClient)); LoadContext.Resolving += OnResolving; Assembly = LoadAssembly(AssemblyPath); } internal static dynamic CreateObject(string typeName, params object?[]? arguments) { // NULLS: CreateInstance returns null only for valueless instances // of Nullable<T>, which cannot happen here. return Activator.CreateInstance(GetType(typeName), arguments)!; } internal static Type GetType(string name) { // NULLS: Does not return null when trowOnError is true. return Assembly.GetType(nameof(PSql) + "." + name, throwOnError: true)!; } private static Assembly? OnResolving(AssemblyLoadContext context, AssemblyName name) { var path = name.Name; if (string.IsNullOrEmpty(path)) return null; if (!HasAssemblyExtension(path)) path += ".dll"; return LoadAssembly(context, path); } private static Assembly LoadAssembly(string path) { return LoadAssembly(LoadContext, path); } private static Assembly LoadAssembly(AssemblyLoadContext context, string path) { path = Path.Combine(LoadPath, path); return context.LoadFromAssemblyPath(path); } private static bool HasAssemblyExtension(string path) { return path.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) || path.EndsWith(".exe", StringComparison.OrdinalIgnoreCase); } } }
Set AssemblyConfiguration attribute to a simple/default value.
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.239 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System.Reflection; [assembly: AssemblyVersion("0.0.0.0")] [assembly: AssemblyFileVersion("0.0.0.0")] [assembly: AssemblyConfiguration("Release built on 2012-03-05 11:24")]
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.239 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System.Reflection; [assembly: AssemblyVersion("0.0.0.0")] [assembly: AssemblyFileVersion("0.0.0.0")] [assembly: AssemblyConfiguration("Debug built on 2012-01-01 00:00")]
Add ISerializer impl. that uses JSON.NET
using System.IO; using System.Text; using log4net.ObjectRenderer; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; namespace log4net.Util.Serializer { public class JsonDotNetSerializer : ISerializer { public RendererMap Map { get; set; } public object Serialize(object obj) { object result; if (obj != null) { using (var writer = new StringWriter(new StringBuilder())) using (var jsonWriter = new RendererMapJsonTextWriter(Map, writer) { CloseOutput = false }) { jsonWriter.WriteValue(obj); result = writer.GetStringBuilder().ToString(); } } else { result = JsonConvert.SerializeObject(obj); } return result; } } }
Add employee and manager as user roles
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace PetAdoptionCRM.Models { public class EmployeeRole : IdentityRole { } }
Add unit test for GetSymmetricAlgorithm.
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.IdentityModel.Tokens; using System.Security.Cryptography; using Infrastructure.Common; using Xunit; public static class SymmetricSecurityKeyTest { [WcfFact] public static void method_GetSymmetricKey() { byte[] gsk = new byte[] { 0x02, 0x01, 0x04, 0x03 }; MockGetSymmetricAlgorithm mgsakey = new MockGetSymmetricAlgorithm(); Assert.NotNull(mgsakey.GetSymmetricKey()); Assert.Equal(gsk, mgsakey.GetSymmetricKey()); } [WcfFact] public static void method_GetSymmetricAlgorithm() { string algorit = "DES"; MockGetSymmetricAlgorithm mgsaalg = new MockGetSymmetricAlgorithm(); Assert.NotNull(mgsaalg.GetSymmetricAlgorithm(algorit)); Assert.IsType<DESCryptoServiceProvider>(mgsaalg.GetSymmetricAlgorithm(algorit)); } } public class MockGetSymmetricAlgorithm : SymmetricSecurityKey { public override int KeySize => throw new System.NotImplementedException(); public override byte[] DecryptKey(string algorithm, byte[] keyData) { throw new System.NotImplementedException(); } public override byte[] EncryptKey(string algorithm, byte[] keyData) { throw new System.NotImplementedException(); } public override byte[] GenerateDerivedKey(string algorithm, byte[] label, byte[] nonce, int derivedKeyLength, int offset) { throw new System.NotImplementedException(); } public override ICryptoTransform GetDecryptionTransform(string algorithm, byte[] iv) { throw new System.NotImplementedException(); } public override ICryptoTransform GetEncryptionTransform(string algorithm, byte[] iv) { throw new System.NotImplementedException(); } public override int GetIVSize(string algorithm) { throw new System.NotImplementedException(); } public override KeyedHashAlgorithm GetKeyedHashAlgorithm(string algorithm) { throw new System.NotImplementedException(); } public override SymmetricAlgorithm GetSymmetricAlgorithm(string algorithm) { return new DESCryptoServiceProvider(); } public override byte[] GetSymmetricKey() { byte[] gsk = new byte[] { 0x02, 0x01, 0x04, 0x03 }; return gsk; } public override bool IsAsymmetricAlgorithm(string algorithm) { throw new System.NotImplementedException(); } public override bool IsSupportedAlgorithm(string algorithm) { throw new System.NotImplementedException(); } public override bool IsSymmetricAlgorithm(string algorithm) { throw new System.NotImplementedException(); } }
Implement a class to query supported commands and get their instances.
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; namespace SCPI { public class Commands { private Dictionary<string, ICommand> commands = new Dictionary<string, ICommand>(); /// <summary> /// Creates a list of supported commands in the SCPI assembly /// </summary> /// <returns>The names of the supported commands</returns> public ICollection<string> Names() { return SupportedCommands().Select(t => t.Name).ToList(); } /// <summary> /// Creates an instance of the requested command (if it does not exist) /// and returns it to the caller. /// </summary> /// <param name="command">Command name</param> /// <returns>Instance of the requested command</returns> public ICommand Get(string command) { ICommand cmd = null; if (!commands.TryGetValue(command, out cmd)) { // Lazy initialization of the command var typeInfo = SupportedCommands().Where(ti => ti.Name.Equals(command)).Single(); cmd = (ICommand)Activator.CreateInstance(typeInfo.AsType()); commands.Add(command, cmd); } return cmd; } private static IEnumerable<TypeInfo> SupportedCommands() { var assembly = typeof(ICommand).GetTypeInfo().Assembly; // Supported commands are the ones that implement ICommand interface var commands = assembly.DefinedTypes.Where(ti => ti.ImplementedInterfaces.Contains(typeof(ICommand))); return commands; } } }
Print pattern without a loop
// http://www.geeksforgeeks.org/print-a-pattern-without-using-any-loop/ // // // Print a pattern without using any loop // // Given a number n, print following pattern without using any loop. // // Input: n = 16 // Output: 16, 11, 6, 1, -4, 1, 6, 11, 16 // // Input: n = 10 // Output: 10, 5, 0, 5, 10 // using System; class Program { static void Print(int i, int m, bool flag) { Console.Write("{0} ", i); if (i == m && !flag) { Console.WriteLine(); return; } if (flag) { Print(i - 5, m, i - 5 > 0); } else { Print(i + 5, m, false); } } static void Main() { Print(16, 16, true); Print(10, 10, true); } }
Add tests for RazorCompile target
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.IO; using System.Threading.Tasks; using Xunit; namespace Microsoft.AspNetCore.Razor.Design.IntegrationTests { public class RazorCompileIntegrationTest : MSBuildIntegrationTestBase { [Fact] [InitializeTestProject("SimpleMvc")] public async Task RazorCompile_Success_CompilesAssembly() { var result = await DotnetMSBuild("RazorCompile"); Assert.BuildPassed(result); // RazorGenerate should compile the assembly and pdb. Assert.FileExists(result, IntermediateOutputPath, "SimpleMvc.dll"); Assert.FileExists(result, IntermediateOutputPath, "SimpleMvc.pdb"); Assert.FileExists(result, IntermediateOutputPath, "SimpleMvc.PrecompiledViews.dll"); Assert.FileExists(result, IntermediateOutputPath, "SimpleMvc.PrecompiledViews.pdb"); } [Fact] [InitializeTestProject("SimpleMvc")] public async Task RazorCompile_NoopsWithNoFiles() { Directory.Delete(Path.Combine(Project.DirectoryPath, "Views"), recursive: true); var result = await DotnetMSBuild("RazorCompile"); Assert.BuildPassed(result); // Everything we do should noop - including building the app. Assert.FileDoesNotExist(result, IntermediateOutputPath, "SimpleMvc.dll"); Assert.FileDoesNotExist(result, IntermediateOutputPath, "SimpleMvc.pdb"); Assert.FileDoesNotExist(result, IntermediateOutputPath, "SimpleMvc.PrecompiledViews.dll"); Assert.FileDoesNotExist(result, IntermediateOutputPath, "SimpleMvc.PrecompiledViews.pdb"); } } }
Create a tool for importing Whitebox *.dep files
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace DotSpatial.Tools { class ImportWhiteboxRaster { } }
Add tests for Sha512 class
using System; using NSec.Cryptography; using Xunit; namespace NSec.Tests.Algorithms { public static class Sha512Tests { public static readonly string HashOfEmpty = "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e"; [Fact] public static void HashEmpty() { var a = new Sha512(); var expected = HashOfEmpty.DecodeHex(); var actual = a.Hash(ReadOnlySpan<byte>.Empty); Assert.Equal(a.DefaultHashSize, actual.Length); Assert.Equal(expected, actual); } [Theory] [InlineData(32)] [InlineData(41)] [InlineData(53)] [InlineData(61)] [InlineData(64)] public static void HashEmptyWithSize(int hashSize) { var a = new Sha512(); var expected = HashOfEmpty.DecodeHex().Slice(0, hashSize); var actual = a.Hash(ReadOnlySpan<byte>.Empty, hashSize); Assert.Equal(hashSize, actual.Length); Assert.Equal(expected, actual); } [Theory] [InlineData(32)] [InlineData(41)] [InlineData(53)] [InlineData(61)] [InlineData(64)] public static void HashEmptyWithSpan(int hashSize) { var a = new Sha512(); var expected = HashOfEmpty.DecodeHex().Slice(0, hashSize); var actual = new byte[hashSize]; a.Hash(ReadOnlySpan<byte>.Empty, actual); Assert.Equal(expected, actual); } } }
Add unit tests for PointND.
namespace EOpt.Math.Tests { using Microsoft.VisualStudio.TestTools.UnitTesting; using EOpt.Math; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; [TestClass()] public class PointNDTests { [TestMethod()] public void PointNDConstrTest4() { PointND point = new PointND(12, 5); bool error = false; foreach (double item in point.Coordinates) { if (item != 12) error = true; } Assert.IsTrue(!error && point.Dimension == 5); } [TestMethod()] public void PointNDConstrTest5() { double[] x = new double[4] { 45, 56, 8, 10 }; PointND point = new PointND(x); Assert.IsTrue(point.Coordinates.SequenceEqual(x) && point.Dimension == 4); } [TestMethod()] public void EqualsTest() { PointND a = new PointND(2, 3); PointND b = new PointND(21, 4); PointND c = a.Clone(); Assert.IsTrue(a.Equals(c) && !a.Equals(b)); } [TestMethod()] public void CloneTest() { PointND p1, p2; p1 = new PointND(1, 2); p2 = p1.Clone(); Assert.IsTrue(p1.Equals(p2)); } [TestMethod()] public void ToStringTest() { PointND p1 = new PointND(90, 2); Assert.IsNotNull(p1.ToString()); } } }
Switch over setup commands from using query class
using System; using System.Collections.Generic; using System.Data; using System.Text; using ZocMonLib; namespace ZocMonLib { public class StorageCommandsSetupSqlServer : IStorageCommandsSetup { public virtual IEnumerable<ReduceLevel> SelectAllReduceLevels(IDbConnection conn) { return DatabaseSqlHelper.CreateListWithConnection<ReduceLevel>(conn, StorageCommandsSqlServerQuery.ReduceLevelSql); } public virtual IEnumerable<MonitorConfig> SelectAllMonitorConfigs(IDbConnection conn) { return DatabaseSqlHelper.CreateListWithConnection<MonitorConfig>(conn, StorageCommandsSqlServerQuery.MonitorConfigSql); } } }
using System; using System.Collections.Generic; using System.Data; using System.Text; using ZocMonLib; namespace ZocMonLib { public class StorageCommandsSetupSqlServer : IStorageCommandsSetup { public virtual IEnumerable<ReduceLevel> SelectAllReduceLevels(IDbConnection conn) { const string sql = @"SELECT * FROM ReduceLevel"; return DatabaseSqlHelper.Query<ReduceLevel>(conn, sql); } public virtual IEnumerable<MonitorConfig> SelectAllMonitorConfigs(IDbConnection conn) { const string sql = @"SELECT * FROM MonitorConfig"; return DatabaseSqlHelper.Query<MonitorConfig>(conn, sql); } } }
Add missing file for ping command test.
using DiabloSpeech.Business.Twitch; using DiabloSpeech.Business.Twitch.Processors; using NUnit.Framework; using tests.Twitch.Mocks; namespace tests.Twitch { public class PingCommandProcessorTest { PingCommandProcessor processor; TwitchConnectionMock connection; TwitchMessageData MessageData => new TwitchMessageData(); [SetUp] public void InitializeTest() { processor = new PingCommandProcessor(); connection = new TwitchConnectionMock("test", "#test"); } [Test] public void PingCommandThrowsWithoutConnection() { Assert.That(() => processor.Process(null, MessageData), Throws.ArgumentNullException); } [Test] public void PingCommandSendPongAndFlushes() { processor.Process(connection, MessageData); Assert.That(connection.FiredCommands.Count, Is.EqualTo(2)); Assert.That(connection.FiredCommands[0], Is.EqualTo("PONG")); Assert.That(connection.FiredCommands[1], Is.EqualTo("__FLUSH")); } } }
Add test covering ThreadedTaskScheduler shutdown
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Threading; using System.Threading.Tasks; using NUnit.Framework; using osu.Framework.Threading; namespace osu.Framework.Tests.Threading { [TestFixture] public class ThreadedTaskSchedulerTest { /// <summary> /// On disposal, <see cref="ThreadedTaskScheduler"/> does a blocking shutdown sequence. /// This asserts all outstanding tasks are run before the shutdown completes. /// </summary> [Test] public void EnsureThreadedTaskSchedulerProcessesBeforeDispose() { int runCount = 0; const int target_count = 128; using (var taskScheduler = new ThreadedTaskScheduler(4, "test")) { for (int i = 0; i < target_count; i++) { Task.Factory.StartNew(() => { Interlocked.Increment(ref runCount); Thread.Sleep(100); }, default, TaskCreationOptions.HideScheduler, taskScheduler); } } Assert.AreEqual(target_count, runCount); } } }
Add message type to blob trigger.
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.WindowsAzure.Storage.Blob; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace Microsoft.Azure.WebJobs.Host.Blobs.Listeners { internal class BlobTriggerMessage { public string FunctionId { get; set; } [JsonConverter(typeof(StringEnumConverter))] public BlobType BlobType { get; set; } public string ContainerName { get; set; } public string BlobName { get; set; } public string ETag { get; set; } } }
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.WindowsAzure.Storage.Blob; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace Microsoft.Azure.WebJobs.Host.Blobs.Listeners { internal class BlobTriggerMessage { public string Type { get { return "BlobTrigger"; } } public string FunctionId { get; set; } [JsonConverter(typeof(StringEnumConverter))] public BlobType BlobType { get; set; } public string ContainerName { get; set; } public string BlobName { get; set; } public string ETag { get; set; } } }
Enable Get Element Property tests in Edge
using System; using System.Collections.Generic; using NUnit.Framework; using System.Collections.ObjectModel; using OpenQA.Selenium.Environment; namespace OpenQA.Selenium { [TestFixture] public class ElementPropertyTest : DriverTestFixture { [Test] [IgnoreBrowser(Browser.Edge)] [IgnoreBrowser(Browser.Chrome, "Chrome does not support get element property command")] [IgnoreBrowser(Browser.Opera)] [IgnoreBrowser(Browser.Remote)] [IgnoreBrowser(Browser.Safari)] public void ShouldReturnNullWhenGettingTheValueOfAPropertyThatIsNotListed() { driver.Url = simpleTestPage; IWebElement head = driver.FindElement(By.XPath("/html")); string attribute = head.GetProperty("cheese"); Assert.IsNull(attribute); } [Test] [IgnoreBrowser(Browser.Edge)] [IgnoreBrowser(Browser.Chrome, "Chrome does not support get element property command")] [IgnoreBrowser(Browser.Opera)] [IgnoreBrowser(Browser.Remote)] [IgnoreBrowser(Browser.Safari)] public void CanRetrieveTheCurrentValueOfAProperty() { driver.Url = formsPage; IWebElement element = driver.FindElement(By.Id("working")); Assert.AreEqual(string.Empty, element.GetProperty("value")); element.SendKeys("hello world"); Assert.AreEqual("hello world", element.GetProperty("value")); } } }
using System; using System.Collections.Generic; using NUnit.Framework; using System.Collections.ObjectModel; using OpenQA.Selenium.Environment; namespace OpenQA.Selenium { [TestFixture] public class ElementPropertyTest : DriverTestFixture { [Test] [IgnoreBrowser(Browser.Chrome, "Chrome does not support get element property command")] [IgnoreBrowser(Browser.Opera)] [IgnoreBrowser(Browser.Remote)] [IgnoreBrowser(Browser.Safari)] public void ShouldReturnNullWhenGettingTheValueOfAPropertyThatIsNotListed() { driver.Url = simpleTestPage; IWebElement head = driver.FindElement(By.XPath("/html")); string attribute = head.GetProperty("cheese"); Assert.IsNull(attribute); } [Test] [IgnoreBrowser(Browser.Chrome, "Chrome does not support get element property command")] [IgnoreBrowser(Browser.Opera)] [IgnoreBrowser(Browser.Remote)] [IgnoreBrowser(Browser.Safari)] public void CanRetrieveTheCurrentValueOfAProperty() { driver.Url = formsPage; IWebElement element = driver.FindElement(By.Id("working")); Assert.AreEqual(string.Empty, element.GetProperty("value")); element.SendKeys("hello world"); Assert.AreEqual("hello world", element.GetProperty("value")); } } }
Add osu!-specific enum for confine mouse mode
// 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.ComponentModel; using osu.Framework.Input; namespace osu.Game.Input { /// <summary> /// Determines the situations in which the mouse cursor should be confined to the window. /// Expands upon <see cref="ConfineMouseMode"/> by providing the option to confine during gameplay. /// </summary> public enum OsuConfineMouseMode { /// <summary> /// The mouse cursor will be free to move outside the game window. /// </summary> Never, /// <summary> /// The mouse cursor will be locked to the window bounds while in fullscreen mode. /// </summary> Fullscreen, /// <summary> /// The mouse cursor will be locked to the window bounds during gameplay, /// but may otherwise move freely. /// </summary> [Description("During Gameplay")] DuringGameplay, /// <summary> /// The mouse cursor will always be locked to the window bounds while the game has focus. /// </summary> Always } }
Change mobile client to use DefaultsController instead of GetwayController
using System.Threading.Tasks; using ContosoMoments.Models; using Xamarin.Forms; using System; namespace ContosoMoments { public class ResizeRequest { public string Id { get; set; } public string BlobName { get; set; } } public class ActivityIndicatorScope : IDisposable { private bool showIndicator; private ActivityIndicator indicator; public ActivityIndicatorScope(ActivityIndicator indicator, bool showIndicator) { this.indicator = indicator; this.showIndicator = showIndicator; SetIndicatorActivity(showIndicator); } private void SetIndicatorActivity(bool isActive) { this.indicator.IsVisible = isActive; this.indicator.IsRunning = isActive; } public void Dispose() { SetIndicatorActivity(false); } } public static class Utils { public static bool IsOnline() { var networkConnection = DependencyService.Get<INetworkConnection>(); networkConnection.CheckNetworkConnection(); return networkConnection.IsConnected; } public static async Task<bool> SiteIsOnline() { bool retVal = true; try { var res = await App.MobileService.InvokeApiAsync<string>("Getway", System.Net.Http.HttpMethod.Get, null); if (res == null && res.Length == 0) { retVal = false; } } catch //(Exception ex) { retVal = false; } return retVal; } } }
using System.Threading.Tasks; using ContosoMoments.Models; using Xamarin.Forms; using System; namespace ContosoMoments { public class ResizeRequest { public string Id { get; set; } public string BlobName { get; set; } } public class ActivityIndicatorScope : IDisposable { private bool showIndicator; private ActivityIndicator indicator; public ActivityIndicatorScope(ActivityIndicator indicator, bool showIndicator) { this.indicator = indicator; this.showIndicator = showIndicator; SetIndicatorActivity(showIndicator); } private void SetIndicatorActivity(bool isActive) { this.indicator.IsVisible = isActive; this.indicator.IsRunning = isActive; } public void Dispose() { SetIndicatorActivity(false); } } public static class Utils { public static bool IsOnline() { var networkConnection = DependencyService.Get<INetworkConnection>(); networkConnection.CheckNetworkConnection(); return networkConnection.IsConnected; } public static async Task<bool> SiteIsOnline() { bool retVal = true; try { var res = await App.MobileService.InvokeApiAsync<string>("Defaults", System.Net.Http.HttpMethod.Get, null); if (res == null) { retVal = false; } } catch (Exception) { retVal = false; } return retVal; } } }
Implement unit test for boyer moore
using System; namespace Algorithms.Strings.Search { public class BoyerMoore { private int[] right; private const int R = 256; private int M; private string pat; public BoyerMoore(string pat) { this.pat = pat; right = new int[R]; for (int i = 0; i < pat.Length; ++i) { right[pat[i]] = i; } M = pat.Length; } public int Search(string text) { int skip = 1; for (int i = 0; i < text.Length - M; i+=skip) { var j; for (j = M - 1; j >= 0; j--) { if (text[i + j] != pat[j]) { skip = Math.Max(1, j - right[text[i + j]]); break; } } if (j == -1) return i; } return -1; } } }
Make the BuiltinThis test clearer
using System; using JSIL; public static class Program { public static void Main (string[] args) { var print = Builtins.Global["pr" + "int"]; if (print != null) print("printed"); if (Builtins.Local["print"] != null) Builtins.Local["print"]("printed again"); var quit = Builtins.Global["quit"]; if (quit != null) quit(); Console.WriteLine("test"); } }
using System; using JSIL; public static class Program { public static void Main (string[] args) { const string pri = "pri"; string nt = "nt"; var p = Builtins.Global[pri + nt]; if (p != null) p("printed"); if (Builtins.Local["p"] != null) Builtins.Local["p"]("printed again"); var q = Builtins.Global["quit"]; if (q != null) q(); Console.WriteLine("test"); } }
Reduce the size of the keys in the generics migrator. This finally fixes the long standing issue of it failing to create the table on linux sometimes. Thanks go to Hippo_Finesmith for helping find the issue with this :).
/* * Copyright (c) Contributors, http://aurora-sim.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Aurora-Sim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using C5; using Aurora.Framework; namespace Aurora.DataManager.Migration.Migrators { public class GenericsMigrator_4 : Migrator { public GenericsMigrator_4() { Version = new Version(0, 0, 4); MigrationName = "Generics"; schema = new List<Rec<string, ColumnDefinition[]>>(); AddSchema("generics", ColDefs( ColDef ("OwnerID", ColumnTypes.String36, true), ColDef ("Type", ColumnTypes.String64, true), ColDef("Key", ColumnTypes.String64, true), ColDef ("Value", ColumnTypes.LongText) )); } protected override void DoCreateDefaults(IDataConnector genericData) { EnsureAllTablesInSchemaExist(genericData); } protected override bool DoValidate(IDataConnector genericData) { return TestThatAllTablesValidate(genericData); } protected override void DoMigrate(IDataConnector genericData) { DoCreateDefaults(genericData); } protected override void DoPrepareRestorePoint(IDataConnector genericData) { CopyAllTablesToTempVersions(genericData); } } }
Add converter for old storable objects
using System; using LazyStorage.Interfaces; namespace LazyStorage.Xml { internal class StorableConverter<T> : IConverter<T> where T : IStorable<T>, IEquatable<T>, new() { public StorableObject GetStorableObject(T item) { return new StorableObject(item.GetStorageInfo()); } public T GetOriginalObject(StorableObject info) { var item = new T(); item.InitialiseWithStorageInfo(info.Info); return item; } public bool IsEqual(StorableObject storageObject, T realObject) { return GetOriginalObject(storageObject).Equals(realObject); } } }
Add benchmark coverage of logger
// 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 BenchmarkDotNet.Attributes; using osu.Framework.Logging; using osu.Framework.Testing; namespace osu.Framework.Benchmarks { [MemoryDiagnoser] public class BenchmarkLogger { private const int line_count = 10000; [GlobalSetup] public void GlobalSetup() { Logger.Storage = new TemporaryNativeStorage(Guid.NewGuid().ToString()); } [Benchmark] public void LogManyLinesDebug() { for (int i = 0; i < line_count; i++) { Logger.Log("This is a test log line.", level: LogLevel.Debug); } Logger.Flush(); } [Benchmark] public void LogManyMultiLineLines() { for (int i = 0; i < line_count; i++) { Logger.Log("This\nis\na\ntest\nlog\nline."); } Logger.Flush(); } [Benchmark] public void LogManyLines() { for (int i = 0; i < line_count; i++) { Logger.Log("This is a test log line."); } Logger.Flush(); } } }
Add serviceable attribute to projects.
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Reflection; [assembly: AssemblyMetadata("Serviceable", "True")]
Add a partial view with form to reply to comments.
@using System.Threading.Tasks @using CompetitionPlatform.Helpers @model CompetitionPlatform.Models.ProjectViewModels.ProjectCommentPartialViewModel <form asp-controller="ProjectDetails" asp-action="AddComment" enctype="multipart/form-data"> @if (ClaimsHelper.GetUser(User.Identity).Email != null) { <div class="form-group"> @Html.Hidden("projectId", Model.ProjectId) @Html.Hidden("ParentId", Model.ParentId) <input asp-for="@Model.ProjectId" type="hidden" /> <textarea asp-for="@Model.Comment" rows="5" class="form-control" placeholder="Enter your comment here..."></textarea> </div> <input type="submit" value="Post Comment" class="btn btn-primary pull-right" /> } </form>
Drop cassette config in for less integration
using Cassette; using Cassette.Scripts; using Cassette.Stylesheets; namespace Exceptional.Web { /// <summary> /// Configures the Cassette asset bundles for the web application. /// </summary> public class CassetteBundleConfiguration : IConfiguration<BundleCollection> { public void Configure(BundleCollection bundles) { // TODO: Configure your bundles here... // Please read http://getcassette.net/documentation/configuration // This default configuration treats each file as a separate 'bundle'. // In production the content will be minified, but the files are not combined. // So you probably want to tweak these defaults! bundles.AddPerIndividualFile<StylesheetBundle>("Content"); bundles.AddPerIndividualFile<ScriptBundle>("Scripts"); // To combine files, try something like this instead: // bundles.Add<StylesheetBundle>("Content"); // In production mode, all of ~/Content will be combined into a single bundle. // If you want a bundle per folder, try this: // bundles.AddPerSubDirectory<ScriptBundle>("Scripts"); // Each immediate sub-directory of ~/Scripts will be combined into its own bundle. // This is useful when there are lots of scripts for different areas of the website. } } }
Add file missed in build
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace ILCompiler { /// <summary> /// Used to mark TypeDesc types that are not part of the core type system /// that should never be turned into an EEType. /// </summary> public interface INonEmittableType { } }
Add NeutralResourcesLanguageAttribute to Channels lib
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Resources; [assembly:NeutralResourcesLanguage("en")]
Add code for creating challenge from IdentityModel
#region Copyright /* * * * * * * * * * * * * * * * * * * * * * * * * */ /* Carl Zeiss IMT (IZfM Dresden) */ /* Softwaresystem PiWeb */ /* (c) Carl Zeiss 2020 */ /* * * * * * * * * * * * * * * * * * * * * * * * * */ #endregion namespace Zeiss.IMT.PiWeb.Api.Common.Utilities { using System; using System.Security.Cryptography; using System.Text; using IdentityModel; /// <remarks> /// The following code is originated from an earlier version of the IdentityModel nuget package. /// </remarks> internal static class ProtocolHelperExtensions { private enum HashStringEncoding { Base64, Base64Url, } public static string ToCodeChallenge(this string input) { return input.ToSha256(HashStringEncoding.Base64Url); } private static string ToSha256(this string input, HashStringEncoding encoding = HashStringEncoding.Base64) { if (string.IsNullOrWhiteSpace(input)) { return string.Empty; } using (var sha256 = SHA256.Create()) { var bytes = Encoding.ASCII.GetBytes(input); return Encode(sha256.ComputeHash(bytes), encoding); } } private static string Encode(byte[] hash, HashStringEncoding encoding) { switch (encoding) { case HashStringEncoding.Base64: return Convert.ToBase64String(hash); case HashStringEncoding.Base64Url: return Base64Url.Encode(hash); default: throw new ArgumentException("Invalid encoding"); } } } }
Add new class to facilitate multi-threaded onion generation
using System; using System.ComponentModel; namespace Xpdm.PurpleOnion { class OnionGenerator { private readonly BackgroundWorker worker = new BackgroundWorker(); public OnionGenerator() { worker.DoWork += GenerateOnion; worker.RunWorkerCompleted += RunWorkerCompleted; } public event EventHandler<OnionGeneratedEventArgs> OnionGenerated; public void StartGenerating() { worker.RunWorkerAsync(); } protected virtual void GenerateOnion(object sender, DoWorkEventArgs e) { e.Result = OnionAddress.Create(); } protected virtual void RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { OnionGeneratedEventArgs args = new OnionGeneratedEventArgs { Result = (OnionAddress) e.Result, }; OnOnionGenerated(args); if (!args.Cancel) { worker.RunWorkerAsync(); } } protected virtual void OnOnionGenerated(OnionGeneratedEventArgs e) { EventHandler<OnionGeneratedEventArgs> handler = OnionGenerated; if (handler != null) { handler(this, e); } } public class OnionGeneratedEventArgs : EventArgs { new internal static readonly OnionGeneratedEventArgs Empty = new OnionGeneratedEventArgs(); public bool Cancel { get; set; } public OnionAddress Result { get; set; } } } }
Add test to ensure ClaimsPrincipal serializes via MobileFormatter
//----------------------------------------------------------------------- // <copyright file="ClaimsPrincipalTests.cs" company="Marimer LLC"> // Copyright (c) Marimer LLC. All rights reserved. // Website: https://cslanet.com // </copyright> // <summary>no summary</summary> //----------------------------------------------------------------------- using System.Linq; using System.Security.Claims; #if !NUNIT using Microsoft.VisualStudio.TestTools.UnitTesting; #else using NUnit.Framework; using TestClass = NUnit.Framework.TestFixtureAttribute; using TestInitialize = NUnit.Framework.SetUpAttribute; using TestCleanup = NUnit.Framework.TearDownAttribute; using TestMethod = NUnit.Framework.TestAttribute; #endif namespace Csla.Test.Serialization { [TestClass] public class ClaimsPrincipalTests { [TestMethod] public void CloneClaimsPrincipal() { Configuration.ConfigurationManager.AppSettings["CslaSerializationFormatter"] = "MobileFormatter"; var i = new ClaimsIdentity(); i.AddClaim(new Claim("name", "Franklin")); var p = new ClaimsPrincipal(i); var p1 = (ClaimsPrincipal)Core.ObjectCloner.Clone(p); Assert.AreNotSame(p, p1, "Should be different instances"); Assert.AreEqual(p.Claims.Count(), p1.Claims.Count(), "Should have same number of claims"); var c = p1.Claims.Where(r => r.Type == "name").First(); Assert.AreEqual("Franklin", c.Value, "Claim value should match"); } } }
Add test scene for thumbnail component
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Game.Beatmaps.Drawables.Cards; using osu.Game.Overlays; using osuTK; namespace osu.Game.Tests.Visual.Beatmaps { public class TestSceneBeatmapCardThumbnail : OsuTestScene { [Cached] private OverlayColourProvider colourProvider = new OverlayColourProvider(OverlayColourScheme.Blue); [Test] public void TestThumbnailPreview() { BeatmapCardThumbnail thumbnail = null; AddStep("create thumbnail", () => Child = thumbnail = new BeatmapCardThumbnail(CreateAPIBeatmapSet(Ruleset.Value)) { Anchor = Anchor.Centre, Origin = Anchor.Centre, Size = new Vector2(200) }); AddToggleStep("toggle dim", dimmed => thumbnail.Dimmed.Value = dimmed); } } }
Add shader disposal test coverage
// 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.Collections.Generic; using NUnit.Framework; using osu.Framework.Graphics.Shaders; using osu.Framework.IO.Stores; using osu.Framework.Testing; using osu.Framework.Tests.Visual; namespace osu.Framework.Tests.Shaders { public class TestSceneShaderDisposal : FrameworkTestScene { private ShaderManager manager; private Shader shader; private WeakReference<IShader> shaderRef; [SetUpSteps] public void SetUpSteps() { AddStep("setup manager", () => { manager = new TestShaderManager(new NamespacedResourceStore<byte[]>(new DllResourceStore(typeof(Game).Assembly), @"Resources/Shaders")); shader = (Shader)manager.Load(VertexShaderDescriptor.TEXTURE_2, FragmentShaderDescriptor.TEXTURE); shaderRef = new WeakReference<IShader>(shader); shader.Compile(); }); AddUntilStep("wait for load", () => shader.IsLoaded); } [Test] public void TestShadersLoseReferencesOnManagerDisposal() { AddStep("remove local reference", () => shader = null); AddStep("dispose manager", () => { manager.Dispose(); manager = null; }); AddUntilStep("reference lost", () => { GC.Collect(); GC.WaitForPendingFinalizers(); return !shaderRef.TryGetTarget(out _); }); } private class TestShaderManager : ShaderManager { public TestShaderManager(IResourceStore<byte[]> store) : base(store) { } internal override Shader CreateShader(string name, List<ShaderPart> parts) => new TestShader(name, parts); private class TestShader : Shader { internal TestShader(string name, List<ShaderPart> parts) : base(name, parts) { } protected override int CreateProgram() => 1337; protected override bool CompileInternal() => true; protected override void SetupUniforms() { Uniforms.Add("test", new Uniform<int>(this, "test", 1)); } protected override string GetProgramLog() => string.Empty; protected override void DeleteProgram(int id) { } } } } }
Make sure changelist timer is enabled in watchdog, because Steamkit can get stuck between being connected and logging in
/* * Copyright (c) 2013-2015, SteamDB. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ using System; using System.Threading; namespace SteamDatabaseBackend { public class Watchdog { public Watchdog() { new Timer(OnTimer, null, TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(20)); } private void OnTimer(object state) { if (Steam.Instance.Client.IsConnected) { AccountInfo.Sync(); } else if (DateTime.Now.Subtract(Connection.LastSuccessfulLogin).TotalMinutes >= 5.0) { Connection.Reconnect(null, null); } } } }
/* * Copyright (c) 2013-2015, SteamDB. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ using System; using System.Threading; namespace SteamDatabaseBackend { class Watchdog { public Watchdog() { new Timer(OnTimer, null, TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(20)); } private void OnTimer(object state) { if (Steam.Instance.Client.IsConnected && Application.ChangelistTimer.Enabled) { AccountInfo.Sync(); } else if (DateTime.Now.Subtract(Connection.LastSuccessfulLogin).TotalMinutes >= 5.0) { Connection.Reconnect(null, null); } } } }