Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Revert "Added method to perform validity check for effect parameters"
namespace SoxSharp.Effects { public abstract class BaseEffect : IBaseEffect { public abstract string Name { get; } public virtual bool IsValid() { return true; } public abstract override string ToString(); } }
namespace SoxSharp.Effects { public abstract class BaseEffect : IBaseEffect { public abstract string Name { get; } public abstract override string ToString(); } }
Add IsFilterActive; remove unneeded parameters for filter method (pass it on ctor)
using System; using System.Collections.Generic; using System.Linq; using PrepareLanding.Extensions; using RimWorld; using RimWorld.Planet; using UnityEngine; using Verse; namespace PrepareLanding.Filters { public abstract class TileFilter : ITileFilter { protected List<int> _filteredTiles = new List<int>(); public abstract string SubjectThingDef { get; } public virtual List<int> FilteredTiles => _filteredTiles; public virtual string RunningDescription => $"Filtering {SubjectThingDef}"; public string AttachedProperty { get; } public Action<PrepareLandingUserData, List<int>> FilterAction { get; } public FilterHeaviness Heaviness { get; } protected TileFilter(string attachedProperty, FilterHeaviness heaviness) { AttachedProperty = attachedProperty; Heaviness = heaviness; FilterAction = Filter; } public virtual void Filter(PrepareLandingUserData userData, List<int> inputList) { _filteredTiles.Clear(); } } }
using System; using System.Collections.Generic; using System.Linq; using PrepareLanding.Extensions; using RimWorld; using RimWorld.Planet; using UnityEngine; using Verse; namespace PrepareLanding.Filters { public abstract class TileFilter : ITileFilter { protected List<int> _filteredTiles = new List<int>(); protected PrepareLandingUserData UserData; public abstract string SubjectThingDef { get; } public abstract bool IsFilterActive { get; } public virtual List<int> FilteredTiles => _filteredTiles; public virtual string RunningDescription => $"Filtering {SubjectThingDef}"; public string AttachedProperty { get; } public Action<List<int>> FilterAction { get; } public FilterHeaviness Heaviness { get; } protected TileFilter(PrepareLandingUserData userData, string attachedProperty, FilterHeaviness heaviness) { UserData = userData; AttachedProperty = attachedProperty; Heaviness = heaviness; FilterAction = Filter; } public virtual void Filter(List<int> inputList) { _filteredTiles.Clear(); } } }
Update description, version and remove ComVisible
using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("NModbus4")] [assembly: AssemblyProduct("NModbus4")] [assembly: AssemblyCompany("Maxwe11")] [assembly: AssemblyCopyright("Licensed under MIT License.")] [assembly: AssemblyDescription("Differs from this one (https://code.google.com/p/nmodbus) in following: " + "removed FtdAdapter.dll, log4net, Unme.Common.dll dependencies, assembly renamed to NModbus.dll, " + "target framework changed to .NET 4")] // required for VBA applications [assembly: ComVisible(true)] [assembly: CLSCompliant(false)] [assembly: Guid("95B2AE1E-E0DC-4306-8431-D81ED10A2D5D")] [assembly: AssemblyVersion("1.12.0.0")] #if !WindowsCE [assembly: AssemblyFileVersion("1.12.0.0")] #endif #if !SIGNED [assembly: InternalsVisibleTo(@"Modbus.UnitTests")] [assembly: InternalsVisibleTo(@"DynamicProxyGenAssembly2")] #endif
using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("NModbus4")] [assembly: AssemblyProduct("NModbus4")] [assembly: AssemblyCompany("Maxwe11")] [assembly: AssemblyCopyright("Licensed under MIT License.")] [assembly: AssemblyDescription("NModbus is a C# implementation of the Modbus protocol. " + "Provides connectivity to Modbus slave compatible devices and applications. " + "Supports serial ASCII, serial RTU, TCP, and UDP protocols. "+ "NModbus4 it's a fork of NModbus(https://code.google.com/p/nmodbus)")] [assembly: CLSCompliant(false)] [assembly: Guid("95B2AE1E-E0DC-4306-8431-D81ED10A2D5D")] [assembly: AssemblyVersion("2.0.*")] #if !SIGNED [assembly: InternalsVisibleTo(@"Modbus.UnitTests")] [assembly: InternalsVisibleTo(@"DynamicProxyGenAssembly2")] #endif
Increase version number to 1.2.0.0.
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Common.Core")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Software Passion")] [assembly: AssemblyProduct("Common.Core")] [assembly: AssemblyCopyright("Copyright © Software Passion 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("30a96287-13a9-48e0-85db-4d0afe222eaf")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.1.0.0")] [assembly: AssemblyFileVersion("1.1.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Common.Core")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Software Passion")] [assembly: AssemblyProduct("Common.Core")] [assembly: AssemblyCopyright("Copyright © Software Passion 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("30a96287-13a9-48e0-85db-4d0afe222eaf")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.2.0.0")] [assembly: AssemblyFileVersion("1.2.0.0")]
Fix typos in cluster reroute explanation
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Nest { [JsonObject] public class ClusterRerouteExplanation { [JsonProperty("command")] public string Comand { get; set; } [JsonProperty("parameters")] public ClusterRerouteParameters Parameters { get; set; } [JsonProperty("decisions")] public IEnumerable<ClusterRerouteDecision> Descisions { get; set; } } }
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Nest { [JsonObject] public class ClusterRerouteExplanation { [JsonProperty("command")] public string Command { get; set; } [JsonProperty("parameters")] public ClusterRerouteParameters Parameters { get; set; } [JsonProperty("decisions")] public IEnumerable<ClusterRerouteDecision> Decisions { get; set; } } }
Correct the sand box to catch exception if a non-CLR dll is present.
using System; using System.Collections.Generic; using System.Text; using System.Reflection; namespace AgateLib.Drivers { class AgateSandBoxLoader : MarshalByRefObject { public AgateDriverInfo[] ReportDrivers(string file) { List<AgateDriverInfo> retval = new List<AgateDriverInfo>(); Assembly ass = Assembly.LoadFrom(file); foreach (Type t in ass.GetTypes()) { if (t.IsAbstract) continue; if (typeof(AgateDriverReporter).IsAssignableFrom(t) == false) continue; AgateDriverReporter reporter = (AgateDriverReporter)Activator.CreateInstance(t); foreach (AgateDriverInfo info in reporter.ReportDrivers()) { info.AssemblyFile = file; info.AssemblyName = ass.FullName; retval.Add(info); } } return retval.ToArray(); } } }
using System; using System.Collections.Generic; using System.Text; using System.Reflection; namespace AgateLib.Drivers { class AgateSandBoxLoader : MarshalByRefObject { public AgateDriverInfo[] ReportDrivers(string file) { List<AgateDriverInfo> retval = new List<AgateDriverInfo>(); Assembly ass; try { ass = Assembly.LoadFrom(file); } catch (BadImageFormatException) { System.Diagnostics.Debug.Print("Could not load the file {0}. Is it a CLR assembly?", file); return retval.ToArray(); } foreach (Type t in ass.GetTypes()) { if (t.IsAbstract) continue; if (typeof(AgateDriverReporter).IsAssignableFrom(t) == false) continue; AgateDriverReporter reporter = (AgateDriverReporter)Activator.CreateInstance(t); foreach (AgateDriverInfo info in reporter.ReportDrivers()) { info.AssemblyFile = file; info.AssemblyName = ass.FullName; retval.Add(info); } } return retval.ToArray(); } } }
Make html template container builder public.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO.IsolatedStorage; namespace Cassette { class HtmlTemplateModuleContainerBuilder : ModuleContainerBuilder { readonly string applicationRoot; public HtmlTemplateModuleContainerBuilder(IsolatedStorageFile storage, string rootDirectory, string applicationRoot) : base(storage, rootDirectory) { this.applicationRoot = EnsureDirectoryEndsWithSlash(applicationRoot); } public override ModuleContainer Build() { var moduleBuilder = new UnresolveHtmlTemplateModuleBuilder(rootDirectory); var unresolvedModules = relativeModuleDirectories.Select(x => moduleBuilder.Build(x.Item1, x.Item2)); var modules = UnresolvedModule.ResolveAll(unresolvedModules); return new ModuleContainer( modules, storage, textWriter => new HtmlTemplateModuleWriter(textWriter, rootDirectory, LoadFile) ); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO.IsolatedStorage; namespace Cassette { public class HtmlTemplateModuleContainerBuilder : ModuleContainerBuilder { readonly string applicationRoot; public HtmlTemplateModuleContainerBuilder(IsolatedStorageFile storage, string rootDirectory, string applicationRoot) : base(storage, rootDirectory) { this.applicationRoot = EnsureDirectoryEndsWithSlash(applicationRoot); } public override ModuleContainer Build() { var moduleBuilder = new UnresolveHtmlTemplateModuleBuilder(rootDirectory); var unresolvedModules = relativeModuleDirectories.Select(x => moduleBuilder.Build(x.Item1, x.Item2)); var modules = UnresolvedModule.ResolveAll(unresolvedModules); return new ModuleContainer( modules, storage, textWriter => new HtmlTemplateModuleWriter(textWriter, rootDirectory, LoadFile) ); } } }
Fix null ref access when texture panel is open and you hover over a texture that failed to load.
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Windows.Forms; using Assimp; namespace open3mod { public partial class TextureDetailsDialog : Form { private TextureThumbnailControl _tex; public TextureDetailsDialog() { InitializeComponent(); } public TextureThumbnailControl GetTexture() { return _tex; } public void SetTexture(TextureThumbnailControl tex) { Debug.Assert(tex != null && tex.Texture != null); _tex = tex; var img = tex.Texture.Image; Text = Path.GetFileName(tex.FilePath) + " - Details"; pictureBox1.Image = img; labelInfo.Text = string.Format("Size: {0} x {1} px", img.Width, img.Height); checkBoxHasAlpha.Checked = tex.Texture.HasAlpha == Texture.AlphaState.HasAlpha; pictureBox1.SizeMode = PictureBoxSizeMode.Zoom; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Windows.Forms; using Assimp; namespace open3mod { public partial class TextureDetailsDialog : Form { private TextureThumbnailControl _tex; public TextureDetailsDialog() { InitializeComponent(); } public TextureThumbnailControl GetTexture() { return _tex; } public void SetTexture(TextureThumbnailControl tex) { Debug.Assert(tex != null && tex.Texture != null); _tex = tex; var img = tex.Texture.Image; Text = Path.GetFileName(tex.FilePath) + " - Details"; pictureBox1.Image = img; if (img != null) { labelInfo.Text = string.Format("Size: {0} x {1} px", img.Width, img.Height); } checkBoxHasAlpha.Checked = tex.Texture.HasAlpha == Texture.AlphaState.HasAlpha; pictureBox1.SizeMode = PictureBoxSizeMode.Zoom; } } }
Use CurrentLocation.ProviderPath to get actual file system path
using System.Management.Automation; namespace PoshGit2 { class PSCurrentWorkingDirectory : ICurrentWorkingDirectory { private SessionState _sessionState; public PSCurrentWorkingDirectory(SessionState sessionState) { _sessionState = sessionState; } public string CWD { get { return _sessionState.Path.CurrentFileSystemLocation.Path; } } } }
using System.Management.Automation; namespace PoshGit2 { class PSCurrentWorkingDirectory : ICurrentWorkingDirectory { private SessionState _sessionState; public PSCurrentWorkingDirectory(SessionState sessionState) { _sessionState = sessionState; } public string CWD { get { return _sessionState.Path.CurrentLocation.ProviderPath; } } } }
Fix osu! mode adding combos twice.
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Game.Modes.Objects.Drawables; using osu.Game.Modes.Osu.Judgements; using osu.Game.Modes.Osu.Objects; using osu.Game.Modes.Scoring; using osu.Game.Modes.UI; namespace osu.Game.Modes.Osu.Scoring { internal class OsuScoreProcessor : ScoreProcessor<OsuHitObject, OsuJudgement> { public OsuScoreProcessor() { } public OsuScoreProcessor(HitRenderer<OsuHitObject, OsuJudgement> hitRenderer) : base(hitRenderer) { } protected override void Reset() { base.Reset(); Health.Value = 1; Accuracy.Value = 1; } protected override void OnNewJudgement(OsuJudgement judgement) { if (judgement != null) { switch (judgement.Result) { case HitResult.Hit: Combo.Value++; Health.Value += 0.1f; break; case HitResult.Miss: Combo.Value = 0; Health.Value -= 0.2f; break; } } int score = 0; int maxScore = 0; foreach (var j in Judgements) { score += j.ScoreValue; maxScore += j.MaxScoreValue; } TotalScore.Value = score; Accuracy.Value = (double)score / maxScore; } } }
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Game.Modes.Objects.Drawables; using osu.Game.Modes.Osu.Judgements; using osu.Game.Modes.Osu.Objects; using osu.Game.Modes.Scoring; using osu.Game.Modes.UI; namespace osu.Game.Modes.Osu.Scoring { internal class OsuScoreProcessor : ScoreProcessor<OsuHitObject, OsuJudgement> { public OsuScoreProcessor() { } public OsuScoreProcessor(HitRenderer<OsuHitObject, OsuJudgement> hitRenderer) : base(hitRenderer) { } protected override void Reset() { base.Reset(); Health.Value = 1; Accuracy.Value = 1; } protected override void OnNewJudgement(OsuJudgement judgement) { int score = 0; int maxScore = 0; foreach (var j in Judgements) { score += j.ScoreValue; maxScore += j.MaxScoreValue; } TotalScore.Value = score; Accuracy.Value = (double)score / maxScore; } } }
Test to have json overall anser
using System; using Nancy; namespace MicroServicesHelloWorld{ public class CurrentDateTimeModule: NancyModule { public CurrentDateTimeModule() { Get("/", _ => DateTime.UtcNow); } } }
using System; using Nancy; namespace MicroServicesHelloWorld{ public class CurrentDateTimeModule: NancyModule { public CurrentDateTimeModule() { Get("/", _ => { var response = (Response)("\""+DateTime.UtcNow.ToString()+"\""); response.ContentType = "application/json"; return response; }); } } }
Fix typo in the CbxBundle refactoring causing the bytecode to not get copied to exported projects.
using System.Collections.Generic; namespace Wax { public class CbxBundleView : JsonBasedObject { public string ByteCode { get { return this.GetString("byteCode"); } set { this.SetString("byteCode", value); } } public ResourceDatabase ResourceDB { get { return this.GetObject("resources") as ResourceDatabase; } set { this.SetObject("resources", value); } } public CbxBundleView(Dictionary<string, object> data) : base(data) { } public CbxBundleView(string byteCode, ResourceDatabase resDb) { this.ByteCode = ByteCode; this.ResourceDB = resDb; } } }
using System.Collections.Generic; namespace Wax { public class CbxBundleView : JsonBasedObject { public string ByteCode { get { return this.GetString("byteCode"); } set { this.SetString("byteCode", value); } } public ResourceDatabase ResourceDB { get { return this.GetObject("resources") as ResourceDatabase; } set { this.SetObject("resources", value); } } public CbxBundleView(Dictionary<string, object> data) : base(data) { } public CbxBundleView(string byteCode, ResourceDatabase resDb) { this.ByteCode = byteCode; this.ResourceDB = resDb; } } }
Add Custom Error Page and Routing
using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; namespace Portal.CMS.Web { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } protected void Application_Error() { //Response.Redirect("~/Home/Error"); } } }
using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; namespace Portal.CMS.Web { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } protected void Application_Error() { Response.Redirect("~/Home/Error"); } } }
Throw better exception for invalid interfaces
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Reflection; using System.Reflection.Metadata; using System.Threading; using Debug = System.Diagnostics.Debug; using Internal.TypeSystem; namespace Internal.TypeSystem.Ecma { // This file has implementations of the .Interfaces.cs logic from its base type. public sealed partial class EcmaType : MetadataType { private DefType[] _implementedInterfaces; public override DefType[] ExplicitlyImplementedInterfaces { get { if (_implementedInterfaces == null) return InitializeImplementedInterfaces(); return _implementedInterfaces; } } private DefType[] InitializeImplementedInterfaces() { var interfaceHandles = _typeDefinition.GetInterfaceImplementations(); int count = interfaceHandles.Count; if (count == 0) return (_implementedInterfaces = Array.Empty<DefType>()); DefType[] implementedInterfaces = new DefType[count]; int i = 0; foreach (var interfaceHandle in interfaceHandles) { var interfaceImplementation = this.MetadataReader.GetInterfaceImplementation(interfaceHandle); implementedInterfaces[i++] = (DefType)_module.GetType(interfaceImplementation.Interface); } return (_implementedInterfaces = implementedInterfaces); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Reflection; using System.Reflection.Metadata; using System.Threading; using Debug = System.Diagnostics.Debug; using Internal.TypeSystem; namespace Internal.TypeSystem.Ecma { // This file has implementations of the .Interfaces.cs logic from its base type. public sealed partial class EcmaType : MetadataType { private DefType[] _implementedInterfaces; public override DefType[] ExplicitlyImplementedInterfaces { get { if (_implementedInterfaces == null) return InitializeImplementedInterfaces(); return _implementedInterfaces; } } private DefType[] InitializeImplementedInterfaces() { var interfaceHandles = _typeDefinition.GetInterfaceImplementations(); int count = interfaceHandles.Count; if (count == 0) return (_implementedInterfaces = Array.Empty<DefType>()); DefType[] implementedInterfaces = new DefType[count]; int i = 0; foreach (var interfaceHandle in interfaceHandles) { var interfaceImplementation = this.MetadataReader.GetInterfaceImplementation(interfaceHandle); DefType interfaceType = _module.GetType(interfaceImplementation.Interface) as DefType; if (interfaceType == null) throw new TypeSystemException.TypeLoadException(ExceptionStringID.ClassLoadBadFormat, this); implementedInterfaces[i++] = interfaceType; } return (_implementedInterfaces = implementedInterfaces); } } }
Add label to the node colour key explaining what it is
using Gtk; using SlimeSimulation.Controller.WindowComponentController; namespace SlimeSimulation.View.WindowComponent { public class NodeHighlightKey { public Widget GetVisualKey() { VBox key = new VBox(true, 10); HBox sourcePart = new HBox(true, 10); sourcePart.Add(new Label("Source")); sourcePart.Add(GetBoxColour(FlowResultNodeViewController.SourceColour)); HBox sinkPart = new HBox(true, 10); sinkPart.Add(new Label("Sink")); sinkPart.Add(GetBoxColour(FlowResultNodeViewController.SinkColour)); HBox normalPart = new HBox(true, 10); normalPart.Add(new Label("Normal node")); normalPart.Add(GetBoxColour(FlowResultNodeViewController.NormalNodeColour)); key.Add(sourcePart); key.Add(sinkPart); key.Add(normalPart); return key; } private DrawingArea GetBoxColour(Rgb color) { return new ColorArea(color); } } }
using Gtk; using SlimeSimulation.Controller.WindowComponentController; namespace SlimeSimulation.View.WindowComponent { public class NodeHighlightKey { public Widget GetVisualKey() { VBox key = new VBox(true, 10); key.Add(new Label("Node colour key")); var sourcePart = new HBox(true, 10); sourcePart.Add(new Label("Source")); sourcePart.Add(GetBoxColour(FlowResultNodeViewController.SourceColour)); HBox sinkPart = new HBox(true, 10); sinkPart.Add(new Label("Sink")); sinkPart.Add(GetBoxColour(FlowResultNodeViewController.SinkColour)); HBox normalPart = new HBox(true, 10); normalPart.Add(new Label("Normal node")); normalPart.Add(GetBoxColour(FlowResultNodeViewController.NormalNodeColour)); key.Add(sourcePart); key.Add(sinkPart); key.Add(normalPart); return key; } private DrawingArea GetBoxColour(Rgb color) { return new ColorArea(color); } } }
Add shipment for physical goods
using System; using System.Collections.Generic; namespace conekta { public class Details { public string name { get; set; } public string phone { get; set; } public string email { get; set; } public Customer customer { get; set; } public List<LineItem> line_items { get; set; } public BillingAddress billing_address { get; set; } } }
using System; using System.Collections.Generic; namespace conekta { public class Details { public string name { get; set; } public string phone { get; set; } public string email { get; set; } public Customer customer { get; set; } public List<LineItem> line_items { get; set; } public BillingAddress billing_address { get; set; } public ShippingAddress shipment { get; set; } } }
Replace precision check with absolute equality assert
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Linq; using NUnit.Framework; using osu.Framework.Utils; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Scoring; using osu.Game.Screens.Ranking.Statistics; namespace osu.Game.Tests.NonVisual.Ranking { [TestFixture] public class UnstableRateTest { [Test] public void TestDistributedHits() { var events = Enumerable.Range(-5, 11) .Select(t => new HitEvent(t - 5, HitResult.Great, new HitObject(), null, null)); var unstableRate = new UnstableRate(events); Assert.IsTrue(Precision.AlmostEquals(unstableRate.Value, 10 * Math.Sqrt(10))); } [Test] public void TestMissesAndEmptyWindows() { var events = new[] { new HitEvent(-100, HitResult.Miss, new HitObject(), null, null), new HitEvent(0, HitResult.Great, new HitObject(), null, null), new HitEvent(200, HitResult.Meh, new HitObject { HitWindows = HitWindows.Empty }, null, null), }; var unstableRate = new UnstableRate(events); Assert.IsTrue(Precision.AlmostEquals(0, unstableRate.Value)); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Linq; using NUnit.Framework; using osu.Framework.Utils; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Scoring; using osu.Game.Screens.Ranking.Statistics; namespace osu.Game.Tests.NonVisual.Ranking { [TestFixture] public class UnstableRateTest { [Test] public void TestDistributedHits() { var events = Enumerable.Range(-5, 11) .Select(t => new HitEvent(t - 5, HitResult.Great, new HitObject(), null, null)); var unstableRate = new UnstableRate(events); Assert.IsTrue(Precision.AlmostEquals(unstableRate.Value, 10 * Math.Sqrt(10))); } [Test] public void TestMissesAndEmptyWindows() { var events = new[] { new HitEvent(-100, HitResult.Miss, new HitObject(), null, null), new HitEvent(0, HitResult.Great, new HitObject(), null, null), new HitEvent(200, HitResult.Meh, new HitObject { HitWindows = HitWindows.Empty }, null, null), }; var unstableRate = new UnstableRate(events); Assert.AreEqual(0, unstableRate.Value); } } }
Fix incorrect return type for spotlight request
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using osu.Game.Online.API.Requests.Responses; namespace osu.Game.Online.API.Requests { public class GetSpotlightsRequest : APIRequest<List<APISpotlight>> { protected override string Target => "spotlights"; } }
// 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 Newtonsoft.Json; using osu.Game.Online.API.Requests.Responses; namespace osu.Game.Online.API.Requests { public class GetSpotlightsRequest : APIRequest<SpotlightsArray> { protected override string Target => "spotlights"; } public class SpotlightsArray { [JsonProperty("spotlights")] public List<APISpotlight> Spotlights; } }
Throw exception if BMP version != 3
using System; using System.Linq; using BmpListener; using BmpListener.Extensions; namespace BmpListener.Bmp { public class BmpHeader { public BmpHeader(byte[] data) { Version = data.First(); //if (Version != 3) //{ // throw new Exception("invalid BMP version"); //} Length = data.ToInt32(1); MessageType = (BmpMessage.Type)data.ElementAt(5); } public byte Version { get; } public int Length { get; } public BmpMessage.Type MessageType { get; } } }
using System; using System.Linq; using BmpListener; using BmpListener.Extensions; namespace BmpListener.Bmp { public class BmpHeader { private readonly int bmpVersion = 3; public BmpHeader(byte[] data) { Version = data.First(); if (Version != bmpVersion) { throw new NotSupportedException("version error"); } Length = data.ToInt32(1); MessageType = (BmpMessage.Type)data.ElementAt(5); } public byte Version { get; } public int Length { get; } public BmpMessage.Type MessageType { get; } } }
Fix issues on first run, which takes a little longer to start up
using System; using System.Net.Http; using System.Threading; using PactNet.Core; namespace PactNet.Mocks.MockHttpService.Host { internal class RubyHttpHost : IHttpHost { private readonly IPactCoreHost _coreHost; private readonly HttpClient _httpClient; internal RubyHttpHost(IPactCoreHost coreHost, HttpClient httpClient) { _coreHost = coreHost; _httpClient = httpClient; //TODO: Use the admin http client once extracted } public RubyHttpHost(Uri baseUri, string providerName, PactConfig config) : this(new PactCoreHost<MockProviderHostConfig>( new MockProviderHostConfig(baseUri.Port, baseUri.Scheme.ToUpperInvariant().Equals("HTTPS"), providerName, config)), new HttpClient { BaseAddress = baseUri }) { } private bool IsMockProviderServiceRunning() { var aliveRequest = new HttpRequestMessage(HttpMethod.Get, "/"); aliveRequest.Headers.Add(Constants.AdministrativeRequestHeaderKey, "true"); var responseMessage = _httpClient.SendAsync(aliveRequest).Result; return responseMessage.IsSuccessStatusCode; } public void Start() { _coreHost.Start(); var aliveChecks = 1; while (!IsMockProviderServiceRunning()) { if (aliveChecks >= 20) { throw new PactFailureException("Could not start the mock provider service"); } Thread.Sleep(200); aliveChecks++; } } public void Stop() { _coreHost.Stop(); } } }
using System; using System.Net.Http; using System.Threading; using PactNet.Core; namespace PactNet.Mocks.MockHttpService.Host { internal class RubyHttpHost : IHttpHost { private readonly IPactCoreHost _coreHost; private readonly HttpClient _httpClient; internal RubyHttpHost(IPactCoreHost coreHost, HttpClient httpClient) { _coreHost = coreHost; _httpClient = httpClient; //TODO: Use the admin http client once extracted } public RubyHttpHost(Uri baseUri, string providerName, PactConfig config) : this(new PactCoreHost<MockProviderHostConfig>( new MockProviderHostConfig(baseUri.Port, baseUri.Scheme.ToUpperInvariant().Equals("HTTPS"), providerName, config)), new HttpClient { BaseAddress = baseUri }) { } private bool IsMockProviderServiceRunning() { try { var aliveRequest = new HttpRequestMessage(HttpMethod.Get, "/"); aliveRequest.Headers.Add(Constants.AdministrativeRequestHeaderKey, "true"); var responseMessage = _httpClient.SendAsync(aliveRequest).Result; return responseMessage.IsSuccessStatusCode; } catch { return false; } } public void Start() { _coreHost.Start(); var aliveChecks = 1; while (!IsMockProviderServiceRunning()) { if (aliveChecks >= 20) { throw new PactFailureException("Could not start the mock provider service"); } Thread.Sleep(200); aliveChecks++; } } public void Stop() { _coreHost.Stop(); } } }
Add argument checking on commit
using System; using System.Collections.Generic; using System.Threading; namespace CollabEdit.VersionControl { public class RepositoryBranch<TValue, TMeta> { private object syncRoot = new Object(); public RepositoryBranch() { } public RepositoryBranch(string name, Repository<TValue, TMeta> repository, Commit<TValue, TMeta> head) { if (string.IsNullOrEmpty(name)) throw new ArgumentException("Name may not be null or empty string."); if (repository == null) throw new ArgumentNullException(nameof(repository)); Name = name; Repository = repository; Head = head; } public Repository<TValue, TMeta> Repository { get; } public string Name { get; } public Commit<TValue, TMeta> Head { get; protected set; } public Commit<TValue, TMeta> Commit(TValue value, TMeta metadata) { if (Head != null && Head.Value.Equals(value)) return Head; // Value was not changed, so no need to create a new version. lock (syncRoot) { var commit = new Commit<TValue, TMeta>(value, metadata, Head); Head = commit; return commit; } } public virtual Commit<TValue, TMeta> MergeWith(RepositoryBranch<TValue, TMeta> sourceBranch) { throw new NotImplementedException(); } public IEnumerable<Commit<TValue, TMeta>> GetHistory() { if (Head == null) yield break; var next = Head; while (next != null) { yield return next; next = next.Parent; } } } }
using System; using System.Collections.Generic; using System.Threading; namespace CollabEdit.VersionControl { public class RepositoryBranch<TValue, TMeta> { private object syncRoot = new Object(); public RepositoryBranch() { } public RepositoryBranch(string name, Repository<TValue, TMeta> repository, Commit<TValue, TMeta> head) { if (string.IsNullOrEmpty(name)) throw new ArgumentException("Name may not be null or empty string."); if (repository == null) throw new ArgumentNullException(nameof(repository)); Name = name; Repository = repository; Head = head; } public Repository<TValue, TMeta> Repository { get; } public string Name { get; } public Commit<TValue, TMeta> Head { get; protected set; } public Commit<TValue, TMeta> Commit(TValue value, TMeta metadata) { if (value == null) throw new ArgumentNullException(nameof(value)); if (metadata == null) throw new ArgumentException(nameof(metadata)); if (Head != null && Head.Value.Equals(value)) return Head; // Value was not changed, so no need to create a new version. lock (syncRoot) { var commit = new Commit<TValue, TMeta>(value, metadata, Head); Head = commit; return commit; } } public virtual Commit<TValue, TMeta> MergeWith(RepositoryBranch<TValue, TMeta> sourceBranch) { throw new NotImplementedException(); } public IEnumerable<Commit<TValue, TMeta>> GetHistory() { if (Head == null) yield break; var next = Head; while (next != null) { yield return next; next = next.Parent; } } } }
Add form for setting balance in one step
@model Cash_Flow_Projection.Models.Dashboard @{ ViewData["Title"] = "Home Page"; } <table class="table table-striped"> @foreach (var entry in Model.Entries.OrderBy(_ => _.Date)) { <tr> <td>@Html.DisplayFor(_ => entry.Date)</td> <td>@Html.DisplayFor(_ => entry.Description)</td> <td>@Html.DisplayFor(_ => entry.Amount)</td> <td>@Cash_Flow_Projection.Models.Balance.BalanceAsOf(Model.Entries, entry.Date)</td> <td> @using (Html.BeginForm("Delete", "Home", new { id = entry.id }, FormMethod.Post)) { @Html.AntiForgeryToken() <button type="submit">Delete</button> } </td> </tr> } </table>
@model Cash_Flow_Projection.Models.Dashboard @{ ViewData["Title"] = "Home Page"; } @using (Html.BeginForm("Balance", "Home", FormMethod.Post)) { @Html.AntiForgeryToken() <input type="text" id="balance" placeholder="Set Balance" /> <button type="submit">Set</button> } <table class="table table-striped"> @foreach (var entry in Model.Entries.OrderBy(_ => _.Date)) { <tr> <td>@Html.DisplayFor(_ => entry.Date)</td> <td>@Html.DisplayFor(_ => entry.Description)</td> <td>@Html.DisplayFor(_ => entry.Amount)</td> <td>@Cash_Flow_Projection.Models.Balance.BalanceAsOf(Model.Entries, entry.Date)</td> <td> @using (Html.BeginForm("Delete", "Home", new { id = entry.id }, FormMethod.Post)) { @Html.AntiForgeryToken() <button type="submit">Delete</button> } </td> </tr> } </table>
Move variable to inner scope where it's used
using UnityEngine; using System; using System.Collections; public class MapifyLevelPopulator { private MapifyMapIterator mapIterator; private MapifyTileRepository tileRepository; private Transform container; public MapifyLevelPopulator(MapifyMapIterator mapIterator, MapifyTileRepository tileRepository, Transform container) { this.mapIterator = mapIterator; this.tileRepository = tileRepository; this.container = container; } public void Populate() { mapIterator.Iterate((character, localPosition) => { var worldPosition = container.TransformPoint(localPosition); if (tileRepository.HasKey(character)) { var tile = tileRepository.Find(character); MapifyTileSpawner.Create(tile, worldPosition, container); } }); } }
using UnityEngine; using System; using System.Collections; public class MapifyLevelPopulator { private MapifyMapIterator mapIterator; private MapifyTileRepository tileRepository; private Transform container; public MapifyLevelPopulator(MapifyMapIterator mapIterator, MapifyTileRepository tileRepository, Transform container) { this.mapIterator = mapIterator; this.tileRepository = tileRepository; this.container = container; } public void Populate() { mapIterator.Iterate((character, localPosition) => { if (tileRepository.HasKey(character)) { var tile = tileRepository.Find(character); var worldPosition = container.TransformPoint(localPosition); MapifyTileSpawner.Create(tile, worldPosition, container); } }); } }
Correct typo (just caught my eye, no biggie).
using System.Globalization; namespace Our.Umbraco.Ditto.Tests.Models { using System.ComponentModel; using Our.Umbraco.Ditto.Tests.TypeConverters; using global::Umbraco.Core.Models; public class ComplexModel { public int Id { get; set; } [DittoValueResolver(typeof(NameVauleResovler))] public string Name { get; set; } [UmbracoProperty("myprop")] public IPublishedContent MyProperty { get; set; } [UmbracoProperty("Id")] [TypeConverter(typeof(MockPublishedContentConverter))] public IPublishedContent MyPublishedContent { get; set; } } public class NameVauleResovler : DittoValueResolver { public override object ResolveValue(ITypeDescriptorContext context, DittoValueResolverAttribute attribute, CultureInfo culture) { var content = context.Instance as IPublishedContent; if (content == null) return null; return content.Name + " Test"; } } }
using System.Globalization; namespace Our.Umbraco.Ditto.Tests.Models { using System.ComponentModel; using Our.Umbraco.Ditto.Tests.TypeConverters; using global::Umbraco.Core.Models; public class ComplexModel { public int Id { get; set; } [DittoValueResolver(typeof(NameValueResovler))] public string Name { get; set; } [UmbracoProperty("myprop")] public IPublishedContent MyProperty { get; set; } [UmbracoProperty("Id")] [TypeConverter(typeof(MockPublishedContentConverter))] public IPublishedContent MyPublishedContent { get; set; } } public class NameValueResovler : DittoValueResolver { public override object ResolveValue(ITypeDescriptorContext context, DittoValueResolverAttribute attribute, CultureInfo culture) { var content = context.Instance as IPublishedContent; if (content == null) return null; return content.Name + " Test"; } } }
Add retry when invoking the lazy to build TagDictionary
using System; using System.Collections.Generic; using System.IO; using FifteenBelow.Deployment.Update; namespace Ensconce { internal static class TextRendering { private static readonly Lazy<TagDictionary> LazyTags = new Lazy<TagDictionary>(BuildTagDictionary); public static IDictionary<string, object> TagDictionary { get { return LazyTags.Value; } } internal static string Render(this string s) { return s.RenderTemplate(LazyTags.Value); } private static TagDictionary BuildTagDictionary() { Logging.Log("Building Tag Dictionary"); var instanceName = Environment.GetEnvironmentVariable("InstanceName"); Logging.Log("Building Tag Dictionary ({0})", instanceName); var tags = new TagDictionary(instanceName); Logging.Log("Built Tag Dictionary ({0})", instanceName); Arguments.FixedPath = Arguments.FixedPath.RenderTemplate(tags); if (File.Exists(Arguments.FixedPath)) { Logging.Log("Loading xml config from file {0}", Path.GetFullPath(Arguments.FixedPath)); var configXml = Retry.Do(() => File.ReadAllText(Arguments.FixedPath), TimeSpan.FromSeconds(5)); Logging.Log("Re-Building Tag Dictionary (Using Config File)"); tags = new TagDictionary(instanceName, configXml); Logging.Log("Built Tag Dictionary (Using Config File)"); } else { Logging.Log("No structure file found at: {0}", Path.GetFullPath(Arguments.FixedPath)); } return tags; } } }
using System; using System.Collections.Generic; using System.IO; using FifteenBelow.Deployment.Update; namespace Ensconce { internal static class TextRendering { private static readonly Lazy<TagDictionary> LazyTags = new Lazy<TagDictionary>(() => Retry.Do(BuildTagDictionary, TimeSpan.FromSeconds(5))); public static IDictionary<string, object> TagDictionary { get { return LazyTags.Value; } } internal static string Render(this string s) { return s.RenderTemplate(TagDictionary); } private static TagDictionary BuildTagDictionary() { Logging.Log("Building Tag Dictionary"); var instanceName = Environment.GetEnvironmentVariable("InstanceName"); Logging.Log("Building Tag Dictionary ({0})", instanceName); var tags = new TagDictionary(instanceName); Logging.Log("Built Tag Dictionary ({0})", instanceName); Arguments.FixedPath = Arguments.FixedPath.RenderTemplate(tags); if (File.Exists(Arguments.FixedPath)) { Logging.Log("Loading xml config from file {0}", Path.GetFullPath(Arguments.FixedPath)); var configXml = Retry.Do(() => File.ReadAllText(Arguments.FixedPath), TimeSpan.FromSeconds(5)); Logging.Log("Re-Building Tag Dictionary (Using Config File)"); tags = new TagDictionary(instanceName, configXml); Logging.Log("Built Tag Dictionary (Using Config File)"); } else { Logging.Log("No structure file found at: {0}", Path.GetFullPath(Arguments.FixedPath)); } return tags; } } }
Change Pick 'position' property to int as it represents position in team
using Newtonsoft.Json; namespace FplClient.Data { public class FplPick { [JsonProperty("element")] public int PlayerId { get; set; } [JsonProperty("element_type")] public int ElementType { get; set; } [JsonProperty("position")] public FplPlayerPosition Position { get; set; } [JsonProperty("points")] public int Points { get; set; } [JsonProperty("can_captain")] public bool? CanCaptain { get; set; } [JsonProperty("is_captain")] public bool IsCaptain { get; set; } [JsonProperty("is_vice_captain")] public bool IsViceCaptain { get; set; } [JsonProperty("can_sub")] public bool? CanSub { get; set; } [JsonProperty("is_sub")] public bool IsSub { get; set; } [JsonProperty("has_played")] public bool HasPlayed { get; set; } [JsonProperty("stats")] public FplPickStats Stats { get; set; } [JsonProperty("multiplier")] public int Multiplier { get; set; } } }
using Newtonsoft.Json; namespace FplClient.Data { public class FplPick { [JsonProperty("element")] public int PlayerId { get; set; } [JsonProperty("element_type")] public int ElementType { get; set; } [JsonProperty("position")] public int TeamPosition { get; set; } [JsonProperty("points")] public int Points { get; set; } [JsonProperty("can_captain")] public bool? CanCaptain { get; set; } [JsonProperty("is_captain")] public bool IsCaptain { get; set; } [JsonProperty("is_vice_captain")] public bool IsViceCaptain { get; set; } [JsonProperty("can_sub")] public bool? CanSub { get; set; } [JsonProperty("is_sub")] public bool IsSub { get; set; } [JsonProperty("has_played")] public bool HasPlayed { get; set; } [JsonProperty("stats")] public FplPickStats Stats { get; set; } [JsonProperty("multiplier")] public int Multiplier { get; set; } } }
Replace Enumerable.Repeat call with an one-element array.
using System.Collections.Generic; using System.Linq; namespace NuGet.VisualStudio { public static class AggregatePackageSource { public static readonly PackageSource Instance = new PackageSource("(Aggregate source)", Resources.VsResources.AggregateSourceName); public static bool IsAggregate(this PackageSource source) { return source == Instance; } public static IEnumerable<PackageSource> GetPackageSourcesWithAggregate(this IPackageSourceProvider provider) { return Enumerable.Repeat(Instance, 1).Concat(provider.LoadPackageSources()); } public static IEnumerable<PackageSource> GetPackageSourcesWithAggregate() { return GetPackageSourcesWithAggregate(ServiceLocator.GetInstance<IVsPackageSourceProvider>()); } } }
using System.Collections.Generic; using System.Linq; namespace NuGet.VisualStudio { public static class AggregatePackageSource { public static readonly PackageSource Instance = new PackageSource("(Aggregate source)", Resources.VsResources.AggregateSourceName); public static bool IsAggregate(this PackageSource source) { return source == Instance; } public static IEnumerable<PackageSource> GetPackageSourcesWithAggregate(this IPackageSourceProvider provider) { return new[] { Instance }.Concat(provider.LoadPackageSources()); } public static IEnumerable<PackageSource> GetPackageSourcesWithAggregate() { return GetPackageSourcesWithAggregate(ServiceLocator.GetInstance<IVsPackageSourceProvider>()); } } }
Add integration tests for MalUserNotFoundException being thrown.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using NUnit.Framework; using MalApi; namespace MalApi.IntegrationTests { [TestFixture] public class GetAnimeListForUserTest { [Test] public void GetAnimeListForUser() { string username = "lordhighcaptain"; using (MyAnimeListApi api = new MyAnimeListApi()) { MalUserLookupResults userLookup = api.GetAnimeListForUser(username); // Just a smoke test that checks that getting an anime list returns something Assert.That(userLookup.AnimeList, Is.Not.Empty); } } } } /* Copyright 2012 Greg Najda Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */
using System; using System.Collections.Generic; using System.Linq; using System.Text; using NUnit.Framework; using MalApi; using System.Threading.Tasks; namespace MalApi.IntegrationTests { [TestFixture] public class GetAnimeListForUserTest { [Test] public void GetAnimeListForUser() { string username = "lordhighcaptain"; using (MyAnimeListApi api = new MyAnimeListApi()) { MalUserLookupResults userLookup = api.GetAnimeListForUser(username); // Just a smoke test that checks that getting an anime list returns something Assert.That(userLookup.AnimeList, Is.Not.Empty); } } [Test] public void GetAnimeListForNonexistentUserThrowsCorrectException() { using (MyAnimeListApi api = new MyAnimeListApi()) { Assert.Throws<MalUserNotFoundException>(() => api.GetAnimeListForUser("oijsfjisfdjfsdojpfsdp")); } } [Test] public void GetAnimeListForNonexistentUserThrowsCorrectExceptionAsync() { using (MyAnimeListApi api = new MyAnimeListApi()) { Assert.ThrowsAsync<MalUserNotFoundException>(() => api.GetAnimeListForUserAsync("oijsfjisfdjfsdojpfsdp")); } } } } /* Copyright 2017 Greg Najda 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. */
Improve the efficiency of puzzle 12
// 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.ProjectEuler.Puzzles { using System; using System.Linq; /// <summary> /// A class representing the solution to <c>https://projecteuler.net/problem=12</c>. This class cannot be inherited. /// </summary> internal sealed class Puzzle012 : Puzzle { /// <inheritdoc /> public override string Question => "What is the value of the first triangle number to have the specified number of divisors?"; /// <inheritdoc /> protected override int MinimumArguments => 1; /// <inheritdoc /> protected override int SolveCore(string[] args) { int divisors; if (!TryParseInt32(args[0], out divisors) || divisors < 1) { Console.Error.WriteLine("The specified number of divisors is invalid."); return -1; } for (int i = 1; ; i++) { long triangleNumber = ParallelEnumerable.Range(1, i) .Select((p) => (long)p) .Sum(); int numberOfFactors = Maths.GetFactors(triangleNumber).Count(); if (numberOfFactors >= divisors) { Answer = triangleNumber; break; } } return 0; } } }
// 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.ProjectEuler.Puzzles { using System; using System.Linq; /// <summary> /// A class representing the solution to <c>https://projecteuler.net/problem=12</c>. This class cannot be inherited. /// </summary> internal sealed class Puzzle012 : Puzzle { /// <inheritdoc /> public override string Question => "What is the value of the first triangle number to have the specified number of divisors?"; /// <inheritdoc /> protected override int MinimumArguments => 1; /// <inheritdoc /> protected override int SolveCore(string[] args) { int divisors; if (!TryParseInt32(args[0], out divisors) || divisors < 1) { Console.Error.WriteLine("The specified number of divisors is invalid."); return -1; } long triangleNumber = 0; for (int n = 1; ; n++) { triangleNumber += n; int numberOfFactors = Maths.GetFactors(triangleNumber).Count(); if (numberOfFactors >= divisors) { Answer = triangleNumber; break; } } return 0; } } }
Make RemoteService a Duplex Service
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel; using System.Text; using System.Threading.Tasks; namespace SPAD.neXt.Interfaces.ServiceContract { public sealed class RemoteServiceResponse { public bool HasError { get; set; } public string Error { get; set; } public double Value { get; set; } } [ServiceContract] [ServiceKnownType(typeof(RemoteServiceResponse))] public interface IRemoteService { [OperationContract] RemoteServiceResponse GetValue(string variableName); [OperationContract] RemoteServiceResponse SetValue(string variableName, double newValue); [OperationContract] RemoteServiceResponse EmulateEvent(string eventTarget, string eventName, string eventParameter); } }
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel; using System.Text; using System.Threading.Tasks; namespace SPAD.neXt.Interfaces.ServiceContract { public static class RemoteServiceContract { public static readonly Uri ServiceUrl = new Uri("net.pipe://localhost/SPAD.neXt"); public static readonly string ServiceEndpoint = "RemoteService"; } public sealed class RemoteServiceResponse { public bool HasError { get; set; } public string Error { get; set; } public double Value { get; set; } } public sealed class RemoteEventTarget { public string Name { get; set; } public HashSet<string> EventNames { get; set; } } [ServiceContract( Namespace = Constants.Namespace , CallbackContract = typeof(IRemoteServiceCallback))] [ServiceKnownType(typeof(RemoteServiceResponse))] [ServiceKnownType(typeof(RemoteEventTarget))] public interface IRemoteService { [OperationContract] RemoteServiceResponse GetValue(string variableName); [OperationContract] RemoteServiceResponse SetValue(string variableName, double newValue); [OperationContract] RemoteServiceResponse EmulateEvent(string eventTarget, string eventName, string eventParameter); [OperationContract] List<RemoteEventTarget> GetEventTargets(); [OperationContract] string GetVersion(); } public interface IRemoteServiceCallback { [OperationContract(IsOneWay = true)] void RemoteEvent(string eventName); } }
Update StreamWriter tests + Explicitly iterate IEnumerable method
namespace Host.UnitTests.Serialization { using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using Crest.Host.Serialization; using FluentAssertions; using Xunit; public class MethodsTests { private readonly Methods methods = new Methods(typeof(FakeSerializerBase)); public sealed class StreamWriter : MethodsTests { private const int StreamWriterWriteMethods = 17; [Fact] public void ShouldEnumerateAllTheWriteMethods() { int count = this.methods.StreamWriter.Count(); count.Should().Be(StreamWriterWriteMethods); } [Fact] public void ShouldProvideANonGenericEnumerateMethod() { int count = ((IEnumerable)this.methods.StreamWriter) .Cast<KeyValuePair<Type, MethodInfo>>() .Count(); count.Should().Be(StreamWriterWriteMethods); } } } }
namespace Host.UnitTests.Serialization { using System.Collections; using System.Linq; using Crest.Host.Serialization; using FluentAssertions; using Xunit; public class MethodsTests { private readonly Methods methods = new Methods(typeof(FakeSerializerBase)); public sealed class StreamWriter : MethodsTests { private const int StreamWriterWriteMethods = 17; [Fact] public void ShouldEnumerateAllTheWriteMethods() { int count = this.methods.StreamWriter.Count(); count.Should().Be(StreamWriterWriteMethods); } [Fact] public void ShouldProvideANonGenericEnumerateMethod() { var enumerable = (IEnumerable)this.methods.StreamWriter; int count = 0; foreach (object x in enumerable) { count++; } count.Should().Be(StreamWriterWriteMethods); } } } }
Add more information to failed Hooks
using System; using Mono.Cecil; using Mono.Cecil.Inject; using Pathfinder.Attribute; using Pathfinder.Util; namespace Pathfinder.Internal.Patcher { internal static class Executor { internal static void Main(AssemblyDefinition gameAssembly) { // Retrieve the hook methods var hooks = typeof(PathfinderHooks); MethodDefinition method; PatchAttribute attrib; string sig; foreach (var meth in hooks.GetMethods()) { attrib = meth.GetFirstAttribute<PatchAttribute>(); if (attrib == null) continue; sig = attrib.MethodSig; if (sig == null) { Console.WriteLine($"Null method signature found, skipping {nameof(PatchAttribute)} on method."); } method = gameAssembly.MainModule.GetType(sig.Remove(sig.LastIndexOf('.')))?.GetMethod(sig.Substring(sig.LastIndexOf('.') + 1)); if(method == null) { Console.WriteLine($"Method signature '{sig}' could not be found, method hook patching failed, skipping {nameof(PatchAttribute)} on '{sig}'."); continue; } method.InjectWith( gameAssembly.MainModule.ImportReference(hooks.GetMethod(meth.Name)).Resolve(), attrib.Offset, attrib.Tag, (InjectFlags)attrib.Flags, attrib.After ? InjectDirection.After : InjectDirection.Before, attrib.LocalIds); } } } }
using System; using Mono.Cecil; using Mono.Cecil.Inject; using Pathfinder.Attribute; using Pathfinder.Util; namespace Pathfinder.Internal.Patcher { internal static class Executor { internal static void Main(AssemblyDefinition gameAssembly) { // Retrieve the hook methods var hooks = typeof(PathfinderHooks); MethodDefinition method; PatchAttribute attrib; string sig; foreach (var meth in hooks.GetMethods()) { attrib = meth.GetFirstAttribute<PatchAttribute>(); if (attrib == null) continue; sig = attrib.MethodSig; if (sig == null) { Console.WriteLine($"Null method signature found, skipping {nameof(PatchAttribute)} on method."); } method = gameAssembly.MainModule.GetType(sig.Remove(sig.LastIndexOf('.')))?.GetMethod(sig.Substring(sig.LastIndexOf('.') + 1)); if(method == null) { Console.WriteLine($"Method signature '{sig}' could not be found, method hook patching failed, skipping {nameof(PatchAttribute)} on '{sig}'."); continue; } try { method.InjectWith( gameAssembly.MainModule.ImportReference(hooks.GetMethod(meth.Name)).Resolve(), attrib.Offset, attrib.Tag, (InjectFlags) attrib.Flags, attrib.After ? InjectDirection.After : InjectDirection.Before, attrib.LocalIds); } catch (Exception ex) { throw new Exception($"Error applying patch for {sig}", ex); } } } } }
Fix json serialization when the destination type is equal to the value type (fixes net40 for boolean conversions)
using System; using Newtonsoft.Json; using System.Reflection; using System.Collections.Generic; using System.ComponentModel; namespace Eto.Serialization.Json { public class TypeConverterConverter : JsonConverter { readonly Dictionary<Type, TypeConverter> converters = new Dictionary<Type, TypeConverter>(); public override bool CanRead { get { return true; } } public override bool CanWrite { get { return false; } } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { } public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { TypeConverter converter; if (converters.TryGetValue(objectType, out converter)) { return converter.ConvertFrom(reader.Value); } return existingValue; } public override bool CanConvert(Type objectType) { if (converters.ContainsKey(objectType)) return true; var converter = TypeDescriptor.GetConverter(objectType); if (converter != null && converter.CanConvertFrom(typeof(string))) { converters.Add(objectType, converter); return true; } return false; } } }
using System; using Newtonsoft.Json; using System.Reflection; using System.Collections.Generic; using System.ComponentModel; namespace Eto.Serialization.Json { public class TypeConverterConverter : JsonConverter { readonly Dictionary<Type, TypeConverter> converters = new Dictionary<Type, TypeConverter>(); public override bool CanRead { get { return true; } } public override bool CanWrite { get { return false; } } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { } public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { TypeConverter converter; if (objectType == reader.ValueType) return reader.Value; if (converters.TryGetValue(objectType, out converter)) { return converter.ConvertFrom(reader.Value); } return existingValue; } public override bool CanConvert(Type objectType) { if (converters.ContainsKey(objectType)) return true; var converter = TypeDescriptor.GetConverter(objectType); if (converter != null && converter.CanConvertFrom(typeof(string))) { converters.Add(objectType, converter); return true; } return false; } } }
Change assembly watcher after notification changes
using Godot; using GodotTools.Internals; using static GodotTools.Internals.Globals; namespace GodotTools { public class HotReloadAssemblyWatcher : Node { private Timer watchTimer; public override void _Notification(int what) { if (what == Node.NotificationWmFocusIn) { RestartTimer(); if (Internal.IsAssembliesReloadingNeeded()) Internal.ReloadAssemblies(softReload: false); } } private void TimerTimeout() { if (Internal.IsAssembliesReloadingNeeded()) Internal.ReloadAssemblies(softReload: false); } public void RestartTimer() { watchTimer.Stop(); watchTimer.Start(); } public override void _Ready() { base._Ready(); watchTimer = new Timer { OneShot = false, WaitTime = (float)EditorDef("mono/assembly_watch_interval_sec", 0.5) }; watchTimer.Timeout += TimerTimeout; AddChild(watchTimer); watchTimer.Start(); } } }
using Godot; using GodotTools.Internals; using static GodotTools.Internals.Globals; namespace GodotTools { public class HotReloadAssemblyWatcher : Node { private Timer watchTimer; public override void _Notification(int what) { if (what == Node.NotificationWmWindowFocusIn) { RestartTimer(); if (Internal.IsAssembliesReloadingNeeded()) Internal.ReloadAssemblies(softReload: false); } } private void TimerTimeout() { if (Internal.IsAssembliesReloadingNeeded()) Internal.ReloadAssemblies(softReload: false); } public void RestartTimer() { watchTimer.Stop(); watchTimer.Start(); } public override void _Ready() { base._Ready(); watchTimer = new Timer { OneShot = false, WaitTime = (float)EditorDef("mono/assembly_watch_interval_sec", 0.5) }; watchTimer.Timeout += TimerTimeout; AddChild(watchTimer); watchTimer.Start(); } } }
Change test to map with allign with initial design and documentation
using NBi.Core.Query; using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NBi.Testing.Unit.Core.Query { [TestFixture] public class CommandBuilderTest { [Test] public void Build_TimeoutSpecified_TimeoutSet() { var builder = new CommandBuilder(); var cmd = builder.Build("Data Source=server;Initial Catalog=database;Integrated Security=SSPI", "WAITFOR DELAY '00:00:15'", null, null, 5000); Assert.That(cmd.CommandTimeout, Is.EqualTo(5)); } [Test] public void Build_TimeoutSetToZero_TimeoutSet30Seconds() { var builder = new CommandBuilder(); var cmd = builder.Build("Data Source=server;Initial Catalog=database;Integrated Security=SSPI", "WAITFOR DELAY '00:00:15'", null, null, 0); Assert.That(cmd.CommandTimeout, Is.EqualTo(30)); } [Test] public void Build_TimeoutSetTo30_TimeoutSet30Seconds() { var builder = new CommandBuilder(); var cmd = builder.Build("Data Source=server;Initial Catalog=database;Integrated Security=SSPI", "WAITFOR DELAY '00:00:15'", null, null, 30000); Assert.That(cmd.CommandTimeout, Is.EqualTo(30)); } } }
using NBi.Core.Query; using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NBi.Testing.Unit.Core.Query { [TestFixture] public class CommandBuilderTest { [Test] public void Build_TimeoutSpecified_TimeoutSet() { var builder = new CommandBuilder(); var cmd = builder.Build("Data Source=server;Initial Catalog=database;Integrated Security=SSPI", "WAITFOR DELAY '00:00:15'", null, null, 5000); Assert.That(cmd.CommandTimeout, Is.EqualTo(5)); } [Test] public void Build_TimeoutSetToZero_TimeoutSet0Seconds() { var builder = new CommandBuilder(); var cmd = builder.Build("Data Source=server;Initial Catalog=database;Integrated Security=SSPI", "WAITFOR DELAY '00:00:15'", null, null, 0); Assert.That(cmd.CommandTimeout, Is.EqualTo(0)); } [Test] public void Build_TimeoutSetTo30_TimeoutSet30Seconds() { var builder = new CommandBuilder(); var cmd = builder.Build("Data Source=server;Initial Catalog=database;Integrated Security=SSPI", "WAITFOR DELAY '00:00:15'", null, null, 30000); Assert.That(cmd.CommandTimeout, Is.EqualTo(30)); } } }
Revert "sandbox demo of shutdown cancel."
using Avalonia; using Avalonia.Controls.ApplicationLifetimes; using Avalonia.Markup.Xaml; namespace Sandbox { public class App : Application { public override void Initialize() { AvaloniaXamlLoader.Load(this); } public override void OnFrameworkInitializationCompleted() { if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktopLifetime) { desktopLifetime.MainWindow = new MainWindow(); desktopLifetime.ShutdownRequested += DesktopLifetime_ShutdownRequested; } } private void DesktopLifetime_ShutdownRequested(object sender, System.ComponentModel.CancelEventArgs e) { e.Cancel = true; } } }
using Avalonia; using Avalonia.Controls.ApplicationLifetimes; using Avalonia.Markup.Xaml; namespace Sandbox { public class App : Application { public override void Initialize() { AvaloniaXamlLoader.Load(this); } public override void OnFrameworkInitializationCompleted() { if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktopLifetime) { desktopLifetime.MainWindow = new MainWindow(); } } } }
Fix external fonts loading example (use folders to seek fonts)
using System; using Aspose.Slides.Export; using Aspose.Slides.Charts; using Aspose.Slides; /* This project uses Automatic Package Restore feature of NuGet to resolve Aspose.Slides for .NET API reference when the project is build. Please check https://docs.nuget.org/consume/nuget-faq for more information. If you do not wish to use NuGet, you can manually download Aspose.Slides for .NET API from http://www.aspose.com/downloads, install it and then add its reference to this project. For any issues, questions or suggestions please feel free to contact us using http://www.aspose.com/community/forums/default.aspx */ namespace Aspose.Slides.Examples.CSharp.Text { class UseCustomFonts { public static void Run() { //ExStart:UseCustomFonts // The path to the documents directory. string dataDir = RunExamples.GetDataDir_Text(); String[] loadFonts = new String[] { dataDir + "CustomFonts.ttf" }; // Load the custom font directory fonts FontsLoader.LoadExternalFonts(loadFonts); // Do Some work and perform presentation/slides rendering using (Presentation presentation = new Presentation(dataDir + "DefaultFonts.pptx")) presentation.Save(dataDir + "NewFonts_out.pptx", SaveFormat.Pptx); // Clear Font Cachce FontsLoader.ClearCache(); //ExEnd:UseCustomFonts } } }
using System; using Aspose.Slides.Export; using Aspose.Slides.Charts; using Aspose.Slides; /* This project uses Automatic Package Restore feature of NuGet to resolve Aspose.Slides for .NET API reference when the project is build. Please check https://docs.nuget.org/consume/nuget-faq for more information. If you do not wish to use NuGet, you can manually download Aspose.Slides for .NET API from http://www.aspose.com/downloads, install it and then add its reference to this project. For any issues, questions or suggestions please feel free to contact us using http://www.aspose.com/community/forums/default.aspx */ namespace Aspose.Slides.Examples.CSharp.Text { class UseCustomFonts { public static void Run() { //ExStart:UseCustomFonts // The path to the documents directory. string dataDir = RunExamples.GetDataDir_Text(); // folders to seek fonts String[] folders = new String[] { dataDir }; // Load the custom font directory fonts FontsLoader.LoadExternalFonts(folders); // Do Some work and perform presentation/slides rendering using (Presentation presentation = new Presentation(dataDir + "DefaultFonts.pptx")) presentation.Save(dataDir + "NewFonts_out.pptx", SaveFormat.Pptx); // Clear Font Cachce FontsLoader.ClearCache(); //ExEnd:UseCustomFonts } } }
Add new employment fields for change employer (Portable)
using System; using SFA.DAS.CommitmentsV2.Types; namespace SFA.DAS.CommitmentsV2.Api.Types.Requests { public class CreateChangeOfPartyRequestRequest : SaveDataRequest { public ChangeOfPartyRequestType ChangeOfPartyRequestType { get; set; } public long NewPartyId { get; set; } public int? NewPrice { get; set; } public DateTime? NewStartDate { get; set; } public DateTime? NewEndDate { get; set; } } }
using System; using SFA.DAS.CommitmentsV2.Types; namespace SFA.DAS.CommitmentsV2.Api.Types.Requests { public class CreateChangeOfPartyRequestRequest : SaveDataRequest { public ChangeOfPartyRequestType ChangeOfPartyRequestType { get; set; } public long NewPartyId { get; set; } public int? NewPrice { get; set; } public DateTime? NewStartDate { get; set; } public DateTime? NewEndDate { get; set; } public DateTime? NewEmploymentEndDate { get; set; } public int? NewEmploymentPrice { get; set; } } }
Change the UpdateManager's version to 2.0.1
using System; namespace UpdateManager { public class UpdateManagerUpdateable : IUpdateable { private UpdateManagerUpdateable() { } private static UpdateManagerUpdateable _Instance { get; set; } public static UpdateManagerUpdateable Instance { get { if (_Instance == null) _Instance = new UpdateManagerUpdateable(); return _Instance; } } public string UpdateName { get { return "Update Manager"; } } public string XMLURL { get { return "http://livesplit.org/update/update.updater.xml"; } } public string UpdateURL { get { return "http://livesplit.org/update/"; } } public Version Version { get { return Version.Parse("2.0"); } } } }
using System; namespace UpdateManager { public class UpdateManagerUpdateable : IUpdateable { private UpdateManagerUpdateable() { } private static UpdateManagerUpdateable _Instance { get; set; } public static UpdateManagerUpdateable Instance { get { if (_Instance == null) _Instance = new UpdateManagerUpdateable(); return _Instance; } } public string UpdateName { get { return "Update Manager"; } } public string XMLURL { get { return "http://livesplit.org/update/update.updater.xml"; } } public string UpdateURL { get { return "http://livesplit.org/update/"; } } public Version Version { get { return Version.Parse("2.0.1"); } } } }
Fix typo in test message.
using System; using System.Xml; using Arkivverket.Arkade.Core; namespace Arkivverket.Arkade.Tests.Noark5 { public class NumberOfArchives : BaseTest { public const string AnalysisKeyArchives = "Archives"; public NumberOfArchives(IArchiveContentReader archiveReader) : base(TestType.Content, archiveReader) { } protected override void Test(Archive archive) { using (var reader = XmlReader.Create(ArchiveReader.GetContentAsStream(archive))) { int counter = 0; while (reader.ReadToFollowing("arkiv")) { counter++; } AddAnalysisResult(AnalysisKeyArchives, counter.ToString()); TestSuccess($"Antall arkiver: {counter}."); } } } }
using System; using System.Xml; using Arkivverket.Arkade.Core; namespace Arkivverket.Arkade.Tests.Noark5 { public class NumberOfArchives : BaseTest { public const string AnalysisKeyArchives = "Archives"; public NumberOfArchives(IArchiveContentReader archiveReader) : base(TestType.Content, archiveReader) { } protected override void Test(Archive archive) { using (var reader = XmlReader.Create(ArchiveReader.GetContentAsStream(archive))) { int counter = 0; while (reader.ReadToFollowing("arkiv")) { counter++; } AddAnalysisResult(AnalysisKeyArchives, counter.ToString()); TestSuccess($"Antall arkiv: {counter}."); } } } }
Update CreatedOn or MmodifiedOn properties of tracked entities when saving changes.
using LanguageSchoolApp.Data.Model; using Microsoft.AspNet.Identity.EntityFramework; using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LanguageSchoolApp.Data { public class MsSqlDbContext : IdentityDbContext<User> { public MsSqlDbContext() : base("DefaultConnection", throwIfV1Schema: false) { } public IDbSet<Course> Courses { get; set; } public static MsSqlDbContext Create() { return new MsSqlDbContext(); } } }
using LanguageSchoolApp.Data.Model; using LanguageSchoolApp.Data.Model.Contracts; using Microsoft.AspNet.Identity.EntityFramework; using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LanguageSchoolApp.Data { public class MsSqlDbContext : IdentityDbContext<User> { public MsSqlDbContext() : base("DefaultConnection", throwIfV1Schema: false) { } public IDbSet<Course> Courses { get; set; } public override int SaveChanges() { this.ApplyAuditInfoRules(); return base.SaveChanges(); } private void ApplyAuditInfoRules() { foreach (var entry in this.ChangeTracker.Entries() .Where(e => e.Entity is IAuditable && ((e.State == EntityState.Added) || (e.State == EntityState.Modified)))) { var entity = (IAuditable)entry.Entity; if (entry.State == EntityState.Added && entity.CreatedOn == default(DateTime)) { entity.CreatedOn = DateTime.Now; } else { entity.ModifiedOn = DateTime.Now; } } } public static MsSqlDbContext Create() { return new MsSqlDbContext(); } } }
Revert "Removed Guid from iOS project"
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("AppShell.Mobile.iOS")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("AppShell.Mobile.iOS")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("AppShell.Mobile.iOS")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("AppShell.Mobile.iOS")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("ecceafc0-b15a-4932-99ec-36315a4e82e7")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0.0")]
Remove + cleanup warnings. Refactor pass.
using System; using System.Collections.Generic; using System.IO; using UnityEngine; namespace Engine { public class BaseEngine : BaseEngineObject { public BaseEngine() { } public virtual void Tick(float deltaTime) { } } }
using System; using System.Collections.Generic; using System.IO; using UnityEngine; namespace Engine { public class BaseEngine : BaseEngineObject { public BaseEngine() { } public virtual void Tick(float deltaTime) { } } }
Remove unnecessary call to Trim
using System; using System.Linq; using AutoMapper; namespace PicklesDoc.Pickles.ObjectModel { public class KeywordResolver : ITypeConverter<string, Keyword> { private readonly string language; public KeywordResolver(string language) { this.language = language; } public Keyword Convert(ResolutionContext context) { string source = (string) context.SourceValue; return this.MapToKeyword(source); } private Keyword MapToKeyword(string keyword) { keyword = keyword.Trim(); var gherkinDialect = new LanguageServices(new Configuration() { Language = this.language }); if (gherkinDialect.WhenStepKeywords.Select(s => s.Trim()).Contains(keyword)) { return Keyword.When; } if (gherkinDialect.GivenStepKeywords.Select(s => s.Trim()).Contains(keyword)) { return Keyword.Given; } if (gherkinDialect.ThenStepKeywords.Select(s => s.Trim()).Contains(keyword)) { return Keyword.Then; } if (gherkinDialect.AndStepKeywords.Select(s => s.Trim()).Contains(keyword)) { return Keyword.And; } if (gherkinDialect.ButStepKeywords.Select(s => s.Trim()).Contains(keyword)) { return Keyword.But; } throw new ArgumentOutOfRangeException("keyword"); } } }
using System; using System.Linq; using AutoMapper; namespace PicklesDoc.Pickles.ObjectModel { public class KeywordResolver : ITypeConverter<string, Keyword> { private readonly string language; public KeywordResolver(string language) { this.language = language; } public Keyword Convert(ResolutionContext context) { string source = (string) context.SourceValue; return this.MapToKeyword(source); } private Keyword MapToKeyword(string keyword) { keyword = keyword.Trim(); var gherkinDialect = new LanguageServices(new Configuration() { Language = this.language }); if (gherkinDialect.WhenStepKeywords.Contains(keyword)) { return Keyword.When; } if (gherkinDialect.GivenStepKeywords.Contains(keyword)) { return Keyword.Given; } if (gherkinDialect.ThenStepKeywords.Select(s => s.Trim()).Contains(keyword)) { return Keyword.Then; } if (gherkinDialect.AndStepKeywords.Select(s => s.Trim()).Contains(keyword)) { return Keyword.And; } if (gherkinDialect.ButStepKeywords.Select(s => s.Trim()).Contains(keyword)) { return Keyword.But; } throw new ArgumentOutOfRangeException("keyword"); } } }
Remove the 'IgnoreHidden' parameter from ITorrentFileSource
using System; using System.Collections.Generic; using System.Text; namespace MonoTorrent.Common { public interface ITorrentFileSource { IEnumerable<FileMapping> Files { get; } bool IgnoreHidden { get; } string TorrentName { get; } } }
using System; using System.Collections.Generic; using System.Text; namespace MonoTorrent.Common { public interface ITorrentFileSource { IEnumerable<FileMapping> Files { get; } string TorrentName { get; } } }
Update server side API for single multiple answer question
using System.Collections.Generic; using Promact.Trappist.DomainModel.Models.Question; using System.Linq; using Promact.Trappist.DomainModel.DbContext; namespace Promact.Trappist.Repository.Questions { public class QuestionRepository : IQuestionRepository { private readonly TrappistDbContext _dbContext; public QuestionRepository(TrappistDbContext dbContext) { _dbContext = dbContext; } /// <summary> /// Get all questions /// </summary> /// <returns>Question list</returns> public List<SingleMultipleAnswerQuestion> GetAllQuestions() { var questions = _dbContext.SingleMultipleAnswerQuestion.ToList(); return questions; } /// <summary> /// Add single multiple answer question into SingleMultipleAnswerQuestion model /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <param name="singleMultipleAnswerQuestionOption"></param> public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption) { _dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion); _dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOption); _dbContext.SaveChanges(); } } }
using System.Collections.Generic; using Promact.Trappist.DomainModel.Models.Question; using System.Linq; using Promact.Trappist.DomainModel.DbContext; namespace Promact.Trappist.Repository.Questions { public class QuestionRepository : IQuestionRepository { private readonly TrappistDbContext _dbContext; public QuestionRepository(TrappistDbContext dbContext) { _dbContext = dbContext; } /// <summary> /// Get all questions /// </summary> /// <returns>Question list</returns> public List<SingleMultipleAnswerQuestion> GetAllQuestions() { var questions = _dbContext.SingleMultipleAnswerQuestion.ToList(); return questions; } /// <summary> /// Add single multiple answer question into SingleMultipleAnswerQuestion model /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <param name="singleMultipleAnswerQuestionOption"></param> public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption) { _dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion); _dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOption); _dbContext.SaveChanges(); } } }
Make TabControl test label more clear
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System.Diagnostics; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Primitives; using osu.Framework.Screens.Testing; using osu.Game.Graphics.Sprites; using osu.Game.Screens.Select.Filter; using osu.Game.Graphics.UserInterface; namespace osu.Desktop.VisualTests.Tests { public class TestCaseTabControl : TestCase { public override string Description => @"Filter for song select"; public override void Reset() { base.Reset(); OsuSpriteText text; OsuTabControl<GroupMode> filter; Add(new FillFlowContainer { Direction = FillDirection.Horizontal, AutoSizeAxes = Axes.Both, Children = new Drawable[] { filter = new OsuTabControl<GroupMode> { Width = 229, AutoSort = true }, text = new OsuSpriteText { Text = "None", Margin = new MarginPadding(4) } } }); filter.PinTab(GroupMode.All); filter.PinTab(GroupMode.RecentlyPlayed); filter.ValueChanged += (sender, mode) => { Debug.WriteLine($"Selected {mode}"); text.Text = mode.ToString(); }; } } }
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using OpenTK; using osu.Framework.Graphics.Primitives; using osu.Framework.Screens.Testing; using osu.Game.Graphics.Sprites; using osu.Game.Graphics.UserInterface; using osu.Game.Screens.Select.Filter; namespace osu.Desktop.VisualTests.Tests { public class TestCaseTabControl : TestCase { public override string Description => @"Filter for song select"; public override void Reset() { base.Reset(); OsuSpriteText text; OsuTabControl<GroupMode> filter; Add(filter = new OsuTabControl<GroupMode> { Width = 229, AutoSort = true }); Add(text = new OsuSpriteText { Text = "None", Margin = new MarginPadding(4), Position = new Vector2(275, 5) }); filter.PinTab(GroupMode.All); filter.PinTab(GroupMode.RecentlyPlayed); filter.ValueChanged += (sender, mode) => { text.Text = "Currently Selected: " + mode.ToString(); }; } } }
Add artificial wait to fix tests
using System; using System.Net.Http; using System.Threading.Tasks; using GlobalExceptionHandler.Tests.WebApi.Fixtures; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.TestHost; using Shouldly; using Xunit; namespace GlobalExceptionHandler.Tests.WebApi.LoggerTests { public class LogExceptionTests : IClassFixture<WebApiServerFixture> { private Exception _exception; private HttpContext _context; public LogExceptionTests(WebApiServerFixture fixture) { // Arrange const string requestUri = "/api/productnotfound"; var webHost = fixture.CreateWebHost(); webHost.Configure(app => { app.UseWebApiGlobalExceptionHandler(x => { x.OnError((ex, context) => { Console.WriteLine("Log error"); _exception = ex; _context = context; return Task.CompletedTask; }); }); app.Map(requestUri, config => { config.Run(context => throw new ArgumentException("Invalid request")); }); }); // Act var server = new TestServer(webHost); using (var client = server.CreateClient()) { var requestMessage = new HttpRequestMessage(new HttpMethod("GET"), requestUri); client.SendAsync(requestMessage).Wait(); Task.Delay(TimeSpan.FromSeconds(3)); } } [Fact] public void Invoke_logger() { _exception.ShouldBeOfType<ArgumentException>(); } [Fact] public void Context_is_set() { _context.ShouldBeOfType<DefaultHttpContext>(); } } }
using System; using System.Net.Http; using System.Threading.Tasks; using GlobalExceptionHandler.Tests.WebApi.Fixtures; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.TestHost; using Shouldly; using Xunit; namespace GlobalExceptionHandler.Tests.WebApi.LoggerTests { public class LogExceptionTests : IClassFixture<WebApiServerFixture> { private Exception _exception; private HttpContext _context; public LogExceptionTests(WebApiServerFixture fixture) { // Arrange const string requestUri = "/api/productnotfound"; var webHost = fixture.CreateWebHost(); webHost.Configure(app => { app.UseWebApiGlobalExceptionHandler(x => { x.OnError((ex, context) => { _exception = ex; _context = context; return Task.CompletedTask; }); }); app.Map(requestUri, config => { config.Run(context => throw new ArgumentException("Invalid request")); }); }); // Act var server = new TestServer(webHost); using (var client = server.CreateClient()) { var requestMessage = new HttpRequestMessage(new HttpMethod("GET"), requestUri); client.SendAsync(requestMessage).Wait(); Task.Delay(1000); } } [Fact] public void Invoke_logger() { _exception.ShouldBeOfType<ArgumentException>(); } [Fact] public void Context_is_set() { _context.ShouldBeOfType<DefaultHttpContext>(); } } }
Increase logging to Verbose for examples
using System; using System.Linq; namespace CefSharp.Example { public static class CefExample { public const string DefaultUrl = "custom://cefsharp/home"; // Use when debugging the actual SubProcess, to make breakpoints etc. inside that project work. private const bool debuggingSubProcess = false; public static void Init() { var settings = new CefSettings(); settings.RemoteDebuggingPort = 8088; if (debuggingSubProcess) { settings.BrowserSubprocessPath = "..\\..\\..\\..\\CefSharp.BrowserSubprocess\\bin\\x86\\Debug\\CefSharp.BrowserSubprocess.exe"; } settings.RegisterScheme(new CefCustomScheme { SchemeName = CefSharpSchemeHandlerFactory.SchemeName, SchemeHandlerFactory = new CefSharpSchemeHandlerFactory() }); if (!Cef.Initialize(settings)) { if (Environment.GetCommandLineArgs().Contains("--type=renderer")) { Environment.Exit(0); } else { return; } } Cef.RegisterJsObject("bound", new BoundObject()); } } }
using System; using System.Linq; namespace CefSharp.Example { public static class CefExample { public const string DefaultUrl = "custom://cefsharp/home"; // Use when debugging the actual SubProcess, to make breakpoints etc. inside that project work. private const bool debuggingSubProcess = false; public static void Init() { var settings = new CefSettings(); settings.RemoteDebuggingPort = 8088; settings.LogSeverity = LogSeverity.Verbose; if (debuggingSubProcess) { settings.BrowserSubprocessPath = "..\\..\\..\\..\\CefSharp.BrowserSubprocess\\bin\\x86\\Debug\\CefSharp.BrowserSubprocess.exe"; } settings.RegisterScheme(new CefCustomScheme { SchemeName = CefSharpSchemeHandlerFactory.SchemeName, SchemeHandlerFactory = new CefSharpSchemeHandlerFactory() }); if (!Cef.Initialize(settings)) { if (Environment.GetCommandLineArgs().Contains("--type=renderer")) { Environment.Exit(0); } else { return; } } Cef.RegisterJsObject("bound", new BoundObject()); } } }
Rewrite markup for password reminder form
@model ForgotPasswordViewModel @{ ViewData["Title"] = "Forgot your password?"; } <h2>@ViewData["Title"].</h2> <p> For more information on how to enable reset password please see this <a href="http://go.microsoft.com/fwlink/?LinkID=532713">article</a>. </p> @*<form asp-controller="Account" asp-action="ForgotPassword" method="post" role="form"> <h4>Enter your email.</h4> <hr /> <div asp-validation-summary="ValidationSummary.All" class="text-danger"></div> <div class="form-group"> <label asp-for="Email" class="col-md-2 control-label"></label> <div class="col-md-10"> <input asp-for="Email" class="form-control" /> <span asp-validation-for="Email" class="text-danger"></span> </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <button type="submit" class="btn btn-default">Submit</button> </div> </div> </form>*@ @section Scripts { @{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); } }
@model ForgotPasswordViewModel @{ ViewData["Title"] = "Forgot your password?"; } <h2>@ViewData["Title"].</h2> <p> For more information on how to enable reset password please see this <a href="http://go.microsoft.com/fwlink/?LinkID=532713">article</a>. </p> @* <form asp-controller="Account" asp-action="ForgotPassword" method="post" role="form"> <h4>Enter your email.</h4> <hr /> <div asp-validation-summary="ValidationSummary.All" class="text-danger"></div> <fieldset> <div class="form-group row"> <label asp-for="Email" class="col-md-2 control-label"></label> <div class="col-md-10"> <input asp-for="Email" class="form-control" /> <span asp-validation-for="Email" class="text-danger"></span> </div> </div> <div class="form-group row"> <div class="col-md-offset-2 col-md-10"> <button type="submit" class="btn btn-primary">Submit</button> </div> </div> </fieldset> </form> *@ @section Scripts { @{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); } }
Add a and x ions
using System.Collections.Generic; namespace EngineLayer { static class ProductTypeToTerminusType { public static TerminusType IdentifyTerminusType(List<ProductType> lp) { if ((lp.Contains(ProductType.B) || lp.Contains(ProductType.BnoB1ions) || lp.Contains(ProductType.C)) && (lp.Contains(ProductType.Y) || lp.Contains(ProductType.Zdot))) { return TerminusType.None; } else if (lp.Contains(ProductType.Y) || lp.Contains(ProductType.Zdot)) { return TerminusType.C; } else //if(lp.Contains(ProductType.B) || lp.Contains(ProductType.BnoB1ions) || lp.Contains(ProductType.C)) { return TerminusType.N; } } } }
using System.Collections.Generic; namespace EngineLayer { static class ProductTypeToTerminusType { public static TerminusType IdentifyTerminusType(List<ProductType> lp) { if ((lp.Contains(ProductType.B) || lp.Contains(ProductType.BnoB1ions) || lp.Contains(ProductType.C) || lp.Contains(ProductType.Adot)) && (lp.Contains(ProductType.Y) || lp.Contains(ProductType.Zdot) || lp.Contains(ProductType.X))) { return TerminusType.None; } else if (lp.Contains(ProductType.Y) || lp.Contains(ProductType.Zdot) || lp.Contains(ProductType.X)) { return TerminusType.C; } else //if(lp.Contains(ProductType.B) || lp.Contains(ProductType.BnoB1ions) || lp.Contains(ProductType.C) || lp.Contains(ProductType.Adot)) { return TerminusType.N; } } } }
Remove unneeded setting of SqlParameter.Offset
namespace NServiceBus { using System; using System.Data.Common; using System.Data.SqlClient; public abstract partial class SqlDialect { /// <summary> /// Microsoft SQL Server /// </summary> public partial class MsSqlServer : SqlDialect { /// <summary> /// Microsoft SQL Server /// </summary> public MsSqlServer() { Schema = "dbo"; } internal override void AddCreationScriptParameters(DbCommand command) { command.AddParameter("schema", Schema); } internal override void SetJsonParameterValue(DbParameter parameter, object value) { SetParameterValue(parameter, value); } internal override void SetParameterValue(DbParameter parameter, object value) { //TODO: do ArraySegment fro outbox if (value is ArraySegment<char> charSegment) { var sqlParameter = (SqlParameter)parameter; sqlParameter.Value = charSegment.Array; sqlParameter.Offset = charSegment.Offset; sqlParameter.Size = charSegment.Count; } else { parameter.Value = value; } } internal override CommandWrapper CreateCommand(DbConnection connection) { var command = connection.CreateCommand(); return new CommandWrapper(command, this); } internal override object GetCustomDialectDiagnosticsInfo() { return new { CustomSchema = string.IsNullOrEmpty(Schema), DoNotUseTransportConnection }; } internal string Schema { get; set; } } } }
namespace NServiceBus { using System; using System.Data.Common; public abstract partial class SqlDialect { /// <summary> /// Microsoft SQL Server /// </summary> public partial class MsSqlServer : SqlDialect { /// <summary> /// Microsoft SQL Server /// </summary> public MsSqlServer() { Schema = "dbo"; } internal override void AddCreationScriptParameters(DbCommand command) { command.AddParameter("schema", Schema); } internal override void SetJsonParameterValue(DbParameter parameter, object value) { SetParameterValue(parameter, value); } internal override void SetParameterValue(DbParameter parameter, object value) { if (value is ArraySegment<char> charSegment) { parameter.Value = charSegment.Array; parameter.Size = charSegment.Count; } else { parameter.Value = value; } } internal override CommandWrapper CreateCommand(DbConnection connection) { var command = connection.CreateCommand(); return new CommandWrapper(command, this); } internal override object GetCustomDialectDiagnosticsInfo() { return new { CustomSchema = string.IsNullOrEmpty(Schema), DoNotUseTransportConnection }; } internal string Schema { get; set; } } } }
Use Enum.Parse overload available in PCL
using System; namespace EvilDICOM.Core.Helpers { public class EnumHelper { public static T StringToEnum<T>(string name) { return (T) Enum.Parse(typeof (T), name); } } }
using System; namespace EvilDICOM.Core.Helpers { public class EnumHelper { public static T StringToEnum<T>(string name) { return (T) Enum.Parse(typeof (T), name, false); } } }
Add [Authorize] to ExecuteCommand action
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using WhitelistExecuter.Lib; using WhitelistExecuter.Web.Models; namespace WhitelistExecuter.Web.Controllers { public class HomeController : Controller { public ActionResult Index() { ViewBag.Message = "Whitelist Executer."; return View(new HomeModel()); } [HttpPost] public ActionResult ExecuteCommand(HomeModel model) { model.Error = null; using (var client = new WhitelistExecuterClient()) { ExecutionResult result; try { result = client.API.ExecuteCommand(model.Command, model.RelativePath); } catch (Exception e) { model.Error = (e.InnerException ?? e).Message; return View("Index", model); } //.....ViewBag.ViewBag.mo model.StandardOutput = result.StandardOutput; model.StandardError = result.StandardError; } return View("Index", model); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using WhitelistExecuter.Lib; using WhitelistExecuter.Web.Filters; using WhitelistExecuter.Web.Models; namespace WhitelistExecuter.Web.Controllers { public class HomeController : Controller { public ActionResult Index() { ViewBag.Message = "Whitelist Executer."; return View(new HomeModel()); } [Authorize] [HttpPost] public ActionResult ExecuteCommand(HomeModel model) { model.Error = null; using (var client = new WhitelistExecuterClient()) { ExecutionResult result; try { result = client.API.ExecuteCommand(model.Command, model.RelativePath); } catch (Exception e) { model.Error = (e.InnerException ?? e).Message; return View("Index", model); } //.....ViewBag.ViewBag.mo model.StandardOutput = result.StandardOutput; model.StandardError = result.StandardError; } return View("Index", model); } } }
Fix for a crash that can occur while exporting from the level editor - falling back to the global scene manager if we can't find a scene manager attached to the dom node tree
// Copyright 2015 XLGAMES Inc. // // Distributed under the MIT License (See // accompanying file "LICENSE" or the website // http://www.opensource.org/licenses/mit-license.php) using System; using Sce.Atf.Adaptation; namespace LevelEditorXLE.Extensions { internal static class ExtensionsClass { internal static GUILayer.EditorSceneManager GetSceneManager(this Sce.Atf.Dom.DomNodeAdapter adapter) { var root = adapter.DomNode.GetRoot(); System.Diagnostics.Debug.Assert(root != null); if (root == null) return null; var gameExt = root.As<Game.GameExtensions>(); System.Diagnostics.Debug.Assert(gameExt != null); if (gameExt == null) return null; return gameExt.SceneManager; } } }
// Copyright 2015 XLGAMES Inc. // // Distributed under the MIT License (See // accompanying file "LICENSE" or the website // http://www.opensource.org/licenses/mit-license.php) using System; using Sce.Atf.Adaptation; namespace LevelEditorXLE.Extensions { internal static class ExtensionsClass { internal static GUILayer.EditorSceneManager GetSceneManager(this Sce.Atf.Dom.DomNodeAdapter adapter) { // Prefer to return the SceneManager object associated // with the root game document. If we can't find one, fall // back to the GlobalSceneManager var root = adapter.DomNode.GetRoot(); if (root != null) { var gameExt = root.As<Game.GameExtensions>(); if (gameExt != null) { var man = gameExt.SceneManager; if (man != null) return man; } } return XLEBridgeUtils.Utils.GlobalSceneManager; } } }
Add integration tests for links and forms
using NUnit.Framework; using System.IO; namespace CertiPay.PDF.Tests { public class PDFServiceTests { [Test] public void ShouldGenerateMultiPagePDF() { IPDFService svc = new PDFService(); byte[] output = svc.CreatePdf(new PDFService.Settings { Uris = new[] { @"http://google.com", @"http://github.com" } }); File.WriteAllBytes("Output.pdf", output); } [Test] public void Should_Generate_Landscape_PDF() { IPDFService svc = new PDFService { }; byte[] output = svc.CreatePdf(new PDFService.Settings { Uris = new[] { "http://google.com" }, UseLandscapeOrientation = true }); File.WriteAllBytes("Output-Landscape.pdf", output); } } }
using NUnit.Framework; using System.IO; namespace CertiPay.PDF.Tests { public class PDFServiceTests { [Test] public void ShouldGenerateMultiPagePDF() { IPDFService svc = new PDFService(); byte[] output = svc.CreatePdf(new PDFService.Settings { Uris = new[] { @"http://google.com", @"http://github.com" } }); File.WriteAllBytes("Output.pdf", output); } [Test] public void Should_Generate_Landscape_PDF() { IPDFService svc = new PDFService { }; byte[] output = svc.CreatePdf(new PDFService.Settings { Uris = new[] { "http://google.com" }, UseLandscapeOrientation = true }); File.WriteAllBytes("Output-Landscape.pdf", output); } [Test] public void Should_Generate_Live_Form_PDF() { IPDFService svc = new PDFService { }; byte[] output = svc.CreatePdf(new PDFService.Settings { Uris = new[] { "http://google.com" }, UseForms = true }); File.WriteAllBytes("Output-Form.pdf", output); } [Test] public void Should_Generate_Live_Links_PDF() { IPDFService svc = new PDFService { }; byte[] output = svc.CreatePdf(new PDFService.Settings { Uris = new[] { "http://google.com" }, UseLinks = true }); File.WriteAllBytes("Output-Links.pdf", output); } } }
Use NonGeneric entry point for MessagePack-CSharp serializer
using System.IO; using MessagePack; using MessagePack.Resolvers; namespace Obvs.Serialization.MessagePack { public class MessagePackCSharpMessageSerializer : IMessageSerializer { private readonly IFormatterResolver _resolver; public MessagePackCSharpMessageSerializer() : this(null) { } public MessagePackCSharpMessageSerializer(IFormatterResolver resolver) { _resolver = resolver ?? StandardResolver.Instance; } public void Serialize(Stream destination, object message) { MessagePackSerializer.Serialize(destination, message, _resolver); } } }
using System.IO; using MessagePack; using MessagePack.Resolvers; namespace Obvs.Serialization.MessagePack { public class MessagePackCSharpMessageSerializer : IMessageSerializer { private readonly IFormatterResolver _resolver; public MessagePackCSharpMessageSerializer() : this(null) { } public MessagePackCSharpMessageSerializer(IFormatterResolver resolver) { _resolver = resolver ?? StandardResolver.Instance; } public void Serialize(Stream destination, object message) { MessagePackSerializer.NonGeneric.Serialize(message.GetType(), destination, message, _resolver); } } }
Fix legacy decoder using wrong configuration
// 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.Game.Beatmaps.Formats; namespace osu.Game.Skinning { public class LegacySkinDecoder : LegacyDecoder<SkinConfiguration> { public LegacySkinDecoder() : base(1) { } protected override void ParseLine(SkinConfiguration skin, Section section, string line) { line = StripComments(line); var pair = SplitKeyVal(line); switch (section) { case Section.General: switch (pair.Key) { case @"Name": skin.SkinInfo.Name = pair.Value; break; case @"Author": skin.SkinInfo.Creator = pair.Value; break; case @"CursorExpand": skin.CursorExpand = pair.Value != "0"; break; case @"SliderBorderSize": skin.SliderBorderSize = Parsing.ParseFloat(pair.Value); break; } break; case Section.Fonts: switch (pair.Key) { case "HitCirclePrefix": skin.HitCircleFont = pair.Value; break; case "HitCircleOverlap": skin.HitCircleOverlap = int.Parse(pair.Value); break; } break; } base.ParseLine(skin, section, line); } } }
// 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.Game.Beatmaps.Formats; namespace osu.Game.Skinning { public class LegacySkinDecoder : LegacyDecoder<DefaultSkinConfiguration> { public LegacySkinDecoder() : base(1) { } protected override void ParseLine(DefaultSkinConfiguration skin, Section section, string line) { line = StripComments(line); var pair = SplitKeyVal(line); switch (section) { case Section.General: switch (pair.Key) { case @"Name": skin.SkinInfo.Name = pair.Value; break; case @"Author": skin.SkinInfo.Creator = pair.Value; break; case @"CursorExpand": skin.CursorExpand = pair.Value != "0"; break; case @"SliderBorderSize": skin.SliderBorderSize = Parsing.ParseFloat(pair.Value); break; } break; case Section.Fonts: switch (pair.Key) { case "HitCirclePrefix": skin.HitCircleFont = pair.Value; break; case "HitCircleOverlap": skin.HitCircleOverlap = int.Parse(pair.Value); break; } break; } base.ParseLine(skin, section, line); } } }
Convert EncryptedString to String explicitly
using System; using System.IO; using LastPass; namespace Example { class Program { static void Main(string[] args) { // Read LastPass credentials from a file // The file should contain 2 lines: username and password. // See credentials.txt.example for an example. var credentials = File.ReadAllLines("../../credentials.txt"); var username = credentials[0]; var password = credentials[1]; // Fetch and create the vault from LastPass var vault = Vault.Create(username, password); // Decrypt all accounts vault.DecryptAllAccounts(Account.Field.Name | Account.Field.Username | Account.Field.Password | Account.Field.Group, username, password); // Dump all the accounts for (var i = 0; i < vault.Accounts.Length; ++i) { var account = vault.Accounts[i]; Console.WriteLine("{0}: {1} {2} {3} {4} {5} {6}", i + 1, account.Id, account.Name, account.Username, account.Password, account.Url, account.Group); } } } }
using System; using System.IO; using LastPass; namespace Example { class Program { static void Main(string[] args) { // Read LastPass credentials from a file // The file should contain 2 lines: username and password. // See credentials.txt.example for an example. var credentials = File.ReadAllLines("../../credentials.txt"); var username = credentials[0]; var password = credentials[1]; // Fetch and create the vault from LastPass var vault = Vault.Create(username, password); // Decrypt all accounts vault.DecryptAllAccounts(Account.Field.Name | Account.Field.Username | Account.Field.Password | Account.Field.Group, username, password); // Dump all the accounts for (var i = 0; i < vault.Accounts.Length; ++i) { var account = vault.Accounts[i]; // Need explicit converstion to string. // String.Format doesn't do that for EncryptedString. Console.WriteLine("{0}: {1} {2} {3} {4} {5} {6}", i + 1, account.Id, (string)account.Name, (string)account.Username, (string)account.Password, account.Url, (string)account.Group); } } } }
Change starting search from 1 billion because none before
using System; using FonctionsUtiles.Fred.Csharp; namespace ConsoleAppPrimesByHundred { internal class Program { private static void Main() { Action<string> display = Console.WriteLine; display("Prime numbers by hundred:"); foreach (var kvp in FunctionsPrimes.NumberOfPrimesByHundred(1000)) { display($"{kvp.Key} - {kvp.Value}"); } display(string.Empty); display("Prime numbers by thousand:"); display(string.Empty); foreach (var kvp in FunctionsPrimes.NumberOfPrimesByNthHundred(9000, 1000)) { display($"{kvp.Key} - {kvp.Value}"); } int count = 0; for (int i = 3; i <= int.MaxValue - 4; i += 2) { if (FunctionsPrimes.IsPrimeTriplet(i)) { count++; } display($"Number of prime found: {count} and i: {i}"); } display("Press any key to exit"); Console.ReadKey(); } } }
using System; using FonctionsUtiles.Fred.Csharp; namespace ConsoleAppPrimesByHundred { internal class Program { private static void Main() { Action<string> display = Console.WriteLine; display("Prime numbers by hundred:"); foreach (var kvp in FunctionsPrimes.NumberOfPrimesByHundred(1000)) { display($"{kvp.Key} - {kvp.Value}"); } display(string.Empty); display("Prime numbers by thousand:"); display(string.Empty); foreach (var kvp in FunctionsPrimes.NumberOfPrimesByNthHundred(9000, 1000)) { display($"{kvp.Key} - {kvp.Value}"); } int count = 0; for (int i = 1000000001; i <= int.MaxValue - 4; i += 2) { if (FunctionsPrimes.IsPrimeTriplet(i)) { count++; } display($"Number of prime found: {count} and i: {i}"); } display("Press any key to exit"); Console.ReadKey(); } } }
Fix user name detection for some regions
// Copyright (c) Gothos // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Tera.Game.Messages { public class LoginServerMessage : ParsedMessage { public EntityId Id { get; private set; } public uint PlayerId { get; private set; } public string Name { get; private set; } public string GuildName { get; private set; } public PlayerClass Class { get { return RaceGenderClass.Class; } } public RaceGenderClass RaceGenderClass { get; private set; } internal LoginServerMessage(TeraMessageReader reader) : base(reader) { reader.Skip(10); RaceGenderClass = new RaceGenderClass(reader.ReadInt32()); Id = reader.ReadEntityId(); reader.Skip(4); PlayerId = reader.ReadUInt32(); reader.Skip(260); Name = reader.ReadTeraString(); } } }
// Copyright (c) Gothos // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Tera.Game.Messages { public class LoginServerMessage : ParsedMessage { public EntityId Id { get; private set; } public uint PlayerId { get; private set; } public string Name { get; private set; } public string GuildName { get; private set; } public PlayerClass Class { get { return RaceGenderClass.Class; } } public RaceGenderClass RaceGenderClass { get; private set; } internal LoginServerMessage(TeraMessageReader reader) : base(reader) { reader.Skip(10); RaceGenderClass = new RaceGenderClass(reader.ReadInt32()); Id = reader.ReadEntityId(); reader.Skip(4); PlayerId = reader.ReadUInt32(); //reader.Skip(260); //This network message doesn't have a fixed size between different region reader.Skip(220); var nameFirstBit = false; while (true) { var b = reader.ReadByte(); if (b == 0x80) { nameFirstBit = true; continue; } if (b == 0x3F && nameFirstBit) { break; } nameFirstBit = false; } reader.Skip(9); Name = reader.ReadTeraString(); } } }
Fix event action "Select Widget" cancel still applying
using System.Windows; using DesktopWidgets.Actions; using DesktopWidgets.Classes; using DesktopWidgets.Events; using DesktopWidgets.Helpers; namespace DesktopWidgets.Windows { /// <summary> /// Interaction logic for EventActionPairEditor.xaml /// </summary> public partial class EventActionPairEditor : Window { public EventActionPairEditor(EventActionPair pair) { InitializeComponent(); EventActionPair = pair; DataContext = this; } public EventActionPair EventActionPair { get; set; } private void btnOK_OnClick(object sender, RoutedEventArgs e) { DialogResult = true; } private void btnSelectWidgetForEvent_OnClick(object sender, RoutedEventArgs e) { ((WidgetEventBase) EventActionPair.Event).WidgetId = WidgetHelper.ChooseWidget(); } private void btnSelectWidgetForAction_OnClick(object sender, RoutedEventArgs e) { ((WidgetActionBase) EventActionPair.Action).WidgetId = WidgetHelper.ChooseWidget(); } } }
using System.Windows; using DesktopWidgets.Actions; using DesktopWidgets.Classes; using DesktopWidgets.Events; using DesktopWidgets.Helpers; namespace DesktopWidgets.Windows { /// <summary> /// Interaction logic for EventActionPairEditor.xaml /// </summary> public partial class EventActionPairEditor : Window { public EventActionPairEditor(EventActionPair pair) { InitializeComponent(); EventActionPair = pair; DataContext = this; } public EventActionPair EventActionPair { get; set; } private void btnOK_OnClick(object sender, RoutedEventArgs e) { DialogResult = true; } private void btnSelectWidgetForEvent_OnClick(object sender, RoutedEventArgs e) { var chosenWidget = WidgetHelper.ChooseWidget(); if (chosenWidget != null) ((WidgetEventBase) EventActionPair.Event).WidgetId = chosenWidget; } private void btnSelectWidgetForAction_OnClick(object sender, RoutedEventArgs e) { var chosenWidget = WidgetHelper.ChooseWidget(); if (chosenWidget != null) ((WidgetActionBase) EventActionPair.Action).WidgetId = chosenWidget; } } }
Change the SendReceiveAsync() implementation to support commands that do not have responses
using PluginContracts; using System; using System.Threading.Tasks; using System.Net; using System.Net.Sockets; using System.Text; using System.IO; namespace LAN { public class LANInterface : IPluginV1 { public string Name { get; } = "LAN"; public string Description { get; } = "LAN communication interface for oscilloscopes such as Rigol DS1054Z"; public IPEndPoint IPEndPoint { get; set; } public async Task<byte[]> SendReceiveAsync(string command) { using (var socket = new Socket(IPEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) { socket.Connect(IPEndPoint); // Start with the initial size of the socket receive buffer using (var ms = new MemoryStream(socket.ReceiveBufferSize)) { socket.Send(Encoding.ASCII.GetBytes(command + "\n")); var data = new byte[1024]; int received = 0; do { // Receive will block if no data available received = socket.Receive(data, data.Length, 0); // Zero bytes received means that socket has been closed by the remote host if (received != 0) { await ms.WriteAsync(data, 0, received); } // Read until terminator '\n' (0x0A) found from buffer } while (received != 0 && data[received - 1] != 0x0A); return ms.ToArray(); } } } } }
using PluginContracts; using System; using System.IO; using System.Net; using System.Net.Sockets; using System.Threading.Tasks; namespace LAN { public class LANInterface : IPluginV1 { public string Name { get; } = "LAN"; public string Description { get; } = "LAN communication interface for oscilloscopes such as Rigol DS1054Z"; public IPEndPoint IPEndPoint { get; set; } public int ReadTimeout { get; set; } = 500; public async Task<byte[]> SendReceiveAsync(string command) { using (var client = new TcpClient()) { await client.ConnectAsync(IPEndPoint.Address, IPEndPoint.Port); using (var stream = client.GetStream()) { stream.ReadTimeout = ReadTimeout; var writer = new BinaryWriter(stream); writer.Write(command + "\n"); writer.Flush(); using (var ms = new MemoryStream()) { try { var reader = new BinaryReader(stream); do { var value = reader.ReadByte(); ms.WriteByte(value); if (client.Available != 0) { var values = reader.ReadBytes(client.Available); ms.Write(values, 0, values.Length); } } while (true); } catch (Exception ex) when (ex.InnerException.GetType() == typeof(SocketException)) { // ReadByte() method will eventually timeout ... } return ms.ToArray(); } } } } } }
Edit accounts of 'all' page.
@Html.Partial("_AccountTypeLinks") <h2>All Accounts</h2> <table id="accountsTable" class="table table-bordered table-hover"> <thead> <tr> <th>Name</th> <th>Type</th> <th>Balance</th> </tr> </thead> </table> @section scripts { <script> $(document).ready(function() { $('#accountsTable').DataTable({ ajax: { url: '/api/Core/Account', dataSrc: '' }, columns: [ { data: 'Name' }, { data: 'AccountType.Name' }, { data: 'Balance' } ] }); }); </script> }
@Html.Partial("_AccountTypeLinks") <h2>All Accounts</h2> <table id="accountsTable" class="table table-bordered table-hover"> <thead> <tr> <th>Name</th> <th>Type</th> <th>Balance</th> </tr> </thead> </table> @section scripts { <script> $(document).ready(function() { $('#accountsTable').DataTable({ ajax: { url: '/api/Core/Account', dataSrc: '' }, columns: [ { data: 'Name', render: function (data, type, account) { return "<a href='/Core/Account/Edit/" + account.Id + "'>" + data + "</a>"; } }, { data: 'AccountType.Name' }, { data: 'Balance' } ] }); }); </script> }
Fix toolbox expand being interrupted by gaps between groups
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Linq; using osu.Framework.Graphics; using osu.Framework.Input.Events; using osu.Game.Graphics.Containers; using osuTK; namespace osu.Game.Rulesets.Edit { public class ExpandingToolboxContainer : ExpandingContainer { protected override double HoverExpansionDelay => 250; public ExpandingToolboxContainer(float contractedWidth, float expandedWidth) : base(contractedWidth, expandedWidth) { RelativeSizeAxes = Axes.Y; FillFlow.Spacing = new Vector2(10); } protected override bool ReceivePositionalInputAtSubTree(Vector2 screenSpacePos) => base.ReceivePositionalInputAtSubTree(screenSpacePos) && anyToolboxHovered(screenSpacePos); public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => base.ReceivePositionalInputAt(screenSpacePos) && anyToolboxHovered(screenSpacePos); private bool anyToolboxHovered(Vector2 screenSpacePos) => FillFlow.Children.Any(d => d.ScreenSpaceDrawQuad.Contains(screenSpacePos)); protected override bool OnMouseDown(MouseDownEvent e) => true; protected override bool OnClick(ClickEvent e) => true; } }
// 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.Graphics; using osu.Framework.Input.Events; using osu.Game.Graphics.Containers; using osuTK; namespace osu.Game.Rulesets.Edit { public class ExpandingToolboxContainer : ExpandingContainer { protected override double HoverExpansionDelay => 250; public ExpandingToolboxContainer(float contractedWidth, float expandedWidth) : base(contractedWidth, expandedWidth) { RelativeSizeAxes = Axes.Y; FillFlow.Spacing = new Vector2(10); } protected override bool ReceivePositionalInputAtSubTree(Vector2 screenSpacePos) => base.ReceivePositionalInputAtSubTree(screenSpacePos) && anyToolboxHovered(screenSpacePos); public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => base.ReceivePositionalInputAt(screenSpacePos) && anyToolboxHovered(screenSpacePos); private bool anyToolboxHovered(Vector2 screenSpacePos) => FillFlow.ScreenSpaceDrawQuad.Contains(screenSpacePos); protected override bool OnMouseDown(MouseDownEvent e) => true; protected override bool OnClick(ClickEvent e) => true; } }
Add support for `type` when listing Products
namespace Stripe { using Newtonsoft.Json; public class ProductListOptions : ListOptionsWithCreated { [JsonProperty("active")] public bool? Active { get; set; } [JsonProperty("ids")] public string[] Ids { get; set; } [JsonProperty("shippable")] public bool? Shippable { get; set; } [JsonProperty("url")] public string Url { get; set; } } }
namespace Stripe { using Newtonsoft.Json; public class ProductListOptions : ListOptionsWithCreated { [JsonProperty("active")] public bool? Active { get; set; } [JsonProperty("ids")] public string[] Ids { get; set; } [JsonProperty("shippable")] public bool? Shippable { get; set; } [JsonProperty("type")] public string Type { get; set; } [JsonProperty("url")] public string Url { get; set; } } }
Add content type for downloads
using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Threading; using System.Threading.Tasks; using System.Web.Http; namespace DSCPullServerWeb.Helpers { public class FileActionResult : IHttpActionResult { private FileInfo _file; public FileActionResult(FileInfo file) { _file = file; } public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken) { HttpResponseMessage response = new HttpResponseMessage(); response.Content = new StreamContent(File.OpenRead(_file.FullName)); response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"); return Task.FromResult(response); } } }
using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Threading; using System.Threading.Tasks; using System.Web.Http; namespace DSCPullServerWeb.Helpers { public class FileActionResult : IHttpActionResult { private FileInfo _file; public FileActionResult(FileInfo file) { _file = file; } public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken) { HttpResponseMessage response = new HttpResponseMessage(); response.Content = new StreamContent(File.OpenRead(_file.FullName)); response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"); return Task.FromResult(response); } } }
Add sanity check to dissalow invalid file paths
// Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System; using System.IO; using SQLite.Net; namespace osu.Framework.Platform { public abstract class BasicStorage { public string BaseName { get; set; } protected BasicStorage(string baseName) { BaseName = baseName; } public abstract bool Exists(string path); public abstract void Delete(string path); public abstract Stream GetStream(string path, FileAccess mode = FileAccess.Read); public abstract SQLiteConnection GetDatabase(string name); public abstract void OpenInNativeExplorer(); } }
// Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System.IO; using osu.Framework.IO.File; using SQLite.Net; namespace osu.Framework.Platform { public abstract class BasicStorage { public string BaseName { get; set; } protected BasicStorage(string baseName) { BaseName = FileSafety.WindowsFilenameStrip(baseName); } public abstract bool Exists(string path); public abstract void Delete(string path); public abstract Stream GetStream(string path, FileAccess mode = FileAccess.Read); public abstract SQLiteConnection GetDatabase(string name); public abstract void OpenInNativeExplorer(); } }
Make hyperdash testcase easier to win again
using NUnit.Framework; using osu.Game.Beatmaps; using osu.Game.Rulesets.Catch.Objects; namespace osu.Game.Rulesets.Catch.Tests { [TestFixture] [Ignore("getting CI working")] public class TestCaseHyperdash : Game.Tests.Visual.TestCasePlayer { public TestCaseHyperdash() : base(typeof(CatchRuleset)) { } protected override Beatmap CreateBeatmap() { var beatmap = new Beatmap(); for (int i = 0; i < 512; i++) beatmap.HitObjects.Add(new Fruit { X = i % 8 < 4 ? 0.02f : 0.98f, StartTime = i * 100, NewCombo = i % 8 == 0 }); return beatmap; } } }
using NUnit.Framework; using osu.Game.Beatmaps; using osu.Game.Rulesets.Catch.Objects; namespace osu.Game.Rulesets.Catch.Tests { [TestFixture] [Ignore("getting CI working")] public class TestCaseHyperdash : Game.Tests.Visual.TestCasePlayer { public TestCaseHyperdash() : base(typeof(CatchRuleset)) { } protected override Beatmap CreateBeatmap() { var beatmap = new Beatmap(); for (int i = 0; i < 512; i++) if (i % 5 < 3) beatmap.HitObjects.Add(new Fruit { X = i % 10 < 5 ? 0.02f : 0.98f, StartTime = i * 100, NewCombo = i % 8 == 0 }); return beatmap; } } }
Fix slight error in documentation
using System; using System.Linq; using System.Reflection; namespace AssemblyVersionFromGit { public static class AssemblyVersionReader { /// <summary> /// Formats the assembly version from the specified assembly. /// Requires that the AssemblyInfo.cs file contains the AssemblyInformationalVersion attribute. /// </summary> /// <param name="assembly"></param> /// <returns></returns> public static string FormatApplicationVersion(this Assembly assembly) { var version = assembly.GetCustomAttributes(typeof(AssemblyInformationalVersionAttribute), false) .OfType<AssemblyInformationalVersionAttribute>().FirstOrDefault(); if (version == null) { return noVersion; } // Truncate long git hashes before display var printVersion = version.InformationalVersion; if (printVersion != null) { var dotLocation = printVersion.IndexOf(".", StringComparison.Ordinal); if (dotLocation >= 0) { const int hashLength = 8; var targetLength = dotLocation + 1 + hashLength; if (printVersion.Length > targetLength) { printVersion = printVersion.Substring(0, targetLength); } } } return printVersion; } private const string noVersion = "No version"; } }
using System; using System.Linq; using System.Reflection; namespace AssemblyVersionFromGit { public static class AssemblyVersionReader { /// <summary> /// Formats the assembly version from the specified assembly. /// Requires that <paramref name="assembly"/> contains an AssemblyInformationalVersion attribute. /// </summary> /// <param name="assembly"></param> /// <returns></returns> public static string FormatApplicationVersion(this Assembly assembly) { var version = assembly.GetCustomAttributes(typeof(AssemblyInformationalVersionAttribute), false) .OfType<AssemblyInformationalVersionAttribute>().FirstOrDefault(); if (version == null) { return noVersion; } // Truncate long git hashes before display var printVersion = version.InformationalVersion; if (printVersion != null) { var dotLocation = printVersion.IndexOf(".", StringComparison.Ordinal); if (dotLocation >= 0) { const int hashLength = 8; var targetLength = dotLocation + 1 + hashLength; if (printVersion.Length > targetLength) { printVersion = printVersion.Substring(0, targetLength); } } } return printVersion; } private const string noVersion = "No version"; } }
Create a database initializer with a url for the github project
using System.Data.Entity; using MyPersonalShortner.Lib.Domain.Url; namespace MyPersonalShortner.Lib.Infrastructure.EntityFramework { public class EFContext : DbContext { public EFContext() : base("MyPersonalShortner") { // TODO: Remove In Prod Database.CreateIfNotExists(); Database.SetInitializer(new DropCreateDatabaseIfModelChanges<EFContext>()); } public DbSet<LongUrl> Urls { get; set; } } }
using System.Data.Entity; using MyPersonalShortner.Lib.Domain.Url; namespace MyPersonalShortner.Lib.Infrastructure.EntityFramework { public class EFContext : DbContext { public EFContext() : base("MyPersonalShortner") { Database.SetInitializer(new MyPersonalSHortnerInitializer()); } public DbSet<LongUrl> Urls { get; set; } private class MyPersonalSHortnerInitializer : DropCreateDatabaseIfModelChanges<EFContext> { protected override void Seed(EFContext context) { context.Urls.Add(new LongUrl { Url = "https://github.com/marciotoshio/MyPersonalShortner" }); context.SaveChanges(); base.Seed(context); } } } }
Add Email test for ReadState.
using OttoMail.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Xunit; namespace OttoMail.Tests { public class EmailTest { [Fact] public void GetSubjectTest() { //Arrange var email = new Email(); email.Subject = "Test"; //Act var result = email.Subject; //Assert Assert.Equal("Test", result); } [Fact] public void GetBodyTest() { var email = new Email(); email.Body = "Test"; var result = email.Body; Assert.Equal("Test", result); } [Fact] public void GetDateTest() { var email = new Email(); var result = email.Date; Assert.Equal(DateTime.Now, result); } } }
using OttoMail.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Xunit; namespace OttoMail.Tests { public class EmailTest { [Fact] public void GetSubjectTest() { //Arrange var email = new Email(); email.Subject = "Test"; //Act var result = email.Subject; //Assert Assert.Equal("Test", result); } [Fact] public void GetBodyTest() { var email = new Email(); email.Body = "Test"; var result = email.Body; Assert.Equal("Test", result); } [Fact] public void GetDateTest() { var email = new Email(); var result = email.Date; Assert.Equal(DateTime.Now, result); } [Fact] public void GetReadStateTest() { var email = new Email(); var result = email.Read; Assert.Equal(false, result); } } }
Add styles and scripts to admin Layout.
<!DOCTYPE html> <html lang="en"> <head> <meta name="viewport" content="width=device-width" /> <title>@ViewBag.Title</title> @Styles.Render("~/Content/bootstrap.min.css") </head> <body> <div> @RenderBody() </div> @RenderSection("Scripts", false) </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta name="viewport" content="width=device-width" /> <title>@ViewBag.Title</title> @Styles.Render("~/Content/bootstrap.min.css") @Styles.Render("~/Content/bootstrap-responsive.min.css") @Styles.Render("~/bundles/font-awesome") <!-- HTML5 shim, for IE6-8 support of HTML5 elements --> <!--[if lt IE 9]> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> @Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/modernizr") @Scripts.Render("~/bundles/knockout") <script type="text/javascript"> Modernizr.load({ test: Modernizr.input.placeholder, nope: '/scripts/placeholder.js' }); Modernizr.load({ test: Modernizr.inputtypes.date, nope: '/scripts/datepicker.js' }); </script> </head> <body> <div> @RenderBody() </div> @RenderSection("Scripts", false) </body> </html>
Test data whitespace fixes (from tabs to spaces)
namespace dotless.Test.Specs.Functions { using NUnit.Framework; public class ExtractFixture : SpecFixtureBase { [Test] public void TestExtractFromCommaSeparatedList() { var input = @" @list: ""Arial"", ""Helvetica""; .someClass { font-family: e(extract(@list, 2)); }"; var expected = @" .someClass { font-family: Helvetica; }"; AssertLess(input, expected); } [Test] public void TestExtractFromSpaceSeparatedList() { var input = @" @list: 1px solid blue; .someClass { border: e(extract(@list, 2)); }"; var expected = @" .someClass { border: solid; }"; AssertLess(input, expected); } } }
namespace dotless.Test.Specs.Functions { using NUnit.Framework; public class ExtractFixture : SpecFixtureBase { [Test] public void TestExtractFromCommaSeparatedList() { var input = @" @list: ""Arial"", ""Helvetica""; .someClass { font-family: e(extract(@list, 2)); }"; var expected = @" .someClass { font-family: Helvetica; }"; AssertLess(input, expected); } [Test] public void TestExtractFromSpaceSeparatedList() { var input = @" @list: 1px solid blue; .someClass { border: e(extract(@list, 2)); }"; var expected = @" .someClass { border: solid; }"; AssertLess(input, expected); } } }
Refactor context to not use vars
namespace ClojSharp.Core { using System; using System.Collections.Generic; using System.Linq; using System.Text; using ClojSharp.Core.Language; public class Context : ClojSharp.Core.IContext { private IDictionary<string, object> values = new Dictionary<string, object>(); private IContext parent; private VarContext topcontext; public Context() : this(null) { } public Context(IContext parent) { this.parent = parent; if (parent != null) this.topcontext = parent.TopContext; } public VarContext TopContext { get { return this.topcontext; } } public void SetValue(string name, object value) { if (this.parent == null) this.values[name] = new Var(name, value); else this.values[name] = value; } public object GetValue(string name) { if (this.values.ContainsKey(name)) if (this.parent == null) return ((Var)this.values[name]).Value; else return this.values[name]; if (this.parent != null) return this.parent.GetValue(name); return null; } } }
namespace ClojSharp.Core { using System; using System.Collections.Generic; using System.Linq; using System.Text; using ClojSharp.Core.Language; public class Context : ClojSharp.Core.IContext { private IDictionary<string, object> values = new Dictionary<string, object>(); private IContext parent; private VarContext topcontext; public Context() : this(null) { } public Context(IContext parent) { this.parent = parent; if (parent != null) this.topcontext = parent.TopContext; } public VarContext TopContext { get { return this.topcontext; } } public void SetValue(string name, object value) { this.values[name] = value; } public object GetValue(string name) { if (this.values.ContainsKey(name)) return this.values[name]; if (this.parent != null) return this.parent.GetValue(name); return null; } } }
Use Trace instead of Console
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SamSeifert.Utilities { public static class Logger { public static Action<String> WriteLine = (String s) => { Console.WriteLine(s); }; } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SamSeifert.Utilities { public static class Logger { public static Action<String> WriteLine = (String s) => { Trace.WriteLine(s); }; } }
Fix issue when WebException with ProtocolError status has empty response
using System; using System.Net; namespace PatchKit.Api { public class WrapHttpWebRequest : IHttpWebRequest { private readonly HttpWebRequest _httpWebRequest; public int Timeout { get { return _httpWebRequest.Timeout; } set { _httpWebRequest.Timeout = value; } } public Uri Address { get { return _httpWebRequest.Address; } } public WrapHttpWebRequest(HttpWebRequest httpWebRequest) { _httpWebRequest = httpWebRequest; } public IHttpWebResponse GetResponse() { return new WrapHttpWebResponse(GetHttpResponse()); } private HttpWebResponse GetHttpResponse() { try { return (HttpWebResponse) _httpWebRequest.GetResponse(); } catch (WebException webException) { if (webException.Status == WebExceptionStatus.ProtocolError) { return (HttpWebResponse) webException.Response; } throw; } } } }
using System; using System.Net; namespace PatchKit.Api { public class WrapHttpWebRequest : IHttpWebRequest { private readonly HttpWebRequest _httpWebRequest; public int Timeout { get { return _httpWebRequest.Timeout; } set { _httpWebRequest.Timeout = value; } } public Uri Address { get { return _httpWebRequest.Address; } } public WrapHttpWebRequest(HttpWebRequest httpWebRequest) { _httpWebRequest = httpWebRequest; } public IHttpWebResponse GetResponse() { return new WrapHttpWebResponse(GetHttpResponse()); } private HttpWebResponse GetHttpResponse() { try { return (HttpWebResponse) _httpWebRequest.GetResponse(); } catch (WebException webException) { if (webException.Status == WebExceptionStatus.ProtocolError && webException.Response != null) { return (HttpWebResponse) webException.Response; } throw; } } } }
Prepare add IsValid for book borrow record
using System; using System.Collections.Generic; using System.Linq; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace hihapi.Models.Library { [Table("T_LIB_BOOK_BORROW_RECORD")] public class LibraryBookBorrowRecord: BaseModel { [Key] [Required] [Column("ID", TypeName = "INT")] public Int32 Id { get; set; } [Required] [Column("HID", TypeName = "INT")] public Int32 HomeID { get; set; } [Required] [Column("BOOK_ID", TypeName = "INT")] public int BookId { get; set; } [Required] [MaxLength(50)] [Column("USER", TypeName = "NVARCHAR(40)")] public String User { get; set; } [Column("FROMORG", TypeName = "INT")] public int? FromOrganization { get; set; } [Column("FROMDATE", TypeName = "DATE")] [DataType(DataType.Date)] public DateTime? FromDate { get; set; } [Column("TODATE", TypeName = "DATE")] [DataType(DataType.Date)] public DateTime? ToDate { get; set; } [Required] [Column("ISRETURNED", TypeName = "BIT")] public Boolean IsReturned { get; set; } [Column("COMMENT", TypeName = "NVARCHAR(50)")] [MaxLength(50)] public String Comment { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace hihapi.Models.Library { [Table("T_LIB_BOOK_BORROW_RECORD")] public class LibraryBookBorrowRecord: BaseModel { [Key] [Required] [Column("ID", TypeName = "INT")] public Int32 Id { get; set; } [Required] [Column("HID", TypeName = "INT")] public Int32 HomeID { get; set; } [Required] [Column("BOOK_ID", TypeName = "INT")] public int BookId { get; set; } [Required] [MaxLength(50)] [Column("USER", TypeName = "NVARCHAR(40)")] public String User { get; set; } [Column("FROMORG", TypeName = "INT")] public int? FromOrganization { get; set; } [Column("FROMDATE", TypeName = "DATE")] [DataType(DataType.Date)] public DateTime? FromDate { get; set; } [Column("TODATE", TypeName = "DATE")] [DataType(DataType.Date)] public DateTime? ToDate { get; set; } [Required] [Column("ISRETURNED", TypeName = "BIT")] public Boolean IsReturned { get; set; } [Column("COMMENT", TypeName = "NVARCHAR(50)")] [MaxLength(50)] public String Comment { get; set; } public override bool IsValid(hihDataContext context) { bool isvalid = base.IsValid(context); if (isvalid) { } return isvalid; } } }
Make the event steam static again
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace EventSourcingTodo.Domain { public interface ITodoListRepository { IList<Event> Events { get; } TodoList Get(); void PostChanges(TodoList todoList); } public class TodoListRepository : ITodoListRepository { // Global event stream for single global TodoList. Replace with something like Event Store. private List<Event> _events = new List<Event>(); public IList<Event> Events { get { lock (_events) { return _events; } } } public TodoList Get() { lock (_events) { return new TodoList(_events); } } public void PostChanges(TodoList todoList) { lock (_events) { _events.AddRange(todoList.UncommittedChanges); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace EventSourcingTodo.Domain { public interface ITodoListRepository { IList<Event> Events { get; } TodoList Get(); void PostChanges(TodoList todoList); } public class TodoListRepository : ITodoListRepository { // Global event stream for single global TodoList. Replace with something like Event Store. private static List<Event> _events = new List<Event>(); public IList<Event> Events { get { lock (_events) { return _events; } } } public TodoList Get() { lock (_events) { return new TodoList(_events); } } public void PostChanges(TodoList todoList) { lock (_events) { _events.AddRange(todoList.UncommittedChanges); } } } }
Refactor default GetElapsed to use static readonly instance
//----------------------------------------------------------------------- // <copyright file="LoopingScheduler.cs" company="Brian Rogers"> // Copyright (c) Brian Rogers. All rights reserved. // </copyright> //----------------------------------------------------------------------- namespace EventHandlerSample { using System; using System.Diagnostics; using System.Threading.Tasks; public class LoopingScheduler { private readonly Func<Task> doAsync; private readonly Stopwatch stopwatch; public LoopingScheduler(Func<Task> doAsync) { this.doAsync = doAsync; this.stopwatch = Stopwatch.StartNew(); this.GetElapsed = this.DefaultGetElapsed; } public event EventHandler Paused; public Func<TimeSpan> GetElapsed { get; set; } public async Task RunAsync(TimeSpan pauseInterval) { TimeSpan start = this.GetElapsed(); while (true) { await this.doAsync(); start = this.CheckPauseInterval(start, pauseInterval); } } private TimeSpan CheckPauseInterval(TimeSpan start, TimeSpan pauseInterval) { TimeSpan elapsed = this.GetElapsed() - start; if (elapsed >= pauseInterval) { start = elapsed; this.Raise(this.Paused); } return start; } private void Raise(EventHandler handler) { if (handler != null) { handler(this, EventArgs.Empty); } } private TimeSpan DefaultGetElapsed() { return this.stopwatch.Elapsed; } } }
//----------------------------------------------------------------------- // <copyright file="LoopingScheduler.cs" company="Brian Rogers"> // Copyright (c) Brian Rogers. All rights reserved. // </copyright> //----------------------------------------------------------------------- namespace EventHandlerSample { using System; using System.Diagnostics; using System.Threading.Tasks; public class LoopingScheduler { private static readonly Stopwatch DefaultStopwatch = Stopwatch.StartNew(); private static readonly Func<TimeSpan> InitialGetElapsed = DefaultGetElapsed; private readonly Func<Task> doAsync; public LoopingScheduler(Func<Task> doAsync) { this.doAsync = doAsync; this.GetElapsed = InitialGetElapsed; } public event EventHandler Paused; public Func<TimeSpan> GetElapsed { get; set; } public async Task RunAsync(TimeSpan pauseInterval) { TimeSpan start = this.GetElapsed(); while (true) { await this.doAsync(); start = this.CheckPauseInterval(start, pauseInterval); } } private static TimeSpan DefaultGetElapsed() { return DefaultStopwatch.Elapsed; } private TimeSpan CheckPauseInterval(TimeSpan start, TimeSpan pauseInterval) { TimeSpan elapsed = this.GetElapsed() - start; if (elapsed >= pauseInterval) { start = elapsed; this.Raise(this.Paused); } return start; } private void Raise(EventHandler handler) { if (handler != null) { handler(this, EventArgs.Empty); } } } }
Fix spelling in error message
namespace DarkSky.Services { using System; using System.Threading.Tasks; using Newtonsoft.Json; /// <summary> /// Interface to use for handling JSON serialization via Json.NET /// </summary> public class JsonNetJsonSerializerService : IJsonSerializerService { JsonSerializerSettings _jsonSettings = new JsonSerializerSettings(); /// <summary> /// The method to use when deserializing a JSON object. /// </summary> /// <param name="json">The JSON string to deserialize.</param> /// <returns>The resulting object from <paramref name="json" />.</returns> public async Task<T> DeserializeJsonAsync<T>(Task<string> json) { try { return (json != null) ? JsonConvert.DeserializeObject<T>(await json.ConfigureAwait(false), _jsonSettings) : default; } catch (JsonReaderException e) { throw new FormatException("Json Parsing Erorr", e); } } } }
namespace DarkSky.Services { using System; using System.Threading.Tasks; using Newtonsoft.Json; /// <summary> /// Interface to use for handling JSON serialization via Json.NET /// </summary> public class JsonNetJsonSerializerService : IJsonSerializerService { JsonSerializerSettings _jsonSettings = new JsonSerializerSettings(); /// <summary> /// The method to use when deserializing a JSON object. /// </summary> /// <param name="json">The JSON string to deserialize.</param> /// <returns>The resulting object from <paramref name="json" />.</returns> public async Task<T> DeserializeJsonAsync<T>(Task<string> json) { try { return (json != null) ? JsonConvert.DeserializeObject<T>(await json.ConfigureAwait(false), _jsonSettings) : default; } catch (JsonReaderException e) { throw new FormatException("Json Parsing Error", e); } } } }
Use "." instead of ":" in env var key.
namespace EventStore.Persistence.AcceptanceTests { using System; using System.Data; using System.Data.Common; using System.Diagnostics; using SqlPersistence; public class EnviromentConnectionFactory : IConnectionFactory { private readonly string providerInvariantName; private readonly string envVarKey; public EnviromentConnectionFactory(string envDatabaseName, string providerInvariantName) { this.envVarKey = "NEventStore:{0}".FormatWith(envDatabaseName); this.providerInvariantName = providerInvariantName; } public IDbConnection OpenMaster(Guid streamId) { return new ConnectionScope("master", Open); } public IDbConnection OpenReplica(Guid streamId) { return new ConnectionScope("master", Open); } private IDbConnection Open() { DbProviderFactory dbProviderFactory = DbProviderFactories.GetFactory(providerInvariantName); string connectionString = Environment.GetEnvironmentVariable(envVarKey, EnvironmentVariableTarget.Process); connectionString = connectionString.TrimStart('"').TrimEnd('"'); DbConnection connection = dbProviderFactory.CreateConnection(); Debug.Assert(connection != null, "connection != null"); connection.ConnectionString = connectionString; try { connection.Open(); } catch (Exception e) { throw new StorageUnavailableException(e.Message, e); } return connection; } } }
namespace EventStore.Persistence.AcceptanceTests { using System; using System.Data; using System.Data.Common; using System.Diagnostics; using SqlPersistence; public class EnviromentConnectionFactory : IConnectionFactory { private readonly string providerInvariantName; private readonly string envVarKey; public EnviromentConnectionFactory(string envDatabaseName, string providerInvariantName) { this.envVarKey = "NEventStore.{0}".FormatWith(envDatabaseName); this.providerInvariantName = providerInvariantName; } public IDbConnection OpenMaster(Guid streamId) { return new ConnectionScope("master", Open); } public IDbConnection OpenReplica(Guid streamId) { return new ConnectionScope("master", Open); } private IDbConnection Open() { DbProviderFactory dbProviderFactory = DbProviderFactories.GetFactory(providerInvariantName); string connectionString = Environment.GetEnvironmentVariable(envVarKey, EnvironmentVariableTarget.Process); connectionString = connectionString.TrimStart('"').TrimEnd('"'); DbConnection connection = dbProviderFactory.CreateConnection(); Debug.Assert(connection != null, "connection != null"); connection.ConnectionString = connectionString; try { connection.Open(); } catch (Exception e) { throw new StorageUnavailableException(e.Message, e); } return connection; } } }
Add missing .dtd file contents.
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.IO; namespace System.Security.Cryptography.Xml.Tests { internal static class TestHelpers { public static TempFile CreateTestDtdFile(string testName) { if (testName == null) throw new ArgumentNullException(nameof(testName)); var file = new TempFile( Path.Combine(Directory.GetCurrentDirectory(), testName + ".dtd") ); return file; } public static TempFile CreateTestTextFile(string testName, string content) { if (testName == null) throw new ArgumentNullException(nameof(testName)); if (content == null) throw new ArgumentNullException(nameof(content)); var file = new TempFile( Path.Combine(Directory.GetCurrentDirectory(), testName + ".txt") ); File.WriteAllText(file.Path, content); return file; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.IO; namespace System.Security.Cryptography.Xml.Tests { internal static class TestHelpers { public static TempFile CreateTestDtdFile(string testName) { if (testName == null) throw new ArgumentNullException(nameof(testName)); var file = new TempFile( Path.Combine(Directory.GetCurrentDirectory(), testName + ".dtd") ); File.WriteAllText(file.Path, "<!-- presence, not content, required -->"); return file; } public static TempFile CreateTestTextFile(string testName, string content) { if (testName == null) throw new ArgumentNullException(nameof(testName)); if (content == null) throw new ArgumentNullException(nameof(content)); var file = new TempFile( Path.Combine(Directory.GetCurrentDirectory(), testName + ".txt") ); File.WriteAllText(file.Path, content); return file; } } }
Add default values to options
using System; using System.Collections; using System.Collections.Generic; namespace Okanshi.Observers { public class InfluxDbObserverOptions { public string DatabaseName { get; } public string RetentionPolicy { get; set; } public Func<Tag, bool> TagToFieldSelector { get; set; } public IEnumerable<string> TagsToIgnore { get; set; } public InfluxDbObserverOptions(string databaseName) { DatabaseName = databaseName; } } }
using System; using System.Collections.Generic; using System.Linq; namespace Okanshi.Observers { public class InfluxDbObserverOptions { public string DatabaseName { get; } public string RetentionPolicy { get; set; } public Func<Tag, bool> TagToFieldSelector { get; set; } = x => false; public IEnumerable<string> TagsToIgnore { get; set; } = Enumerable.Empty<string>(); public InfluxDbObserverOptions(string databaseName) { DatabaseName = databaseName; } } }
Update the ViewModel we return as JSON to the Upgrade Installer Step - Has logic for checking latest logic (Needs bullet proof testing & discussion most likely)
using Umbraco.Web.Install.Models; namespace Umbraco.Web.Install.InstallSteps { /// <summary> /// This step is purely here to show the button to commence the upgrade /// </summary> [InstallSetupStep(InstallationType.Upgrade, "Upgrade", "upgrade", 1, "Upgrading Umbraco to the latest and greatest version.")] internal class UpgradeStep : InstallSetupStep<object> { public override bool RequiresExecution(object model) { return true; } public override InstallSetupResult Execute(object model) { return null; } } }
using Semver; using Umbraco.Core; using Umbraco.Core.Configuration; using Umbraco.Web.Install.Models; namespace Umbraco.Web.Install.InstallSteps { /// <summary> /// This step is purely here to show the button to commence the upgrade /// </summary> [InstallSetupStep(InstallationType.Upgrade, "Upgrade", "upgrade", 1, "Upgrading Umbraco to the latest and greatest version.")] internal class UpgradeStep : InstallSetupStep<object> { public override bool RequiresExecution(object model) { return true; } public override InstallSetupResult Execute(object model) { return null; } public override object ViewModel { get { var currentVersion = CurrentVersion().GetVersion(3).ToString(); var newVersion = UmbracoVersion.Current.ToString(); var reportUrl = string.Format("https://our.umbraco.org/contribute/releases/compare?from={0}&to={1}&notes=1", currentVersion, newVersion); return new { currentVersion = currentVersion, newVersion = newVersion, reportUrl = reportUrl }; } } /// <summary> /// Gets the Current Version of the Umbraco Site before an upgrade /// by using the last/most recent Umbraco Migration that has been run /// </summary> /// <returns>A SemVersion of the latest Umbraco DB Migration run</returns> private SemVersion CurrentVersion() { //Set a default version of 0.0.0 var version = new SemVersion(0); //If we have a db context available, if we don't then we are not installed anyways if (ApplicationContext.Current.DatabaseContext.IsDatabaseConfigured && ApplicationContext.Current.DatabaseContext.CanConnect) { version = ApplicationContext.Current.DatabaseContext.ValidateDatabaseSchema().DetermineInstalledVersionByMigrations(ApplicationContext.Current.Services.MigrationEntryService); } return version; } } }
Add calibrate command to the factory to be able to be parsed
using System; using System.Collections.Generic; using Admo.classes.lib.commands; using NLog; using Newtonsoft.Json; namespace Admo.classes.lib { class CommandFactory { private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); private static readonly Dictionary<string, Type> Commmands = new Dictionary<string, Type>() { { "screenshot", typeof(ScreenshotCommand)}, { "checkin", typeof(CheckinCommand)}, { "updateConfig", typeof(UpdateConfigCommand)}, }; public static BaseCommand ParseCommand(string rawCommand) { dynamic rawOjbect = JsonConvert.DeserializeObject(rawCommand); string cmd = rawOjbect.command; if (Commmands.ContainsKey(cmd)) { return (BaseCommand) Activator.CreateInstance(Commmands[cmd]); } Logger.Error("Unkown command ["+cmd+"]"); return new UnknownCommand(); } } }
using System; using System.Collections.Generic; using Admo.classes.lib.commands; using NLog; using Newtonsoft.Json; namespace Admo.classes.lib { class CommandFactory { private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); private static readonly Dictionary<string, Type> Commmands = new Dictionary<string, Type>() { { "screenshot", typeof(ScreenshotCommand)}, { "checkin", typeof(CheckinCommand)}, { "updateConfig", typeof(UpdateConfigCommand)}, { "calibrate", typeof(CalibrateCommand)}, }; public static BaseCommand ParseCommand(string rawCommand) { dynamic rawOjbect = JsonConvert.DeserializeObject(rawCommand); string cmd = rawOjbect.command; if (Commmands.ContainsKey(cmd)) { return (BaseCommand) Activator.CreateInstance(Commmands[cmd]); } Logger.Error("Unkown command ["+cmd+"]"); return new UnknownCommand(); } } }
Allow DI for LoginOverlay to resolve to null in non-graphical environments (fix tests)
// 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.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Sprites; using osu.Framework.Input.Events; using osu.Game.Overlays; namespace osu.Game.Online.Placeholders { public sealed class LoginPlaceholder : Placeholder { [Resolved] private LoginOverlay login { get; set; } public LoginPlaceholder(string action) { AddIcon(FontAwesome.Solid.UserLock, cp => { cp.Font = cp.Font.With(size: TEXT_SIZE); cp.Padding = new MarginPadding { Right = 10 }; }); AddText(@"Please sign in to " + action); } protected override bool OnMouseDown(MouseDownEvent e) { this.ScaleTo(0.8f, 4000, Easing.OutQuint); return base.OnMouseDown(e); } protected override bool OnMouseUp(MouseUpEvent e) { this.ScaleTo(1, 1000, Easing.OutElastic); return base.OnMouseUp(e); } protected override bool OnClick(ClickEvent e) { login?.Show(); return base.OnClick(e); } } }
// 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.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Sprites; using osu.Framework.Input.Events; using osu.Game.Overlays; namespace osu.Game.Online.Placeholders { public sealed class LoginPlaceholder : Placeholder { [Resolved(CanBeNull = true)] private LoginOverlay login { get; set; } public LoginPlaceholder(string action) { AddIcon(FontAwesome.Solid.UserLock, cp => { cp.Font = cp.Font.With(size: TEXT_SIZE); cp.Padding = new MarginPadding { Right = 10 }; }); AddText(@"Please sign in to " + action); } protected override bool OnMouseDown(MouseDownEvent e) { this.ScaleTo(0.8f, 4000, Easing.OutQuint); return base.OnMouseDown(e); } protected override bool OnMouseUp(MouseUpEvent e) { this.ScaleTo(1, 1000, Easing.OutElastic); return base.OnMouseUp(e); } protected override bool OnClick(ClickEvent e) { login?.Show(); return base.OnClick(e); } } }
Add missing namespace from service registration
using Glimpse.Server; using Microsoft.Framework.ConfigurationModel; using Microsoft.Framework.DependencyInjection; using System.Collections.Generic; namespace Glimpse { public class GlimpseServerServices { public static IEnumerable<IServiceDescriptor> GetDefaultServices() { return GetDefaultServices(new Configuration()); } public static IEnumerable<IServiceDescriptor> GetDefaultServices(IConfiguration configuration) { var describe = new ServiceDescriber(configuration); // // Broker // yield return describe.Singleton<IMessageServerBus, DefaultMessageServerBus>(); } public static IEnumerable<IServiceDescriptor> GetPublisherServices() { return GetPublisherServices(new Configuration()); } public static IEnumerable<IServiceDescriptor> GetPublisherServices(IConfiguration configuration) { var describe = new ServiceDescriber(configuration); // // Broker // yield return describe.Singleton<IMessagePublisher, LocalMessagePublisher>(); } } }
using Glimpse.Agent; using Glimpse.Server; using Microsoft.Framework.ConfigurationModel; using Microsoft.Framework.DependencyInjection; using System.Collections.Generic; namespace Glimpse { public class GlimpseServerServices { public static IEnumerable<IServiceDescriptor> GetDefaultServices() { return GetDefaultServices(new Configuration()); } public static IEnumerable<IServiceDescriptor> GetDefaultServices(IConfiguration configuration) { var describe = new ServiceDescriber(configuration); // // Broker // yield return describe.Singleton<IMessageServerBus, DefaultMessageServerBus>(); } public static IEnumerable<IServiceDescriptor> GetPublisherServices() { return GetPublisherServices(new Configuration()); } public static IEnumerable<IServiceDescriptor> GetPublisherServices(IConfiguration configuration) { var describe = new ServiceDescriber(configuration); // // Broker // yield return describe.Singleton<IMessagePublisher, LocalMessagePublisher>(); } } }
Fix indentation; add braces around single-line if.
namespace Nancy.Demo.Authentication.Basic { using Nancy.Authentication.Basic; using Nancy.Security; public class UserValidator : IUserValidator { public IUserIdentity Validate(string username, string password) { if (username == "demo" && password == "demo") return new DemoUserIdentity { UserName = username }; // Not recognised => anonymous. return null; } } }
namespace Nancy.Demo.Authentication.Basic { using Nancy.Authentication.Basic; using Nancy.Security; public class UserValidator : IUserValidator { public IUserIdentity Validate(string username, string password) { if (username == "demo" && password == "demo") { return new DemoUserIdentity { UserName = username }; } // Not recognised => anonymous. return null; } } }
Use temporary redirect to swagger
namespace ApiTemplate.Controllers { using ApiTemplate.Constants; using Microsoft.AspNetCore.Mvc; [Route("")] [ApiExplorerSettings(IgnoreApi = true)] public class HomeController : ControllerBase { /// <summary> /// Redirects to the swagger page. /// </summary> /// <returns>A 301 Moved Permanently response.</returns> [HttpGet("", Name = HomeControllerRoute.GetIndex)] public IActionResult Index() => this.RedirectPermanent("/swagger"); } }
namespace ApiTemplate.Controllers { using ApiTemplate.Constants; using Microsoft.AspNetCore.Mvc; [Route("")] [ApiExplorerSettings(IgnoreApi = true)] public class HomeController : ControllerBase { /// <summary> /// Redirects to the swagger page. /// </summary> /// <returns>A 301 Moved Permanently response.</returns> [HttpGet("", Name = HomeControllerRoute.GetIndex)] public IActionResult Index() => this.Redirect("/swagger"); } }
Make codefixer for explicit interface polymorph analyzer
using System; using System.Composition; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Rename; using Microsoft.CodeAnalysis.Text; namespace FonsDijkstra.CConst { [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(ConstPolymorphismCodeFixProvider)), Shared] public class ConstPolymorphismCodeFixProvider : CodeFixProvider { public const string DiagnosticId = ConstPolymorphismAnalyzer.OverrideDiagnosticId; public sealed override ImmutableArray<string> FixableDiagnosticIds { get { return ImmutableArray.Create(DiagnosticId); } } public sealed override FixAllProvider GetFixAllProvider() { return WellKnownFixAllProviders.BatchFixer; } public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken); var method = root.FindNode(context.Span) as MethodDeclarationSyntax; if (method != null) { context.RegisterCodeFix( CodeAction.Create( "Add const declaration", c => method.AddConstAttributeAsync(context.Document, c), DiagnosticId + "_add"), context.Diagnostics.Single()); } } } }
using System; using System.Composition; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Rename; using Microsoft.CodeAnalysis.Text; namespace FonsDijkstra.CConst { [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(ConstPolymorphismCodeFixProvider)), Shared] public class ConstPolymorphismCodeFixProvider : CodeFixProvider { public sealed override ImmutableArray<string> FixableDiagnosticIds { get { return ImmutableArray.Create(ConstPolymorphismAnalyzer.OverrideDiagnosticId, ConstPolymorphismAnalyzer.ExplicitInterfaceDiagnosticId); } } public sealed override FixAllProvider GetFixAllProvider() { return WellKnownFixAllProviders.BatchFixer; } public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken); var method = root.FindNode(context.Span) as MethodDeclarationSyntax; if (method != null) { context.RegisterCodeFix( CodeAction.Create( "Add const declaration", c => method.AddConstAttributeAsync(context.Document, c), nameof(ConstPolymorphismCodeFixProvider) + "_add"), context.Diagnostics.Single()); } } } }
Increase assembly version to 1.0.
// Copyright // ---------------------------------------------------------------------------------------------------------- // <copyright file="AssemblyInfo.cs" company="https://github.com/safakgur/Dawn.SocketAwaitable"> // MIT // </copyright> // <license> // This source code is subject to terms and conditions of The MIT License (MIT). // A copy of the license can be found in the License.txt file at the root of this distribution. // </license> // <summary> // Contains the attributes that provide information about the assembly. // </summary> // ---------------------------------------------------------------------------------------------------------- using System; using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Dawn.SocketAwaitable")] [assembly: AssemblyCompany("https://github.com/safakgur/Dawn.SocketAwaitable")] [assembly: AssemblyDescription("Provides utilities for asynchronous socket operations.")] [assembly: AssemblyProduct("Dawn Framework")] [assembly: AssemblyCopyright("MIT")] [assembly: CLSCompliant(true)] [assembly: ComVisible(false)] [assembly: AssemblyVersion("0.1.0.0")] [assembly: AssemblyFileVersion("0.1.0.0")] #if DEBUG [assembly: AssemblyConfiguration("Debug")] #else [assembly: AssemblyConfiguration("Release")] #endif
// Copyright // ---------------------------------------------------------------------------------------------------------- // <copyright file="AssemblyInfo.cs" company="https://github.com/safakgur/Dawn.SocketAwaitable"> // MIT // </copyright> // <license> // This source code is subject to terms and conditions of The MIT License (MIT). // A copy of the license can be found in the License.txt file at the root of this distribution. // </license> // <summary> // Contains the attributes that provide information about the assembly. // </summary> // ---------------------------------------------------------------------------------------------------------- using System; using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Dawn.SocketAwaitable")] [assembly: AssemblyCompany("https://github.com/safakgur/Dawn.SocketAwaitable")] [assembly: AssemblyDescription("Provides utilities for asynchronous socket operations.")] [assembly: AssemblyProduct("Dawn Framework")] [assembly: AssemblyCopyright("MIT")] [assembly: CLSCompliant(true)] [assembly: ComVisible(false)] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] #if DEBUG [assembly: AssemblyConfiguration("Debug")] #else [assembly: AssemblyConfiguration("Release")] #endif
Change StartJobsAsync to work on the generic host
using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; namespace MR.AspNetCore.Jobs { public static class JobsWebHostExtensions { public static Task StartJobsAsync(this IWebHost host) { var bootstrapper = host.Services.GetRequiredService<IBootstrapper>(); return bootstrapper.BootstrapAsync(); } } }
using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace MR.AspNetCore.Jobs { public static class JobsWebHostExtensions { public static Task StartJobsAsync(this IHost host) { var bootstrapper = host.Services.GetRequiredService<IBootstrapper>(); return bootstrapper.BootstrapAsync(); } } }
Set the access token properly in the OAuth form
using LiveSplit.Options; using System; using System.Windows.Forms; namespace LiveSplit.Web.Share { public partial class SpeedrunComOAuthForm : Form, ISpeedrunComAuthenticator { private string accessToken; public SpeedrunComOAuthForm() { InitializeComponent(); } void OAuthForm_Load(object sender, EventArgs e) { OAuthWebBrowser.Navigate(new Uri("http://www.speedrun.com/api/auth")); } private void OAuthWebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { try { var html = OAuthWebBrowser.DocumentText; var index = html.IndexOf("id=\"api-key\">"); var secondIndex = html.IndexOf("</code"); if (index >= 0 && secondIndex >= 0) { index = index + "id=\"api-key\">".Length; var accessToken = html.Substring(index, secondIndex - index); try { ShareSettings.Default.SpeedrunComAccessToken = accessToken; ShareSettings.Default.Save(); } catch (Exception ex) { Log.Error(ex); } Action closeAction = () => Close(); if (InvokeRequired) Invoke(closeAction); else closeAction(); } } catch (Exception ex) { Log.Error(ex); } } public string GetAccessToken() { accessToken = null; ShowDialog(); return accessToken; } } }
using LiveSplit.Options; using System; using System.Windows.Forms; namespace LiveSplit.Web.Share { public partial class SpeedrunComOAuthForm : Form, ISpeedrunComAuthenticator { private string accessToken; public SpeedrunComOAuthForm() { InitializeComponent(); } void OAuthForm_Load(object sender, EventArgs e) { OAuthWebBrowser.Navigate(new Uri("http://www.speedrun.com/api/auth")); } private void OAuthWebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { try { var html = OAuthWebBrowser.DocumentText; var index = html.IndexOf("id=\"api-key\">"); var secondIndex = html.IndexOf("</code"); if (index >= 0 && secondIndex >= 0) { index = index + "id=\"api-key\">".Length; accessToken = html.Substring(index, secondIndex - index); try { ShareSettings.Default.SpeedrunComAccessToken = accessToken; ShareSettings.Default.Save(); } catch (Exception ex) { Log.Error(ex); } Action closeAction = () => Close(); if (InvokeRequired) Invoke(closeAction); else closeAction(); } } catch (Exception ex) { Log.Error(ex); } } public string GetAccessToken() { accessToken = null; ShowDialog(); return accessToken; } } }
Add new properties to message schema
using System.Collections; using System.Collections.Generic; namespace Mindscape.Raygun4Net.Messages { public class RaygunMessageDetails { public string MachineName { get; set; } public string GroupingKey { get; set; } public string Version { get; set; } public RaygunErrorMessage Error { get; set; } public RaygunEnvironmentMessage Environment { get; set; } public RaygunClientMessage Client { get; set; } public IList<string> Tags { get; set; } public IDictionary UserCustomData { get; set; } public RaygunIdentifierMessage User { get; set; } public RaygunRequestMessage Request { get; set; } public RaygunResponseMessage Response { get; set; } public IList<RaygunBreadcrumb> Breadcrumbs { get; set; } } }
using System.Collections; using System.Collections.Generic; namespace Mindscape.Raygun4Net.Messages { public class RaygunMessageDetails { public string MachineName { get; set; } public string GroupingKey { get; set; } public string Version { get; set; } public string CorrelationId { get; set; } public string ContextId { get; set; } public RaygunErrorMessage Error { get; set; } public RaygunEnvironmentMessage Environment { get; set; } public RaygunClientMessage Client { get; set; } public IList<string> Tags { get; set; } public IDictionary UserCustomData { get; set; } public RaygunIdentifierMessage User { get; set; } public RaygunRequestMessage Request { get; set; } public RaygunResponseMessage Response { get; set; } public IList<RaygunBreadcrumb> Breadcrumbs { get; set; } } }
Use AutoFixture to populate test objects
using System.IO; using AppHarbor.Commands; using Moq; using Xunit; namespace AppHarbor.Tests.Commands { public class LogoutAuthCommandTest { [Fact] public void ShouldLogoutUser() { var accessTokenConfigurationMock = new Mock<AccessTokenConfiguration>(); var writer = new Mock<TextWriter>(); var logoutCommand = new LogoutAuthCommand(accessTokenConfigurationMock.Object, writer.Object); logoutCommand.Execute(new string[0]); writer.Verify(x => x.WriteLine("Successfully logged out.")); accessTokenConfigurationMock.Verify(x => x.DeleteAccessToken(), Times.Once()); } } }
using System.IO; using AppHarbor.Commands; using Moq; using Ploeh.AutoFixture.Xunit; using Xunit.Extensions; namespace AppHarbor.Tests.Commands { public class LogoutAuthCommandTest { [Theory, AutoCommandData] public void ShouldLogoutUser([Frozen]Mock<IAccessTokenConfiguration> accessTokenConfigurationMock, [Frozen]Mock<TextWriter> writer, LogoutAuthCommand logoutCommand) { logoutCommand.Execute(new string[0]); writer.Verify(x => x.WriteLine("Successfully logged out.")); accessTokenConfigurationMock.Verify(x => x.DeleteAccessToken(), Times.Once()); } } }
Add default format (json) in web api config
using System; using System.Collections.Generic; using System.Linq; using System.Web.Http; namespace TokenAuthentification { public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API configuration and services // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } } }
using Newtonsoft.Json.Serialization; using System.Linq; using System.Net.Http.Formatting; using System.Web.Http; namespace TokenAuthentification { public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API configuration and services // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); // Default format var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First(); jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); } } }
Remove plants from tundra biome
using System; using System.Collections.Generic; using System.Linq; using System.Text; using TrueCraft.Core.TerrainGen.Noise; using TrueCraft.Core.Logic.Blocks; using TrueCraft.API.World; using TrueCraft.API; namespace TrueCraft.Core.TerrainGen.Biomes { public class TundraBiome : BiomeProvider { public override byte ID { get { return (byte)Biome.Tundra; } } public override double Temperature { get { return 0.1f; } } public override double Rainfall { get { return 0.7f; } } public override TreeSpecies[] Trees { get { return new[] { TreeSpecies.Spruce }; } } public override double TreeDensity { get { return 50; } } public override byte SurfaceBlock { get { return GrassBlock.BlockID; } } public override byte FillerBlock { get { return DirtBlock.BlockID; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using TrueCraft.Core.TerrainGen.Noise; using TrueCraft.Core.Logic.Blocks; using TrueCraft.API.World; using TrueCraft.API; namespace TrueCraft.Core.TerrainGen.Biomes { public class TundraBiome : BiomeProvider { public override byte ID { get { return (byte)Biome.Tundra; } } public override double Temperature { get { return 0.1f; } } public override double Rainfall { get { return 0.7f; } } public override TreeSpecies[] Trees { get { return new[] { TreeSpecies.Spruce }; } } public override PlantSpecies[] Plants { get { return new PlantSpecies[0]; } } public override double TreeDensity { get { return 50; } } public override byte SurfaceBlock { get { return GrassBlock.BlockID; } } public override byte FillerBlock { get { return DirtBlock.BlockID; } } } }
Disable provider filtering for Alexa
@inject Microsoft.AspNetCore.Identity.SignInManager<LondonTravelUser> SignInManager @{ var providers = SignInManager.GetExternalAuthenticationSchemes() .OrderBy((p) => p.DisplayName) .ThenBy((p) => p.AuthenticationScheme) .ToList(); var schemesToShow = ViewData["AuthenticationSchemesToShow"] as IEnumerable<string>; if (schemesToShow != null) { providers = providers .Where((p) => schemesToShow.Contains(p.AuthenticationScheme, StringComparer.OrdinalIgnoreCase)) .ToList(); } } <form asp-route="@SiteRoutes.ExternalSignIn" asp-route-returnurl="@ViewData["ReturnUrl"]" method="post" class="form-horizontal"> <div> <p> @foreach (var provider in providers) { @await Html.PartialAsync("_SocialButton", provider) } </p> </div> </form>
@inject Microsoft.AspNetCore.Identity.SignInManager<LondonTravelUser> SignInManager @{ var providers = SignInManager.GetExternalAuthenticationSchemes() .OrderBy((p) => p.DisplayName) .ThenBy((p) => p.AuthenticationScheme) .ToList(); /* var schemesToShow = ViewData["AuthenticationSchemesToShow"] as IEnumerable<string>; if (schemesToShow != null) { providers = providers .Where((p) => schemesToShow.Contains(p.AuthenticationScheme, StringComparer.OrdinalIgnoreCase)) .ToList(); } */ } <form asp-route="@SiteRoutes.ExternalSignIn" asp-route-returnurl="@ViewData["ReturnUrl"]" method="post" class="form-horizontal"> <div> <p> @foreach (var provider in providers) { @await Html.PartialAsync("_SocialButton", provider) } </p> </div> </form>
Refactor - rename test methods
using NUnit.Framework; namespace IntUITive.Selenium.Tests { [TestFixture] public class IntuitivelyFindByIdTests : BaseIntuitivelyTests { [Test] public void Find_WithIdAsTerm_ReturnsSingleElement() { var element = Intuitively.Find("uniqueId"); Assert.That(element.GetAttribute("id"), Is.EqualTo("uniqueId")); } [Test] public void Find_WithCaseInsensitiveId_ReturnsSingleElement() { var element = Intuitively.Find("UNIQUEID"); Assert.That(element.GetAttribute("id"), Is.EqualTo("uniqueId")); } } }
using NUnit.Framework; namespace IntUITive.Selenium.Tests { [TestFixture] public class IntuitivelyFindByIdTests : BaseIntuitivelyTests { [Test] public void Find_WithIdAsTerm_ReturnsElement() { var element = Intuitively.Find("uniqueId"); Assert.That(element.GetAttribute("id"), Is.EqualTo("uniqueId")); } [Test] public void Find_WithCaseInsensitiveId_ReturnsElement() { var element = Intuitively.Find("UNIQUEID"); Assert.That(element.GetAttribute("id"), Is.EqualTo("uniqueId")); } } }