Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Add version to SQL instance selector screen
@using StackExchange.Opserver.Data.SQL @{ Layout = null; var clusters = SQLModule.Clusters; var standalone = SQLModule.StandaloneInstances; } @helper RenderInstances(IEnumerable<SQLInstance> instances) { foreach (var i in instances) { var props = i.ServerProperties.SafeData(true); <a class="list-group-item" href="?node=@i.Name.UrlEncode()"> @i.IconSpan() @i.Name <span class="badge" title="@props.FullVersion">@props.MajorVersion</span> </a> } } <h5 class="page-header">Please select a SQL instance.</h5> <div class="row"> @foreach (var c in clusters) { <div class="col-md-3"> <div class="panel panel-default"> <div class="panel-heading">@c.Name</div> <div class="panel-body small list-group"> @RenderInstances(c.Nodes) </div> </div> </div> } @if (standalone.Any()) { <div class="col-md-3"> <div class="panel panel-default"> <div class="panel-heading">Standalone</div> <div class="panel-body small list-group"> @RenderInstances(standalone) </div> </div> </div> } </div>
@using StackExchange.Opserver.Data.SQL @{ Layout = null; var clusters = SQLModule.Clusters; var standalone = SQLModule.StandaloneInstances; } @helper RenderInstances(IEnumerable<SQLInstance> instances, bool showVersion) { foreach (var i in instances) { var props = i.ServerProperties.SafeData(true); <a class="list-group-item" href="?node=@i.Name.UrlEncode()"> @i.IconSpan() @i.Name <span class="badge" title="@props.FullVersion"> @props.MajorVersion @if (showVersion) { <span class="small"> (@i.Version.ToString())</span> } </span> </a> } } @helper RenderList(IEnumerable<SQLInstance> instances, string title) { var versions = instances.Select(n => n.Version).Distinct().ToList(); <div class="col-md-3"> <div class="panel panel-default"> <div class="panel-heading"> @title @if (versions.Count == 1) { <span class="small text-muted">(Version @versions[0].ToString())</span> } </div> <div class="panel-body small list-group"> @RenderInstances(instances, versions.Count > 1) </div> </div> </div> } <h5 class="page-header">Please select a SQL instance.</h5> <div class="row"> @foreach (var c in clusters) { @RenderList(c.Nodes, c.Name) } @if (standalone.Any()) { @RenderList(standalone, "Standalone") } </div>
Add values for a couple of enum values
// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. namespace PInvoke { using System; /// <content> /// Contains the <see cref="NCryptCreatePersistedKeyFlags"/> nested type. /// </content> public static partial class NCrypt { /// <summary> /// Flags that may be passed to the <see cref="NCryptCreatePersistedKey(SafeProviderHandle, out SafeKeyHandle, string, string, LegacyKeySpec, NCryptCreatePersistedKeyFlags)"/> method. /// </summary> [Flags] public enum NCryptCreatePersistedKeyFlags { /// <summary> /// No flags. /// </summary> None = 0x0, /// <summary> /// The key applies to the local computer. If this flag is not present, the key applies to the current user. /// </summary> NCRYPT_MACHINE_KEY_FLAG, /// <summary> /// If a key already exists in the container with the specified name, the existing key will be overwritten. If this flag is not specified and a key with the specified name already exists, this function will return <see cref="SECURITY_STATUS.NTE_EXISTS"/>. /// </summary> NCRYPT_OVERWRITE_KEY_FLAG, } } }
// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. namespace PInvoke { using System; /// <content> /// Contains the <see cref="NCryptCreatePersistedKeyFlags"/> nested type. /// </content> public static partial class NCrypt { /// <summary> /// Flags that may be passed to the <see cref="NCryptCreatePersistedKey(SafeProviderHandle, out SafeKeyHandle, string, string, LegacyKeySpec, NCryptCreatePersistedKeyFlags)"/> method. /// </summary> [Flags] public enum NCryptCreatePersistedKeyFlags { /// <summary> /// No flags. /// </summary> None = 0x0, /// <summary> /// The key applies to the local computer. If this flag is not present, the key applies to the current user. /// </summary> NCRYPT_MACHINE_KEY_FLAG = 0x20, /// <summary> /// If a key already exists in the container with the specified name, the existing key will be overwritten. If this flag is not specified and a key with the specified name already exists, this function will return <see cref="SECURITY_STATUS.NTE_EXISTS"/>. /// </summary> NCRYPT_OVERWRITE_KEY_FLAG = 0x80, } } }
Set default relative path for Project Identity in Integration tests
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. namespace Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils { public abstract class Identity { public string Name { get; protected set; } } public class Project : Identity { public Project(string name, string relativePath = null) { Name = name; RelativePath = relativePath; } public string RelativePath { get; } } public class ProjectReference : Identity { public ProjectReference(string name) { Name = name; } } public class AssemblyReference : Identity { public AssemblyReference(string name) { Name = name; } } public class PackageReference : Identity { public string Version { get; } public PackageReference(string name, string version) { Name = name; Version = version; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.IO; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils { public abstract class Identity { public string Name { get; protected set; } } public class Project : Identity { public Project(string name, string projectExtension = ".csproj", string relativePath = null) { Name = name; if (string.IsNullOrWhiteSpace(relativePath)) { RelativePath = Path.Combine(name, name + projectExtension); } else { RelativePath = relativePath; } } /// <summary> /// This path is relative to the Solution file. Default value is set to ProjectName\ProjectName.csproj /// </summary> public string RelativePath { get; } } public class ProjectReference : Identity { public ProjectReference(string name) { Name = name; } } public class AssemblyReference : Identity { public AssemblyReference(string name) { Name = name; } } public class PackageReference : Identity { public string Version { get; } public PackageReference(string name, string version) { Name = name; Version = version; } } }
Fix catch legacy replay positions not being relative to playfield size
// 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.Game.Beatmaps; using osu.Game.Rulesets.Replays; using osu.Game.Rulesets.Replays.Legacy; using osu.Game.Rulesets.Replays.Types; namespace osu.Game.Rulesets.Catch.Replays { public class CatchReplayFrame : ReplayFrame, IConvertibleReplayFrame { public float Position; public bool Dashing; public CatchReplayFrame() { } public CatchReplayFrame(double time, float? position = null, bool dashing = false) : base(time) { Position = position ?? -1; Dashing = dashing; } public void ConvertFrom(LegacyReplayFrame legacyFrame, Beatmap beatmap) { // Todo: This needs to be re-scaled Position = legacyFrame.Position.X; Dashing = legacyFrame.ButtonState == ReplayButtonState.Left1; } } }
// 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.Game.Beatmaps; using osu.Game.Rulesets.Catch.UI; using osu.Game.Rulesets.Replays; using osu.Game.Rulesets.Replays.Legacy; using osu.Game.Rulesets.Replays.Types; namespace osu.Game.Rulesets.Catch.Replays { public class CatchReplayFrame : ReplayFrame, IConvertibleReplayFrame { public float Position; public bool Dashing; public CatchReplayFrame() { } public CatchReplayFrame(double time, float? position = null, bool dashing = false) : base(time) { Position = position ?? -1; Dashing = dashing; } public void ConvertFrom(LegacyReplayFrame legacyFrame, Beatmap beatmap) { Position = legacyFrame.Position.X / CatchPlayfield.BASE_WIDTH; Dashing = legacyFrame.ButtonState == ReplayButtonState.Left1; } } }
Add setter to Proxy property.
#region using System.Net; using Tabster.Core.Data.Processing; using Tabster.Core.Types; #endregion namespace Tabster.Core.Searching { /// <summary> /// Tab service which enables searching. /// </summary> public interface ISearchService { /// <summary> /// Service name. /// </summary> string Name { get; } /// <summary> /// Associated parser. /// </summary> ITablatureWebpageImporter Parser { get; } /// <summary> /// Service flags. /// </summary> SearchServiceFlags Flags { get; } /// <summary> /// Proxy settings. /// </summary> WebProxy Proxy { get; } /// <summary> /// Determines whether the service supports ratings. /// </summary> bool SupportsRatings { get; } /// <summary> /// Queries service and returns results based on search parameters. /// </summary> /// <param name="query"> Search query. </param> SearchResult[] Search(SearchQuery query); ///<summary> /// Determines whether a specific TabType is supported by the service. ///</summary> ///<param name="type"> The type to check. </param> ///<returns> True if the type is supported by the service; otherwise, False. </returns> bool SupportsTabType(TabType type); } }
#region using System.Net; using Tabster.Core.Data.Processing; using Tabster.Core.Types; #endregion namespace Tabster.Core.Searching { /// <summary> /// Tab service which enables searching. /// </summary> public interface ISearchService { /// <summary> /// Service name. /// </summary> string Name { get; } /// <summary> /// Associated parser. /// </summary> ITablatureWebpageImporter Parser { get; } /// <summary> /// Service flags. /// </summary> SearchServiceFlags Flags { get; } /// <summary> /// Proxy settings. /// </summary> WebProxy Proxy { get; set; } /// <summary> /// Determines whether the service supports ratings. /// </summary> bool SupportsRatings { get; } /// <summary> /// Queries service and returns results based on search parameters. /// </summary> /// <param name="query"> Search query. </param> SearchResult[] Search(SearchQuery query); ///<summary> /// Determines whether a specific TabType is supported by the service. ///</summary> ///<param name="type"> The type to check. </param> ///<returns> True if the type is supported by the service; otherwise, False. </returns> bool SupportsTabType(TabType type); } }
Bump it even more to follow semver
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("BTDB")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("BTDB")] [assembly: AssemblyCopyright("Copyright Boris Letocha 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM componenets. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("d949b20a-70ec-46bf-8eed-3a3cfb0d4593")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision [assembly: AssemblyVersion("2.13.0.0")] [assembly: AssemblyFileVersion("2.13.0.0")] [assembly: InternalsVisibleTo("BTDBTest")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("BTDB")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("BTDB")] [assembly: AssemblyCopyright("Copyright Boris Letocha 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM componenets. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("d949b20a-70ec-46bf-8eed-3a3cfb0d4593")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision [assembly: AssemblyVersion("3.0.0.0")] [assembly: AssemblyFileVersion("3.0.0.0")] [assembly: InternalsVisibleTo("BTDBTest")]
Upgrade version from 5.5.0 to 5.5.1
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Reflection; using System.Resources; using System.Runtime.InteropServices; #if !BUILD_GENERATED_VERSION [assembly: AssemblyCompany("Microsoft Corporation.")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] #endif [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] #if !NOT_CLS_COMPLIANT [assembly: CLSCompliant(true)] #endif [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyMetadata("Serviceable", "True")] // =========================================================================== // DO NOT EDIT OR REMOVE ANYTHING BELOW THIS COMMENT. // Version numbers are automatically generated based on regular expressions. // =========================================================================== #if ASPNETODATA #if !BUILD_GENERATED_VERSION [assembly: AssemblyVersion("5.5.0.0")] // ASPNETODATA [assembly: AssemblyFileVersion("5.5.0.0")] // ASPNETODATA #endif [assembly: AssemblyProduct("Microsoft OData Web API")] #endif
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Reflection; using System.Resources; using System.Runtime.InteropServices; #if !BUILD_GENERATED_VERSION [assembly: AssemblyCompany("Microsoft Corporation.")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] #endif [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] #if !NOT_CLS_COMPLIANT [assembly: CLSCompliant(true)] #endif [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyMetadata("Serviceable", "True")] // =========================================================================== // DO NOT EDIT OR REMOVE ANYTHING BELOW THIS COMMENT. // Version numbers are automatically generated based on regular expressions. // =========================================================================== #if ASPNETODATA #if !BUILD_GENERATED_VERSION [assembly: AssemblyVersion("5.5.1.0")] // ASPNETODATA [assembly: AssemblyFileVersion("5.5.1.0")] // ASPNETODATA #endif [assembly: AssemblyProduct("Microsoft OData Web API")] #endif
Build script now writes the package name and version into the AssemblyDescription attibute. This allows the package information to be seen in Visual Studio avoiding confusion with the assembly version that remains at the major.
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Autofac.Extras.NHibernate")] [assembly: AssemblyDescription("Autofac Integration for NHibernate")] [assembly: ComVisible(false)]
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Autofac.Extras.NHibernate")] [assembly: ComVisible(false)]
Fix a few for Example1
using System; using System.Threading; namespace Example1 { public class Program { public static void Main (string [] args) { using (var streamer = new AudioStreamer ("ws://agektmr.node-ninja.com:3000/socket")) //using (var streamer = new AudioStreamer ("ws://localhost:3000/socket")) { string name; do { Console.Write ("Input your name> "); name = Console.ReadLine (); } while (name.Length == 0); streamer.Connect (name); Console.WriteLine ("\nType \"exit\" to exit.\n"); while (true) { Thread.Sleep (1000); Console.Write ("> "); var msg = Console.ReadLine (); if (msg == "exit") break; streamer.Write (msg); } } } } }
using System; using System.Threading; namespace Example1 { public class Program { public static void Main (string [] args) { using (var streamer = new AudioStreamer ("ws://agektmr.node-ninja.com:3000/socket")) //using (var streamer = new AudioStreamer ("ws://localhost:3000/socket")) { string name; do { Console.Write ("Input your name> "); name = Console.ReadLine (); } while (name.Length == 0); streamer.Connect (name); Console.WriteLine ("\nType 'exit' to exit.\n"); while (true) { Thread.Sleep (1000); Console.Write ("> "); var msg = Console.ReadLine (); if (msg == "exit") break; streamer.Write (msg); } } } } }
Correct the namespace and add copyright message.
using System; using NUnit.Framework; namespace Google.Apis.Tools.CodeGen.Tests { [TestFixture()] public class NewtonsoftObjectToJsonTest { [Test()] public void TestCase () { Assert.Fail("Not tested yet"); } } }
/* Copyright 2010 Google Inc Licensed under the Apache License, Version 2.0 (the ""License""); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using NUnit.Framework; namespace Google.Apis.Tools.CodeGen.Tests.Decorator.ServiceDecorator { [TestFixture()] public class NewtonsoftObjectToJsonTest { [Test()] public void TestCase () { Assert.Fail("Not tested yet"); } } }
Remove button handler on Cancel.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SiliconStudio.Core.Mathematics; using SiliconStudio.Xenko.Input; using SiliconStudio.Xenko.Engine; using SiliconStudio.Xenko.UI.Controls; using XenkoToolkit.Samples.Core; namespace XenkoToolkit.Samples.Core { public class NavigationButtonHandler : SyncScript { public UIPage Page { get; set; } public string ButtonName { get; set; } public INavigationButtonAction ButtonAction { get; set; } = new NavigateToScreen(); public override void Start() { Page = Page ?? this.Entity.Get<UIComponent>()?.Page; if (string.IsNullOrEmpty(ButtonName) || ButtonAction == null) return; // Initialization of the script. if (Page?.RootElement.FindName(ButtonName) is Button button) { button.Click += Button_Click; } } private async void Button_Click(object sender, SiliconStudio.Xenko.UI.Events.RoutedEventArgs e) { var navService = Game.Services.GetService<ISceneNavigationService>(); await ButtonAction?.Handle(navService); } public override void Update() { // Do stuff every new frame } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SiliconStudio.Core.Mathematics; using SiliconStudio.Xenko.Input; using SiliconStudio.Xenko.Engine; using SiliconStudio.Xenko.UI.Controls; using XenkoToolkit.Samples.Core; namespace XenkoToolkit.Samples.Core { public class NavigationButtonHandler : SyncScript { public UIPage Page { get; set; } public string ButtonName { get; set; } public INavigationButtonAction ButtonAction { get; set; } = new NavigateToScreen(); public override void Start() { Page = Page ?? this.Entity.Get<UIComponent>()?.Page; if (string.IsNullOrEmpty(ButtonName) || ButtonAction == null) return; // Initialization of the script. if (Page?.RootElement.FindName(ButtonName) is Button button) { button.Click += Button_Click; } } private async void Button_Click(object sender, SiliconStudio.Xenko.UI.Events.RoutedEventArgs e) { var navService = Game.Services.GetService<ISceneNavigationService>(); await ButtonAction?.Handle(navService); } public override void Update() { // Do stuff every new frame } public override void Cancel() { if (Page?.RootElement.FindName(ButtonName) is Button button) { button.Click -= Button_Click; } } } }
Make agent test less brittle
using System; using Xunit; namespace SparkPost.Tests { public partial class ClientTests { public partial class UserAgentTests { private readonly Client.Settings settings; public UserAgentTests() { settings = new Client.Settings(); } [Fact] public void It_should_default_to_the_library_version() { Assert.Equal($"csharp-sparkpost/2.0.0", settings.UserAgent); } [Fact] public void It_should_allow_the_user_agent_to_be_changed() { var userAgent = Guid.NewGuid().ToString(); settings.UserAgent = userAgent; Assert.Equal(userAgent, settings.UserAgent); } } } }
using System; using Xunit; namespace SparkPost.Tests { public partial class ClientTests { public partial class UserAgentTests { private readonly Client.Settings settings; public UserAgentTests() { settings = new Client.Settings(); } [Fact] public void It_should_default_to_the_library_version() { Assert.StartsWith($"csharp-sparkpost/2.", settings.UserAgent); } [Fact] public void It_should_allow_the_user_agent_to_be_changed() { var userAgent = Guid.NewGuid().ToString(); settings.UserAgent = userAgent; Assert.Equal(userAgent, settings.UserAgent); } } } }
Set accordion panels to be default collapsed
@inherits Umbraco.Web.Mvc.UmbracoViewPage<dynamic> <div class="panel panel-default"> <div class="panel-heading"> <h4 class="panel-title"> <a data-toggle="collapse" @AccordionHelper() href="#collapse-@Model.UniqueId">@Model.Header </a> </h4> </div> <div id="collapse-@Model.UniqueId" class="panel-collapse collapse"> <div class="panel-body"> @Html.Raw(@Model.Body) </div> @if (Model.Footer != null && !String.IsNullOrEmpty(Convert.ToString(Model.Footer))) { <div class="panel-footer"> @Model.Footer </div> } </div> </div> @helper AccordionHelper() { if (Model != null && Model.AccordionParent != null) { @:data-parent="@Model.AccordionParent" } }
@inherits Umbraco.Web.Mvc.UmbracoViewPage<dynamic> <div class="panel panel-default"> <div class="panel-heading"> <h4 class="panel-title"> <a data-toggle="collapse" @AccordionHelper() href="#collapse-@Model.UniqueId">@Model.Header </a> </h4> </div> <div id="collapse-@Model.UniqueId" class="panel-collapse collapse"> <div class="panel-body"> @Html.Raw(@Model.Body) </div> @if (Model.Footer != null && !String.IsNullOrEmpty(Convert.ToString(Model.Footer))) { <div class="panel-footer"> @Model.Footer </div> } </div> </div> @helper AccordionHelper() { if (Model != null && Model.AccordionParent != null) { @:data-parent="@Model.AccordionParent" class="collapsed" } }
Add tricky cases to test class: - nullable primitives - non-nullable custom structs - nullable structs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ValueUtilsTest { class SampleClass { public SampleEnum AnEnum; public string AutoPropWithPrivateBackingField { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ValueUtilsTest { struct CustomStruct { public int Bla; } class SampleClass { public SampleEnum AnEnum; public int? NullableField; public CustomStruct PlainStruct; public CustomStruct? NullableStruct; public string AutoPropWithPrivateBackingField { get; set; } } }
Update conditional code blocks with new versions
#if NETCOREAPP2_1 using System.Runtime.InteropServices; #endif namespace XSharp.Launch { internal static class RuntimeHelper { public static bool IsWindows { get { #if NETCOREAPP2_1 return RuntimeInformation.IsOSPlatform(OSPlatform.Windows); #elif NET471 return true; #endif } } public static bool IsOSX { get { #if NETCOREAPP2_1 return RuntimeInformation.IsOSPlatform(OSPlatform.OSX); #elif NET471 return false; #endif } } public static bool IsLinux { get { #if NETCOREAPP2_1 return RuntimeInformation.IsOSPlatform(OSPlatform.Linux); #elif NET471 return false; #endif } } } }
#if NETCOREAPP2_0 using System.Runtime.InteropServices; #endif namespace XSharp.Launch { internal static class RuntimeHelper { public static bool IsWindows { get { #if NETCOREAPP2_0 return RuntimeInformation.IsOSPlatform(OSPlatform.Windows); #elif NET472 return true; #endif } } public static bool IsOSX { get { #if NETCOREAPP2_0 return RuntimeInformation.IsOSPlatform(OSPlatform.OSX); #elif NET472 return false; #endif } } public static bool IsLinux { get { #if NETCOREAPP2_0 return RuntimeInformation.IsOSPlatform(OSPlatform.Linux); #elif NET472 return false; #endif } } } }
Add test for authorization requirement in TraktUserFollowUserRequest
namespace TraktApiSharp.Tests.Experimental.Requests.Users.OAuth { using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; using TraktApiSharp.Experimental.Requests.Base.Post.Bodyless; using TraktApiSharp.Experimental.Requests.Users.OAuth; using TraktApiSharp.Objects.Post.Users.Responses; [TestClass] public class TraktUserFollowUserRequestTests { [TestMethod, TestCategory("Requests"), TestCategory("Users")] public void TestTraktUserFollowUserRequestIsNotAbstract() { typeof(TraktUserFollowUserRequest).IsAbstract.Should().BeFalse(); } [TestMethod, TestCategory("Requests"), TestCategory("Users")] public void TestTraktUserFollowUserRequestIsSealed() { typeof(TraktUserFollowUserRequest).IsSealed.Should().BeTrue(); } [TestMethod, TestCategory("Requests"), TestCategory("Users")] public void TestTraktUserFollowUserRequestIsSubclassOfATraktSingleItemBodylessPostRequest() { typeof(TraktUserFollowUserRequest).IsSubclassOf(typeof(ATraktSingleItemBodylessPostRequest<TraktUserFollowUserPostResponse>)).Should().BeTrue(); } } }
namespace TraktApiSharp.Tests.Experimental.Requests.Users.OAuth { using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; using TraktApiSharp.Experimental.Requests.Base.Post.Bodyless; using TraktApiSharp.Experimental.Requests.Users.OAuth; using TraktApiSharp.Objects.Post.Users.Responses; using TraktApiSharp.Requests; [TestClass] public class TraktUserFollowUserRequestTests { [TestMethod, TestCategory("Requests"), TestCategory("Users")] public void TestTraktUserFollowUserRequestIsNotAbstract() { typeof(TraktUserFollowUserRequest).IsAbstract.Should().BeFalse(); } [TestMethod, TestCategory("Requests"), TestCategory("Users")] public void TestTraktUserFollowUserRequestIsSealed() { typeof(TraktUserFollowUserRequest).IsSealed.Should().BeTrue(); } [TestMethod, TestCategory("Requests"), TestCategory("Users")] public void TestTraktUserFollowUserRequestIsSubclassOfATraktSingleItemBodylessPostRequest() { typeof(TraktUserFollowUserRequest).IsSubclassOf(typeof(ATraktSingleItemBodylessPostRequest<TraktUserFollowUserPostResponse>)).Should().BeTrue(); } [TestMethod, TestCategory("Requests"), TestCategory("Users")] public void TestTraktUserFollowUserRequestHasAuthorizationRequired() { var request = new TraktUserFollowUserRequest(null); request.AuthorizationRequirement.Should().Be(TraktAuthorizationRequirement.Required); } } }
Fix NgBy when used with IWebElement
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using OpenQA.Selenium; namespace Protractor { internal class JavaScriptBy : By { private string script; private object[] args; public JavaScriptBy(string script, params object[] args) { this.script = script; this.args = args; } public IWebElement RootElement { get; set; } public override IWebElement FindElement(ISearchContext context) { ReadOnlyCollection<IWebElement> elements = this.FindElements(context); return elements.Count > 0 ? elements[0] : null; } public override ReadOnlyCollection<IWebElement> FindElements(ISearchContext context) { // Create script arguments object[] scriptArgs = new object[this.args.Length + 1]; scriptArgs[0] = this.RootElement; Array.Copy(this.args, 0, scriptArgs, 1, this.args.Length); ReadOnlyCollection<IWebElement> elements = ((IJavaScriptExecutor)context).ExecuteScript(this.script, scriptArgs) as ReadOnlyCollection<IWebElement>; if (elements == null) { elements = new ReadOnlyCollection<IWebElement>(new List<IWebElement>(0)); } return elements; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using OpenQA.Selenium; using OpenQA.Selenium.Internal; namespace Protractor { internal class JavaScriptBy : By { private string script; private object[] args; public JavaScriptBy(string script, params object[] args) { this.script = script; this.args = args; } public IWebElement RootElement { get; set; } public override IWebElement FindElement(ISearchContext context) { ReadOnlyCollection<IWebElement> elements = this.FindElements(context); return elements.Count > 0 ? elements[0] : null; } public override ReadOnlyCollection<IWebElement> FindElements(ISearchContext context) { // Create script arguments object[] scriptArgs = new object[this.args.Length + 1]; scriptArgs[0] = this.RootElement; Array.Copy(this.args, 0, scriptArgs, 1, this.args.Length); // Get JS executor IJavaScriptExecutor jsExecutor = context as IJavaScriptExecutor; if (jsExecutor == null) { IWrapsDriver wrapsDriver = context as IWrapsDriver; if (wrapsDriver != null) { jsExecutor = wrapsDriver.WrappedDriver as IJavaScriptExecutor; } } if (jsExecutor == null) { throw new NotSupportedException("Could not get an IJavaScriptExecutor instance from the context."); } ReadOnlyCollection<IWebElement> elements = jsExecutor.ExecuteScript(this.script, scriptArgs) as ReadOnlyCollection<IWebElement>; if (elements == null) { elements = new ReadOnlyCollection<IWebElement>(new List<IWebElement>(0)); } return elements; } } }
Add a newline to Mac OS X output
using System; using System.IO; using System.Diagnostics; using Xp.Cert; namespace Xp.Cert.Commands { public partial class Update : Command { const string SECURITY_EXECUTABLE = "/usr/bin/security"; const string SECURITY_ARGUMENTS = "find-certificate -a -p"; const string SECURITY_KEYCHAIN = "/System/Library/Keychains/SystemRootCertificates.keychain"; /// <summary>Execute this command</summary> public void MacOSX(FileInfo bundle) { var proc = new Process(); proc.StartInfo.UseShellExecute = false; proc.StartInfo.FileName = SECURITY_EXECUTABLE; proc.StartInfo.Arguments = SECURITY_ARGUMENTS + " " + SECURITY_KEYCHAIN; proc.StartInfo.RedirectStandardOutput = true; proc.StartInfo.RedirectStandardError = false; try { Console.Write("> From {0}: [", SECURITY_KEYCHAIN); proc.Start(); using (var writer = new StreamWriter(bundle.Open(FileMode.Create))) { var count = 0; proc.OutputDataReceived += (sender, e) => { if (e.Data.StartsWith(BEGIN_CERT)) { count++; Console.Write('.'); } writer.WriteLine(e.Data); }; proc.BeginOutputReadLine(); proc.WaitForExit(); Console.WriteLine("]"); Console.WriteLine(" {0} certificates", count); } } finally { proc.Close(); } } } }
using System; using System.IO; using System.Diagnostics; using Xp.Cert; namespace Xp.Cert.Commands { public partial class Update : Command { const string SECURITY_EXECUTABLE = "/usr/bin/security"; const string SECURITY_ARGUMENTS = "find-certificate -a -p"; const string SECURITY_KEYCHAIN = "/System/Library/Keychains/SystemRootCertificates.keychain"; /// <summary>Execute this command</summary> public void MacOSX(FileInfo bundle) { var proc = new Process(); proc.StartInfo.UseShellExecute = false; proc.StartInfo.FileName = SECURITY_EXECUTABLE; proc.StartInfo.Arguments = SECURITY_ARGUMENTS + " " + SECURITY_KEYCHAIN; proc.StartInfo.RedirectStandardOutput = true; proc.StartInfo.RedirectStandardError = false; try { Console.Write("> From {0}: [", SECURITY_KEYCHAIN); proc.Start(); using (var writer = new StreamWriter(bundle.Open(FileMode.Create))) { var count = 0; proc.OutputDataReceived += (sender, e) => { if (e.Data.StartsWith(BEGIN_CERT)) { count++; Console.Write('.'); } writer.WriteLine(e.Data); }; proc.BeginOutputReadLine(); proc.WaitForExit(); Console.WriteLine("]"); Console.WriteLine(" {0} certificates", count); Console.WriteLine(); } } finally { proc.Close(); } } } }
Format change to match other methods;
using System; using Android.App; using AndroidHUD; namespace XHUD { public enum MaskType { // None = 1, Clear, Black, // Gradient } public static class HUD { public static Activity MyActivity; public static void Show(string message, int progress = -1, MaskType maskType = MaskType.Black) { AndHUD.Shared.Show(HUD.MyActivity, message, progress,(AndroidHUD.MaskType)maskType); } public static void Dismiss() { AndHUD.Shared.Dismiss(HUD.MyActivity); } public static void ShowToast(string message, bool showToastCentered = true, double timeoutMs = 1000) { AndHUD.Shared.ShowToast(HUD.MyActivity, message, (AndroidHUD.MaskType)MaskType.Black, TimeSpan.FromSeconds(timeoutMs/1000), showToastCentered); } public static void ShowToast (string message, MaskType maskType, bool showToastCentered = true, double timeoutMs = 1000) { AndHUD.Shared.ShowToast(HUD.MyActivity, message, (AndroidHUD.MaskType)maskType, TimeSpan.FromSeconds(timeoutMs/1000), showToastCentered); } } }
using System; using Android.App; using AndroidHUD; namespace XHUD { public enum MaskType { // None = 1, Clear, Black, // Gradient } public static class HUD { public static Activity MyActivity; public static void Show(string message, int progress = -1, MaskType maskType = MaskType.Black) { AndHUD.Shared.Show(HUD.MyActivity, message, progress,(AndroidHUD.MaskType)maskType); } public static void Dismiss() { AndHUD.Shared.Dismiss(HUD.MyActivity); } public static void ShowToast(string message, bool showToastCentered = true, double timeoutMs = 1000) { AndHUD.Shared.ShowToast(HUD.MyActivity, message, (AndroidHUD.MaskType)MaskType.Black, TimeSpan.FromSeconds(timeoutMs/1000), showToastCentered); } public static void ShowToast(string message, MaskType maskType, bool showToastCentered = true, double timeoutMs = 1000) { AndHUD.Shared.ShowToast(HUD.MyActivity, message, (AndroidHUD.MaskType)maskType, TimeSpan.FromSeconds(timeoutMs/1000), showToastCentered); } } }
Add filter property to most played movies request.
namespace TraktApiSharp.Requests.WithoutOAuth.Movies.Common { using Base.Get; using Enums; using Objects.Basic; using Objects.Get.Movies.Common; using System.Collections.Generic; internal class TraktMoviesMostPlayedRequest : TraktGetRequest<TraktPaginationListResult<TraktMostPlayedMovie>, TraktMostPlayedMovie> { internal TraktMoviesMostPlayedRequest(TraktClient client) : base(client) { Period = TraktPeriod.Weekly; } internal TraktPeriod? Period { get; set; } protected override IDictionary<string, object> GetUriPathParameters() { var uriParams = base.GetUriPathParameters(); if (Period.HasValue && Period.Value != TraktPeriod.Unspecified) uriParams.Add("period", Period.Value.AsString()); return uriParams; } protected override string UriTemplate => "movies/played{/period}{?extended,page,limit}"; protected override TraktAuthorizationRequirement AuthorizationRequirement => TraktAuthorizationRequirement.NotRequired; protected override bool SupportsPagination => true; protected override bool IsListResult => true; } }
namespace TraktApiSharp.Requests.WithoutOAuth.Movies.Common { using Base; using Base.Get; using Enums; using Objects.Basic; using Objects.Get.Movies.Common; using System.Collections.Generic; internal class TraktMoviesMostPlayedRequest : TraktGetRequest<TraktPaginationListResult<TraktMostPlayedMovie>, TraktMostPlayedMovie> { internal TraktMoviesMostPlayedRequest(TraktClient client) : base(client) { Period = TraktPeriod.Weekly; } internal TraktPeriod? Period { get; set; } protected override IDictionary<string, object> GetUriPathParameters() { var uriParams = base.GetUriPathParameters(); if (Period.HasValue && Period.Value != TraktPeriod.Unspecified) uriParams.Add("period", Period.Value.AsString()); return uriParams; } protected override string UriTemplate => "movies/played{/period}{?extended,page,limit,query,years,genres,languages,countries,runtimes,ratings,certifications}"; protected override TraktAuthorizationRequirement AuthorizationRequirement => TraktAuthorizationRequirement.NotRequired; internal TraktMovieFilter Filter { get; set; } protected override bool SupportsPagination => true; protected override bool IsListResult => true; } }
Remove un-needed ctor and other methods
using System; using System.Xml; using System.Xml.Linq; namespace openvassharp { public class OpenVASManager : IDisposable { private OpenVASSession _session; public OpenVASManager () { _session = null; } public OpenVASManager(OpenVASSession session) { if (session != null) _session = session; } public XDocument GetVersion() { return _session.ExecuteCommand (XDocument.Parse ("<get_version />")); } private bool CheckSession() { if (!_session.Stream.CanRead) throw new Exception("Bad session"); return true; } public void Dispose() { _session = null; } } }
using System; using System.Xml; using System.Xml.Linq; namespace openvassharp { public class OpenVASManager : IDisposable { private OpenVASSession _session; public OpenVASManager(OpenVASSession session) { if (session != null) _session = session; } public XDocument GetVersion() { return _session.ExecuteCommand (XDocument.Parse ("<get_version />")); } public void Dispose() { _session = null; } } }
Add test for authorization requirement in TraktUserUnfollowUserRequest
namespace TraktApiSharp.Tests.Experimental.Requests.Users.OAuth { using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; using TraktApiSharp.Experimental.Requests.Base.Delete; using TraktApiSharp.Experimental.Requests.Users.OAuth; [TestClass] public class TraktUserUnfollowUserRequestTests { [TestMethod, TestCategory("Requests"), TestCategory("Users")] public void TestTraktUserUnfollowUserRequestIsNotAbstract() { typeof(TraktUserUnfollowUserRequest).IsAbstract.Should().BeFalse(); } [TestMethod, TestCategory("Requests"), TestCategory("Users")] public void TestTraktUserUnfollowUserRequestIsSealed() { typeof(TraktUserUnfollowUserRequest).IsSealed.Should().BeTrue(); } [TestMethod, TestCategory("Requests"), TestCategory("Users")] public void TestTraktUserUnfollowUserRequestIsSubclassOfATraktNoContentDeleteRequest() { typeof(TraktUserUnfollowUserRequest).IsSubclassOf(typeof(ATraktNoContentDeleteRequest)).Should().BeTrue(); } } }
namespace TraktApiSharp.Tests.Experimental.Requests.Users.OAuth { using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; using TraktApiSharp.Experimental.Requests.Base.Delete; using TraktApiSharp.Experimental.Requests.Users.OAuth; using TraktApiSharp.Requests; [TestClass] public class TraktUserUnfollowUserRequestTests { [TestMethod, TestCategory("Requests"), TestCategory("Users")] public void TestTraktUserUnfollowUserRequestIsNotAbstract() { typeof(TraktUserUnfollowUserRequest).IsAbstract.Should().BeFalse(); } [TestMethod, TestCategory("Requests"), TestCategory("Users")] public void TestTraktUserUnfollowUserRequestIsSealed() { typeof(TraktUserUnfollowUserRequest).IsSealed.Should().BeTrue(); } [TestMethod, TestCategory("Requests"), TestCategory("Users")] public void TestTraktUserUnfollowUserRequestIsSubclassOfATraktNoContentDeleteRequest() { typeof(TraktUserUnfollowUserRequest).IsSubclassOf(typeof(ATraktNoContentDeleteRequest)).Should().BeTrue(); } [TestMethod, TestCategory("Requests"), TestCategory("Users")] public void TestTraktUserUnfollowUserRequestHasAuthorizationRequired() { var request = new TraktUserUnfollowUserRequest(null); request.AuthorizationRequirement.Should().Be(TraktAuthorizationRequirement.Required); } } }
Fix take until exception error.
using System; using System.Collections.Generic; using System.Linq; using CSharpViaTest.Collections.Annotations; using Xunit; namespace CSharpViaTest.Collections._20_YieldPractices { [Medium] public class TakeUntilCatchingAnException { readonly int indexThatWillThrow = new Random().Next(2, 10); IEnumerable<int> GetSequenceOfData() { for (int i = 0;; ++i) { if (i == indexThatWillThrow) { throw new Exception("An exception is thrown"); } yield return i; } } #region Please modifies the code to pass the test static IEnumerable<int> TakeUntilError(IEnumerable<int> sequence) { throw new NotImplementedException(); } #endregion [Fact] public void should_get_sequence_until_an_exception_is_thrown() { IEnumerable<int> sequence = TakeUntilError(GetSequenceOfData()); Assert.Equal(Enumerable.Range(0, indexThatWillThrow + 1), sequence); } [Fact] public void should_get_sequence_given_normal_collection() { var sequence = new[] { 1, 2, 3 }; IEnumerable<int> result = TakeUntilError(sequence); Assert.Equal(sequence, result); } } }
using System; using System.Collections.Generic; using System.Linq; using CSharpViaTest.Collections.Annotations; using Xunit; namespace CSharpViaTest.Collections._20_YieldPractices { [Medium] public class TakeUntilCatchingAnException { readonly int indexThatWillThrow = new Random().Next(2, 10); IEnumerable<int> GetSequenceOfData() { for (int i = 0;; ++i) { if (i == indexThatWillThrow) { throw new Exception("An exception is thrown"); } yield return i; } } #region Please modifies the code to pass the test static IEnumerable<int> TakeUntilError(IEnumerable<int> sequence) { throw new NotImplementedException(); } #endregion [Fact] public void should_get_sequence_until_an_exception_is_thrown() { IEnumerable<int> sequence = TakeUntilError(GetSequenceOfData()); Assert.Equal(Enumerable.Range(0, indexThatWillThrow), sequence); } [Fact] public void should_get_sequence_given_normal_collection() { var sequence = new[] { 1, 2, 3 }; IEnumerable<int> result = TakeUntilError(sequence); Assert.Equal(sequence, result); } } }
Add PermissionChecker for Identity registration.
using AbpCompanyName.AbpProjectName.Authorization; using AbpCompanyName.AbpProjectName.Authorization.Roles; using AbpCompanyName.AbpProjectName.Authorization.Users; using AbpCompanyName.AbpProjectName.Editions; using AbpCompanyName.AbpProjectName.MultiTenancy; using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.DependencyInjection; namespace AbpCompanyName.AbpProjectName.Identity { public static class IdentityRegistrar { public static void Register(IServiceCollection services) { services.AddLogging(); services.AddAbpIdentity<Tenant, User, Role>() .AddAbpTenantManager<TenantManager>() .AddAbpUserManager<UserManager>() .AddAbpRoleManager<RoleManager>() .AddAbpEditionManager<EditionManager>() .AddAbpUserStore<UserStore>() .AddAbpRoleStore<RoleStore>() .AddAbpLogInManager<LogInManager>() .AddAbpSignInManager<SignInManager>() .AddAbpSecurityStampValidator<SecurityStampValidator>() .AddAbpUserClaimsPrincipalFactory<UserClaimsPrincipalFactory>() .AddDefaultTokenProviders(); } } }
using AbpCompanyName.AbpProjectName.Authorization; using AbpCompanyName.AbpProjectName.Authorization.Roles; using AbpCompanyName.AbpProjectName.Authorization.Users; using AbpCompanyName.AbpProjectName.Editions; using AbpCompanyName.AbpProjectName.MultiTenancy; using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.DependencyInjection; namespace AbpCompanyName.AbpProjectName.Identity { public static class IdentityRegistrar { public static void Register(IServiceCollection services) { services.AddLogging(); services.AddAbpIdentity<Tenant, User, Role>() .AddAbpTenantManager<TenantManager>() .AddAbpUserManager<UserManager>() .AddAbpRoleManager<RoleManager>() .AddAbpEditionManager<EditionManager>() .AddAbpUserStore<UserStore>() .AddAbpRoleStore<RoleStore>() .AddAbpLogInManager<LogInManager>() .AddAbpSignInManager<SignInManager>() .AddAbpSecurityStampValidator<SecurityStampValidator>() .AddAbpUserClaimsPrincipalFactory<UserClaimsPrincipalFactory>() .AddPermissionChecker<PermissionChecker>() .AddDefaultTokenProviders(); } } }
Use newline when writing to stdout.
using System; namespace kgrep { public class WriteStdout : IHandleOutput { public void Write(string line) { if (line.EndsWith("\n")) Console.Write(line); else Console.Write(line); } public string Close() { return ""; } } }
using System; namespace kgrep { public class WriteStdout : IHandleOutput { public void Write(string line) { Console.WriteLine(line); } public string Close() { return ""; } } }
Return a single value in procedure return message
using Newtonsoft.Json; using RestRPC.Framework.Messages.Inputs; namespace RestRPC.Framework.Messages.Outputs { /// <summary> /// This message is sent to server as a response to a request /// </summary> class WebReturn : WebOutput { const char HEADER_RETURN = 'r'; [JsonConstructor] public WebReturn(object Data, WebInput input) : base(HEADER_RETURN, new object[] { Data }, input.UID, input.CID) { } } }
using Newtonsoft.Json; using RestRPC.Framework.Messages.Inputs; namespace RestRPC.Framework.Messages.Outputs { /// <summary> /// This message is sent to server as a response to a request /// </summary> class WebReturn : WebOutput { const char HEADER_RETURN = 'r'; [JsonConstructor] public WebReturn(object Data, WebInput input) : base(HEADER_RETURN, Data, input.UID, input.CID) { } } }
Add directives to reprompt object
using Newtonsoft.Json; namespace Alexa.NET.Response { public class Reprompt { public Reprompt() { } public Reprompt(string text) { OutputSpeech = new PlainTextOutputSpeech {Text = text}; } public Reprompt(Ssml.Speech speech) { OutputSpeech = new SsmlOutputSpeech {Ssml = speech.ToXml()}; } [JsonProperty("outputSpeech", NullValueHandling=NullValueHandling.Ignore)] public IOutputSpeech OutputSpeech { get; set; } } }
using System.Collections.Generic; using Newtonsoft.Json; namespace Alexa.NET.Response { public class Reprompt { public Reprompt() { } public Reprompt(string text) { OutputSpeech = new PlainTextOutputSpeech {Text = text}; } public Reprompt(Ssml.Speech speech) { OutputSpeech = new SsmlOutputSpeech {Ssml = speech.ToXml()}; } [JsonProperty("outputSpeech", NullValueHandling=NullValueHandling.Ignore)] public IOutputSpeech OutputSpeech { get; set; } [JsonProperty("directives", NullValueHandling = NullValueHandling.Ignore)] public IList<IDirective> Directives { get; set; } = new List<IDirective>(); public bool ShouldSerializeDirectives() { return Directives.Count > 0; } } }
Add support for optional list of keys to limit view queries
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net; using Newtonsoft.Json; using System.Windows.Forms; using System.Dynamic; namespace CouchTrafficClient { class QueryException : Exception { } class QueryBase { public string Run() { return "Query Client Not Implemented"; } public string Server { get { return "http://52.10.252.48:5984/traffic/"; } } protected ExpandoObject Query(string designDocumentName, string viewName) { try { var url = Server + "_design/" + designDocumentName + "/_view/" + viewName; using (WebClient wc = new WebClient()) { wc.Encoding = System.Text.Encoding.UTF8; wc.Headers["User-Agent"] = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET4.0C; .NET4.0E)"; string str = wc.DownloadString(url); return JsonConvert.DeserializeObject<ExpandoObject>(str); } } catch (Exception e) { MessageBox.Show("Error in WebClient: " + e.ToString()); throw new QueryException(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net; using Newtonsoft.Json; using System.Windows.Forms; using System.Dynamic; namespace CouchTrafficClient { class QueryException : Exception { } class QueryBase { public string Run() { return "Query Client Not Implemented"; } public string Server { get { return "http://52.10.252.48:5984/traffic/"; } } protected ExpandoObject Query(string designDocumentName, string viewName, IList<object> keys = null) { try { var keyString = ""; if (keys != null) { keyString = string.Format("?keys={0}", Uri.EscapeDataString(JsonConvert.SerializeObject(keys))); } var url = Server + "_design/" + designDocumentName + "/_view/" + viewName + keyString; using (WebClient wc = new WebClient()) { wc.Encoding = System.Text.Encoding.UTF8; wc.Headers["User-Agent"] = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET4.0C; .NET4.0E)"; string str = wc.DownloadString(url); return JsonConvert.DeserializeObject<ExpandoObject>(str); } } catch (Exception e) { MessageBox.Show("Error in WebClient: " + e.ToString()); throw new QueryException(); } } } }
Remove unneeded property carry over for jsonwritter
using Newtonsoft.Json; using System; using System.Globalization; using System.IO; using System.Text; namespace Glimpse { public class DefaultMessageConverter : IMessageConverter { private readonly JsonSerializer _jsonSerializer; public DefaultMessageConverter(JsonSerializer jsonSerializer) { _jsonSerializer = jsonSerializer; } public IMessageEnvelope ConvertMessage(IMessage message) { var newMessage = new MessageEnvelope(); newMessage.Type = message.GetType().FullName; newMessage.Payload = Serialize(message); return newMessage; } protected string Serialize(object data) { // Brought across from - https://github.com/JamesNK/Newtonsoft.Json/blob/master/Src/Newtonsoft.Json/JsonConvert.cs#L635 var stringBuilder = new StringBuilder(256); using (var stringWriter = new StringWriter(stringBuilder, CultureInfo.InvariantCulture)) using (var jsonWriter = new JsonTextWriter(stringWriter) { Formatting = _jsonSerializer.Formatting }) { _jsonSerializer.Serialize(jsonWriter, data, data.GetType()); return stringWriter.ToString(); } } } }
using Newtonsoft.Json; using System; using System.Globalization; using System.IO; using System.Text; namespace Glimpse { public class DefaultMessageConverter : IMessageConverter { private readonly JsonSerializer _jsonSerializer; public DefaultMessageConverter(JsonSerializer jsonSerializer) { _jsonSerializer = jsonSerializer; } public IMessageEnvelope ConvertMessage(IMessage message) { var newMessage = new MessageEnvelope(); newMessage.Type = message.GetType().FullName; newMessage.Payload = Serialize(message); return newMessage; } protected string Serialize(object data) { // Brought across from - https://github.com/JamesNK/Newtonsoft.Json/blob/master/Src/Newtonsoft.Json/JsonConvert.cs#L635 var stringBuilder = new StringBuilder(256); using (var stringWriter = new StringWriter(stringBuilder, CultureInfo.InvariantCulture)) using (var jsonWriter = new JsonTextWriter(stringWriter)) { _jsonSerializer.Serialize(jsonWriter, data, data.GetType()); return stringWriter.ToString(); } } } }
Enable GTK theming on Mono.
using System.Windows.Forms; namespace IronAHK.Scripting { partial class Script { public static void Init() { Application.EnableVisualStyles(); } public static void Run() { Application.Run(); } } }
using System; using System.Windows.Forms; namespace IronAHK.Scripting { partial class Script { public static void Init() { if (Environment.OSVersion.Platform == PlatformID.Unix) Environment.SetEnvironmentVariable("MONO_VISUAL_STYLES", "gtkplus"); Application.EnableVisualStyles(); } public static void Run() { Application.Run(); } } }
Fix a bug with parsing.
using System; namespace Scheme.Storage { internal abstract class Atom : Object { public static Atom Parse(string input) { double number; bool isNumber = Double.TryParse(input, out number); if (isNumber) return new Number(number); bool isString = input[0] == '"' && input[input.Length - 1] == '"'; if (isString) return new String(input.Substring(1, input.Length - 2)); bool isValidSymbol = true; // TODO: validate. if (isValidSymbol) return Symbol.FromString(input); throw new FormatException(); } } }
using System; namespace Scheme.Storage { internal abstract class Atom : Object { public static Atom Parse(string input) { double number; bool isNumber = Double.TryParse(input, out number); if (isNumber) return new Number(number); bool isString = input.Length > 2 && input[0] == '"' && input[input.Length - 1] == '"'; if (isString) return new String(input.Substring(1, input.Length - 2)); bool isValidSymbol = true; // TODO: validate. if (isValidSymbol) return Symbol.FromString(input); throw new FormatException(); } } }
Add error handling to import process (resolves await warning).
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System.Diagnostics; using System.Threading.Tasks; using osu.Framework.Platform; using osu.Game.Database; namespace osu.Game.IPC { public class BeatmapImporter { private IpcChannel<BeatmapImportMessage> channel; private BeatmapDatabase beatmaps; public BeatmapImporter(GameHost host, BeatmapDatabase beatmaps = null) { this.beatmaps = beatmaps; channel = new IpcChannel<BeatmapImportMessage>(host); channel.MessageReceived += messageReceived; } public async Task ImportAsync(string path) { if (beatmaps != null) beatmaps.Import(path); else { await channel.SendMessageAsync(new BeatmapImportMessage { Path = path }); } } private void messageReceived(BeatmapImportMessage msg) { Debug.Assert(beatmaps != null); ImportAsync(msg.Path); } } public class BeatmapImportMessage { public string Path; } }
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System.Diagnostics; using System.Threading.Tasks; using osu.Framework.Logging; using osu.Framework.Platform; using osu.Game.Database; namespace osu.Game.IPC { public class BeatmapImporter { private IpcChannel<BeatmapImportMessage> channel; private BeatmapDatabase beatmaps; public BeatmapImporter(GameHost host, BeatmapDatabase beatmaps = null) { this.beatmaps = beatmaps; channel = new IpcChannel<BeatmapImportMessage>(host); channel.MessageReceived += messageReceived; } public async Task ImportAsync(string path) { if (beatmaps != null) beatmaps.Import(path); else { await channel.SendMessageAsync(new BeatmapImportMessage { Path = path }); } } private void messageReceived(BeatmapImportMessage msg) { Debug.Assert(beatmaps != null); ImportAsync(msg.Path).ContinueWith(t => Logger.Error(t.Exception, @"error during async import"), TaskContinuationOptions.OnlyOnFaulted); } } public class BeatmapImportMessage { public string Path; } }
Move the private member to the top of the class
using System; using System.Collections; namespace Mos6510 { public class Register { public Register(int numberOfBits) { bits = new BitArray(numberOfBits); } public int Length { get { return bits.Length; } } public int GetValue() { return ToInt(); } public void SetValue(int value) { FromInt(value); } private int ToInt() { int[] array = new int[1]; bits.CopyTo(array, 0); return array[0]; } private void FromInt(int value) { var inputBits = new BitArray(new[]{ value }); for (var i = 0; i < bits.Length; ++i) bits[i] = inputBits[i]; } private BitArray bits; } }
using System; using System.Collections; namespace Mos6510 { public class Register { private BitArray bits; public Register(int numberOfBits) { bits = new BitArray(numberOfBits); } public int Length { get { return bits.Length; } } public int GetValue() { return ToInt(); } public void SetValue(int value) { FromInt(value); } private int ToInt() { int[] array = new int[1]; bits.CopyTo(array, 0); return array[0]; } private void FromInt(int value) { var inputBits = new BitArray(new[]{ value }); for (var i = 0; i < bits.Length; ++i) bits[i] = inputBits[i]; } } }
Change button types on editor exit dialog to match purpose
// 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.Graphics.Sprites; using osu.Game.Overlays.Dialog; namespace osu.Game.Screens.Edit { public class PromptForSaveDialog : PopupDialog { public PromptForSaveDialog(Action exit, Action saveAndExit, Action cancel) { HeaderText = "Did you want to save your changes?"; Icon = FontAwesome.Regular.Save; Buttons = new PopupDialogButton[] { new PopupDialogCancelButton { Text = @"Save my masterpiece!", Action = saveAndExit }, new PopupDialogOkButton { Text = @"Forget all changes", Action = exit }, new PopupDialogCancelButton { Text = @"Oops, continue editing", Action = cancel }, }; } } }
// 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.Graphics.Sprites; using osu.Game.Overlays.Dialog; namespace osu.Game.Screens.Edit { public class PromptForSaveDialog : PopupDialog { public PromptForSaveDialog(Action exit, Action saveAndExit, Action cancel) { HeaderText = "Did you want to save your changes?"; Icon = FontAwesome.Regular.Save; Buttons = new PopupDialogButton[] { new PopupDialogOkButton { Text = @"Save my masterpiece!", Action = saveAndExit }, new PopupDialogDangerousButton { Text = @"Forget all changes", Action = exit }, new PopupDialogCancelButton { Text = @"Oops, continue editing", Action = cancel }, }; } } }
Add "ApplicationPath" in tenant URL
using System.Web.Mvc; using Orchard.Environment.Configuration; namespace Orchard.MultiTenancy.Extensions { public static class UrlHelperExtensions { public static string Tenant(this UrlHelper urlHelper, ShellSettings tenantShellSettings) { //info: (heskew) might not keep the port insertion around beyond... var port = string.Empty; string host = urlHelper.RequestContext.HttpContext.Request.Headers["Host"]; if(host.Contains(":")) port = host.Substring(host.IndexOf(":")); return string.Format( "http://{0}/{1}", !string.IsNullOrEmpty(tenantShellSettings.RequestUrlHost) ? tenantShellSettings.RequestUrlHost + port : host, tenantShellSettings.RequestUrlPrefix); } } }
using System.Web.Mvc; using Orchard.Environment.Configuration; namespace Orchard.MultiTenancy.Extensions { public static class UrlHelperExtensions { public static string Tenant(this UrlHelper urlHelper, ShellSettings tenantShellSettings) { //info: (heskew) might not keep the port/vdir insertion around beyond... var port = string.Empty; string host = urlHelper.RequestContext.HttpContext.Request.Headers["Host"]; if (host.Contains(":")) port = host.Substring(host.IndexOf(":")); var result = string.Format("http://{0}", !string.IsNullOrEmpty(tenantShellSettings.RequestUrlHost) ? tenantShellSettings.RequestUrlHost + port : host); if (!string.IsNullOrEmpty(tenantShellSettings.RequestUrlPrefix)) result += "/" + tenantShellSettings.RequestUrlPrefix; if (!string.IsNullOrEmpty(urlHelper.RequestContext.HttpContext.Request.ApplicationPath)) result += urlHelper.RequestContext.HttpContext.Request.ApplicationPath; return result; } } }
Order the list of deployments by start time.
using System.Collections.Generic; using System.Linq; using Kudu.Core.Deployment; using Kudu.SignalR.ViewModels; using SignalR.Hubs; namespace Kudu.SignalR.Hubs { public class Deployment : Hub { private readonly IDeploymentManager _deploymentManager; public Deployment(IDeploymentManager deploymentManager) { _deploymentManager = deploymentManager; } public IEnumerable<DeployResultViewModel> GetDeployments() { string active = _deploymentManager.ActiveDeploymentId; Caller.id = active; return _deploymentManager.GetResults().Select(d => new DeployResultViewModel(d) { Active = active == d.Id }); } public IEnumerable<LogEntryViewModel> GetDeployLog(string id) { return from entry in _deploymentManager.GetLogEntries(id) select new LogEntryViewModel(entry); } public void Deploy(string id) { _deploymentManager.Deploy(id); } } }
using System.Collections.Generic; using System.Linq; using Kudu.Core.Deployment; using Kudu.SignalR.ViewModels; using SignalR.Hubs; namespace Kudu.SignalR.Hubs { public class Deployment : Hub { private readonly IDeploymentManager _deploymentManager; public Deployment(IDeploymentManager deploymentManager) { _deploymentManager = deploymentManager; } public IEnumerable<DeployResultViewModel> GetDeployments() { string active = _deploymentManager.ActiveDeploymentId; Caller.id = active; return _deploymentManager.GetResults() .OrderByDescending(d => d.DeployStartTime) .Select(d => new DeployResultViewModel(d) { Active = active == d.Id }); } public IEnumerable<LogEntryViewModel> GetDeployLog(string id) { return from entry in _deploymentManager.GetLogEntries(id) select new LogEntryViewModel(entry); } public void Deploy(string id) { _deploymentManager.Deploy(id); } } }
Update version number to 2.11.0.
using System.Reflection; [assembly: AssemblyVersion("2.10.7.0")] [assembly: AssemblyFileVersion("2.10.7.0")] [assembly: AssemblyInformationalVersion("2.10.7")]
using System.Reflection; [assembly: AssemblyVersion("2.11.0.0")] [assembly: AssemblyFileVersion("2.11.0.0")] [assembly: AssemblyInformationalVersion("2.11.0")]
Improve CanMakePhoneCall on iOS to check support of url and link to a carrier
using System; #if __UNIFIED__ using Foundation; using UIKit; #else using MonoTouch.Foundation; using MonoTouch.UIKit; #endif namespace Plugin.Messaging { internal class PhoneCallTask : IPhoneCallTask { public PhoneCallTask() { } #region IPhoneCallTask Members public bool CanMakePhoneCall { get { // UIApplication.SharedApplication.CanOpenUrl does not validate the URL, it merely checks whether a handler for // the URL has been installed on the system. Therefore string.Empty can be used as phone number. var nsurl = CreateNsUrl(string.Empty); return UIApplication.SharedApplication.CanOpenUrl(nsurl); } } public void MakePhoneCall(string number, string name = null) { if (string.IsNullOrWhiteSpace(number)) throw new ArgumentNullException(nameof(number)); if (CanMakePhoneCall) { var nsurl = CreateNsUrl(number); UIApplication.SharedApplication.OpenUrl(nsurl); } } private NSUrl CreateNsUrl(string number) { return new NSUrl(new Uri($"tel:{number}").AbsoluteUri); } #endregion } }
using System; #if __UNIFIED__ using Foundation; using UIKit; using CoreTelephony; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreTelephony; #endif namespace Plugin.Messaging { internal class PhoneCallTask : IPhoneCallTask { public PhoneCallTask() { } #region IPhoneCallTask Members public bool CanMakePhoneCall { get { var nsurl = CreateNsUrl("0000000000"); bool canCall = UIApplication.SharedApplication.CanOpenUrl(nsurl); if (canCall) { using (CTTelephonyNetworkInfo netInfo = new CTTelephonyNetworkInfo()) { string mnc = netInfo.SubscriberCellularProvider?.MobileNetworkCode; return !string.IsNullOrEmpty(mnc) && mnc != "65535"; //65535 stands for NoNetwordProvider } } return false; } } public void MakePhoneCall(string number, string name = null) { if (string.IsNullOrWhiteSpace(number)) throw new ArgumentNullException(nameof(number)); if (CanMakePhoneCall) { var nsurl = CreateNsUrl(number); UIApplication.SharedApplication.OpenUrl(nsurl); } } private NSUrl CreateNsUrl(string number) { return new NSUrl(new Uri($"tel:{number}").AbsoluteUri); } #endregion } }
Fix a few service paths in portal
using System.Net; using System.Net.Http; using System.Threading.Tasks; using System.Xml.Linq; using Kudu.Client.Deployment; using Kudu.Client.Infrastructure; using Kudu.Client.SourceControl; using Kudu.Core.SourceControl; using Kudu.Web.Models; namespace Kudu.Web.Infrastructure { public static class ApplicationExtensions { public static Task<RepositoryInfo> GetRepositoryInfo(this IApplication application, ICredentials credentials) { var repositoryManager = new RemoteRepositoryManager(application.ServiceUrl + "live/scm", credentials); return repositoryManager.GetRepositoryInfo(); } public static RemoteDeploymentManager GetDeploymentManager(this IApplication application, ICredentials credentials) { var deploymentManager = new RemoteDeploymentManager(application.ServiceUrl + "/deployments", credentials); return deploymentManager; } public static RemoteDeploymentSettingsManager GetSettingsManager(this IApplication application, ICredentials credentials) { var deploymentSettingsManager = new RemoteDeploymentSettingsManager(application.ServiceUrl + "/settings", credentials); return deploymentSettingsManager; } public static Task<XDocument> DownloadTrace(this IApplication application, ICredentials credentials) { var clientHandler = HttpClientHelper.CreateClientHandler(application.ServiceUrl, credentials); var client = new HttpClient(clientHandler); return client.GetAsync(application.ServiceUrl + "dump").Then(response => { return response.EnsureSuccessStatusCode().Content.ReadAsStreamAsync().Then(stream => { return ZipHelper.ExtractTrace(stream); }); }); } } }
using System.Net; using System.Net.Http; using System.Threading.Tasks; using System.Xml.Linq; using Kudu.Client.Deployment; using Kudu.Client.Infrastructure; using Kudu.Client.SourceControl; using Kudu.Core.SourceControl; using Kudu.Web.Models; namespace Kudu.Web.Infrastructure { public static class ApplicationExtensions { public static Task<RepositoryInfo> GetRepositoryInfo(this IApplication application, ICredentials credentials) { var repositoryManager = new RemoteRepositoryManager(application.ServiceUrl + "scm", credentials); return repositoryManager.GetRepositoryInfo(); } public static RemoteDeploymentManager GetDeploymentManager(this IApplication application, ICredentials credentials) { var deploymentManager = new RemoteDeploymentManager(application.ServiceUrl + "deployments", credentials); return deploymentManager; } public static RemoteDeploymentSettingsManager GetSettingsManager(this IApplication application, ICredentials credentials) { var deploymentSettingsManager = new RemoteDeploymentSettingsManager(application.ServiceUrl + "settings", credentials); return deploymentSettingsManager; } public static Task<XDocument> DownloadTrace(this IApplication application, ICredentials credentials) { var clientHandler = HttpClientHelper.CreateClientHandler(application.ServiceUrl, credentials); var client = new HttpClient(clientHandler); return client.GetAsync(application.ServiceUrl + "dump").Then(response => { return response.EnsureSuccessStatusCode().Content.ReadAsStreamAsync().Then(stream => { return ZipHelper.ExtractTrace(stream); }); }); } } }
Remove useless code in blockcontrol test
using System; using System.Drawing; using System.Windows.Forms; using Linking.Controls; using Linking.Core; using Linking.Core.Blocks; namespace Linking { public partial class Form1 : Form { public Form1() { //이것도 커밋해 보시지!! InitializeComponent(); Board board = new Board(); BoardControl boardCtrl = new BoardControl(board); boardCtrl.Dock = DockStyle.Fill; this.Controls.Add(boardCtrl); EntryBlock entry = new EntryBlock(board); BlockControl b = new BlockControl(entry); b.Location = new Point(50, 50); boardCtrl.AddBlock(entry); } } }
using System; using System.Drawing; using System.Windows.Forms; using Linking.Controls; using Linking.Core; using Linking.Core.Blocks; namespace Linking { public partial class Form1 : Form { public Form1() { //이것도 커밋해 보시지!! InitializeComponent(); Board board = new Board(); BoardControl boardCtrl = new BoardControl(board); boardCtrl.Dock = DockStyle.Fill; this.Controls.Add(boardCtrl); EntryBlock entry = new EntryBlock(board); boardCtrl.AddBlock(entry); } } }
Add namespace and fix DisplayAttribute.Order evaluation to avoid exception when Order is not set.
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Reflection; public static class TypeExtensions { public static IEnumerable<PropertyInfo> GetSortedProperties(this Type t) { return from pi in t.GetProperties() let da = (DisplayAttribute)pi.GetCustomAttributes(typeof(DisplayAttribute), false).SingleOrDefault() let order = ((da != null && da.Order != 0) ? da.Order : int.MaxValue) orderby order select pi; } public static IEnumerable<PropertyInfo> GetSortedProperties<T>() { return typeof(T).GetSortedProperties(); } public static IEnumerable<PropertyInfo> GetProperties(this Type t) { return from pi in t.GetProperties() select pi; } public static IEnumerable<PropertyInfo> GetProperties<T>() { return typeof(T).GetSortedProperties(); } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Reflection; namespace Mvc.JQuery.Datatables { public static class TypeExtensions { public static IEnumerable<PropertyInfo> GetSortedProperties(this Type t) { return from pi in t.GetProperties() let da = (DisplayAttribute)pi.GetCustomAttributes(typeof(DisplayAttribute), false).SingleOrDefault() let order = ((da != null && da.GetOrder() != null && da.GetOrder() >= 0) ? da.Order : int.MaxValue) orderby order select pi; } public static IEnumerable<PropertyInfo> GetSortedProperties<T>() { return typeof(T).GetSortedProperties(); } public static IEnumerable<PropertyInfo> GetProperties(this Type t) { return from pi in t.GetProperties() select pi; } public static IEnumerable<PropertyInfo> GetProperties<T>() { return typeof(T).GetSortedProperties(); } } }
Add parameter specifying color to pad with.
using LibPixelPet; using System; namespace PixelPet.CLI.Commands { internal class PadPalettesCmd : CliCommand { public PadPalettesCmd() : base("Pad-Palettes", new Parameter(true, new ParameterValue("width", "0")) ) { } public override void Run(Workbench workbench, ILogger logger) { int width = FindUnnamedParameter(0).Values[0].ToInt32(); if (width < 1) { logger?.Log("Invalid palette width.", LogLevel.Error); return; } if (workbench.PaletteSet.Count == 0) { logger?.Log("No palettes to pad. Creating 1 palette based on current bitmap format.", LogLevel.Information); Palette pal = new Palette(workbench.BitmapFormat, -1); workbench.PaletteSet.Add(pal); } int addedColors = 0; foreach (PaletteEntry pe in workbench.PaletteSet) { while (pe.Palette.Count < width) { pe.Palette.Add(0); addedColors++; } } logger?.Log("Padded palettes to width " + width + " (added " + addedColors + " colors).", LogLevel.Information); } } }
using LibPixelPet; using System; namespace PixelPet.CLI.Commands { internal class PadPalettesCmd : CliCommand { public PadPalettesCmd() : base("Pad-Palettes", new Parameter(true, new ParameterValue("width", "0")), new Parameter("color", "c", false, new ParameterValue("value", "0")) ) { } public override void Run(Workbench workbench, ILogger logger) { int width = FindUnnamedParameter(0).Values[0].ToInt32(); int color = FindNamedParameter("--color").Values[0].ToInt32(); if (width < 1) { logger?.Log("Invalid palette width.", LogLevel.Error); return; } if (workbench.PaletteSet.Count == 0) { logger?.Log("No palettes to pad. Creating 1 palette based on current bitmap format.", LogLevel.Information); Palette pal = new Palette(workbench.BitmapFormat, -1); workbench.PaletteSet.Add(pal); } int addedColors = 0; foreach (PaletteEntry pe in workbench.PaletteSet) { while (pe.Palette.Count < width) { pe.Palette.Add(color); addedColors++; } } logger?.Log("Padded palettes to width " + width + " (added " + addedColors + " colors).", LogLevel.Information); } } }
Build MSI only on Windows.
using System; using System.Diagnostics; [assembly: CLSCompliant(true)] namespace IronAHK.Setup { static partial class Program { static void Main(string[] args) { TransformDocs(); PackageZip(); AppBundle(); BuildMsi(); } [Conditional("DEBUG")] static void Cleanup() { Console.Read(); } } }
using System; using System.Diagnostics; [assembly: CLSCompliant(true)] namespace IronAHK.Setup { static partial class Program { static void Main(string[] args) { TransformDocs(); PackageZip(); AppBundle(); if (Environment.OSVersion.Platform == PlatformID.Win32NT) BuildMsi(); Cleanup(); } [Conditional("DEBUG")] static void Cleanup() { Console.Read(); } } }
Build script now creates individual zip file packages to align with the NuGet packages and semantic versioning.
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.18033 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyVersion("3.0.0.0")] [assembly: AssemblyFileVersion("3.0.0.0")] [assembly: AssemblyConfiguration("Release built on 2013-02-22 14:39")] [assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")]
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.18033 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyVersion("3.0.0.0")] [assembly: AssemblyFileVersion("3.0.0.0")] [assembly: AssemblyConfiguration("Release built on 2013-02-28 02:03")] [assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")]
Add Code Contracts in ButonExt
using System; using System.Windows.Controls; using static System.Reactive.Linq.Observable; namespace cardio.Ext { /// <summary> /// Represents Button Extension /// </summary> static class ButtonExt { /// <summary> /// Disables the button /// </summary> /// <param name="button">Given button to be disbaled</param> /// <returns>button</returns> internal static Button Disable (this Button button) { if ( !button.IsEnabled ) return button; button.IsEnabled = false; return button; } /// <summary> /// Enables the button /// </summary> /// <param name="button">Given button to enabled</param> /// <returns>button</returns> internal static Button Enable (this Button button) { if ( button.IsEnabled ) return button; button.IsEnabled = true; return button; } /// <summary> /// Converts Button Click to Stream of Button /// </summary> /// <param name="button">The given button</param> /// <returns>The sender button</returns> internal static IObservable<Button> StreamButtonClick(this Button button) { return from evt in FromEventPattern(button, "Click") select evt.Sender as Button; } } }
using System; using System.Windows.Controls; using static System.Reactive.Linq.Observable; using static System.Diagnostics.Contracts.Contract; namespace cardio.Ext { /// <summary> /// Represents Button Extension /// </summary> static class ButtonExt { /// <summary> /// Disables the button /// </summary> /// <param name="button">Given button to be disbaled</param> /// <returns>button</returns> internal static Button Disable (this Button button) { Requires(button != null); if ( !button.IsEnabled ) return button; button.IsEnabled = false; return button; } /// <summary> /// Enables the button /// </summary> /// <param name="button">Given button to enabled</param> /// <returns>button</returns> internal static Button Enable (this Button button) { Requires(button != null); if ( button.IsEnabled ) return button; button.IsEnabled = true; return button; } /// <summary> /// Converts Button Click to Stream of Button /// </summary> /// <param name="button">The given button</param> /// <returns>The sender button</returns> internal static IObservable<Button> StreamButtonClick(this Button button) { Requires(button != null); return from evt in FromEventPattern(button, "Click") select evt.Sender as Button; } } }
Fix for base command being shown as command on command line.
using System; using System.Collections.Generic; using ManyConsole; namespace TeamCityBuildChanges { class Program { static int Main(string[] args) { var commands = GetCommands(); return ConsoleCommandDispatcher.DispatchCommand(commands, args, Console.Out); } static IEnumerable<ConsoleCommand> GetCommands() { return ConsoleCommandDispatcher.FindCommandsInSameAssemblyAs(typeof(Program)); } } }
using System; using System.Collections.Generic; using System.Linq; using ManyConsole; namespace TeamCityBuildChanges { class Program { static int Main(string[] args) { var commands = GetCommands(); return ConsoleCommandDispatcher.DispatchCommand(commands, args, Console.Out); } static IEnumerable<ConsoleCommand> GetCommands() { return ConsoleCommandDispatcher.FindCommandsInSameAssemblyAs(typeof(Program)).Where(c => !string.IsNullOrEmpty(c.Command)); } } }
Correct full screen test class name.
using System; using System.Collections.Generic; using AgateLib; using AgateLib.DisplayLib; using AgateLib.Geometry; using AgateLib.InputLib; namespace Tests.DisplayTests { class HelloWorldProgram : IAgateTest { public string Name { get { return "Full Screen"; } } public string Category { get { return "Display"; } } public void Main(string[] args) { using (AgateSetup setup = new AgateSetup(args)) { setup.InitializeAll(); if (setup.WasCanceled) return; DisplayWindow wind = DisplayWindow.CreateFullScreen("Hello World", 640, 480); Surface mySurface = new Surface("jellybean.png"); // Run the program while the window is open. while (Display.CurrentWindow.IsClosed == false && Keyboard.Keys[KeyCode.Escape] == false) { Display.BeginFrame(); Display.Clear(Color.DarkGreen); mySurface.Draw(Mouse.X, Mouse.Y); Display.EndFrame(); Core.KeepAlive(); } } } } }
using System; using System.Collections.Generic; using AgateLib; using AgateLib.DisplayLib; using AgateLib.Geometry; using AgateLib.InputLib; namespace Tests.DisplayTests { class FullscreenTest : IAgateTest { public string Name { get { return "Full Screen"; } } public string Category { get { return "Display"; } } public void Main(string[] args) { using (AgateSetup setup = new AgateSetup(args)) { setup.InitializeAll(); if (setup.WasCanceled) return; DisplayWindow wind = DisplayWindow.CreateFullScreen("Hello World", 640, 480); Surface mySurface = new Surface("jellybean.png"); // Run the program while the window is open. while (Display.CurrentWindow.IsClosed == false && Keyboard.Keys[KeyCode.Escape] == false) { Display.BeginFrame(); Display.Clear(Color.DarkGreen); mySurface.Draw(Mouse.X, Mouse.Y); Display.EndFrame(); Core.KeepAlive(); } } } } }
Add possibility to customize plugin search pattern
using System; using System.Collections.Generic; using System.IO; using System.Reflection; namespace PluginLoader { public static class Plugins<T> where T : class { /// <summary> /// Loads interface plugins from the specified location. /// </summary> /// <param name="path">Load path</param> /// <returns></returns> public static ICollection<T> Load(string path) { var plugins = new List<T>(); if (Directory.Exists(path)) { Type pluginType = typeof(T); // All interface plugins have "if_" prefix var assemblies = Directory.GetFiles(path, "if_*.dll"); foreach (var assemblyPath in assemblies) { var assembly = Assembly.LoadFrom(assemblyPath); foreach (var type in assembly.GetTypes()) { var typeInfo = type.GetTypeInfo(); if (typeInfo.GetInterface(pluginType.FullName) != null) { T plugin = Activator.CreateInstance(type) as T; plugins.Add(plugin); } } } } return plugins; } } }
using System; using System.Collections.Generic; using System.IO; using System.Reflection; namespace PluginLoader { public static class Plugins<T> where T : class { /// <summary> /// Loads interface plugins from the specified location. /// </summary> /// <param name="path">Load path</param> /// <param name="searchPattern">Plugin file search pattern, default "if_*.dll"</param> /// <returns></returns> public static ICollection<T> Load(string path, string searchPattern = "if_*.dll") { var plugins = new List<T>(); if (Directory.Exists(path)) { Type pluginType = typeof(T); var assemblies = Directory.GetFiles(path, searchPattern); foreach (var assemblyPath in assemblies) { var assembly = Assembly.LoadFrom(assemblyPath); foreach (var type in assembly.GetTypes()) { var typeInfo = type.GetTypeInfo(); if (typeInfo.GetInterface(pluginType.FullName) != null) { T plugin = Activator.CreateInstance(type) as T; plugins.Add(plugin); } } } } return plugins; } } }
Include symbols, etc in the memory dump
using System.IO; using ClrSpy.CliSupport; using ClrSpy.Debugger; using Microsoft.Diagnostics.Runtime.Interop; namespace ClrSpy.Jobs { public class DumpMemoryJob : IDebugJob { private readonly DebugRunningProcess target; public int Pid => target.Process.Pid; public string DumpFilePath { get; } public bool OverwriteDumpFileIfExists { get; set; } public DumpMemoryJob(DebugRunningProcess target, string dumpFilePath) { DumpFilePath = dumpFilePath; this.target = target; } public void Run(TextWriter output, ConsoleLog console) { using (var session = target.CreateSession()) { if (File.Exists(DumpFilePath)) { if (!OverwriteDumpFileIfExists) throw new IOException($"File already exists: {DumpFilePath}"); File.Delete(DumpFilePath); } var clientInterface = session.DataTarget.DebuggerInterface as IDebugClient2; if (clientInterface == null) { console.WriteLine("WARNING: API only supports old-style dump? Recording minidump instead."); session.DataTarget.DebuggerInterface.WriteDumpFile(DumpFilePath, DEBUG_DUMP.SMALL); return; } clientInterface.WriteDumpFile2(DumpFilePath, DEBUG_DUMP.SMALL, DEBUG_FORMAT.USER_SMALL_FULL_MEMORY, ""); } } } }
using System.IO; using ClrSpy.CliSupport; using ClrSpy.Debugger; using Microsoft.Diagnostics.Runtime.Interop; namespace ClrSpy.Jobs { public class DumpMemoryJob : IDebugJob { private readonly DebugRunningProcess target; public int Pid => target.Process.Pid; public string DumpFilePath { get; } public bool OverwriteDumpFileIfExists { get; set; } public DumpMemoryJob(DebugRunningProcess target, string dumpFilePath) { DumpFilePath = dumpFilePath; this.target = target; } public void Run(TextWriter output, ConsoleLog console) { using (var session = target.CreateSession()) { if (File.Exists(DumpFilePath)) { if (!OverwriteDumpFileIfExists) throw new IOException($"File already exists: {DumpFilePath}"); File.Delete(DumpFilePath); } var clientInterface = session.DataTarget.DebuggerInterface as IDebugClient2; if (clientInterface == null) { console.WriteLine("WARNING: API only supports old-style dump? Recording minidump instead."); session.DataTarget.DebuggerInterface.WriteDumpFile(DumpFilePath, DEBUG_DUMP.SMALL); return; } clientInterface.WriteDumpFile2(DumpFilePath, DEBUG_DUMP.SMALL, DEBUG_FORMAT.USER_SMALL_FULL_MEMORY | DEBUG_FORMAT.CAB_SECONDARY_ALL_IMAGES, ""); } } } }
Change list display for soldiers
@model IEnumerable<Soldier> <h2>Soldiers @Html.ActionLink("Add New", "New", "Soldiers", null, new { @class = "btn btn-default" })</h2> <table class="table table-striped"> <thead> <tr> <th></th> <th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Rank)</th> <th>@Html.DisplayNameFor(_ => _.FirstOrDefault().LastName)</th> <th>@Html.DisplayNameFor(_ => _.FirstOrDefault().FirstName)</th> <th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Unit)</th> <th></th> </tr> </thead> <tbody> @foreach (var soldier in Model) { <tr> <td>@Html.ActionLink("Details", "Details", new { soldier.Id })</td> <td>@Html.DisplayFor(s => soldier.Rank)</td> <td>@Html.DisplayFor(s => soldier.LastName)</td> <td>@Html.DisplayFor(s => soldier.FirstName)</td> <td>@Html.DisplayFor(s => soldier.Unit)</td> <td> @Html.ActionLink("Add ABCP", "New", "ABCP", new { soldier = soldier.Id }, new { @class = "btn btn-default" }) @Html.ActionLink("Add APFT", "New", "APFT", new { soldier = soldier.Id }, new { @class = "btn btn-default" }) </td> </tr> } </tbody> </table>
@model IEnumerable<Soldier> <h2>Soldiers @Html.ActionLink("Add New", "New", "Soldiers", null, new { @class = "btn btn-default" })</h2> <table class="table table-striped"> <thead> <tr> <th></th> <th>@Html.DisplayNameFor(_ => _.FirstOrDefault().FirstName)</th> <th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Unit)</th> <th></th> </tr> </thead> <tbody> @foreach (var soldier in Model) { <tr> <td>@Html.ActionLink("Details", "Details", new { soldier.Id })</td> <td>@Html.DisplayFor(s => soldier)</td> <td>@Html.DisplayFor(s => soldier.Unit)</td> <td> @Html.ActionLink("Add ABCP", "New", "ABCP", new { soldier = soldier.Id }, new { @class = "btn btn-default" }) @Html.ActionLink("Add APFT", "New", "APFT", new { soldier = soldier.Id }, new { @class = "btn btn-default" }) </td> </tr> } </tbody> </table>
Use expected, but incorrect, truncated RFC3339 format
using System; using MessageBird.Utilities; using Newtonsoft.Json; using System.Globalization; namespace MessageBird.Json.Converters { public class RFC3339DateTimeConverter : JsonConverter { private const string format = "Y-m-d\\TH:i:sP"; public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { if (value is DateTime) { DateTime dateTime = (DateTime)value; writer.WriteValue(dateTime.ToString(format)); } else { throw new JsonSerializationException("Expected value of type 'DateTime'."); } } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { Type t = (ReflectionUtils.IsNullable(objectType)) ? Nullable.GetUnderlyingType(objectType) : objectType; if (reader.TokenType == JsonToken.Null) { return null; } if (reader.TokenType == JsonToken.Date) { return reader.Value; } else { throw new JsonSerializationException(String.Format("Unexpected token '{0}' when parsing date.", reader.TokenType)); } } public override bool CanConvert(Type objectType) { Type t = (ReflectionUtils.IsNullable(objectType)) ? Nullable.GetUnderlyingType(objectType) : objectType; return t == typeof(DateTime); } } }
using System; using MessageBird.Utilities; using Newtonsoft.Json; using System.Globalization; namespace MessageBird.Json.Converters { public class RFC3339DateTimeConverter : JsonConverter { // XXX: Format should be "yyyy-MM-dd'T'THH:mm:ssK". // However, due to bug the endpoint expects the current used format. // Need to be changed when the endpoint is updated! private const string format = "yyyy-MM-dd'T'HH:mm"; public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { if (value is DateTime) { DateTime dateTime = (DateTime)value; writer.WriteValue(dateTime.ToString(format)); } else { throw new JsonSerializationException("Expected value of type 'DateTime'."); } } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { Type t = (ReflectionUtils.IsNullable(objectType)) ? Nullable.GetUnderlyingType(objectType) : objectType; if (reader.TokenType == JsonToken.Null) { return null; } if (reader.TokenType == JsonToken.Date) { return reader.Value; } else { throw new JsonSerializationException(String.Format("Unexpected token '{0}' when parsing date.", reader.TokenType)); } } public override bool CanConvert(Type objectType) { Type t = (ReflectionUtils.IsNullable(objectType)) ? Nullable.GetUnderlyingType(objectType) : objectType; return t == typeof(DateTime); } } }
Fix XP text not displaying
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class HUD_Manager : MonoBehaviour { // The names of the GUI objects we're editing public string amountXPElementName; public string playerHealthElementName; public string equippedWeaponIconElementName; // Equipped weapon icons to use public Sprite equippedMeleeSprite; public Sprite equippedRangedSprite; public Sprite equippedMagicSprite; // The GUI objects we're editing GUIText amountXPText; Slider playerHealthSlider; Image equippedWeaponIcon; // Use this for initialization void Start () { // Find and store the things we'll be modifying amountXPText = GameObject.Find(amountXPElementName).GetComponent<GUIText>(); playerHealthSlider = GameObject.Find(playerHealthElementName).GetComponent<Slider>(); equippedWeaponIcon = GameObject.Find(equippedWeaponIconElementName).GetComponent<Image>(); } // Update is called once per frame void Update () { // Update player XP, health and equipped weapon icon amountXPText.text = Game.thePlayer.XP.ToString(); playerHealthSlider.value = Game.thePlayer.health / Game.thePlayer.maxHealth; // TODO: equipped weapon } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class HUD_Manager : MonoBehaviour { // The names of the GUI objects we're editing public string amountXPElementName; public string playerHealthElementName; public string equippedWeaponIconElementName; // Equipped weapon icons to use public Sprite equippedMeleeSprite; public Sprite equippedRangedSprite; public Sprite equippedMagicSprite; // The GUI objects we're editing Text amountXPText; Slider playerHealthSlider; Image equippedWeaponIcon; // Use this for initialization void Start () { // Find and store the things we'll be modifying amountXPText = GameObject.Find(amountXPElementName).GetComponent<Text>(); playerHealthSlider = GameObject.Find(playerHealthElementName).GetComponent<Slider>(); equippedWeaponIcon = GameObject.Find(equippedWeaponIconElementName).GetComponent<Image>(); } // Update is called once per frame void Update () { // Update player XP, health and equipped weapon icon amountXPText.text = Game.thePlayer.XP.ToString(); playerHealthSlider.value = Game.thePlayer.health / Game.thePlayer.maxHealth; // TODO: equipped weapon } }
Adjust sample to fit on default Windows cmd console.
using System; using System.Threading; namespace ConsoleProgressBar { /// <summary> /// Simple program with sample usage of ConsoleProgressBar. /// </summary> class Program { public static void Main(string[] args) { using (var progressBar = new ConsoleProgressBar(totalUnitsOfWork: 3500)) { for (uint i = 0; i < 3500; ++i) { progressBar.Draw(i + 1); Thread.Sleep(1); } } using (var progressBar = new ConsoleProgressBar( totalUnitsOfWork: 2000, startingPosition: 10, widthInCharacters: 65, completedColor: ConsoleColor.DarkBlue, remainingColor: ConsoleColor.DarkGray)) { for (uint i = 0; i < 2000; ++i) { progressBar.Draw(i + 1); Thread.Sleep(1); } } } } }
using System; using System.Threading; namespace ConsoleProgressBar { /// <summary> /// Simple program with sample usage of ConsoleProgressBar. /// </summary> class Program { public static void Main(string[] args) { using (var progressBar = new ConsoleProgressBar(totalUnitsOfWork: 3500)) { for (uint i = 0; i < 3500; ++i) { progressBar.Draw(i + 1); Thread.Sleep(1); } } using (var progressBar = new ConsoleProgressBar( totalUnitsOfWork: 2000, startingPosition: 3, widthInCharacters: 48, completedColor: ConsoleColor.DarkBlue, remainingColor: ConsoleColor.DarkGray)) { for (uint i = 0; i < 2000; ++i) { progressBar.Draw(i + 1); Thread.Sleep(1); } } } } }
Update to send mail function
using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Net; using System.Net.Mail; using System.Threading.Tasks; using System.Web; namespace KryptPadWebApp.Email { public class EmailHelper { /// <summary> /// Sends an email /// </summary> /// <param name="subject"></param> /// <param name="body"></param> /// <param name="to"></param> /// <returns></returns> public static Task SendAsync(string subject, string body, string to) { // Credentials var credentialUserName = ConfigurationManager.AppSettings["SmtpUserName"]; var sentFrom = ConfigurationManager.AppSettings["SmtpSendFrom"]; var pwd = ConfigurationManager.AppSettings["SmtpPassword"]; var server = ConfigurationManager.AppSettings["SmtpHostName"]; var port = Convert.ToInt32(ConfigurationManager.AppSettings["SmtpPort"]); // Configure the client var client = new SmtpClient(server); client.Port = port; client.DeliveryMethod = SmtpDeliveryMethod.Network; client.UseDefaultCredentials = false; // Create the credentials var credentials = new NetworkCredential(credentialUserName, pwd); client.EnableSsl = false; client.Credentials = credentials; // Create the message var mail = new MailMessage(sentFrom, to); mail.IsBodyHtml = true; mail.Subject = subject; mail.Body = body; // Send return client.SendMailAsync(mail); } } }
using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Net; using System.Net.Mail; using System.Threading.Tasks; using System.Web; namespace KryptPadWebApp.Email { public class EmailHelper { /// <summary> /// Sends an email /// </summary> /// <param name="subject"></param> /// <param name="body"></param> /// <param name="to"></param> /// <returns></returns> public static Task SendAsync(string subject, string body, string to) { // Credentials var credentialUserName = ConfigurationManager.AppSettings["SmtpUserName"]; var sentFrom = ConfigurationManager.AppSettings["SmtpSendFrom"]; var pwd = ConfigurationManager.AppSettings["SmtpPassword"]; var server = ConfigurationManager.AppSettings["SmtpHostName"]; var port = Convert.ToInt32(ConfigurationManager.AppSettings["SmtpPort"]); // Configure the client var client = new SmtpClient(server); client.Port = port; client.DeliveryMethod = SmtpDeliveryMethod.Network; client.UseDefaultCredentials = false; client.EnableSsl = false; // Create the credentials client.Credentials = new NetworkCredential(credentialUserName, pwd); // Create the message var mail = new MailMessage(sentFrom, to); mail.IsBodyHtml = true; mail.Subject = subject; mail.Body = body; // Send return client.SendMailAsync(mail); } } }
Remove call to EnableInternalPdfViewerOffScreen as it's been removed as Chromium no longer supports disabling of surfaces
using System; using System.Windows; namespace CefSharp.MinimalExample.Wpf { public partial class App : Application { public App() { //Perform dependency check to make sure all relevant resources are in our output directory. var settings = new CefSettings(); settings.EnableInternalPdfViewerOffScreen(); Cef.Initialize(settings, performDependencyCheck: true, browserProcessHandler: null); } } }
using System; using System.Windows; namespace CefSharp.MinimalExample.Wpf { public partial class App : Application { public App() { //Perform dependency check to make sure all relevant resources are in our output directory. var settings = new CefSettings(); Cef.Initialize(settings, performDependencyCheck: true, browserProcessHandler: null); } } }
Add option for groupname to group options by groups
using SPAD.neXt.Interfaces.Profile; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; namespace SPAD.neXt.Interfaces.Configuration { public interface ISettingsProvider : IProfileOptionsProvider, IWindowPlacementProvider { } public interface IProfileOptionsProvider { IProfileOption AddOption(string key, Interfaces.Profile.ProfileOptionTypes type, string defaultValue, bool needrestart = false, bool editable = false, bool hidden = false); IProfileOption GetOption(string key); void SetOption(string key, string value); } public interface IWindowPlacementProvider { IWindowPlacement GetWindowPlacement(string key); void SetWindowPlacement(IWindowPlacement placement); } public interface IWindowPlacement { string Key { get; } double Top { get; set; } double Left { get; set; } double Height { get; set; } double Width { get; set; } bool HasValues { get; } void ApplyPlacement(Window w); bool SavePlacement(Window w); T GetOption<T>(string key, T defaultValue = default(T)); void SetOption(string key, object value); } }
using SPAD.neXt.Interfaces.Profile; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; namespace SPAD.neXt.Interfaces.Configuration { public interface ISettingsProvider : IProfileOptionsProvider, IWindowPlacementProvider { } public interface IProfileOptionsProvider { IProfileOption AddOption(string key, Interfaces.Profile.ProfileOptionTypes type, string defaultValue, bool needrestart = false, bool editable = false, bool hidden = false,string groupName="Other"); IProfileOption GetOption(string key); void SetOption(string key, string value); } public interface IWindowPlacementProvider { IWindowPlacement GetWindowPlacement(string key); void SetWindowPlacement(IWindowPlacement placement); } public interface IWindowPlacement { string Key { get; } double Top { get; set; } double Left { get; set; } double Height { get; set; } double Width { get; set; } bool HasValues { get; } void ApplyPlacement(Window w); bool SavePlacement(Window w); T GetOption<T>(string key, T defaultValue = default(T)); void SetOption(string key, object value); } }
Fix the namespace following an earlier rename
using System; using FluentMigrator.Runner; using FluentMigrator.Runner.Announcers; using FluentMigrator.Runner.Initialization; using FluentMigrator.Runner.Processors.SqlServer; namespace BroadbandStats.Database.Migrations { public sealed class Migrator { private readonly string connectionString; public Migrator(string connectionString) { if (connectionString == null) { throw new ArgumentNullException(nameof(connectionString)); } this.connectionString = connectionString; } public void MigrateToLatestSchema() { var todaysDate = DateTime.Today.ToString("yyyyMMdd"); var todaysSchemaVersion = long.Parse(todaysDate); MigrateTo(todaysSchemaVersion); } private void MigrateTo(long targetVersion) { var options = new MigrationOptions { PreviewOnly = false, Timeout = 60 }; var announcer = new NullAnnouncer(); var processor = new SqlServer2012ProcessorFactory().Create(connectionString, announcer, options); var migrationContext = new RunnerContext(announcer) { Namespace = "BroadbandSpeedTests.Database.Migrations.Migrations" }; var runner = new MigrationRunner(GetType().Assembly, migrationContext, processor); runner.MigrateUp(targetVersion, true); } } }
using System; using BroadbandStats.Database.Migrations.Migrations; using FluentMigrator.Runner; using FluentMigrator.Runner.Announcers; using FluentMigrator.Runner.Initialization; using FluentMigrator.Runner.Processors.SqlServer; namespace BroadbandStats.Database.Migrations { public sealed class Migrator { private readonly string connectionString; public Migrator(string connectionString) { if (connectionString == null) { throw new ArgumentNullException(nameof(connectionString)); } this.connectionString = connectionString; } public void MigrateToLatestSchema() { var todaysDate = DateTime.Today.ToString("yyyyMMdd"); var todaysSchemaVersion = long.Parse(todaysDate); MigrateTo(todaysSchemaVersion); } private void MigrateTo(long targetVersion) { var options = new MigrationOptions { PreviewOnly = false, Timeout = 60 }; var announcer = new NullAnnouncer(); var processor = new SqlServer2012ProcessorFactory().Create(connectionString, announcer, options); var migrationContext = new RunnerContext(announcer) { Namespace = typeof(InitialDatabase).Namespace }; var runner = new MigrationRunner(GetType().Assembly, migrationContext, processor); runner.MigrateUp(targetVersion, true); } } }
Change default world size to compensate for use of chunks
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Common.Data { public class OnionState { public bool Enabled { get; set; } = true; public bool CustomWorldSize { get; set; } = false; public int Width { get; set; } = 256; public int Height { get; set; } = 384; public bool Debug { get; set; } = false; public bool FreeCamera { get; set; } = true; public bool CustomMaxCameraDistance { get; set; } = true; public float MaxCameraDistance { get; set; } = 300; public bool LogSeed { get; set; } = true; public bool CustomSeeds { get; set; } = false; public int WorldSeed { get; set; } = 0; public int LayoutSeed { get; set; } = 0; public int TerrainSeed { get; set; } = 0; public int NoiseSeed { get; set; } = 0; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Common.Data { public class OnionState { public bool Enabled { get; set; } = true; public bool CustomWorldSize { get; set; } = false; public int Width { get; set; } = 8; public int Height { get; set; } = 12; public bool Debug { get; set; } = false; public bool FreeCamera { get; set; } = true; public bool CustomMaxCameraDistance { get; set; } = true; public float MaxCameraDistance { get; set; } = 300; public bool LogSeed { get; set; } = true; public bool CustomSeeds { get; set; } = false; public int WorldSeed { get; set; } = 0; public int LayoutSeed { get; set; } = 0; public int TerrainSeed { get; set; } = 0; public int NoiseSeed { get; set; } = 0; } }
Add xml comment to TransitionType
// Copyright © 2010-2014 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. using System.Collections.Specialized; namespace CefSharp { public interface IRequest { string Url { get; set; } string Method { get; } string Body { get; } NameValueCollection Headers { get; set; } TransitionType TransitionType { get; } } }
// Copyright © 2010-2014 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. using System.Collections.Specialized; namespace CefSharp { public interface IRequest { string Url { get; set; } string Method { get; } string Body { get; } NameValueCollection Headers { get; set; } /// <summary> /// Get the transition type for this request. /// Applies to requests that represent a main frame or sub-frame navigation. /// </summary> TransitionType TransitionType { get; } } }
Add HardRock position mangling for CatchTheBeat
// 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.Game.Rulesets.Mods; namespace osu.Game.Rulesets.Catch.Mods { public class CatchModHardRock : ModHardRock { public override double ScoreMultiplier => 1.12; public override bool Ranked => true; } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.MathUtils; using osu.Game.Rulesets.Catch.Objects; using osu.Game.Rulesets.Mods; using System; namespace osu.Game.Rulesets.Catch.Mods { public class CatchModHardRock : ModHardRock, IApplicableToHitObject<CatchHitObject> { public override double ScoreMultiplier => 1.12; public override bool Ranked => true; private float lastStartX; private int lastStartTime; public void ApplyToHitObject(CatchHitObject hitObject) { // Code from Stable, we keep calculation on a scale of 0 to 512 float position = hitObject.X * 512; int startTime = (int)hitObject.StartTime; if (lastStartX == 0) { lastStartX = position; lastStartTime = startTime; return; } float diff = lastStartX - position; int timeDiff = startTime - lastStartTime; if (timeDiff > 1000) { lastStartX = position; lastStartTime = startTime; return; } if (diff == 0) { bool right = RNG.NextBool(); float rand = Math.Min(20, (float)RNG.NextDouble(0, timeDiff / 4)); if (right) { if (position + rand <= 512) position += rand; else position -= rand; } else { if (position - rand >= 0) position -= rand; else position += rand; } hitObject.X = position / 512; return; } if (Math.Abs(diff) < timeDiff / 3) { if (diff > 0) { if (position - diff > 0) position -= diff; } else { if (position - diff < 512) position -= diff; } } hitObject.X = position / 512; lastStartX = position; lastStartTime = startTime; } } }
Add BMP version to initiation message
using System; namespace BmpListener.Bmp { public class BmpInitiation : BmpMessage { public BmpInitiation(BmpHeader bmpHeader) : base(bmpHeader) { } } }
using System; namespace BmpListener.Bmp { public class BmpInitiation : BmpMessage { public BmpInitiation(BmpHeader bmpHeader) : base(bmpHeader) { BmpVersion = BmpHeader.Version; } public int BmpVersion { get; } } }
Implement text copying to Clipboard.
using System.Windows.Input; using Microsoft.Practices.Prism.Commands; namespace TimesheetParser { class MainViewModel { public ICommand CopyCommand { get; set; } public MainViewModel() { CopyCommand = new DelegateCommand<string>(CopyCommand_Executed); } void CopyCommand_Executed(string param) { } } }
using System.Windows; using System.Windows.Input; using Microsoft.Practices.Prism.Commands; namespace TimesheetParser { class MainViewModel { public ICommand CopyCommand { get; set; } public MainViewModel() { CopyCommand = new DelegateCommand<string>(CopyCommand_Executed); } void CopyCommand_Executed(string param) { Clipboard.SetData(DataFormats.UnicodeText, param); } } }
Hide the site report on really small screens.
@using DataAccess @using Localization @using WebApplication.Helpers @using WebGrease @model IEnumerable<DataAccess.Site> @{ ViewBag.Title = Resources.LabelSitesList; } @Html.Partial("_PageTitlePartial") <table class="table"> <tr> <th></th> <th> @Html.DisplayNameFor(model => model.Name) </th> <th class="hidden-sm">Postcode</th> <th class="hidden-xs">Features</th> <th style="font-weight:normal;">@Html.ActionLink("Create a New Site", "Create")</th> </tr> @foreach (var item in Model) { <tr> <td> @Html.ActionLink("Delete Site", "Delete", new { id = item.Id }) </td> <td> @Html.DisplayFor(modelItem => item.Name) </td> <td class="hidden-sm" style="text-transform:uppercase;">@Html.DisplayFor(modelItem => item.Postcode)</td> <td class="hidden-xs"> @Html.SiteSummaryIconsFor(item) </td> <td> @Html.ActionLink("Site Report", "Report", new { id = item.Id }) | @Html.ActionLink("Edit Site", "Edit", new { id = item.Id }) | @Html.ActionLink(Resources.LabelPerformanceData, "Index", "Months", new { id = item.Id }, null) </td> </tr> } </table>
@using DataAccess @using Localization @using WebApplication.Helpers @using WebGrease @model IEnumerable<DataAccess.Site> @{ ViewBag.Title = Resources.LabelSitesList; } @Html.Partial("_PageTitlePartial") <table class="table"> <tr> <th></th> <th> @Html.DisplayNameFor(model => model.Name) </th> <th class="hidden-sm hidden-xs">Postcode</th> <th class="hidden-xs">Features</th> <th style="font-weight:normal;">@Html.ActionLink("Create a New Site", "Create")</th> </tr> @foreach (var item in Model) { <tr> <td> @Html.ActionLink("Delete Site", "Delete", new { id = item.Id }) </td> <td> @Html.DisplayFor(modelItem => item.Name) </td> <td class="hidden-sm hidden-xs" style="text-transform:uppercase;">@Html.DisplayFor(modelItem => item.Postcode)</td> <td class="hidden-xs"> @Html.SiteSummaryIconsFor(item) </td> <td> <span class="hidden-xs">@Html.ActionLink("Site Report", "Report", new { id = item.Id }) | </span> @Html.ActionLink("Edit Site", "Edit", new { id = item.Id }) | @Html.ActionLink(Resources.LabelPerformanceData, "Index", "Months", new { id = item.Id }, null) </td> </tr> } </table>
Implement basic IRC Message without parsing IRC format yet
// // Copyright 2014 luke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; namespace WolfyBot.Core { public class IRCMessage { public IRCMessage () { } } }
// // Copyright 2014 luke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; namespace WolfyBot.Core { public class IRCMessage { #region Constructors /// <summary> /// Initializes a new instance of the <see cref="WolfyBot.Core.IRCMessage"/> class. /// </summary> /// <param name="ircMessage">A Message formatted in the IRC Protocol</param> public IRCMessage (String ircMessage) { TimeStamp = DateTime.Now; //TODO: write IRC Parser } //Copy Constructor public IRCMessage (IRCMessage other) { TimeStamp = other.TimeStamp; Prefix = new String (other.Prefix); Command = new String (other.Command); Parameters = new String (other.Parameters); TrailingParameters = new String (other.TrailingParameters); } #endregion #region Methods public String ToIRCString () { //TODO: Implement Serialization to IRC Protocol } public String ToLogString () { //TODO: Implement Serialization to logging format } #endregion #region Properties public String Prefix { get; set; } public String Command { get; set; } public String Parameters { get; set; } public String TrailingParameters { get; set; } public DateTime TimeStamp { get; set; } #endregion } }
Fix daemon event loop bugs
using System.Linq; using OdjfsScraper.Database; namespace OdjfsScraper.Tool.Support { public class DaemonEventLoop { private readonly Entities _ctx; public DaemonEventLoop(Entities ctx) { _ctx = ctx; UpdateCounts(); CurrentStep = 0; IsRunning = true; } public bool IsRunning { get; set; } public int CurrentStep { get; private set; } public int CountyCount { get; private set; } public int ChildCareCount { get; private set; } private int StepCount { get { return CountyCount + ChildCareCount; } } public int ChildCaresPerCounty { get { if (CountyCount == 0) { return 0; } return ChildCareCount/CountyCount; } } public bool IsCountyStep { get { if (ChildCaresPerCounty == 0) { return true; } return CurrentStep%ChildCaresPerCounty == 1; } } public bool IsChildCareStep { get { return !IsCountyStep; } } private void UpdateCounts() { CountyCount = _ctx.Counties.Count(); ChildCareCount = _ctx.ChildCares.Count(); } public bool NextStep() { CurrentStep = (CurrentStep + 1)%StepCount; if (CurrentStep == 0) { UpdateCounts(); } return IsRunning; } } }
using System.Linq; using OdjfsScraper.Database; namespace OdjfsScraper.Tool.Support { public class DaemonEventLoop { private readonly Entities _ctx; public DaemonEventLoop(Entities ctx) { _ctx = ctx; UpdateCounts(); CurrentStep = -1; IsRunning = true; } public bool IsRunning { get; set; } public int CurrentStep { get; private set; } public int CountyCount { get; private set; } public int ChildCareCount { get; private set; } private int StepCount { get { return CountyCount + ChildCareCount; } } public int ChildCaresPerCounty { get { if (CountyCount == 0) { return 0; } return ChildCareCount/CountyCount; } } public bool IsCountyStep { get { if (ChildCaresPerCounty == 0) { return true; } return CurrentStep%ChildCaresPerCounty == 1; } } public bool IsChildCareStep { get { return !IsCountyStep; } } private void UpdateCounts() { CountyCount = _ctx.Counties.Count(); ChildCareCount = _ctx.ChildCares.Count() + _ctx.ChildCareStubs.Count(); } public bool NextStep() { CurrentStep = (CurrentStep + 1)%StepCount; if (CurrentStep == 0) { UpdateCounts(); } return IsRunning; } } }
Add an IntentFilter to handle osu! files.
// 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 Android.App; using Android.Content.PM; using Android.OS; using Android.Views; using osu.Framework.Android; namespace osu.Android { [Activity(Theme = "@android:style/Theme.NoTitleBar", MainLauncher = true, ScreenOrientation = ScreenOrientation.FullUser, SupportsPictureInPicture = false, ConfigurationChanges = ConfigChanges.Orientation | ConfigChanges.ScreenSize, HardwareAccelerated = false)] public class OsuGameActivity : AndroidGameActivity { protected override Framework.Game CreateGame() => new OsuGameAndroid(this); protected override void OnCreate(Bundle savedInstanceState) { // The default current directory on android is '/'. // On some devices '/' maps to the app data directory. On others it maps to the root of the internal storage. // In order to have a consistent current directory on all devices the full path of the app data directory is set as the current directory. System.Environment.CurrentDirectory = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal); base.OnCreate(savedInstanceState); Window.AddFlags(WindowManagerFlags.Fullscreen); Window.AddFlags(WindowManagerFlags.KeepScreenOn); } } }
// 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 Android.App; using Android.Content; using Android.Content.PM; using Android.OS; using Android.Views; using osu.Framework.Android; namespace osu.Android { [Activity(Theme = "@android:style/Theme.NoTitleBar", MainLauncher = true, ScreenOrientation = ScreenOrientation.FullUser, SupportsPictureInPicture = false, ConfigurationChanges = ConfigChanges.Orientation | ConfigChanges.ScreenSize, HardwareAccelerated = false)] [IntentFilter(new[] { Intent.ActionDefault }, Categories = new[] { Intent.CategoryDefault, Intent.CategoryBrowsable, Intent.CategoryAppFiles }, DataSchemes = new[] { "content" }, DataPathPatterns = new[] { ".*\\.osz", ".*\\.osk" }, DataMimeType = "application/*")] public class OsuGameActivity : AndroidGameActivity { protected override Framework.Game CreateGame() => new OsuGameAndroid(this); protected override void OnCreate(Bundle savedInstanceState) { // The default current directory on android is '/'. // On some devices '/' maps to the app data directory. On others it maps to the root of the internal storage. // In order to have a consistent current directory on all devices the full path of the app data directory is set as the current directory. System.Environment.CurrentDirectory = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal); base.OnCreate(savedInstanceState); Window.AddFlags(WindowManagerFlags.Fullscreen); Window.AddFlags(WindowManagerFlags.KeepScreenOn); } } }
Change how yield works: treat more op types as "progress".
using System; using System.Collections.Generic; using System.Linq; namespace ActorTestingFramework { public class RandomScheduler : IScheduler { private readonly Random rand; public RandomScheduler(int seed) { rand = new Random(seed); } private static bool IsProgressOp(OpType op) { switch (op) { case OpType.INVALID: case OpType.START: case OpType.END: case OpType.CREATE: case OpType.JOIN: case OpType.WaitForDeadlock: case OpType.Yield: return false; case OpType.SEND: case OpType.RECEIVE: return true; default: throw new ArgumentOutOfRangeException(nameof(op), op, null); } } #region Implementation of IScheduler public ActorInfo GetNext(List<ActorInfo> actorList, ActorInfo currentActor) { if (currentActor.currentOp == OpType.Yield) { currentActor.enabled = false; } if (IsProgressOp(currentActor.currentOp)) { foreach (var actorInfo in actorList.Where(info => info.currentOp == OpType.Yield && !info.enabled)) { actorInfo.enabled = true; } } var enabled = actorList.Where(info => info.enabled).ToList(); if (enabled.Count == 0) { return null; } int nextIndex = rand.Next(enabled.Count - 1); return enabled[nextIndex]; } public void NextSchedule() { } #endregion } }
using System; using System.Collections.Generic; using System.Linq; namespace ActorTestingFramework { public class RandomScheduler : IScheduler { private readonly Random rand; public RandomScheduler(int seed) { rand = new Random(seed); } private static bool IsProgressOp(OpType op) { switch (op) { case OpType.INVALID: case OpType.WaitForDeadlock: case OpType.Yield: return false; case OpType.START: case OpType.END: case OpType.CREATE: case OpType.JOIN: case OpType.SEND: case OpType.RECEIVE: return true; default: throw new ArgumentOutOfRangeException(nameof(op), op, null); } } #region Implementation of IScheduler public ActorInfo GetNext(List<ActorInfo> actorList, ActorInfo currentActor) { if (currentActor.currentOp == OpType.Yield) { currentActor.enabled = false; } if (IsProgressOp(currentActor.currentOp)) { foreach (var actorInfo in actorList.Where(info => info.currentOp == OpType.Yield && !info.enabled)) { actorInfo.enabled = true; } } var enabled = actorList.Where(info => info.enabled).ToList(); if (enabled.Count == 0) { return null; } int nextIndex = rand.Next(enabled.Count - 1); return enabled[nextIndex]; } public void NextSchedule() { } #endregion } }
Fix an issue where ISerializable is not available on .NET Core
using System.Reflection; #if !NETCORE using System.Runtime.Serialization; #endif namespace Moq { /// <summary> /// A <see cref="IDefaultValueProvider"/> that returns an empty default value /// for serializable types that do not implement <see cref="ISerializable"/> properly, /// and returns the value provided by the decorated provider otherwise. /// </summary> internal class SerializableTypesValueProvider : IDefaultValueProvider { private readonly IDefaultValueProvider decorated; private readonly EmptyDefaultValueProvider emptyDefaultValueProvider = new EmptyDefaultValueProvider(); public SerializableTypesValueProvider(IDefaultValueProvider decorated) { this.decorated = decorated; } public void DefineDefault<T>(T value) { decorated.DefineDefault(value); } public object ProvideDefault(MethodInfo member) { return !member.ReturnType.GetTypeInfo().IsSerializable || member.ReturnType.IsSerializableMockable() ? decorated.ProvideDefault(member) : emptyDefaultValueProvider.ProvideDefault(member); } } }
using System.Reflection; #if !NETCORE using System.Runtime.Serialization; #endif namespace Moq { #if !NETCORE /// <summary> /// A <see cref="IDefaultValueProvider"/> that returns an empty default value /// for serializable types that do not implement <see cref="ISerializable"/> properly, /// and returns the value provided by the decorated provider otherwise. /// </summary> #else /// <summary> /// A <see cref="IDefaultValueProvider"/> that returns an empty default value /// for serializable types that do not implement ISerializable properly, /// and returns the value provided by the decorated provider otherwise. /// </summary> #endif internal class SerializableTypesValueProvider : IDefaultValueProvider { private readonly IDefaultValueProvider decorated; private readonly EmptyDefaultValueProvider emptyDefaultValueProvider = new EmptyDefaultValueProvider(); public SerializableTypesValueProvider(IDefaultValueProvider decorated) { this.decorated = decorated; } public void DefineDefault<T>(T value) { decorated.DefineDefault(value); } public object ProvideDefault(MethodInfo member) { return !member.ReturnType.GetTypeInfo().IsSerializable || member.ReturnType.IsSerializableMockable() ? decorated.ProvideDefault(member) : emptyDefaultValueProvider.ProvideDefault(member); } } }
Fix execution of windows app
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting.WindowsServices; using Resonance.Common.Web; using System.Diagnostics; using System.Linq; namespace Resonance.Windows { public class Program { public static void Main(string[] args) { var isService = !(Debugger.IsAttached || args.Contains("--console")); var host = ResonanceWebHostBuilderExtensions.GetWebHostBuilder() .UseStartup<Startup>() .UseApplicationInsights() .Build(); if (isService) { System.IO.Directory.SetCurrentDirectory(System.AppDomain.CurrentDomain.BaseDirectory); host.RunAsService(); } else { host.Run(); } } } }
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting.WindowsServices; using Resonance.Common.Web; using System.Diagnostics; using System.Linq; namespace Resonance.Windows { public class Program { public static void Main(string[] args) { System.IO.Directory.SetCurrentDirectory(System.AppDomain.CurrentDomain.BaseDirectory); var isService = !(Debugger.IsAttached || args.Contains("--console")); var host = ResonanceWebHostBuilderExtensions.GetWebHostBuilder() .UseStartup<Startup>() .UseApplicationInsights() .Build(); if (isService) { host.RunAsService(); } else { host.Run(); } } } }
Fix issue of singleton causing false-positives during running of full test-suite
using System; using System.Collections.Generic; namespace RimDev.Supurlative { public class SupurlativeOptions { public static readonly SupurlativeOptions Defaults = new SupurlativeOptions(); public UriKind UriKind { get; set; } public string PropertyNameSeperator { get; set; } public bool LowercaseKeys { get; set; } public SupurlativeOptions() { UriKind = UriKind.Absolute; PropertyNameSeperator = "."; Formatters = new List<BaseFormatterAttribute>(); LowercaseKeys = true; } public void Validate() { if (UriKind == UriKind.RelativeOrAbsolute) throw new ArgumentException("must choose between relative or absolute", "UriKind"); if (PropertyNameSeperator == null) throw new ArgumentNullException("PropertyNameSeperator", "seperator must not be null"); } public IList<BaseFormatterAttribute> Formatters { get; protected set; } public SupurlativeOptions AddFormatter(BaseFormatterAttribute formatter) { if (formatter == null) throw new ArgumentNullException("formatter"); Formatters.Add(formatter); return this; } public SupurlativeOptions AddFormatter<T>() where T : BaseFormatterAttribute { return AddFormatter(Activator.CreateInstance<T>()); } public SupurlativeOptions AddFormatter<T>(Func<T, string> func) { return AddFormatter(new LambdaFormatter(typeof(T), (x) => func((T)x))); } } }
using System; using System.Collections.Generic; namespace RimDev.Supurlative { public class SupurlativeOptions { public static SupurlativeOptions Defaults { get { return new SupurlativeOptions(); } } public UriKind UriKind { get; set; } public string PropertyNameSeperator { get; set; } public bool LowercaseKeys { get; set; } public SupurlativeOptions() { UriKind = UriKind.Absolute; PropertyNameSeperator = "."; Formatters = new List<BaseFormatterAttribute>(); LowercaseKeys = true; } public void Validate() { if (UriKind == UriKind.RelativeOrAbsolute) throw new ArgumentException("must choose between relative or absolute", "UriKind"); if (PropertyNameSeperator == null) throw new ArgumentNullException("PropertyNameSeperator", "seperator must not be null"); } public IList<BaseFormatterAttribute> Formatters { get; protected set; } public SupurlativeOptions AddFormatter(BaseFormatterAttribute formatter) { if (formatter == null) throw new ArgumentNullException("formatter"); Formatters.Add(formatter); return this; } public SupurlativeOptions AddFormatter<T>() where T : BaseFormatterAttribute { return AddFormatter(Activator.CreateInstance<T>()); } public SupurlativeOptions AddFormatter<T>(Func<T, string> func) { return AddFormatter(new LambdaFormatter(typeof(T), (x) => func((T)x))); } } }
Add way to record usage, fix LoadAllGifsAsync
using Microsoft.Data.Entity; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GifWin.Data { class GifWinDatabaseHelper : IDisposable { GifWinContext db; public GifWinDatabaseHelper() { db = new GifWinContext(); } public async Task<int> ConvertGifWitLibraryAsync(GifWitLibrary librarySource) { foreach (var entry in librarySource) { var newGif = new GifEntry { Url = entry.Url.ToString(), AddedAt = DateTimeOffset.UtcNow, }; foreach (var tag in entry.KeywordString.Split(' ')) { newGif.Tags.Add(new GifTag { Tag = tag }); } db.Gifs.Add(newGif); } return await db.SaveChangesAsync().ConfigureAwait(false); } public async Task<IEnumerable<GifEntry>> LoadAllGifsAsync() { return await db.Gifs.Include(ge => ge.Tags).ToArrayAsync().ConfigureAwait(false); } private bool disposedValue = false; protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { db.Dispose(); } disposedValue = true; } } public void Dispose() { Dispose(true); } } }
using Microsoft.Data.Entity; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GifWin.Data { class GifWinDatabaseHelper : IDisposable { GifWinContext db; public GifWinDatabaseHelper() { db = new GifWinContext(); } public async Task<int> ConvertGifWitLibraryAsync(GifWitLibrary librarySource) { foreach (var entry in librarySource) { var newGif = new GifEntry { Url = entry.Url.ToString(), AddedAt = DateTimeOffset.UtcNow, }; foreach (var tag in entry.KeywordString.Split(' ')) { newGif.Tags.Add(new GifTag { Tag = tag }); } db.Gifs.Add(newGif); } return await db.SaveChangesAsync().ConfigureAwait(false); } public async Task RecordGifUsageAsync(int gifId) { var gif = await db.Gifs.SingleOrDefaultAsync(ge => ge.Id == gifId).ConfigureAwait(false); if (gif != null) { var ts = DateTimeOffset.UtcNow; var usage = new GifUsage(); gif.LastUsed = usage.UsedAt = ts; gif.Usages.Add(usage); await db.SaveChangesAsync().ConfigureAwait(false); } } public async Task<IQueryable<GifEntry>> LoadAllGifsAsync() { var query = db.Gifs.Include(ge => ge.Tags); await query.LoadAsync().ConfigureAwait(false); return query; } private bool disposedValue = false; protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { db.Dispose(); } disposedValue = true; } } public void Dispose() { Dispose(true); } } }
Use `TaskHelper` instead of TCS
using System; using System.Threading.Tasks; namespace MicroFlow { public abstract class SyncActivity<TResult> : Activity<TResult> { public sealed override Task<TResult> Execute() { var tcs = new TaskCompletionSource<TResult>(); try { TResult result = ExecuteActivity(); tcs.TrySetResult(result); } catch (Exception ex) { tcs.TrySetException(ex); } return tcs.Task; } protected abstract TResult ExecuteActivity(); } public abstract class SyncActivity : Activity { protected sealed override Task ExecuteCore() { var tcs = new TaskCompletionSource<Null>(); try { ExecuteActivity(); tcs.TrySetResult(null); } catch (Exception ex) { tcs.TrySetException(ex); } return tcs.Task; } protected abstract void ExecuteActivity(); } }
using System; using System.Threading.Tasks; namespace MicroFlow { public abstract class SyncActivity<TResult> : Activity<TResult> { public sealed override Task<TResult> Execute() { try { TResult result = ExecuteActivity(); return TaskHelper.FromResult(result); } catch (Exception ex) { return TaskHelper.FromException<TResult>(ex); } } protected abstract TResult ExecuteActivity(); } public abstract class SyncActivity : Activity { protected sealed override Task ExecuteCore() { try { ExecuteActivity(); return TaskHelper.CompletedTask; } catch (Exception ex) { return TaskHelper.FromException(ex); } } protected abstract void ExecuteActivity(); } }
Bring back setting the app name based on the package info
using Newtonsoft.Json; using ReactiveUI.Mobile; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Akavache.Mobile { public class Registrations : IWantsToRegisterStuff { public void Register(Action<Func<object>, Type, string> registerFunction) { registerFunction(() => new JsonSerializerSettings() { ObjectCreationHandling = ObjectCreationHandling.Replace, ReferenceLoopHandling = ReferenceLoopHandling.Ignore, TypeNameHandling = TypeNameHandling.All, }, typeof(JsonSerializerSettings), null); var akavacheDriver = new AkavacheDriver(); registerFunction(() => akavacheDriver, typeof(ISuspensionDriver), null); #if APPKIT || UIKIT registerFunction(() => new MacFilesystemProvider(), typeof(IFilesystemProvider), null); #endif #if ANDROID registerFunction(() => new AndroidFilesystemProvider(), typeof(IFilesystemProvider), null); #endif } } }
using Newtonsoft.Json; using ReactiveUI.Mobile; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; #if UIKIT using MonoTouch.Foundation; using ReactiveUI.Mobile; #endif #if APPKIT using MonoMac.Foundation; #endif #if ANDROID using Android.App; #endif #if APPKIT namespace Akavache.Mac #else namespace Akavache.Mobile #endif { public class Registrations : IWantsToRegisterStuff { public void Register(Action<Func<object>, Type, string> registerFunction) { registerFunction(() => new JsonSerializerSettings() { ObjectCreationHandling = ObjectCreationHandling.Replace, ReferenceLoopHandling = ReferenceLoopHandling.Ignore, TypeNameHandling = TypeNameHandling.All, }, typeof(JsonSerializerSettings), null); var akavacheDriver = new AkavacheDriver(); registerFunction(() => akavacheDriver, typeof(ISuspensionDriver), null); #if APPKIT || UIKIT BlobCache.ApplicationName = NSBundle.MainBundle.BundleIdentifier; registerFunction(() => new MacFilesystemProvider(), typeof(IFilesystemProvider), null); #endif #if ANDROID var ai = Application.Context.PackageManager.GetApplicationInfo(Application.Context.PackageName, 0); BlobCache.ApplicationName = ai.LoadLabel(Application.Context.PackageManager); registerFunction(() => new AndroidFilesystemProvider(), typeof(IFilesystemProvider), null); #endif } } }
Add Warning value to the enumeration.
namespace HtmlLogger.Model { public enum LogCategory { Info, Error } }
namespace HtmlLogger.Model { public enum LogCategory { Info, Warning, Error } }
Update the assembly version for LibPhoneNumber.Contrib since we added a new extension method.
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("LibPhoneNumber.Contrib")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("LibPhoneNumber.Contrib")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("9ea084a1-6add-4b90-97fe-5ec441b8cb76")] [assembly: AssemblyVersion(AssemblyMeta.Version)] [assembly: AssemblyFileVersion(AssemblyMeta.Version)] [assembly: AssemblyInformationalVersion(AssemblyMeta.Version)] internal static class AssemblyMeta { public const string Version = "1.1.2"; }
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("LibPhoneNumber.Contrib")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("LibPhoneNumber.Contrib")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("9ea084a1-6add-4b90-97fe-5ec441b8cb76")] [assembly: AssemblyVersion(AssemblyMeta.Version)] [assembly: AssemblyFileVersion(AssemblyMeta.Version)] [assembly: AssemblyInformationalVersion(AssemblyMeta.Version)] internal static class AssemblyMeta { public const string Version = "1.2.0"; }
Fix code as suggested by compiler.
using ServiceStack.OrmLite; namespace Nonagon.Modular { /// <summary> /// Data module interface base class. /// </summary> public abstract class DataModuleInterface : ModuleInterface, IDataModuleInterface { /// <summary> /// Gets or sets the db connection factory. /// </summary> /// <value>The db connection factory.</value> public IDbConnectionFactory DbConnectionFactory { get; private set; } public DataModuleInterface(IDbConnectionFactory dbConnectionFactory) { DbConnectionFactory = dbConnectionFactory; } /// <summary> /// Resolve the instance of operation from type parameter. /// </summary> /// <typeparam name="TOperation">The IDataModuleOperation to be instantiated.</typeparam> protected override TOperation Resolve<TOperation>() { TOperation opt = base.Resolve<TOperation>(); if(opt is IDataModuleOperation) (opt as IDataModuleOperation).DbConnectionFactory = DbConnectionFactory; return opt; } } }
using ServiceStack.OrmLite; namespace Nonagon.Modular { /// <summary> /// Data module interface base class. /// </summary> public abstract class DataModuleInterface : ModuleInterface, IDataModuleInterface { /// <summary> /// Gets or sets the db connection factory. /// </summary> /// <value>The db connection factory.</value> public IDbConnectionFactory DbConnectionFactory { get; private set; } protected DataModuleInterface(IDbConnectionFactory dbConnectionFactory) { DbConnectionFactory = dbConnectionFactory; } /// <summary> /// Resolve the instance of operation from type parameter. /// </summary> /// <typeparam name="TOperation">The IDataModuleOperation to be instantiated.</typeparam> protected override TOperation Resolve<TOperation>() { TOperation opt = base.Resolve<TOperation>(); var iDataModuleOperation = opt as IDataModuleOperation; if(iDataModuleOperation != null) iDataModuleOperation.DbConnectionFactory = DbConnectionFactory; return opt; } } }
Update alias in usage examples
using System.Collections.Generic; using CommandLine; using CommandLine.Text; namespace dotnet_setversion { public class Options { [Option('r', "recursive", Default = false, HelpText = "Recursively search the current directory for csproj files and apply the given version to all files found. " + "Mutually exclusive to the csprojFile argument.")] public bool Recursive { get; set; } [Value(0, MetaName = "version", HelpText = "The version to apply to the given csproj file(s).", Required = true)] public string Version { get; set; } [Value(1, MetaName = "csprojFile", Required = false, HelpText = "Path to a csproj file to apply the given version. Mutually exclusive to the --recursive option.")] public string CsprojFile { get; set; } [Usage(ApplicationAlias = "dotnet setversion")] public static IEnumerable<Example> Examples { get { yield return new Example("Directory with a single csproj file", new Options {Version = "1.2.3"}); yield return new Example("Explicitly specifying a csproj file", new Options {Version = "1.2.3", CsprojFile = "MyProject.csproj"}); yield return new Example("Large repo with multiple csproj files in nested directories", new UnParserSettings {PreferShortName = true}, new Options {Version = "1.2.3", Recursive = true}); } } } }
using System.Collections.Generic; using CommandLine; using CommandLine.Text; namespace dotnet_setversion { public class Options { [Option('r', "recursive", Default = false, HelpText = "Recursively search the current directory for csproj files and apply the given version to all files found. " + "Mutually exclusive to the csprojFile argument.")] public bool Recursive { get; set; } [Value(0, MetaName = "version", HelpText = "The version to apply to the given csproj file(s).", Required = true)] public string Version { get; set; } [Value(1, MetaName = "csprojFile", Required = false, HelpText = "Path to a csproj file to apply the given version. Mutually exclusive to the --recursive option.")] public string CsprojFile { get; set; } [Usage(ApplicationAlias = "setversion")] public static IEnumerable<Example> Examples { get { yield return new Example("Directory with a single csproj file", new Options {Version = "1.2.3"}); yield return new Example("Explicitly specifying a csproj file", new Options {Version = "1.2.3", CsprojFile = "MyProject.csproj"}); yield return new Example("Large repo with multiple csproj files in nested directories", new UnParserSettings {PreferShortName = true}, new Options {Version = "1.2.3", Recursive = true}); } } } }
Fix out of range exceptions due to out-of-order hitobjects.
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Game.Rulesets.Beatmaps; using osu.Game.Rulesets.Mania.Objects; using System; using System.Collections.Generic; using osu.Game.Beatmaps; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Objects.Types; using System.Linq; namespace osu.Game.Rulesets.Mania.Beatmaps { public class ManiaBeatmapConverter : BeatmapConverter<ManiaHitObject> { protected override IEnumerable<Type> ValidConversionTypes { get; } = new[] { typeof(IHasXPosition) }; protected override Beatmap<ManiaHitObject> ConvertBeatmap(Beatmap original) { // Todo: This should be cased when we get better conversion methods var converter = new LegacyConverter(original); return new Beatmap<ManiaHitObject> { BeatmapInfo = original.BeatmapInfo, TimingInfo = original.TimingInfo, HitObjects = original.HitObjects.SelectMany(converter.Convert).ToList() }; } protected override IEnumerable<ManiaHitObject> ConvertHitObject(HitObject original, Beatmap beatmap) { // Handled by the LegacyConvereter yield return null; } } }
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Game.Rulesets.Beatmaps; using osu.Game.Rulesets.Mania.Objects; using System; using System.Collections.Generic; using osu.Game.Beatmaps; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Objects.Types; using System.Linq; namespace osu.Game.Rulesets.Mania.Beatmaps { public class ManiaBeatmapConverter : BeatmapConverter<ManiaHitObject> { protected override IEnumerable<Type> ValidConversionTypes { get; } = new[] { typeof(IHasXPosition) }; protected override Beatmap<ManiaHitObject> ConvertBeatmap(Beatmap original) { // Todo: This should be cased when we get better conversion methods var converter = new LegacyConverter(original); return new Beatmap<ManiaHitObject> { BeatmapInfo = original.BeatmapInfo, TimingInfo = original.TimingInfo, // We need to sort here, because the converter generates patterns HitObjects = original.HitObjects.SelectMany(converter.Convert).OrderBy(h => h.StartTime).ToList() }; } protected override IEnumerable<ManiaHitObject> ConvertHitObject(HitObject original, Beatmap beatmap) { // Handled by the LegacyConvereter yield return null; } } }
Allow payments to be marked as reconciled
using System; namespace XeroApi.Model { public class Payment : EndpointModelBase { [ItemId] public Guid? PaymentID { get; set; } public DateTime Date { get; set; } public decimal Amount { get; set; } public string Reference { get; set; } public decimal? CurrencyRate { get; set; } public string PaymentType { get; set; } public string Status { get; set; } [ItemUpdatedDate] public DateTime? UpdatedDateUTC { get; set; } public Account Account { get; set; } public Invoice Invoice { get; set; } } public class Payments : ModelList<Payment> { } }
using System; namespace XeroApi.Model { public class Payment : EndpointModelBase { [ItemId] public Guid? PaymentID { get; set; } public DateTime Date { get; set; } public decimal Amount { get; set; } public string Reference { get; set; } public decimal? CurrencyRate { get; set; } public string PaymentType { get; set; } public string Status { get; set; } public bool IsReconciled { get; set; } [ItemUpdatedDate] public DateTime? UpdatedDateUTC { get; set; } public Account Account { get; set; } public Invoice Invoice { get; set; } } public class Payments : ModelList<Payment> { } }
Update code generator relative filepath
using System; using System.IO; namespace LibSassGen { public partial class CodeGenerator { private const string DefaultIncludeDir = @"../../../../../libsass/include"; private const string DefaultOutputFilePath = @"../../../../SharpScss/LibSass.Generated.cs"; private const int IndentMultiplier = 4; private int _indentLevel; private TextWriter _writer; private TextWriter _writerBody; private TextWriter _writerGlobal; public bool OutputToConsole { get; set; } public void Run() { var outputFilePath = Path.Combine(Environment.CurrentDirectory, DefaultOutputFilePath); outputFilePath = Path.GetFullPath(outputFilePath); _writerGlobal = new StringWriter(); _writerBody = new StringWriter(); ParseAndWrite(); var finalWriter = OutputToConsole ? Console.Out : new StreamWriter(outputFilePath); finalWriter.Write(_writerGlobal); if (!OutputToConsole) { finalWriter.Flush(); finalWriter.Dispose(); finalWriter = null; } } } }
using System; using System.IO; namespace LibSassGen { public partial class CodeGenerator { private const string DefaultIncludeDir = @"../../../../libsass/include"; private const string DefaultOutputFilePath = @"../../../SharpScss/LibSass.Generated.cs"; private const int IndentMultiplier = 4; private int _indentLevel; private TextWriter _writer; private TextWriter _writerBody; private TextWriter _writerGlobal; public bool OutputToConsole { get; set; } public void Run() { var outputFilePath = Path.Combine(Environment.CurrentDirectory, DefaultOutputFilePath); outputFilePath = Path.GetFullPath(outputFilePath); _writerGlobal = new StringWriter(); _writerBody = new StringWriter(); ParseAndWrite(); var finalWriter = OutputToConsole ? Console.Out : new StreamWriter(outputFilePath); finalWriter.Write(_writerGlobal); if (!OutputToConsole) { finalWriter.Flush(); finalWriter.Dispose(); finalWriter = null; } } } }
Make main program class static
using System; using System.IO; using System.Security.Cryptography; using Mono.Security; using Mono.Security.Cryptography; namespace Xpdm.PurpleOnion { class Program { private static void Main() { long count = 0; while (true) { RSA pki = RSA.Create(); ASN1 asn = RSAExtensions.ToAsn1Key(pki); byte[] hash = SHA1CryptoServiceProvider.Create().ComputeHash(asn.GetBytes()); string onion = ConvertExtensions.FromBytesToBase32String(hash).Substring(0,16).ToLowerInvariant(); if (onion.Contains("tor") || onion.Contains("mirror")) { Console.WriteLine("Found: " + onion); Directory.CreateDirectory(onion); File.WriteAllText(Path.Combine(onion, "pki.xml"), pki.ToXmlString(true)); File.WriteAllText(Path.Combine(onion, "private_key"), System.Convert.ToBase64String(PKCS8.PrivateKeyInfo.Encode(pki))); File.WriteAllText(Path.Combine(onion, "hostname"), onion + ".onion"); } Console.WriteLine(onion + " " + ++count); } } } }
using System; using System.IO; using System.Security.Cryptography; using Mono.Security; using Mono.Security.Cryptography; namespace Xpdm.PurpleOnion { static class Program { private static void Main() { long count = 0; while (true) { RSA pki = RSA.Create(); ASN1 asn = RSAExtensions.ToAsn1Key(pki); byte[] hash = SHA1CryptoServiceProvider.Create().ComputeHash(asn.GetBytes()); string onion = ConvertExtensions.FromBytesToBase32String(hash).Substring(0,16).ToLowerInvariant(); if (onion.Contains("tor") || onion.Contains("mirror")) { Console.WriteLine("Found: " + onion); Directory.CreateDirectory(onion); File.WriteAllText(Path.Combine(onion, "pki.xml"), pki.ToXmlString(true)); File.WriteAllText(Path.Combine(onion, "private_key"), System.Convert.ToBase64String(PKCS8.PrivateKeyInfo.Encode(pki))); File.WriteAllText(Path.Combine(onion, "hostname"), onion + ".onion"); } Console.WriteLine(onion + " " + ++count); } } } }
Fix crash when clearing resetting template
using System; using System.Resources; using System.Windows.Data; namespace GoldenAnvil.Utility.Windows { public sealed class EnumToDisplayStringConverter : IValueConverter { public static readonly EnumToDisplayStringConverter Instance = new EnumToDisplayStringConverter(); public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (!(parameter is ResourceManager resources)) throw new ArgumentException($"{nameof(parameter)} must be a ResourceManager."); var method = typeof(ResourceManagerUtility).GetMethod("EnumToDisplayString"); var generic = method.MakeGenericMethod(value.GetType()); return generic.Invoke(null, new [] { resources, value }); } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } }
using System; using System.Resources; using System.Windows.Data; namespace GoldenAnvil.Utility.Windows { public sealed class EnumToDisplayStringConverter : IValueConverter { public static readonly EnumToDisplayStringConverter Instance = new EnumToDisplayStringConverter(); public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (!(parameter is ResourceManager resources)) throw new ArgumentException($"{nameof(parameter)} must be a ResourceManager."); // sometimes an empty string can be passed instead of a null value if (value is string stringValue) { if (stringValue == "") return null; } var method = typeof(ResourceManagerUtility).GetMethod("EnumToDisplayString"); var generic = method.MakeGenericMethod(value.GetType()); return generic.Invoke(null, new [] { resources, value }); } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } }
Remove obsolete methods and add sumary texts.
using System; using System.Data; namespace Smooth.IoC.Dapper.Repository.UnitOfWork.Data { public interface IDbFactory { /// <summary> /// Creates an instance of your ISession expanded interface /// </summary> /// <typeparam name="T"></typeparam> /// <returns>ISession</returns> T Create<T>() where T : class, ISession; [Obsolete] T CreateSession<T>() where T : class, ISession; TUnitOfWork Create<TUnitOfWork, TSession>(IsolationLevel isolationLevel= IsolationLevel.Serializable) where TUnitOfWork : class, IUnitOfWork where TSession : class, ISession; T Create<T>(IDbFactory factory, ISession session, IsolationLevel isolationLevel = IsolationLevel.Serializable) where T : class, IUnitOfWork; void Release(IDisposable instance); } }
using System; using System.Data; namespace Smooth.IoC.Dapper.Repository.UnitOfWork.Data { public interface IDbFactory { /// <summary> /// Creates an instance of your ISession expanded interface /// </summary> /// <typeparam name="T"></typeparam> /// <returns>ISession</returns> T Create<T>() where T : class, ISession; /// <summary> /// Creates a UnitOfWork and Session at same time. The session has the same scope as the unit of work. /// </summary> /// <param name="isolationLevel"></param> /// <typeparam name="TUnitOfWork"></typeparam> /// <typeparam name="TSession"></typeparam> /// <returns></returns> TUnitOfWork Create<TUnitOfWork, TSession>(IsolationLevel isolationLevel= IsolationLevel.Serializable) where TUnitOfWork : class, IUnitOfWork where TSession : class, ISession; /// <summary> /// Used for Session base to create UnitOfWork. Not recommeded to use in other code /// </summary> /// <param name="factory"></param> /// <param name="session"></param> /// <param name="isolationLevel"></param> /// <typeparam name="T"></typeparam> /// <returns></returns> T Create<T>(IDbFactory factory, ISession session, IsolationLevel isolationLevel = IsolationLevel.Serializable) where T : class, IUnitOfWork; /// <summary> /// Release the component. Done by Sessnion and UnitOfWork on there own. /// </summary> /// <param name="instance"></param> void Release(IDisposable instance); } }
Change default user agent for web views
using CefSharp; using CefSharp.Wpf; using Playnite.Common; using Playnite.Settings; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Playnite { public class CefTools { public static bool IsInitialized { get; private set; } public static void ConfigureCef() { FileSystem.CreateDirectory(PlaynitePaths.BrowserCachePath); var settings = new CefSettings(); settings.WindowlessRenderingEnabled = true; if (settings.CefCommandLineArgs.ContainsKey("disable-gpu")) { settings.CefCommandLineArgs.Remove("disable-gpu"); } if (settings.CefCommandLineArgs.ContainsKey("disable-gpu-compositing")) { settings.CefCommandLineArgs.Remove("disable-gpu-compositing"); } settings.CefCommandLineArgs.Add("disable-gpu", "1"); settings.CefCommandLineArgs.Add("disable-gpu-compositing", "1"); settings.CachePath = PlaynitePaths.BrowserCachePath; settings.PersistSessionCookies = true; settings.LogFile = Path.Combine(PlaynitePaths.ConfigRootPath, "cef.log"); IsInitialized = Cef.Initialize(settings); } public static void Shutdown() { Cef.Shutdown(); IsInitialized = false; } } }
using CefSharp; using CefSharp.Wpf; using Playnite.Common; using Playnite.Settings; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Playnite { public class CefTools { public static bool IsInitialized { get; private set; } public static void ConfigureCef() { FileSystem.CreateDirectory(PlaynitePaths.BrowserCachePath); var settings = new CefSettings(); settings.WindowlessRenderingEnabled = true; if (settings.CefCommandLineArgs.ContainsKey("disable-gpu")) { settings.CefCommandLineArgs.Remove("disable-gpu"); } if (settings.CefCommandLineArgs.ContainsKey("disable-gpu-compositing")) { settings.CefCommandLineArgs.Remove("disable-gpu-compositing"); } settings.CefCommandLineArgs.Add("disable-gpu", "1"); settings.CefCommandLineArgs.Add("disable-gpu-compositing", "1"); settings.CachePath = PlaynitePaths.BrowserCachePath; settings.PersistSessionCookies = true; settings.LogFile = Path.Combine(PlaynitePaths.ConfigRootPath, "cef.log"); settings.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:86.0) Gecko/20100101 Firefox/86.0"; IsInitialized = Cef.Initialize(settings); } public static void Shutdown() { Cef.Shutdown(); IsInitialized = false; } } }
Delete override keyword from Equals method to indicate that this method implement interface
using System; using System.Collections.Generic; namespace TirkxDownloader.Framework { public sealed class Pair<TFirst, TSecond> : IEquatable<Pair<TFirst, TSecond>> { private readonly TFirst first; private readonly TSecond second; public Pair(TFirst first, TSecond second) { this.first = first; this.second = second; } public TFirst First { get { return first; } } public TSecond Second { get { return second; } } public override bool Equals(Pair<TFirst, TSecond> other) { if (other == null) { return false; } return EqualityComparer<TFirst>.Default.Equals(first, other.first) && EqualityComparer<TSecond>.Default.Equals(second, other.second); } public override int GetHashCode() { return EqualityComparer<TFirst>.Default.GetHashCode(first) * 37 + EqualityComparer<TSecond>.Default.GetHashCode(second); } } }
using System; using System.Collections.Generic; namespace TirkxDownloader.Framework { public sealed class Pair<TFirst, TSecond> : IEquatable<Pair<TFirst, TSecond>> { private readonly TFirst first; private readonly TSecond second; public Pair(TFirst first, TSecond second) { this.first = first; this.second = second; } public TFirst First { get { return first; } } public TSecond Second { get { return second; } } public bool Equals(Pair<TFirst, TSecond> other) { if (other == null) { return false; } return EqualityComparer<TFirst>.Default.Equals(first, other.first) && EqualityComparer<TSecond>.Default.Equals(second, other.second); } public override int GetHashCode() { return EqualityComparer<TFirst>.Default.GetHashCode(first) * 37 + EqualityComparer<TSecond>.Default.GetHashCode(second); } } }
Return instead of using a variable.
using System; using System.IO; using System.Text; using System.Xml; using System.Xml.Schema; using NUnit.Framework; namespace SharpBrake.Tests { public class AirbrakeValidator { public static void ValidateSchema(string xml) { var schema = GetXmlSchema(); XmlReaderSettings settings = new XmlReaderSettings { ValidationType = ValidationType.Schema, }; var errorBuffer = new StringBuilder(); settings.ValidationEventHandler += (sender, args) => errorBuffer.AppendLine(args.Message); settings.Schemas.Add(schema); using (var reader = new StringReader(xml)) { using (var xmlReader = new XmlTextReader(reader)) { using (var validator = XmlReader.Create(xmlReader, settings)) { while (validator.Read()) { } } } } if (errorBuffer.Length > 0) Assert.Fail(errorBuffer.ToString()); } private static XmlSchema GetXmlSchema() { const string xsd = "hoptoad_2_1.xsd"; Type clientType = typeof(AirbrakeClient); XmlSchema schema; using (Stream schemaStream = clientType.Assembly.GetManifestResourceStream(clientType, xsd)) { if (schemaStream == null) Assert.Fail("{0}.{1} not found.", clientType.Namespace, xsd); schema = XmlSchema.Read(schemaStream, (sender, args) => { }); } return schema; } } }
using System; using System.IO; using System.Text; using System.Xml; using System.Xml.Schema; using NUnit.Framework; namespace SharpBrake.Tests { public class AirbrakeValidator { public static void ValidateSchema(string xml) { var schema = GetXmlSchema(); XmlReaderSettings settings = new XmlReaderSettings { ValidationType = ValidationType.Schema, }; var errorBuffer = new StringBuilder(); settings.ValidationEventHandler += (sender, args) => errorBuffer.AppendLine(args.Message); settings.Schemas.Add(schema); using (var reader = new StringReader(xml)) { using (var xmlReader = new XmlTextReader(reader)) { using (var validator = XmlReader.Create(xmlReader, settings)) { while (validator.Read()) { } } } } if (errorBuffer.Length > 0) Assert.Fail(errorBuffer.ToString()); } private static XmlSchema GetXmlSchema() { Type clientType = typeof(AirbrakeClient); const string xsd = "hoptoad_2_1.xsd"; using (Stream schemaStream = clientType.Assembly.GetManifestResourceStream(clientType, xsd)) { if (schemaStream == null) Assert.Fail("{0}.{1} not found.", clientType.Namespace, xsd); return XmlSchema.Read(schemaStream, (sender, args) => { }); } } } }
Update vendor api to ensure task returned
using Alexa.NET.Management.Vendors; using Refit; namespace Alexa.NET.Management { [Headers("Authorization: Bearer")] public interface IVendorApi { [Get("/vendors")] Vendor[] Get(); } }
using System.Threading.Tasks; using Alexa.NET.Management.Vendors; using Refit; namespace Alexa.NET.Management { [Headers("Authorization: Bearer")] public interface IVendorApi { [Get("/vendors")] Task<Vendor[]> Get(); } }
Remove old XNAControls code from initialization. Crash & burn if old XNAControls are used.
// Original Work Copyright (c) Ethan Moffat 2014-2016 // This file is subject to the GPL v2 License // For additional details, see the LICENSE file using EndlessClient.GameExecution; using EOLib.DependencyInjection; using Microsoft.Practices.Unity; using Microsoft.Xna.Framework; namespace EndlessClient { public class XNAControlsDependencyContainer : IInitializableContainer { public void RegisterDependencies(IUnityContainer container) { } public void InitializeDependencies(IUnityContainer container) { var game = (Game)container.Resolve<IEndlessGame>(); XNAControls.GameRepository.SetGame(game); //todo: remove this once converted to new XNAControls code XNAControls.Old.XNAControls.Initialize(game); XNAControls.Old.XNAControls.IgnoreEnterForDialogs = true; XNAControls.Old.XNAControls.IgnoreEscForDialogs = true; } } }
// Original Work Copyright (c) Ethan Moffat 2014-2016 // This file is subject to the GPL v2 License // For additional details, see the LICENSE file using EndlessClient.GameExecution; using EOLib.DependencyInjection; using Microsoft.Practices.Unity; using Microsoft.Xna.Framework; namespace EndlessClient { public class XNAControlsDependencyContainer : IInitializableContainer { public void RegisterDependencies(IUnityContainer container) { } public void InitializeDependencies(IUnityContainer container) { var game = (Game)container.Resolve<IEndlessGame>(); XNAControls.GameRepository.SetGame(game); } } }
Set preUpdate to null with the rest of the hooks.
using System; using System.Collections.Generic; using System.Linq; using Prism.API; namespace Prism.Mods.Hooks { class ModDefHooks : IHookManager { IEnumerable<Action> onAllModsLoaded, onUnload , preUpdate , postUpdate ; public void Create() { onAllModsLoaded = HookManager.CreateHooks<ModDef, Action>(ModData.mods.Values, "OnAllModsLoaded"); onUnload = HookManager.CreateHooks<ModDef, Action>(ModData.mods.Values, "OnUnload" ); preUpdate = HookManager.CreateHooks<ModDef, Action>(ModData.mods.Values, "PreUpdate" ); postUpdate = HookManager.CreateHooks<ModDef, Action>(ModData.mods.Values, "PostUpdate" ); } public void Clear () { onAllModsLoaded = null; onUnload = null; postUpdate = null; } public void OnAllModsLoaded() { HookManager.Call(onAllModsLoaded); } public void OnUnload () { HookManager.Call(onUnload); } public void PreUpdate () { HookManager.Call(preUpdate); } public void PostUpdate () { HookManager.Call(postUpdate); } } }
using System; using System.Collections.Generic; using System.Linq; using Prism.API; namespace Prism.Mods.Hooks { class ModDefHooks : IHookManager { IEnumerable<Action> onAllModsLoaded, onUnload , preUpdate , postUpdate ; public void Create() { onAllModsLoaded = HookManager.CreateHooks<ModDef, Action>(ModData.mods.Values, "OnAllModsLoaded"); onUnload = HookManager.CreateHooks<ModDef, Action>(ModData.mods.Values, "OnUnload" ); preUpdate = HookManager.CreateHooks<ModDef, Action>(ModData.mods.Values, "PreUpdate" ); postUpdate = HookManager.CreateHooks<ModDef, Action>(ModData.mods.Values, "PostUpdate" ); } public void Clear () { onAllModsLoaded = null; onUnload = null; preUpdate = null; postUpdate = null; } public void OnAllModsLoaded() { HookManager.Call(onAllModsLoaded); } public void OnUnload () { HookManager.Call(onUnload); } public void PreUpdate () { HookManager.Call(preUpdate); } public void PostUpdate () { HookManager.Call(postUpdate); } } }
Fix PublishedSnapshotAccessor to not throw but return null
using System; namespace Umbraco.Web.PublishedCache { public class UmbracoContextPublishedSnapshotAccessor : IPublishedSnapshotAccessor { private readonly IUmbracoContextAccessor _umbracoContextAccessor; public UmbracoContextPublishedSnapshotAccessor(IUmbracoContextAccessor umbracoContextAccessor) { _umbracoContextAccessor = umbracoContextAccessor; } public IPublishedSnapshot PublishedSnapshot { get { var umbracoContext = _umbracoContextAccessor.UmbracoContext; if (umbracoContext == null) throw new Exception("The IUmbracoContextAccessor could not provide an UmbracoContext."); return umbracoContext.PublishedSnapshot; } set { throw new NotSupportedException(); // not ok to set } } } }
using System; namespace Umbraco.Web.PublishedCache { public class UmbracoContextPublishedSnapshotAccessor : IPublishedSnapshotAccessor { private readonly IUmbracoContextAccessor _umbracoContextAccessor; public UmbracoContextPublishedSnapshotAccessor(IUmbracoContextAccessor umbracoContextAccessor) { _umbracoContextAccessor = umbracoContextAccessor; } public IPublishedSnapshot PublishedSnapshot { get { var umbracoContext = _umbracoContextAccessor.UmbracoContext; return umbracoContext?.PublishedSnapshot; } set => throw new NotSupportedException(); // not ok to set } } }
Change interop calls to directly pinvoke.
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Runtime.InteropServices; namespace MICore { internal class NativeMethods { // TODO: It would be better to route these to the correct .so files directly rather than pasing through system.native. [DllImport("System.Native", SetLastError = true)] internal static extern int Kill(int pid, int mode); [DllImport("System.Native", SetLastError = true)] internal static extern int MkFifo(string name, int mode); [DllImport("System.Native", SetLastError = true)] internal static extern uint GetEUid(); } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Runtime.InteropServices; namespace MICore { internal class NativeMethods { private const string Libc = "libc"; [DllImport(Libc, EntryPoint = "kill", SetLastError = true)] internal static extern int Kill(int pid, int mode); [DllImport(Libc, EntryPoint = "mkfifo", SetLastError = true)] internal static extern int MkFifo(string name, int mode); [DllImport(Libc, EntryPoint = "geteuid", SetLastError = true)] internal static extern uint GetEUid(); } }
Use Py.GIL directly, now that it doesn't try to init anymore
using System; using System.Text; namespace Python.Runtime { using static Runtime; [Obsolete("Only to be used from within Python")] static class Loader { public unsafe static int Initialize(IntPtr data, int size) { try { var dllPath = Encoding.UTF8.GetString((byte*)data.ToPointer(), size); if (!string.IsNullOrEmpty(dllPath)) { PythonDLL = dllPath; } else { PythonDLL = null; } var gs = PyGILState_Ensure(); try { // Console.WriteLine("Startup thread"); PythonEngine.InitExt(); // Console.WriteLine("Startup finished"); } finally { PyGILState_Release(gs); } } catch (Exception exc) { Console.Error.Write( $"Failed to initialize pythonnet: {exc}\n{exc.StackTrace}" ); return 1; } return 0; } public unsafe static int Shutdown(IntPtr data, int size) { try { var command = Encoding.UTF8.GetString((byte*)data.ToPointer(), size); if (command == "full_shutdown") { var gs = PyGILState_Ensure(); try { PythonEngine.Shutdown(); } finally { PyGILState_Release(gs); } } } catch (Exception exc) { Console.Error.Write( $"Failed to shutdown pythonnet: {exc}\n{exc.StackTrace}" ); return 1; } return 0; } } }
using System; using System.Text; namespace Python.Runtime { using static Runtime; [Obsolete("Only to be used from within Python")] static class Loader { public unsafe static int Initialize(IntPtr data, int size) { try { var dllPath = Encoding.UTF8.GetString((byte*)data.ToPointer(), size); if (!string.IsNullOrEmpty(dllPath)) { PythonDLL = dllPath; } else { PythonDLL = null; } using var _ = Py.GIL(); PythonEngine.InitExt(); } catch (Exception exc) { Console.Error.Write( $"Failed to initialize pythonnet: {exc}\n{exc.StackTrace}" ); return 1; } return 0; } public unsafe static int Shutdown(IntPtr data, int size) { try { var command = Encoding.UTF8.GetString((byte*)data.ToPointer(), size); if (command == "full_shutdown") { using var _ = Py.GIL(); PythonEngine.Shutdown(); } } catch (Exception exc) { Console.Error.Write( $"Failed to shutdown pythonnet: {exc}\n{exc.StackTrace}" ); return 1; } return 0; } } }
Support commit listing for single file within repository
using System; using GitHubSharp.Models; using System.Collections.Generic; namespace GitHubSharp.Controllers { public class CommitsController : Controller { public RepositoryController RepositoryController { get; private set; } public CommitController this[string key] { get { return new CommitController(Client, RepositoryController, key); } } public CommitsController(Client client, RepositoryController repo) : base(client) { RepositoryController = repo; } public GitHubRequest<List<CommitModel>> GetAll(string sha = null) { if (sha == null) return GitHubRequest.Get<List<CommitModel>>(Uri); else return GitHubRequest.Get<List<CommitModel>>(Uri, new { sha = sha }); } public override string Uri { get { return RepositoryController.Uri + "/commits"; } } } public class CommitController : Controller { public RepositoryController RepositoryController { get; private set; } public string Sha { get; private set; } public CommitCommentsController Comments { get { return new CommitCommentsController(Client, this); } } public CommitController(Client client, RepositoryController repositoryController, string sha) : base(client) { RepositoryController = repositoryController; Sha = sha; } public GitHubRequest<CommitModel> Get() { return GitHubRequest.Get<CommitModel>(Uri); } public override string Uri { get { return RepositoryController.Uri + "/commits/" + Sha; } } } }
using System; using GitHubSharp.Models; using System.Collections.Generic; namespace GitHubSharp.Controllers { public class CommitsController : Controller { public string FilePath { get; set; } public RepositoryController RepositoryController { get; private set; } public CommitController this[string key] { get { return new CommitController(Client, RepositoryController, key); } } public CommitsController(Client client, RepositoryController repo) : base(client) { RepositoryController = repo; } public GitHubRequest<List<CommitModel>> GetAll(string sha = null) { if (sha == null) return GitHubRequest.Get<List<CommitModel>>(Uri); else return GitHubRequest.Get<List<CommitModel>>(Uri, new { sha = sha }); } public override string Uri { get { return RepositoryController.Uri + "/commits" + (string.IsNullOrEmpty(this.FilePath) ? string.Empty : "?path=" + this.FilePath); } } } public class CommitController : Controller { public RepositoryController RepositoryController { get; private set; } public string Sha { get; private set; } public CommitCommentsController Comments { get { return new CommitCommentsController(Client, this); } } public CommitController(Client client, RepositoryController repositoryController, string sha) : base(client) { RepositoryController = repositoryController; Sha = sha; } public GitHubRequest<CommitModel> Get() { return GitHubRequest.Get<CommitModel>(Uri); } public override string Uri { get { return RepositoryController.Uri + "/commits/" + Sha; } } } }
Set default target path gizmo curve color
namespace ATP.AnimationPathTools { public class TargetAnimationPath : AnimationPath { } }
using UnityEngine; namespace ATP.AnimationPathTools { public class TargetAnimationPath : AnimationPath { /// <summary> /// Color of the gizmo curve. /// </summary> private Color gizmoCurveColor = Color.magenta; } }
Convert Distance to Expression Bodied Member
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TourOfCSharp6 { public class Point { public double X { get; set; } public double Y { get; set; } public double Distance { get { return Math.Sqrt(X * X + Y * Y); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TourOfCSharp6 { public class Point { public double X { get; set; } public double Y { get; set; } public double Distance => Math.Sqrt(X * X + Y * Y); } }
Revert "bump version again to 1.3.76.0"
using System; using System.Reflection; using System.Runtime.InteropServices; [ assembly : ComVisible( false ) ] [ assembly : AssemblyProduct( "ShipStationAccess" ) ] [ assembly : AssemblyCompany( "Agile Harbor, LLC" ) ] [ assembly : AssemblyCopyright( "Copyright (C) Agile Harbor, LLC" ) ] [ assembly : AssemblyDescription( "ShipStation webservices API wrapper." ) ] [ assembly : AssemblyTrademark( "" ) ] [ assembly : AssemblyCulture( "" ) ] [ assembly : CLSCompliant( false ) ] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] // Keep in track with CA API version [ assembly : AssemblyVersion( "1.3.76.0" ) ]
using System; using System.Reflection; using System.Runtime.InteropServices; [ assembly : ComVisible( false ) ] [ assembly : AssemblyProduct( "ShipStationAccess" ) ] [ assembly : AssemblyCompany( "Agile Harbor, LLC" ) ] [ assembly : AssemblyCopyright( "Copyright (C) Agile Harbor, LLC" ) ] [ assembly : AssemblyDescription( "ShipStation webservices API wrapper." ) ] [ assembly : AssemblyTrademark( "" ) ] [ assembly : AssemblyCulture( "" ) ] [ assembly : CLSCompliant( false ) ] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] // Keep in track with CA API version [ assembly : AssemblyVersion( "1.3.75.0" ) ]
Use StringEnumConvert for Approvals.VerifyJson / VerifyMe
namespace CertiPay.Common.Testing { using ApprovalTests; using Newtonsoft.Json; using Ploeh.AutoFixture; public static class TestExtensions { private static readonly Fixture _fixture = new Fixture { }; /// <summary> /// Runs ApprovalTests's VerifyJson against a JSON.net serialized representation of the provided object /// </summary> public static void VerifyMe(this object obj) { var json = JsonConvert.SerializeObject(obj); Approvals.VerifyJson(json); } /// <summary> /// Returns an auto-initialized instance of the type T, filled via mock /// data via AutoFixture. /// /// This will not work for interfaces, only concrete types. /// </summary> public static T AutoGenerate<T>() { return _fixture.Create<T>(); } } }
namespace CertiPay.Common.Testing { using ApprovalTests; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Ploeh.AutoFixture; public static class TestExtensions { private static readonly Fixture _fixture = new Fixture { }; private static readonly JsonSerializerSettings _settings = new JsonSerializerSettings { Formatting = Formatting.Indented }; static TestExtensions() { _settings.Converters.Add(new StringEnumConverter { }); } /// <summary> /// Runs ApprovalTests's VerifyJson against a JSON.net serialized representation of the provided object /// </summary> public static void VerifyMe(this object obj) { var json = JsonConvert.SerializeObject(obj, _settings); Approvals.VerifyJson(json); } /// <summary> /// Returns an auto-initialized instance of the type T, filled via mock /// data via AutoFixture. /// /// This will not work for interfaces, only concrete types. /// </summary> public static T AutoGenerate<T>() { return _fixture.Create<T>(); } } }
Fix bug in pinmode usage The device.PinMode was being set from internal members which had not been stored yet. Would result in Relay module not working as expected.
using System; namespace GrovePi.Sensors { public abstract class Sensor<TSensorType> where TSensorType : class { protected readonly IGrovePi Device; protected readonly Pin Pin; internal Sensor(IGrovePi device, Pin pin, PinMode pinMode) { if (device == null) throw new ArgumentNullException(nameof(device)); device.PinMode(Pin, pinMode); Device = device; Pin = pin; } internal Sensor(IGrovePi device, Pin pin) { if (device == null) throw new ArgumentNullException(nameof(device)); Device = device; Pin = pin; } public SensorStatus CurrentState => (SensorStatus) Device.DigitalRead(Pin); public TSensorType ChangeState(SensorStatus newState) { Device.DigitalWrite(Pin, (byte) newState); return this as TSensorType; } public void AnalogWrite(byte value) { Device.AnalogWrite(Pin,value); } } }
using System; namespace GrovePi.Sensors { public abstract class Sensor<TSensorType> where TSensorType : class { protected readonly IGrovePi Device; protected readonly Pin Pin; internal Sensor(IGrovePi device, Pin pin, PinMode pinMode) { if (device == null) throw new ArgumentNullException(nameof(device)); Device = device; Pin = pin; device.PinMode(Pin, pinMode); } internal Sensor(IGrovePi device, Pin pin) { if (device == null) throw new ArgumentNullException(nameof(device)); Device = device; Pin = pin; } public SensorStatus CurrentState => (SensorStatus) Device.DigitalRead(Pin); public TSensorType ChangeState(SensorStatus newState) { Device.DigitalWrite(Pin, (byte) newState); return this as TSensorType; } public void AnalogWrite(byte value) { Device.AnalogWrite(Pin,value); } } }
Revert "Now with "yield" in GetaNum()"
using System.Collections; class IENumDemo { /// <summary> /// Create a cosinus table enumerator with 0..360 deg values /// </summary> private IEnumerator costable = new Func<List<float>>(() => { List<float> nn = new List<float>(); for (int v = 0; v < 360; v++) { nn.Add((float)Math.Cos(v * Math.PI / 180)); } return nn; } )().GetEnumerator(); /// <summary> /// Demonstrates eternal fetch of next value from an IEnumerator /// At end of list the enumerator is reset to start of list /// </summary> /// <returns></returns> private float GetaNum() { //Advance to next item if (!costable.MoveNext()) { //End of list - reset and advance to first costable.Reset(); costable.MoveNext(); } //Return Enum current value yield return costable.Current; } }
using System.Collections; class IENumDemo { /// <summary> /// Create a cosinus table enumerator with 0..360 deg values /// </summary> private IEnumerator costable = new Func<List<float>>(() => { List<float> nn = new List<float>(); for (int v = 0; v < 360; v++) { nn.Add((float)Math.Cos(v * Math.PI / 180)); } return nn; } )().GetEnumerator(); /// <summary> /// Demonstrates eternal fetch of next value from an IEnumerator /// At end of list the enumerator is reset to start of list /// </summary> /// <returns></returns> private float GetaNum() { //Advance to next item if (!costable.MoveNext()) { //End of list - reset and advance to first costable.Reset(); costable.MoveNext(); } //Return Enum current value return costable.Current; } }
Update description to match mania mirror implementation
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Bindables; using osu.Game.Configuration; using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Osu.Objects; using osu.Game.Rulesets.Osu.Utils; namespace osu.Game.Rulesets.Osu.Mods { public class OsuModMirror : ModMirror, IApplicableToHitObject { public override string Description => "Reflect the playfield."; public override Type[] IncompatibleMods => new[] { typeof(ModHardRock) }; [SettingSource("Mirrored axes", "Choose which of the playfield's axes are mirrored.")] public Bindable<MirrorType> Reflection { get; } = new Bindable<MirrorType>(); public void ApplyToHitObject(HitObject hitObject) { var osuObject = (OsuHitObject)hitObject; switch (Reflection.Value) { case MirrorType.Horizontal: OsuHitObjectGenerationUtils.ReflectHorizontally(osuObject); break; case MirrorType.Vertical: OsuHitObjectGenerationUtils.ReflectVertically(osuObject); break; case MirrorType.Both: OsuHitObjectGenerationUtils.ReflectHorizontally(osuObject); OsuHitObjectGenerationUtils.ReflectVertically(osuObject); break; } } public enum MirrorType { Horizontal, Vertical, Both } } }
// 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; using osu.Game.Configuration; using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Osu.Objects; using osu.Game.Rulesets.Osu.Utils; namespace osu.Game.Rulesets.Osu.Mods { public class OsuModMirror : ModMirror, IApplicableToHitObject { public override string Description => "Flip objects on the chosen axes."; public override Type[] IncompatibleMods => new[] { typeof(ModHardRock) }; [SettingSource("Mirrored axes", "Choose which axes objects are mirrored over.")] public Bindable<MirrorType> Reflection { get; } = new Bindable<MirrorType>(); public void ApplyToHitObject(HitObject hitObject) { var osuObject = (OsuHitObject)hitObject; switch (Reflection.Value) { case MirrorType.Horizontal: OsuHitObjectGenerationUtils.ReflectHorizontally(osuObject); break; case MirrorType.Vertical: OsuHitObjectGenerationUtils.ReflectVertically(osuObject); break; case MirrorType.Both: OsuHitObjectGenerationUtils.ReflectHorizontally(osuObject); OsuHitObjectGenerationUtils.ReflectVertically(osuObject); break; } } public enum MirrorType { Horizontal, Vertical, Both } } }