Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Make Activity Serializable on NET 4.5 since it's stored in CallContext
// 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.Runtime.Remoting.Messaging; using System.Security; using System.Threading; namespace System.Diagnostics { public partial class Activity { /// <summary> /// Returns the current operation (Activity) for the current thread. This flows /// across async calls. /// </summary> public static Activity Current { #if ALLOW_PARTIALLY_TRUSTED_CALLERS [System.Security.SecuritySafeCriticalAttribute] #endif get { return (Activity)CallContext.LogicalGetData(FieldKey); } #if ALLOW_PARTIALLY_TRUSTED_CALLERS [System.Security.SecuritySafeCriticalAttribute] #endif private set { CallContext.LogicalSetData(FieldKey, value); } } #region private private static readonly string FieldKey = $"{typeof(Activity).FullName}.Value.{AppDomain.CurrentDomain.Id}"; #endregion } }
// 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.Runtime.Remoting.Messaging; using System.Security; using System.Threading; namespace System.Diagnostics { [Serializable] public partial class Activity { /// <summary> /// Returns the current operation (Activity) for the current thread. This flows /// across async calls. /// </summary> public static Activity Current { #if ALLOW_PARTIALLY_TRUSTED_CALLERS [System.Security.SecuritySafeCriticalAttribute] #endif get { return (Activity)CallContext.LogicalGetData(FieldKey); } #if ALLOW_PARTIALLY_TRUSTED_CALLERS [System.Security.SecuritySafeCriticalAttribute] #endif private set { CallContext.LogicalSetData(FieldKey, value); } } #region private private static readonly string FieldKey = $"{typeof(Activity).FullName}.Value.{AppDomain.CurrentDomain.Id}"; #endregion } }
Set name for Avalonia thread to identify it more easily in debugger.
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Windows; using Avalonia; using Avalonia.Logging.Serilog; namespace Infusion.Desktop { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : System.Windows.Application { private Avalonia.Application avaloniaApplication; private CancellationTokenSource applicationClosedTokenSource = new CancellationTokenSource(); protected override void OnStartup(StartupEventArgs e) { if (e.Args.Length == 2) { if (e.Args[0] == "command") { InterProcessCommunication.SendCommand(e.Args[1]); Shutdown(0); } } CommandLine.Handler.Handle(e.Args); Task.Run(() => { avaloniaApplication = AppBuilder.Configure<AvaloniaApp>() .UsePlatformDetect() .UseReactiveUI() .LogToDebug() .SetupWithoutStarting() .Instance; avaloniaApplication.ExitMode = ExitMode.OnExplicitExit; avaloniaApplication.Run(applicationClosedTokenSource.Token); }); base.OnStartup(e); } protected override void OnExit(ExitEventArgs e) { foreach (var window in avaloniaApplication.Windows) { window.Close(); } avaloniaApplication.MainWindow?.Close(); applicationClosedTokenSource.Cancel(); base.OnExit(e); } } }
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Windows; using Avalonia; using Avalonia.Logging.Serilog; namespace Infusion.Desktop { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : System.Windows.Application { private Avalonia.Application avaloniaApplication; private CancellationTokenSource applicationClosedTokenSource = new CancellationTokenSource(); protected override void OnStartup(StartupEventArgs e) { if (e.Args.Length == 2) { if (e.Args[0] == "command") { InterProcessCommunication.SendCommand(e.Args[1]); Shutdown(0); } } CommandLine.Handler.Handle(e.Args); Task.Run(() => { Thread.CurrentThread.Name = "Avalonia"; avaloniaApplication = AppBuilder.Configure<AvaloniaApp>() .UsePlatformDetect() .UseReactiveUI() .LogToDebug() .SetupWithoutStarting() .Instance; avaloniaApplication.ExitMode = ExitMode.OnExplicitExit; avaloniaApplication.Run(applicationClosedTokenSource.Token); }); base.OnStartup(e); } protected override void OnExit(ExitEventArgs e) { foreach (var window in avaloniaApplication.Windows) { window.Close(); } avaloniaApplication.MainWindow?.Close(); applicationClosedTokenSource.Cancel(); base.OnExit(e); } } }
Implement room exists data contract
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace Schedutalk.Logic.KTHPlaces { [DataContract] public class RoomDataContract { [DataMember(Name = "floorUid")] public string FloorUId { get; set; } [DataMember(Name = "buildingName")] public string BuildingName { get; set; } [DataMember(Name = "campus")] public string Campus { get; set; } [DataMember(Name = "typeName")] public string TypeName { get; set; } [DataMember(Name = "placeName")] public string PlaceName { get; set; } [DataMember(Name = "uid")] public string UId { get; set; } } }
Add test coverage of nested game usage
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using NUnit.Framework; using osu.Framework.Testing; namespace osu.Framework.Tests.Visual.Testing { public class TestSceneNestedGame : FrameworkTestScene { private bool hostWasRunningAfterNestedExit; [SetUpSteps] public void SetUpSteps() { AddStep("reset host running", () => hostWasRunningAfterNestedExit = false); } [Test] public void AddGameUsingStandardMethodThrows() { AddStep("Add game via add throws", () => Assert.Throws<InvalidOperationException>(() => Add(new TestGame()))); } [Test] public void TestNestedGame() { TestGame game = null; AddStep("Add game", () => AddGame(game = new TestGame())); AddStep("exit game", () => game.Exit()); AddUntilStep("game expired", () => game.Parent == null); } [TearDownSteps] public void TearDownSteps() { AddStep("mark host running", () => hostWasRunningAfterNestedExit = true); } protected override void RunTests() { base.RunTests(); Assert.IsTrue(hostWasRunningAfterNestedExit); } } }
Test to verify compiled query error was addressed in v4 changes. Closes GH-784
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using Marten.Linq; using Marten.Testing.Documents; using Marten.Testing.Harness; using Shouldly; using Xunit; using Xunit.Abstractions; namespace Marten.Testing.Bugs { public class Bug_784_Collection_Contains_within_compiled_query : IntegrationContext { private readonly ITestOutputHelper _output; [Fact] public void do_not_blow_up_with_exceptions() { var targets = Target.GenerateRandomData(100).ToArray(); targets[1].NumberArray = new[] {3, 4, 5}; targets[1].Flag = true; targets[5].NumberArray = new[] {3, 4, 5}; targets[5].Flag = true; targets[20].NumberArray = new[] {5, 6, 7}; targets[20].Flag = true; theStore.BulkInsert(targets); using (var query = theStore.QuerySession()) { query.Logger = new TestOutputMartenLogger(_output); var expected = targets.Where(x => x.Flag && x.NumberArray.Contains(5)).ToArray(); expected.Any(x => x.Id == targets[1].Id).ShouldBeTrue(); expected.Any(x => x.Id == targets[5].Id).ShouldBeTrue(); expected.Any(x => x.Id == targets[20].Id).ShouldBeTrue(); var actuals = query.Query(new FunnyTargetQuery{Number = 5}).ToArray(); actuals.OrderBy(x => x.Id).Select(x => x.Id) .ShouldHaveTheSameElementsAs(expected.OrderBy(x => x.Id).Select(x => x.Id)); actuals.Any(x => x.Id == targets[1].Id).ShouldBeTrue(); actuals.Any(x => x.Id == targets[5].Id).ShouldBeTrue(); actuals.Any(x => x.Id == targets[20].Id).ShouldBeTrue(); } } public class FunnyTargetQuery : ICompiledListQuery<Target> { public Expression<Func<IMartenQueryable<Target>, IEnumerable<Target>>> QueryIs() { return q => q.Where(x => x.Flag && x.NumberArray.Contains(Number)); } public int Number { get; set; } } public Bug_784_Collection_Contains_within_compiled_query(DefaultStoreFixture fixture, ITestOutputHelper output) : base(fixture) { _output = output; } } }
Verify that an exception is thrown when more than one type matches
using System; using System.Collections.Generic; using Xunit; using Xunit.Extensions; namespace AppHarbor.Tests { public class TypeNameMatcherTest { interface IFoo { } class Foo : IFoo { } private static Type FooType = typeof(Foo); [Fact] public void ShouldThrowIfInitializedWithUnnasignableType() { var exception = Assert.Throws<ArgumentException>(() => new TypeNameMatcher<IFoo>(new List<Type> { typeof(string) })); } [Theory] [InlineData("Foo")] [InlineData("foo")] public void ShouldGetTypeStartingWithCommandName(string commandName) { var matcher = new TypeNameMatcher<IFoo>(new Type[] { FooType }); Assert.Equal(FooType, matcher.GetMatchedType(commandName)); } [Theory] [InlineData("Bar")] public void ShouldThrowWhenNoTypesMatches(string commandName) { var matcher = new TypeNameMatcher<IFoo>(new Type[] { FooType }); Assert.Throws<ArgumentException>(() => matcher.GetMatchedType(commandName)); } } }
using System; using System.Collections.Generic; using Xunit; using Xunit.Extensions; namespace AppHarbor.Tests { public class TypeNameMatcherTest { interface IFoo { } class Foo : IFoo { } private static Type FooType = typeof(Foo); [Fact] public void ShouldThrowIfInitializedWithUnnasignableType() { var exception = Assert.Throws<ArgumentException>(() => new TypeNameMatcher<IFoo>(new List<Type> { typeof(string) })); } [Theory] [InlineData("Foo")] [InlineData("foo")] public void ShouldGetTypeStartingWithCommandName(string commandName) { var matcher = new TypeNameMatcher<IFoo>(new Type[] { FooType }); Assert.Equal(FooType, matcher.GetMatchedType(commandName)); } [Theory] [InlineData("Foo")] public void ShouldThrowWhenMoreThanOneTypeMatches(string commandName) { var matcher = new TypeNameMatcher<IFoo>(new Type[] { FooType, FooType }); Assert.Throws<ArgumentException>(() => matcher.GetMatchedType(commandName)); } [Theory] [InlineData("Bar")] public void ShouldThrowWhenNoTypesMatches(string commandName) { var matcher = new TypeNameMatcher<IFoo>(new Type[] { FooType }); Assert.Throws<ArgumentException>(() => matcher.GetMatchedType(commandName)); } } }
Remove the nullable disable annotation in the testing beatmap and mark some of the properties as nullable.
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable disable using System.IO; using osu.Framework.Audio; using osu.Framework.Audio.Track; using osu.Framework.Graphics.Textures; using osu.Game.Beatmaps; using osu.Game.Skinning; using osu.Game.Storyboards; namespace osu.Game.Tests.Beatmaps { public class TestWorkingBeatmap : WorkingBeatmap { private readonly IBeatmap beatmap; private readonly Storyboard storyboard; /// <summary> /// Create an instance which provides the <see cref="IBeatmap"/> when requested. /// </summary> /// <param name="beatmap">The beatmap.</param> /// <param name="storyboard">An optional storyboard.</param> /// <param name="audioManager">The <see cref="AudioManager"/>.</param> public TestWorkingBeatmap(IBeatmap beatmap, Storyboard storyboard = null, AudioManager audioManager = null) : base(beatmap.BeatmapInfo, audioManager) { this.beatmap = beatmap; this.storyboard = storyboard; } public override bool BeatmapLoaded => true; protected override IBeatmap GetBeatmap() => beatmap; protected override Storyboard GetStoryboard() => storyboard ?? base.GetStoryboard(); protected internal override ISkin GetSkin() => null; public override Stream GetStream(string storagePath) => null; protected override Texture GetBackground() => null; protected override Track GetBeatmapTrack() => null; } }
// 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.IO; using osu.Framework.Audio; using osu.Framework.Audio.Track; using osu.Framework.Graphics.Textures; using osu.Game.Beatmaps; using osu.Game.Skinning; using osu.Game.Storyboards; namespace osu.Game.Tests.Beatmaps { public class TestWorkingBeatmap : WorkingBeatmap { private readonly IBeatmap beatmap; private readonly Storyboard? storyboard; /// <summary> /// Create an instance which provides the <see cref="IBeatmap"/> when requested. /// </summary> /// <param name="beatmap">The beatmap.</param> /// <param name="storyboard">An optional storyboard.</param> /// <param name="audioManager">The <see cref="AudioManager"/>.</param> public TestWorkingBeatmap(IBeatmap beatmap, Storyboard? storyboard = null, AudioManager? audioManager = null) : base(beatmap.BeatmapInfo, audioManager) { this.beatmap = beatmap; this.storyboard = storyboard; } public override bool BeatmapLoaded => true; protected override IBeatmap GetBeatmap() => beatmap; protected override Storyboard GetStoryboard() => storyboard ?? base.GetStoryboard(); protected internal override ISkin? GetSkin() => null; public override Stream? GetStream(string storagePath) => null; protected override Texture? GetBackground() => null; protected override Track? GetBeatmapTrack() => null; } }
Add a level script that can trigger the ending cutscene
using System.Collections; using System.Collections.Generic; using UnityEngine; public class BuilderLevel : MonoBehaviour { public CameraManager camera; public void doTakeoff() { double time = 1.5; Vector3 pos = camera.transform.position; pos.y += -10; //camera.scootTo (pos, time); camera.rotateTo (new Vector3 (0, 0, 180), time); camera.zoomTo (25, time); } // Use this for initialization void Start () { } // Update is called once per frame void Update () { if (Input.GetKeyUp ("return")) { doTakeoff (); } } }
Add tracingheader for support Diagnostics
// Copyright (c) .NET Core Community. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System.Collections; using System.Collections.Generic; using System.Linq; namespace DotNetCore.CAP.Diagnostics { public class TracingHeaders : IEnumerable<KeyValuePair<string, string>> { private List<KeyValuePair<string, string>> _dataStore; public IEnumerator<KeyValuePair<string, string>> GetEnumerator() { return _dataStore.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public void Add(string name, string value) { if (_dataStore == null) { _dataStore = new List<KeyValuePair<string, string>>(); } _dataStore.Add(new KeyValuePair<string, string>(name, value)); } public bool Contains(string name) { return _dataStore != null && _dataStore.Any(x => x.Key == name); } public void Remove(string name) { _dataStore?.RemoveAll(x => x.Key == name); } public void Cleaar() { _dataStore?.Clear(); } } }
Update the example to skip authentication
namespace BasicExample { using System; using System.Collections.Generic; using Crest.Abstractions; /// <summary> /// Shows an example of how to disable JWT authentication. /// </summary> public sealed class DisableJwtAuthentication : IJwtSettings { /// <inheritdoc /> public ISet<string> Audiences { get; } /// <inheritdoc /> public string AuthenticationType { get; } /// <inheritdoc /> public TimeSpan ClockSkew { get; } /// <inheritdoc /> public ISet<string> Issuers { get; } /// <inheritdoc /> public IReadOnlyDictionary<string, string> JwtClaimMappings { get; } /// <inheritdoc /> public bool SkipAuthentication => true; } }
Create initial attributes for attribute-driven Worksheet.FromData
using System; namespace Simplexcel.Cells { [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false, Inherited = true)] internal class XlsxColumnAttribute : Attribute { /// <summary> /// The name of the Column, used as the Header row /// </summary> public string Name { get; set; } } /// <summary> /// This attribute causes <see cref="Worksheet.FromData"/> to ignore the property completely /// </summary> [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false, Inherited = true)] internal class XlsxIgnoreColumnAttribute : Attribute { } }
Add Brandon Olin as author
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using System.Web; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class BrandonOlin : IFilterMyBlogPosts, IAmACommunityMember { public string FirstName => "Brandon"; public string LastName => "Olin"; public string ShortBioOrTagLine => "Cloud Architect and veteran Systems Engineer with a penchant for PowerShell, DevOps processes, and open-source software."; public string StateOrRegion => "Portland, Oregon"; public string EmailAddress => "brandon@devblackops.io"; public string TwitterHandle => "devblackops"; public string GitHubHandle => "devblackops"; public string GravatarHash => "07f265f8f921b6876ce9ea65902f0480"; public GeoPosition Position => new GeoPosition(45.5131063, -122.670492); public Uri WebSite => new Uri("https://devblackops.io/"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://devblackops.io/feed.xml"); } } public bool Filter(SyndicationItem item) { return item.Categories.Where(i => i.Name.Equals("powershell", StringComparison.OrdinalIgnoreCase)).Any(); } } }
Add benchmark coverage of `Scheduler`
// 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 BenchmarkDotNet.Attributes; using osu.Framework.Threading; namespace osu.Framework.Benchmarks { public class BenchmarkScheduler : BenchmarkTest { private Scheduler scheduler = null!; private Scheduler schedulerWithEveryUpdate = null!; private Scheduler schedulerWithManyDelayed = null!; public override void SetUp() { base.SetUp(); scheduler = new Scheduler(); schedulerWithEveryUpdate = new Scheduler(); schedulerWithEveryUpdate.AddDelayed(() => { }, 0, true); schedulerWithManyDelayed = new Scheduler(); for (int i = 0; i < 1000; i++) schedulerWithManyDelayed.AddDelayed(() => { }, int.MaxValue); } [Benchmark] public void UpdateEmptyScheduler() { for (int i = 0; i < 1000; i++) scheduler.Update(); } [Benchmark] public void UpdateSchedulerWithManyDelayed() { for (int i = 0; i < 1000; i++) schedulerWithManyDelayed.Update(); } [Benchmark] public void UpdateSchedulerWithEveryUpdate() { for (int i = 0; i < 1000; i++) schedulerWithEveryUpdate.Update(); } [Benchmark] public void UpdateSchedulerWithManyAdded() { for (int i = 0; i < 1000; i++) { scheduler.Add(() => { }); scheduler.Update(); } } } }
Add dump PSI for file internal action
using System.Diagnostics; using System.IO; using System.Text; using JetBrains.Application.DataContext; using JetBrains.Application.UI.Actions; using JetBrains.Application.UI.ActionsRevised.Menu; using JetBrains.Application.UI.ActionSystem.ActionsRevised.Menu; using JetBrains.ProjectModel; using JetBrains.ProjectModel.DataContext; using JetBrains.ReSharper.Features.Internal.PsiModules; using JetBrains.ReSharper.Features.Internal.resources; using JetBrains.ReSharper.Psi; using JetBrains.ReSharper.Psi.ExtensionsAPI; using JetBrains.Util; namespace JetBrains.ReSharper.Plugins.Unity.Internal { [Action("Dump PSI for Current File")] public class DumpPsiForFileAction : IExecutableAction, IInsertBefore<InternalPsiMenu, DumpPsiSourceFilePropertiesAction> { public bool Update(IDataContext context, ActionPresentation presentation, DelegateUpdate nextUpdate) { var projectFile = context.GetData(ProjectModelDataConstants.PROJECT_MODEL_ELEMENT) as IProjectFile; return projectFile?.ToSourceFile() != null; } public void Execute(IDataContext context, DelegateExecute nextExecute) { var projectFile = context.GetData(ProjectModelDataConstants.PROJECT_MODEL_ELEMENT) as IProjectFile; var sourceFile = projectFile?.ToSourceFile(); if (sourceFile == null) return; var path = CompanySpecificFolderLocations.TempFolder / (Path.GetRandomFileName() + ".txt"); using (var sw = new StreamWriter(path.OpenFileForWriting(), Encoding.UTF8)) { foreach (var psiFile in sourceFile.EnumerateDominantPsiFiles()) { sw.WriteLine("Language: {0}", psiFile.Language.Name); DebugUtil.DumpPsi(sw, psiFile); } } Process.Start(path.FullPath); } } }
Create abstract base class for a HttpServer
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net; using System.Threading; namespace Snowflake.Core.Server { public abstract class BaseHttpServer { HttpListener serverListener; Thread serverThread; bool cancel; public BaseHttpServer(int port) { serverListener = new HttpListener(); serverListener.Prefixes.Add("http://localhost:" + port.ToString() + "/"); } public void StartServer() { this.serverThread = new Thread( () => { serverListener.Start(); while (!this.cancel) { HttpListenerContext context = serverListener.GetContext(); Task.Run(() => this.Process(context)); } } ); this.serverThread.IsBackground = true; this.serverThread.Start(); } public void StopServer() { this.cancel = true; this.serverThread.Join(); this.serverListener.Stop(); } public abstract void Process(HttpListenerContext context); } }
Fix build error for XCode
using System; using System.IO; using UnityEngine; using UnityEditor; using UnityEditor.iOS.Xcode; using UnityEditor.Callbacks; using System.Collections; public class UpdateXcodeProject { [PostProcessBuildAttribute (0)] public static void OnPostprocessBuild (BuildTarget buildTarget, string pathToBuiltProject) { // Stop processing if targe is NOT iOS if (buildTarget != BuildTarget.iOS) return; UpdateXcode(pathToBuiltProject); } static void UpdateXcode(string pathToBuiltProject) { var projectPath = pathToBuiltProject + "/Unity-iPhone.xcodeproj/project.pbxproj"; if (!File.Exists(projectPath)) { throw new Exception(string.Format("projectPath is null {0}", projectPath)); } // Initialize PbxProject PBXProject pbxProject = new PBXProject(); pbxProject.ReadFromFile(projectPath); string targetGuid = pbxProject.TargetGuidByName("Unity-iPhone"); // Adding required framework pbxProject.AddFrameworkToProject(targetGuid, "UserNotifications.framework", false); // Apply settings File.WriteAllText (projectPath, pbxProject.WriteToString()); } }
Add helper extension methods for route data - Added RouteData.GetCurrentPage<T>() - Added RouteData.GetNavigationContext()
using System.Web; using System.Web.Routing; using BrickPile.Core.Routing; namespace BrickPile.Core.Extensions { public static class RouteDataExtensions { public static T GetCurrentPage<T>(this RouteData data) { return (T)data.Values[PageRoute.CurrentPageKey]; } public static NavigationContext GetNavigationContext(this RouteData data) { return new NavigationContext(HttpContext.Current.Request.RequestContext); } } }
Add helper to track ongoing operations in UI
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Bindables; namespace osu.Game.Screens.OnlinePlay { /// <summary> /// Utility class to track ongoing online operations' progress. /// Can be used to disable interactivity while waiting for a response from online sources. /// </summary> public class OngoingOperationTracker { /// <summary> /// Whether there is an online operation in progress. /// </summary> public IBindable<bool> InProgress => inProgress; private readonly Bindable<bool> inProgress = new BindableBool(); private LeasedBindable<bool> leasedInProgress; /// <summary> /// Begins tracking a new online operation. /// </summary> /// <exception cref="InvalidOperationException">An operation has already been started.</exception> public void BeginOperation() { if (leasedInProgress != null) throw new InvalidOperationException("Cannot begin operation while another is in progress."); leasedInProgress = inProgress.BeginLease(true); leasedInProgress.Value = true; } /// <summary> /// Ends tracking an online operation. /// Does nothing if an operation has not been begun yet. /// </summary> public void EndOperation() { leasedInProgress?.Return(); leasedInProgress = null; } } }
Add missing file to repository
// *********************************************************************** // Copyright (c) 2012 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. // *********************************************************************** using System; using System.Collections.Generic; using System.Text; using NUnit.Engine.Internal; namespace NUnit.Engine.Services { public interface ITraceService : IService { Logger GetLogger(string name); void Log(InternalTraceLevel level, string message, string category); void Log(InternalTraceLevel level, string message, string category, Exception ex); } public class InternalTraceService : ITraceService { private readonly static string TIME_FMT = "HH:mm:ss.fff"; private static bool initialized; private InternalTraceWriter writer; public InternalTraceLevel Level; public InternalTraceService(InternalTraceLevel level) { this.Level = level; } public void Initialize(string logName, InternalTraceLevel level) { if (!initialized) { Level = level; if (writer == null && Level > InternalTraceLevel.Off) { writer = new InternalTraceWriter(logName); writer.WriteLine("InternalTrace: Initializing at level " + Level.ToString()); } initialized = true; } } public Logger GetLogger(string name) { return new Logger(this, name); } public Logger GetLogger(Type type) { return new Logger(this, type.FullName); } public void Log(InternalTraceLevel level, string message, string category) { Log(level, message, category, null); } public void Log(InternalTraceLevel level, string message, string category, Exception ex) { if (writer != null) { writer.WriteLine("{0} {1,-5} [{2,2}] {3}: {4}", DateTime.Now.ToString(TIME_FMT), level == InternalTraceLevel.Verbose ? "Debug" : level.ToString(), System.Threading.Thread.CurrentThread.ManagedThreadId, category, message); if (ex != null) writer.WriteLine(ex.ToString()); } } #region IService Members private ServiceContext services; public ServiceContext ServiceContext { get { return services; } set { services = value; } } public void InitializeService() { } public void UnloadService() { } #endregion } }
Add utility class (mapped from Java SDK)
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Alexa.NET.Request.Type; namespace Alexa.NET.Request { public static class SkillRequestUtility { public static string GetIntentName(this SkillRequest request) { return request.Request is IntentRequest intentRequest ? intentRequest.Intent.Name : string.Empty; } public static string GetAccountLinkAccessToken(this SkillRequest request) { return request?.Context?.System?.User?.AccessToken; } public static string GetApiAccessToken(this SkillRequest request) { return request?.Context?.System?.ApiAccessToken; } public static string GetDeviceId(this SkillRequest request) { return request?.Context?.System?.Device?.DeviceID; } public static string GetDialogState(this SkillRequest request) { return request.Request is IntentRequest intentRequest ? intentRequest.DialogState : string.Empty; } public static Slot GetSlot(this SkillRequest request, string slotName) { return request.Request is IntentRequest intentRequest && intentRequest.Intent.Slots.ContainsKey(slotName) ? intentRequest.Intent.Slots[slotName] : null; } public static string GetSlotValue(this SkillRequest request, string slotName) { return GetSlot(request, slotName)?.Value; } public static Dictionary<string,object> GetSupportedInterfaces(this SkillRequest request) { return request?.Context?.System?.Device?.SupportedInterfaces; } public static bool? IsNewSession(this SkillRequest request) { return request?.Session?.New; } public static string GetUserId(this SkillRequest request) { return request?.Session?.User?.UserId; } } }
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 API service to handle save and load of API keys
using System; using System.Threading.Tasks; using ReceptionKiosk.Helpers; using Windows.Storage; using Windows.UI.Xaml; namespace ReceptionKiosk.Services { public class APISettingsService { private string faceAPI; private string bingAPI; public APISettingsService() { LoadAPIKeysFromSettingsAsync(); } public string FaceAPI { get { return faceAPI; } set { faceAPI = value; SaveAPIKeysInSettingsAsync("FaceAPI", faceAPI); } } public string BingAPI { get { return bingAPI; } set { bingAPI = value; SaveAPIKeysInSettingsAsync("BingAPI", bingAPI); } } private async void LoadAPIKeysFromSettingsAsync() { BingAPI = await ApplicationData.Current.LocalSettings.ReadAsync<string>("FaceAPI"); FaceAPI = await ApplicationData.Current.LocalSettings.ReadAsync<string>("BingAPI"); } private static async Task SaveAPIKeysInSettingsAsync(string SettingsKey, string APIKeyValue) { await ApplicationData.Current.LocalSettings.SaveAsync<string>(SettingsKey, APIKeyValue); } } }
Add missing PartsDb base class
using System; using System.Data; using System.Collections.Generic; public delegate void ErrorHandler(string message, Exception exception); public delegate void PartTypesHandler(List<PartType> partTypes); public delegate void PartsHandler(PartCollection part); public delegate void PartHandler(Part part); public abstract class PartsDb { public string Username { get; set; } public string Password { get; set; } public string Hostname { get; set; } public string Database { get; set; } public abstract void GetPartTypes(PartTypesHandler partTypeHandler, ErrorHandler errorHandler); public abstract void GetPart(string Part_num, PartHandler partHandler, ErrorHandler errorHandler); public abstract void GetParts(PartType partType, PartsHandler partsHandler, ErrorHandler errorHandler); //TODO: This should be based off a new part. The *controller* should figure out how to make the new part, the DB should only dutifully insert it. public abstract void NewPart(PartType partType, ErrorHandler errorHandler); public abstract void UpdatePart(Part part, ErrorHandler errorHandler); }
Test for async graph updates from gui block/connector
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using KSPCommEngr; namespace CommEngrTest { [TestClass] public class CommBlockTests { [TestMethod] public void UpdateGraphOnDragStop() { Graph graph = new Graph(new int[,] { { 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 } }); Graph expectedGraph = new Graph(new int[,] { { 0, 0, 0, 0, 0 }, { 0, 1, 1, 1, 0 }, { 0, 1, 1, 1, 0 }, { 0, 1, 1, 1, 0 }, { 0, 0, 0, 0, 0 } }); // User Drag and Drop Event CollectionAssert.AreEqual(expectedGraph.nodes, graph.nodes); } } }
Add simple test case for FullscreenOverlay
// 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.Graphics; using osu.Framework.Graphics.Shapes; using osu.Game.Overlays; using osuTK.Graphics; namespace osu.Game.Tests.Visual.Online { [TestFixture] public class TestCaseFullscreenOverlay : OsuTestCase { private FullscreenOverlay overlay; protected override void LoadComplete() { base.LoadComplete(); Add(overlay = new TestFullscreenOverlay()); AddStep(@"toggle", overlay.ToggleVisibility); } private class TestFullscreenOverlay : FullscreenOverlay { public TestFullscreenOverlay() { Children = new Drawable[] { new Box { Colour = Color4.Black, RelativeSizeAxes = Axes.Both, }, }; } } } }
Check we don't reference DesignTime assemblies
using System.IO; using System.Reflection; using NUnit.Framework; public class GitHubAssemblyTests { [Theory] public void GitHub_Assembly_Should_Not_Reference_DesignTime_Assembly(string assemblyFile) { var asm = Assembly.LoadFrom(assemblyFile); foreach (var referencedAssembly in asm.GetReferencedAssemblies()) { Assert.That(referencedAssembly.Name, Does.Not.EndWith(".DesignTime"), "DesignTime assemblies should be embedded not referenced"); } } [DatapointSource] string[] GitHubAssemblies => Directory.GetFiles(AssemblyDirectory, "GitHub.*.dll"); string AssemblyDirectory => Path.GetDirectoryName(GetType().Assembly.Location); }
Create new CelestialBody from asteroid data
using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; namespace DMModuleScienceAnimateGeneric { public class AsteroidScience { protected DMModuleScienceAnimateGeneric ModSci = FlightGlobals.ActiveVessel.FindPartModulesImplementing<DMModuleScienceAnimateGeneric>().First(); //Let's make us some asteroid science //First construct a new celestial body from an asteroid public CelestialBody AsteroidBody = null; public CelestialBody Asteroid() { AsteroidBody = new CelestialBody(); AsteroidBody.bodyName = "Asteroid P2X-459"; AsteroidBody.use_The_InName = false; asteroidValues(AsteroidBody); return AsteroidBody; } public void asteroidValues(CelestialBody body) { //Find out how to vary based on asteroid size body.scienceValues.LandedDataValue = 10f; body.scienceValues.InSpaceLowDataValue = 4f; } public ExperimentSituations asteroidSituation() { if (asteroidGrappled()) return ExperimentSituations.SrfLanded; else if (asteroidNear()) return ExperimentSituations.InSpaceLow; else return ModSci.getSituation(); } //Are we attached to the asteroid public bool asteroidGrappled() { if (FlightGlobals.ActiveVessel.FindPartModulesImplementing<ModuleAsteroid>().Count >= 1) return true; else return false; } //Are we near the asteroid - need to figure this out public bool asteroidNear() { return false; } } }
Add test for BinarySearcher class
using System.Collections.Generic; using Xunit; using Algorithms.Search; namespace UnitTest.AlgorithmsTests { public static class BinarySearcherTest { [Fact] public static void MergeSortTest() { //a list of int IList<int> list = new List<int> {9, 3, 7, 1, 6, 10}; IList<int> sortedList = BinarySearcher.MergeSort<int>(list); IList<int> expectedList = new List<int> { 1, 3, 6, 7, 9, 10 }; Assert.Equal(expectedList, sortedList); //a list of strings IList<string> animals = new List<string> {"lion", "cat", "tiger", "bee"}; IList<string> sortedAnimals = BinarySearcher.MergeSort<string>(animals); IList<string> expectedAnimals = new List<string> {"bee", "cat", "lion", "tiger"}; Assert.Equal(expectedAnimals, sortedAnimals); } [Fact] public static void BinarySearchTest() { //list of ints IList<int> list = new List<int> { 9, 3, 7, 1, 6, 10 }; IList<int> sortedList = BinarySearcher.MergeSort<int>(list); int itemIndex = BinarySearcher.BinarySearch<int>(list, 6); int expectedIndex = sortedList.IndexOf(6); Assert.Equal(expectedIndex, itemIndex); //list of strings IList<string> animals = new List<string> {"lion", "cat", "tiger", "bee", "sparrow"}; IList<string> sortedAnimals = BinarySearcher.MergeSort<string>(animals); int actualIndex = BinarySearcher.BinarySearch<string>(animals, "cat"); int expectedAnimalIndex = sortedAnimals.IndexOf("cat"); Assert.Equal(expectedAnimalIndex, actualIndex); } [Fact] public static void NullCollectionExceptionTest() { IList<int> list = null; Assert.Throws<System.NullReferenceException>(() => BinarySearcher.BinarySearch<int>(list,0)); } } }
Adjust transform to look better
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; namespace osu.Game.Graphics.Containers { public class ShakeContainer : Container { public void Shake() { const int shake_amount = 8; const int shake_duration = 20; this.MoveToX(shake_amount, shake_duration).Then() .MoveToX(-shake_amount, shake_duration).Then() .MoveToX(shake_amount, shake_duration).Then() .MoveToX(-shake_amount, shake_duration).Then() .MoveToX(shake_amount, shake_duration).Then() .MoveToX(0, shake_duration); } } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; namespace osu.Game.Graphics.Containers { public class ShakeContainer : Container { public void Shake() { const float shake_amount = 8; const float shake_duration = 30; this.MoveToX(shake_amount, shake_duration / 2, Easing.OutSine).Then() .MoveToX(-shake_amount, shake_duration, Easing.InOutSine).Then() .MoveToX(shake_amount, shake_duration, Easing.InOutSine).Then() .MoveToX(-shake_amount, shake_duration, Easing.InOutSine).Then() .MoveToX(shake_amount, shake_duration, Easing.InOutSine).Then() .MoveToX(0, shake_duration / 2, Easing.InSine); } } }
Add the support for autoscale SCPI command
using System; using System.Collections.Generic; using System.Text; namespace SCPI { public class AUTOSCALE : ICommand { public string Description => "The oscilloscope will automatically adjust the vertical scale, horizontal timebase, and trigger mode according to the input signal to realize optimum waveform display"; public string Command(params string[] parameters) => ":AUToscale"; public string HelpMessage() => nameof(AUTOSCALE); public bool Parse(byte[] data) => true; } }
Fix typo: Arrary --> Array
using System; using System.Linq.Expressions; namespace Nest.Resolvers { public static class Property { /// <summary> /// Create a strongly typed string representation of the path to a property /// <para>i.e p => p.Arrary.First().SubProperty.Field will return 'array.subProperty.field'</para> /// </summary> /// <typeparam name="T">The type of the object</typeparam> /// <param name="path">The path we want to specify</param> /// <param name="boost">An optional ^boost postfix, only make sense with queries</param> public static PropertyPathMarker Path<T>(Expression<Func<T, object>> path, double? boost = null) where T : class { return PropertyPathMarker.Create(path, boost); } /// <summary> /// Create a strongly typed string representation of the name to a property /// <para>i.e p => p.Arrary.First().SubProperty.Field will return 'field'</para> /// </summary> /// <typeparam name="T">The type of the object</typeparam> /// <param name="path">The path we want to specify</param> /// <param name="boost">An optional ^boost postfix, only make sense with queries</param> public static PropertyNameMarker Name<T>(Expression<Func<T, object>> path, double? boost = null) where T : class { return PropertyNameMarker.Create(path, boost); } } }
using System; using System.Linq.Expressions; namespace Nest.Resolvers { public static class Property { /// <summary> /// Create a strongly typed string representation of the path to a property /// <para>i.e p => p.Array.First().SubProperty.Field will return 'array.subProperty.field'</para> /// </summary> /// <typeparam name="T">The type of the object</typeparam> /// <param name="path">The path we want to specify</param> /// <param name="boost">An optional ^boost postfix, only make sense with queries</param> public static PropertyPathMarker Path<T>(Expression<Func<T, object>> path, double? boost = null) where T : class { return PropertyPathMarker.Create(path, boost); } /// <summary> /// Create a strongly typed string representation of the name to a property /// <para>i.e p => p.Array.First().SubProperty.Field will return 'field'</para> /// </summary> /// <typeparam name="T">The type of the object</typeparam> /// <param name="path">The path we want to specify</param> /// <param name="boost">An optional ^boost postfix, only make sense with queries</param> public static PropertyNameMarker Name<T>(Expression<Func<T, object>> path, double? boost = null) where T : class { return PropertyNameMarker.Create(path, boost); } } }
Move JobStore cleanup to abstract class.
using System; namespace Quartz.DynamoDB.Tests.Integration.JobStore { /// <summary> /// Abstract class that provides common dynamo db cleanup for JobStore integration testing. /// </summary> public abstract class JobStoreIntegrationTest : IDisposable { protected DynamoDB.JobStore _sut; protected DynamoClientFactory _testFactory; #region IDisposable implementation bool _disposedValue = false; protected virtual void Dispose(bool disposing) { if (!_disposedValue) { if (disposing) { _testFactory.CleanUpDynamo(); if (_sut != null) { _sut.Dispose(); } } _disposedValue = true; } } // This code added to correctly implement the disposable pattern. public void Dispose() { // Do not change this code. Put cleanup code in Dispose(bool disposing) above. Dispose(true); } #endregion } }
Copy source code from KLibrary-Labs
using System; using System.Collections.Generic; namespace KLibrary.Linq { public static class Comparison { public static IComparer<T> CreateComparer<T>(Func<T, T, int> compare) { return new DelegateComparer<T>(compare); } public static IEqualityComparer<T> CreateEqualityComparer<T>(Func<T, T, bool> equals) { return new DelegateEqualityComparer<T>(equals); } } class DelegateComparer<T> : Comparer<T> { Func<T, T, int> _compare; public DelegateComparer(Func<T, T, int> compare) { if (compare == null) throw new ArgumentNullException("compare"); _compare = compare; } public override int Compare(T x, T y) { return _compare(x, y); } } class DelegateEqualityComparer<T> : EqualityComparer<T> { Func<T, T, bool> _equals; public DelegateEqualityComparer(Func<T, T, bool> equals) { if (equals == null) throw new ArgumentNullException("equals"); _equals = equals; } public override bool Equals(T x, T y) { return _equals(x, y); } public override int GetHashCode(T obj) { return obj != null ? obj.GetHashCode() : 0; } } }
Implement testcase for room settings
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Online.Multiplayer; using osu.Game.Screens.Multi.Match.Components; namespace osu.Game.Tests.Visual { public class TestCaseMatchSettingsOverlay : OsuTestCase { public TestCaseMatchSettingsOverlay() { Child = new RoomSettingsOverlay(new Room()) { RelativeSizeAxes = Axes.Both, State = Visibility.Visible }; } } }
Add stub implementation of local
using System; namespace Glimpse.Server { public class LocalBrokerPublisher : IBrokerPublisher { public void PublishMessage(IMessage message) { // TODO: push straight to the bus } } }
Add auto exit play mode on compile
using UnityEngine; using System.Collections; using UnityEditor; namespace Expanse { /// <summary> /// Exits play mode automatically when Unity performs code compilation. /// </summary> [InitializeOnLoad] public class ExitPlayModeOnCompile { private static ExitPlayModeOnCompile instance = null; static ExitPlayModeOnCompile() { instance = new ExitPlayModeOnCompile(); } private ExitPlayModeOnCompile() { EditorApplication.update += OnEditorUpdate; } ~ExitPlayModeOnCompile() { EditorApplication.update -= OnEditorUpdate; if (instance == this) instance = null; } private static void OnEditorUpdate() { if (EditorApplication.isPlaying && EditorApplication.isCompiling) { EditorApplication.isPlaying = false; } } } }
Add constant time functions and functions for generating random bytes
using System; using System.Runtime.CompilerServices; namespace NSec.Experimental { public static class CryptographicUtilities { [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void FillRandomBytes(Span<byte> data) { System.Security.Cryptography.RandomNumberGenerator.Fill(data); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool FixedTimeEquals(ReadOnlySpan<byte> left, ReadOnlySpan<byte> right) { return System.Security.Cryptography.CryptographicOperations.FixedTimeEquals(left, right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ZeroMemory(Span<byte> buffer) { System.Security.Cryptography.CryptographicOperations.ZeroMemory(buffer); } } }
Add new configuration for ServiceContainer
namespace TestHttpCompositionConsoleApp.ConfigurationSources { using System; using Newtonsoft.Json; using Serviceable.Objects.Composition.Graph; using Serviceable.Objects.Composition.Graph.Stages.Configuration; using Serviceable.Objects.Composition.Service; using Serviceable.Objects.IO.NamedPipes.Server; using Serviceable.Objects.IO.NamedPipes.Server.Configuration; using Serviceable.Objects.Remote.Composition.ServiceContainer.Configuration; public sealed class ServiceContainerConfigurationSource : IConfigurationSource { public string GetConfigurationValueForKey(IService service, GraphContext graphContext, GraphNodeContext graphNodeContext, Type type) { switch (type) { case var t when t == typeof(NamedPipeServerContext): return JsonConvert.SerializeObject(new NamedPipeServerConfiguration { PipeName = "testpipe" }); case var t when t == typeof(ServiceContainerContextConfiguration): return JsonConvert.SerializeObject(new ServiceContainerContextConfiguration { ContainerName = "container-X", OrchestratorName = "orchestrator-X", }); default: throw new InvalidOperationException($"Type {type.FullName} is not supported."); } } } }
Add a class to perform basic vector operations (addition, subtraction, scaling) for the optimization needs.
using System; namespace ISAAR.MSolve.Analyzers.Optimization.Commons { public static class VectorOperations { public static double[] Add(double[] v1, double[] v2) { CheckDimensions(v1, v2); double[] result = new double[v1.Length]; for (int i = 0; i < v1.Length; i++) { result[i] = v1[i] + v2[i]; } return result; } public static double[] Scale(double scalar, double[] vector) { double[] result = new double[vector.Length]; for (int i = 0; i < vector.Length; i++) { result[i] = scalar * vector[i]; } return result; } public static double[] Subtract(double[] v1, double[] v2) { CheckDimensions(v1, v2); double[] result = new double[v1.Length]; for (int i = 0; i < v1.Length; i++) { result[i] = v1[i] - v2[i]; } return result; } private static void CheckDimensions(double[] v1, double[] v2) { if (v1.Length != v2.Length) { throw new ArgumentException("Vectors must have equal lengths!"); } } } }
Add interface for common properties
namespace food_tracker { public interface IListItems { double calories { get; set; } double amount { get; set; } double fats { get; set; } double saturatedFat { get; set; } double carbohydrates { get; set; } double sugar { get; set; } double protein { get; set; } double salt { get; set; } double fibre { get; set; } string name { get; set; } int nutritionId { get; set; } } }
Return Dummy from unconfigured property getter
namespace FakeItEasy.Core { using System; using System.Linq; using FakeItEasy.Creation; /// <content>Auto fake property rule.</content> public partial class FakeManager { [Serializable] private class AutoFakePropertyRule : IFakeObjectCallRule { public FakeManager FakeManager { private get; set; } public int? NumberOfTimesToCall { get { return null; } } private static IFakeAndDummyManager FakeAndDummyManager { get { return ServiceLocator.Current.Resolve<IFakeAndDummyManager>(); } } public bool IsApplicableTo(IFakeObjectCall fakeObjectCall) { Guard.AgainstNull(fakeObjectCall, "fakeObjectCall"); return PropertyBehaviorRule.IsPropertyGetter(fakeObjectCall.Method); } public void Apply(IInterceptedFakeObjectCall fakeObjectCall) { Guard.AgainstNull(fakeObjectCall, "fakeObjectCall"); object theValue; if (!TryCreateFake(fakeObjectCall.Method.ReturnType, out theValue)) { theValue = DefaultReturnValue(fakeObjectCall); } var newRule = new CallRuleMetadata { Rule = new PropertyBehaviorRule(fakeObjectCall.Method, FakeManager) { Value = theValue, Indices = fakeObjectCall.Arguments.ToArray(), }, CalledNumberOfTimes = 1 }; this.FakeManager.allUserRulesField.AddFirst(newRule); newRule.Rule.Apply(fakeObjectCall); } private static bool TryCreateFake(Type type, out object fake) { return FakeAndDummyManager.TryCreateFake(type, new ProxyOptions(), out fake); } private static object DefaultReturnValue(IInterceptedFakeObjectCall fakeObjectCall) { return DefaultReturnValueRule.ResolveReturnValue(fakeObjectCall); } } } }
namespace FakeItEasy.Core { using System; using System.Linq; /// <content>Auto fake property rule.</content> public partial class FakeManager { [Serializable] private class AutoFakePropertyRule : IFakeObjectCallRule { public FakeManager FakeManager { private get; set; } public int? NumberOfTimesToCall { get { return null; } } public bool IsApplicableTo(IFakeObjectCall fakeObjectCall) { Guard.AgainstNull(fakeObjectCall, "fakeObjectCall"); return PropertyBehaviorRule.IsPropertyGetter(fakeObjectCall.Method); } public void Apply(IInterceptedFakeObjectCall fakeObjectCall) { Guard.AgainstNull(fakeObjectCall, "fakeObjectCall"); var newRule = new CallRuleMetadata { Rule = new PropertyBehaviorRule(fakeObjectCall.Method, FakeManager) { Value = DefaultReturnValue(fakeObjectCall), Indices = fakeObjectCall.Arguments.ToArray(), }, CalledNumberOfTimes = 1 }; this.FakeManager.allUserRulesField.AddFirst(newRule); newRule.Rule.Apply(fakeObjectCall); } private static object DefaultReturnValue(IInterceptedFakeObjectCall fakeObjectCall) { return DefaultReturnValueRule.ResolveReturnValue(fakeObjectCall); } } } }
Add a simple debug query
using HotChocolate.Types; using System; using System.Collections.Generic; using System.Text; namespace Snowflake.Support.GraphQLFrameworkQueries.Queries.Debug { public class EchoQueries : ObjectTypeExtension { protected override void Configure(IObjectTypeDescriptor descriptor) { descriptor .Name("Query"); descriptor.Field("DEBUG__HelloWorld") .Resolver("Hello World"); } } }
Add keywords of the Print Schema Keywords v1.1
using System.Xml.Linq; namespace Kip { public static class Pskv11 { public static readonly XNamespace Namespace = "http://schemas.microsoft.com/windows/2013/05/printing/printschemakeywordsv11"; public static readonly XName JobPasscode = Namespace + "JobPasscode"; public static readonly XName JobPasscodeString = Namespace + "JobPasscodeString"; public static readonly XName JobImageFormat = Namespace + "JobImageFormat"; public static readonly XName Jpeg = Namespace + "Jpeg"; public static readonly XName PNG = Namespace + "PNG"; } }
Add class to avoid byte[] creation
using System.IO; using System.Runtime.InteropServices; namespace Diadoc.Api.Com { [ComVisible(true)] [Guid("AC96A3DD-E099-44CC-ABD5-11C303307159")] public interface IComBytes { byte[] Bytes { get; set; } void ReadFromFile(string path); void SaveToFile(string path); } [ComVisible(true)] [ProgId("Diadoc.Api.ComBytes")] [Guid("97D998E3-E603-4450-A027-EA774091BE72")] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(IComBytes))] public class ComBytes : SafeComObject, IComBytes { public byte[] Bytes { get; set; } public void ReadFromFile(string path) { Bytes = File.ReadAllBytes(path); } public void SaveToFile(string path) { if (Bytes != null) { File.WriteAllBytes(path, Bytes); } } } }
Add generation of KML file to maps menu
using FTAnalyzer.Utilities; using System; namespace FTAnalyzer.Mapping { static class GoogleAPIKey { static string APIkeyValue = string.Empty; public static string KeyValue { get { if (string.IsNullOrEmpty(APIkeyValue)) { try { if (string.IsNullOrEmpty(Properties.MappingSettings.Default.GoogleAPI)) APIkeyValue = "AIzaSyDJCForfeivoVF03Sr04rN9MMulO6KwA_M"; else { APIkeyValue = Properties.MappingSettings.Default.GoogleAPI; UIHelpers.ShowMessage("Using your private Google API Key.\nPlease observe monthly usage limits to avoid a large bill from Google."); } } catch (Exception) { APIkeyValue = "AIzaSyDJCForfeivoVF03Sr04rN9MMulO6KwA_M"; } } return APIkeyValue; } } } }
Move a small part of current
using System; using Umbraco.Core.Logging; namespace Umbraco.Core.Composing { /// <summary> /// Provides a static service locator for most singletons. /// </summary> /// <remarks> /// <para>This class is initialized with the container in UmbracoApplicationBase, /// right after the container is created in UmbracoApplicationBase.HandleApplicationStart.</para> /// <para>Obviously, this is a service locator, which some may consider an anti-pattern. And yet, /// practically, it works.</para> /// </remarks> public static class CurrentCore { private static IFactory _factory; private static ILogger _logger; private static IProfiler _profiler; private static IProfilingLogger _profilingLogger; /// <summary> /// Gets or sets the factory. /// </summary> public static IFactory Factory { get { if (_factory == null) throw new InvalidOperationException("No factory has been set."); return _factory; } set { if (_factory != null) throw new InvalidOperationException("A factory has already been set."); // if (_configs != null) throw new InvalidOperationException("Configs are unlocked."); _factory = value; } } internal static bool HasFactory => _factory != null; #region Getters public static ILogger Logger => _logger ?? (_logger = _factory?.TryGetInstance<ILogger>() ?? throw new Exception("TODO Fix")); //?? new DebugDiagnosticsLogger(new MessageTemplates())); public static IProfiler Profiler => _profiler ?? (_profiler = _factory?.TryGetInstance<IProfiler>() ?? new LogProfiler(Logger)); public static IProfilingLogger ProfilingLogger => _profilingLogger ?? (_profilingLogger = _factory?.TryGetInstance<IProfilingLogger>()) ?? new ProfilingLogger(Logger, Profiler); #endregion } }
Add model class for mod presets
// 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; namespace osu.Game.Rulesets.Mods { /// <summary> /// A mod preset is a named collection of configured mods. /// Presets are presented to the user in the mod select overlay for convenience. /// </summary> public class ModPreset { /// <summary> /// The ruleset that the preset is valid for. /// </summary> public RulesetInfo RulesetInfo { get; set; } = null!; /// <summary> /// The name of the mod preset. /// </summary> public string Name { get; set; } = string.Empty; /// <summary> /// The description of the mod preset. /// </summary> public string Description { get; set; } = string.Empty; /// <summary> /// The set of configured mods that are part of the preset. /// </summary> public ICollection<Mod> Mods { get; set; } = Array.Empty<Mod>(); } }
Add exception type for native call failures.
// --------------------------------------------------------------------------------------- // <copyright file="NativeCallException.cs" company=""> // Copyright © 2015 by Adam Hellberg and Brandon Scott. // // 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. // // Disclaimer: Colore is in no way affiliated with Razer and/or any of its employees // and/or licensors. Adam Hellberg and Brandon Scott do not take responsibility // for any harm caused, direct or indirect, to any Razer peripherals // via the use of Colore. // // "Razer" is a trademark of Razer USA Ltd. // </copyright> // --------------------------------------------------------------------------------------- namespace Colore.Razer { using System.ComponentModel; using System.Globalization; using System.Runtime.Serialization; public class NativeCallException : ColoreException { private readonly string _function; private readonly Result _result; public NativeCallException(string function, Result result) : base( string.Format( CultureInfo.InvariantCulture, "Call to native Chroma API function {0} failed with error: {1}", function, result), new Win32Exception(result)) { _function = function; _result = result; } protected NativeCallException(SerializationInfo info, StreamingContext context) : base(info, context) { } public string Function { get { return _function; } } public Result Result { get { return _result; } } } }
Add version helper to simplify creating a version list
using System; using System.Collections.Generic; using System.Linq; namespace KenticoInspector.Core.Helpers { public class VersionHelper { public static IList<Version> GetVersionList(params string[] versions) { return versions.Select(x => GetVersionFromShortString(x)).ToList(); } public static Version GetVersionFromShortString(string version) { var expandedVersionString = ExpandVersionString(version); return new Version(expandedVersionString); } public static string ExpandVersionString(string version) { var periodCount = version.Count(x => x == '.'); for (int i = 0; i < 2; i++) { version += ".0"; } return version; } } }
Add CreateGenericInstance Type extension method to help building models
using System; namespace Zbu.ModelsBuilder { public static class TypeExtensions { /// <summary> /// Creates a generic instance of a generic type with the proper actual type of an object. /// </summary> /// <param name="genericType">A generic type such as <c>Something{}</c></param> /// <param name="typeParmObj">An object whose type is used as generic type param.</param> /// <param name="ctorArgs">Arguments for the constructor.</param> /// <returns>A generic instance of the generic type with the proper type.</returns> /// <remarks>Usage... typeof (Something{}).CreateGenericInstance(object1, object2, object3) will return /// a Something{Type1} if object1.GetType() is Type1.</remarks> public static object CreateGenericInstance(this Type genericType, object typeParmObj, params object[] ctorArgs) { var type = genericType.MakeGenericType(typeParmObj.GetType()); return Activator.CreateInstance(type, ctorArgs); } } }
Add a base for web forms controls
namespace My.AspNetCore.WebForms.Controls { public abstract class Control { public string Id { get; set; } public string InnerHtml { get; protected set; } public abstract void Render(); } }
Add initial contract for message bus
using System; namespace Glimpse.Broker { public interface IMessageBus { IObservable<T> Listen<T>(); IObservable<T> ListenIncludeLatest<T>(); bool IsRegistered(Type type); } }
Add JWA enumeration for JWS Algorithms
using System.Runtime.Serialization; namespace THNETII.Security.JOSE { /// <summary> /// Defines the set of <c>"alg"</c> (algorithm) Header Parameter /// values defined by this specification for use with JWS. /// <para>Specified in <a href="https://tools.ietf.org/html/rfc7518#section-3.1">RFC 7518 - JSON Web Algorithms, Section 3.1: "alg" (Algorithm) Header Parameter Values for JWS</a>.</para> /// </summary> public enum JsonWebSignatureAlgorithm { Unknown = 0, /// <summary>HMAC using SHA-256</summary> [EnumMember] HS256, /// <summary>HMAC using SHA-384</summary> [EnumMember] HS384, /// <summary>HMAC using SHA-512</summary> [EnumMember] HS512, /// <summary> /// RSASSA-PKCS1-v1_5 using /// SHA-256 /// </summary> [EnumMember] RS256, /// <summary> /// RSASSA-PKCS1-v1_5 using /// SHA-384 /// </summary> [EnumMember] RS384, /// <summary> /// RSASSA-PKCS1-v1_5 using /// SHA-512 /// </summary> [EnumMember] RS512, /// <summary>ECDSA using P-256 and SHA-256</summary> [EnumMember] ES256, /// <summary>ECDSA using P-384 and SHA-384</summary> [EnumMember] ES384, /// <summary>ECDSA using P-521 and SHA-512</summary> [EnumMember] ES512, /// <summary> /// RSASSA-PSS using SHA-256 and /// MGF1 with SHA-256 /// </summary> [EnumMember] PS256, /// <summary> /// RSASSA-PSS using SHA-384 and /// MGF1 with SHA-384 /// </summary> [EnumMember] PS384, /// <summary> /// RSASSA-PSS using SHA-512 and /// MGF1 with SHA-512 /// </summary> [EnumMember] PS512, /// <summary> /// No digital signature or MAC /// performed /// </summary> [EnumMember(Value = "none")] None } }
Read and write a Trie
// Print a trie using System; using System.Collections.Generic; using System.Linq; using System.IO; class Node { private Dictionary<char, Node> Next = new Dictionary<char, Node>(); private bool IsWord; public static Node Read(List<String> items) { return items .Aggregate( new Node(), (acc, x) => { var root = acc; for (var i = 0 ; i < x.Length; i++) { if (!root.Next.ContainsKey(x[i])) { root.Next[x[i]] = new Node { IsWord = i == x.Length - 1 }; } root = root.Next[x[i]]; } return acc; }); } public static List<String> Write(Node node) { return node.Next.Keys.Count == 0 ? new [] { String.Empty }.ToList() : node.Next.Keys.SelectMany(x => Write(node.Next[x]).Select(y => String.Format("{0}{1}", x, y)).ToList()) .OrderBy(x => x) .ToList(); } } class Solution { static IEnumerable<String> GetWords(int n) { var r = new Random(); var lines = File.ReadAllLines("/usr/share/dict/words"); return Enumerable .Range(0, n) .Select(x => lines[r.Next(lines.Length)]); } static void Main() { var words = GetWords(100).OrderBy(x => x).ToList(); Console.WriteLine(String.Join(", ", words)); Console.WriteLine(String.Join(", ", Node.Write(Node.Read(words)))); if (!words.SequenceEqual(Node.Write(Node.Read(words)))) { Console.WriteLine("HAHAHA IDOIT!!!"); } } }
Add sendgeneric command to TestClient to allow one to send arbitrary GenericMessagePackets to the simulator for testing purposes
using System; using System.Collections.Generic; using System.Text; using OpenMetaverse; using OpenMetaverse.Packets; namespace OpenMetaverse.TestClient { /// <summary> /// Sends a packet of type GenericMessage to the simulator. /// </summary> public class GenericMessageCommand : Command { public GenericMessageCommand(TestClient testClient) { Name = "sendgeneric"; Description = "send a generic UDP message to the simulator."; Category = CommandCategory.Other; } public override string Execute(string[] args, UUID fromAgentID) { UUID target; if (args.Length < 1) return "Usage: sendgeneric method_name [value1 value2 ...]"; string methodName = args[0]; GenericMessagePacket gmp = new GenericMessagePacket(); gmp.AgentData.AgentID = Client.Self.AgentID; gmp.AgentData.SessionID = Client.Self.SessionID; gmp.AgentData.TransactionID = UUID.Zero; gmp.MethodData.Method = Utils.StringToBytes(methodName); gmp.MethodData.Invoice = UUID.Zero; gmp.ParamList = new GenericMessagePacket.ParamListBlock[args.Length - 1]; StringBuilder sb = new StringBuilder(); for (int i = 1; i < args.Length; i++) { GenericMessagePacket.ParamListBlock paramBlock = new GenericMessagePacket.ParamListBlock(); paramBlock.Parameter = Utils.StringToBytes(args[i]); gmp.ParamList[i - 1] = paramBlock; sb.AppendFormat(" {0}", args[i]); } Client.Network.SendPacket(gmp); return string.Format("Sent generic message with method {0}, params{1}", methodName, sb); } } }
Add failing tests for mapping of enum values
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using EntryPoint; using Xunit; namespace EntryPointTests { public class EnumArguments { [Fact] public void Enums_Int() { string[] args = new string[] { "--opt-1", "3" }; var options = EntryPointApi.Parse<EnumAppOptions>(args); Assert.StrictEqual(Enum1.item3, options.OptEnum1); } [Fact] public void Enums_Named() { string[] args = new string[] { "--opt-1", "item3" }; var options = EntryPointApi.Parse<EnumAppOptions>(args); Assert.StrictEqual(Enum1.item3, options.OptEnum1); } [Fact] public void Enums_Defaults() { string[] args = new string[] { }; var options = EntryPointApi.Parse<EnumAppOptions>(args); Assert.StrictEqual(default(Enum1), options.OptEnum1); Assert.StrictEqual(Enum1.item2, options.OptEnum2); } } class EnumAppOptions : BaseApplicationOptions { [OptionParameter( DoubleDashName = "opt-1")] public Enum1 OptEnum1 { get; set; } [OptionParameter( DoubleDashName = "opt-2", ParameterDefaultBehaviour = ParameterDefaultEnum.CustomValue, ParameterDefaultValue = Enum1.item2)] public Enum1 OptEnum2 { get; set; } } enum Enum1 { item1 = 1, item2 = 2, item3 = 3 } }
Remove duplicate exception clear similar link
@model StackExchange.Opserver.Views.Exceptions.ExceptionsModel @{ var e = Model.Exception; var log = Model.SelectedLog; var exceptions = Model.Errors; this.SetPageTitle(Model.Title); } @section head { <script> $(function () { Status.Exceptions.init({ log: '@log', id: '@e.GUID', enablePreviews: @(Current.Settings.Exceptions.EnablePreviews ? "true" : "false"), showingDeleted: true }); }); </script> } <div class="top-section error-bread-top"> <div class="error-header"> <a href="/exceptions">Exceptions</a> > <a href="/exceptions?log=@log.UrlEncode()">@e.ApplicationName</a> > <span class="error-title">@e.Message</span> @if (log.HasValue() && exceptions.Any(er => !er.IsProtected && !er.DeletionDate.HasValue) && Current.User.IsExceptionAdmin) { <span class="top-delete-link">(<a class="delete-link clear-all-link" href="/exceptions/delete-similar">Clear all visible</a>)</span> } </div> </div> <div class="bottom-section"> @Html.Partial("Exceptions.Table", Model) <div class="no-content@(exceptions.Any() ? " hidden" : "")">No similar exceptions in @Model.SelectedLog</div> </div>
@model StackExchange.Opserver.Views.Exceptions.ExceptionsModel @{ var e = Model.Exception; var log = Model.SelectedLog; var exceptions = Model.Errors; this.SetPageTitle(Model.Title); } @section head { <script> $(function () { Status.Exceptions.init({ log: '@log', id: '@e.GUID', enablePreviews: @(Current.Settings.Exceptions.EnablePreviews ? "true" : "false"), showingDeleted: true }); }); </script> } <div class="top-section error-bread-top"> <div class="error-header"> <a href="/exceptions">Exceptions</a> > <a href="/exceptions?log=@log.UrlEncode()">@e.ApplicationName</a> > <span class="error-title">@e.Message</span> </div> </div> <div class="bottom-section"> @Html.Partial("Exceptions.Table", Model) <div class="no-content@(exceptions.Any() ? " hidden" : "")">No similar exceptions in @Model.SelectedLog</div> </div>
Add class to hold snippets for the Period type
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NodaTime.Demo { class PeriodDemo { } }
Add - Attività Utente per la gestrione degli stati "InLavorazione" e "Prenotato"
using System; using System.Collections.Generic; using System.Text; namespace SO115App.Models.Classi.Soccorso { public class AttivitaUtente { public string Nominativo { get; set; } public DateTime DataInizioAttivita { get; set; } } }
Add simple ping controller to check functionality.
using A2BBAPI.Data; using A2BBAPI.Models; using A2BBCommon; using A2BBCommon.DTO; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using System; using System.Linq; using static A2BBAPI.Models.InOut; namespace A2BBAPI.Controllers { /// <summary> /// Controller user by HW granters to record in/out actions. /// </summary> [Produces("application/json")] [Route("api/ping")] [AllowAnonymous] public class PingController : Controller { #region Private fields /// <summary> /// The DB context. /// </summary> private readonly A2BBApiDbContext _dbContext; /// <summary> /// The logger. /// </summary> private readonly ILogger _logger; #endregion #region Public methods /// <summary> /// Create a new instance of this class. /// </summary> /// <param name="dbContext">The DI DB context.</param> /// <param name="loggerFactory">The DI logger factory.</param> public PingController(A2BBApiDbContext dbContext, ILoggerFactory loggerFactory) { _dbContext = dbContext; _logger = loggerFactory.CreateLogger<MeController>(); } /// <summary> /// Register in action. /// </summary> /// <param name="deviceId">The id of the device which performs this action.</param> /// <param name="subId">The subject id linked to the granter.</param> /// <returns><c>True</c> if ok, <c>false</c> otherwise.</returns> [HttpGet] public ResponseWrapper<bool> Ping() { return new ResponseWrapper<bool>(true, Constants.RestReturn.OK); } #endregion } }
Add enumeration of supported SqlClient versions.
/* Copyright 2021 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. */ namespace PSql; /// <summary> /// Supported SqlClient versions. /// </summary> public enum SqlClientVersion { /* Connection string history: MDS 1.0 - Authentication: AadPassword (all) - Authentication: AadIntegrated, AadInteractive (netfx) MDS 1.1 - Attestation Protocol - Enclave Attestation Url MDS 2.0: - Authentication: AadIntegrated, AadInteractive, AadServicePrincipal - Application Intent (was: ApplicationIntent) - Connect Retry Count (was: ConnectRetryCount) - Connect Retry Interval (was: ConnectRetryInterval) - Pool Blocking Period (was: PoolBlockingPeriod) - Multiple Active Result Sets (was: MultipleActiveResultSets) - Multi Subnet Failover (was: MultiSubnetFailover) - Transparent Network IP Resolution (was: TransparentNetworkIPResolution) - Trust Server Certificate (was: TrustServerCertificate) MDS 2.1 - Authentication: AadDeviceCodeFlow, AadManagedIdentity - Command Timeout MDS 3.0 - Authentication: AadDefault - The User ID connection property now requires a client id instead of an object id for user-assigned managed identity. MDS 4.0 - Encrypt: true by default - Authentication: AadIntegrated (allows User ID) - [REMOVED] Asynchronous Processing */ /// <summary> /// System.Data.SqlClient /// </summary> Legacy, /// <summary> /// Microsoft.Data.SqlClient 1.0.x /// </summary> Mds1, /// <summary> /// Microsoft.Data.SqlClient 1.1.x /// </summary> Mds1_1, /// <summary> /// Microsoft.Data.SqlClient 2.0.x /// </summary> Mds2, /// <summary> /// Microsoft.Data.SqlClient 2.1.x /// </summary> Mds2_1, /// <summary> /// Microsoft.Data.SqlClient 3.0.x /// </summary> Mds3, /// <summary> /// Microsoft.Data.SqlClient 4.0.x /// </summary> Mds4, }
Introduce a new ReleaseManager tool (populate-api-catalog)
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Google.Cloud.Tools.Common; using Newtonsoft.Json.Linq; using System; using System.IO; using System.Linq; namespace Google.Cloud.Tools.ReleaseManager { /// <summary> /// Tool to populate the API catalog (in google-cloud-dotnet) with values from the API index (in googleapis). /// This is only generally run when we add a new field to the API catalog, at which /// point this tool will need to change as well... but at least with it here, /// we don't need to rewrite the code every time. /// </summary> internal class PopulateApiCatalogCommand : CommandBase { public PopulateApiCatalogCommand() : base("populate-api-catalog", "Populates API catalog information from the API index. (You probably don't want this.)") { } protected override void ExecuteImpl(string[] args) { var catalog = ApiCatalog.Load(); var root = DirectoryLayout.DetermineRootDirectory(); var googleapis = Path.Combine(root, "googleapis"); var apiIndex = ApiIndex.V1.Index.LoadFromGoogleApis(googleapis); int modifiedCount = 0; foreach (var api in catalog.Apis) { var indexEntry = apiIndex.Apis.FirstOrDefault(x => x.DeriveCSharpNamespace() == api.Id); if (indexEntry is null) { continue; } // Change this line when introducing a new field... api.Json.Last.AddAfterSelf(new JProperty("serviceConfigFile", indexEntry.ConfigFile)); modifiedCount++; } Console.WriteLine($"Modified APIs: {modifiedCount}"); string json = catalog.FormatJson(); // Validate that we can still load it, before saving it to disk... ApiCatalog.FromJson(json); File.WriteAllText(ApiCatalog.CatalogPath, json); } } }
Add testable spectator streaming client
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using osu.Framework.Bindables; using osu.Framework.Utils; using osu.Game.Online; using osu.Game.Online.Spectator; using osu.Game.Replays.Legacy; using osu.Game.Scoring; namespace osu.Game.Tests.Visual.Spectator { public class TestSpectatorStreamingClient : SpectatorStreamingClient { public new BindableList<int> PlayingUsers => (BindableList<int>)base.PlayingUsers; private readonly HashSet<int> watchingUsers = new HashSet<int>(); private readonly Dictionary<int, int> userBeatmapDictionary = new Dictionary<int, int>(); private readonly Dictionary<int, bool> userSentStateDictionary = new Dictionary<int, bool>(); public TestSpectatorStreamingClient() : base(new DevelopmentEndpointConfiguration()) { } public void StartPlay(int userId, int beatmapId) { userBeatmapDictionary[userId] = beatmapId; sendState(userId, beatmapId); } public void EndPlay(int userId, int beatmapId) { ((ISpectatorClient)this).UserFinishedPlaying(userId, new SpectatorState { BeatmapID = beatmapId, RulesetID = 0, }); userSentStateDictionary[userId] = false; } public void SendFrames(int userId, int index, int count) { var frames = new List<LegacyReplayFrame>(); for (int i = index; i < index + count; i++) { var buttonState = i == index + count - 1 ? ReplayButtonState.None : ReplayButtonState.Left1; frames.Add(new LegacyReplayFrame(i * 100, RNG.Next(0, 512), RNG.Next(0, 512), buttonState)); } var bundle = new FrameDataBundle(new ScoreInfo(), frames); ((ISpectatorClient)this).UserSentFrames(userId, bundle); if (!userSentStateDictionary[userId]) sendState(userId, userBeatmapDictionary[userId]); } public override void WatchUser(int userId) { // When newly watching a user, the server sends the playing state immediately. if (!watchingUsers.Contains(userId) && PlayingUsers.Contains(userId)) sendState(userId, userBeatmapDictionary[userId]); base.WatchUser(userId); watchingUsers.Add(userId); } private void sendState(int userId, int beatmapId) { ((ISpectatorClient)this).UserBeganPlaying(userId, new SpectatorState { BeatmapID = beatmapId, RulesetID = 0, }); userSentStateDictionary[userId] = true; } } }
Add visual test for EdgeSnappingContainer
// 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 osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osuTK; using osuTK.Graphics; namespace osu.Framework.Tests.Visual.Containers { public class TestSceneEdgeSnappingContainer : FrameworkTestScene { public override IReadOnlyList<Type> RequiredTypes => new[] { typeof(EdgeSnappingContainer), typeof(SnapTargetContainer) }; public TestSceneEdgeSnappingContainer() { FillFlowContainer<SnapTestContainer> container; Child = container = new FillFlowContainer<SnapTestContainer> { Direction = FillDirection.Horizontal, Margin = new MarginPadding(20), Spacing = new Vector2(20), Children = new[] { new SnapTestContainer(Edges.Left), new SnapTestContainer(Edges.Left | Edges.Top), new SnapTestContainer(Edges.Top), new SnapTestContainer(Edges.Top | Edges.Right), new SnapTestContainer(Edges.Right), new SnapTestContainer(Edges.Bottom | Edges.Right), new SnapTestContainer(Edges.Bottom), new SnapTestContainer(Edges.Bottom | Edges.Left), } }; foreach (var child in container.Children) addBoxAssert(child); } private void addBoxAssert(SnapTestContainer container) { bool leftSnapped = container.EdgeSnappingContainer.SnappedEdges.HasFlag(Edges.Left); bool topSnapped = container.EdgeSnappingContainer.SnappedEdges.HasFlag(Edges.Top); bool rightSnapped = container.EdgeSnappingContainer.SnappedEdges.HasFlag(Edges.Right); bool bottomSnapped = container.EdgeSnappingContainer.SnappedEdges.HasFlag(Edges.Bottom); AddAssert($"\"{container.Name}\" snaps correctly", () => leftSnapped == container.EdgeSnappingContainer.Padding.Left < 0 && topSnapped == container.EdgeSnappingContainer.Padding.Top < 0 && rightSnapped == container.EdgeSnappingContainer.Padding.Right < 0 && bottomSnapped == container.EdgeSnappingContainer.Padding.Bottom < 0); } private class SnapTestContainer : SnapTargetContainer { internal readonly EdgeSnappingContainer EdgeSnappingContainer; public SnapTestContainer(Edges snappedEdges) { const float inset = 10f; Name = snappedEdges.ToString(); Size = new Vector2(50); Children = new Drawable[] { new Box { Colour = Color4.Blue, RelativeSizeAxes = Axes.Both, }, EdgeSnappingContainer = new EdgeSnappingContainer { SnappedEdges = snappedEdges, Position = new Vector2(inset), Size = Size - new Vector2(inset * 2), Child = new Box { Colour = Color4.Green, RelativeSizeAxes = Axes.Both } } }; } } } }
Add unit tests for TestId
using System.Collections.Generic; using System.Linq; using Arkivverket.Arkade.Core.Util; using FluentAssertions; using Xunit; namespace Arkivverket.Arkade.CoreTests.Util { public class TestIdTests { [Fact] public void ToStringTest() { var testId = new TestId(TestId.TestKind.Noark5, 15); testId.ToString().Should().Be("N5.15"); } [Fact] public void CompareToTest() { var testId16 = new TestId(TestId.TestKind.Noark5, 16); var testId15 = new TestId(TestId.TestKind.Noark5, 15); var testIds = new List<TestId> { testId16, testId15 }; testIds.Sort(); testIds.First().Should().Be(testId15); } [Fact] public void EqualsTest() { var testIdA = new TestId(TestId.TestKind.Noark5, 15); var testIdB = new TestId(TestId.TestKind.Noark5, 15); testIdA.Should().BeEquivalentTo(testIdB); } } }
Add missing file to repository
// *********************************************************************** // Copyright (c) 2010 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. // *********************************************************************** using System; namespace NUnit.Framework.Api { public interface ISetRunState { RunState GetRunState(); string GetReason(); } }
Fix missing files for release 3.7.4.2704
namespace Patagames.Pdf.Net.Controls.Wpf { /// <summary> /// Represents the scaling options of the page for printing /// </summary> public enum PrintSizeMode { /// <summary> /// Fit page /// </summary> Fit, /// <summary> /// Actual size /// </summary> ActualSize, /// <summary> /// Custom scale /// </summary> CustomScale } }
Disable test parallelization in Marten.Testing
using Xunit; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: CollectionBehavior(DisableTestParallelization = true)]
Optimize coins management with CoinRegistry
using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using NBitcoin; using WalletWasabi.Models; namespace WalletWasabi.Gui.Models { public class CoinsRegistry { private HashSet<SmartCoin> _coins; private object _lock; public event NotifyCollectionChangedEventHandler CollectionChanged; public CoinsRegistry() { _coins = new HashSet<SmartCoin>(); _lock = new object(); } public CoinsView AsCoinsView() { return new CoinsView(_coins); } public bool IsEmpty => !_coins.Any(); public SmartCoin GetByOutPoint(OutPoint outpoint) { return _coins.FirstOrDefault(x => x.GetOutPoint() == outpoint); } public bool TryAdd(SmartCoin coin) { var added = false; lock (_lock) { added = _coins.Add(coin); } if( added ) { CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, coin)); } return added; } public void Remove(SmartCoin coin) { var coinsToRemove = AsCoinsView().DescendatOf(coin).ToList(); coinsToRemove.Add(coin); lock (_lock) { foreach(var toRemove in coinsToRemove) { _coins.Remove(coin); } } CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, coinsToRemove)); } public void Clear() { lock (_lock) { _coins.Clear(); } CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); } } }
Add tests to cover TestSuite.Copy
using NUnit.Framework.Api; using NUnit.TestData.OneTimeSetUpTearDownData; using NUnit.TestData.TestFixtureSourceData; using NUnit.TestUtilities; namespace NUnit.Framework.Internal { // Tests that Copy is properly overridden for all types extending TestSuite - #3171 public class TestSuiteCopyTests { [Test] public void CopyTestSuiteReturnsCorrectType() { TestSuite testSuite = new TestSuite(new TypeWrapper(typeof(NUnit.TestData.ParameterizedTestFixture))); var copiedTestSuite = testSuite.Copy(TestFilter.Empty); Assert.AreEqual(copiedTestSuite.GetType(), typeof(TestSuite)); } [Test] public void CopyParameterizedTestFixtureReturnsCorrectType() { TestSuite parameterizedTestFixture = new ParameterizedFixtureSuite(new TypeWrapper(typeof(NUnit.TestData.ParameterizedTestFixture))); var copiedParameterizedTestFixture = parameterizedTestFixture.Copy(TestFilter.Empty); Assert.AreEqual(copiedParameterizedTestFixture.GetType(), typeof(ParameterizedFixtureSuite)); } [Test] public void CopyParameterizedMethodSuiteReturnsCorrectType() { TestSuite parameterizedMethodSuite = new ParameterizedMethodSuite(new MethodWrapper( typeof(NUnit.TestData.ParameterizedTestFixture), nameof(NUnit.TestData.ParameterizedTestFixture.MethodWithParams))); var copiedparameterizedMethodSuite = parameterizedMethodSuite.Copy(TestFilter.Empty); Assert.AreEqual(copiedparameterizedMethodSuite.GetType(), typeof(ParameterizedMethodSuite)); } [Test] public void CopyTestFixtureReturnsCorrectType() { TestSuite testFixture = TestBuilder.MakeFixture(typeof(FixtureWithNoTests)); var copiedTestFixture = testFixture.Copy(TestFilter.Empty); Assert.AreEqual(copiedTestFixture.GetType(), typeof(TestFixture)); } [Test] public void CopySetUpFixtureReturnsCorrectType() { TestSuite setUpFixture = new SetUpFixture( new TypeWrapper(typeof(NUnit.TestData.SetupFixture.Namespace1.NUnitNamespaceSetUpFixture1))); var copiedSetupFixture = setUpFixture.Copy(TestFilter.Empty); Assert.AreEqual(copiedSetupFixture.GetType(), typeof(SetUpFixture)); } [Test] public void CopyTestAssemblyReturnsCorrectType() { var runner = new NUnitTestAssemblyRunner(new DefaultTestAssemblyBuilder()); TestSuite assembly = new TestAssembly(AssemblyHelper.Load("mock-assembly.dll"), "mock-assembly"); var copiedAssembly = assembly.Copy(TestFilter.Empty); Assert.AreEqual(copiedAssembly.GetType(), typeof(TestAssembly)); } } }
Create Test that dapper works wil Session
using System.Collections.Generic; using System.Linq; using Dapper; using FakeItEasy; using NUnit.Framework; using Smooth.IoC.Dapper.FastCRUD.Repository.UnitOfWork.Tests.TestHelpers; using Smooth.IoC.Dapper.Repository.UnitOfWork.Data; namespace Smooth.IoC.Dapper.FastCRUD.Repository.UnitOfWork.Tests.ExampleTests { [TestFixture] public class RepositoryQueryTests : CommonTestDataSetup { [Test, Category("Integration")] public static void Query_Returns_DataFromBrave() { IEnumerable<Brave> results = null; Assert.DoesNotThrow(()=> results = Connection.Query<Brave>("Select * FROM Braves")); Assert.That(results, Is.Not.Null); Assert.That(results, Is.Not.Empty); Assert.That(results.Count(), Is.EqualTo(3)); } } }
Add Win32 functionality to get foreground process
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace Articulate { /// <summary> /// Gets information about the currently active window /// </summary> public static class ForegroundProcess { [DllImport("user32.dll", SetLastError = true)] static extern uint GetWindowThreadProcessId(IntPtr hWnd, out IntPtr lpdwProcessId); [DllImport("user32.dll")] static extern IntPtr GetForegroundWindow(); /// <summary> /// Gets the Full Path to the current foreground window's executable file /// </summary> public static string FullPath { get { IntPtr processID; GetWindowThreadProcessId(GetForegroundWindow(), out processID); Process p = Process.GetProcessById((int)processID); return p.MainModule.FileName; } } /// <summary> /// Gets the executable's filename without extension /// </summary> public static string ExecutableName { get { return Path.GetFileNameWithoutExtension(FullPath); } } } }
Add an xUnit test discoverer that ignores tests when run on AppVeyor
namespace Respawn.DatabaseTests { using System; using System.Collections.Generic; using System.Linq; using Xunit; using Xunit.Abstractions; using Xunit.Sdk; public class SkipOnAppVeyorTestDiscoverer : IXunitTestCaseDiscoverer { private readonly IMessageSink _diagnosticMessageSink; public SkipOnAppVeyorTestDiscoverer(IMessageSink diagnosticMessageSink) { _diagnosticMessageSink = diagnosticMessageSink; } public IEnumerable<IXunitTestCase> Discover(ITestFrameworkDiscoveryOptions discoveryOptions, ITestMethod testMethod, IAttributeInfo factAttribute) { if (Environment.GetEnvironmentVariable("Appveyor")?.ToUpperInvariant() == "TRUE") { return Enumerable.Empty<IXunitTestCase>(); } return new[] { new XunitTestCase(_diagnosticMessageSink, discoveryOptions.MethodDisplayOrDefault(), testMethod) }; } } [XunitTestCaseDiscoverer("Respawn.DatabaseTests.SkipOnAppVeyorTestDiscoverer", "Respawn.DatabaseTests")] public class SkipOnAppVeyorAttribute : FactAttribute { } }
Change DropDownButton, Change Sepparotor name on Menu, Logout if unsuccessful ping Part VII
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using Gtk; namespace Moscrif.IDE.Components { class DropDownRadioButton: DropDownButton { public DropDownRadioButton() { } protected override void OnPressed () { //base.OnPressed (); Gtk.Menu menu = new Gtk.Menu (); if (menu.Children.Length > 0) { Gtk.SeparatorMenuItem sep = new Gtk.SeparatorMenuItem (); sep.Show (); menu.Insert (sep, -1); } Gtk.RadioMenuItem grp = new Gtk.RadioMenuItem (""); foreach (ComboItem ci in items) { Gtk.RadioMenuItem mi = new Gtk.RadioMenuItem (grp, ci.Label.Replace ("_","__")); if (ci.Item == items.CurrentItem || ci.Item.Equals (items.CurrentItem)) mi.Active = true; ComboItemSet isetLocal = items; ComboItem ciLocal = ci; mi.Activated += delegate { SelectItem (isetLocal, ciLocal); }; mi.ShowAll (); menu.Insert (mi, -1); } menu.Popup (null, null, PositionFunc, 0, Gtk.Global.CurrentEventTime); } } }
Allow running gzip-ped script from URL
using System; using System.IO; using System.Net.Http; using System.Net.Mime; using System.Threading.Tasks; namespace Dotnet.Script.Core { public class ScriptDownloader { public async Task<string> Download(string uri) { const string plainTextMediaType = "text/plain"; using (HttpClient client = new HttpClient()) { using (HttpResponseMessage response = await client.GetAsync(uri)) { response.EnsureSuccessStatusCode(); using (HttpContent content = response.Content) { string mediaType = content.Headers.ContentType.MediaType; if (string.IsNullOrWhiteSpace(mediaType) || mediaType.Equals(plainTextMediaType, StringComparison.InvariantCultureIgnoreCase)) { return await content.ReadAsStringAsync(); } throw new NotSupportedException($"The media type '{mediaType}' is not supported when executing a script over http/https"); } } } } } }
using System; using System.IO; using System.IO.Compression; using System.Net.Http; using System.Threading.Tasks; namespace Dotnet.Script.Core { public class ScriptDownloader { public async Task<string> Download(string uri) { using (HttpClient client = new HttpClient()) { using (HttpResponseMessage response = await client.GetAsync(uri)) { response.EnsureSuccessStatusCode(); using (HttpContent content = response.Content) { var mediaType = content.Headers.ContentType.MediaType?.ToLowerInvariant().Trim(); switch (mediaType) { case null: case "": case "text/plain": return await content.ReadAsStringAsync(); case "application/gzip": case "application/x-gzip": using (var stream = await content.ReadAsStreamAsync()) using (var gzip = new GZipStream(stream, CompressionMode.Decompress)) using (var reader = new StreamReader(gzip)) return await reader.ReadToEndAsync(); default: throw new NotSupportedException($"The media type '{mediaType}' is not supported when executing a script over http/https"); } } } } } } }
Add missed paren in comment.
using System; using System.Threading; namespace ProcessTest_ConsoleApp { class Program { static int Main(string[] args) { try { if (args.Length > 0) { if (args[0].Equals("infinite")) { // To avoid potential issues with orphaned processes (say, the test exits before // exiting the process, we'll say "infinite" is actually 30 seconds. Console.WriteLine("ProcessTest_ConsoleApp.exe started with an endless loop"); Thread.Sleep(30 * 1000); } if (args[0].Equals("error")) { Exception ex = new Exception("Intentional Exception thrown"); throw ex; } if (args[0].Equals("input")) { string str = Console.ReadLine(); } } else { Console.WriteLine("ProcessTest_ConsoleApp.exe started"); Console.WriteLine("ProcessTest_ConsoleApp.exe closed"); } return 100; } catch (Exception toLog) { // We're testing STDERR streams, not the JIT debugger. // This makes the process behave just like a crashing .NET app, but without the WER invocation // nor the blocking dialog that comes with it, or the need to suppress that. Console.Error.WriteLine(string.Format("Unhandled Exception: {0}", toLog.ToString())); return 1; } } } }
using System; using System.Threading; namespace ProcessTest_ConsoleApp { class Program { static int Main(string[] args) { try { if (args.Length > 0) { if (args[0].Equals("infinite")) { // To avoid potential issues with orphaned processes (say, the test exits before // exiting the process), we'll say "infinite" is actually 30 seconds. Console.WriteLine("ProcessTest_ConsoleApp.exe started with an endless loop"); Thread.Sleep(30 * 1000); } if (args[0].Equals("error")) { Exception ex = new Exception("Intentional Exception thrown"); throw ex; } if (args[0].Equals("input")) { string str = Console.ReadLine(); } } else { Console.WriteLine("ProcessTest_ConsoleApp.exe started"); Console.WriteLine("ProcessTest_ConsoleApp.exe closed"); } return 100; } catch (Exception toLog) { // We're testing STDERR streams, not the JIT debugger. // This makes the process behave just like a crashing .NET app, but without the WER invocation // nor the blocking dialog that comes with it, or the need to suppress that. Console.Error.WriteLine(string.Format("Unhandled Exception: {0}", toLog.ToString())); return 1; } } } }
Set specs on all tiles at Awake()
using UnityEngine; using UnityEngine.Assertions; public class TileSystemManager : BaseBehaviour { private Shader shader; void Start() { shader = Shader.Find("Sprites/Diffuse"); Assert.IsNotNull(shader); SetChunksToStatic(); DisableShadows(); } void SetChunksToStatic() { foreach (Transform child in transform) child.gameObject.isStatic = true; } void DisableShadows() { MeshRenderer[] allChildren = GetComponentsInChildren<MeshRenderer>(); Assert.IsNotNull(allChildren); foreach (MeshRenderer child in allChildren) { child.sharedMaterial.shader = shader; child.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off; child.receiveShadows = false; child.lightProbeUsage = 0; child.reflectionProbeUsage = 0; if (debug_TileMapDisabled) child.enabled = false; } } }
Add TLS token binding feature
// 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; using Microsoft.Framework.Runtime; namespace Microsoft.AspNet.Http.Interfaces { /// <summary> /// Provides information regarding TLS token binding parameters. /// </summary> /// <remarks> /// TLS token bindings help mitigate the risk of impersonation by an attacker in the /// event an authenticated client's bearer tokens are somehow exfiltrated from the /// client's machine. See https://datatracker.ietf.org/doc/draft-popov-token-binding/ /// for more information. /// </remarks> [AssemblyNeutral] public interface ITlsTokenBindingFeature { /// <summary> /// Gets the 'provided' token binding identifier associated with the request. /// </summary> /// <returns>The token binding identifier, or null if the client did not /// supply a 'provided' token binding or valid proof of possession of the /// associated private key. The caller should treat this identifier as an /// opaque blob and should not try to parse it.</returns> byte[] GetProvidedTokenBindingId(); /// <summary> /// Gets the 'referred' token binding identifier associated with the request. /// </summary> /// <returns>The token binding identifier, or null if the client did not /// supply a 'referred' token binding or valid proof of possession of the /// associated private key. The caller should treat this identifier as an /// opaque blob and should not try to parse it.</returns> byte[] GetReferredTokenBindingId(); } }
Add items for database persistence
namespace food_tracker { public class NutritionItem { public string name { get; set; } public double calories { get; set; } public double carbohydrates { get; set; } public double sugars { get; set; } public double fats { get; set; } public double saturatedFats { get; set; } public double protein { get; set; } public double salt { get; set; } public double fibre { get; set; } public NutritionItem(string name, double calories, double carbohydrates, double sugars, double fats, double satFat, double protein, double salt, double fibre) { this.name = name; this.calories = calories; this.carbohydrates = carbohydrates; this.sugars = sugars; this.fats = fats; this.saturatedFats = satFat; this.protein = protein; this.salt = salt; this.fibre = fibre; } } }
Add a abstract server class. Watch out for the todos.
/* * WoWCore - World of Warcraft 1.12 Server * Copyright (C) 2017 exceptionptr * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ using System; using System.Net; using System.Net.Sockets; namespace WoWCore.Common.Network { public abstract class Server { private string _listenerIp; private TcpListener _listener; private Func<string, bool> _clientConnected; private Func<string, bool> _clientDisconnected; private Func<string, byte[], bool> _messageReceived; /// <summary> /// Initialize the TCP server. /// </summary> /// <param name="listenerIp"></param> /// <param name="listenerPort"></param> /// <param name="clientConnected"></param> /// <param name="clientDisconnected"></param> /// <param name="messageReceived"></param> protected Server(string listenerIp, int listenerPort, Func<string, bool> clientConnected, Func<string, bool> clientDisconnected, Func<string, byte[], bool> messageReceived) { IPAddress listenerIpAddress; if (listenerPort < 1) throw new ArgumentOutOfRangeException(nameof(listenerPort)); _clientConnected = clientConnected; _clientDisconnected = clientDisconnected; _messageReceived = messageReceived ?? throw new ArgumentNullException(nameof(messageReceived)); if (string.IsNullOrEmpty(listenerIp)) { listenerIpAddress = IPAddress.Any; _listenerIp = listenerIpAddress.ToString(); } else { listenerIpAddress = IPAddress.Parse(listenerIp); _listenerIp = listenerIp; } _listener = new TcpListener(listenerIpAddress, listenerPort); } // TODO: Task AcceptConnections(), Task DataReceiver(), MessageReadAsync(), MessageWriteAsync etc. } }
Add assembly info for new project
// 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.Reflection; using System.Resources; [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: NeutralResourcesLanguage("en-us")]
Implement CartSpecs to Control Specification
using WJStore.Domain.Interfaces.Validation; namespace WJStore.Domain.Entities.Specifications.CartSpecs { public class CartCountShouldBeGreaterThanZeroSpec : ISpecification<Cart> { public bool IsSatisfiedBy(Cart cart) { return cart.Count > 0; } } }
Use the correct icon for osu!direct in the toolbar
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Allocation; using osu.Game.Graphics; namespace osu.Game.Overlays.Toolbar { internal class ToolbarDirectButton : ToolbarOverlayToggleButton { public ToolbarDirectButton() { SetIcon(FontAwesome.fa_download); } [BackgroundDependencyLoader] private void load(DirectOverlay direct) { StateContainer = direct; } } }
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Allocation; using osu.Game.Graphics; namespace osu.Game.Overlays.Toolbar { internal class ToolbarDirectButton : ToolbarOverlayToggleButton { public ToolbarDirectButton() { SetIcon(FontAwesome.fa_osu_chevron_down_o); } [BackgroundDependencyLoader] private void load(DirectOverlay direct) { StateContainer = direct; } } }
Add test fixture for secret splitting
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NUnit.Framework; namespace ElectronicCash.Tests { [TestFixture] class SecretSplittingTests { private static readonly byte[] _message = Helpers.GetBytes("Supersecretmessage"); private static readonly byte[] _randBytes = Helpers.GetRandomBytes(Helpers.GetString(_message).Length * sizeof(char)); private readonly SecretSplittingProvider _splitter = new SecretSplittingProvider(_message, _randBytes); [Test] public void OnSplit_OriginalMessageShouldBeRecoverable() { _splitter.SplitSecretBetweenTwoPeople(); var r = _splitter.R; var s = _splitter.S; var m = Helpers.ExclusiveOr(r, s); Assert.AreEqual(Helpers.GetString(m), Helpers.GetString(_message)); } } }
Add a logging effect to debug
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SmokeScreen { [EffectDefinition("DEBUG_EFFECT")] class DebugEffect : EffectBehaviour { public override void OnEvent() { Print(effectName.PadRight(16) + "OnEvent single -------------------------------------------------------"); } private float lastPower = -1; public override void OnEvent(float power) { if (Math.Abs(lastPower - power) > 0.01f) { lastPower = power; Print(effectName.PadRight(16) + " " + instanceName + "OnEvent pow = " + power.ToString("F2")); } } public override void OnInitialize() { Print("OnInitialize"); } public override void OnLoad(ConfigNode node) { Print("OnLoad"); } public override void OnSave(ConfigNode node) { Print("OnSave"); } private static void Print(String s) { print("[SmokeScreen DebugEffect] " + s); } } }
Implement test for client login.
using Microsoft.VisualStudio.TestTools.UnitTesting; using Moegirlpedia.MediaWikiInterop.Actions; using Moegirlpedia.MediaWikiInterop.Actions.Models; using Moegirlpedia.MediaWikiInterop.Actions.QueryProviders; using Moegirlpedia.MediaWikiInterop.Primitives.DependencyInjection; using System; using System.Threading.Tasks; namespace ActionLibraryTest.Actions { [TestClass] public class ClientLoginTest { private const string ApiEndpoint = "https://zh.moegirl.org/api.php"; [TestMethod] public async Task TestClientLogin() { var apiFactory = ApiConnectionFactory.CreateConnection(ApiEndpoint); using (var apiConnection = apiFactory.CreateConnection()) using (var session = apiConnection.CreateSession()) { // First, token var queryResponse = await apiConnection.CreateAction<QueryAction>().RunActionAsync(config => { config.AddQueryProvider(new TokenQueryProvider { Types = TokenQueryProvider.TokenTypes.Login }); }, session); var tokenResponse = queryResponse.GetQueryTypedResponse<Tokens>(); Assert.IsNotNull(tokenResponse?.Response?.LoginToken); // Then, login var loginResponse = await apiConnection.CreateAction<ClientLoginAction>().RunActionAsync(config => { config.LoginToken = tokenResponse.Response.LoginToken; config.ReturnUrl = "https://zh.moegirl.org/Mainpage"; config.AddCredential("username", Environment.GetEnvironmentVariable("UT_USERNAME")); config.AddCredential("password", Environment.GetEnvironmentVariable("UT_PASSWORD")); }, session); Assert.AreEqual(ClientLoginResponse.AuthManagerLoginResult.Pass, loginResponse.Status, loginResponse.Message); } } } }
Add a script for check if we are a tank.
switch (ObjectManager.Me.WowSpecialization()) { case WoWSpecialization.PaladinProtection: case WoWSpecialization.WarriorProtection: case WoWSpecialization.MonkBrewmaster: case WoWSpecialization.DruidGuardian: case WoWSpecialization.DeathknightBlood: return true; default: return false; } // Usage: <ScriptCondition>=IsTankScript.cs</ScriptCondition>
Add date time passing practices.
using System; using System.Collections.Generic; using System.Globalization; using Xunit; namespace CSharpViaTest.OtherBCLs.HandleDates { /* * Description * =========== * * This test will try passing date time between the boundary (e.g. via HTTP). * And the culture information at each site is different. You have to pass * the date time accurately. * * Difficulty: Super Easy * * Knowledge Point * =============== * * - DateTime.ParseExtact / DateTime.Parse * - DateTime.ToString(string, IFormatProvider) */ public class PassingDateTimeBetweenDifferentCultures { class CultureContext : IDisposable { readonly CultureInfo old; public CultureContext(CultureInfo culture) { old = CultureInfo.CurrentCulture; CultureInfo.CurrentCulture = culture; } public void Dispose() { CultureInfo.CurrentCulture = old; } } #region Please modifies the code to pass the test static DateTime DeserializeDateTimeFromTargetSite(string serialized) { throw new NotImplementedException(); } static string SerializeDateTimeFromCallerSite(DateTime dateTime) { throw new NotImplementedException(); } #endregion [Theory] [MemberData(nameof(GetDateTimeForDifferentCultures))] public void should_pass_date_time_correctly_between_different_cultures( DateTime expected, CultureInfo from, CultureInfo to) { string serialized; using (new CultureContext(from)) { serialized = SerializeDateTimeFromCallerSite(expected); } using (new CultureContext(to)) { DateTime deserialized = DeserializeDateTimeFromTargetSite(serialized); Assert.Equal(expected.ToUniversalTime(), deserialized.ToUniversalTime()); } } static IEnumerable<object[]> GetDateTimeForDifferentCultures() { return new[] { new object[] {new DateTime(2012, 8, 1, 0, 0, 0, DateTimeKind.Utc), new CultureInfo("zh-CN"), new CultureInfo("tr-TR")}, new object[] {new DateTime(2012, 8, 1, 0, 0, 0, DateTimeKind.Utc), new CultureInfo("ja-JP"), new CultureInfo("en-US")} }; } } }
Add script for serializing level data
using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System; using UnityEngine; public class LevelData : BaseBehaviour { public int HP { get; set; } public int AC { get; set; } public int Damage { get; set; } public void Save() { var bf = new BinaryFormatter(); FileStream file = File.Create(Application.persistentDataPath + "/LevelData.dat"); var container = new LevelDataContainer(); container.hp = HP; container.ac = AC; container.damage = Damage; bf.Serialize(file, container); file.Close(); } public void Load() { if (File.Exists(Application.persistentDataPath + "/LevelData.dat")) { var bf = new BinaryFormatter(); FileStream file = File.Open(Application.persistentDataPath + "/LevelData.dat",FileMode.Open); var container = (LevelDataContainer)bf.Deserialize(file); file.Close(); HP = container.hp; AC = container.ac; Damage = container.damage; } } void OnSaveLevelData(bool status) { Save(); } void OnLoadLevelData(bool status) { Load(); } void OnEnable() { EventKit.Subscribe<bool>("save level data", OnSaveLevelData); EventKit.Subscribe<bool>("load level data", OnLoadLevelData); } void OnDestroy() { EventKit.Unsubscribe<bool>("save level data", OnSaveLevelData); EventKit.Unsubscribe<bool>("load level data", OnLoadLevelData); } } [Serializable] class LevelDataContainer { public int hp; public int ac; public int damage; }
Split model class for mod state
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Bindables; using osu.Game.Rulesets.Mods; namespace osu.Game.Overlays.Mods { /// <summary> /// Wrapper class used to store the current state of a mod shown on the <see cref="ModSelectOverlay"/>. /// Used primarily to decouple data from drawable logic. /// </summary> public class ModState { /// <summary> /// The mod that whose state this instance describes. /// </summary> public Mod Mod { get; } /// <summary> /// Whether the mod is currently selected. /// </summary> public BindableBool Active { get; } = new BindableBool(); /// <summary> /// Whether the mod is currently filtered out due to not matching imposed criteria. /// </summary> public BindableBool Filtered { get; } = new BindableBool(); public ModState(Mod mod) { Mod = mod; } } }
Add IProvideExpenditure class to support data provision
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using GeneralUseClasses.Contracts; namespace GeneralUseClasses.Services { public interface IProvideExpenditureData { IEnumerable<string> GetDominantTags(); IEnumerable<string> GetAssociatedTags(); IEnumerable<string> GetPeople(); } }
Add tagging capability to Dinamico news page
@model Dinamico.Models.ContentPage @{ Content.Define(re => { re.Title = "News page"; re.IconUrl = "{IconsUrl}/newspaper.png"; re.DefaultValue("Visible", false); re.RestrictParents("Container"); re.Sort(N2.Definitions.SortBy.PublishedDescending); }); } @Html.Partial("LayoutPartials/BlogContent") @using (Content.BeginScope(Content.Traverse.Parent())) { @Content.Render.Tokens("NewsFooter") }
@model Dinamico.Models.ContentPage @{ Content.Define(re => { re.Title = "News page"; re.IconUrl = "{IconsUrl}/newspaper.png"; re.DefaultValue("Visible", false); re.RestrictParents("Container"); re.Sort(N2.Definitions.SortBy.PublishedDescending); re.Tags("Tags"); }); } @Html.Partial("LayoutPartials/BlogContent") @using (Content.BeginScope(Content.Traverse.Parent())) { @Content.Render.Tokens("NewsFooter") }
Hide logout when not using forms auth
 namespace N2.Management { public partial class Top : System.Web.UI.MasterPage { } }
using System.Configuration; using System.Web.Configuration; namespace N2.Management { public partial class Top : System.Web.UI.MasterPage { protected override void OnLoad(System.EventArgs e) { base.OnLoad(e); try { var section = (AuthenticationSection)ConfigurationManager.GetSection("system.web/authentication"); logout.Visible = section.Mode == AuthenticationMode.Forms; } catch (System.Exception) { } } } }
Add a factory for Property path element
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace Pather.CSharp.PathElements { public class PropertyFactory : IPathElementFactory { public IPathElement Create(string pathElement) { return new Property(pathElement); } public bool IsApplicable(string pathElement) { return Regex.IsMatch(pathElement, @"\w+"); } } }
Add Rect <-> Vector2i collisions
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using neon2d.Math; namespace neon2d.Physics { public class Rect { public float x, y; public float width, height; public Rect(int x, int y, int width, int height) { this.x = x; this.y = y; this.width = width; this.height = height; } public bool intersects(Rect other) { return this.x + this.width > other.x && this.x < other.x + other.width && this.y + this.height > other.y && this.y < other.y + other.height; } } public class Circle { public float centerX, centerY; public float radius; public Circle(int centerX, int centerY, int radius) { this.centerX = centerX; this.centerY = centerY; this.radius = radius; } public Circle(Vector2i centerPoint, int radius) { this.centerX = centerPoint.x; this.centerY = centerPoint.y; this.radius = radius; } public bool intersects(Vector2i other) { return other.x >= centerX - radius && other.x <= centerX + radius && other.y >= centerY - radius && other.y <= centerY + radius; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using neon2d.Math; namespace neon2d.Physics { public class Rect { public float x, y; public float width, height; public Rect(int x, int y, int width, int height) { this.x = x; this.y = y; this.width = width; this.height = height; } public bool intersects(Rect other) { return this.x + this.width > other.x && this.x < other.x + other.width && this.y + this.height > other.y && this.y < other.y + other.height; } public bool intersects(Vector2i other) { return other.x > this.x && other.x < this.x + width && other.y > this.y && other.y < this.y; } } public class Circle { public float centerX, centerY; public float radius; public Circle(int centerX, int centerY, int radius) { this.centerX = centerX; this.centerY = centerY; this.radius = radius; } public Circle(Vector2i centerPoint, int radius) { this.centerX = centerPoint.x; this.centerY = centerPoint.y; this.radius = radius; } public bool intersects(Vector2i other) { return other.x >= centerX - radius && other.x <= centerX + radius && other.y >= centerY - radius && other.y <= centerY + radius; } } }
Add extension method to provide drawable adjustments
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; namespace osu.Framework.Graphics { /// <summary> /// Holds extension methods for <see cref="Drawable"/>. /// </summary> public static class DrawableExtensions { /// <summary> /// Adjusts specified properties of a <see cref="Drawable"/>. /// </summary> /// <param name="drawable">The <see cref="Drawable"/> whose properties should be adjusted.</param> /// <param name="adjustment">The adjustment function.</param> /// <returns>The given <see cref="Drawable"/>.</returns> public static T With<T>(this T drawable, Action<T> adjustment) where T : Drawable { adjustment?.Invoke(drawable); return drawable; } } }
Fix warnings in unit tests flagged by MSBuild Log
 // 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("Naming", "CA1707:Identifiers should not contain underscores", Justification = "Unit test names can contain a _")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1034:Nested types should not be visible", Justification = "Nested unit test classes should be visible", Scope = "type")]
Add a button press example
using UnityEngine; using System.Collections; public class HandleButtonPress : MonoBehaviour { public OSVR.Unity.OSVRClientKit clientKit; public OSVR.Unity.InterfaceCallbacks cb; public void Start() { GetComponent<OSVR.Unity.InterfaceCallbacks> ().RegisterCallback (handleButton); } public void handleButton(string path, bool state) { Debug.Log ("Got button: " + path + " state is " + state); } }
Add unit tests for UaTcpChannelOptions
using FluentAssertions; using System; using System.Collections.Generic; using System.Text; using Workstation.ServiceModel.Ua; using Xunit; namespace Workstation.UaClient.UnitTests { public class UaApplicationOptionsTests { [Fact] public void UaTcpTransportChannelOptionsDefaults() { var lowestBufferSize = 1024u; var options = new UaTcpTransportChannelOptions(); options.LocalMaxChunkCount .Should().BeGreaterOrEqualTo(lowestBufferSize); options.LocalMaxMessageSize .Should().BeGreaterOrEqualTo(lowestBufferSize); options.LocalReceiveBufferSize .Should().BeGreaterOrEqualTo(lowestBufferSize); options.LocalSendBufferSize .Should().BeGreaterOrEqualTo(lowestBufferSize); } [Fact] public void UaTcpSecureChannelOptionsDefaults() { var shortestTimespan = TimeSpan.FromMilliseconds(100); var options = new UaTcpSecureChannelOptions(); TimeSpan.FromMilliseconds(options.TimeoutHint) .Should().BeGreaterOrEqualTo(shortestTimespan); options.DiagnosticsHint .Should().Be(0); } [Fact] public void UaTcpSessionChannelOptionsDefaults() { var shortestTimespan = TimeSpan.FromMilliseconds(100); var options = new UaTcpSessionChannelOptions(); TimeSpan.FromMilliseconds(options.SessionTimeout) .Should().BeGreaterOrEqualTo(shortestTimespan); } } }
Create a class that is used to process the restQL queries.
using System; using System.Collections.Generic; using System.Text; namespace Nohros.Toolkit.RestQL { /// <summary> /// A class used to process a restQL query. /// </summary> public class QueryProcessor { QueryInfo query_; string query_key_; #region .ctor /// <summary> /// Initializes a new instance of the <see cref="QueryProcessor"/> class /// by using the specified query string. /// </summary> /// <param name="query_key">A string that uniquely identifies a query /// within the main data store.</param> /// <param name="query_string">A <see cref="IDictionary"/> object /// containing the parameters that will be used by the query associated /// with the given <paramref name="query_key"/>.</param> public QueryProcessor(QueryInfo query) { } #endregion /// <summary> /// Retrieve the query information from the main datastore and execute it, /// using the supplied parameters. /// </summary> /// <returns></returns> public string Process() { } } }