Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Handle dir separator better for Mono
using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.ComponentModel.Composition.Hosting; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using NutzCode.Libraries.Web.StreamProvider; namespace NutzCode.CloudFileSystem { public class AuthorizationFactory { private static AuthorizationFactory _instance; public static AuthorizationFactory Instance => _instance ?? (_instance = new AuthorizationFactory()); [Import(typeof(IAppAuthorization))] public IAppAuthorization AuthorizationProvider { get; set; } public AuthorizationFactory(string dll=null) { Assembly assembly = Assembly.GetEntryAssembly(); string codebase = assembly.CodeBase; UriBuilder uri = new UriBuilder(codebase); string dirname = Pri.LongPath.Path.GetDirectoryName(Uri.UnescapeDataString(uri.Path).Replace("/", "\\")); if (dirname != null) { AggregateCatalog catalog = new AggregateCatalog(); catalog.Catalogs.Add(new AssemblyCatalog(assembly)); if (dll!=null) catalog.Catalogs.Add(new DirectoryCatalog(dirname, dll)); var container = new CompositionContainer(catalog); container.ComposeParts(this); } } } }
using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.ComponentModel.Composition.Hosting; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using NutzCode.Libraries.Web.StreamProvider; namespace NutzCode.CloudFileSystem { public class AuthorizationFactory { private static AuthorizationFactory _instance; public static AuthorizationFactory Instance => _instance ?? (_instance = new AuthorizationFactory()); [Import(typeof(IAppAuthorization))] public IAppAuthorization AuthorizationProvider { get; set; } public AuthorizationFactory(string dll=null) { Assembly assembly = Assembly.GetEntryAssembly(); string codebase = assembly.CodeBase; UriBuilder uri = new UriBuilder(codebase); string dirname = Pri.LongPath.Path.GetDirectoryName(Uri.UnescapeDataString(uri.Path) .Replace("/", $"{System.IO.Path.DirectorySeparatorChar}")); if (dirname != null) { AggregateCatalog catalog = new AggregateCatalog(); catalog.Catalogs.Add(new AssemblyCatalog(assembly)); if (dll!=null) catalog.Catalogs.Add(new DirectoryCatalog(dirname, dll)); var container = new CompositionContainer(catalog); container.ComposeParts(this); } } } }
Make demo script comply with guidelines
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ReturnToBounds : MonoBehaviour { [SerializeField] Transform frontBounds = null; [SerializeField] Transform backBounds = null; [SerializeField] Transform leftBounds = null; [SerializeField] Transform rightBounds = null; [SerializeField] Transform bottomBounds = null; [SerializeField] Transform topBounds = null; Vector3 positionAtStart; // Start is called before the first frame update void Start() { positionAtStart = transform.position; } // Update is called once per frame void Update() { if (transform.position.x > rightBounds.position.x || transform.position.x < leftBounds.position.x || transform.position.y > topBounds.position.y || transform.position.y < bottomBounds.position.y || transform.position.z > backBounds.position.z || transform.position.z < frontBounds.position.z) { transform.position = positionAtStart; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Microsoft.MixedReality.Toolkit.Examples.Experimental.Demos { public class ReturnToBounds : MonoBehaviour { [SerializeField] private Transform frontBounds = null; public Transform FrontBounds { get => frontBounds; set => frontBounds = value; } [SerializeField] private Transform backBounds = null; public Transform BackBounds { get => backBounds; set => backBounds = value; } [SerializeField] private Transform leftBounds = null; public Transform LeftBounds { get => leftBounds; set => leftBounds = value; } [SerializeField] private Transform rightBounds = null; public Transform RightBounds { get => rightBounds; set => rightBounds = value; } [SerializeField] private Transform bottomBounds = null; public Transform BottomBounds { get => bottomBounds; set => bottomBounds = value; } [SerializeField] private Transform topBounds = null; public Transform TopBounds { get => topBounds; set => topBounds = value; } private Vector3 positionAtStart; // Start is called before the first frame update void Start() { positionAtStart = transform.position; } // Update is called once per frame void Update() { if (transform.position.x > rightBounds.position.x || transform.position.x < leftBounds.position.x || transform.position.y > topBounds.position.y || transform.position.y < bottomBounds.position.y || transform.position.z > backBounds.position.z || transform.position.z < frontBounds.position.z) { transform.position = positionAtStart; } } } }
Change ctor parameter to byte array
using System; using System.Linq; using System.Net; namespace BmpListener.Bgp { public class IPAddrPrefix { public IPAddrPrefix(ArraySegment<byte> data, AddressFamily afi = AddressFamily.IP) { DecodeFromBytes(data, afi); } public byte Length { get; private set; } public IPAddress Prefix { get; private set; } public override string ToString() { return ($"{Prefix}/{Length}"); } public int GetByteLength() { return 1 + (Length + 7) / 8; } public void DecodeFromBytes(ArraySegment<byte> data, Bgp.AddressFamily afi) { Length = data.ElementAt(0); if (Length <= 0) return; var byteLength = (Length + 7) / 8; var ipBytes = afi == AddressFamily.IP ? new byte[4] : new byte[16]; Buffer.BlockCopy(data.ToArray(), 1, ipBytes, 0, byteLength); Prefix = new IPAddress(ipBytes); } } }
using System; using System.Net; namespace BmpListener.Bgp { public class IPAddrPrefix { public IPAddrPrefix(byte[] data, AddressFamily afi = AddressFamily.IP) { DecodeFromBytes(data, afi); } public byte Length { get; private set; } public IPAddress Prefix { get; private set; } public override string ToString() { return ($"{Prefix}/{Length}"); } public int GetByteLength() { return 1 + (Length + 7) / 8; } public void DecodeFromBytes(byte[] data, AddressFamily afi) { Length = data.ElementAt(0); if (Length <= 0) return; var byteLength = (Length + 7) / 8; var ipBytes = afi == AddressFamily.IP ? new byte[4] : new byte[16]; Buffer.BlockCopy(data, 1, ipBytes, 0, byteLength); Prefix = new IPAddress(ipBytes); } } }
Use current principal if provided for auth
using System; using System.Net.Http; using System.Threading.Tasks; namespace Archon.WebApi { public abstract class Link { public Authorization Authorization { get; set; } public HttpRequestMessage CreateRequest() { var req = CreateRequestInternal(); if (Authorization != null) req.Headers.Authorization = Authorization.AsHeader(); return req; } protected abstract HttpRequestMessage CreateRequestInternal(); } public abstract class Link<TResponse> : Link { public Task<TResponse> ParseResponseAsync(HttpResponseMessage response) { if (response == null) throw new ArgumentNullException("response"); return ParseResponseInternal(response); } protected abstract Task<TResponse> ParseResponseInternal(HttpResponseMessage response); } }
using System; using System.Net.Http; using System.Threading; using System.Threading.Tasks; namespace Archon.WebApi { public abstract class Link { public Authorization Authorization { get; set; } public HttpRequestMessage CreateRequest() { var req = CreateRequestInternal(); var authToken = GetAuthToken(); if (authToken != null) req.Headers.Authorization = authToken.AsHeader(); return req; } Authorization GetAuthToken() { if (Authorization != null) return Authorization; var token = Thread.CurrentPrincipal as AuthToken; if (token != null) return Authorization.Bearer(token.Token); return null; } protected abstract HttpRequestMessage CreateRequestInternal(); } public abstract class Link<TResponse> : Link { public Task<TResponse> ParseResponseAsync(HttpResponseMessage response) { if (response == null) throw new ArgumentNullException("response"); return ParseResponseInternal(response); } protected abstract Task<TResponse> ParseResponseInternal(HttpResponseMessage response); } }
Update Bootstrap package in v5 test pages to v5.2.2
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>@ViewBag.Title - Atata.Bootstrap.TestApp v5</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous"> @RenderSection("styles", false) </head> <body> <div class="container"> <h1 class="text-center">@ViewBag.Title</h1> @RenderBody() </div> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" crossorigin="anonymous"></script> @RenderSection("scripts", false) </body> </html>
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>@ViewBag.Title - Atata.Bootstrap.TestApp v5</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css" rel="stylesheet"> @RenderSection("styles", false) </head> <body> <div class="container"> <h1 class="text-center">@ViewBag.Title</h1> @RenderBody() </div> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"></script> @RenderSection("scripts", false) </body> </html>
Test to run gui on STA thread
using System; using System.Threading; using Microsoft.VisualStudio.TestTools.UnitTesting; using AdmoInstallerCustomAction; using System.Windows; namespace AdmoTests.CustomActionTests { [TestClass] public class CustomActionTests { [TestMethod] public void TestMethod1() { //Will have to use gui testing tools here //ManualResetEvent syncEvent = new ManualResetEvent(false); //Thread t = new Thread(() => //{ // var app = new Application(); // app.Run(new DownloadRuntimeWPF()); // // syncEvent.Set(); //}); //t.SetApartmentState(ApartmentState.STA); //t.Start(); //t.Join(); } } }
using System; using System.Threading; using Admo; using Microsoft.VisualStudio.TestTools.UnitTesting; using AdmoInstallerCustomAction; using System.Windows; namespace AdmoTests.CustomActionTests { [TestClass] public class CustomActionTests { [TestMethod] public void TestRunWPFOnSTAThread() { //Will have to use gui testing tools here Thread t = new Thread(() => { var app = new Application(); app.Run(new DownloadRuntimeWPF()); }); t.SetApartmentState(ApartmentState.STA); t.Start(); t.Abort(); } } }
Implement first step of automation layer
using System; using System.Collections.Generic; using System.Linq; using System.Text; using TechTalk.SpecFlow; namespace FizzBuzz.Specification.AutomationLayer { [Binding] public class StepDefinitions { [Given(@"the current number is '(.*)'")] public void GivenTheCurrentNumberIs(int p0) { ScenarioContext.Current.Pending(); } [When(@"I print the number")] public void WhenIPrintTheNumber() { ScenarioContext.Current.Pending(); } [Then(@"the result is '(.*)'")] public void ThenTheResultIs(int p0) { ScenarioContext.Current.Pending(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using TechTalk.SpecFlow; namespace FizzBuzz.Specification.AutomationLayer { [Binding] public class StepDefinitions { private int currentNumber; [Given(@"the current number is '(.*)'")] public void GivenTheCurrentNumberIs(int currentNumber) { this.currentNumber = currentNumber; } [When(@"I print the number")] public void WhenIPrintTheNumber() { ScenarioContext.Current.Pending(); } [Then(@"the result is '(.*)'")] public void ThenTheResultIs(int p0) { ScenarioContext.Current.Pending(); } } }
Set expires header to max when response is intented to be cached, so browsers will not use try-get pattern for those resources next time.
using System.Threading.Tasks; using Microsoft.Owin; using System.Linq; using System; using Foundation.Api.Implementations; using System.Threading; namespace Foundation.Api.Middlewares { public class OwinCacheResponseMiddleware : DefaultOwinActionFilterMiddleware { public OwinCacheResponseMiddleware() { } public OwinCacheResponseMiddleware(OwinMiddleware next) : base(next) { } public override async Task OnActionExecutingAsync(IOwinContext owinContext) { if (owinContext.Response.Headers.Any(h => string.Equals(h.Key, "Cache-Control", StringComparison.InvariantCultureIgnoreCase))) owinContext.Response.Headers.Remove("Cache-Control"); owinContext.Response.Headers.Add("Cache-Control", new[] { "public", "max-age=31536000" }); if (owinContext.Response.Headers.Any(h => string.Equals(h.Key, "Pragma", StringComparison.InvariantCultureIgnoreCase))) owinContext.Response.Headers.Remove("Pragma"); owinContext.Response.Headers.Add("Pragma", new[] { "public" }); if (owinContext.Response.Headers.Any(h => string.Equals(h.Key, "Expires", StringComparison.InvariantCultureIgnoreCase))) owinContext.Response.Headers.Remove("Expires"); owinContext.Response.Headers.Add("Expires", new[] { "31536000" }); await base.OnActionExecutingAsync(owinContext); } } }
using System.Threading.Tasks; using Microsoft.Owin; using System.Linq; using System; using Foundation.Api.Implementations; namespace Foundation.Api.Middlewares { public class OwinCacheResponseMiddleware : DefaultOwinActionFilterMiddleware { public OwinCacheResponseMiddleware() { } public OwinCacheResponseMiddleware(OwinMiddleware next) : base(next) { } public override async Task OnActionExecutingAsync(IOwinContext owinContext) { if (owinContext.Response.Headers.Any(h => string.Equals(h.Key, "Cache-Control", StringComparison.InvariantCultureIgnoreCase))) owinContext.Response.Headers.Remove("Cache-Control"); owinContext.Response.Headers.Add("Cache-Control", new[] { "public", "max-age=31536000" }); if (owinContext.Response.Headers.Any(h => string.Equals(h.Key, "Pragma", StringComparison.InvariantCultureIgnoreCase))) owinContext.Response.Headers.Remove("Pragma"); owinContext.Response.Headers.Add("Pragma", new[] { "public" }); if (owinContext.Response.Headers.Any(h => string.Equals(h.Key, "Expires", StringComparison.InvariantCultureIgnoreCase))) owinContext.Response.Headers.Remove("Expires"); owinContext.Response.Headers.Add("Expires", new[] { "max" }); await base.OnActionExecutingAsync(owinContext); } } }
Set line ending according to the enviroment in ReFormatXML
using System.IO; using System.Xml; namespace VanillaTransformer.PostTransformations.XML { public class ReFormatXMLTransformation:IPostTransformation { public string Name { get { return "ReFormatXML"; } } public string Execute(string configContent) { var settings = new XmlWriterSettings() { Indent = true, IndentChars = " ", NewLineChars = "\r\n", NewLineHandling = NewLineHandling.Replace, }; var xDocument = new XmlDocument(); xDocument.LoadXml(configContent); using (var textWriter = new StringWriter()) { using (var writer = XmlWriter.Create(textWriter,settings)) { xDocument.WriteTo(writer); } return textWriter.ToString(); } } } }
using System; using System.IO; using System.Xml; namespace VanillaTransformer.PostTransformations.XML { public class ReFormatXMLTransformation:IPostTransformation { public string Name { get { return "ReFormatXML"; } } public string Execute(string configContent) { var settings = new XmlWriterSettings() { Indent = true, IndentChars = " ", NewLineChars = Environment.NewLine, NewLineHandling = NewLineHandling.Replace, }; var xDocument = new XmlDocument(); xDocument.LoadXml(configContent); using (var textWriter = new StringWriter()) { using (var writer = XmlWriter.Create(textWriter,settings)) { xDocument.WriteTo(writer); } return textWriter.ToString(); } } } }
Revert "Fix potential crash in tests when attempting to lookup key bindings in cases the lookup is not available"
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Platform; using osu.Framework.Testing; namespace osu.Game.Configuration { [ExcludeFromDynamicCompile] public class DevelopmentOsuConfigManager : OsuConfigManager { protected override string Filename => base.Filename.Replace(".ini", ".dev.ini"); public DevelopmentOsuConfigManager(Storage storage) : base(storage) { LookupKeyBindings = _ => "unknown"; LookupSkinName = _ => "unknown"; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Platform; using osu.Framework.Testing; namespace osu.Game.Configuration { [ExcludeFromDynamicCompile] public class DevelopmentOsuConfigManager : OsuConfigManager { protected override string Filename => base.Filename.Replace(".ini", ".dev.ini"); public DevelopmentOsuConfigManager(Storage storage) : base(storage) { } } }
Append new line at EOF
namespace PcscDotNet { /// <summary> /// Indicates whether other applications may form connections to the card. /// </summary> public enum SCardShare { /// <summary> /// This application demands direct control of the reader, so it is not available to other applications. /// </summary> Direct = 3, /// <summary> /// This application is not willing to share this card with other applications. /// </summary> Exclusive = 1, /// <summary> /// This application is willing to share this card with other applications. /// </summary> Shared = 2, /// <summary> /// Share mode is undefined, can not be used to connect to card/reader. /// </summary> Undefined = 0 } }
namespace PcscDotNet { /// <summary> /// Indicates whether other applications may form connections to the card. /// </summary> public enum SCardShare { /// <summary> /// This application demands direct control of the reader, so it is not available to other applications. /// </summary> Direct = 3, /// <summary> /// This application is not willing to share this card with other applications. /// </summary> Exclusive = 1, /// <summary> /// This application is willing to share this card with other applications. /// </summary> Shared = 2, /// <summary> /// Share mode is undefined, can not be used to connect to card/reader. /// </summary> Undefined = 0 } }
Increase AuthorBage.HoverText db table column length
using System.ComponentModel.DataAnnotations; namespace TM.Shared { public class AuthorBadge { [StringLength(400)] public string ImageSiteUrl { get; set; } [StringLength(100)] public string ImageName { get; set; } [StringLength(400)] public string Link { get; set; } [StringLength(100)] public string HoverText { get; set; } public bool IsEmpty { get { return string.IsNullOrWhiteSpace(Link); } } } }
using System.ComponentModel.DataAnnotations; namespace TM.Shared { public class AuthorBadge { [StringLength(400)] public string ImageSiteUrl { get; set; } [StringLength(100)] public string ImageName { get; set; } [StringLength(400)] public string Link { get; set; } [StringLength(400)] public string HoverText { get; set; } public bool IsEmpty { get { return string.IsNullOrWhiteSpace(Link); } } } }
Fix time bug with scrobbles
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace IF.Lastfm.Core.Api.Helpers { public static class ApiExtensions { public static T GetAttribute<T>(this Enum enumValue) where T : Attribute { return enumValue .GetType() .GetTypeInfo() .GetDeclaredField(enumValue.ToString()) .GetCustomAttribute<T>(); } public static string GetApiName(this Enum enumValue) { var attribute = enumValue.GetAttribute<ApiNameAttribute>(); return (attribute != null && !string.IsNullOrWhiteSpace(attribute.Text)) ? attribute.Text : enumValue.ToString(); } public static int ToUnixTimestamp(this DateTime dt) { var d = (dt - new DateTime(1970, 1, 1).ToUniversalTime()).TotalSeconds; return Convert.ToInt32(d); } public static DateTime ToDateTimeUtc(this double stamp) { var d = new DateTime(1970, 1, 1).ToUniversalTime(); d = d.AddSeconds(stamp); return d; } public static int CountOrDefault<T>(this IEnumerable<T> enumerable) { return enumerable != null ? enumerable.Count() : 0; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace IF.Lastfm.Core.Api.Helpers { public static class ApiExtensions { public static T GetAttribute<T>(this Enum enumValue) where T : Attribute { return enumValue .GetType() .GetTypeInfo() .GetDeclaredField(enumValue.ToString()) .GetCustomAttribute<T>(); } public static string GetApiName(this Enum enumValue) { var attribute = enumValue.GetAttribute<ApiNameAttribute>(); return (attribute != null && !string.IsNullOrWhiteSpace(attribute.Text)) ? attribute.Text : enumValue.ToString(); } public static int ToUnixTimestamp(this DateTime dt) { var d = (dt - new DateTime(1970, 1, 1)).TotalSeconds; return Convert.ToInt32(d); } public static DateTime ToDateTimeUtc(this double stamp) { var d = new DateTime(1970, 1, 1).ToUniversalTime(); d = d.AddSeconds(stamp); return d; } public static int CountOrDefault<T>(this IEnumerable<T> enumerable) { return enumerable != null ? enumerable.Count() : 0; } } }
Fix issue with nulll image icon in tabbed navigation container
using System; using Xamarin.Forms; using System.Collections.Generic; namespace FreshMvvm { public class FreshTabbedNavigationContainer : TabbedPage, IFreshNavigationService { public FreshTabbedNavigationContainer () { RegisterNavigation (); } protected void RegisterNavigation () { FreshIOC.Container.Register<IFreshNavigationService> (this); } public virtual Page AddTab<T> (string title, string icon, object data = null) where T : FreshBasePageModel { var page = FreshPageModelResolver.ResolvePageModel<T> (data); var navigationContainer = CreateContainerPage (page); navigationContainer.Title = title; navigationContainer.Icon = icon; Children.Add (navigationContainer); return navigationContainer; } protected virtual Page CreateContainerPage (Page page) { return new NavigationPage (page); } public async System.Threading.Tasks.Task PushPage (Xamarin.Forms.Page page, FreshBasePageModel model, bool modal = false) { if (modal) await this.CurrentPage.Navigation.PushModalAsync (CreateContainerPage (page)); else await this.CurrentPage.Navigation.PushAsync (page); } public async System.Threading.Tasks.Task PopPage (bool modal = false) { if (modal) await this.CurrentPage.Navigation.PopModalAsync (); else await this.CurrentPage.Navigation.PopAsync (); } } }
using System; using Xamarin.Forms; using System.Collections.Generic; namespace FreshMvvm { public class FreshTabbedNavigationContainer : TabbedPage, IFreshNavigationService { public FreshTabbedNavigationContainer () { RegisterNavigation (); } protected void RegisterNavigation () { FreshIOC.Container.Register<IFreshNavigationService> (this); } public virtual Page AddTab<T> (string title, string icon, object data = null) where T : FreshBasePageModel { var page = FreshPageModelResolver.ResolvePageModel<T> (data); var navigationContainer = CreateContainerPage (page); navigationContainer.Title = title; if (!string.IsNullOrWhiteSpace(icon)) navigationContainer.Icon = icon; Children.Add (navigationContainer); return navigationContainer; } protected virtual Page CreateContainerPage (Page page) { return new NavigationPage (page); } public async System.Threading.Tasks.Task PushPage (Xamarin.Forms.Page page, FreshBasePageModel model, bool modal = false) { if (modal) await this.CurrentPage.Navigation.PushModalAsync (CreateContainerPage (page)); else await this.CurrentPage.Navigation.PushAsync (page); } public async System.Threading.Tasks.Task PopPage (bool modal = false) { if (modal) await this.CurrentPage.Navigation.PopModalAsync (); else await this.CurrentPage.Navigation.PopAsync (); } } }
Implement supported parts of Spn/UpnEndpointIdentity
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.IdentityModel.Claims; using System.Runtime; using System.Security.Principal; namespace System.ServiceModel { public class SpnEndpointIdentity : EndpointIdentity { private static TimeSpan _spnLookupTime = TimeSpan.FromMinutes(1); public SpnEndpointIdentity(string spnName) { if (spnName == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("spnName"); base.Initialize(Claim.CreateSpnClaim(spnName)); } public SpnEndpointIdentity(Claim identity) { if (identity == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("identity"); if (!identity.ClaimType.Equals(ClaimTypes.Spn)) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.Format(SR.UnrecognizedClaimTypeForIdentity, identity.ClaimType, ClaimTypes.Spn)); base.Initialize(identity); } public static TimeSpan SpnLookupTime { get { return _spnLookupTime; } set { if (value.Ticks < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ArgumentOutOfRangeException("value", value.Ticks, SR.Format(SR.ValueMustBeNonNegative))); } _spnLookupTime = value; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.IdentityModel.Claims; using System.Runtime; using System.Security.Principal; namespace System.ServiceModel { public class SpnEndpointIdentity : EndpointIdentity { private static TimeSpan _spnLookupTime = TimeSpan.FromMinutes(1); public SpnEndpointIdentity(string spnName) { if (spnName == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("spnName"); base.Initialize(Claim.CreateSpnClaim(spnName)); } public SpnEndpointIdentity(Claim identity) { if (identity == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("identity"); if (!identity.ClaimType.Equals(ClaimTypes.Spn)) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.Format(SR.UnrecognizedClaimTypeForIdentity, identity.ClaimType, ClaimTypes.Spn)); base.Initialize(identity); } public static TimeSpan SpnLookupTime { get { return _spnLookupTime; } set { if (value.Ticks < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ArgumentOutOfRangeException("value", value.Ticks, SR.Format(SR.ValueMustBeNonNegative))); } _spnLookupTime = value; } } } }
Add an overload of `AddSystemFonts`
// Copyright (c) Six Labors. // Licensed under the Apache License, Version 2.0. namespace SixLabors.Fonts { /// <summary> /// Extension methods for <see cref="IFontCollection"/>. /// </summary> public static class FontCollectionExtensions { /// <summary> /// Adds the fonts from the <see cref="SystemFonts"/> collection to this <see cref="FontCollection"/>. /// </summary> /// <param name="collection">The font collection.</param> /// <returns>The <see cref="FontCollection"/> containing the system fonts.</returns> public static FontCollection AddSystemFonts(this FontCollection collection) { // This cast is safe because our underlying SystemFontCollection implements // both interfaces separately. foreach (FontMetrics? metric in (IReadOnlyFontMetricsCollection)SystemFonts.Collection) { ((IFontMetricsCollection)collection).AddMetrics(metric); } return collection; } } }
// Copyright (c) Six Labors. // Licensed under the Apache License, Version 2.0. using System; namespace SixLabors.Fonts { /// <summary> /// Extension methods for <see cref="IFontCollection"/>. /// </summary> public static class FontCollectionExtensions { /// <summary> /// Adds the fonts from the <see cref="SystemFonts"/> collection to this <see cref="FontCollection"/>. /// </summary> /// <param name="collection">The font collection.</param> /// <returns>The <see cref="FontCollection"/> containing the system fonts.</returns> public static FontCollection AddSystemFonts(this FontCollection collection) { // This cast is safe because our underlying SystemFontCollection implements // both interfaces separately. foreach (FontMetrics metric in (IReadOnlyFontMetricsCollection)SystemFonts.Collection) { ((IFontMetricsCollection)collection).AddMetrics(metric); } return collection; } /// <summary> /// Adds the fonts from the <see cref="SystemFonts"/> collection to this <see cref="FontCollection"/>. /// </summary> /// <param name="collection">The font collection.</param> /// <param name="match">The System.Predicate delegate that defines the conditions of <see cref="FontMetrics"/> to add into the font collection.</param> /// <returns>The <see cref="FontCollection"/> containing the system fonts.</returns> public static FontCollection AddSystemFonts(this FontCollection collection, Predicate<FontMetrics> match) { foreach (FontMetrics metric in (IReadOnlyFontMetricsCollection)SystemFonts.Collection) { if (match(metric)) { ((IFontMetricsCollection)collection).AddMetrics(metric); } } return collection; } } }
Remove ViewLogic Validation on Edit Settings Screen
@model Portal.CMS.Web.Areas.Admin.ViewModels.Settings.EditViewModel @{ Layout = ""; } @using (Html.BeginForm("Edit", "Settings", FormMethod.Post)) { @Html.AntiForgeryToken() @Html.HiddenFor(x => x.SettingId) @Html.ValidationMessage("SettingName") <div class="control-group float-container"> @Html.LabelFor(x => x.SettingName) @if (Model.SettingName != "Website Name") { @Html.TextBoxFor(x => x.SettingName, new { placeholder = "Setting Name" }) } else { @Html.TextBoxFor(x => x.SettingName, new { placeholder = "Setting Name", @readonly="true" }) } </div> <div class="control-group float-container"> @Html.LabelFor(x => x.SettingValue) @Html.TextBoxFor(x => x.SettingValue, new { placeholder = "Setting Value" }) </div> <br /> <div class="footer"> <button class="btn primary">Save</button> @if (Model.SettingName != "Website Name") { <a href="@Url.Action("Delete", "Settings", new { settingId = Model.SettingId })" class="btn delete">Delete</a> } <button class="btn" data-dismiss="modal">Cancel</button> </div> }
@model Portal.CMS.Web.Areas.Admin.ViewModels.Settings.EditViewModel @{ Layout = ""; } @using (Html.BeginForm("Edit", "Settings", FormMethod.Post)) { @Html.AntiForgeryToken() @Html.HiddenFor(x => x.SettingId) @Html.ValidationMessage("SettingName") <div class="control-group float-container"> @Html.LabelFor(x => x.SettingName) @Html.TextBoxFor(x => x.SettingName, new { placeholder = "Setting Name" }) </div> <div class="control-group float-container"> @Html.LabelFor(x => x.SettingValue) @Html.TextBoxFor(x => x.SettingValue, new { placeholder = "Setting Value" }) </div> <br /> <div class="footer"> <button class="btn primary">Save</button> <a href="@Url.Action("Delete", "Settings", new { settingId = Model.SettingId })" class="btn delete">Delete</a> <button class="btn" data-dismiss="modal">Cancel</button> </div> }
Exclude test utility from coverage
using System; using System.Collections; using System.Collections.Generic; using TSQLLint.Lib.Rules.RuleViolations; namespace TSQLLint.Tests.Helpers { public class RuleViolationComparer : IComparer, IComparer<RuleViolation> { public int Compare(object x, object y) { if (!(x is RuleViolation lhs) || !(y is RuleViolation rhs)) { throw new InvalidOperationException("cannot compare null object"); } return Compare(lhs, rhs); } public int Compare(RuleViolation left, RuleViolation right) { if (right != null && left != null && left.Line != right.Line) { return -1; } if (right != null && left != null && left.Column != right.Column) { return -1; } if (right != null && left != null && left.RuleName != right.RuleName) { return -1; } return 0; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using TSQLLint.Lib.Rules.RuleViolations; namespace TSQLLint.Tests.Helpers { [ExcludeFromCodeCoverage] public class RuleViolationComparer : IComparer, IComparer<RuleViolation> { public int Compare(object x, object y) { if (!(x is RuleViolation lhs) || !(y is RuleViolation rhs)) { throw new InvalidOperationException("cannot compare null object"); } return Compare(lhs, rhs); } public int Compare(RuleViolation left, RuleViolation right) { if (right != null && left != null && left.Line != right.Line) { return -1; } if (right != null && left != null && left.Column != right.Column) { return -1; } if (right != null && left != null && left.RuleName != right.RuleName) { return -1; } return 0; } } }
Fix for previous minor refactoring.
using System; using System.Linq; using Abp.Dependency; using Castle.Core; using Castle.MicroKernel; namespace Abp.Auditing { internal class AuditingInterceptorRegistrar { private readonly IAuditingConfiguration _auditingConfiguration; private readonly IIocManager _iocManager; public AuditingInterceptorRegistrar(IIocManager iocManager) { _auditingConfiguration = _iocManager.Resolve<IAuditingConfiguration>(); _iocManager = iocManager; } public void Initialize() { if (!_auditingConfiguration.IsEnabled) { return; } _iocManager.IocContainer.Kernel.ComponentRegistered += Kernel_ComponentRegistered; } private void Kernel_ComponentRegistered(string key, IHandler handler) { if (ShouldIntercept(handler.ComponentModel.Implementation)) { handler.ComponentModel.Interceptors.Add(new InterceptorReference(typeof(AuditingInterceptor))); } } private bool ShouldIntercept(Type type) { if (_auditingConfiguration.Selectors.Any(selector => selector.Predicate(type))) { return true; } if (type.IsDefined(typeof(AuditedAttribute), true)) //TODO: true or false? { return true; } if (type.GetMethods().Any(m => m.IsDefined(typeof(AuditedAttribute), true))) //TODO: true or false? { return true; } return false; } } }
using System; using System.Linq; using Abp.Dependency; using Castle.Core; using Castle.MicroKernel; namespace Abp.Auditing { internal class AuditingInterceptorRegistrar { private readonly IIocManager _iocManager; private readonly IAuditingConfiguration _auditingConfiguration; public AuditingInterceptorRegistrar(IIocManager iocManager) { _iocManager = iocManager; _auditingConfiguration = _iocManager.Resolve<IAuditingConfiguration>(); } public void Initialize() { if (!_auditingConfiguration.IsEnabled) { return; } _iocManager.IocContainer.Kernel.ComponentRegistered += Kernel_ComponentRegistered; } private void Kernel_ComponentRegistered(string key, IHandler handler) { if (ShouldIntercept(handler.ComponentModel.Implementation)) { handler.ComponentModel.Interceptors.Add(new InterceptorReference(typeof(AuditingInterceptor))); } } private bool ShouldIntercept(Type type) { if (_auditingConfiguration.Selectors.Any(selector => selector.Predicate(type))) { return true; } if (type.IsDefined(typeof(AuditedAttribute), true)) //TODO: true or false? { return true; } if (type.GetMethods().Any(m => m.IsDefined(typeof(AuditedAttribute), true))) //TODO: true or false? { return true; } return false; } } }
Load only if the file given exists
// vimage - http://torrunt.net/vimage // Corey Zeke Womack (Torrunt) - me@torrunt.net using System; namespace vimage { class Program { static void Main(string[] args) { string file; if (args.Length == 0) { #if DEBUG //file = @"C:\Users\Corey\Pictures\Test Images\Beaver_Transparent.png"; //file = @"C:\Users\Corey\Pictures\Test Images\AdventureTime_TransparentAnimation.gif"; //file = @"C:\Users\Corey\Pictures\Test Images\AnimatedGif.gif"; file = @"G:\Misc\Desktop Backgrounds\0diHF.jpg"; #else return; #endif } else file = args[0]; ImageViewer ImageViewer = new ImageViewer(file); } } }
// vimage - http://torrunt.net/vimage // Corey Zeke Womack (Torrunt) - me@torrunt.net using System; namespace vimage { class Program { static void Main(string[] args) { string file; if (args.Length == 0) return; else file = args[0]; if (System.IO.File.Exists(file)) { ImageViewer imageViewer = new ImageViewer(file); } } } }
Patch delegates.xml for non Windows platform.
// Copyright 2013-2021 Dirk Lemstra <https://github.com/dlemstra/Magick.NET/> // // Licensed under the ImageMagick License (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // https://www.imagemagick.org/script/license.php // // 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.IO; namespace ImageMagick.Configuration { internal sealed class ConfigurationFile : IConfigurationFile { public ConfigurationFile(string fileName) { FileName = fileName; Data = LoadData(); } public string FileName { get; } public string Data { get; set; } private string LoadData() { using (Stream stream = TypeHelper.GetManifestResourceStream(typeof(ConfigurationFile), "ImageMagick.Resources.Xml", FileName)) { using (var reader = new StreamReader(stream)) { return reader.ReadToEnd(); } } } } }
// Copyright 2013-2021 Dirk Lemstra <https://github.com/dlemstra/Magick.NET/> // // Licensed under the ImageMagick License (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // https://www.imagemagick.org/script/license.php // // 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.IO; namespace ImageMagick.Configuration { internal sealed class ConfigurationFile : IConfigurationFile { public ConfigurationFile(string fileName) { FileName = fileName; Data = LoadData(); } public string FileName { get; } public string Data { get; set; } private string LoadData() { using (Stream stream = TypeHelper.GetManifestResourceStream(typeof(ConfigurationFile), "ImageMagick.Resources.Xml", FileName)) { using (var reader = new StreamReader(stream)) { var data = reader.ReadToEnd(); data = UpdateDelegatesXml(data); return data; } } } private string UpdateDelegatesXml(string data) { if (OperatingSystem.IsWindows || FileName != "delegates.xml") return data; return data.Replace("@PSDelegate@", "gs"); } } }
Add text/html as first content type, should possible detect IE..
#region using System.Collections.Generic; #endregion namespace Snooze { public static class ResourceFormatters { static readonly IList<IResourceFormatter> _formatters = new List<IResourceFormatter>(); static ResourceFormatters() { // The order of formatters matters. // Browsers like Chrome will ask for "text/xml, application/xhtml+xml, ..." // But we don't want to use the XML formatter by default // - which would happen since "text/xml" appears first in the list. // So we add an explicitly typed ViewFormatter first. _formatters.Add(new ViewFormatter("application/xhtml+xml")); _formatters.Add(new ViewFormatter("*/*")); // similar reason for this. _formatters.Add(new JsonFormatter()); _formatters.Add(new XmlFormatter()); _formatters.Add(new ViewFormatter()); _formatters.Add(new StringFormatter()); _formatters.Add(new ByteArrayFormatter()); } public static IList<IResourceFormatter> Formatters { get { return _formatters; } } } }
#region using System.Collections.Generic; #endregion namespace Snooze { public static class ResourceFormatters { static readonly IList<IResourceFormatter> _formatters = new List<IResourceFormatter>(); static ResourceFormatters() { // The order of formatters matters. // Browsers like Chrome will ask for "text/xml, application/xhtml+xml, ..." // But we don't want to use the XML formatter by default // - which would happen since "text/xml" appears first in the list. // So we add an explicitly typed ViewFormatter first. _formatters.Add(new ViewFormatter("text/html")); _formatters.Add(new ViewFormatter("application/xhtml+xml")); _formatters.Add(new ViewFormatter("*/*")); // similar reason for this. _formatters.Add(new JsonFormatter()); _formatters.Add(new XmlFormatter()); _formatters.Add(new ViewFormatter()); _formatters.Add(new StringFormatter()); _formatters.Add(new ByteArrayFormatter()); } public static IList<IResourceFormatter> Formatters { get { return _formatters; } } } }
Make griddly defaults and parameters case insensitive
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Griddly.Mvc { public class GriddlyContext { public string Name { get; set; } public bool IsDefaultSkipped { get; set; } public bool IsDeepLink { get; set; } public GriddlyFilterCookieData CookieData { get; set; } public string CookieName => "gf_" + Name; public Dictionary<string, object> Defaults { get; set; } = new Dictionary<string, object>(); public Dictionary<string, object> Parameters { get; set; } = new Dictionary<string, object>(); public int PageNumber { get; set; } public int PageSize { get; set; } public GriddlyExportFormat? ExportFormat { get; set; } public SortField[] SortFields { get; set; } } public class GriddlyFilterCookieData { public Dictionary<string, string[]> Values { get; set; } public SortField[] SortFields { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Griddly.Mvc { public class GriddlyContext { public string Name { get; set; } public bool IsDefaultSkipped { get; set; } public bool IsDeepLink { get; set; } public GriddlyFilterCookieData CookieData { get; set; } public string CookieName => "gf_" + Name; public Dictionary<string, object> Defaults { get; set; } = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase); public Dictionary<string, object> Parameters { get; set; } = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase); public int PageNumber { get; set; } public int PageSize { get; set; } public GriddlyExportFormat? ExportFormat { get; set; } public SortField[] SortFields { get; set; } } public class GriddlyFilterCookieData { public Dictionary<string, string[]> Values { get; set; } public SortField[] SortFields { get; set; } } }
Add field for error responses
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SlackAPI { [RequestPath("conversations.open")] public class ConversationsOpenResponse : Response { public string no_op; public string already_open; public Channel channel; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SlackAPI { [RequestPath("conversations.open")] public class ConversationsOpenResponse : Response { public string no_op; public string already_open; public Channel channel; public string error; }
Add license disclaimer Cleanup formatting
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CefSharp.Wpf.Example.Handlers { public class MenuHandler : IMenuHandler { public bool OnBeforeContextMenu(IWebBrowser browser, IContextMenuParams parameters) { Console.WriteLine("Context menu opened"); Console.WriteLine(parameters.MisspelledWord); return true; } } }
// 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; namespace CefSharp.Wpf.Example.Handlers { public class MenuHandler : IMenuHandler { public bool OnBeforeContextMenu(IWebBrowser browser, IContextMenuParams parameters) { Console.WriteLine("Context menu opened"); Console.WriteLine(parameters.MisspelledWord); return true; } } }
Add property 'Descricao' to class 'DetalheCurso'
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Fatec.Treinamento.Model.DTO { public class DetalhesCurso { public int Id { get; set; } public string Nome { get; set; } public string Assunto { get; set; } public string Autor { get; set; } public DateTime DataCriacao { get; set; } public int Classificacao { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Fatec.Treinamento.Model.DTO { public class DetalhesCurso { public int Id { get; set; } public string Nome { get; set; } public string Assunto { get; set; } public string Autor { get; set; } public DateTime DataCriacao { get; set; } public int Classificacao { get; set; } //public string Descricao { get; set; } } }
Add Peter Parker to contact page.
@{ ViewBag.Title = "Contact"; } <h2>@ViewBag.Title.</h2> <h3>@ViewBag.Message</h3> <address> One Microsoft Way<br /> Redmond, WA 98052-6399<br /> <abbr title="Phone">P:</abbr> 425.555.0100 </address> <address> <strong>Support:</strong> <a href="mailto:Support@example.com">Support@wechangedthis.com</a><br /> <strong>Marketing:</strong> <a href="mailto:Marketing@example.com">Marketing@example.com</a> <strong>Batman:</strong> <a href="mailto:Batman@batman.com">Batman@batman.com</a> </address>
@{ ViewBag.Title = "Contact"; } <h2>@ViewBag.Title.</h2> <h3>@ViewBag.Message</h3> <address> One Microsoft Way<br /> Redmond, WA 98052-6399<br /> <abbr title="Phone">P:</abbr> 425.555.0100 </address> <address> <strong>Support:</strong> <a href="mailto:Support@example.com">Support@wechangedthis.com</a><br /> <strong>Marketing:</strong> <a href="mailto:Marketing@example.com">Marketing@example.com</a> <strong>Batman:</strong> <a href="mailto:Batman@batman.com">Batman@batman.com</a> <strong>Peter Parker</strong> <a href="mailto:spiderman@spiderman.com">Spiderman@spiderman.com</a> </address>
Fix default name for images
// // Image.cs // // Author: // Benito Palacios Sánchez (aka pleonex) <benito356@gmail.com> // // Copyright (c) 2015 Benito Palacios Sánchez (c) 2015 // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. using System; namespace Deblocus.Entities { public class Image { private string name; public Image() { Name = DefaultName; } public static string DefaultName { get { return "No Title"; } } public virtual int Id { get; protected set; } public virtual byte[] Data { get; set; } public virtual string Name { get { return name; } set { name = string.IsNullOrEmpty(value) ? DefaultName : value; } } public virtual string Description { get; set; } } }
// // Image.cs // // Author: // Benito Palacios Sánchez (aka pleonex) <benito356@gmail.com> // // Copyright (c) 2015 Benito Palacios Sánchez (c) 2015 // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. using System; namespace Deblocus.Entities { public class Image { private string name; public Image() { Name = DefaultName; } public static string DefaultName { get { return "No Name"; } } public virtual int Id { get; protected set; } public virtual byte[] Data { get; set; } public virtual string Name { get { return name; } set { name = string.IsNullOrEmpty(value) ? DefaultName : value; } } public virtual string Description { get; set; } } }
Fix html enconded characters in plain text
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; namespace AppStudio.Uwp.Html { public sealed class HtmlText : HtmlFragment { public string Content { get; set; } public HtmlText() { Name = "text"; } public HtmlText(string doc, int startIndex, int endIndex) : this() { if (!string.IsNullOrEmpty(doc) && endIndex - startIndex > 0) { Content = WebUtility.HtmlDecode(doc.Substring(startIndex, endIndex - startIndex)); } } public override string ToString() { return Content; } internal static HtmlText Create(string doc, HtmlTag startTag, HtmlTag endTag) { var startIndex = 0; if (startTag != null) { startIndex = startTag.StartIndex + startTag.Length; } var endIndex = doc.Length; if (endTag != null) { endIndex = endTag.StartIndex; } var text = new HtmlText(doc, startIndex, endIndex); if (text != null && !string.IsNullOrEmpty(text.Content)) { return text; } return null; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; namespace AppStudio.Uwp.Html { public sealed class HtmlText : HtmlFragment { private string _content; public string Content { get { return _content; } set { _content = WebUtility.HtmlDecode(value); } } public HtmlText() { Name = "text"; } public HtmlText(string doc, int startIndex, int endIndex) : this() { if (!string.IsNullOrEmpty(doc) && endIndex - startIndex > 0) { Content = doc.Substring(startIndex, endIndex - startIndex); } } public override string ToString() { return Content; } internal static HtmlText Create(string doc, HtmlTag startTag, HtmlTag endTag) { var startIndex = 0; if (startTag != null) { startIndex = startTag.StartIndex + startTag.Length; } var endIndex = doc.Length; if (endTag != null) { endIndex = endTag.StartIndex; } var text = new HtmlText(doc, startIndex, endIndex); if (text != null && !string.IsNullOrEmpty(text.Content)) { return text; } return null; } } }
Allow model config to be modified
namespace Halcyon.HAL { public interface IHALModelConfig { string LinkBase { get; } bool ForceHAL { get; } } }
namespace Halcyon.HAL { public interface IHALModelConfig { string LinkBase { get; set; } bool ForceHAL { get; set; } } }
Change the behavior of the object serializer so that objects are initialized with values instead of Nulls
using System.Collections.Generic; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Serialization; namespace LoveSeat { public interface IObjectSerializer<T> { T Deserialize(string json); string Serialize(object obj); } public class ObjectSerializer<T> : IObjectSerializer<T> { protected readonly JsonSerializerSettings settings; public ObjectSerializer() { settings = new JsonSerializerSettings(); var converters = new List<JsonConverter> { new IsoDateTimeConverter() }; settings.Converters = converters; settings.ContractResolver = new CamelCasePropertyNamesContractResolver(); settings.NullValueHandling = NullValueHandling.Ignore; } public virtual T Deserialize(string json) { return JsonConvert.DeserializeObject<T>(json.Replace("_id", "id").Replace("_rev", "rev"), settings); } public virtual string Serialize(object obj) { return JsonConvert.SerializeObject(obj, Formatting.Indented, settings).Replace("id", "_id").Replace("rev", "_rev"); } } }
using System.Collections.Generic; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Serialization; namespace LoveSeat { public interface IObjectSerializer<T> { T Deserialize(string json); string Serialize(object obj); } public class ObjectSerializer<T> : IObjectSerializer<T> { protected readonly JsonSerializerSettings settings; public ObjectSerializer() { settings = new JsonSerializerSettings(); var converters = new List<JsonConverter> { new IsoDateTimeConverter() }; settings.Converters = converters; settings.ContractResolver = new CamelCasePropertyNamesContractResolver(); settings.NullValueHandling = NullValueHandling.Include; } public virtual T Deserialize(string json) { return JsonConvert.DeserializeObject<T>(json.Replace("_id", "id").Replace("_rev", "rev"), settings); } public virtual string Serialize(object obj) { return JsonConvert.SerializeObject(obj, Formatting.Indented, settings).Replace("id", "_id").Replace("rev", "_rev"); } } }
Add test for 2000 (MM) - this should have been done before adding loop for M.
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using VasysRomanNumeralsKata; namespace VasysRomanNumeralsKataTest { [TestClass] public class ToRomanNumeralsTest { [TestMethod] public void WhenRomanNumeralExtensionIsPassedTenItReturnsX() { int ten = 10; Assert.IsTrue(ten.ToRomanNumeral() == "X"); } [TestMethod] public void WhenRomanNumeralExtensionIsPassedNumbersDivisibleByOneHundredItReturnsARomanNumeral() { int oneThousand = 1000; Assert.IsTrue(oneThousand.ToRomanNumeral() == "M"); int nineHundred = 900; Assert.IsTrue(nineHundred.ToRomanNumeral() == "CM"); int fiveHundred = 500; Assert.IsTrue(fiveHundred.ToRomanNumeral() == "D"); int fourHundred = 400; Assert.IsTrue(fourHundred.ToRomanNumeral() == "CD"); int oneHundred = 100; Assert.IsTrue(oneHundred.ToRomanNumeral() == "C"); int twoHundred = 200; Assert.IsTrue(twoHundred.ToRomanNumeral() == "CC"); int threeHundred = 300; Assert.IsTrue(threeHundred.ToRomanNumeral() == "CCC"); } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using VasysRomanNumeralsKata; namespace VasysRomanNumeralsKataTest { [TestClass] public class ToRomanNumeralsTest { [TestMethod] public void WhenRomanNumeralExtensionIsPassedTenItReturnsX() { int ten = 10; Assert.IsTrue(ten.ToRomanNumeral() == "X"); } [TestMethod] public void WhenRomanNumeralExtensionIsPassedNumbersDivisibleByOneHundredItReturnsARomanNumeral() { int oneThousand = 1000; Assert.IsTrue(oneThousand.ToRomanNumeral() == "M"); int nineHundred = 900; Assert.IsTrue(nineHundred.ToRomanNumeral() == "CM"); int fiveHundred = 500; Assert.IsTrue(fiveHundred.ToRomanNumeral() == "D"); int fourHundred = 400; Assert.IsTrue(fourHundred.ToRomanNumeral() == "CD"); int oneHundred = 100; Assert.IsTrue(oneHundred.ToRomanNumeral() == "C"); int twoHundred = 200; Assert.IsTrue(twoHundred.ToRomanNumeral() == "CC"); int threeHundred = 300; Assert.IsTrue(threeHundred.ToRomanNumeral() == "CCC"); int twoThousand = 2000; Assert.IsTrue(twoThousand.ToRomanNumeral() == "MM"); } } }
Include GogoKit version in User-Agent header
using System; using System.Collections.Generic; using System.Globalization; using System.Net.Http; using System.Net.Http.Headers; using System.Threading; using System.Threading.Tasks; namespace GogoKit.Http { public class UserAgentHandler : DelegatingHandler { private readonly IReadOnlyList<ProductInfoHeaderValue> _userAgentHeaderValues; public UserAgentHandler(ProductHeaderValue product) { Requires.ArgumentNotNull(product, nameof(product)); _userAgentHeaderValues = GetUserAgentHeaderValues(product); } private IReadOnlyList<ProductInfoHeaderValue> GetUserAgentHeaderValues(ProductHeaderValue product) { return new List<ProductInfoHeaderValue> { new ProductInfoHeaderValue(product), //new ProductInfoHeaderValue($"({CultureInfo.CurrentCulture.Name}; GogoKit {AssemblyVersionInformation.Version})") }; } protected override Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { foreach (var product in _userAgentHeaderValues) { request.Headers.UserAgent.Add(product); } return base.SendAsync(request, cancellationToken); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Net.Http; using System.Net.Http.Headers; using System.Reflection; using System.Threading; using System.Threading.Tasks; namespace GogoKit.Http { public class UserAgentHandler : DelegatingHandler { private static readonly ProductInfoHeaderValue GogoKitVersionHeaderValue = new ProductInfoHeaderValue( "GogoKit", FileVersionInfo.GetVersionInfo(typeof(UserAgentHandler).Assembly.Location).ProductVersion); private readonly IReadOnlyList<ProductInfoHeaderValue> _userAgentHeaderValues; public UserAgentHandler(ProductHeaderValue product) { Requires.ArgumentNotNull(product, nameof(product)); _userAgentHeaderValues = GetUserAgentHeaderValues(product); } private IReadOnlyList<ProductInfoHeaderValue> GetUserAgentHeaderValues(ProductHeaderValue product) { return new List<ProductInfoHeaderValue> { new ProductInfoHeaderValue(product), GogoKitVersionHeaderValue }; } protected override Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { foreach (var product in _userAgentHeaderValues) { request.Headers.UserAgent.Add(product); } return base.SendAsync(request, cancellationToken); } } }
Make MethodReplacer change opcode to CALL as default
using System.Collections.Generic; using System.Reflection; using System.Reflection.Emit; namespace Harmony { public static class Transpilers { public static IEnumerable<CodeInstruction> MethodReplacer(this IEnumerable<CodeInstruction> instructions, MethodBase from, MethodBase to) { foreach (var instruction in instructions) { var method = instruction.operand as MethodBase; if (method == from) instruction.operand = to; yield return instruction; } } public static IEnumerable<CodeInstruction> DebugLogger(this IEnumerable<CodeInstruction> instructions, string text) { yield return new CodeInstruction(OpCodes.Ldstr, text); yield return new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(FileLog), nameof(FileLog.Log))); foreach (var instruction in instructions) yield return instruction; } // more added soon } }
using System.Collections.Generic; using System.Reflection; using System.Reflection.Emit; namespace Harmony { public static class Transpilers { public static IEnumerable<CodeInstruction> MethodReplacer(this IEnumerable<CodeInstruction> instructions, MethodBase from, MethodBase to, OpCode? callOpcode = null) { foreach (var instruction in instructions) { var method = instruction.operand as MethodBase; if (method == from) { instruction.opcode = callOpcode ?? OpCodes.Call; instruction.operand = to; } yield return instruction; } } public static IEnumerable<CodeInstruction> DebugLogger(this IEnumerable<CodeInstruction> instructions, string text) { yield return new CodeInstruction(OpCodes.Ldstr, text); yield return new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(FileLog), nameof(FileLog.Log))); foreach (var instruction in instructions) yield return instruction; } // more added soon } }
Update agent name to only allow 18 characters so that it looks good on the screen
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using FluentValidation; using PlanetWars.Shared; namespace PlanetWars.Validators { public class LogonRequestValidator : AbstractValidator<LogonRequest> { public LogonRequestValidator() { RuleFor(logon => logon.AgentName) .NotEmpty().WithMessage("Please use a non empty agent name, logon failed") .Length(1, 20).WithMessage("Please use an agent name between 1-20 characters, logon failed"); RuleFor(logon => logon.MapGeneration) .Must(x => x == MapGenerationOption.Basic || x == MapGenerationOption.Random).WithMessage("Please use a valid Map Generation Option"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using FluentValidation; using PlanetWars.Shared; namespace PlanetWars.Validators { public class LogonRequestValidator : AbstractValidator<LogonRequest> { public LogonRequestValidator() { RuleFor(logon => logon.AgentName) .NotEmpty().WithMessage("Please use a non empty agent name, logon failed") .Length(1, 18).WithMessage("Please use an agent name between 1-18 characters, logon failed"); RuleFor(logon => logon.MapGeneration) .Must(x => x == MapGenerationOption.Basic || x == MapGenerationOption.Random).WithMessage("Please use a valid Map Generation Option"); } } }
Change this to a double so that we don't have to always cast.
using System; using engine.core; namespace engine.rules { public class PercentageDiscount : Rule { private readonly string m_ApplicableItemName; private readonly int m_Percentage; public PercentageDiscount(string applicableItemName, int percentage) { m_ApplicableItemName = applicableItemName; m_Percentage = percentage; } public override Basket Apply(Basket basket) { var discountedBasket = new Basket(); foreach (var item in basket) { discountedBasket.Add(item); if (item.Name.Equals(m_ApplicableItemName) && !item.UsedInOffer) { var discountToApply = -(int) Math.Ceiling(item.Price * ((double) m_Percentage / 100)); discountedBasket.Add(string.Format("{0}:{1}% discount", m_ApplicableItemName, m_Percentage), discountToApply); } } return discountedBasket; } } }
using System; using engine.core; namespace engine.rules { public class PercentageDiscount : Rule { private readonly string m_ApplicableItemName; private readonly double m_Percentage; public PercentageDiscount(string applicableItemName, int percentage) { m_ApplicableItemName = applicableItemName; m_Percentage = percentage; } public override Basket Apply(Basket basket) { var discountedBasket = new Basket(); foreach (var item in basket) { discountedBasket.Add(item); if (item.Name.Equals(m_ApplicableItemName) && !item.UsedInOffer) { var discountToApply = -(int) Math.Ceiling(item.Price * (m_Percentage / 100)); discountedBasket.Add(string.Format("{0}:{1}% discount", m_ApplicableItemName, m_Percentage), discountToApply); } } return discountedBasket; } } }
Make telemetry break execution if debugger is attached instead of pushing report
using AxoCover.Models.Extensions; using AxoCover.Properties; using System; using System.Threading.Tasks; using System.Windows; using System.Windows.Threading; namespace AxoCover.Models { public abstract class TelemetryManager : ITelemetryManager { protected IEditorContext _editorContext; public bool IsTelemetryEnabled { get { return Settings.Default.IsTelemetryEnabled; } set { Settings.Default.IsTelemetryEnabled = value; } } public TelemetryManager(IEditorContext editorContext) { _editorContext = editorContext; Application.Current.DispatcherUnhandledException += OnDispatcherUnhandledException; } private void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e) { var description = e.Exception.GetDescription(); if (description.Contains(nameof(AxoCover))) { _editorContext.WriteToLog(Resources.ExceptionEncountered); _editorContext.WriteToLog(description); UploadExceptionAsync(e.Exception); e.Handled = true; } } public abstract Task<bool> UploadExceptionAsync(Exception exception); } }
using AxoCover.Models.Extensions; using AxoCover.Properties; using System; using System.Diagnostics; using System.Threading.Tasks; using System.Windows; using System.Windows.Threading; namespace AxoCover.Models { public abstract class TelemetryManager : ITelemetryManager { protected IEditorContext _editorContext; public bool IsTelemetryEnabled { get { return Settings.Default.IsTelemetryEnabled; } set { Settings.Default.IsTelemetryEnabled = value; } } public TelemetryManager(IEditorContext editorContext) { _editorContext = editorContext; Application.Current.DispatcherUnhandledException += OnDispatcherUnhandledException; } private void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e) { var description = e.Exception.GetDescription(); if (description.Contains(nameof(AxoCover))) { _editorContext.WriteToLog(Resources.ExceptionEncountered); _editorContext.WriteToLog(description); if (Debugger.IsAttached) { Debugger.Break(); } else { UploadExceptionAsync(e.Exception); } e.Handled = true; } } public abstract Task<bool> UploadExceptionAsync(Exception exception); } }
Fix a null ref error submitting MobileMiner stats without Network Devices
using MultiMiner.Engine; using MultiMiner.Utility.Serialization; using System.Collections.Generic; using System.IO; namespace MultiMiner.Win.Data.Configuration { public class NetworkDevices { public class NetworkDevice { public string IPAddress { get; set; } public int Port { get; set; } } public List<NetworkDevice> Devices { get; set; } private static string NetworkDevicesConfigurationFileName() { return Path.Combine(ApplicationPaths.AppDataPath(), "NetworkDevicesConfiguration.xml"); } public void SaveNetworkDevicesConfiguration() { ConfigurationReaderWriter.WriteConfiguration(Devices, NetworkDevicesConfigurationFileName()); } public void LoadNetworkDevicesConfiguration() { Devices = ConfigurationReaderWriter.ReadConfiguration<List<NetworkDevice>>(NetworkDevicesConfigurationFileName()); } } }
using MultiMiner.Engine; using MultiMiner.Utility.Serialization; using System.Collections.Generic; using System.IO; namespace MultiMiner.Win.Data.Configuration { public class NetworkDevices { public class NetworkDevice { public string IPAddress { get; set; } public int Port { get; set; } } public List<NetworkDevice> Devices { get; set; } public NetworkDevices() { //set a default - null ref errors if submitting MobileMiner stats before scan is completed Devices = new List<NetworkDevice>(); } private static string NetworkDevicesConfigurationFileName() { return Path.Combine(ApplicationPaths.AppDataPath(), "NetworkDevicesConfiguration.xml"); } public void SaveNetworkDevicesConfiguration() { ConfigurationReaderWriter.WriteConfiguration(Devices, NetworkDevicesConfigurationFileName()); } public void LoadNetworkDevicesConfiguration() { Devices = ConfigurationReaderWriter.ReadConfiguration<List<NetworkDevice>>(NetworkDevicesConfigurationFileName()); } } }
Change Order of Loading Styles
<!DOCTYPE html> <html lang="en-gb"> <head> <title>@SettingHelper.Get("Website Name"): @ViewBag.Title</title> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0" /> <meta name="description" content="@SettingHelper.Get("Description Meta Tag")"> @RenderSection("Styles", false) @Styles.Render("~/Resources/CSS/Bootstrap") @Styles.Render("~/Resources/CSS/FontAwesome") @Styles.Render("~/Resources/CSS/Administration/Framework") @Styles.Render("~/Resources/CSS/PageBuilder/Framework") @Styles.Render("~/Resources/CSS/Framework") @Scripts.Render("~/Resources/JavaScript/JQuery") @Scripts.Render("~/Resources/JavaScript/JQueryUI") @RenderSection("HEADScripts", false) @Html.Partial("_Analytics") </head> <body> @Html.Partial("_NavBar") @Html.Partial("_Administration") @RenderBody() @if (UserHelper.IsAdmin) { @Styles.Render("~/Resources/CSS/Bootstrap/Tour") @Styles.Render("~/Resources/CSS/PageBuilder/Framework/Administration") } <link href="@Url.Action("Render", "Theme", new { area = "Builder" })" rel="stylesheet" type="text/css" /> @Html.Partial("_DOMScripts") @RenderSection("DOMScripts", false) </body> </html>
<!DOCTYPE html> <html lang="en-gb"> <head> <title>@SettingHelper.Get("Website Name"): @ViewBag.Title</title> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0" /> <meta name="description" content="@SettingHelper.Get("Description Meta Tag")"> @RenderSection("Styles", false) @Styles.Render("~/Resources/CSS/Bootstrap") @Styles.Render("~/Resources/CSS/FontAwesome") @Styles.Render("~/Resources/CSS/Administration/Framework") @Styles.Render("~/Resources/CSS/PageBuilder/Framework") @Styles.Render("~/Resources/CSS/Framework") @if (UserHelper.IsAdmin) { @Styles.Render("~/Resources/CSS/Bootstrap/Tour") @Styles.Render("~/Resources/CSS/PageBuilder/Framework/Administration") } <link href="@Url.Action("Render", "Theme", new { area = "Builder" })" rel="stylesheet" type="text/css" /> @Scripts.Render("~/Resources/JavaScript/JQuery") @Scripts.Render("~/Resources/JavaScript/JQueryUI") @RenderSection("HEADScripts", false) @Html.Partial("_Analytics") </head> <body> @Html.Partial("_NavBar") @Html.Partial("_Administration") @RenderBody() @Html.Partial("_DOMScripts") @RenderSection("DOMScripts", false) </body> </html>
Allow syntax like "hex 56"
using static MyOwnSearchEngine.HtmlFactory; namespace MyOwnSearchEngine { public class Hex : IProcessor { public string GetResult(Query query) { var integer = query.TryGetStructure<Integer>(); if (integer != null) { return GetResult(integer.Value); } var separatedList = query.TryGetStructure<SeparatedList>(); if (separatedList != null && separatedList.Count >= 2) { var number = separatedList.TryGetStructure<Integer>(0); if (number != null) { var keyword1 = separatedList.TryGetStructure<Keyword>(1); if (keyword1 != null) { if (keyword1 == "hex" && separatedList.Count == 2) { return GetResult(number.Value); } if (separatedList.Count == 3 && (keyword1 == "in" || keyword1 == "to") && separatedList.TryGetStructure<Keyword>(2) == "hex") { return GetResult(number.Value); } } } } return null; } private string GetResult(int value) { return Div(Escape($"{value} = 0x{value.ToString("X")}")); } } }
using static MyOwnSearchEngine.HtmlFactory; namespace MyOwnSearchEngine { public class Hex : IProcessor { public string GetResult(Query query) { var integer = query.TryGetStructure<Integer>(); if (integer != null) { return GetResult(integer.Value); } var separatedList = query.TryGetStructure<SeparatedList>(); if (separatedList != null && separatedList.Count >= 2) { var number = separatedList.TryGetStructure<Integer>(0); if (number != null) { var keyword1 = separatedList.TryGetStructure<Keyword>(1); if (keyword1 != null) { if (keyword1 == "hex" && separatedList.Count == 2) { return GetResult(number.Value); } if (separatedList.Count == 3 && (keyword1 == "in" || keyword1 == "to") && separatedList.TryGetStructure<Keyword>(2) == "hex") { return GetResult(number.Value); } } } else { number = separatedList.TryGetStructure<Integer>(1); var keyword1 = separatedList.TryGetStructure<Keyword>(0); if (number != null && keyword1 != null && keyword1 == "hex" && separatedList.Count == 2) { return GetResult(number.Value); } } } return null; } private string GetResult(int value) { return Div(Escape($"{value} = 0x{value.ToString("X")}")); } } }
Change "Countdown" widget default "TimeFormat"
using System; using DesktopWidgets.Classes; namespace DesktopWidgets.Widgets.CountdownClock { public class Settings : WidgetClockSettingsBase { public DateTime EndDateTime { get; set; } = DateTime.Now; } }
using System; using DesktopWidgets.Classes; namespace DesktopWidgets.Widgets.CountdownClock { public class Settings : WidgetClockSettingsBase { public Settings() { TimeFormat = "dd:hh:mm:ss"; } public DateTime EndDateTime { get; set; } = DateTime.Now; } }
Change conditional from decorator to a task
public class Conditional : DecoratorTask { private ConditionalDelegate conditionalDelegate; public Conditional(string name, ConditionalDelegate conditionalDelegate) : base(name) { this.conditionalDelegate = conditionalDelegate; } public override ReturnCode Update() { var value = conditionalDelegate(); if (value) { return ReturnCode.Succeed; } else { return ReturnCode.Fail; } } } public delegate bool ConditionalDelegate();
public class Conditional : Task { private ConditionalDelegate conditionalDelegate; public Conditional(string name, ConditionalDelegate conditionalDelegate) : base(name) { this.conditionalDelegate = conditionalDelegate; } public override ReturnCode Update() { var value = conditionalDelegate(); if (value) { return ReturnCode.Succeed; } else { return ReturnCode.Fail; } } } public delegate bool ConditionalDelegate();
Add type string converter documentation.
using System; using System.Collections.Generic; using System.Text; namespace SharpConfig { public interface ITypeStringConverter { string ConvertToString(object value); object ConvertFromString(string value, Type hint); Type ConvertibleType { get; } } public abstract class TypeStringConverter<T> : ITypeStringConverter { public abstract string ConvertToString(object value); public abstract object ConvertFromString(string value, Type hint); public Type ConvertibleType { get { return typeof(T); } } } }
using System; using System.Collections.Generic; using System.Text; namespace SharpConfig { /// <summary> /// Defines a type-to-string and string-to-type converter /// that is used for the conversion of setting values. /// </summary> public interface ITypeStringConverter { /// <summary> /// Converts an object to its string representation. /// </summary> /// <param name="value">The value to convert.</param> /// <returns>The object's string representation.</returns> string ConvertToString(object value); /// <summary> /// Converts a string value to an object of this converter's type. /// </summary> /// <param name="value"></param> /// <param name="hint"> /// A type hint. This is used rarely, such as in the enum converter. /// The enum converter's official type is Enum, whereas the type hint /// represents the underlying enum type. /// This parameter can be safely ignored for custom converters. /// </param> /// <returns>The converted object.</returns> object ConvertFromString(string value, Type hint); /// <summary> /// The type that this converter is able to convert to and from a string. /// </summary> Type ConvertibleType { get; } } /// <summary> /// Represents a type-to-string and string-to-type converter /// that is used for the conversion of setting values. /// </summary> /// <typeparam name="T">The type that this converter is able to convert.</typeparam> public abstract class TypeStringConverter<T> : ITypeStringConverter { /// <summary> /// Converts an object to its string representation. /// </summary> /// <param name="value">The value to convert.</param> /// <returns>The object's string representation.</returns> public abstract string ConvertToString(object value); /// <summary> /// Converts a string value to an object of this converter's type. /// </summary> /// <param name="value"></param> /// <param name="hint"> /// A type hint. This is used rarely, such as in the enum converter. /// The enum converter's official type is Enum, whereas the type hint /// represents the underlying enum type. /// This parameter can be safely ignored for custom converters. /// </param> /// <returns>The converted object.</returns> public abstract object ConvertFromString(string value, Type hint); /// <summary> /// The type that this converter is able to convert to and from a string. /// </summary> public Type ConvertibleType { get { return typeof(T); } } } }
Fix isAuthenticated -> authenticated to get it working - Camunda docs error
using System; using System.Collections.Generic; using System.Text; namespace Camunda.Api.Client.Identity { public class IdentityVerifiedUser { /// <summary> /// The id of the user /// </summary> public string AuthenticatedUser; /// <summary> /// Verification successful or not /// </summary> public bool IsAuthenticated; } }
using System; using System.Collections.Generic; using System.Text; namespace Camunda.Api.Client.Identity { public class IdentityVerifiedUser { /// <summary> /// The id of the user /// </summary> public string AuthenticatedUser; /// <summary> /// Verification successful or not /// </summary> public bool Authenticated; } }
Fix namespace function not using top level types
using dnlib.DotNet; namespace Confuser.Core.Project.Patterns { /// <summary> /// A function that compare the namespace of definition. /// </summary> public class NamespaceFunction : PatternFunction { internal const string FnName = "namespace"; /// <inheritdoc /> public override string Name { get { return FnName; } } /// <inheritdoc /> public override int ArgumentCount { get { return 1; } } /// <inheritdoc /> public override object Evaluate(IDnlibDef definition) { if (!(definition is TypeDef) && !(definition is IMemberDef)) return false; object ns = Arguments[0].Evaluate(definition); var type = definition as TypeDef; if (type == null) type = ((IMemberDef)definition).DeclaringType; return type != null && type.Namespace == ns.ToString(); } } }
using dnlib.DotNet; namespace Confuser.Core.Project.Patterns { /// <summary> /// A function that compare the namespace of definition. /// </summary> public class NamespaceFunction : PatternFunction { internal const string FnName = "namespace"; /// <inheritdoc /> public override string Name { get { return FnName; } } /// <inheritdoc /> public override int ArgumentCount { get { return 1; } } /// <inheritdoc /> public override object Evaluate(IDnlibDef definition) { if (!(definition is TypeDef) && !(definition is IMemberDef)) return false; object ns = Arguments[0].Evaluate(definition); var type = definition as TypeDef; if (type == null) type = ((IMemberDef)definition).DeclaringType; while (type.IsNested) type = type.DeclaringType; return type != null && type.Namespace == ns.ToString(); } } }
Fix Dic2 lexer regexes to work properly on Linux
using System.Collections.Generic; using System.Text.RegularExpressions; using Rant.Stringes; using Rant.Stringes.Tokens; namespace Rant.Vocabulary { internal static class Dic2Lexer { private const RegexOptions DicRegexOptions = RegexOptions.Compiled; private static readonly LexerRules<DicTokenType> Rules; static Dic2Lexer() { Rules = new LexerRules<DicTokenType> { {new Regex(@"\#\s*(?<value>[^\r]*)[\s\r]*(?=\#|\||\>|$)", DicRegexOptions), DicTokenType.Directive, 2}, {new Regex(@"\|\s*(?<value>[^\r]*)[\s\r]*(?=\#|\||\>|$)", DicRegexOptions), DicTokenType.Property, 2}, {new Regex(@"\>\s*(?<value>[^\r]*)[\s\r]*(?=\#|\||\>|$)", DicRegexOptions), DicTokenType.Entry, 2}, {new Regex(@"\s+"), DicTokenType.Ignore} }; Rules.AddEndToken(DicTokenType.EOF); Rules.IgnoreRules.Add(DicTokenType.Ignore); } public static IEnumerable<Token<DicTokenType>> Tokenize(string data) { Token<DicTokenType> token; var reader = new StringeReader(data); while ((token = reader.ReadToken(Rules)).Identifier != DicTokenType.EOF) { yield return token; } } } internal enum DicTokenType { Directive, Entry, Property, Ignore, EOF } }
using System.Collections.Generic; using System.Text.RegularExpressions; using Rant.Stringes; using Rant.Stringes.Tokens; namespace Rant.Vocabulary { internal static class Dic2Lexer { private const RegexOptions DicRegexOptions = RegexOptions.Compiled; private static readonly LexerRules<DicTokenType> Rules; static Dic2Lexer() { Rules = new LexerRules<DicTokenType> { {new Regex(@"\#\s*(?<value>.*?)[\s\r]*(?=\#|\||\>|$)", DicRegexOptions), DicTokenType.Directive, 2}, {new Regex(@"\|\s*(?<value>.*?)[\s\r]*(?=\#|\||\>|$)", DicRegexOptions), DicTokenType.Property, 2}, {new Regex(@"\>\s*(?<value>.*?)[\s\r]*(?=\#|\||\>|$)", DicRegexOptions), DicTokenType.Entry, 2}, {new Regex(@"\s+"), DicTokenType.Ignore} }; Rules.AddEndToken(DicTokenType.EOF); Rules.IgnoreRules.Add(DicTokenType.Ignore); } public static IEnumerable<Token<DicTokenType>> Tokenize(string data) { Token<DicTokenType> token; var reader = new StringeReader(data); while ((token = reader.ReadToken(Rules)).Identifier != DicTokenType.EOF) { yield return token; } } } internal enum DicTokenType { Directive, Entry, Property, Ignore, EOF } }
Add test coverage for score counter alignment
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using System.Linq; using NUnit.Framework; using osu.Framework.Testing; using osu.Game.Rulesets; using osu.Game.Rulesets.Osu; using osu.Game.Screens.Play.HUD; namespace osu.Game.Tests.Visual.Gameplay { public class TestSceneSkinnableScoreCounter : SkinnableTestScene { private IEnumerable<SkinnableScoreCounter> scoreCounters => CreatedDrawables.OfType<SkinnableScoreCounter>(); protected override Ruleset CreateRulesetForSkinProvider() => new OsuRuleset(); [SetUpSteps] public void SetUpSteps() { AddStep("Create combo counters", () => SetContents(() => { var comboCounter = new SkinnableScoreCounter(); comboCounter.Current.Value = 1; return comboCounter; })); } [Test] public void TestScoreCounterIncrementing() { AddStep(@"Reset all", delegate { foreach (var s in scoreCounters) s.Current.Value = 0; }); AddStep(@"Hit! :D", delegate { foreach (var s in scoreCounters) s.Current.Value += 300; }); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using System.Linq; using NUnit.Framework; using osu.Framework.Extensions.IEnumerableExtensions; using osu.Framework.Testing; using osu.Game.Rulesets; using osu.Game.Rulesets.Osu; using osu.Game.Screens.Play.HUD; namespace osu.Game.Tests.Visual.Gameplay { public class TestSceneSkinnableScoreCounter : SkinnableTestScene { private IEnumerable<SkinnableScoreCounter> scoreCounters => CreatedDrawables.OfType<SkinnableScoreCounter>(); protected override Ruleset CreateRulesetForSkinProvider() => new OsuRuleset(); [SetUpSteps] public void SetUpSteps() { AddStep("Create combo counters", () => SetContents(() => { var comboCounter = new SkinnableScoreCounter(); comboCounter.Current.Value = 1; return comboCounter; })); } [Test] public void TestScoreCounterIncrementing() { AddStep(@"Reset all", delegate { foreach (var s in scoreCounters) s.Current.Value = 0; }); AddStep(@"Hit! :D", delegate { foreach (var s in scoreCounters) s.Current.Value += 300; }); } [Test] public void TestVeryLargeScore() { AddStep("set large score", () => scoreCounters.ForEach(counter => counter.Current.Value = 1_00_000_000)); } } }
Add test for day 18 part 2
// Copyright (c) Martin Costello, 2015. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. namespace MartinCostello.AdventOfCode.Puzzles.Y2016 { using Xunit; /// <summary> /// A class containing tests for the <see cref="Day18"/> class. This class cannot be inherited. /// </summary> public static class Day18Tests { [Theory] [InlineData("..^^.", 3, 6)] [InlineData(".^^.^.^^^^", 10, 38)] public static void Y2016_Day18_FindSafeTileCount_Returns_Correct_Solution(string firstRowTiles, int rows, int expected) { // Act int actual = Day18.FindSafeTileCount(firstRowTiles, rows); // Assert Assert.Equal(expected, actual); } [Theory] [InlineData("40", 1987)] public static void Y2016_Day18_Solve_Returns_Correct_Solution(string rows, int expected) { // Arrange string[] args = new[] { rows }; // Act var puzzle = PuzzleTestHelpers.SolvePuzzle<Day18>(args); // Assert Assert.Equal(expected, puzzle.SafeTileCount); } } }
// Copyright (c) Martin Costello, 2015. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. namespace MartinCostello.AdventOfCode.Puzzles.Y2016 { using Xunit; /// <summary> /// A class containing tests for the <see cref="Day18"/> class. This class cannot be inherited. /// </summary> public static class Day18Tests { [Theory] [InlineData("..^^.", 3, 6)] [InlineData(".^^.^.^^^^", 10, 38)] public static void Y2016_Day18_FindSafeTileCount_Returns_Correct_Solution(string firstRowTiles, int rows, int expected) { // Act int actual = Day18.FindSafeTileCount(firstRowTiles, rows); // Assert Assert.Equal(expected, actual); } [Theory] [InlineData("40", 1987)] [InlineData("400000", 19984714)] public static void Y2016_Day18_Solve_Returns_Correct_Solution(string rows, int expected) { // Arrange string[] args = new[] { rows }; // Act var puzzle = PuzzleTestHelpers.SolvePuzzle<Day18>(args); // Assert Assert.Equal(expected, puzzle.SafeTileCount); } } }
Fix saving changes when seeding data
using System; using System.Linq; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; using Diploms.Core; using System.Collections.Generic; namespace Diploms.DataLayer { public static class DiplomContentSystemExtensions { public static void EnsureSeedData(this DiplomContext context) { if (context.AllMigrationsApplied()) { if (!context.Roles.Any()) { context.Roles.AddRange(Role.Admin, Role.Owner, Role.Student, Role.Teacher); context.SaveChanges(); } if(!context.Users.Any()) { context.Users.Add(new User{ Id = 1, Login = "admin", PasswordHash = @"WgHWgYQpzkpETS0VemCGE15u2LNPjTbtocMdxtqLll8=", Roles = new List<UserRole> { new UserRole { UserId = 1, RoleId = 1 } } }); } } } private static bool AllMigrationsApplied(this DiplomContext context) { var applied = context.GetService<IHistoryRepository>() .GetAppliedMigrations() .Select(m => m.MigrationId); var total = context.GetService<IMigrationsAssembly>() .Migrations .Select(m => m.Key); return !total.Except(applied).Any(); } } }
using System; using System.Linq; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; using Diploms.Core; using System.Collections.Generic; namespace Diploms.DataLayer { public static class DiplomContentSystemExtensions { public static void EnsureSeedData(this DiplomContext context) { if (context.AllMigrationsApplied()) { if (!context.Roles.Any()) { context.Roles.AddRange(Role.Admin, Role.Owner, Role.Student, Role.Teacher); context.SaveChanges(); } if(!context.Users.Any()) { context.Users.Add(new User{ Id = 1, Login = "admin", PasswordHash = @"WgHWgYQpzkpETS0VemCGE15u2LNPjTbtocMdxtqLll8=", Roles = new List<UserRole> { new UserRole { UserId = 1, RoleId = 1 } } }); } context.SaveChanges(); } } private static bool AllMigrationsApplied(this DiplomContext context) { var applied = context.GetService<IHistoryRepository>() .GetAppliedMigrations() .Select(m => m.MigrationId); var total = context.GetService<IMigrationsAssembly>() .Migrations .Select(m => m.Key); return !total.Except(applied).Any(); } } }
Set to 0 if null
#region using System.Linq; using System.Management; using UlteriusServer.TaskServer.Api.Models; using UlteriusServer.TaskServer.Api.Serialization; using vtortola.WebSockets; #endregion namespace UlteriusServer.TaskServer.Api.Controllers.Impl { internal class GpuController : ApiController { private readonly WebSocket client; private readonly Packets packet; private readonly ApiSerializator serializator = new ApiSerializator(); public GpuController(WebSocket client, Packets packet) { this.client = client; this.packet = packet; } public void GetGpuInformation() { var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_VideoController"); var gpus = (from ManagementBaseObject mo in searcher.Get() select new GpuInformation { Name = mo["Name"]?.ToString(), ScreenInfo = mo["VideoModeDescription"]?.ToString(), DriverVersion = mo["DriverVersion"]?.ToString(), RefreshRate = int.Parse(mo["CurrentRefreshRate"]?.ToString()), AdapterRam = mo["AdapterRAM"]?.ToString(), VideoArchitecture = int.Parse(mo["VideoArchitecture"]?.ToString()), VideoMemoryType = int.Parse(mo["VideoMemoryType"]?.ToString()), InstalledDisplayDrivers = mo["InstalledDisplayDrivers"]?.ToString()?.Split(','), AdapterCompatibility = mo["AdapterCompatibility"]?.ToString() }).ToList(); var data = new { gpus }; serializator.Serialize(client, packet.endpoint, packet.syncKey, data); } } }
#region using System.Linq; using System.Management; using UlteriusServer.TaskServer.Api.Models; using UlteriusServer.TaskServer.Api.Serialization; using vtortola.WebSockets; #endregion namespace UlteriusServer.TaskServer.Api.Controllers.Impl { internal class GpuController : ApiController { private readonly WebSocket client; private readonly Packets packet; private readonly ApiSerializator serializator = new ApiSerializator(); public GpuController(WebSocket client, Packets packet) { this.client = client; this.packet = packet; } public void GetGpuInformation() { var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_VideoController"); var gpus = (from ManagementBaseObject mo in searcher.Get() select new GpuInformation { Name = mo["Name"]?.ToString(), ScreenInfo = mo["VideoModeDescription"]?.ToString(), DriverVersion = mo["DriverVersion"]?.ToString(), RefreshRate = int.Parse(mo["CurrentRefreshRate"]?.ToString() ?? "0"), AdapterRam = mo["AdapterRAM"]?.ToString(), VideoArchitecture = int.Parse(mo["VideoArchitecture"]?.ToString() ?? "0"), VideoMemoryType = int.Parse(mo["VideoMemoryType"]?.ToString() ?? "0"), InstalledDisplayDrivers = mo["InstalledDisplayDrivers"]?.ToString()?.Split(','), AdapterCompatibility = mo["AdapterCompatibility"]?.ToString() }).ToList(); var data = new { gpus }; serializator.Serialize(client, packet.endpoint, packet.syncKey, data); } } }
Update plateformer gravity at fixed update
using UnityEngine; using System.Collections; public class PlateformerManager : MonoBehaviour { public float MoveSpeed; public float JumpForce; public float Gravity; public float TimerForDifficulty; float timeUntilEndGame; public static PlateformerManager Instance; void Awake () { PlateformerManager.Instance = this; } // Use this for initialization void Start () { this.timeUntilEndGame = Time.time + TimerForDifficulty; Physics2D.gravity = new Vector2(0f, this.Gravity); } // Update is called once per frame void Update () { if(Time.time > this.timeUntilEndGame) { if(GameObject.FindGameObjectWithTag("Player").GetComponent<PlateformerCharacter>().LockMove) { GameManager.Instance.LevelEnd(true); } else { GameManager.Instance.LevelEnd(false); } } } public float GetJumpForce () { return this.JumpForce; } public float GetMoveSpeed () { return this.MoveSpeed; } public float GetGravity () { return this.Gravity; } }
using UnityEngine; using System.Collections; public class PlateformerManager : MonoBehaviour { public float MoveSpeed; public float JumpForce; public float Gravity; public float TimerForDifficulty; float timeUntilEndGame; public static PlateformerManager Instance; void Awake () { PlateformerManager.Instance = this; } // Use this for initialization void Start () { this.timeUntilEndGame = Time.time + TimerForDifficulty; } // Update is called once per frame void Update () { if(Time.time > this.timeUntilEndGame) { if(GameObject.FindGameObjectWithTag("Player").GetComponent<PlateformerCharacter>().LockMove) { GameManager.Instance.LevelEnd(true); } else { GameManager.Instance.LevelEnd(false); } } } void FixedUpdate () { Physics2D.gravity = new Vector2(0f, this.Gravity); } public float GetJumpForce () { return this.JumpForce; } public float GetMoveSpeed () { return this.MoveSpeed; } public float GetGravity () { return this.Gravity; } }
Remove IO dependency; expect contents of private key and not path to key
using System; using System.Collections.Generic; using System.IO; using System.Security.Cryptography; using Jose; namespace Nexmo.Api { internal class Jwt { internal static string CreateToken(string appId, string privateKeyFile) { var tokenData = new byte[64]; var rng = RandomNumberGenerator.Create(); rng.GetBytes(tokenData); var jwtTokenId = Convert.ToBase64String(tokenData); var payload = new Dictionary<string, object> { { "iat", (long) (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds }, { "application_id", appId }, { "jti", jwtTokenId } }; var pemContents = File.ReadAllText(privateKeyFile); var rsa = PemParse.DecodePEMKey(pemContents); return JWT.Encode(payload, rsa, JwsAlgorithm.RS256); } } }
using System; using System.Collections.Generic; using System.Security.Cryptography; using Jose; namespace Nexmo.Api { internal class Jwt { internal static string CreateToken(string appId, string privateKey) { var tokenData = new byte[64]; var rng = RandomNumberGenerator.Create(); rng.GetBytes(tokenData); var jwtTokenId = Convert.ToBase64String(tokenData); var payload = new Dictionary<string, object> { { "iat", (long) (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds }, { "application_id", appId }, { "jti", jwtTokenId } }; var rsa = PemParse.DecodePEMKey(privateKey); return JWT.Encode(payload, rsa, JwsAlgorithm.RS256); } } }
Add support for update property
using System; using System.Xml.Linq; namespace Buildalyzer.Construction { public class PackageReference : IPackageReference { public string Name { get; } public string Version { get; } internal PackageReference(XElement packageReferenceElement) { this.Name = packageReferenceElement.GetAttributeValue("Include"); this.Version = packageReferenceElement.GetAttributeValue("Version"); } } }
using System; using System.Xml.Linq; namespace Buildalyzer.Construction { public class PackageReference : IPackageReference { public string Name { get; } public string Version { get; } internal PackageReference(XElement packageReferenceElement) { this.Name = packageReferenceElement.GetAttributeValue("Include") ?? packageReferenceElement.GetAttributeValue("Update"); this.Version = packageReferenceElement.GetAttributeValue("Version"); } } }
Use floor for better file sizes
using System; namespace GUtils.IO { public static class FileSizes { public const UInt64 B = 1024; public const UInt64 KiB = 1024 * B; public const UInt64 MiB = 1024 * KiB; public const UInt64 GiB = 1024 * MiB; public const UInt64 TiB = 1024 * GiB; public const UInt64 PiB = 1024 * TiB; private static readonly String[] _suffixes = new[] { "B", "KiB", "MiB", "GiB", "TiB", "PiB" }; public static String Format ( UInt64 Size ) { var i = ( Int32 ) Math.Round ( Math.Log ( Size, 1024 ) ); return $"{Size / ( Math.Pow ( B, i ) )} {_suffixes[i]}"; } } }
using System; namespace GUtils.IO { public static class FileSizes { public const UInt64 B = 1024; public const UInt64 KiB = 1024 * B; public const UInt64 MiB = 1024 * KiB; public const UInt64 GiB = 1024 * MiB; public const UInt64 TiB = 1024 * GiB; public const UInt64 PiB = 1024 * TiB; private static readonly String[] _suffixes = new[] { "B", "KiB", "MiB", "GiB", "TiB", "PiB" }; public static String Format ( UInt64 Size ) { var i = ( Int32 ) Math.Floor ( Math.Log ( Size, 1024 ) ); return $"{Size / ( Math.Pow ( B, i ) )} {_suffixes[i]}"; } } }
Add our own Vertices method
namespace Mapsui; public class MRect2 { public MPoint Max { get; } public MPoint Min { get; } public double MaxX => Max.X; public double MaxY => Max.Y; public double MinX => Min.X; public double MinY => Min.Y; public MPoint Centroid => new MPoint(Max.X - Min.X, Max.Y - Min.Y); public double Width => Max.X - MinX; public double Height => Max.Y - MinY; public double Bottom => Min.Y; public double Left => Min.X; public double Top => Max.Y; public double Right => Max.X; public MPoint TopLeft => new MPoint(Left, Top); public MPoint TopRight => new MPoint(Right, Top); public MPoint BottomLeft => new MPoint(Left, Bottom); public MPoint BottomRight => new MPoint(Right, Bottom); //IEnumerable<MPoint> Vertices { get; } //MRect Clone(); //bool Contains(MPoint? p); //bool Contains(MRect r); //bool Equals(MRect? other); //double GetArea(); //MRect Grow(double amount); //MRect Grow(double amountInX, double amountInY); //bool Intersects(MRect? box); //MRect Join(MRect? box); //MRect Multiply(double factor); //MQuad Rotate(double degrees); }
using System.Collections.Generic; namespace Mapsui; public class MRect2 { public MPoint Max { get; } public MPoint Min { get; } public double MaxX => Max.X; public double MaxY => Max.Y; public double MinX => Min.X; public double MinY => Min.Y; public MPoint Centroid => new MPoint(Max.X - Min.X, Max.Y - Min.Y); public double Width => Max.X - MinX; public double Height => Max.Y - MinY; public double Bottom => Min.Y; public double Left => Min.X; public double Top => Max.Y; public double Right => Max.X; public MPoint TopLeft => new MPoint(Left, Top); public MPoint TopRight => new MPoint(Right, Top); public MPoint BottomLeft => new MPoint(Left, Bottom); public MPoint BottomRight => new MPoint(Right, Bottom); /// <summary> /// Returns the vertices in clockwise order from bottom left around to bottom right /// </summary> public IEnumerable<MPoint> Vertices { get { yield return BottomLeft; yield return TopLeft; yield return TopRight; yield return BottomRight; } } //MRect Clone(); //bool Contains(MPoint? p); //bool Contains(MRect r); //bool Equals(MRect? other); //double GetArea(); //MRect Grow(double amount); //MRect Grow(double amountInX, double amountInY); //bool Intersects(MRect? box); //MRect Join(MRect? box); //MRect Multiply(double factor); //MQuad Rotate(double degrees); }
Use settings repository in twitch channel service
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using twitch_tv_viewer.Models; namespace twitch_tv_viewer.Services { public class TwitchChannelService : ITwitchChannelService { public async Task<string> PlayVideo(TwitchChannel channel, string quality) { var startInfo = new ProcessStartInfo { FileName = "livestreamer", Arguments = $"--http-query-param client_id=spyiu9jqdnfjtwv6l1xjk5zgt8qb91l twitch.tv/{channel.Name} {quality}", UseShellExecute = false, RedirectStandardOutput = true, CreateNoWindow = true }; var process = new Process { StartInfo = startInfo }; process.Start(); return await process.StandardOutput.ReadToEndAsync(); } public async Task<string> PlayVideo(TwitchChannel twitchChannel) => await PlayVideo(twitchChannel, "source"); public void OpenChat(TwitchChannel channel) { Process.Start($"http://twitch.tv/{channel.Name}/chat?popout="); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using twitch_tv_viewer.Models; using twitch_tv_viewer.Repositories; namespace twitch_tv_viewer.Services { public class TwitchChannelService : ITwitchChannelService { public TwitchChannelService() { Settings = new SettingsRepository(); } public ISettingsRepository Settings { get; set; } public async Task<string> PlayVideo(TwitchChannel channel, string quality) { var startInfo = new ProcessStartInfo { FileName = "livestreamer", Arguments = $"--http-query-param client_id=spyiu9jqdnfjtwv6l1xjk5zgt8qb91l twitch.tv/{channel.Name} {quality}", UseShellExecute = false, RedirectStandardOutput = true, CreateNoWindow = true }; var process = new Process { StartInfo = startInfo }; process.Start(); return await process.StandardOutput.ReadToEndAsync(); } public async Task<string> PlayVideo(TwitchChannel twitchChannel) => await PlayVideo(twitchChannel, Settings.Quality); public void OpenChat(TwitchChannel channel) { Process.Start($"http://twitch.tv/{channel.Name}/chat?popout="); } } }
Order by start date by default
using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using BatteryCommander.Web.Models; using MediatR; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; namespace BatteryCommander.Web.Queries { public class GetSUTARequests : IRequest<IEnumerable<SUTA>> { [FromRoute] public int Unit { get; set; } // Search by Soldier, Status, Dates private class Handler : IRequestHandler<GetSUTARequests, IEnumerable<SUTA>> { private readonly Database db; public Handler(Database db) { this.db = db; } public async Task<IEnumerable<SUTA>> Handle(GetSUTARequests request, CancellationToken cancellationToken) { return await AsQueryable(db) .Where(suta => suta.Soldier.UnitId == request.Unit) .ToListAsync(cancellationToken); } } public static IQueryable<SUTA> AsQueryable(Database db) { return db .SUTAs .Include(suta => suta.Soldier) .ThenInclude(soldier => soldier.Unit) .Include(suta => suta.Supervisor) .Include(suta => suta.Events); } } }
using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using BatteryCommander.Web.Models; using MediatR; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; namespace BatteryCommander.Web.Queries { public class GetSUTARequests : IRequest<IEnumerable<SUTA>> { [FromRoute] public int Unit { get; set; } // Search by Soldier, Status, Dates private class Handler : IRequestHandler<GetSUTARequests, IEnumerable<SUTA>> { private readonly Database db; public Handler(Database db) { this.db = db; } public async Task<IEnumerable<SUTA>> Handle(GetSUTARequests request, CancellationToken cancellationToken) { return await AsQueryable(db) .Where(suta => suta.Soldier.UnitId == request.Unit) .OrderBy(suta => suta.StartDate) .ToListAsync(cancellationToken); } } public static IQueryable<SUTA> AsQueryable(Database db) { return db .SUTAs .Include(suta => suta.Soldier) .ThenInclude(soldier => soldier.Unit) .Include(suta => suta.Supervisor) .Include(suta => suta.Events); } } }
Implement third step of automation layer
using System; using System.Collections.Generic; using System.Linq; using System.Text; using FizzBuzz.ConsoleApp; using TechTalk.SpecFlow; namespace FizzBuzz.Specification.AutomationLayer { [Binding] public class StepDefinitions { private int currentNumber; private string currentResult; [Given(@"the current number is '(.*)'")] public void GivenTheCurrentNumberIs(int currentNumber) { this.currentNumber = currentNumber; } [When(@"I print the number")] public void WhenIPrintTheNumber() { this.currentResult = new FizzBuzzer().Print(this.currentNumber); } [Then(@"the result is '(.*)'")] public void ThenTheResultIs(int p0) { ScenarioContext.Current.Pending(); } } }
using System; using FizzBuzz.ConsoleApp; using NFluent; using TechTalk.SpecFlow; namespace FizzBuzz.Specification.AutomationLayer { [Binding] public class StepDefinitions { private int currentNumber; private string currentResult; [Given(@"the current number is '(.*)'")] public void GivenTheCurrentNumberIs(int currentNumber) { this.currentNumber = currentNumber; } [When(@"I print the number")] public void WhenIPrintTheNumber() { this.currentResult = new FizzBuzzer().Print(this.currentNumber); } [Then(@"the result is '(.*)'")] public void ThenTheResultIs(string expectedResult) { Check.That(this.currentResult).IsEqualTo(expectedResult); } } }
Test for CRLF line ending bug
using UnityEngine; using System.Collections; [SelectionBase] [DisallowMultipleComponent] public class Unit : MonoBehaviour { [SerializeField] string faction; [SerializeField] int maxHeath = 100; [SerializeField] int health; // This function is called on Component Placement/Replacement void Reset() { } // Use this for initialization void Start () { } // Update is called once per frame void Update () { } }
using UnityEngine; using System.Collections; [SelectionBase] [DisallowMultipleComponent] public class Unit : MonoBehaviour { [SerializeField] string faction; [SerializeField] int maxHeath = 100; [SerializeField] int health; // This function is called on Component Placement/Replacement void Reset() { } // Use this for initialization void Start () { } // Update is called once per frame void Update () { } //Called every frame in editor void OnDrawGizmos() { } }
Add it to the job log too.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Serilog; namespace Commencement.Jobs.Common.Logging { public static class LogHelper { private static bool _loggingSetup = false; public static void ConfigureLogging() { if (_loggingSetup) return; //only setup logging once Log.Logger = new LoggerConfiguration() .WriteTo.Stackify() .WriteTo.Console() .CreateLogger(); AppDomain.CurrentDomain.UnhandledException += (sender, eventArgs) => Log.Fatal(eventArgs.ExceptionObject as Exception, eventArgs.ExceptionObject.ToString()); _loggingSetup = true; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Serilog; using Serilog.Exceptions.Destructurers; namespace Commencement.Jobs.Common.Logging { public static class LogHelper { private static bool _loggingSetup = false; public static void ConfigureLogging() { if (_loggingSetup) return; //only setup logging once Log.Logger = new LoggerConfiguration() .WriteTo.Stackify() .WriteTo.Console() .Enrich.With<ExceptionEnricher>() .CreateLogger(); AppDomain.CurrentDomain.UnhandledException += (sender, eventArgs) => Log.Fatal(eventArgs.ExceptionObject as Exception, eventArgs.ExceptionObject.ToString()); _loggingSetup = true; } } }
Fix unprivileged file symlink creation
using System; using System.ComponentModel; using System.IO; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; namespace Tgstation.Server.Host.IO { /// <summary> /// <see cref="ISymlinkFactory"/> for windows systems /// </summary> sealed class WindowsSymlinkFactory : ISymlinkFactory { /// <inheritdoc /> public Task CreateSymbolicLink(string targetPath, string linkPath, CancellationToken cancellationToken) => Task.Factory.StartNew(() => { if (targetPath == null) throw new ArgumentNullException(nameof(targetPath)); if (linkPath == null) throw new ArgumentNullException(nameof(linkPath)); //check if its not a file var flags = File.Exists(targetPath) ? 0 : 3; //SYMBOLIC_LINK_FLAG_DIRECTORY | SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE on win10 1607+ developer mode cancellationToken.ThrowIfCancellationRequested(); if (!NativeMethods.CreateSymbolicLink(linkPath, targetPath, flags)) throw new Win32Exception(Marshal.GetLastWin32Error()); }, cancellationToken, TaskCreationOptions.LongRunning, TaskScheduler.Current); } }
using System; using System.ComponentModel; using System.IO; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; namespace Tgstation.Server.Host.IO { /// <summary> /// <see cref="ISymlinkFactory"/> for windows systems /// </summary> sealed class WindowsSymlinkFactory : ISymlinkFactory { /// <inheritdoc /> public Task CreateSymbolicLink(string targetPath, string linkPath, CancellationToken cancellationToken) => Task.Factory.StartNew(() => { if (targetPath == null) throw new ArgumentNullException(nameof(targetPath)); if (linkPath == null) throw new ArgumentNullException(nameof(linkPath)); //check if its not a file var flags = File.Exists(targetPath) ? 2 : 3; //SYMBOLIC_LINK_FLAG_DIRECTORY and SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE on win10 1607+ developer mode cancellationToken.ThrowIfCancellationRequested(); if (!NativeMethods.CreateSymbolicLink(linkPath, targetPath, flags)) throw new Win32Exception(Marshal.GetLastWin32Error()); }, cancellationToken, TaskCreationOptions.LongRunning, TaskScheduler.Current); } }
Remove whitespace and add using
using System; using System.Collections.Generic; namespace FisherYates { public static class FisherYates { /* ** http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle */ static readonly Random Rand = new Random(); public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> list) { var rand = Rand; var enumerable = list as T[] ?? list.ToArray(); for (var i = enumerable.Length; i > 1; i--) { // First step : Pick random element to swap. var j = rand.Next(i); // Second step : Swap. var tmp = enumerable[j]; enumerable[j] = enumerable[i - 1]; enumerable[i - 1] = tmp; } return enumerable; } } }
using System; using System.Collections.Generic; using System.Linq; namespace FisherYates { public static class FisherYates { /* ** http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle */ static readonly Random Rand = new Random(); public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> list) { var rand = Rand; var enumerable = list as T[] ?? list.ToArray(); for (var i = enumerable.Length; i > 1; i--) { // First step : Pick random element to swap. var j = rand.Next(i); // Second step : Swap. var tmp = enumerable[j]; enumerable[j] = enumerable[i - 1]; enumerable[i - 1] = tmp; } return enumerable; } } }
Move the ExprSMTLIB test cases (there's only one right now) into their own namespace.
using NUnit.Framework; using System; using Microsoft.Boogie; using Microsoft.Basetypes; using System.IO; using symbooglix; namespace SymbooglixLibTests { [TestFixture()] public class Literal { public Literal() { SymbooglixTest.setupDebug(); } [Test()] public void bitvector() { var literal = new LiteralExpr(Token.NoToken, BigNum.FromInt(19), 32); // 19bv32 checkLiteral(literal, "(_ bv19 32)"); } [Test()] public void Bools() { checkLiteral(Expr.True, "true"); checkLiteral(Expr.False, "false"); } private void checkLiteral(LiteralExpr e, string expected) { using (var writer = new StringWriter()) { var printer = new SMTLIBQueryPrinter(writer); printer.Traverse(e); Assert.IsTrue(writer.ToString() == expected); } } } }
using NUnit.Framework; using System; using Microsoft.Boogie; using Microsoft.Basetypes; using System.IO; using symbooglix; namespace ExprSMTLIBTest { [TestFixture()] public class Literal { public Literal() { SymbooglixLibTests.SymbooglixTest.setupDebug(); } [Test()] public void bitvector() { var literal = new LiteralExpr(Token.NoToken, BigNum.FromInt(19), 32); // 19bv32 checkLiteral(literal, "(_ bv19 32)"); } [Test()] public void Bools() { checkLiteral(Expr.True, "true"); checkLiteral(Expr.False, "false"); } private void checkLiteral(LiteralExpr e, string expected) { using (var writer = new StringWriter()) { var printer = new SMTLIBQueryPrinter(writer); printer.Traverse(e); Assert.IsTrue(writer.ToString() == expected); } } } }
Add Guid as name for workspace registration
using System; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Data; using System.Linq; using System.Threading.Tasks; using System.Windows; using Microsoft.Practices.Unity; using UI.AddComponent; namespace UI { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); this.MainWindow = new MainWindow(); var compManager = new MEF_CompositionManager(); compManager.ComposeParts(); var container = new UnityContainer(); foreach (var component in compManager.ImportedComponents) { container.RegisterType(component.Provider.Key, component.Provider.Value); container.RegisterType(typeof(WorkspaceViewModel), component.Workspace, component.Workspace.Name); } container.RegisterType<IWorkspaceService, WorkspaceService>(); this.MainWindow.DataContext = container.Resolve<CalculatorViewModel>(); this.MainWindow.Show(); } } public interface IWorkspaceService { IEnumerable<WorkspaceViewModel> GetWorkspaces(); } public class WorkspaceService : IWorkspaceService { private readonly IUnityContainer container; public WorkspaceService(IUnityContainer container) { this.container = container; } public IEnumerable<WorkspaceViewModel> GetWorkspaces() { return container.ResolveAll<WorkspaceViewModel>().ToArray();; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Data; using System.Linq; using System.Threading.Tasks; using System.Windows; using Microsoft.Practices.Unity; using UI.AddComponent; namespace UI { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); this.MainWindow = new MainWindow(); var compManager = new MEF_CompositionManager(); compManager.ComposeParts(); var container = new UnityContainer(); foreach (var component in compManager.ImportedComponents) { container.RegisterType(component.Provider.Key, component.Provider.Value); container.RegisterType(typeof(WorkspaceViewModel), component.Workspace, Guid.NewGuid().ToString()); } container.RegisterType<IWorkspaceService, WorkspaceService>(); this.MainWindow.DataContext = container.Resolve<CalculatorViewModel>(); this.MainWindow.Show(); } } public interface IWorkspaceService { IEnumerable<WorkspaceViewModel> GetWorkspaces(); } public class WorkspaceService : IWorkspaceService { private readonly IUnityContainer container; public WorkspaceService(IUnityContainer container) { this.container = container; } public IEnumerable<WorkspaceViewModel> GetWorkspaces() { return container.ResolveAll<WorkspaceViewModel>().ToArray(); } } }
Update now actually does things in EvoCommand
using EvoSim; using Microsoft.Xna.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace EvoCommand { class Program { static void Main(string[] args) { Simulation sim = new Simulation(); sim.Initialize(sim); DateTime startTime = DateTime.UtcNow; DateTime lastUpdate; DateTime lastSerializationTime = DateTime.UtcNow; long i = 0; while (true) { lastUpdate = DateTime.UtcNow; update(new GameTime(DateTime.UtcNow - startTime, lastUpdate - lastUpdate)); i++; if (i % 1000000 == 1) Console.WriteLine("Programm still active - " + DateTime.Now.ToString()); // Save progress every minute if ((DateTime.UtcNow - lastSerializationTime).TotalSeconds > 10) { lastSerializationTime = DateTime.UtcNow; sim.TileMap.SerializeToFile("tilemap.dat"); sim.CreatureManager.Serialize("creatures.dat", "graveyard/graveyard"); Console.WriteLine("Save everything."); } } } public static void update(GameTime gametime) { } } }
using EvoSim; using Microsoft.Xna.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace EvoCommand { class Program { static void Main(string[] args) { Simulation sim = new Simulation(); sim.Initialize(sim); DateTime startTime = DateTime.UtcNow; DateTime lastUpdate; DateTime lastSerializationTime = DateTime.UtcNow; long i = 0; while (true) { lastUpdate = DateTime.UtcNow; sim.NotifyTick(new GameTime(DateTime.UtcNow - startTime, lastUpdate - lastUpdate)); i++; if (i % 1000000 == 1) Console.WriteLine("Programm still active - " + DateTime.Now.ToString()); // Save progress every minute if ((DateTime.UtcNow - lastSerializationTime).TotalSeconds > 10) { lastSerializationTime = DateTime.UtcNow; sim.TileMap.SerializeToFile("tilemap.dat"); sim.CreatureManager.Serialize("creatures.dat", "graveyard/graveyard"); Console.WriteLine("Save everything."); } } } } }
Add Value object with Id and Text
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; namespace netcore.Controllers { [Route("api/[controller]")] public class ValuesController : Controller { // GET api/values [HttpGet] public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; } // GET api/values/5 [HttpGet("{id}")] public string Get(int id) { return "value"; } // POST api/values [HttpPost] public void Post([FromBody]string value) { } // PUT api/values/5 [HttpPut("{id}")] public void Put(int id, [FromBody]string value) { } // DELETE api/values/5 [HttpDelete("{id}")] public void Delete(int id) { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; namespace netcore.Controllers { [Route("api/[controller]")] public class ValuesController : Controller { // GET api/values [HttpGet] public IEnumerable<Value> Get() { return new Value[] { new Value { Id = 1, Text = "value1"}, new Value { Id = 2, Text = "value2"} }; } // GET api/values/5 [HttpGet("{id:int}")] public Value Get(int id) { return new Value { Id = id, Text = "value" }; } // POST api/values [HttpPost] public void Post([FromBody]string value) { } // PUT api/values/5 [HttpPut("{id}")] public void Put(int id, [FromBody]string value) { } // DELETE api/values/5 [HttpDelete("{id}")] public void Delete(int id) { } } public class Value { public int Id { get; set; } public string Text { get; set; } } }
Set TTL for prefix to infinity rn
using System; using System.Threading.Tasks; using SoraBot.Data.Repositories.Interfaces; using SoraBot.Services.Cache; namespace SoraBot.Services.Guilds { public class PrefixService : IPrefixService { public const string CACHE_PREFIX = "prfx:"; public const short CACHE_TTL_MINS = 60; private readonly ICacheService _cacheService; private readonly IGuildRepository _guildRepo; public PrefixService(ICacheService cacheService, IGuildRepository guildRepo) { _cacheService = cacheService; _guildRepo = guildRepo; } public async Task<string> GetPrefix(ulong id) { string idStr = CACHE_PREFIX + id.ToString(); return await _cacheService.GetOrSetAndGetAsync(idStr, async () => await _guildRepo.GetGuildPrefix(id).ConfigureAwait(false) ?? "$", TimeSpan.FromMinutes(CACHE_TTL_MINS)).ConfigureAwait(false); } public async Task<bool> SetPrefix(ulong id, string prefix) { // Let's set it in the DB. And if it succeeds we'll also add it to our cache if (!await _guildRepo.SetGuildPrefix(id, prefix).ConfigureAwait(false)) return false; // Update the Cache string idStr = CACHE_PREFIX + id.ToString(); _cacheService.Set(idStr, prefix, TimeSpan.FromMinutes(CACHE_TTL_MINS)); return true; } } }
using System; using System.Threading.Tasks; using SoraBot.Data.Repositories.Interfaces; using SoraBot.Services.Cache; namespace SoraBot.Services.Guilds { public class PrefixService : IPrefixService { public const string CACHE_PREFIX = "prfx:"; // public const short CACHE_TTL_MINS = 60; private readonly ICacheService _cacheService; private readonly IGuildRepository _guildRepo; public PrefixService(ICacheService cacheService, IGuildRepository guildRepo) { _cacheService = cacheService; _guildRepo = guildRepo; } public async Task<string> GetPrefix(ulong id) { string idStr = CACHE_PREFIX + id.ToString(); return await _cacheService.GetOrSetAndGetAsync(idStr, async () => await _guildRepo.GetGuildPrefix(id).ConfigureAwait(false) ?? "$" ).ConfigureAwait(false); } public async Task<bool> SetPrefix(ulong id, string prefix) { // Let's set it in the DB. And if it succeeds we'll also add it to our cache if (!await _guildRepo.SetGuildPrefix(id, prefix).ConfigureAwait(false)) return false; // Update the Cache string idStr = CACHE_PREFIX + id.ToString(); _cacheService.Set(idStr, prefix); return true; } } }
Use generic host in sample
using System.Threading.Tasks; using Basic.Models; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using MR.AspNetCore.Jobs; namespace Basic { public class Program { public static async Task Main(string[] args) { var host = CreateWebHostBuilder(args).Build(); await host.StartJobsAsync(); using (var scope = host.Services.CreateScope()) { var context = scope.ServiceProvider.GetService<AppDbContext>(); await context.Database.MigrateAsync(); } host.Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>(); } }
using System.Threading.Tasks; using Basic.Models; using Microsoft.AspNetCore.Hosting; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using MR.AspNetCore.Jobs; namespace Basic { public class Program { public static async Task Main(string[] args) { var host = CreateHostBuilder(args).Build(); await host.StartJobsAsync(); using (var scope = host.Services.CreateScope()) { var context = scope.ServiceProvider.GetService<AppDbContext>(); await context.Database.MigrateAsync(); } host.Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } }
Check if the specified path is a physical or a virtual path
using System; using System.Web; using System.Web.Hosting; using System.Configuration; namespace NuGet.Server.Infrastructure { public class PackageUtility { internal static string PackagePhysicalPath; private static string DefaultPackagePhysicalPath = HostingEnvironment.MapPath("~/Packages"); static PackageUtility() { string packagePath = ConfigurationManager.AppSettings["NuGetPackagePath"]; if (string.IsNullOrEmpty(packagePath)) { PackagePhysicalPath = DefaultPackagePhysicalPath; } else { PackagePhysicalPath = packagePath; } } public static Uri GetPackageUrl(string path, Uri baseUri) { return new Uri(baseUri, GetPackageDownloadUrl(path)); } private static string GetPackageDownloadUrl(string path) { return VirtualPathUtility.ToAbsolute("~/Packages/" + path); } } }
using System; using System.Web; using System.Web.Hosting; using System.Configuration; using System.IO; namespace NuGet.Server.Infrastructure { public class PackageUtility { internal static string PackagePhysicalPath; private static string DefaultPackagePhysicalPath = HostingEnvironment.MapPath("~/Packages"); static PackageUtility() { string packagePath = ConfigurationManager.AppSettings["NuGetPackagePath"]; if (string.IsNullOrEmpty(packagePath)) { PackagePhysicalPath = DefaultPackagePhysicalPath; } else { if (Path.IsPathRooted(packagePath)) { PackagePhysicalPath = packagePath; } else { PackagePhysicalPath = HostingEnvironment.MapPath(packagePath); } } } public static Uri GetPackageUrl(string path, Uri baseUri) { return new Uri(baseUri, GetPackageDownloadUrl(path)); } private static string GetPackageDownloadUrl(string path) { return VirtualPathUtility.ToAbsolute("~/Packages/" + path); } } }
Change id type from uint to ulong
namespace NTwitch { public interface IEntity { ITwitchClient Client { get; } uint Id { get; } } }
namespace NTwitch { public interface IEntity { ITwitchClient Client { get; } ulong Id { get; } } }
Remove uneeded player collection methods
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Booma.Proxy { /// <summary> /// The collection of network players that are known about. /// </summary> public interface INetworkPlayerCollection : IEnumerable<INetworkPlayer> { /// <summary> /// The local player. /// </summary> INetworkPlayer Local { get; } /// <summary> /// The networked players. /// </summary> IEnumerable<INetworkPlayer> Players { get; } /// <summary> /// The networked player's excluding the <see cref="Local"/> player. /// </summary> IEnumerable<INetworkPlayer> ExcludingLocal { get; } /// <summary> /// Returns the <see cref="INetworkPlayer"/> with the id. /// Or null if the player doesn't exist. /// </summary> /// <param name="id">The id to check for.</param> /// <returns>The <see cref="INetworkPlayer"/> with the id or null.</returns> INetworkPlayer this[int id] { get; } /// <summary> /// Indicates if it contains the <see cref="id"/> key value. /// </summary> /// <param name="id">The id to check for.</param> /// <returns>True if the collection contains the ID.</returns> bool ContainsId(int id); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Booma.Proxy { /// <summary> /// The collection of network players that are known about. /// </summary> public interface INetworkPlayerCollection : IEnumerable<INetworkPlayer> { /// <summary> /// The networked players. /// </summary> IEnumerable<INetworkPlayer> Players { get; } /// <summary> /// Returns the <see cref="INetworkPlayer"/> with the id. /// Or null if the player doesn't exist. /// </summary> /// <param name="id">The id to check for.</param> /// <returns>The <see cref="INetworkPlayer"/> with the id or null.</returns> INetworkPlayer this[int id] { get; } /// <summary> /// Indicates if it contains the <see cref="id"/> key value. /// </summary> /// <param name="id">The id to check for.</param> /// <returns>True if the collection contains the ID.</returns> bool ContainsId(int id); } }
Comment out non-compiling test while we don't flatten ListGroups
// Copyright 2016 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Google.Api.Gax; using System; using System.Linq; using Xunit; namespace Google.Monitoring.V3 { [Collection(nameof(MonitoringFixture))] public class GroupServiceClientSnippets { private readonly MonitoringFixture _fixture; public GroupServiceClientSnippets(MonitoringFixture fixture) { _fixture = fixture; } [Fact] public void ListGroups() { string projectId = _fixture.ProjectId; // Snippet: ListGroups GroupServiceClient client = GroupServiceClient.Create(); string projectName = MetricServiceClient.FormatProjectName(projectId); IPagedEnumerable<ListGroupsResponse, Group> groups = client.ListGroups(projectName, "", "", ""); foreach (Group group in groups.Take(10)) { Console.WriteLine($"{group.Name}: {group.DisplayName}"); } // End snippet } } }
// Copyright 2016 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Google.Api.Gax; using System; using System.Linq; using Xunit; namespace Google.Monitoring.V3 { [Collection(nameof(MonitoringFixture))] public class GroupServiceClientSnippets { private readonly MonitoringFixture _fixture; public GroupServiceClientSnippets(MonitoringFixture fixture) { _fixture = fixture; } /* TODO: Reinstate when ListGroups is present again. [Fact] public void ListGroups() { string projectId = _fixture.ProjectId; // Snippet: ListGroups GroupServiceClient client = GroupServiceClient.Create(); string projectName = MetricServiceClient.FormatProjectName(projectId); IPagedEnumerable<ListGroupsResponse, Group> groups = client.ListGroups(projectName, "", "", ""); foreach (Group group in groups.Take(10)) { Console.WriteLine($"{group.Name}: {group.DisplayName}"); } // End snippet } */ } }
Add execute method overload with ordering
// // Query.cs // // Author: // Roman M. Yagodin <roman.yagodin@gmail.com> // // Copyright (c) 2016 Roman M. Yagodin // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. using System; using System.Collections.Generic; using System.Linq; using R7.University.Models; namespace R7.University.Queries { public class Query<TEntity> where TEntity: class { private readonly IModelContext modelContext; public Query (IModelContext modelContext) { this.modelContext = modelContext; } public IEnumerable<TEntity> Execute () { return modelContext.Query<TEntity> ().ToList (); } } }
// // Query.cs // // Author: // Roman M. Yagodin <roman.yagodin@gmail.com> // // Copyright (c) 2016 Roman M. Yagodin // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. using System; using System.Collections.Generic; using System.Linq; using R7.University.Models; namespace R7.University.Queries { public class Query<TEntity> where TEntity: class { private readonly IModelContext modelContext; public Query (IModelContext modelContext) { this.modelContext = modelContext; } public IList<TEntity> Execute () { return modelContext.Query<TEntity> ().ToList (); } public IList<TEntity> Execute<TKey> (Func<TEntity,TKey> keySelector) { return modelContext.Query<TEntity> ().OrderBy (keySelector).ToList (); } } }
Reduce footer height to match back button
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Extensions.Color4Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Game.Graphics; using osu.Game.Online.Multiplayer; using osuTK; namespace osu.Game.Screens.Multi.Match.Components { public class Footer : CompositeDrawable { public const float HEIGHT = 100; public Action OnStart; public readonly Bindable<PlaylistItem> SelectedItem = new Bindable<PlaylistItem>(); private readonly Drawable background; public Footer() { RelativeSizeAxes = Axes.X; Height = HEIGHT; InternalChildren = new[] { background = new Box { RelativeSizeAxes = Axes.Both }, new ReadyButton { Anchor = Anchor.Centre, Origin = Anchor.Centre, Size = new Vector2(600, 50), SelectedItem = { BindTarget = SelectedItem }, Action = () => OnStart?.Invoke() } }; } [BackgroundDependencyLoader] private void load(OsuColour colours) { background.Colour = Color4Extensions.FromHex(@"28242d"); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Extensions.Color4Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Game.Graphics; using osu.Game.Online.Multiplayer; using osuTK; namespace osu.Game.Screens.Multi.Match.Components { public class Footer : CompositeDrawable { public const float HEIGHT = 50; public Action OnStart; public readonly Bindable<PlaylistItem> SelectedItem = new Bindable<PlaylistItem>(); private readonly Drawable background; public Footer() { RelativeSizeAxes = Axes.X; Height = HEIGHT; InternalChildren = new[] { background = new Box { RelativeSizeAxes = Axes.Both }, new ReadyButton { Anchor = Anchor.Centre, Origin = Anchor.Centre, Size = new Vector2(600, 50), SelectedItem = { BindTarget = SelectedItem }, Action = () => OnStart?.Invoke() } }; } [BackgroundDependencyLoader] private void load(OsuColour colours) { background.Colour = Color4Extensions.FromHex(@"28242d"); } } }
Change hello world implementation to using the
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; namespace Tiesmaster.Dcc { public class Startup { public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(); if(env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.Run(async (context) => { await context.Response.WriteAsync("Hello from DCC ;)"); }); } } }
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Logging; namespace Tiesmaster.Dcc { public class Startup { public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(); if(env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.RunProxy(new ProxyOptions { Host = "jsonplaceholder.typicode.com" }); } } }
Add implementation details to MySQLScheamAggregator.cs
using System; using System.Data; namespace Gigobyte.Daterpillar.Data { public class MySQLSchemaAggregator : SchemaAggregatorBase { public MySQLSchemaAggregator(IDbConnection connection) : base(connection) { } protected override string GetColumnInfoQuery(string tableName) { throw new NotImplementedException(); } protected override string GetForeignKeyInfoQuery(string tableName) { throw new NotImplementedException(); } protected override string GetIndexColumnsQuery(string indexIdentifier) { throw new NotImplementedException(); } protected override string GetIndexInfoQuery(string tableName) { throw new NotImplementedException(); } protected override string GetTableInfoQuery() { throw new NotImplementedException(); } } }
using System; using System.Data; namespace Gigobyte.Daterpillar.Data { public class MySQLSchemaAggregator : SchemaAggregatorBase { public MySQLSchemaAggregator(IDbConnection connection) : base(connection) { } protected override string GetColumnInfoQuery(string tableName) { return $"SELECT c.`COLUMN_NAME` AS `Name`, c.DATA_TYPE AS `Type`, if(c.CHARACTER_MAXIMUM_LENGTH IS NULL, if(c.NUMERIC_PRECISION IS NULL, 0, c.NUMERIC_PRECISION), c.CHARACTER_MAXIMUM_LENGTH) AS `Scale`, if(c.NUMERIC_SCALE IS NULL, 0, c.NUMERIC_SCALE) AS `Precision`, c.IS_NULLABLE AS `Nullable`, c.COLUMN_DEFAULT AS `Default`, if(c.EXTRA = 'auto_increment', 1, 0) AS `Auto`, c.COLUMN_COMMENT AS `Comment` FROM information_schema.`COLUMNS` c WHERE c.TABLE_SCHEMA = '{Schema.Name}' AND c.`TABLE_NAME` = '{tableName}';"; } protected override string GetForeignKeyInfoQuery(string tableName) { return $"SELECT rc.`CONSTRAINT_NAME` AS `Name`, fc.FOR_COL_NAME AS `Column`, rc.REFERENCED_TABLE_NAME AS `Referecne_Table`, fc.REF_COL_NAME AS `Reference_Column`, rc.UPDATE_RULE AS `On_Update`, rc.DELETE_RULE AS `On_Delete`, rc.MATCH_OPTION AS `On_Match` FROM information_schema.REFERENTIAL_CONSTRAINTS rc JOIN information_schema.INNODB_SYS_FOREIGN_COLS fc ON fc.ID = concat(rc.`CONSTRAINT_SCHEMA`, '/', rc.`CONSTRAINT_NAME`) WHERE rc.`CONSTRAINT_SCHEMA` = '{Schema.Name}' AND rc.`TABLE_NAME` = '{tableName}';"; } protected override string GetIndexColumnsQuery(string indexIdentifier) { throw new NotImplementedException(); } protected override string GetIndexInfoQuery(string tableName) { throw new NotImplementedException(); } protected override string GetTableInfoQuery() { return $"SELECT t.TABLE_NAME AS `Name`, t.TABLE_COMMENT AS `Comment` FROM information_schema.TABLES t WHERE t.TABLE_SCHEMA = '{Schema.Name}';"; } } }
Add image and description to playlist location
using System; using System.Collections.Generic; using System.Xml.Serialization; namespace SevenDigital.Api.Schema.Playlists.Response { [Serializable] public class PlaylistLocation : UserBasedUpdatableItem { [XmlAttribute("id")] public string Id { get; set; } [XmlElement("name")] public string Name { get; set; } [XmlArray("links")] [XmlArrayItem("link")] public List<Link> Links { get; set; } [XmlElement("trackCount")] public int TrackCount { get; set; } [XmlElement("visibility")] public PlaylistVisibilityType Visibility { get; set; } [XmlElement("status")] public PlaylistStatusType Status { get; set; } [XmlArray("tags")] [XmlArrayItem("tag")] public List<Tag> Tags { get; set; } public override string ToString() { return string.Format("{0}: {1}", Id, Name); } } }
using System; using System.Collections.Generic; using System.Xml.Serialization; namespace SevenDigital.Api.Schema.Playlists.Response { [Serializable] public class PlaylistLocation : UserBasedUpdatableItem { [XmlAttribute("id")] public string Id { get; set; } [XmlElement("name")] public string Name { get; set; } [XmlArray("links")] [XmlArrayItem("link")] public List<Link> Links { get; set; } [XmlElement("trackCount")] public int TrackCount { get; set; } [XmlElement("visibility")] public PlaylistVisibilityType Visibility { get; set; } [XmlElement("description")] public string Description { get; set; } [XmlElement("image")] public string Image { get; set; } [XmlElement("status")] public PlaylistStatusType Status { get; set; } [XmlArray("tags")] [XmlArrayItem("tag")] public List<Tag> Tags { get; set; } public override string ToString() { return string.Format("{0}: {1}", Id, Name); } } }
Rename Wallets group to Managers group
using AvalonStudio.MainMenu; using AvalonStudio.Menus; using System; using System.Collections.Generic; using System.Composition; using System.Text; namespace WalletWasabi.Gui.Shell.MainMenu { internal class ToolsMainMenuItems { private IMenuItemFactory _menuItemFactory; [ImportingConstructor] public ToolsMainMenuItems(IMenuItemFactory menuItemFactory) { _menuItemFactory = menuItemFactory; } #region MainMenu [ExportMainMenuItem("Tools")] [DefaultOrder(1)] public IMenuItem Tools => _menuItemFactory.CreateHeaderMenuItem("Tools", null); #endregion MainMenu #region Group [ExportMainMenuDefaultGroup("Tools", "Wallet")] [DefaultOrder(0)] public object WalletGroup => null; [ExportMainMenuDefaultGroup("Tools", "Settings")] [DefaultOrder(1)] public object SettingsGroup => null; #endregion Group #region MenuItem [ExportMainMenuItem("Tools", "Wallet")] [DefaultOrder(0)] [DefaultGroup("Wallet")] public IMenuItem GenerateWallet => _menuItemFactory.CreateCommandMenuItem("Tools.WalletManager"); [ExportMainMenuItem("Tools", "Settings")] [DefaultOrder(1)] [DefaultGroup("Settings")] public IMenuItem Settings => _menuItemFactory.CreateCommandMenuItem("Tools.Settings"); #endregion MenuItem } }
using AvalonStudio.MainMenu; using AvalonStudio.Menus; using System; using System.Collections.Generic; using System.Composition; using System.Text; namespace WalletWasabi.Gui.Shell.MainMenu { internal class ToolsMainMenuItems { private IMenuItemFactory _menuItemFactory; [ImportingConstructor] public ToolsMainMenuItems(IMenuItemFactory menuItemFactory) { _menuItemFactory = menuItemFactory; } #region MainMenu [ExportMainMenuItem("Tools")] [DefaultOrder(1)] public IMenuItem Tools => _menuItemFactory.CreateHeaderMenuItem("Tools", null); #endregion MainMenu #region Group [ExportMainMenuDefaultGroup("Tools", "Managers")] [DefaultOrder(0)] public object ManagersGroup => null; [ExportMainMenuDefaultGroup("Tools", "Settings")] [DefaultOrder(1)] public object SettingsGroup => null; #endregion Group #region MenuItem [ExportMainMenuItem("Tools", "Wallet Manager")] [DefaultOrder(0)] [DefaultGroup("Managers")] public IMenuItem GenerateWallet => _menuItemFactory.CreateCommandMenuItem("Tools.WalletManager"); [ExportMainMenuItem("Tools", "Settings")] [DefaultOrder(1)] [DefaultGroup("Settings")] public IMenuItem Settings => _menuItemFactory.CreateCommandMenuItem("Tools.Settings"); #endregion MenuItem } }
Remove the label as you can not see it when running the app
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using Android.App; using Android.OS; using Android.Content.PM; using Android.Views; namespace SampleGame.Android { [Activity(Label = "SampleGame", ConfigurationChanges = ConfigChanges.Orientation | ConfigChanges.ScreenSize, MainLauncher = true, Theme = "@android:style/Theme.NoTitleBar")] public class MainActivity : Activity { protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); Window.AddFlags(WindowManagerFlags.Fullscreen); Window.AddFlags(WindowManagerFlags.KeepScreenOn); SetContentView(new SampleGameView(this)); } } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using Android.App; using Android.OS; using Android.Content.PM; using Android.Views; namespace SampleGame.Android { [Activity(ConfigurationChanges = ConfigChanges.Orientation | ConfigChanges.ScreenSize, MainLauncher = true, Theme = "@android:style/Theme.NoTitleBar")] public class MainActivity : Activity { protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); Window.AddFlags(WindowManagerFlags.Fullscreen); Window.AddFlags(WindowManagerFlags.KeepScreenOn); SetContentView(new SampleGameView(this)); } } }
Bump the protocol version to 0x1343
#if !DEBUG using System; using System.IO; #endif using System.Threading; using YGOSharp.OCGWrapper; namespace YGOSharp { public class Program { public static uint ClientVersion = 0x133D; public static void Main(string[] args) { #if !DEBUG try { #endif Config.Load(args); BanlistManager.Init(Config.GetString("BanlistFile", "lflist.conf")); Api.Init(Config.GetString("RootPath", "."), Config.GetString("ScriptDirectory", "script"), Config.GetString("DatabaseFile", "cards.cdb")); ClientVersion = Config.GetUInt("ClientVersion", ClientVersion); CoreServer server = new CoreServer(); server.Start(); while (server.IsRunning) { server.Tick(); Thread.Sleep(1); } #if !DEBUG } catch (Exception ex) { File.WriteAllText("crash_" + DateTime.UtcNow.ToString("yyyy-MM-dd_HH-mm-ss") + ".txt", ex.ToString()); } #endif } } }
#if !DEBUG using System; using System.IO; #endif using System.Threading; using YGOSharp.OCGWrapper; namespace YGOSharp { public class Program { public static uint ClientVersion = 0x1343; public static void Main(string[] args) { #if !DEBUG try { #endif Config.Load(args); BanlistManager.Init(Config.GetString("BanlistFile", "lflist.conf")); Api.Init(Config.GetString("RootPath", "."), Config.GetString("ScriptDirectory", "script"), Config.GetString("DatabaseFile", "cards.cdb")); ClientVersion = Config.GetUInt("ClientVersion", ClientVersion); CoreServer server = new CoreServer(); server.Start(); while (server.IsRunning) { server.Tick(); Thread.Sleep(1); } #if !DEBUG } catch (Exception ex) { File.WriteAllText("crash_" + DateTime.UtcNow.ToString("yyyy-MM-dd_HH-mm-ss") + ".txt", ex.ToString()); } #endif } } }
Reduce unit test logger verbosity
using System; using NUnit.Framework; using RethinkDb; using System.Net; using System.Linq; using System.Threading.Tasks; using RethinkDb.Configuration; namespace RethinkDb.Test { public class TestBase { protected IConnection connection; [TestFixtureSetUp] public virtual void TestFixtureSetUp() { try { DoTestFixtureSetUp().Wait(); } catch (Exception e) { Console.WriteLine("TestFixtureSetUp failed: {0}", e); throw; } } private async Task DoTestFixtureSetUp() { connection = ConfigConnectionFactory.Instance.Get("testCluster"); connection.Logger = new DefaultLogger(LoggingCategory.Debug, Console.Out); await connection.ConnectAsync(); try { var dbList = await connection.RunAsync(Query.DbList()); if (dbList.Contains("test")) await connection.RunAsync(Query.DbDrop("test")); } catch (Exception) { } } } }
using System; using NUnit.Framework; using RethinkDb; using System.Net; using System.Linq; using System.Threading.Tasks; using RethinkDb.Configuration; namespace RethinkDb.Test { public class TestBase { protected IConnection connection; [TestFixtureSetUp] public virtual void TestFixtureSetUp() { try { DoTestFixtureSetUp().Wait(); } catch (Exception e) { Console.WriteLine("TestFixtureSetUp failed: {0}", e); throw; } } private async Task DoTestFixtureSetUp() { connection = ConfigConnectionFactory.Instance.Get("testCluster"); connection.Logger = new DefaultLogger(LoggingCategory.Warning, Console.Out); await connection.ConnectAsync(); try { var dbList = await connection.RunAsync(Query.DbList()); if (dbList.Contains("test")) await connection.RunAsync(Query.DbDrop("test")); } catch (Exception) { } } } }
Fix offset samples for GetData
using System.Linq; using UniRx; using UniRx.Triggers; using UnityEngine; public class WaveformRenderer : MonoBehaviour { [SerializeField] Color color; void Awake() { var model = NotesEditorModel.Instance; var waveData = new float[500000]; var skipSamples = 50; var lines = Enumerable.Range(0, waveData.Length / skipSamples) .Select(_ => new Line(Vector3.zero, Vector3.zero, color)) .ToArray(); this.LateUpdateAsObservable() .Where(_ => model.WaveformDisplayEnabled.Value) .SkipWhile(_ => model.Audio.clip == null) .Subscribe(_ => { model.Audio.clip.GetData(waveData, model.Audio.timeSamples); var x = (model.CanvasWidth.Value / model.Audio.clip.samples) / 2f; var offsetX = model.CanvasOffsetX.Value; var offsetY = 200; for (int li = 0, wi = skipSamples / 2, l = waveData.Length; wi < l; li++, wi += skipSamples) { lines[li].start.x = lines[li].end.x = wi * x + offsetX; lines[li].end.y = waveData[wi] * 45 - offsetY; lines[li].start.y = waveData[wi - skipSamples / 2] * 45 - offsetY; } GLLineRenderer.RenderLines("waveform", lines); }); } }
using System.Linq; using UniRx; using UniRx.Triggers; using UnityEngine; public class WaveformRenderer : MonoBehaviour { [SerializeField] Color color; void Awake() { var model = NotesEditorModel.Instance; var waveData = new float[500000]; var skipSamples = 50; var lines = Enumerable.Range(0, waveData.Length / skipSamples) .Select(_ => new Line(Vector3.zero, Vector3.zero, color)) .ToArray(); this.LateUpdateAsObservable() .Where(_ => model.WaveformDisplayEnabled.Value) .SkipWhile(_ => model.Audio.clip == null) .Subscribe(_ => { var timeSamples = Mathf.Min(model.Audio.timeSamples, model.Audio.clip.samples - 1); model.Audio.clip.GetData(waveData, timeSamples); var x = (model.CanvasWidth.Value / model.Audio.clip.samples) / 2f; var offsetX = model.CanvasOffsetX.Value; var offsetY = 200; for (int li = 0, wi = skipSamples / 2, l = waveData.Length; wi < l; li++, wi += skipSamples) { lines[li].start.x = lines[li].end.x = wi * x + offsetX; lines[li].end.y = waveData[wi] * 45 - offsetY; lines[li].start.y = waveData[wi - skipSamples / 2] * 45 - offsetY; } GLLineRenderer.RenderLines("waveform", lines); }); } }
Fix UI scale; add Canvas property
using System; using System.Collections.Generic; using ContractsWindow.Unity.Unity; using UnityEngine; using UnityEngine.UI; namespace ContractsWindow.Unity.Interfaces { public interface ICW_Window { bool HideTooltips { get; set; } bool BlizzyAvailable { get; } bool StockToolbar { get; set; } bool ReplaceToolbar { get; set; } bool LargeFont { get; set; } bool IgnoreScale { get; set; } float Scale { get; set; } float MasterScale { get; set; } string Version { get; } IList<IMissionSection> GetMissions { get; } IMissionSection GetCurrentMission { get; } void Rebuild(); void NewMission(string title, Guid id); void SetWindowPosition(Rect r); } }
using System; using System.Collections.Generic; using ContractsWindow.Unity.Unity; using UnityEngine; using UnityEngine.UI; namespace ContractsWindow.Unity.Interfaces { public interface ICW_Window { bool HideTooltips { get; set; } bool BlizzyAvailable { get; } bool StockToolbar { get; set; } bool ReplaceToolbar { get; set; } bool LargeFont { get; set; } bool IgnoreScale { get; set; } float Scale { get; set; } float MasterScale { get; } string Version { get; } Canvas MainCanvas { get; } IList<IMissionSection> GetMissions { get; } IMissionSection GetCurrentMission { get; } void Rebuild(); void NewMission(string title, Guid id); void SetWindowPosition(Rect r); } }
Destroy factory items when moving them to stockpile
using System.Collections; using System.Collections.Generic; using UnityEngine; [RequireComponent(typeof(GridPositionComponent))] [RequireComponent(typeof(ResourceSink))] public class GridOutput : MonoBehaviour { private ResourceStorage ItemDestination; private ResourceSink ItemSource; // Use this for initialization void Start () { ItemDestination = GetComponentInParent<ResourceStorage>(); ItemSource = GetComponent<ResourceSink>(); ItemSource.DeliverItem = (item) => { Debug.Log(new System.Diagnostics.StackTrace()); Debug.Log(ItemDestination); Debug.Log(item); ItemDestination.AddResource(item.ResourceType, 1); // TODO destroy the in-game item return true; }; } // Update is called once per frame void Update () { } }
using System.Collections; using System.Collections.Generic; using UnityEngine; [RequireComponent(typeof(GridPositionComponent))] [RequireComponent(typeof(ResourceSink))] public class GridOutput : MonoBehaviour { private ResourceStorage ItemDestination; private ResourceSink ItemSource; // Use this for initialization void Start () { ItemDestination = GetComponentInParent<ResourceStorage>(); ItemSource = GetComponent<ResourceSink>(); ItemSource.DeliverItem = (item) => { Debug.Log(new System.Diagnostics.StackTrace()); Debug.Log(ItemDestination); Debug.Log(item); ItemDestination.AddResource(item.ResourceType, 1); Destroy(item.gameObject); return true; }; } // Update is called once per frame void Update () { } }
Fix bug where test mode wouldn't launch
// 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 EndlessClient.Rendering.Factories; using EOLib.IO.Repositories; namespace EndlessClient { //todo: move this to a different namespace public class TestModeLauncher : ITestModeLauncher { private readonly IEndlessGameProvider _endlessGameProvider; private readonly ICharacterRendererFactory _characterRendererFactory; private readonly IEIFFileProvider _eifFileProvider; private readonly IGameStateProvider _gameStateProvider; public TestModeLauncher(IEndlessGameProvider endlessGameProvider, ICharacterRendererFactory characterRendererFactory, IEIFFileProvider eifFileProvider, IGameStateProvider gameStateProvider) { _endlessGameProvider = endlessGameProvider; _characterRendererFactory = characterRendererFactory; _eifFileProvider = eifFileProvider; _gameStateProvider = gameStateProvider; } public void LaunchTestMode() { if (_gameStateProvider.CurrentState != GameStates.Initial) return; var testMode = new CharacterStateTest( _endlessGameProvider.Game, _characterRendererFactory, _eifFileProvider); _endlessGameProvider.Game.Components.Clear(); _endlessGameProvider.Game.Components.Add(testMode); } } public interface ITestModeLauncher { void LaunchTestMode(); } }
// 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 EndlessClient.Rendering.Factories; using EOLib.IO.Repositories; namespace EndlessClient { //todo: move this to a different namespace public class TestModeLauncher : ITestModeLauncher { private readonly IEndlessGameProvider _endlessGameProvider; private readonly ICharacterRendererFactory _characterRendererFactory; private readonly IEIFFileProvider _eifFileProvider; private readonly IGameStateProvider _gameStateProvider; public TestModeLauncher(IEndlessGameProvider endlessGameProvider, ICharacterRendererFactory characterRendererFactory, IEIFFileProvider eifFileProvider, IGameStateProvider gameStateProvider) { _endlessGameProvider = endlessGameProvider; _characterRendererFactory = characterRendererFactory; _eifFileProvider = eifFileProvider; _gameStateProvider = gameStateProvider; } public void LaunchTestMode() { if (_gameStateProvider.CurrentState != GameStates.None) return; var testMode = new CharacterStateTest( _endlessGameProvider.Game, _characterRendererFactory, _eifFileProvider); _endlessGameProvider.Game.Components.Clear(); _endlessGameProvider.Game.Components.Add(testMode); } } public interface ITestModeLauncher { void LaunchTestMode(); } }
Split WCF functionality out of Autofac.Extras.Multitenant into a separate assembly/package, Autofac.Extras.Multitenant.Wcf. Both packages are versioned 3.1.0.
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.34003 // // 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-10-23 22:48")] [assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")] [assembly: AssemblyDescription("Autofac.Extras.EnterpriseLibraryConfigurator 3.0.0")]
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.18051 // // 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-12-03 10:23")] [assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")] [assembly: AssemblyDescription("Autofac.Extras.EnterpriseLibraryConfigurator 3.0.0")]
Make Range report invalid arguments when throwing
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ItemCollage { public static class Helper { public static IEnumerable<int> Range(int start, int end, int step = 1) { if (start > end && step > 0 || start < end && step < 0 || step == 0) throw new ArgumentException("Impossible range"); int steps = (end - start) / step; int i, s; for (i = start, s = 0; s <= steps; i += step, s++) { yield return i; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ItemCollage { public static class Helper { public static IEnumerable<int> Range(int start, int end, int step = 1) { if (start > end && step > 0 || start < end && step < 0 || step == 0) throw new ArgumentException(string.Format( "Impossible range: {0} to {1} with step {2}", start, end, step)); int steps = (end - start) / step; int i, s; for (i = start, s = 0; s <= steps; i += step, s++) { yield return i; } } } }
Change assembly version for release
using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle("ChangeLoadingImage_beta")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion("1.0.*")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")]
using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle("ChangeLoadingImage1.0")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion("1.0.*")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")]
Store sent date in UTC
using System; using System.Runtime.Serialization; [DataContract] class TellEntry { [DataMember] public readonly string From; [DataMember] public readonly string Message; [DataMember] public readonly DateTimeOffset SentDate; public TimeSpan ElapsedTime { get { return DateTimeOffset.Now - SentDate; } } public TellEntry(string from, string message) { From = from; Message = message; SentDate = DateTimeOffset.Now; } }
using System; using System.Runtime.Serialization; [DataContract] class TellEntry { [DataMember] public readonly string From; [DataMember] public readonly string Message; [DataMember] public readonly DateTime SentDateUtc; public TimeSpan ElapsedTime { get { return DateTime.UtcNow - SentDateUtc; } } public TellEntry(string from, string message) { From = from; Message = message; SentDateUtc = DateTime.UtcNow; } }
Enumerate once, make it readonly
using System; using System.Collections.Generic; using System.Linq; using NuGet.Packaging.Core; using NuGet.Versioning; namespace NuKeeper.RepositoryInspection { public class PackageUpdateSet { public PackageUpdateSet(PackageIdentity newPackage, IEnumerable<PackageInProject> currentPackages) { if (newPackage == null) { throw new ArgumentNullException(nameof(newPackage)); } if (currentPackages == null) { throw new ArgumentNullException(nameof(currentPackages)); } if (!currentPackages.Any()) { throw new ArgumentException($"{nameof(currentPackages)} is empty"); } if (currentPackages.Any(p => p.Id != newPackage.Id)) { throw new ArgumentException($"Updates must all be for package {newPackage.Id}"); } NewPackage = newPackage; CurrentPackages = currentPackages.ToList(); } public PackageIdentity NewPackage { get; } public List<PackageInProject> CurrentPackages { get; } public string PackageId => NewPackage.Id; public NuGetVersion NewVersion => NewPackage.Version; } }
using System; using System.Collections.Generic; using System.Linq; using NuGet.Packaging.Core; using NuGet.Versioning; namespace NuKeeper.RepositoryInspection { public class PackageUpdateSet { public PackageUpdateSet(PackageIdentity newPackage, IEnumerable<PackageInProject> currentPackages) { if (newPackage == null) { throw new ArgumentNullException(nameof(newPackage)); } if (currentPackages == null) { throw new ArgumentNullException(nameof(currentPackages)); } var currentPackagesList = currentPackages.ToList(); if (!currentPackagesList.Any()) { throw new ArgumentException($"{nameof(currentPackages)} is empty"); } if (currentPackagesList.Any(p => p.Id != newPackage.Id)) { throw new ArgumentException($"Updates must all be for package {newPackage.Id}"); } NewPackage = newPackage; CurrentPackages = currentPackagesList; } public PackageIdentity NewPackage { get; } public IReadOnlyCollection<PackageInProject> CurrentPackages { get; } public string PackageId => NewPackage.Id; public NuGetVersion NewVersion => NewPackage.Version; } }
Increment and Decrement with 0 does not send any data.
using System; using LandauMedia.Telemetry.Internal; namespace LandauMedia.Telemetry { public class Counter : ITelemeter { readonly Lazy<string> _lazyName; Action<Lazy<string>, int> _decrement; Action<Lazy<string>> _decrementByOne; Action<Lazy<string>, int> _icnremnent; Action<Lazy<string>> _increamentByOne; internal Counter(LazyName lazyName) { _lazyName = lazyName.Get(this); } void ITelemeter.ChangeImplementation(ITelemeterImpl impl) { _increamentByOne = impl.GetCounterIncrementByOne(); _icnremnent = impl.GetCounterIncrement(); _decrement = impl.GetCounterDecrement(); _decrementByOne = impl.GetCounterDecrementByOne(); } public void Increment() { _increamentByOne(_lazyName); } public void Increment(int count) { _icnremnent(_lazyName, count); } public void Decrement() { _decrementByOne(_lazyName); } public void Decrement(int count) { _decrement(_lazyName, count); } } }
using System; using LandauMedia.Telemetry.Internal; namespace LandauMedia.Telemetry { public class Counter : ITelemeter { readonly Lazy<string> _lazyName; Action<Lazy<string>, int> _decrement; Action<Lazy<string>> _decrementByOne; Action<Lazy<string>, int> _icnremnent; Action<Lazy<string>> _increamentByOne; internal Counter(LazyName lazyName) { _lazyName = lazyName.Get(this); } void ITelemeter.ChangeImplementation(ITelemeterImpl impl) { _increamentByOne = impl.GetCounterIncrementByOne(); _icnremnent = impl.GetCounterIncrement(); _decrement = impl.GetCounterDecrement(); _decrementByOne = impl.GetCounterDecrementByOne(); } public void Increment() { _increamentByOne(_lazyName); } public void Increment(int count) { if(count==0) return; _icnremnent(_lazyName, count); } public void Decrement() { _decrementByOne(_lazyName); } public void Decrement(int count) { if(count==0) return; _decrement(_lazyName, count); } } }
Change instance from Motor to Object in test case
using System; using CSharpTraining; using MonoBrickFirmware.Movement; namespace XUnitSample.Tests { /// <summary> /// Sample test class /// </summary> /// <remarks> /// It was described below URL how to use XUnit /// https://xunit.github.io/docs/comparisons.html /// </remarks> public class MainClassTests { [Xunit.Fact(DisplayName = "We can describe test summary by this attribute."), Xunit.Trait("Category", "Sample")] public void MainTest() { Xunit.Assert.True(true); Xunit.Assert.Equal(10, MainClass.SampleMethod()); var foo = new Motor(MotorPort.OutA); var same = foo; Xunit.Assert.Same(foo, same); // Verify their variables are same object. } [Xunit.Fact(Skip="If you want to ignore test case, you set this attribute to the test case.")] public void IgnoreTest() { Xunit.Assert.True(false, "Expected this test case does not be executed."); MainClass.Main(new string[] { "" }); Motor dummy = new Motor(MotorPort.OutA); dummy.GetSpeed(); } } }
using System; using CSharpTraining; using MonoBrickFirmware.Movement; namespace XUnitSample.Tests { /// <summary> /// Sample test class /// </summary> /// <remarks> /// It was described below URL how to use XUnit /// https://xunit.github.io/docs/comparisons.html /// </remarks> public class MainClassTests { [Xunit.Fact(DisplayName = "We can describe test summary by this attribute."), Xunit.Trait("Category", "Sample")] public void MainTest() { Xunit.Assert.True(true); Xunit.Assert.Equal(10, MainClass.SampleMethod()); var foo = new Object(); var same = foo; Xunit.Assert.Same(foo, same); // Verify their variables are same object. } [Xunit.Fact(Skip="If you want to ignore test case, you set this attribute to the test case.")] public void IgnoreTest() { Xunit.Assert.True(false, "Expected this test case does not be executed."); MainClass.Main(new string[] { "" }); Motor dummy = new Motor(MotorPort.OutA); dummy.GetSpeed(); } } }
Fix zip download to be non-blocking
#region Copyright (c) 2016 Atif Aziz. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion namespace WebLinq.Zip { using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; public static class ZipQuery { public static IEnumerable<HttpFetch<Zip>> DownloadZip(this IEnumerable<HttpFetch<HttpContent>> query) => from fetch in query select fetch.WithContent(new Zip(DownloadZip(fetch.Content))); static string DownloadZip(HttpContent content) { var path = Path.GetTempFileName(); using (var output = File.Create(path)) content.CopyToAsync(output).Wait(); return path; } } }
#region Copyright (c) 2016 Atif Aziz. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion namespace WebLinq.Zip { using System; using System.IO; using System.Net.Http; using System.Reactive.Linq; using System.Threading.Tasks; public static class ZipQuery { public static IObservable<HttpFetch<Zip>> DownloadZip(this IObservable<HttpFetch<HttpContent>> query) => from fetch in query from path in DownloadZip(fetch.Content) select fetch.WithContent(new Zip(path)); static async Task<string> DownloadZip(HttpContent content) { var path = Path.GetTempFileName(); using (var output = File.Create(path)) await content.CopyToAsync(output); return path; } } }
Fix KeyCounter M1 M2 display.
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Input; using OpenTK; using OpenTK.Input; namespace osu.Game.Screens.Play { public class KeyCounterMouse : KeyCounter { public MouseButton Button { get; } public KeyCounterMouse(MouseButton button) : base(button.ToString()) { Button = button; } public override bool Contains(Vector2 screenSpacePos) => true; protected override bool OnMouseDown(InputState state, MouseDownEventArgs args) { if (args.Button == Button) IsLit = true; return base.OnMouseDown(state, args); } protected override bool OnMouseUp(InputState state, MouseUpEventArgs args) { if (args.Button == Button) IsLit = false; return base.OnMouseUp(state, args); } } }
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Input; using OpenTK; using OpenTK.Input; namespace osu.Game.Screens.Play { public class KeyCounterMouse : KeyCounter { public MouseButton Button { get; } public KeyCounterMouse(MouseButton button) : base(getStringRepresentation(button)) { Button = button; } private static string getStringRepresentation(MouseButton button) { switch (button) { default: return button.ToString(); case MouseButton.Left: return @"M1"; case MouseButton.Right: return @"M2"; } } public override bool Contains(Vector2 screenSpacePos) => true; protected override bool OnMouseDown(InputState state, MouseDownEventArgs args) { if (args.Button == Button) IsLit = true; return base.OnMouseDown(state, args); } protected override bool OnMouseUp(InputState state, MouseUpEventArgs args) { if (args.Button == Button) IsLit = false; return base.OnMouseUp(state, args); } } }
Add platform init calls for UWP
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; namespace Sample.Forms.UWP { public sealed partial class MainPage { public MainPage() { this.InitializeComponent(); LoadApplication(new Sample.Forms.App()); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; namespace Sample.Forms.UWP { public sealed partial class MainPage { public MainPage() { this.InitializeComponent(); LoadApplication(new Sample.Forms.App()); ZXing.Net.Mobile.Forms.WindowsUniversal.ZXingScannerViewRenderer.Init(); ZXing.Net.Mobile.Forms.WindowsUniversal.ZXingBarcodeImageViewRenderer.Init(); } } }
Fix async warning in toggle block comment.
// 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; using System.ComponentModel.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CommentSelection; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Operations; using Microsoft.VisualStudio.Utilities; using VSCommanding = Microsoft.VisualStudio.Commanding; namespace Microsoft.CodeAnalysis.Editor.Implementation.CommentSelection { /* TODO - Modify these once the toggle block comment handler is added. [Export(typeof(VSCommanding.ICommandHandler))] [ContentType(ContentTypeNames.RoslynContentType)] [Name(PredefinedCommandHandlerNames.CommentSelection)]*/ internal class ToggleBlockCommentCommandHandler : AbstractToggleBlockCommentBase { [ImportingConstructor] internal ToggleBlockCommentCommandHandler( ITextUndoHistoryRegistry undoHistoryRegistry, IEditorOperationsFactoryService editorOperationsFactoryService) : base(undoHistoryRegistry, editorOperationsFactoryService) { } /// <summary> /// Gets the default text based document data provider for block comments. /// </summary> protected override async Task<IToggleBlockCommentDocumentDataProvider> GetBlockCommentDocumentDataProvider(Document document, ITextSnapshot snapshot, CommentSelectionInfo commentInfo, CancellationToken cancellationToken) { return new ToggleBlockCommentDocumentDataProvider(snapshot, commentInfo); } } }
// 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; using System.ComponentModel.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CommentSelection; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Operations; using Microsoft.VisualStudio.Utilities; using VSCommanding = Microsoft.VisualStudio.Commanding; namespace Microsoft.CodeAnalysis.Editor.Implementation.CommentSelection { /* TODO - Modify these once the toggle block comment handler is added. [Export(typeof(VSCommanding.ICommandHandler))] [ContentType(ContentTypeNames.RoslynContentType)] [Name(PredefinedCommandHandlerNames.CommentSelection)]*/ internal class ToggleBlockCommentCommandHandler : AbstractToggleBlockCommentBase { [ImportingConstructor] internal ToggleBlockCommentCommandHandler( ITextUndoHistoryRegistry undoHistoryRegistry, IEditorOperationsFactoryService editorOperationsFactoryService) : base(undoHistoryRegistry, editorOperationsFactoryService) { } /// <summary> /// Gets the default text based document data provider for block comments. /// </summary> protected override Task<IToggleBlockCommentDocumentDataProvider> GetBlockCommentDocumentDataProvider(Document document, ITextSnapshot snapshot, CommentSelectionInfo commentInfo, CancellationToken cancellationToken) { IToggleBlockCommentDocumentDataProvider provider = new ToggleBlockCommentDocumentDataProvider(snapshot, commentInfo); return Task.FromResult(provider); } } }
Add override to fix left/right arrow control
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using OpenTK.Graphics; using OpenTK.Input; using osu.Framework.Input; using System; namespace osu.Game.Graphics.UserInterface { /// <summary> /// A textbox which holds focus eagerly. /// </summary> public class FocusedTextBox : OsuTextBox { protected override Color4 BackgroundUnfocused => new Color4(10, 10, 10, 255); protected override Color4 BackgroundFocused => new Color4(10, 10, 10, 255); public Action Exit; private bool focus; public bool HoldFocus { get { return focus; } set { focus = value; if (!focus && HasFocus) GetContainingInputManager().ChangeFocus(null); } } protected override void OnFocus(InputState state) { base.OnFocus(state); BorderThickness = 0; } protected override bool OnKeyDown(InputState state, KeyDownEventArgs args) { if (!args.Repeat && args.Key == Key.Escape) { if (Text.Length > 0) Text = string.Empty; else Exit?.Invoke(); return true; } return base.OnKeyDown(state, args); } public override bool RequestsFocus => HoldFocus; } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using OpenTK.Graphics; using OpenTK.Input; using osu.Framework.Input; using System; namespace osu.Game.Graphics.UserInterface { /// <summary> /// A textbox which holds focus eagerly. /// </summary> public class FocusedTextBox : OsuTextBox { protected override Color4 BackgroundUnfocused => new Color4(10, 10, 10, 255); protected override Color4 BackgroundFocused => new Color4(10, 10, 10, 255); public Action Exit; public override bool HandleLeftRightArrows => false; private bool focus; public bool HoldFocus { get { return focus; } set { focus = value; if (!focus && HasFocus) GetContainingInputManager().ChangeFocus(null); } } protected override void OnFocus(InputState state) { base.OnFocus(state); BorderThickness = 0; } protected override bool OnKeyDown(InputState state, KeyDownEventArgs args) { if (!args.Repeat && args.Key == Key.Escape) { if (Text.Length > 0) Text = string.Empty; else Exit?.Invoke(); return true; } return base.OnKeyDown(state, args); } public override bool RequestsFocus => HoldFocus; } }
Change assembly version to be major version
// // Copyright (c) Microsoft. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System.Reflection; using System.Resources; [assembly: AssemblyTitle("Microsoft Azure Network Management Library")] [assembly: AssemblyDescription("Provides Microsoft Azure Network management functions for managing the Microsoft Azure Network service.")] [assembly: AssemblyVersion("6.1.1.0")] [assembly: AssemblyFileVersion("6.1.1.0")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Microsoft Azure .NET SDK")] [assembly: AssemblyCopyright("Copyright (c) Microsoft Corporation")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")]
// // Copyright (c) Microsoft. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System.Reflection; using System.Resources; [assembly: AssemblyTitle("Microsoft Azure Network Management Library")] [assembly: AssemblyDescription("Provides Microsoft Azure Network management functions for managing the Microsoft Azure Network service.")] [assembly: AssemblyVersion("6.0.0.0")] [assembly: AssemblyFileVersion("6.1.1.0")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Microsoft Azure .NET SDK")] [assembly: AssemblyCopyright("Copyright (c) Microsoft Corporation")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")]
Handle change to cookie parser.
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http.Core; using Microsoft.AspNet.Http.Core.Collections; using Xunit; namespace MusicStore.Models { public class ShoppingCartTest { [Fact] public void GetCartId_ReturnsCartIdFromCookies() { // Arrange var cartId = "cartId_A"; var httpContext = new DefaultHttpContext(); httpContext.SetFeature<IRequestCookiesFeature>(new CookiesFeature("Session=" + cartId)); var cart = new ShoppingCart(new MusicStoreContext()); // Act var result = cart.GetCartId(httpContext); // Assert Assert.NotNull(result); Assert.Equal(cartId, result); } private class CookiesFeature : IRequestCookiesFeature { private readonly RequestCookiesCollection _cookies; public CookiesFeature(string cookiesHeader) { _cookies = new RequestCookiesCollection(); _cookies.Reparse(cookiesHeader); } public IReadableStringCollection Cookies { get { return _cookies; } } } } }
using System.Collections.Generic; using Microsoft.AspNet.Http; using Microsoft.AspNet.Http.Core; using Microsoft.AspNet.Http.Core.Collections; using Xunit; namespace MusicStore.Models { public class ShoppingCartTest { [Fact] public void GetCartId_ReturnsCartIdFromCookies() { // Arrange var cartId = "cartId_A"; var httpContext = new DefaultHttpContext(); httpContext.SetFeature<IRequestCookiesFeature>(new CookiesFeature("Session", cartId)); var cart = new ShoppingCart(new MusicStoreContext()); // Act var result = cart.GetCartId(httpContext); // Assert Assert.NotNull(result); Assert.Equal(cartId, result); } private class CookiesFeature : IRequestCookiesFeature { private readonly IReadableStringCollection _cookies; public CookiesFeature(string key, string value) { _cookies = new ReadableStringCollection(new Dictionary<string, string[]>() { { key, new[] { value } } }); } public IReadableStringCollection Cookies { get { return _cookies; } } } } }
Add short link to Service
using System; namespace KpdApps.Common.MsCrm2015 { public class BasePluginAction { public PluginState State { get; set; } public BasePluginAction(PluginState state) { State = state; } public virtual void Execute() { throw new NotImplementedException(); } } }
using System; using Microsoft.Xrm.Sdk; namespace KpdApps.Common.MsCrm2015 { public class BasePluginAction { public PluginState State { get; set; } public IOrganizationService Service => State.Service; public BasePluginAction(PluginState state) { State = state; } public virtual void Execute() { throw new NotImplementedException(); } } }