Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Align assembly version with package version
using System.Resources; 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("Eve")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("CIR 2000")] [assembly: AssemblyProduct("Eve")] [assembly: AssemblyCopyright("Copyright © CIR 2000 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] // 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")]
using System.Resources; 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("Eve")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("CIR 2000")] [assembly: AssemblyProduct("Eve")] [assembly: AssemblyCopyright("Copyright © CIR 2000 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] // 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("0.1.1.0")] [assembly: AssemblyFileVersion("0.1.1.0")]
Remove unused using embedded in reverted changes
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Bindables; using osu.Framework.Graphics.UserInterface; using osu.Game.Beatmaps; using osu.Game.Rulesets; using System.Linq; using osu.Framework.Allocation; namespace osu.Game.Overlays.BeatmapSet { public class BeatmapRulesetSelector : OverlayRulesetSelector { protected override bool SelectInitialRuleset => false; private readonly Bindable<BeatmapSetInfo> beatmapSet = new Bindable<BeatmapSetInfo>(); public BeatmapSetInfo BeatmapSet { get => beatmapSet.Value; set { // propagate value to tab items first to enable only available rulesets. beatmapSet.Value = value; SelectTab(TabContainer.TabItems.FirstOrDefault(t => t.Enabled.Value)); } } protected override TabItem<RulesetInfo> CreateTabItem(RulesetInfo value) => new BeatmapRulesetTabItem(value) { BeatmapSet = { BindTarget = beatmapSet } }; } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Bindables; using osu.Framework.Graphics.UserInterface; using osu.Game.Beatmaps; using osu.Game.Rulesets; using System.Linq; namespace osu.Game.Overlays.BeatmapSet { public class BeatmapRulesetSelector : OverlayRulesetSelector { protected override bool SelectInitialRuleset => false; private readonly Bindable<BeatmapSetInfo> beatmapSet = new Bindable<BeatmapSetInfo>(); public BeatmapSetInfo BeatmapSet { get => beatmapSet.Value; set { // propagate value to tab items first to enable only available rulesets. beatmapSet.Value = value; SelectTab(TabContainer.TabItems.FirstOrDefault(t => t.Enabled.Value)); } } protected override TabItem<RulesetInfo> CreateTabItem(RulesetInfo value) => new BeatmapRulesetTabItem(value) { BeatmapSet = { BindTarget = beatmapSet } }; } }
Add TextTags properties to request data
using System.Collections.Generic; using System.IO; using System.Linq; namespace HelloSignNet.Core { public class HSSendSignatureRequestData { public string Title { get; set; } public string Subject { get; set; } public string Message { get; set; } public string SigningRedirectUrl { get; set; } public List<HSSigner> Signers { get; set; } public List<string> CcEmailAddresses { get; set; } public List<FileInfo> Files { get; set; } public List<string> FileUrls { get; set; } public int TestMode { get; set; } // true=1, false=0 public bool IsValid { get { if (Files == null && FileUrls == null) { return false; } if (Files != null && FileUrls == null) { if (!Files.Any()) return true; } if (Files == null && FileUrls != null) { if (!FileUrls.Any()) return false; } if (Signers == null || Signers.Count == 0) return false; if (Signers.Any(s => string.IsNullOrEmpty(s.Name) || string.IsNullOrEmpty(s.EmailAddress))) return false; return true; } } } }
using System.Collections.Generic; using System.IO; using System.Linq; namespace HelloSignNet.Core { public class HSSendSignatureRequestData { public string Title { get; set; } public string Subject { get; set; } public string Message { get; set; } public string SigningRedirectUrl { get; set; } public List<HSSigner> Signers { get; set; } public List<string> CcEmailAddresses { get; set; } public List<FileInfo> Files { get; set; } public List<string> FileUrls { get; set; } public int TestMode { get; set; } // true=1, false=0, default=0 public int UseTextTags { get; set; } // true=1, false=0, default=0 public int HideTextTags { get; set; } // true=1, false=0, default=0 public bool IsValid { get { if (Files == null && FileUrls == null) { return false; } // API does not accept both files param in a request if (Files != null && FileUrls != null && Files.Any() && FileUrls.Any()) return false; if (Files != null && FileUrls == null) { if (!Files.Any()) return false; } if (Files == null && FileUrls != null) { if (!FileUrls.Any()) return false; } if (Signers == null || Signers.Count == 0) return false; if (Signers.Any(s => string.IsNullOrEmpty(s.Name) || string.IsNullOrEmpty(s.EmailAddress))) return false; return true; } } } }
Add item index for multiple items with same name
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; namespace Downlitor { public partial class ItemInfoControl : UserControl { public ItemInfoControl(DlcItem dlc) { InitializeComponent(); var manager = ItemManager.Instance; for (int i = 0; i < ItemManager.NumEntries; i++) { var item = manager.GetItem(i); comboItems.Items.Add((item == null) ? "Invalid" : item); } comboItems.SelectedIndex = dlc.Index; comboItems.AutoCompleteMode = AutoCompleteMode.Suggest; comboItems.AutoCompleteSource = AutoCompleteSource.ListItems; comboItems.SelectedIndexChanged += delegate { if ((string)comboItems.SelectedItem == "Invalid") return; dlc.Index = (ushort)comboItems.SelectedIndex; }; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; namespace Downlitor { public partial class ItemInfoControl : UserControl { public ItemInfoControl(DlcItem dlc) { InitializeComponent(); var manager = ItemManager.Instance; for (int i = 0; i < ItemManager.NumEntries; i++) { var item = manager.GetItem(i); comboItems.Items.Add((item == null) ? "Invalid" : item + " (" + i.ToString("D3") + ")"); } comboItems.SelectedIndex = dlc.Index; comboItems.AutoCompleteMode = AutoCompleteMode.Suggest; comboItems.AutoCompleteSource = AutoCompleteSource.ListItems; comboItems.SelectedIndexChanged += delegate { if ((string)comboItems.SelectedItem == "Invalid") return; dlc.Index = (ushort)comboItems.SelectedIndex; }; } } }
Add support for compound index keys to newtonsoft
using RethinkDb.DatumConverters; namespace RethinkDb.Newtonsoft.Configuration { public class NewtonSerializer : AggregateDatumConverterFactory { public NewtonSerializer() : base( PrimitiveDatumConverterFactory.Instance, TupleDatumConverterFactory.Instance, AnonymousTypeDatumConverterFactory.Instance, BoundEnumDatumConverterFactory.Instance, NullableDatumConverterFactory.Instance, NamedValueDictionaryDatumConverterFactory.Instance, NewtonsoftDatumConverterFactory.Instance ) { } } }
using RethinkDb.DatumConverters; namespace RethinkDb.Newtonsoft.Configuration { public class NewtonSerializer : AggregateDatumConverterFactory { public NewtonSerializer() : base( PrimitiveDatumConverterFactory.Instance, TupleDatumConverterFactory.Instance, AnonymousTypeDatumConverterFactory.Instance, BoundEnumDatumConverterFactory.Instance, NullableDatumConverterFactory.Instance, NamedValueDictionaryDatumConverterFactory.Instance, CompoundIndexDatumConverterFactory.Instance, NewtonsoftDatumConverterFactory.Instance ) { } } }
Update usage notes when crayon.exe is invoked without arguments.
using Common; using System; namespace Crayon { internal class UsageDisplayWorker { private static readonly string USAGE = Util.JoinLines( "Usage:", " crayon BUILD-FILE -target BUILD-TARGET-NAME [OPTIONS...]", "", "Flags:", "", " -target When a build file is specified, selects the", " target within that build file to build.", "", " -vm Output a standalone VM for a platform.", "", " -vmdir Directory to output the VM to (when -vm is", " specified).", "", " -genDefaultProj Generate a default boilerplate project to", " the current directory.", "", " -genDefaultProjES Generates a default project with ES locale.", "", " -genDefaultProjJP Generates a default project with JP locale.", ""); public void DoWorkImpl() { Console.WriteLine(USAGE); } } }
using Common; using System; namespace Crayon { internal class UsageDisplayWorker { private static readonly string USAGE = Util.JoinLines( "Crayon version " + VersionInfo.VersionString, "", "To export:", " crayon BUILD-FILE -target BUILD-TARGET-NAME [OPTIONS...]", "", "To run:", " crayon BUILD-FILE [args...]", "", "Flags:", "", " -target When a build file is specified, selects the", " target within that build file to build.", "", " -vm Output a standalone VM for a platform.", "", " -vmdir Directory to output the VM to (when -vm is", " specified).", "", " -genDefaultProj Generate a default boilerplate project to", " the current directory.", "", " -genDefaultProjES Generates a default project with ES locale.", "", " -genDefaultProjJP Generates a default project with JP locale.", "", " -showLibDepTree Shows a dependency tree of the build.", "", " -showLibStack Stack traces will include libraries. By", " default, stack traces are truncated to only", " show user code.", ""); public void DoWorkImpl() { Console.WriteLine(USAGE); } } }
Build script now writes the package name and version into the AssemblyDescription attibute. This allows the package information to be seen in Visual Studio avoiding confusion with the assembly version that remains at the major.
using System; using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Autofac.Integration.SignalR")] [assembly: AssemblyDescription("Autofac ASP.NET SignalR Integration")] [assembly: ComVisible(false)] [assembly: CLSCompliant(false)]
using System; using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Autofac.Integration.SignalR")] [assembly: ComVisible(false)] [assembly: CLSCompliant(false)]
Fix test event ordering to correctly test fail case
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Threading; using NUnit.Framework; using osu.Framework.Audio; namespace osu.Framework.Tests.Audio { [TestFixture] public class AudioCollectionManagerTest { [Test] public void TestDisposalWhileItemsAreAddedDoesNotThrowInvalidOperationException() { var manager = new TestAudioCollectionManager(); var threadExecutionFinished = new ManualResetEventSlim(); var updateLoopStarted = new ManualResetEventSlim(); // add a huge amount of items to the queue for (int i = 0; i < 10000; i++) manager.AddItem(new TestingAdjustableAudioComponent()); // in a separate thread start processing the queue var thread = new Thread(() => { while (!manager.IsDisposed) { manager.Update(); updateLoopStarted.Set(); } threadExecutionFinished.Set(); }); thread.Start(); Assert.IsTrue(updateLoopStarted.Wait(10000)); Assert.DoesNotThrow(() => manager.Dispose()); Assert.IsTrue(threadExecutionFinished.Wait(10000)); } private class TestAudioCollectionManager : AudioCollectionManager<AdjustableAudioComponent> { public new bool IsDisposed => base.IsDisposed; } private class TestingAdjustableAudioComponent : AdjustableAudioComponent { } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Threading; using NUnit.Framework; using osu.Framework.Audio; namespace osu.Framework.Tests.Audio { [TestFixture] public class AudioCollectionManagerTest { [Test] public void TestDisposalWhileItemsAreAddedDoesNotThrowInvalidOperationException() { var manager = new TestAudioCollectionManager(); var threadExecutionFinished = new ManualResetEventSlim(); var updateLoopStarted = new ManualResetEventSlim(); // add a huge amount of items to the queue for (int i = 0; i < 10000; i++) manager.AddItem(new TestingAdjustableAudioComponent()); // in a separate thread start processing the queue var thread = new Thread(() => { while (!manager.IsDisposed) { updateLoopStarted.Set(); manager.Update(); } threadExecutionFinished.Set(); }); thread.Start(); Assert.IsTrue(updateLoopStarted.Wait(10000)); Assert.DoesNotThrow(() => manager.Dispose()); Assert.IsTrue(threadExecutionFinished.Wait(10000)); } private class TestAudioCollectionManager : AudioCollectionManager<AdjustableAudioComponent> { public new bool IsDisposed => base.IsDisposed; } private class TestingAdjustableAudioComponent : AdjustableAudioComponent { } } }
Add test showing all mod icons for reference
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable disable using System.Linq; using NUnit.Framework; using osu.Game.Rulesets.Osu; using osu.Game.Rulesets.Osu.Mods; using osu.Game.Rulesets.UI; namespace osu.Game.Tests.Visual.UserInterface { public class TestSceneModIcon : OsuTestScene { [Test] public void TestChangeModType() { ModIcon icon = null; AddStep("create mod icon", () => Child = icon = new ModIcon(new OsuModDoubleTime())); AddStep("change mod", () => icon.Mod = new OsuModEasy()); } [Test] public void TestInterfaceModType() { ModIcon icon = null; var ruleset = new OsuRuleset(); AddStep("create mod icon", () => Child = icon = new ModIcon(ruleset.AllMods.First(m => m.Acronym == "DT"))); AddStep("change mod", () => icon.Mod = ruleset.AllMods.First(m => m.Acronym == "EZ")); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Linq; using NUnit.Framework; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Rulesets.Osu; using osu.Game.Rulesets.Osu.Mods; using osu.Game.Rulesets.UI; namespace osu.Game.Tests.Visual.UserInterface { public class TestSceneModIcon : OsuTestScene { [Test] public void TestShowAllMods() { AddStep("create mod icons", () => { Child = new FillFlowContainer { RelativeSizeAxes = Axes.Both, Direction = FillDirection.Full, ChildrenEnumerable = Ruleset.Value.CreateInstance().CreateAllMods().Select(m => new ModIcon(m)), }; }); } [Test] public void TestChangeModType() { ModIcon icon = null!; AddStep("create mod icon", () => Child = icon = new ModIcon(new OsuModDoubleTime())); AddStep("change mod", () => icon.Mod = new OsuModEasy()); } [Test] public void TestInterfaceModType() { ModIcon icon = null!; var ruleset = new OsuRuleset(); AddStep("create mod icon", () => Child = icon = new ModIcon(ruleset.AllMods.First(m => m.Acronym == "DT"))); AddStep("change mod", () => icon.Mod = ruleset.AllMods.First(m => m.Acronym == "EZ")); } } }
Verify that an ApplicationConfigurationException is thrown if no configuration file exists
using System.IO; using System.Text; using Moq; using Xunit; namespace AppHarbor.Tests { public class ApplicationConfigurationTest { [Fact] public void ShouldReturnApplicationIdIfConfigurationFileExists() { var fileSystem = new Mock<IFileSystem>(); var applicationName = "bar"; var configurationFile = Path.GetFullPath(".appharbor"); var stream = new MemoryStream(Encoding.Default.GetBytes(applicationName)); fileSystem.Setup(x => x.OpenRead(configurationFile)).Returns(stream); var applicationConfiguration = new ApplicationConfiguration(fileSystem.Object); Assert.Equal(applicationName, applicationConfiguration.GetApplicationId()); } } }
using System.IO; using System.Text; using Moq; using Xunit; namespace AppHarbor.Tests { public class ApplicationConfigurationTest { public static string ConfigurationFile = Path.GetFullPath(".appharbor"); [Fact] public void ShouldReturnApplicationIdIfConfigurationFileExists() { var fileSystem = new Mock<IFileSystem>(); var applicationName = "bar"; var configurationFile = ConfigurationFile; var stream = new MemoryStream(Encoding.Default.GetBytes(applicationName)); fileSystem.Setup(x => x.OpenRead(configurationFile)).Returns(stream); var applicationConfiguration = new ApplicationConfiguration(fileSystem.Object); Assert.Equal(applicationName, applicationConfiguration.GetApplicationId()); } [Fact] public void ShouldThrowIfApplicationFileDoesNotExist() { var fileSystem = new InMemoryFileSystem(); var applicationConfiguration = new ApplicationConfiguration(fileSystem); Assert.Throws<ApplicationConfigurationException>(() => applicationConfiguration.GetApplicationId()); } } }
Test IsNearExpiracy while converted ToLocalTime
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Create.CSP.GitHub.Reporting.Entities { public class AuthorizationToken { /// <summary> /// Captures when the token expires /// </summary> public DateTime ExpiresOn { get; set; } /// <summary> /// Access token /// </summary> public string AccessToken { get; private set; } /// <summary> /// Constructor for getting an authorization token /// </summary> /// <param name="access_Token">access token</param> /// <param name="expires_in">number of seconds the token is valid for</param> public AuthorizationToken(string access_Token, long expires_in) { this.AccessToken = access_Token; this.ExpiresOn = DateTime.UtcNow.AddSeconds(expires_in); } public AuthorizationToken(string accessToken, DateTime expiresOn) { this.AccessToken = accessToken; this.ExpiresOn = expiresOn.ToLocalTime(); } /// <summary> /// Returns true if the authorization token is near expiracy. /// </summary> /// <returnsTtrue if the authorization token is near expiracy. False otherwise.</returns> public bool IsNearExpiracy() { //// if token is expiring in the next minute or expired, return true return DateTime.UtcNow > this.ExpiresOn.AddMinutes(-1); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Create.CSP.GitHub.Reporting.Entities { public class AuthorizationToken { /// <summary> /// Captures when the token expires /// </summary> public DateTime ExpiresOn { get; set; } /// <summary> /// Access token /// </summary> public string AccessToken { get; private set; } /// <summary> /// Constructor for getting an authorization token /// </summary> /// <param name="access_Token">access token</param> /// <param name="expires_in">number of seconds the token is valid for</param> public AuthorizationToken(string access_Token, long expires_in) { this.AccessToken = access_Token; this.ExpiresOn = DateTime.UtcNow.AddSeconds(expires_in); } public AuthorizationToken(string accessToken, DateTime expiresOn) { this.AccessToken = accessToken; this.ExpiresOn = expiresOn.ToLocalTime(); } /// <summary> /// Returns true if the authorization token is near expiracy. /// </summary> /// <returnsTtrue if the authorization token is near expiracy. False otherwise.</returns> public bool IsNearExpiracy() { //// if token is expiring in the next minute or expired, return true return DateTime.UtcNow.ToLocalTime() > this.ExpiresOn.AddMinutes(-1); } } }
Add shared project for models for client-server communication.
using System.Threading.Tasks; using Microsoft.AspNet.SignalR; using System.Collections.Generic; using WaveDev.ModelR.Models; using System; using System.Globalization; namespace WaveDev.ModelR.Server { public class ModelRHub : Hub { #region Private Fields private IList<SceneInfoModel> _scenes; #endregion #region Constructor public ModelRHub() { _scenes = new List<SceneInfoModel> { new SceneInfoModel { Id = Guid.NewGuid(), Name = "Scene 1", Description = "The first default scene at the server." }, new SceneInfoModel { Id = Guid.NewGuid(), Name = "Scene 2", Description = "Just another scene." } }; } #endregion #region Public Overrides public override Task OnConnected() { Console.WriteLine(string.Format(CultureInfo.CurrentUICulture, "Client '{0}' connected.", Context.ConnectionId)); return base.OnConnected(); } public override Task OnDisconnected(bool stopCalled) { Console.WriteLine(string.Format(CultureInfo.CurrentUICulture, "Client '{0}' disconnected.", Context.ConnectionId)); return base.OnDisconnected(stopCalled); } #endregion #region Public Hub Methods public IEnumerable<SceneInfoModel> GetAvailableScenes() { return _scenes; } [Authorize] public void JoinSceneGroup(Guid sceneId) { } #endregion } }
using System.Threading.Tasks; using Microsoft.AspNet.SignalR; using System.Collections.Generic; using System; using System.Globalization; using WaveDev.ModelR.Shared.Models; namespace WaveDev.ModelR.Server { public class ModelRHub : Hub { #region Private Fields private IList<SceneInfoModel> _scenes; #endregion #region Constructor public ModelRHub() { _scenes = new List<SceneInfoModel> { new SceneInfoModel { Id = Guid.NewGuid(), Name = "Scene 1", Description = "The first default scene at the server." }, new SceneInfoModel { Id = Guid.NewGuid(), Name = "Scene 2", Description = "Just another scene." } }; } #endregion #region Public Overrides public override Task OnConnected() { Console.WriteLine(string.Format(CultureInfo.CurrentUICulture, "Client '{0}' connected.", Context.ConnectionId)); return base.OnConnected(); } public override Task OnDisconnected(bool stopCalled) { Console.WriteLine(string.Format(CultureInfo.CurrentUICulture, "Client '{0}' disconnected.", Context.ConnectionId)); return base.OnDisconnected(stopCalled); } #endregion #region Public Hub Methods public IEnumerable<SceneInfoModel> GetAvailableScenes() { return _scenes; } [Authorize] public void JoinSceneGroup(Guid sceneId) { } [Authorize] public void CreateSceneObject() { } #endregion } }
Make vision and locomotion required on humanoids
using Alensia.Core.Locomotion; using Alensia.Core.Sensor; using UnityEngine; using UnityEngine.Assertions; using Zenject; namespace Alensia.Core.Character { public class Humanoid : Character<IBinocularVision, ILeggedLocomotion>, IHumanoid { public override Transform Head { get; } public override IBinocularVision Vision { get; } public override ILeggedLocomotion Locomotion { get; } public Humanoid( [InjectOptional] Race race, [InjectOptional] Sex sex, [InjectOptional] IBinocularVision vision, [InjectOptional] ILeggedLocomotion locomotion, Animator animator, Transform transform) : base(race, sex, animator, transform) { Assert.IsNotNull(vision, "vision != null"); Assert.IsNotNull(locomotion, "locomotion != null"); Head = GetBodyPart(HumanBodyBones.Head); Vision = vision; Locomotion = locomotion; } public Transform GetBodyPart(HumanBodyBones bone) => Animator.GetBoneTransform(bone); } }
using Alensia.Core.Locomotion; using Alensia.Core.Sensor; using UnityEngine; using UnityEngine.Assertions; using Zenject; namespace Alensia.Core.Character { public class Humanoid : Character<IBinocularVision, ILeggedLocomotion>, IHumanoid { public override Transform Head { get; } public override IBinocularVision Vision { get; } public override ILeggedLocomotion Locomotion { get; } public Humanoid( [InjectOptional] Race race, [InjectOptional] Sex sex, IBinocularVision vision, ILeggedLocomotion locomotion, Animator animator, Transform transform) : base(race, sex, animator, transform) { Assert.IsNotNull(vision, "vision != null"); Assert.IsNotNull(locomotion, "locomotion != null"); Head = GetBodyPart(HumanBodyBones.Head); Vision = vision; Locomotion = locomotion; } public Transform GetBodyPart(HumanBodyBones bone) => Animator.GetBoneTransform(bone); } }
Build script now creates individual zip file packages to align with the NuGet packages and semantic versioning.
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.18033 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyVersion("3.0.0.0")] [assembly: AssemblyFileVersion("3.0.0.0")] [assembly: AssemblyConfiguration("Release built on 2013-02-22 14:39")] [assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")]
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.18033 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyVersion("3.0.0.0")] [assembly: AssemblyFileVersion("3.0.0.0")] [assembly: AssemblyConfiguration("Release built on 2013-02-28 02:03")] [assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")]
Add toggle play by keyboard input
using UniRx; using UnityEngine; using UnityEngine.UI; public class TogglePlayPresenter : MonoBehaviour { [SerializeField] Button togglePlayButton; [SerializeField] Sprite iconPlay; [SerializeField] Sprite iconPause; NotesEditorModel model; void Awake() { model = NotesEditorModel.Instance; model.OnLoadedMusicObservable.First().Subscribe(_ => Init()); } void Init() { togglePlayButton.OnClickAsObservable() .Subscribe(_ => model.IsPlaying.Value = !model.IsPlaying.Value); model.IsPlaying.DistinctUntilChanged().Subscribe(playing => { var playButtonImage = togglePlayButton.GetComponent<Image>(); if (playing) { model.Audio.Play(); playButtonImage.sprite = iconPause; } else { model.Audio.Pause(); playButtonImage.sprite = iconPlay; } }); } }
using UniRx; using UniRx.Triggers; using UnityEngine; using UnityEngine.UI; public class TogglePlayPresenter : MonoBehaviour { [SerializeField] Button togglePlayButton; [SerializeField] Sprite iconPlay; [SerializeField] Sprite iconPause; NotesEditorModel model; void Awake() { model = NotesEditorModel.Instance; model.OnLoadedMusicObservable.First().Subscribe(_ => Init()); } void Init() { this.UpdateAsObservable() .Where(_ => Input.GetKeyDown(KeyCode.Space)) .Merge(togglePlayButton.OnClickAsObservable()) .Subscribe(_ => model.IsPlaying.Value = !model.IsPlaying.Value); model.IsPlaying.DistinctUntilChanged().Subscribe(playing => { var playButtonImage = togglePlayButton.GetComponent<Image>(); if (playing) { model.Audio.Play(); playButtonImage.sprite = iconPause; } else { model.Audio.Pause(); playButtonImage.sprite = iconPlay; } }); } }
Remove unused `Unavailable` connection state
namespace PusherClient { public enum ConnectionState { Initialized, Connecting, Connected, Unavailable, Disconnected, WaitingToReconnect } }
namespace PusherClient { public enum ConnectionState { Initialized, Connecting, Connected, Disconnected, WaitingToReconnect } }
Exclude Seadragon.config.js from combining because it does substitution.
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; using System.Web.UI; using AjaxControlToolkit; // Dependency Attribute for assemblies [assembly: DependencyAttribute("System.Web,", LoadHint.Always)] [assembly: DependencyAttribute("System.Web.Ajax,", LoadHint.Always)] [assembly: DependencyAttribute("System.Web.Extensions,", LoadHint.Always)] [assembly: SecurityPermission(SecurityAction.RequestMinimum, Execution = true)] [assembly: TagPrefix("AjaxControlToolkit", "asp")] [assembly: AllowPartiallyTrustedCallers] [assembly: ComVisible(false)] [assembly: System.CLSCompliant(true)] [assembly: AssemblyVersion("3.0.31106.*")] [assembly: AssemblyFileVersion("3.0.31106.0")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: ScriptCombine(ExcludeScripts = "Slider.SliderBehavior_resource.js")] // CDN Path // http[s]://ajax.microsoft.com/ajax/beta/0910/extended/*
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; using System.Web.UI; using AjaxControlToolkit; // Dependency Attribute for assemblies [assembly: DependencyAttribute("System.Web,", LoadHint.Always)] [assembly: DependencyAttribute("System.Web.Ajax,", LoadHint.Always)] [assembly: DependencyAttribute("System.Web.Extensions,", LoadHint.Always)] [assembly: SecurityPermission(SecurityAction.RequestMinimum, Execution = true)] [assembly: TagPrefix("AjaxControlToolkit", "asp")] [assembly: AllowPartiallyTrustedCallers] [assembly: ComVisible(false)] [assembly: System.CLSCompliant(true)] [assembly: AssemblyVersion("3.0.31106.*")] [assembly: AssemblyFileVersion("3.0.31106.0")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: ScriptCombine(ExcludeScripts = "Slider.SliderBehavior_resource.js,Seadragon.Seadragon.Config.js")] // CDN Path // http[s]://ajax.microsoft.com/ajax/beta/0910/extended/*
Use GUID for component name
using System; using System.Threading; using WebScriptHook.Framework; using WebScriptHook.Framework.BuiltinPlugins; using WebScriptHook.Terminal.Plugins; namespace WebScriptHook.Terminal { class Program { static WebScriptHookComponent wshComponent; static void Main(string[] args) { string componentName = "testbench"; //Guid.NewGuid().ToString(); wshComponent = new WebScriptHookComponent(componentName, new RemoteSettings("ws", "localhost", "25555", "/componentws")); // Register custom plugins wshComponent.PluginManager.RegisterPlugin(new Echo()); wshComponent.PluginManager.RegisterPlugin(new PluginList()); wshComponent.PluginManager.RegisterPlugin(new PrintToScreen()); // Start WSH component wshComponent.Start(); // Print all registered plugins Console.WriteLine("Registered plugins on \"" + wshComponent.Name + "\":"); var pluginIDs = wshComponent.PluginManager.PluginIDs; foreach (var pluginID in pluginIDs) { Console.WriteLine(pluginID); } // TODO: Use a timer instead of Sleep while (true) { wshComponent.Update(); Thread.Sleep(20); } } } }
using System; using System.Threading; using WebScriptHook.Framework; using WebScriptHook.Framework.BuiltinPlugins; using WebScriptHook.Terminal.Plugins; namespace WebScriptHook.Terminal { class Program { static WebScriptHookComponent wshComponent; static void Main(string[] args) { string componentName = Guid.NewGuid().ToString(); wshComponent = new WebScriptHookComponent(componentName, new RemoteSettings("ws", "localhost", "25555", "/componentws")); // Register custom plugins wshComponent.PluginManager.RegisterPlugin(new Echo()); wshComponent.PluginManager.RegisterPlugin(new PluginList()); wshComponent.PluginManager.RegisterPlugin(new PrintToScreen()); // Start WSH component wshComponent.Start(); // Print all registered plugins Console.WriteLine("Registered plugins on \"" + wshComponent.Name + "\":"); var pluginIDs = wshComponent.PluginManager.PluginIDs; foreach (var pluginID in pluginIDs) { Console.WriteLine(pluginID); } // TODO: Use a timer instead of Sleep while (true) { wshComponent.Update(); Thread.Sleep(20); } } } }
Add primary key to completed steps db table
using Dapper; using RapidCore.Migration; using RapidCore.PostgreSql.Internal; using System.Threading.Tasks; namespace RapidCore.PostgreSql.Migration.Internal { public static class PostgreSqlSchemaCreator { public static async Task CreateSchemaIfNotExists(IMigrationContext context) { var db = ((PostgreSqlMigrationContext)context).ConnectionProvider.Default(); ; await db.ExecuteAsync($@"CREATE TABLE IF NOT EXISTS {PostgreSqlConstants.MigrationInfoTableName} ( id serial not null constraint migrationinfo_pkey primary key, Name varchar(255) unique, MigrationCompleted boolean, TotalMigrationTimeInMs int8, CompletedAtUtc timestamp );"); await db.ExecuteAsync($@"CREATE TABLE IF NOT EXISTS {PostgreSqlConstants.CompletedStepsTableName} ( StepName varchar(255), MigrationInfoId integer references { PostgreSqlConstants.MigrationInfoTableName } (id), unique (StepName, MigrationInfoId) );"); } } }
using Dapper; using RapidCore.Migration; using RapidCore.PostgreSql.Internal; using System.Threading.Tasks; namespace RapidCore.PostgreSql.Migration.Internal { public static class PostgreSqlSchemaCreator { public static async Task CreateSchemaIfNotExists(IMigrationContext context) { var db = ((PostgreSqlMigrationContext)context).ConnectionProvider.Default(); ; await db.ExecuteAsync($@"CREATE TABLE IF NOT EXISTS {PostgreSqlConstants.MigrationInfoTableName} ( id serial not null constraint migrationinfo_pkey primary key, Name varchar(255) unique, MigrationCompleted boolean, TotalMigrationTimeInMs int8, CompletedAtUtc timestamp );"); await db.ExecuteAsync($@"CREATE TABLE IF NOT EXISTS {PostgreSqlConstants.CompletedStepsTableName} ( StepName varchar(255), MigrationInfoId integer references { PostgreSqlConstants.MigrationInfoTableName } (id), PRIMARY KEY (StepName, MigrationInfoId) );"); } } }
Set default value to PropertyMetadata
using System.Windows; using System.Windows.Controls; namespace BindingTest.Control { public partial class CheckboxControl : UserControl { public bool Checked { get { return (bool)GetValue(CheckboxProperty); } set { SetValue(CheckboxProperty, value); _CheckBox.IsChecked = value; } } public static readonly DependencyProperty CheckboxProperty = DependencyProperty.Register( "Checked", typeof(bool), typeof(CheckboxControl), new PropertyMetadata(new PropertyChangedCallback(CheckboxControl.StateChanged))); private static void StateChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { (d as CheckboxControl).Checked = (bool)e.NewValue; } public CheckboxControl() { InitializeComponent(); } private void _CheckBox_Checked(object sender, RoutedEventArgs e) { this.Checked = (bool)(sender as CheckBox).IsChecked; } private void _CheckBox_Unchecked(object sender, RoutedEventArgs e) { this.Checked = (bool)(sender as CheckBox).IsChecked; } } }
using System.Windows; using System.Windows.Controls; namespace BindingTest.Control { public partial class CheckboxControl : UserControl { public bool Checked { get { return (bool)GetValue(CheckboxProperty); } set { SetValue(CheckboxProperty, value); _CheckBox.IsChecked = value; } } public static readonly DependencyProperty CheckboxProperty = DependencyProperty.Register( "Checked", typeof(bool), typeof(CheckboxControl), new PropertyMetadata(false, new PropertyChangedCallback(CheckboxControl.StateChanged))); private static void StateChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { (d as CheckboxControl).Checked = (bool)e.NewValue; } public CheckboxControl() { InitializeComponent(); } private void _CheckBox_Checked(object sender, RoutedEventArgs e) { this.Checked = (bool)(sender as CheckBox).IsChecked; } private void _CheckBox_Unchecked(object sender, RoutedEventArgs e) { this.Checked = (bool)(sender as CheckBox).IsChecked; } } }
Set today as default value
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; namespace TribalWars.Controls { /// <summary> /// Adds addings time functionality to the TimeConverterControl /// </summary> public partial class TimeConverterCalculatorControl : UserControl { #region Constructors public TimeConverterCalculatorControl() { InitializeComponent(); } #endregion #region Event Handlers /// <summary> /// Adds the time to the original date value /// </summary> private void AddTime_Click(object sender, EventArgs e) { if (ToAdd.Value.Hour == 0 && ToAdd.Value.Minute == 0 && ToAdd.Value.Second == 0) { MessageBox.Show("Specify the time in the right box (format: HH:MM:SS (hours, minutes, seconds)) to be added to the time in the box left." + Environment.NewLine + "This can be handy when you need to calculate the time to send your troops."); } else { TimeSpan span = new TimeSpan(ToAdd.Value.Hour, ToAdd.Value.Minute, ToAdd.Value.Second); TimeConverter.Value = TimeConverter.Value.Add(span); } } #endregion } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; namespace TribalWars.Controls { /// <summary> /// Adds addings time functionality to the TimeConverterControl /// </summary> public partial class TimeConverterCalculatorControl : UserControl { #region Constructors public TimeConverterCalculatorControl() { InitializeComponent(); } #endregion protected override void OnLoad(EventArgs e) { base.OnLoad(e); TimeConverter.Value = DateTime.Today; } #region Event Handlers /// <summary> /// Adds the time to the original date value /// </summary> private void AddTime_Click(object sender, EventArgs e) { if (ToAdd.Value.Hour == 0 && ToAdd.Value.Minute == 0 && ToAdd.Value.Second == 0) { MessageBox.Show("Specify the time in the right box (format: HH:MM:SS (hours, minutes, seconds)) to be added to the time in the box left." + Environment.NewLine + "This can be handy when you need to calculate the time to send your troops."); } else { var span = new TimeSpan(ToAdd.Value.Hour, ToAdd.Value.Minute, ToAdd.Value.Second); TimeConverter.Value = TimeConverter.Value.Add(span); } } #endregion } }
Make stacked hitcircles more visible when using default skin
// 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.Graphics.Containers; using osuTK; using osuTK.Graphics; using osu.Framework.Graphics.Shapes; namespace osu.Game.Rulesets.Osu.Objects.Drawables.Pieces { public class RingPiece : CircularContainer { public RingPiece() { Size = new Vector2(OsuHitObject.OBJECT_RADIUS * 2); Anchor = Anchor.Centre; Origin = Anchor.Centre; Masking = true; BorderThickness = 10; BorderColour = Color4.White; Child = new Box { AlwaysPresent = true, Alpha = 0, RelativeSizeAxes = Axes.Both }; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osuTK; using osuTK.Graphics; using osu.Framework.Graphics.Shapes; namespace osu.Game.Rulesets.Osu.Objects.Drawables.Pieces { public class RingPiece : CircularContainer { public RingPiece() { Size = new Vector2(OsuHitObject.OBJECT_RADIUS * 2); Anchor = Anchor.Centre; Origin = Anchor.Centre; Masking = true; BorderThickness = 9; // roughly matches slider borders and makes stacked circles distinctly visible from each other. BorderColour = Color4.White; Child = new Box { AlwaysPresent = true, Alpha = 0, RelativeSizeAxes = Axes.Both }; } } }
Make Cake Bakery resolution case insensitive
using System.IO; using System.Linq; using OmniSharp.Cake.Configuration; namespace OmniSharp.Cake.Services { internal static class ScriptGenerationToolResolver { public static string GetExecutablePath(string rootPath, ICakeConfiguration configuration) { var toolPath = GetToolPath(rootPath, configuration); if (!Directory.Exists(toolPath)) { return string.Empty; } var bakeryPath = GetLatestBakeryPath(toolPath); if (bakeryPath == null) { return string.Empty; } return Path.Combine(toolPath, bakeryPath, "tools", "Cake.Bakery.exe"); } private static string GetToolPath(string rootPath, ICakeConfiguration configuration) { var toolPath = configuration.GetValue(Constants.Paths.Tools); return Path.Combine(rootPath, !string.IsNullOrWhiteSpace(toolPath) ? toolPath : "tools"); } private static string GetLatestBakeryPath(string toolPath) { var directories = Directory.GetDirectories(toolPath, "cake.bakery*", SearchOption.TopDirectoryOnly); // TODO: Sort by semantic version? return directories.OrderByDescending(x => x).FirstOrDefault(); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; using OmniSharp.Cake.Configuration; namespace OmniSharp.Cake.Services { internal static class ScriptGenerationToolResolver { public static string GetExecutablePath(string rootPath, ICakeConfiguration configuration) { var toolPath = GetToolPath(rootPath, configuration); if (!Directory.Exists(toolPath)) { return string.Empty; } var bakeryPath = GetLatestBakeryPath(toolPath); if (bakeryPath == null) { return string.Empty; } return Path.Combine(toolPath, bakeryPath, "tools", "Cake.Bakery.exe"); } private static string GetToolPath(string rootPath, ICakeConfiguration configuration) { var toolPath = configuration.GetValue(Constants.Paths.Tools); return Path.Combine(rootPath, !string.IsNullOrWhiteSpace(toolPath) ? toolPath : "tools"); } private static string GetLatestBakeryPath(string toolPath) { var directories = GetBakeryPaths(toolPath); // TODO: Sort by semantic version? return directories.OrderByDescending(x => x).FirstOrDefault(); } private static IEnumerable<string> GetBakeryPaths(string toolPath) { foreach (var directory in Directory.EnumerateDirectories(toolPath)) { var topDirectory = directory.Split(Path.DirectorySeparatorChar).Last(); if (topDirectory.StartsWith("cake.bakery", StringComparison.OrdinalIgnoreCase)) { yield return topDirectory; } } } } }
Add jQuery mobile loader widget
using System; using PortableRazor; namespace PortableCongress { public class PoliticianController { IHybridWebView webView; IDataAccess dataAccess; public PoliticianController (IHybridWebView webView, IDataAccess dataAccess) { this.webView = webView; this.dataAccess = dataAccess; } public void ShowPoliticianList() { var list = dataAccess.LoadAllPoliticans (); var template = new PoliticianList () { Model = list }; var page = template.GenerateString (); webView.LoadHtmlString (page); } public Politician ShowPoliticianView(int id) { var politician = dataAccess.LoadPolitician (id); var template = new PoliticianView () { Model = politician }; var page = template.GenerateString (); webView.LoadHtmlString (page); return politician; } public async void ShowRecentVotes(int id) { //var votes = dataAccess.LoadRecentVotes (id); var votes = await WebAccess.GetRecentVotesAsync (id); var template = new RecentVotesList () { Model = votes }; var page = template.GenerateString (); webView.LoadHtmlString (page); } } }
using System; using PortableRazor; namespace PortableCongress { public class PoliticianController { IHybridWebView webView; IDataAccess dataAccess; public PoliticianController (IHybridWebView webView, IDataAccess dataAccess) { this.webView = webView; this.dataAccess = dataAccess; } public void ShowPoliticianList() { var list = dataAccess.LoadAllPoliticans (); var template = new PoliticianList () { Model = list }; var page = template.GenerateString (); webView.LoadHtmlString (page); } public Politician ShowPoliticianView(int id) { var politician = dataAccess.LoadPolitician (id); var template = new PoliticianView () { Model = politician }; var page = template.GenerateString (); webView.LoadHtmlString (page); return politician; } public async void ShowRecentVotes(int id) { webView.EvaluateJavascript ("$.mobile.loading( 'show', {\n text: 'Loading Recent Votes ...',\n " + "textVisible: 'false',\n theme: 'b',\n textonly: 'false' });"); var votes = await WebAccess.GetRecentVotesAsync (id); var template = new RecentVotesList () { Model = votes }; var page = template.GenerateString (); webView.LoadHtmlString (page); } } }
Fix naming of MonoMac vs MonoMac 64-bit platform
using System.Reflection; #if XAMMAC2 [assembly: AssemblyTitle("Eto.Forms - Xamarin.Mac v2.0 Platform")] [assembly: AssemblyDescription("OS X Platform for the Eto.Forms UI Framework using Xamarin.Mac v2.0")] #elif XAMMAC [assembly: AssemblyTitle("Eto.Forms - Xamarin.Mac Platform")] [assembly: AssemblyDescription("OS X Platform for the Eto.Forms UI Framework using Xamarin.Mac")] #elif Mac64 [assembly: AssemblyTitle("Eto.Forms - MonoMac Platform")] [assembly: AssemblyDescription("OS X Platform for the Eto.Forms UI Framework using the open-source MonoMac")] #else [assembly: AssemblyTitle("Eto.Forms - MonoMac 64-bit Platform")] [assembly: AssemblyDescription("OS X Platform for the Eto.Forms UI Framework using the open-source MonoMac with 64-bit mono")] #endif
using System.Reflection; #if XAMMAC2 [assembly: AssemblyTitle("Eto.Forms - Xamarin.Mac v2.0 Platform")] [assembly: AssemblyDescription("OS X Platform for the Eto.Forms UI Framework using Xamarin.Mac v2.0")] #elif XAMMAC [assembly: AssemblyTitle("Eto.Forms - Xamarin.Mac Platform")] [assembly: AssemblyDescription("OS X Platform for the Eto.Forms UI Framework using Xamarin.Mac")] #elif Mac64 [assembly: AssemblyTitle("Eto.Forms - MonoMac 64-bit Platform")] [assembly: AssemblyDescription("OS X Platform for the Eto.Forms UI Framework using the open-source MonoMac with 64-bit mono")] #else [assembly: AssemblyTitle("Eto.Forms - MonoMac Platform")] [assembly: AssemblyDescription("OS X Platform for the Eto.Forms UI Framework using the open-source MonoMac")] #endif
Fix issue of wrong counting characters if a text contains newline
using System.Linq; using System.Text.RegularExpressions; namespace Inscribe.Text { public static class TweetTextCounter { public static int Count(string input) { // URL is MAX 20 Chars (if URL has HTTPS scheme, URL is MAX 21 Chars) int prevIndex = 0; int totalCount = 0; foreach (var m in RegularExpressions.UrlRegex.Matches(input).OfType<Match>()) { totalCount += m.Index - prevIndex; prevIndex = m.Index + m.Groups[0].Value.Length; bool isHasHttpsScheme = m.Groups[0].Value.Contains("https"); if (m.Groups[0].Value.Length < TwitterDefine.UrlMaxLength + ((isHasHttpsScheme) ? 1 : 0)) totalCount += m.Groups[0].Value.Length; else totalCount += TwitterDefine.UrlMaxLength + ((isHasHttpsScheme) ? 1 : 0); } totalCount += input.Length - prevIndex; return totalCount; } } }
using System.Linq; using System.Text.RegularExpressions; namespace Inscribe.Text { public static class TweetTextCounter { public static int Count(string input) { // Input maybe contains CRLF as a new line, but twitter converts CRLF to LF. // It means CRLF should be treat as one charator. string inputCRLFProcessed = input.Replace(System.Environment.NewLine, "\n"); // URL is MAX 20 Chars (if URL has HTTPS scheme, URL is MAX 21 Chars) int prevIndex = 0; int totalCount = 0; foreach (var m in RegularExpressions.UrlRegex.Matches(inputCRLFProcessed).OfType<Match>()) { totalCount += m.Index - prevIndex; prevIndex = m.Index + m.Groups[0].Value.Length; bool isHasHttpsScheme = m.Groups[0].Value.Contains("https"); if (m.Groups[0].Value.Length < TwitterDefine.UrlMaxLength + ((isHasHttpsScheme) ? 1 : 0)) totalCount += m.Groups[0].Value.Length; else totalCount += TwitterDefine.UrlMaxLength + ((isHasHttpsScheme) ? 1 : 0); } totalCount += inputCRLFProcessed.Length - prevIndex; return totalCount; } } }
Fix bug by removing duplicate code
using SFA.DAS.Authorization; using System; using System.Linq; using System.Linq.Expressions; using System.Web.Mvc; namespace SFA.DAS.EmployerAccounts.Web.Extensions { public static class HtmlHelperExtensions { public static MvcHtmlString CommaSeperatedAddressToHtml(this HtmlHelper htmlHelper, string commaSeperatedAddress) { var htmlAddress = commaSeperatedAddress.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries) .Select(line => $"{line.Trim()}<br/>") .Aggregate("", (x, y) => x + y); return new MvcHtmlString(htmlAddress); } public static AuthorizationResult GetAuthorizationResult(this HtmlHelper htmlHelper, FeatureType featureType) { var authorisationService = DependencyResolver.Current.GetService<IAuthorizationService>(); var authorizationResult = authorisationService.GetAuthorizationResult(featureType); return authorizationResult; } public static bool IsValid<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression) { var partialFieldName = ExpressionHelper.GetExpressionText(expression); var fullHtmlFieldName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(partialFieldName); if (htmlHelper.ViewData.ModelState.ContainsKey(fullHtmlFieldName)) { var modelState = htmlHelper.ViewData.ModelState[fullHtmlFieldName]; var errors = modelState?.Errors; if (errors != null && errors.Any()) { return false; } } return true; } public static bool ViewExists(this HtmlHelper html, string viewName) { var controllerContext = html.ViewContext.Controller.ControllerContext; var result = ViewEngines.Engines.FindView(controllerContext, viewName, null); return result.View != null; } } }
using SFA.DAS.Authorization; using System; using System.Linq; using System.Web.Mvc; namespace SFA.DAS.EmployerAccounts.Web.Extensions { public static class HtmlHelperExtensions { public static MvcHtmlString CommaSeperatedAddressToHtml(this HtmlHelper htmlHelper, string commaSeperatedAddress) { var htmlAddress = commaSeperatedAddress.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries) .Select(line => $"{line.Trim()}<br/>") .Aggregate("", (x, y) => x + y); return new MvcHtmlString(htmlAddress); } public static AuthorizationResult GetAuthorizationResult(this HtmlHelper htmlHelper, FeatureType featureType) { var authorisationService = DependencyResolver.Current.GetService<IAuthorizationService>(); var authorizationResult = authorisationService.GetAuthorizationResult(featureType); return authorizationResult; } public static bool ViewExists(this HtmlHelper html, string viewName) { var controllerContext = html.ViewContext.Controller.ControllerContext; var result = ViewEngines.Engines.FindView(controllerContext, viewName, null); return result.View != null; } } }
Update GetServiceDirectory() API to use EndpointConfig
/* Empiria Extensions Framework ****************************************************************************** * * * Module : Empiria Web Api Component : Base controllers * * Assembly : Empiria.WebApi.dll Pattern : Web Api Controller * * Type : ServiceDirectoryController License : Please read LICENSE.txt file * * * * Summary : Web api methods to get information about the web service directory. * * * ************************* Copyright(c) La Vía Óntica SC, Ontica LLC and contributors. All rights reserved. **/ using System; using System.Web.Http; using Empiria.Security; namespace Empiria.WebApi.Controllers { /// <summary>Web api methods to get information about the web service directory.</summary> public class ServiceDirectoryController : WebApiController { #region Public APIs /// <summary>Gets a list of available web services in the context of the client application.</summary> /// <returns>A list of services as instances of the type ServiceDirectoryItem.</returns> [HttpGet, AllowAnonymous] [Route("v1/system/service-directory")] public CollectionModel GetServiceDirectory() { try { ClientApplication clientApplication = base.GetClientApplication(); var services = ServiceDirectoryItem.GetList(clientApplication); return new CollectionModel(base.Request, services); } catch (Exception e) { throw base.CreateHttpException(e); } } #endregion Public APIs } // class ServiceDirectoryController } // namespace Empiria.WebApi.Controllers
/* Empiria Extensions Framework ****************************************************************************** * * * Module : Empiria Web Api Component : Base controllers * * Assembly : Empiria.WebApi.dll Pattern : Web Api Controller * * Type : ServiceDirectoryController License : Please read LICENSE.txt file * * * * Summary : Web api methods to get information about the web service directory. * * * ************************* Copyright(c) La Vía Óntica SC, Ontica LLC and contributors. All rights reserved. **/ using System; using System.Web.Http; using Empiria.Security; namespace Empiria.WebApi.Controllers { /// <summary>Web api methods to get information about the web service directory.</summary> public class ServiceDirectoryController : WebApiController { #region Public APIs /// <summary>Gets a list of available web services in the context of the client application.</summary> /// <returns>A list of services as instances of the type ServiceDirectoryItem.</returns> [HttpGet, AllowAnonymous] [Route("v1/system/service-directory")] public CollectionModel GetServiceDirectory() { try { ClientApplication clientApplication = base.GetClientApplication(); var endpointsList = EndpointConfig.GetList(clientApplication); return new CollectionModel(base.Request, endpointsList); } catch (Exception e) { throw base.CreateHttpException(e); } } #endregion Public APIs } // class ServiceDirectoryController } // namespace Empiria.WebApi.Controllers
Allow to specify font in the label constructor
using System.Drawing; using MonoHaven.Graphics; namespace MonoHaven.UI { public class Label : Widget { private string text; private readonly TextBlock textBlock; public Label(Widget parent) : base(parent) { textBlock = new TextBlock(Fonts.Default); } public string Text { get { return text; } set { text = value; textBlock.Clear(); textBlock.Append(text); } } public TextAlign TextAlign { get { return textBlock.TextAlign; } set { textBlock.TextAlign = value; } } public Color TextColor { get { return textBlock.TextColor; } set { textBlock.TextColor = value; } } protected override void OnDraw(DrawingContext dc) { dc.Draw(textBlock, 0, 0, Width, Height); } } }
using System.Drawing; using MonoHaven.Graphics; namespace MonoHaven.UI { public class Label : Widget { private string text; private readonly TextBlock textBlock; public Label(Widget parent, SpriteFont font) : base(parent) { textBlock = new TextBlock(font); textBlock.TextColor = Color.White; SetSize(0, font.Height); } public Label(Widget parent) : this(parent, Fonts.Default) { } public string Text { get { return text; } set { text = value; textBlock.Clear(); textBlock.Append(text); } } public TextAlign TextAlign { get { return textBlock.TextAlign; } set { textBlock.TextAlign = value; } } public Color TextColor { get { return textBlock.TextColor; } set { textBlock.TextColor = value; } } protected override void OnDraw(DrawingContext dc) { dc.Draw(textBlock, 0, 0, Width, Height); } } }
Refactor process to remove FormatException from trace log
using System; using Arkivverket.Arkade.Tests; namespace Arkivverket.Arkade.Core.Addml.Processes { public class AnalyseFindMinMaxValues : IAddmlProcess { public const string Name = "Analyse_FindMinMaxValues"; private readonly TestRun _testRun; private int? _minValue; private int? _maxValue; public AnalyseFindMinMaxValues() { _testRun = new TestRun(Name, TestType.Content); } public string GetName() { return Name; } public void Run(FlatFile flatFile) { } public void Run(Record record) { } public TestRun GetTestRun() { return _testRun; } public void EndOfFile() { string minValueString = _minValue?.ToString() ?? "<no value>"; string maxValueString = _maxValue?.ToString() ?? "<no value>"; _testRun.Add(new TestResult(ResultType.Success, $"MinValue ({minValueString}). MaxValue {maxValueString}.")); } public void Run(Field field) { // TODO: Use type to decide wether field is int? // field.Definition.GetType() try { int value = int.Parse(field.Value); if (!_maxValue.HasValue || value > _maxValue) { _maxValue = value; } if (!_minValue.HasValue || value < _minValue) { _minValue = value; } } catch (FormatException e) { // ignore } } } }
using System; using Arkivverket.Arkade.Tests; namespace Arkivverket.Arkade.Core.Addml.Processes { public class AnalyseFindMinMaxValues : IAddmlProcess { public const string Name = "Analyse_FindMinMaxValues"; private readonly TestRun _testRun; private int? _minValue; private int? _maxValue; public AnalyseFindMinMaxValues() { _testRun = new TestRun(Name, TestType.Content); } public string GetName() { return Name; } public void Run(FlatFile flatFile) { } public void Run(Record record) { } public TestRun GetTestRun() { return _testRun; } public void EndOfFile() { string minValueString = _minValue?.ToString() ?? "<no value>"; string maxValueString = _maxValue?.ToString() ?? "<no value>"; _testRun.Add(new TestResult(ResultType.Success, $"MinValue ({minValueString}). MaxValue {maxValueString}.")); } public void Run(Field field) { // TODO: Use type to decide wether field is int? // field.Definition.GetType() int value; if (!int.TryParse(field.Value, out value)) return; if (!_maxValue.HasValue || value > _maxValue) { _maxValue = value; } if (!_minValue.HasValue || value < _minValue) { _minValue = value; } } } }
Fix styling for users download page
@model Orc.CheckForUpdate.Web.Models.VersionsViewModel @{ ViewBag.Title = "Index"; } @section additionalstyles { @Styles.Render("~/Content/css/downloads") } <h2>Releases</h2> <div> @{ Html.RenderPartial("ReleasesList", Model); } </div>
@model Orc.CheckForUpdate.Web.Models.VersionsViewModel @{ ViewBag.Title = "Index"; } @section additionalstyles { @Styles.Render("~/Content/css/releases") } <h2>Releases</h2> <div> @{ Html.RenderPartial("ReleasesList", Model); } </div>
Set Client Provided Name when creating connection
using EasyRabbitMQ.Configuration; using RabbitMQ.Client; namespace EasyRabbitMQ.Infrastructure { internal class ConnectionFactory : IConnectionFactory { private readonly IConfiguration _configuration; public ConnectionFactory(IConfiguration configuration) { _configuration = configuration; } public IConnection CreateConnection() { var factory = new RabbitMQ.Client.ConnectionFactory { Uri = _configuration.ConnectionString, AutomaticRecoveryEnabled = true }; var connection = factory.CreateConnection(); return connection; } } }
using EasyRabbitMQ.Configuration; using RabbitMQ.Client; namespace EasyRabbitMQ.Infrastructure { internal class ConnectionFactory : IConnectionFactory { private readonly IConfiguration _configuration; private const string ClientProvidedName = "EasyRabbitMQ"; public ConnectionFactory(IConfiguration configuration) { _configuration = configuration; } public IConnection CreateConnection() { var factory = new RabbitMQ.Client.ConnectionFactory { Uri = _configuration.ConnectionString, AutomaticRecoveryEnabled = true }; var connection = factory.CreateConnection(ClientProvidedName); return connection; } } }
Fix weird english in test ignore comment
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Configuration; using osu.Framework.Platform; namespace osu.Framework.Tests.Visual.Platform { [Ignore("This test does not cover correct GL context acquire/release when ran headless.")] public class TestSceneExecutionModes : FrameworkTestScene { private Bindable<ExecutionMode> executionMode; [BackgroundDependencyLoader] private void load(FrameworkConfigManager configManager) { executionMode = configManager.GetBindable<ExecutionMode>(FrameworkSetting.ExecutionMode); } [Test] public void ToggleModeSmokeTest() { AddRepeatStep("toggle execution mode", () => executionMode.Value = executionMode.Value == ExecutionMode.MultiThreaded ? ExecutionMode.SingleThread : ExecutionMode.MultiThreaded, 2); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Configuration; using osu.Framework.Platform; namespace osu.Framework.Tests.Visual.Platform { [Ignore("This test does not cover correct GL context acquire/release when run headless.")] public class TestSceneExecutionModes : FrameworkTestScene { private Bindable<ExecutionMode> executionMode; [BackgroundDependencyLoader] private void load(FrameworkConfigManager configManager) { executionMode = configManager.GetBindable<ExecutionMode>(FrameworkSetting.ExecutionMode); } [Test] public void ToggleModeSmokeTest() { AddRepeatStep("toggle execution mode", () => executionMode.Value = executionMode.Value == ExecutionMode.MultiThreaded ? ExecutionMode.SingleThread : ExecutionMode.MultiThreaded, 2); } } }
Fix - forgot to commit version change to 0.2.1.
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("PinWin")] [assembly: AssemblyDescription("Allows user to make desktop windows top most")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("PinWin")] [assembly: AssemblyCopyright("Copyright © Victor Zakharov 2017")] [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("7ae6966c-0686-4ac4-afbb-9ffd7bf7b81c")] // 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("0.2.0")] [assembly: AssemblyFileVersion("0.2.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("PinWin")] [assembly: AssemblyDescription("Allows user to make desktop windows top most")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("PinWin")] [assembly: AssemblyCopyright("Copyright © Victor Zakharov 2017")] [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("7ae6966c-0686-4ac4-afbb-9ffd7bf7b81c")] // 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("0.2.1")] [assembly: AssemblyFileVersion("0.2.1")]
Reset Y postiions of TabItems before performing layout.
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System; using System.Collections.Generic; using System.Linq; using osu.Framework.Graphics.UserInterface.Tab; using OpenTK; namespace osu.Framework.Graphics.Containers { public class TabFillFlowContainer<T> : FillFlowContainer<T> where T : TabItem { public Action<T, bool> TabVisibilityChanged; protected override IEnumerable<Vector2> ComputeLayoutPositions() { var result = base.ComputeLayoutPositions().ToArray(); int i = 0; foreach (var child in FlowingChildren) { updateChildIfNeeded(child, result[i].Y == 0); ++i; } return result; } private Dictionary<T, bool> previousValues = new Dictionary<T, bool>(); private void updateChildIfNeeded(T child, bool isVisible) { if (!previousValues.ContainsKey(child) || previousValues[child] != isVisible) { TabVisibilityChanged?.Invoke(child, isVisible); previousValues[child] = isVisible; } } } }
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System; using System.Collections.Generic; using System.Linq; using osu.Framework.Graphics.UserInterface.Tab; using OpenTK; namespace osu.Framework.Graphics.Containers { public class TabFillFlowContainer<T> : FillFlowContainer<T> where T : TabItem { public Action<T, bool> TabVisibilityChanged; protected override IEnumerable<Vector2> ComputeLayoutPositions() { foreach (var child in Children) child.Y = 0; var result = base.ComputeLayoutPositions().ToArray(); int i = 0; foreach (var child in FlowingChildren) { updateChildIfNeeded(child, result[i].Y == 0); ++i; } return result; } private Dictionary<T, bool> tabVisibility = new Dictionary<T, bool>(); private void updateChildIfNeeded(T child, bool isVisible) { if (!tabVisibility.ContainsKey(child) || tabVisibility[child] != isVisible) { TabVisibilityChanged?.Invoke(child, isVisible); tabVisibility[child] = isVisible; } } } }
Check if credit card payment received
@using Microsoft.Web.Mvc @model CRP.Controllers.ViewModels.PaymentConfirmationViewModel @{ ViewBag.Title = "Confirmation"; } <div class="boundary"> <h2>Registration Confirmation</h2> <p>You have successfully registered for the following event:</p> <div> <label>Item: </label> @Model.Transaction.Item.Name </div> <div> <label>Transaction: </label> @Model.Transaction.TransactionNumber </div> <div> <label>Amount: </label> @($"{Model.Transaction.Total:C}") </div> @if (Model.Transaction.Credit) { <div> <p>Payment is still due:</p> <form action="@Model.PostUrl" method="post" autocomplete="off" style="margin-right: 3px"> @foreach (var pair in Model.PaymentDictionary) { <input type="hidden" name="@pair.Key" value="@pair.Value"/> } <input type="hidden" name="signature" value="@Model.Signature"/> <input type="submit" class="btn btn-primary" value="Click here to be taken to our payment site"/> </form> </div> } else if (Model.Transaction.Total > 0) { <div> @Html.Raw(Model.Transaction.Item.CheckPaymentInstructions) </div> } </div>
@using Microsoft.Web.Mvc @model CRP.Controllers.ViewModels.PaymentConfirmationViewModel @{ ViewBag.Title = "Confirmation"; } <div class="boundary"> <h2>Registration Confirmation</h2> <p>You have successfully registered for the following event:</p> <div> <label>Item: </label> @Model.Transaction.Item.Name </div> <div> <label>Transaction: </label> @Model.Transaction.TransactionNumber </div> <div> <label>Amount: </label> @($"{Model.Transaction.Total:C}") </div> @if (Model.Transaction.Credit) { <div> @if (Model.Transaction.Paid) { <div class="alert alert-danger"> <button type="button" class="close" data-dismiss="alert">×</button> It appears this has been paid. If you think it hasn't you may still pay. </div> } else { <p>Payment is still due:</p> } <form action="@Model.PostUrl" method="post" autocomplete="off" style="margin-right: 3px"> @foreach (var pair in Model.PaymentDictionary) { <input type="hidden" name="@pair.Key" value="@pair.Value"/> } <input type="hidden" name="signature" value="@Model.Signature"/> <input type="submit" class="btn btn-primary" value="Click here to be taken to our payment site"/> </form> </div> } else if (Model.Transaction.Total > 0) { <div> @Html.Raw(Model.Transaction.Item.CheckPaymentInstructions) </div> } </div>
Fix Stylecop failure - long line
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using Microsoft.AspNet.Mvc.OptionDescriptors; using Microsoft.Framework.DependencyInjection; using Microsoft.Framework.OptionsModel; namespace Microsoft.AspNet.Mvc { /// <inheritdoc /> public class DefaultOutputFormattersProvider : OptionDescriptorBasedProvider<IOutputFormatter>, IOutputFormattersProvider { /// <summary> /// Initializes a new instance of the DefaultOutputFormattersProvider class. /// </summary> /// <param name="options">An accessor to the <see cref="MvcOptions"/> configured for this application.</param> /// <param name="typeActivator">An <see cref="ITypeActivator"/> instance used to instantiate types.</param> /// <param name="serviceProvider">A <see cref="IServiceProvider"/> instance that retrieves services from the /// service collection.</param> public DefaultOutputFormattersProvider(IOptionsAccessor<MvcOptions> optionsAccessor, ITypeActivator typeActivator, IServiceProvider serviceProvider) : base(optionsAccessor.Options.OutputFormatters, typeActivator, serviceProvider) { } /// <inheritdoc /> public IReadOnlyList<IOutputFormatter> OutputFormatters { get { return Options; } } } }
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using Microsoft.AspNet.Mvc.OptionDescriptors; using Microsoft.Framework.DependencyInjection; using Microsoft.Framework.OptionsModel; namespace Microsoft.AspNet.Mvc { /// <inheritdoc /> public class DefaultOutputFormattersProvider : OptionDescriptorBasedProvider<IOutputFormatter>, IOutputFormattersProvider { /// <summary> /// Initializes a new instance of the DefaultOutputFormattersProvider class. /// </summary> /// <param name="options">An accessor to the <see cref="MvcOptions"/> configured for this application.</param> /// <param name="typeActivator">An <see cref="ITypeActivator"/> instance used to instantiate types.</param> /// <param name="serviceProvider">A <see cref="IServiceProvider"/> instance that retrieves services from the /// service collection.</param> public DefaultOutputFormattersProvider(IOptionsAccessor<MvcOptions> optionsAccessor, ITypeActivator typeActivator, IServiceProvider serviceProvider) : base(optionsAccessor.Options.OutputFormatters, typeActivator, serviceProvider) { } /// <inheritdoc /> public IReadOnlyList<IOutputFormatter> OutputFormatters { get { return Options; } } } }
Disable command debugging for now, and clean up.
#define DEBUG_COMMANDS //using UnityEditor; //using UnityEngine; //using System.Collections; using System.Diagnostics; public class ShellHelpers { public static Process StartProcess(string filename, string arguments) { #if DEBUG_COMMANDS UnityEngine.Debug.Log("Running: " + filename + " " + arguments); #endif Process p = new Process(); p.StartInfo.Arguments = arguments; p.StartInfo.CreateNoWindow = true; p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardInput = true; p.StartInfo.RedirectStandardError = true; p.StartInfo.FileName = filename; p.Start(); return p; } public static string OutputFromCommand(string filename, string arguments) { var p = StartProcess(filename, arguments); var output = p.StandardOutput.ReadToEnd(); p.WaitForExit(); if(output.EndsWith("\n")) output = output.Substring(0, output.Length - 1); return output; } }
//define DEBUG_COMMANDS using System.Diagnostics; public class ShellHelpers { public static Process StartProcess(string filename, string arguments) { #if DEBUG_COMMANDS UnityEngine.Debug.Log("Running: " + filename + " " + arguments); #endif Process p = new Process(); p.StartInfo.Arguments = arguments; p.StartInfo.CreateNoWindow = true; p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardInput = true; p.StartInfo.RedirectStandardError = true; p.StartInfo.FileName = filename; p.Start(); return p; } public static string OutputFromCommand(string filename, string arguments) { var p = StartProcess(filename, arguments); var output = p.StandardOutput.ReadToEnd(); p.WaitForExit(); if(output.EndsWith("\n")) output = output.Substring(0, output.Length - 1); return output; } }
Set OperationId via annotations in test project
using Microsoft.AspNetCore.Mvc; using Swashbuckle.AspNetCore.Annotations; using Basic.Swagger; namespace Basic.Controllers { [SwaggerTag("Manipulate Carts to your heart's content", "http://www.tempuri.org")] public class SwaggerAnnotationsController { [HttpPost("/carts")] [SwaggerResponse(201, "The cart was created", typeof(Cart))] [SwaggerResponse(400, "The cart data is invalid")] public Cart Create([FromBody]Cart cart) { return new Cart { Id = 1 }; } [HttpGet("/carts/{id}")] [SwaggerOperationFilter(typeof(AddCartsByIdGetExternalDocs))] public Cart GetById(int id) { return new Cart { Id = id }; } [HttpDelete("/carts/{id}")] [SwaggerOperation( Summary = "Deletes a specific cart", Description = "Requires admin privileges", Consumes = new string[] { "test/plain", "application/json" }, Produces = new string[] { "application/javascript", "application/xml" })] public Cart Delete([FromRoute(Name = "id"), SwaggerParameter("The cart identifier")]int cartId) { return new Cart { Id = cartId }; } } public class Cart { public int Id { get; internal set; } } }
using Microsoft.AspNetCore.Mvc; using Swashbuckle.AspNetCore.Annotations; using Basic.Swagger; namespace Basic.Controllers { [SwaggerTag("Manipulate Carts to your heart's content", "http://www.tempuri.org")] public class SwaggerAnnotationsController { [HttpPost("/carts")] [SwaggerResponse(201, "The cart was created", typeof(Cart))] [SwaggerResponse(400, "The cart data is invalid")] public Cart Create([FromBody]Cart cart) { return new Cart { Id = 1 }; } [HttpGet("/carts/{id}")] [SwaggerOperationFilter(typeof(AddCartsByIdGetExternalDocs))] public Cart GetById(int id) { return new Cart { Id = id }; } [HttpDelete("/carts/{id}")] [SwaggerOperation( OperationId = "DeleteCart", Summary = "Deletes a specific cart", Description = "Requires admin privileges", Consumes = new string[] { "test/plain", "application/json" }, Produces = new string[] { "application/javascript", "application/xml" })] public Cart Delete([FromRoute(Name = "id"), SwaggerParameter("The cart identifier")]int cartId) { return new Cart { Id = cartId }; } } public class Cart { public int Id { get; internal set; } } }
Set nuget package version to 2.0.0
using System.Reflection; // 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("CakeMail.RestClient")] [assembly: AssemblyDescription("CakeMail.RestClient is a .NET wrapper for the CakeMail API")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Jeremie Desautels")] [assembly: AssemblyProduct("CakeMail.RestClient")] [assembly: AssemblyCopyright("Copyright Jeremie Desautels © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 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("2.0.0.0")] [assembly: AssemblyFileVersion("2.0.0.0")] [assembly: AssemblyInformationalVersion("2.0.0-beta03")]
using System.Reflection; // 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("CakeMail.RestClient")] [assembly: AssemblyDescription("CakeMail.RestClient is a .NET wrapper for the CakeMail API")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Jeremie Desautels")] [assembly: AssemblyProduct("CakeMail.RestClient")] [assembly: AssemblyCopyright("Copyright Jeremie Desautels © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 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("2.0.0.0")] [assembly: AssemblyFileVersion("2.0.0.0")] [assembly: AssemblyInformationalVersion("2.0.0")]
Add another unit test for an MSBuild project (currently failing)
using System.IO; using Microsoft.Extensions.Logging; using OmniSharp.MSBuild.ProjectFile; using TestUtility; using Xunit; using Xunit.Abstractions; namespace OmniSharp.MSBuild.Tests { public class ProjectFileInfoTests { private readonly TestAssets _testAssets; private readonly ILogger _logger; public ProjectFileInfoTests(ITestOutputHelper output) { this._testAssets = TestAssets.Instance; this._logger = new TestLogger(output); MSBuildEnvironment.Initialize(this._logger); } [Fact] public void Hello_world_has_correct_property_values() { var projectFolder = _testAssets.GetTestProjectFolder("HelloWorld"); var projectFilePath = Path.Combine(projectFolder, "HelloWorld.csproj"); var projectFileInfo = ProjectFileInfo.Create(projectFilePath, projectFolder, this._logger); Assert.NotNull(projectFileInfo); Assert.Equal(projectFilePath, projectFileInfo.ProjectFilePath); Assert.Equal(1, projectFileInfo.TargetFrameworks.Count); Assert.Equal(".NETCoreApp,Version=v1.0", projectFileInfo.TargetFrameworks[0].DotNetFrameworkName); } } }
using System.IO; using Microsoft.Extensions.Logging; using OmniSharp.MSBuild.ProjectFile; using TestUtility; using Xunit; using Xunit.Abstractions; namespace OmniSharp.MSBuild.Tests { public class ProjectFileInfoTests { private readonly TestAssets _testAssets; private readonly ILogger _logger; public ProjectFileInfoTests(ITestOutputHelper output) { this._testAssets = TestAssets.Instance; this._logger = new TestLogger(output); MSBuildEnvironment.Initialize(this._logger); } [Fact] public void HelloWorld_has_correct_property_values() { var projectFolder = _testAssets.GetTestProjectFolder("HelloWorld"); var projectFilePath = Path.Combine(projectFolder, "HelloWorld.csproj"); var projectFileInfo = ProjectFileInfo.Create(projectFilePath, projectFolder, this._logger); Assert.NotNull(projectFileInfo); Assert.Equal(projectFilePath, projectFileInfo.ProjectFilePath); Assert.Equal(1, projectFileInfo.TargetFrameworks.Count); Assert.Equal(".NETCoreApp,Version=v1.0", projectFileInfo.TargetFrameworks[0].DotNetFrameworkName); } [Fact] public void NetStandardAndNetCoreApp_has_correct_property_values() { var projectFolder = _testAssets.GetTestProjectFolder("NetStandardAndNetCoreApp"); var projectFilePath = Path.Combine(projectFolder, "NetStandardAndNetCoreApp.csproj"); var projectFileInfo = ProjectFileInfo.Create(projectFilePath, projectFolder, this._logger); Assert.NotNull(projectFileInfo); Assert.Equal(projectFilePath, projectFileInfo.ProjectFilePath); Assert.Equal(1, projectFileInfo.TargetFrameworks.Count); Assert.Equal(".NETCoreApp,Version=v1.0", projectFileInfo.TargetFrameworks[0].DotNetFrameworkName); } } }
Add a check for api keys in query parameters.
using jab.Attributes; using NSwag; using Xunit; using System.Linq; namespace jab { public class TestExample { [Theory, ParameterisedClassData(typeof(ApiOperations), "samples/example.json")] public void DeleteMethodsShouldNotTakeFormEncodedData( SwaggerService service, string path, SwaggerOperationMethod method, SwaggerOperation operation) { if (method == SwaggerOperationMethod.Delete) { Assert.Null(operation.ActualConsumes); } else { Assert.True(true); } } } }
using jab.Attributes; using NSwag; using Xunit; using System.Linq; namespace jab { public partial class TestExample { const string testDefinition = "samples/example.json"; [Theory, ParameterisedClassData(typeof(ApiOperations), testDefinition)] public void DeleteMethodsShouldNotTakeFormEncodedData( SwaggerService service, string path, SwaggerOperationMethod method, SwaggerOperation operation) { if (method == SwaggerOperationMethod.Delete) { Assert.Null(operation.ActualConsumes); } else { Assert.True(true); } } /// <summary> /// You should not ask for api keys in query parameters. /// https://www.owasp.org/index.php/REST_Security_Cheat_Sheet#Authentication_and_session_management /// </summary> /// <param name="service"></param> /// <param name="path"></param> /// <param name="method"></param> /// <param name="operation"></param> [Theory, ParameterisedClassData(typeof(ApiOperations), testDefinition)] public void NoApiKeysInParameters( SwaggerService service, string path, SwaggerOperationMethod method, SwaggerOperation operation) { if (operation.ActualParameters.Count > 0) { Assert.False( operation.Parameters.Count( c => ((c.Name.ToLower() == "apikey") || (c.Name.ToLower() == "api_key")) && c.Kind == SwaggerParameterKind.Query) > 0); } else { Assert.True(true); } } } }
Add global keyboard shortcut listener
using System.Windows.Input; namespace clipman.Settings { public static class Keyboard { public static Key ClearTextboxKey = Key.Escape; } }
using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Windows.Input; using System.Windows.Interop; namespace clipman.Settings { public static class Keyboard { public static Key ClearTextboxKey = Key.Escape; } public class KeyboardMonitor : IDisposable { private bool disposed = false; private static class NativeMethods { [DllImport("User32.dll")] public static extern bool RegisterHotKey( [In] IntPtr hWnd, [In] int id, [In] uint fsModifiers, [In] uint vk ); [DllImport("User32.dll")] public static extern bool UnregisterHotKey( [In] IntPtr hWnd, [In] int id ); public const int WM_HOTKEY = 0x0312; /// <summary> /// To find message-only windows, specify HWND_MESSAGE in the hwndParent parameter of the FindWindowEx function. /// </summary> public static IntPtr HWND_MESSAGE = new IntPtr(-3); } public class HotkeyEventArgs : EventArgs { public int HotkeyId { get; set; } } private HwndSource hwndSource = new HwndSource(0, 0, 0, 0, 0, 0, 0, null, NativeMethods.HWND_MESSAGE); private List<int> hotkeyIds = new List<int>(); public KeyboardMonitor() { hwndSource.AddHook(WndProc); } public int AddHotkey(int modifier, int key) { int id = hotkeyIds.Count + 9000; hotkeyIds.Add(id); NativeMethods.RegisterHotKey(hwndSource.Handle, id, (uint)modifier, (uint)key); return id; } private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) { if (msg == NativeMethods.WM_HOTKEY) { Utility.Logging.Log("WM_HOTKEY"); if (hotkeyIds.Contains(wParam.ToInt32())) { handled = true; var args = new HotkeyEventArgs(); args.HotkeyId = wParam.ToInt32(); KeyPressed?.Invoke(this, args); } } return IntPtr.Zero; } public void Dispose() { if (!disposed) { foreach (var id in hotkeyIds) { NativeMethods.UnregisterHotKey(hwndSource.Handle, id); } } } public event EventHandler<HotkeyEventArgs> KeyPressed; } }
Fix test which relies on reflection over the code fixes assembly
// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. namespace StyleCop.Analyzers.Test { using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeFixes; using StyleCop.Analyzers.ReadabilityRules; using Xunit; public class ExportCodeFixProviderAttributeNameTest { public static IEnumerable<object[]> CodeFixProviderTypeData { get { var codeFixProviders = typeof(SA1110OpeningParenthesisMustBeOnDeclarationLine) .Assembly .GetTypes() .Where(t => typeof(CodeFixProvider).IsAssignableFrom(t)); return codeFixProviders.Select(x => new[] { x }); } } [Theory] [MemberData(nameof(CodeFixProviderTypeData))] public void TestExportCodeFixProviderAttribute(Type codeFixProvider) { var exportCodeFixProviderAttribute = codeFixProvider.GetCustomAttributes<ExportCodeFixProviderAttribute>(false).FirstOrDefault(); Assert.NotNull(exportCodeFixProviderAttribute); Assert.Equal(codeFixProvider.Name, exportCodeFixProviderAttribute.Name); Assert.Equal(1, exportCodeFixProviderAttribute.Languages.Length); Assert.Equal(LanguageNames.CSharp, exportCodeFixProviderAttribute.Languages[0]); } } }
// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. namespace StyleCop.Analyzers.Test { using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Analyzers.SpacingRules; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeFixes; using Xunit; public class ExportCodeFixProviderAttributeNameTest { public static IEnumerable<object[]> CodeFixProviderTypeData { get { var codeFixProviders = typeof(TokenSpacingCodeFixProvider) .Assembly .GetTypes() .Where(t => typeof(CodeFixProvider).IsAssignableFrom(t)); return codeFixProviders.Select(x => new[] { x }); } } [Theory] [MemberData(nameof(CodeFixProviderTypeData))] public void TestExportCodeFixProviderAttribute(Type codeFixProvider) { var exportCodeFixProviderAttribute = codeFixProvider.GetCustomAttributes<ExportCodeFixProviderAttribute>(false).FirstOrDefault(); Assert.NotNull(exportCodeFixProviderAttribute); Assert.Equal(codeFixProvider.Name, exportCodeFixProviderAttribute.Name); Assert.Equal(1, exportCodeFixProviderAttribute.Languages.Length); Assert.Equal(LanguageNames.CSharp, exportCodeFixProviderAttribute.Languages[0]); } } }
Increase timeout for Timer tests
using System; using System.Threading; using Xunit; using Should; using Timer = SlackConnector.Connections.Monitoring.Timer; namespace SlackConnector.Tests.Unit.Connections.Monitoring { public class TimerTests { [Fact] public void should_run_task_at_least_5_times() { // given var timer = new Timer(); int calls = 0; DateTime timeout = DateTime.Now.AddSeconds(4); // when timer.RunEvery(() => calls++, TimeSpan.FromMilliseconds(1)); while (calls < 5 && DateTime.Now < timeout) { Thread.Sleep(TimeSpan.FromMilliseconds(5)); } // then calls.ShouldBeGreaterThanOrEqualTo(5); } [Fact] public void should_throw_exception_if_a_second_timer_is_created() { // given var timer = new Timer(); timer.RunEvery(() => { }, TimeSpan.FromMilliseconds(1)); // when + then Assert.Throws<Timer.TimerAlreadyInitialisedException>(() => timer.RunEvery(() => { }, TimeSpan.FromMinutes(1))); } } }
using System; using System.Threading; using Xunit; using Should; using Timer = SlackConnector.Connections.Monitoring.Timer; namespace SlackConnector.Tests.Unit.Connections.Monitoring { public class TimerTests { [Fact] public void should_run_task_at_least_5_times() { // given var timer = new Timer(); int calls = 0; DateTime timeout = DateTime.Now.AddSeconds(20); // when timer.RunEvery(() => calls++, TimeSpan.FromMilliseconds(1)); while (calls < 5 && DateTime.Now < timeout) { Thread.Sleep(TimeSpan.FromMilliseconds(5)); } // then calls.ShouldBeGreaterThanOrEqualTo(5); } [Fact] public void should_throw_exception_if_a_second_timer_is_created() { // given var timer = new Timer(); timer.RunEvery(() => { }, TimeSpan.FromMilliseconds(1)); // when + then Assert.Throws<Timer.TimerAlreadyInitialisedException>(() => timer.RunEvery(() => { }, TimeSpan.FromMinutes(1))); } } }
Fix REST API url in documentation
using System.Collections.Generic; using System.Linq; using TimeLog.Api.Core.Documentation.Models.RestDocumentationHelpers.Core; namespace TimeLog.Api.Core.Documentation.Models.RestDocumentationHelpers { public class RestMethodDoc { #region Variables public IReadOnlyList<RestResponse> Responses { get; } public IReadOnlyList<RestMethodParam> Params { get; } public string MethodType { get; } public RestTypeDoc Parent { get; } public string OperationId { get; } public string FullName { get; } public string Summary { get; } public string Name { get; } #endregion #region Constructor public RestMethodDoc(RestTypeDoc restTypeDoc, RestAction action) { OperationId = action.OperationId; FullName = $"http://app[x].timelog.com/[account name]{action.Name}"; Name = action.OperationId.Replace($"{action.Tags[0]}_", ""); Summary = action.Summary; MethodType = action.MethodType.ToUpper(); Parent = restTypeDoc; Params = MapToMethodParam(action.Parameters); Responses = action.Responses.OrderBy(x => x.Code).ToList(); } #endregion #region Internal and Private Implementations private IReadOnlyList<RestMethodParam> MapToMethodParam(IReadOnlyList<RestParameter> parameters) { return parameters .Select(x => new RestMethodParam(x.Name, x.Description, x.Type, x.SchemaRestRef)) .ToList(); } #endregion } }
using System.Collections.Generic; using System.Linq; using TimeLog.Api.Core.Documentation.Models.RestDocumentationHelpers.Core; namespace TimeLog.Api.Core.Documentation.Models.RestDocumentationHelpers { public class RestMethodDoc { #region Variables public IReadOnlyList<RestResponse> Responses { get; } public IReadOnlyList<RestMethodParam> Params { get; } public string MethodType { get; } public RestTypeDoc Parent { get; } public string OperationId { get; } public string FullName { get; } public string Summary { get; } public string Name { get; } #endregion #region Constructor public RestMethodDoc(RestTypeDoc restTypeDoc, RestAction action) { OperationId = action.OperationId; FullName = $"https://app[x].timelog.com/[account name]/api{action.Name}"; Name = action.OperationId.Replace($"{action.Tags[0]}_", ""); Summary = action.Summary; MethodType = action.MethodType.ToUpper(); Parent = restTypeDoc; Params = MapToMethodParam(action.Parameters); Responses = action.Responses.OrderBy(x => x.Code).ToList(); } #endregion #region Internal and Private Implementations private IReadOnlyList<RestMethodParam> MapToMethodParam(IReadOnlyList<RestParameter> parameters) { return parameters .Select(x => new RestMethodParam(x.Name, x.Description, x.Type, x.SchemaRestRef)) .ToList(); } #endregion } }
Mark the eight-byte-boundaries when dumping a message
using System; using System.Buffers; namespace Dbus { internal static class ExtensionMethods { public static void Dump(this ReadOnlySequence<byte> buffers) { foreach (var segment in buffers) { var buffer = segment.Span; dump(buffer); } Console.WriteLine(); } public static void Dump(this Span<byte> memory) { dump(memory); Console.WriteLine(); } private static void dump(this ReadOnlySpan<byte> buffer) { for (var i = 0; i < buffer.Length; ++i) { var isDigitOrAsciiLetter = false; isDigitOrAsciiLetter |= 48 <= buffer[i] && buffer[i] <= 57; isDigitOrAsciiLetter |= 65 <= buffer[i] && buffer[i] <= 90; isDigitOrAsciiLetter |= 97 <= buffer[i] && buffer[i] <= 122; if (isDigitOrAsciiLetter) Console.Write($"{(char)buffer[i]} "); else Console.Write($"x{buffer[i]:X} "); } } } }
using System; using System.Buffers; namespace Dbus { internal static class ExtensionMethods { public static void Dump(this ReadOnlySequence<byte> buffers) { var counter = 0; foreach (var segment in buffers) { var buffer = segment.Span; dump(buffer, ref counter); } Console.WriteLine(); } public static void Dump(this Span<byte> memory) { var counter = 0; dump(memory, ref counter); Console.WriteLine(); } private static void dump(this ReadOnlySpan<byte> buffer, ref int counter) { for (var i = 0; i < buffer.Length; ++i) { var isDigitOrAsciiLetter = false; isDigitOrAsciiLetter |= 48 <= buffer[i] && buffer[i] <= 57; isDigitOrAsciiLetter |= 65 <= buffer[i] && buffer[i] <= 90; isDigitOrAsciiLetter |= 97 <= buffer[i] && buffer[i] <= 122; if (isDigitOrAsciiLetter) Console.Write($"{(char)buffer[i]} "); else Console.Write($"x{buffer[i]:X} "); counter += 1; if ((counter & 7) == 0) Console.Write("| "); } } } }
Add access tests for all nullable types.
/* Copyright 2015 Realm Inc - All Rights Reserved * Proprietary and Confidential */ using System.IO; using NUnit.Framework; using Realms; namespace IntegrationTests.Shared { [TestFixture] public class AccessTests { protected string _databasePath; protected Realm _realm; [SetUp] public void Setup() { _databasePath = Path.GetTempFileName(); _realm = Realm.GetInstance(_databasePath); } [TearDown] public void TearDown() { _realm.Dispose(); } [Test] public void SetValueAndReplaceWithNull() { AllTypesObject ato; using (var transaction = _realm.BeginWrite()) { ato = _realm.CreateObject<AllTypesObject>(); TestHelpers.SetPropertyValue(ato, "NullableBooleanProperty", true); transaction.Commit(); } Assert.That(ato.NullableBooleanProperty, Is.EqualTo(true)); using (var transaction = _realm.BeginWrite()) { TestHelpers.SetPropertyValue(ato, "NullableBooleanProperty", null); transaction.Commit(); } Assert.That(ato.NullableBooleanProperty, Is.EqualTo(null)); } } }
/* Copyright 2015 Realm Inc - All Rights Reserved * Proprietary and Confidential */ using System.IO; using NUnit.Framework; using Realms; namespace IntegrationTests.Shared { [TestFixture] public class AccessTests { protected string _databasePath; protected Realm _realm; [SetUp] public void Setup() { _databasePath = Path.GetTempFileName(); _realm = Realm.GetInstance(_databasePath); } [TearDown] public void TearDown() { _realm.Dispose(); } [TestCase("NullableCharProperty", '0')] [TestCase("NullableByteProperty", (byte)100)] [TestCase("NullableInt16Property", (short)100)] [TestCase("NullableInt32Property", 100)] [TestCase("NullableInt64Property", 100L)] [TestCase("NullableSingleProperty", 123.123f)] [TestCase("NullableDoubleProperty", 123.123)] [TestCase("NullableBooleanProperty", true)] public void SetValueAndReplaceWithNull(string propertyName, object propertyValue) { AllTypesObject ato; using (var transaction = _realm.BeginWrite()) { ato = _realm.CreateObject<AllTypesObject>(); TestHelpers.SetPropertyValue(ato, propertyName, propertyValue); transaction.Commit(); } Assert.That(TestHelpers.GetPropertyValue(ato, propertyName), Is.EqualTo(propertyValue)); using (var transaction = _realm.BeginWrite()) { TestHelpers.SetPropertyValue(ato, propertyName, null); transaction.Commit(); } Assert.That(ato.NullableBooleanProperty, Is.EqualTo(null)); } } }
Remove redundant case from switch statement
using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation.Language; namespace Microsoft.PowerShell.EditorServices { internal class PesterDocumentSymbolProvider : DocumentSymbolProvider { protected override bool CanProvideFor(ScriptFile scriptFile) { return scriptFile.FilePath.EndsWith("tests.ps1", StringComparison.OrdinalIgnoreCase); } protected override IEnumerable<SymbolReference> GetSymbolsImpl(ScriptFile scriptFile, Version psVersion) { var commandAsts = scriptFile.ScriptAst.FindAll(ast => { switch ((ast as CommandAst)?.GetCommandName().ToLower()) { case "describe": case "context": case "it": return true; case null: default: return false; } }, true); return commandAsts.Select(ast => new SymbolReference( SymbolType.Function, ast.Extent, scriptFile.FilePath, scriptFile.GetLine(ast.Extent.StartLineNumber))); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation.Language; namespace Microsoft.PowerShell.EditorServices { internal class PesterDocumentSymbolProvider : DocumentSymbolProvider { protected override bool CanProvideFor(ScriptFile scriptFile) { return scriptFile.FilePath.EndsWith("tests.ps1", StringComparison.OrdinalIgnoreCase); } protected override IEnumerable<SymbolReference> GetSymbolsImpl(ScriptFile scriptFile, Version psVersion) { var commandAsts = scriptFile.ScriptAst.FindAll(ast => { switch ((ast as CommandAst)?.GetCommandName().ToLower()) { case "describe": case "context": case "it": return true; default: return false; } }, true); return commandAsts.Select(ast => new SymbolReference( SymbolType.Function, ast.Extent, scriptFile.FilePath, scriptFile.GetLine(ast.Extent.StartLineNumber))); } } }
Set current directory when running as a service.
using System; using System.Collections.Generic; using System.Linq; using System.ServiceProcess; using System.Text; namespace SteamIrcBot { static class Program { /// <summary> /// The main entry point for the application. /// </summary> static void Main( string[] args ) { AppDomain.CurrentDomain.UnhandledException += ( sender, e ) => { Log.WriteError( "Program", "Unhandled exception (IsTerm: {0}): {1}", e.IsTerminating, e.ExceptionObject ); }; var service = new BotService(); #if SERVICE_BUILD ServiceBase.Run( service ); #else service.Start( args ); #endif } } }
using System; using System.Collections.Generic; using System.Linq; using System.ServiceProcess; using System.Text; using System.Reflection; using System.IO; namespace SteamIrcBot { static class Program { /// <summary> /// The main entry point for the application. /// </summary> static void Main( string[] args ) { string path = Assembly.GetExecutingAssembly().Location; path = Path.GetDirectoryName( path ); Directory.SetCurrentDirectory( path ); AppDomain.CurrentDomain.UnhandledException += ( sender, e ) => { Log.WriteError( "Program", "Unhandled exception (IsTerm: {0}): {1}", e.IsTerminating, e.ExceptionObject ); }; var service = new BotService(); #if SERVICE_BUILD ServiceBase.Run( service ); #else service.Start( args ); #endif } } }
Fix datetime json ext - lost one millisecond
using System; namespace MK.Ext { /// <summary> /// DateTime Json Extensions /// </summary> public static class DateTimeJsonExt { private static readonly DateTime D1970_01_01 = new DateTime(1970, 1, 1); public static string JsonValue(this DateTime d) { return "( new Date(" + System.Convert.ToInt64((d - D1970_01_01).TotalMilliseconds) + "))"; } } }
using System; namespace MK.Ext { /// <summary> /// DateTime Json Extensions /// </summary> public static class DateTimeJsonExt { private static readonly DateTime D1970_01_01 = new DateTime(1970, 1, 1); public static string JsonValue(this DateTime d) { return "( new Date(" + ((d.Ticks - D1970_01_01.Ticks) / 10000) + "))"; } } }
Change the page title and h1.
@{ Layout = null; } <!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap 101 Template</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Bootstrap --> <link href="assets/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet" media="screen"> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script> <![endif]--> </head> <body> <h1>Hello, world!</h1> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="https://code.jquery.com/jquery.js"></script> <!-- Include all compiled plugins (below), or include individual files as needed --> <script src="assets/bootstrap/dist/js/bootstrap.min.js"></script> </body> </html>
@{ Layout = null; } <!DOCTYPE html> <html lang="en"> <head> <title>Sweet Water Revolver</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Bootstrap --> <link href="assets/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet" media="screen"> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script> <![endif]--> </head> <body> <h1>Sweet Water Revolver</h1> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="https://code.jquery.com/jquery.js"></script> <!-- Include all compiled plugins (below), or include individual files as needed --> <script src="assets/bootstrap/dist/js/bootstrap.min.js"></script> </body> </html>
Add mapping for all entities
using AutoMapper; using BusinessEntities; using BusinessEntities.Dictionaries; using DataModel; using DataModel.Dictionaries; namespace BLL.Mapping { public class AutomapperProfile : Profile { public AutomapperProfile() { CreateMap<Animal, AnimalEntity>(); CreateMap<Council, CouncilEntity>(); } } }
using AutoMapper; using BusinessEntities; using BusinessEntities.Dictionaries; using DataModel; using DataModel.Dictionaries; namespace BLL.Mapping { public class AutomapperProfile : Profile { public AutomapperProfile() { CreateMap<Animal, AnimalEntity>(); CreateMap<Council, CouncilEntity>(); CreateMap<ActivityType, ActivityTypeEntity>(); CreateMap<Address, AddressEntity>(); CreateMap<City, CityEntity>(); CreateMap<CityType, CityTypeEntity>(); CreateMap<Company, CompanyEntity>(); CreateMap<Country, CountryEntity>(); CreateMap<District, DistrictEntity>(); CreateMap<DocumentType, DocumentTypeEntity>(); CreateMap<EducationDegree, EducationDegreeEntity>(); CreateMap<FamilyRelations, FamilyRelationsEntity>(); CreateMap<FamilyStatus, FamilyStatusEntity>(); CreateMap<Institution, InstitutionEntity>(); CreateMap<Material, MaterialEntity>(); CreateMap<Nationality, NationalityEntity>(); CreateMap<PassAuthority, PassAuthorityEntity>(); CreateMap<PensionType, PensionTypeEntity>(); CreateMap<Person, PersonEntity>(); CreateMap<Position, PositionEntity>(); CreateMap<Region, RegionEntity>(); CreateMap<Speciality, SpecialityEntity>(); CreateMap<Street, StreetEntity>(); CreateMap<StreetType, StreetType>(); CreateMap<Catalog, CatalogEntity>(); CreateMap<Document, DocumentEntity>(); CreateMap<Education, EducationEntity>(); CreateMap<Employment, EmploymentEntity>(); CreateMap<House, HouseEntity>(); CreateMap<People, PeopleEntity>(); CreateMap<PersonDocument, PersonDocumentEntity>(); } } }
Add Message if AvgKmL is null
@using CarFuel.Models @model Car <h2>@Model.Make (@Model.Model)</h2> <div class="well well-sm"> Average consumption is <strong>@(Model.AverageKmL?.ToString("n2"))</strong> km/L </div>
@using CarFuel.Models @model Car <h2>@Model.Make (@Model.Model)</h2> <div class="well well-sm"> @if (Model.AverageKmL == null) { <div> Not has enough data to calculate consumption rate. Please add more fill up. </div> } Average consumption is <strong>@(Model.AverageKmL?.ToString("n2"))</strong> km/L </div>
Add logic for creating a pantru for new users
using System; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using PlanEatSave.Models; using PlanEatSave.Utils; namespace PlanEatSave.DataAceessLayer { public class PantryService { private ApplicationDbContext _context; private IPlanEatSaveLogger _logger; public PantryService(ApplicationDbContext context, IPlanEatSaveLogger logger) { _context = context; _logger = logger; } public async Task<Pantry> GetPantryByUserIdAsync(string userId) { return await _context.Pantries .Where(pantry => pantry.UserId == userId) .Include(pantry => pantry.PantryItems).FirstOrDefaultAsync(); } public async Task<bool> AddItem(string userId, PantryItem item) { var pantryDb = await _context.Pantries.Where(pantry => pantry.Id == item.PantryId).FirstOrDefaultAsync(); if (pantryDb == null || pantryDb.UserId != userId) { return false; } _context.PantryItems.Add(item); await _context.SaveChangesAsync(); return true; } } }
using System; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using PlanEatSave.Models; using PlanEatSave.Utils; namespace PlanEatSave.DataAceessLayer { public class PantryService { private ApplicationDbContext _context; private IPlanEatSaveLogger _logger; public PantryService(ApplicationDbContext context, IPlanEatSaveLogger logger) { _context = context; _logger = logger; } public async Task<Pantry> GetPantryByUserIdAsync(string userId) { var pantryFromDb = await _context.Pantries .Where(pantry => pantry.UserId == userId) .Include(pantry => pantry.PantryItems).FirstOrDefaultAsync(); if (pantryFromDb != null) { return pantryFromDb; } var newPantry = new Pantry { UserId = userId }; _context.Pantries.Add(newPantry); await _context.SaveChangesAsync(); return newPantry; } public async Task<bool> AddItem(string userId, PantryItem item) { var pantryDb = await _context.Pantries.Where(pantry => pantry.Id == item.PantryId).FirstOrDefaultAsync(); if (pantryDb == null || pantryDb.UserId != userId) { return false; } _context.PantryItems.Add(item); await _context.SaveChangesAsync(); return true; } } }
Add Image to clipboard data
namespace ElectronNET.API.Entities { /// <summary> /// /// </summary> public class Data { /// <summary> /// Gets or sets the text. /// </summary> /// <value> /// The text. /// </value> public string Text { get; set; } /// <summary> /// Gets or sets the HTML. /// </summary> /// <value> /// The HTML. /// </value> public string Html { get; set; } /// <summary> /// Gets or sets the RTF. /// </summary> /// <value> /// The RTF. /// </value> public string Rtf { get; set; } /// <summary> /// The title of the url at text. /// </summary> public string Bookmark { get; set; } } }
namespace ElectronNET.API.Entities { /// <summary> /// /// </summary> public class Data { /// <summary> /// Gets or sets the text. /// </summary> /// <value> /// The text. /// </value> public string Text { get; set; } /// <summary> /// Gets or sets the HTML. /// </summary> /// <value> /// The HTML. /// </value> public string Html { get; set; } /// <summary> /// Gets or sets the RTF. /// </summary> /// <value> /// The RTF. /// </value> public string Rtf { get; set; } /// <summary> /// The title of the url at text. /// </summary> public string Bookmark { get; set; } public NativeImage? Image { get; set; } } }
Move the Recenter and Monoscoping Rendering feature to the Oculus Head Controller
using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEditor; using UnityEngine; [CustomEditor(typeof(VRSubjectController))] public class VRSubjectInspector : Editor { VRSubjectController instance; public override void OnInspectorGUI() { instance = target as VRSubjectController; base.OnInspectorGUI(); GUILayout.BeginVertical(); var availableBodyController = instance.GetComponents<IBodyMovementController>(); var availableHeadController = instance.GetComponents<IHeadMovementController>(); EditorGUILayout.LabelField("Available Head Controller"); if (!availableHeadController.Any()) EditorGUILayout.HelpBox("No Head Controller Implementations found! \n Attache them to this GameObject!", MessageType.Info); foreach (var headController in availableHeadController) { if (GUILayout.Button(headController.Identifier)) { instance.ChangeHeadController(headController); } } EditorGUILayout.LabelField("Available Body Controller"); if (!availableBodyController.Any()) EditorGUILayout.HelpBox("No Body Controller Implementations found! \n Attache them to this GameObject!", MessageType.Info); foreach (var bodyController in availableBodyController) { if(GUILayout.Button(bodyController.Identifier)) instance.ChangeBodyController(bodyController); } EditorGUILayout.Space(); if (GUILayout.Button("Reset Controller")) { instance.ResetController(); } GUILayout.EndVertical(); instance.UseMonoscopigRendering = EditorGUILayout.Toggle("Monoscopic Rendering", instance.UseMonoscopigRendering); if (instance.UseMonoscopigRendering) instance.SetMonoscopic(instance.UseMonoscopigRendering); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEditor; using UnityEngine; [CustomEditor(typeof(VRSubjectController))] public class VRSubjectInspector : Editor { VRSubjectController instance; public override void OnInspectorGUI() { instance = target as VRSubjectController; base.OnInspectorGUI(); GUILayout.BeginVertical(); var availableBodyController = instance.GetComponents<IBodyMovementController>(); var availableHeadController = instance.GetComponents<IHeadMovementController>(); EditorGUILayout.LabelField("Available Head Controller"); if (!availableHeadController.Any()) EditorGUILayout.HelpBox("No Head Controller Implementations found! \n Attache them to this GameObject!", MessageType.Info); foreach (var headController in availableHeadController) { if (GUILayout.Button(headController.Identifier)) { instance.ChangeHeadController(headController); } } EditorGUILayout.LabelField("Available Body Controller"); if (!availableBodyController.Any()) EditorGUILayout.HelpBox("No Body Controller Implementations found! \n Attache them to this GameObject!", MessageType.Info); foreach (var bodyController in availableBodyController) { if(GUILayout.Button(bodyController.Identifier)) instance.ChangeBodyController(bodyController); } EditorGUILayout.Space(); if (GUILayout.Button("Reset Controller")) { instance.ResetController(); } GUILayout.EndVertical(); } }
Remove signupbox id from register bx since then it can be hidden by the zk.showLoginBox function
@{ ViewBag.Title = "Registreer je vandaag bij de Oogstplanner"; } <div class="flowtype-area"> <!-- START RESPONSIVE RECTANGLE LAYOUT --> <!-- Top bar --> <div id="top"> <h1>Registreer je vandaag bij de Oogstplanner</h1> </div> <!-- Fixed main screen --> <div id="login" class="bg imglogin"> <!-- Signup box inspired by http://bootsnipp.com/snippets/featured/login-amp-signup-forms-in-panel --> <div id="signupbox" class="mainbox span12"> <div class="panel panel-info"> <div class="panel-heading"> <div class="panel-side-link"> <a id="signin-link form-text" href="Login">Inloggen</a> </div> </div> <div class="panel-body"> @{ Html.RenderPartial("_RegisterForm"); } </div><!-- End panel body --> </div><!-- End panel --> </div><!-- End signup box --> </div><!-- End main login div --> <!-- END RESPONSIVE RECTANGLES LAYOUT --> </div><!-- End flowtype-area -->
@{ ViewBag.Title = "Registreer je vandaag bij de Oogstplanner"; } <div class="flowtype-area"> <!-- START RESPONSIVE RECTANGLE LAYOUT --> <!-- Top bar --> <div id="top"> </div> <!-- Fixed main screen --> <div id="login" class="bg imglogin"> <div class="row"> <div class="mainbox col-md-12 col-sm-12 col-xs-12"> <div class="panel panel-info"> <div class="panel-heading"> <div class="panel-title">Registreer je vandaag bij de Oogstplanner</div> <div class="panel-side-link"> <a id="signin-link" href="#">Inloggen</a> </div> </div> <div class="panel-body"> @{ Html.RenderPartial("_RegisterForm"); } </div><!-- End panel body --> </div><!-- End panel --> </div><!-- End signup box --> </div><!-- End row --> </div><!-- End main login div --> <!-- END RESPONSIVE RECTANGLES LAYOUT --> </div><!-- End flowtype-area -->
Change unity scene type to struct
using UnityEngine; namespace LiteNetLibManager { [System.Serializable] public class LiteNetLibScene { [SerializeField] private Object sceneAsset; [SerializeField] private string sceneName = string.Empty; public string SceneName { get { return sceneName; } set { sceneName = value; } } public static implicit operator string(LiteNetLibScene unityScene) { return unityScene.SceneName; } public bool IsSet() { return !string.IsNullOrEmpty(sceneName); } } }
using UnityEngine; namespace LiteNetLibManager { [System.Serializable] public struct LiteNetLibScene { [SerializeField] private Object sceneAsset; [SerializeField] private string sceneName; public string SceneName { get { return sceneName; } set { sceneName = value; } } public static implicit operator string(LiteNetLibScene unityScene) { return unityScene.SceneName; } public bool IsSet() { return !string.IsNullOrEmpty(sceneName); } } }
Check IAllowAnonymousFilter in a simpler way.
using System.Linq; using System.Threading.Tasks; using Abp.AspNetCore.Mvc.Extensions; using Abp.Authorization; using Abp.Dependency; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc.Filters; namespace Abp.AspNetCore.Mvc.Authorization { public class AbpAuthorizationFilter : IAsyncAuthorizationFilter, ITransientDependency { private readonly IAuthorizationHelper _authorizationHelper; public AbpAuthorizationFilter(IAuthorizationHelper authorizationHelper) { _authorizationHelper = authorizationHelper; } public async Task OnAuthorizationAsync(AuthorizationFilterContext context) { //Check IAllowAnonymous if (context.ActionDescriptor .GetMethodInfo() .GetCustomAttributes(true) .OfType<IAllowAnonymous>() .Any()) { return; } await _authorizationHelper.AuthorizeAsync(context.ActionDescriptor.GetMethodInfo()); } } }
using System.Linq; using System.Threading.Tasks; using Abp.AspNetCore.Mvc.Extensions; using Abp.Authorization; using Abp.Dependency; using Microsoft.AspNetCore.Mvc.Authorization; using Microsoft.AspNetCore.Mvc.Filters; namespace Abp.AspNetCore.Mvc.Authorization { //TODO: Register only actions which define AbpMvcAuthorizeAttribute..? public class AbpAuthorizationFilter : IAsyncAuthorizationFilter, ITransientDependency { private readonly IAuthorizationHelper _authorizationHelper; public AbpAuthorizationFilter(IAuthorizationHelper authorizationHelper) { _authorizationHelper = authorizationHelper; } public async Task OnAuthorizationAsync(AuthorizationFilterContext context) { // Allow Anonymous skips all authorization if (context.Filters.Any(item => item is IAllowAnonymousFilter)) { return; } await _authorizationHelper.AuthorizeAsync(context.ActionDescriptor.GetMethodInfo()); } } }
Fix for initializing models from assembly.
using System; using Gtk; using Castle.ActiveRecord.Framework.Config; using Castle.ActiveRecord; using HumanRightsTracker.Models; namespace HumanRightsTracker { class MainClass { public static void Main (string[] args) { XmlConfigurationSource config = new XmlConfigurationSource("Config/ARConfig.xml"); ActiveRecordStarter.Initialize(Models, config); Application.Init (); LoginWindow win = new LoginWindow (); win.Show (); Application.Run (); } } }
using System; using System.Reflection; using Gtk; using Castle.ActiveRecord.Framework.Config; using Castle.ActiveRecord; using HumanRightsTracker.Models; namespace HumanRightsTracker { class MainClass { public static void Main (string[] args) { XmlConfigurationSource config = new XmlConfigurationSource("Config/ARConfig.xml"); Assembly asm = Assembly.Load("Models"); ActiveRecordStarter.Initialize(asm, config); Application.Init (); LoginWindow win = new LoginWindow (); win.Show (); Application.Run (); } } }
Fix note masks not working
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Graphics; using osu.Framework.Allocation; using osu.Game.Graphics; using osu.Game.Rulesets.Edit; using osu.Game.Rulesets.Mania.Objects.Drawables; using osu.Game.Rulesets.Mania.Objects.Drawables.Pieces; namespace osu.Game.Rulesets.Mania.Edit.Layers.Selection.Overlays { public class NoteMask : HitObjectMask { public NoteMask(DrawableNote note) : base(note) { Origin = Anchor.Centre; Position = note.Position; Size = note.Size; Scale = note.Scale; AddInternal(new NotePiece()); note.HitObject.ColumnChanged += _ => Position = note.Position; } [BackgroundDependencyLoader] private void load(OsuColour colours) { Colour = colours.Yellow; } } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Allocation; using osu.Game.Graphics; using osu.Game.Rulesets.Edit; using osu.Game.Rulesets.Mania.Objects.Drawables; using osu.Game.Rulesets.Mania.Objects.Drawables.Pieces; namespace osu.Game.Rulesets.Mania.Edit.Layers.Selection.Overlays { public class NoteMask : HitObjectMask { public NoteMask(DrawableNote note) : base(note) { Scale = note.Scale; AddInternal(new NotePiece()); note.HitObject.ColumnChanged += _ => Position = note.Position; } [BackgroundDependencyLoader] private void load(OsuColour colours) { Colour = colours.Yellow; } protected override void Update() { base.Update(); Size = HitObject.DrawSize; Position = Parent.ToLocalSpace(HitObject.ScreenSpaceDrawQuad.BottomLeft); } } }
Add cert-test action to help diagnose issues in azure
using System.Web.Mvc; using SFA.DAS.EmployerUsers.WebClientComponents; namespace SFA.DAS.EmployerUsers.Web.Controllers { public class HomeController : ControllerBase { public ActionResult Index() { return View(); } public ActionResult CatchAll(string path) { return RedirectToAction("NotFound", "Error", new {path}); } [AuthoriseActiveUser] [Route("Login")] public ActionResult Login() { return RedirectToAction("Index"); } } }
using System; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Web.Mvc; using Microsoft.Azure; using SFA.DAS.EmployerUsers.WebClientComponents; namespace SFA.DAS.EmployerUsers.Web.Controllers { public class HomeController : ControllerBase { public ActionResult Index() { return View(); } public ActionResult CatchAll(string path) { return RedirectToAction("NotFound", "Error", new { path }); } [AuthoriseActiveUser] [Route("Login")] public ActionResult Login() { return RedirectToAction("Index"); } public ActionResult CertTest() { var certificatePath = string.Format(@"{0}\bin\DasIDPCert.pfx", AppDomain.CurrentDomain.BaseDirectory); var codeCert = new X509Certificate2(certificatePath, "idsrv3test"); X509Certificate2 storeCert; var store = new X509Store(StoreLocation.LocalMachine); store.Open(OpenFlags.ReadOnly); try { var thumbprint = CloudConfigurationManager.GetSetting("TokenCertificateThumbprint"); var certificates = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false); storeCert = certificates.Count > 0 ? certificates[0] : null; if (storeCert == null) { return Content($"Failed to load cert with thumbprint {thumbprint} from store"); } } finally { store.Close(); } var details = new StringBuilder(); details.AppendLine("Code cert"); details.AppendLine("-------------------------"); details.AppendLine($"FriendlyName: {codeCert.FriendlyName}"); details.AppendLine($"PublicKey: {codeCert.GetPublicKeyString()}"); details.AppendLine($"HasPrivateKey: {codeCert.HasPrivateKey}"); details.AppendLine($"Thumbprint: {codeCert.Thumbprint}"); details.AppendLine(); details.AppendLine("Store cert"); details.AppendLine("-------------------------"); details.AppendLine($"FriendlyName: {storeCert.FriendlyName}"); details.AppendLine($"PublicKey: {storeCert.GetPublicKeyString()}"); details.AppendLine($"HasPrivateKey: {storeCert.HasPrivateKey}"); details.AppendLine($"Thumbprint: {storeCert.Thumbprint}"); return Content(details.ToString(), "text/plain"); } } }
Add basic hello server version
using System; namespace HelloServer { class MainClass { public static void Main(string[] args) { Console.WriteLine("Hello World!"); } } }
using System; using System.Threading.Tasks; using Grpc.Core; using Hello; namespace HelloServer { class HelloServerImpl : HelloService.HelloServiceBase { // Server side handler of the SayHello RPC public override Task<HelloResp> SayHello(HelloReq request, ServerCallContext context) { return Task.FromResult(new HelloResp { Result = "Hello " + request.Name }); } } class Program { const int Port = 50051; public static void Main(string[] args) { Server server = new Server { Services = { HelloService.BindService(new HelloServerImpl()) }, Ports = { new ServerPort("localhost", Port, ServerCredentials.Insecure) } }; server.Start(); Console.WriteLine("Greeter server listening on port " + Port); Console.WriteLine("Press any key to stop the server..."); Console.ReadKey(); server.ShutdownAsync().Wait(); } } }
Put StreamReader into using blog
using System; using System.IO; using DotVVM.Framework.Controls; using DotVVM.Framework.Hosting; using Newtonsoft.Json; namespace DotVVM.Framework.ResourceManagement { /// <summary> /// CSS in header. It's perfect for critical CSS. /// </summary> public class InlineStylesheetResource : ResourceBase { private string code; private readonly ILocalResourceLocation resourceLocation; [JsonConstructor] public InlineStylesheetResource(ILocalResourceLocation resourceLocation) : base(ResourceRenderPosition.Head) { this.resourceLocation = resourceLocation; } /// <inheritdoc/> public override void Render(IHtmlWriter writer, IDotvvmRequestContext context, string resourceName) { if (code == null) { using (var resourceStream = resourceLocation.LoadResource(context)) { code = new StreamReader(resourceStream).ReadToEnd(); } } if (!string.IsNullOrWhiteSpace(code)) { writer.RenderBeginTag("style"); writer.WriteUnencodedText(code); writer.RenderEndTag(); } } } }
using System; using System.IO; using DotVVM.Framework.Controls; using DotVVM.Framework.Hosting; using Newtonsoft.Json; namespace DotVVM.Framework.ResourceManagement { /// <summary> /// CSS in header. It's perfect for small css. For example critical CSS. /// </summary> public class InlineStylesheetResource : ResourceBase { private string code; private readonly ILocalResourceLocation resourceLocation; [JsonConstructor] public InlineStylesheetResource(ILocalResourceLocation resourceLocation) : base(ResourceRenderPosition.Head) { this.resourceLocation = resourceLocation; } /// <inheritdoc/> public override void Render(IHtmlWriter writer, IDotvvmRequestContext context, string resourceName) { if (code == null) { using (var resourceStream = resourceLocation.LoadResource(context)) { using (var resourceStreamReader = new StreamReader(resourceStream)) { code = resourceStreamReader.ReadToEnd(); } } } if (!string.IsNullOrWhiteSpace(code)) { writer.RenderBeginTag("style"); writer.WriteUnencodedText(code); writer.RenderEndTag(); } } } }
Add static to class definition because reasons.
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace LearnosityDemo { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace LearnosityDemo { public static class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } }
Set default timeout to 100 seconds
using System; using System.Collections.Generic; using System.Net.Http; namespace Octokit.Internal { public class Request : IRequest { public Request() { Headers = new Dictionary<string, string>(); Parameters = new Dictionary<string, string>(); AllowAutoRedirect = true; } public object Body { get; set; } public Dictionary<string, string> Headers { get; private set; } public HttpMethod Method { get; set; } public Dictionary<string, string> Parameters { get; private set; } public Uri BaseAddress { get; set; } public Uri Endpoint { get; set; } public TimeSpan Timeout { get; set; } public string ContentType { get; set; } public bool AllowAutoRedirect { get; set; } } }
using System; using System.Collections.Generic; using System.Net.Http; namespace Octokit.Internal { public class Request : IRequest { public Request() { Headers = new Dictionary<string, string>(); Parameters = new Dictionary<string, string>(); AllowAutoRedirect = true; Timeout = TimeSpan.FromSeconds(100); } public object Body { get; set; } public Dictionary<string, string> Headers { get; private set; } public HttpMethod Method { get; set; } public Dictionary<string, string> Parameters { get; private set; } public Uri BaseAddress { get; set; } public Uri Endpoint { get; set; } public TimeSpan Timeout { get; set; } public string ContentType { get; set; } public bool AllowAutoRedirect { get; set; } } }
Sort the i18n keys by descending length Fix 'FullHP' getting overridden by 'Full'.
using System.Collections.Generic; using System.IO; using System.Xml; namespace PROProtocol { public class Language { private const string FileName = "Resources/Lang.xml"; private Dictionary<string, string> _texts = new Dictionary<string, string>(); public Language() { if (File.Exists(FileName)) { XmlDocument xml = new XmlDocument(); xml.Load(FileName); LoadXmlDocument(xml); } } private void LoadXmlDocument(XmlDocument xml) { XmlNode languageNode = xml.DocumentElement.GetElementsByTagName("English")[0]; if (languageNode != null) { foreach (XmlElement textNode in languageNode) { _texts.Add(textNode.GetAttribute("name"), textNode.InnerText); } } } public string GetText(string name) { return _texts[name]; } public string Replace(string originalText) { if (originalText.IndexOf('$') != -1) { foreach (var text in _texts) { originalText = originalText.Replace("$" + text.Key, text.Value); } } return originalText; } } }
using System; using System.Collections.Generic; using System.IO; using System.Xml; namespace PROProtocol { public class Language { private class DescendingLengthComparer : IComparer<string> { public int Compare(string x, string y) { int result = y.Length.CompareTo(x.Length); return result != 0 ? result : x.CompareTo(y); } } private const string FileName = "Resources/Lang.xml"; private SortedDictionary<string, string> _texts = new SortedDictionary<string, string>(); public Language() { _texts = new SortedDictionary<string, string>(new DescendingLengthComparer()); if (File.Exists(FileName)) { XmlDocument xml = new XmlDocument(); xml.Load(FileName); LoadXmlDocument(xml); } } private void LoadXmlDocument(XmlDocument xml) { XmlNode languageNode = xml.DocumentElement.GetElementsByTagName("English")[0]; if (languageNode != null) { foreach (XmlElement textNode in languageNode) { _texts.Add(textNode.GetAttribute("name"), textNode.InnerText); } } } public string GetText(string name) { return _texts[name]; } public string Replace(string originalText) { if (originalText.IndexOf('$') != -1) { foreach (var text in _texts) { originalText = originalText.Replace("$" + text.Key, text.Value); } } return originalText; } } }
Make mania selection blueprint abstract
// 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.Game.Rulesets.Edit; using osu.Game.Rulesets.Mania.Objects.Drawables; using osu.Game.Rulesets.Objects.Drawables; using osu.Game.Rulesets.UI.Scrolling; using osuTK; namespace osu.Game.Rulesets.Mania.Edit.Blueprints { public class ManiaSelectionBlueprint : OverlaySelectionBlueprint { public new DrawableManiaHitObject DrawableObject => (DrawableManiaHitObject)base.DrawableObject; [Resolved] private IScrollingInfo scrollingInfo { get; set; } [Resolved] private IManiaHitObjectComposer composer { get; set; } public ManiaSelectionBlueprint(DrawableHitObject drawableObject) : base(drawableObject) { RelativeSizeAxes = Axes.None; } protected override void Update() { base.Update(); Position = Parent.ToLocalSpace(DrawableObject.ToScreenSpace(Vector2.Zero)); } public override void Show() { DrawableObject.AlwaysAlive = true; base.Show(); } public override void Hide() { DrawableObject.AlwaysAlive = false; base.Hide(); } } }
// 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.Game.Rulesets.Edit; using osu.Game.Rulesets.Mania.Objects.Drawables; using osu.Game.Rulesets.Objects.Drawables; using osu.Game.Rulesets.UI.Scrolling; using osuTK; namespace osu.Game.Rulesets.Mania.Edit.Blueprints { public abstract class ManiaSelectionBlueprint : OverlaySelectionBlueprint { public new DrawableManiaHitObject DrawableObject => (DrawableManiaHitObject)base.DrawableObject; [Resolved] private IScrollingInfo scrollingInfo { get; set; } [Resolved] private IManiaHitObjectComposer composer { get; set; } protected ManiaSelectionBlueprint(DrawableHitObject drawableObject) : base(drawableObject) { RelativeSizeAxes = Axes.None; } protected override void Update() { base.Update(); Position = Parent.ToLocalSpace(DrawableObject.ToScreenSpace(Vector2.Zero)); } public override void Show() { DrawableObject.AlwaysAlive = true; base.Show(); } public override void Hide() { DrawableObject.AlwaysAlive = false; base.Hide(); } } }
Add path and line to GH console output
using System; using System.ComponentModel.Composition; using System.Text; using NVika.Abstractions; using NVika.Parsers; namespace NVika.BuildServers { internal sealed class GitHub : BuildServerBase { private readonly IEnvironment _environment; [ImportingConstructor] internal GitHub(IEnvironment environment) { _environment = environment; } public override string Name => nameof(GitHub); public override bool CanApplyToCurrentContext() => !string.IsNullOrEmpty(_environment.GetEnvironmentVariable("GITHUB_ACTIONS")); public override void WriteMessage(Issue issue) { var outputString = new StringBuilder(); switch (issue.Severity) { case IssueSeverity.Error: outputString.Append("::error "); break; case IssueSeverity.Warning: outputString.Append("::warning"); break; } if (issue.FilePath != null) { var file = issue.FilePath.Replace('\\', '/'); outputString.Append($"file={file},"); } if (issue.Offset != null) outputString.Append($"col={issue.Offset.Start},"); outputString.Append($"line={issue.Line}::{issue.Message}"); Console.WriteLine(outputString.ToString()); } } }
using System; using System.ComponentModel.Composition; using System.Text; using NVika.Abstractions; using NVika.Parsers; namespace NVika.BuildServers { internal sealed class GitHub : BuildServerBase { private readonly IEnvironment _environment; [ImportingConstructor] internal GitHub(IEnvironment environment) { _environment = environment; } public override string Name => nameof(GitHub); public override bool CanApplyToCurrentContext() => !string.IsNullOrEmpty(_environment.GetEnvironmentVariable("GITHUB_ACTIONS")); public override void WriteMessage(Issue issue) { var outputString = new StringBuilder(); switch (issue.Severity) { case IssueSeverity.Error: outputString.Append("::error "); break; case IssueSeverity.Warning: outputString.Append("::warning"); break; } var details = issue.Message; if (issue.FilePath != null) { var absolutePath = issue.FilePath.Replace('\\', '/'); var relativePath = issue.Project != null ? issue.FilePath.Replace($"{issue.Project.Replace('\\', '/')}/", string.Empty) : absolutePath; outputString.Append($"file={absolutePath},"); details = $"{issue.Message} in {relativePath} on line {issue.Line}"; } if (issue.Offset != null) outputString.Append($"col={issue.Offset.Start},"); outputString.Append($"line={issue.Line}::{details}"); Console.WriteLine(outputString.ToString()); } } }
Change exception message and pass innerexception to argumentexception
using System; using System.Collections.Generic; using System.Linq; namespace AppHarbor { public class TypeNameMatcher<T> { private readonly IEnumerable<Type> _candidateTypes; public TypeNameMatcher(IEnumerable<Type> candidateTypes) { if (candidateTypes.Any(x => !typeof(T).IsAssignableFrom(x))) { throw new ArgumentException(string.Format("{0} must be assignable from all injected types", typeof(T).FullName), "candidateTypes"); } _candidateTypes = candidateTypes; } public Type GetMatchedType(string commandName, string scope) { var scopedTypes = _candidateTypes.Where(x => x.Name.EndsWith(string.Concat(scope, "Command"))); try { return scopedTypes.Single(x => x.Name.ToLower().StartsWith(commandName.ToLower())); } catch (InvalidOperationException) { throw new ArgumentException("No candidate type matches", "commandName"); } } } }
using System; using System.Collections.Generic; using System.Linq; namespace AppHarbor { public class TypeNameMatcher<T> { private readonly IEnumerable<Type> _candidateTypes; public TypeNameMatcher(IEnumerable<Type> candidateTypes) { if (candidateTypes.Any(x => !typeof(T).IsAssignableFrom(x))) { throw new ArgumentException(string.Format("{0} must be assignable from all injected types", typeof(T).FullName), "candidateTypes"); } _candidateTypes = candidateTypes; } public Type GetMatchedType(string commandName, string scope) { var scopedTypes = _candidateTypes.Where(x => x.Name.EndsWith(string.Concat(scope, "Command"))); try { return scopedTypes.Single(x => x.Name.ToLower().StartsWith(commandName.ToLower())); } catch (InvalidOperationException exception) { throw new ArgumentException("Error while matching type", "commandName", exception); } } } }
Fix compile issue from merge
using System; using System.Collections.Generic; using JetBrains.ReSharper.Feature.Services.LiveTemplates.Scope; using JetBrains.ReSharper.Plugins.Unity.ShaderLab.ProjectModel; using JetBrains.ReSharper.Plugins.Unity.ShaderLab.Psi; using JetBrains.ReSharper.Psi; namespace JetBrains.ReSharper.Plugins.Unity.Feature.Services.LiveTemplates.Scope { public class InUnityShaderLabFile : InAnyLanguageFile, IMainScopePoint { private static readonly Guid DefaultUID = new Guid("ED25967E-EAEA-47CC-AB3C-C549C5F3F378"); private static readonly Guid QuickUID = new Guid("1149A991-197E-468A-90E0-07700A01FBD3"); public override Guid GetDefaultUID() => DefaultUID; public override PsiLanguageType RelatedLanguage => ShaderLabLanguage.Instance; public override string PresentableShortName => "ShaderLab (Unity)"; protected override IEnumerable<string> GetExtensions() { yield return ShaderLabProjectFileType.SHADER_EXTENSION; } public override string ToString() => "ShaderLab (Unity)"; public new string QuickListTitle => "Unity files"; public new Guid QuickListUID => QuickUID; } }
using System; using System.Collections.Generic; using JetBrains.ReSharper.Feature.Services.LiveTemplates.Scope; using JetBrains.ReSharper.Plugins.Unity.ShaderLab.ProjectModel; using JetBrains.ReSharper.Plugins.Unity.ShaderLab.Psi; using JetBrains.ReSharper.Psi; namespace JetBrains.ReSharper.Plugins.Unity.Feature.Services.LiveTemplates.Scope { public class InUnityShaderLabFile : InAnyLanguageFile, IMainScopePoint { private static readonly Guid DefaultUID = new Guid("ED25967E-EAEA-47CC-AB3C-C549C5F3F378"); private static readonly Guid QuickUID = new Guid("1149A991-197E-468A-90E0-07700A01FBD3"); public override Guid GetDefaultUID() => DefaultUID; public override PsiLanguageType RelatedLanguage => ShaderLabLanguage.Instance; public override string PresentableShortName => "ShaderLab (Unity)"; protected override IEnumerable<string> GetExtensions() { yield return ShaderLabProjectFileType.SHADERLAB_EXTENSION; } public override string ToString() => "ShaderLab (Unity)"; public new string QuickListTitle => "Unity files"; public new Guid QuickListUID => QuickUID; } }
Remove a dependency on System.Drawing.Common by using a compatible color parser.
using System.Drawing; using System.Globalization; namespace ClosedXML.Utils { internal static class ColorStringParser { public static Color ParseFromHtml(string htmlColor) { try { if (htmlColor[0] != '#') htmlColor = '#' + htmlColor; return ColorTranslator.FromHtml(htmlColor); } catch { // https://github.com/ClosedXML/ClosedXML/issues/675 // When regional settings list separator is # , the standard ColorTranslator.FromHtml fails return Color.FromArgb(int.Parse(htmlColor.Replace("#", ""), NumberStyles.AllowHexSpecifier)); } } } }
using System; using System.ComponentModel; using System.Drawing; using System.Globalization; namespace ClosedXML.Utils { internal static class ColorStringParser { public static Color ParseFromHtml(string htmlColor) { try { if (htmlColor[0] == '#' && (htmlColor.Length == 4 || htmlColor.Length == 7)) { if (htmlColor.Length == 4) { var r = ReadHex(htmlColor, 1, 1); var g = ReadHex(htmlColor, 2, 1); var b = ReadHex(htmlColor, 3, 1); return Color.FromArgb( (r << 4) | r, (g << 4) | g, (b << 4) | b); } return Color.FromArgb( ReadHex(htmlColor, 1, 2), ReadHex(htmlColor, 3, 2), ReadHex(htmlColor, 5, 2)); } return (Color)TypeDescriptor.GetConverter(typeof(Color)).ConvertFromString(htmlColor); } catch { // https://github.com/ClosedXML/ClosedXML/issues/675 // When regional settings list separator is # , the standard ColorTranslator.FromHtml fails return Color.FromArgb(int.Parse(htmlColor.Replace("#", ""), NumberStyles.AllowHexSpecifier)); } } private static int ReadHex(string text, int start, int length) { return Convert.ToInt32(text.Substring(start, length), 16); } } }
Update context that is passed through
using System; namespace Glimpse.Agent.Web { public interface IIgnoredRequestPolicy { bool ShouldIgnore(IContext context); } }
using System; using Glimpse.Web; namespace Glimpse.Agent.Web { public interface IIgnoredRequestPolicy { bool ShouldIgnore(IHttpContext context); } }
Add scaffolding for skipping ease-in
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MainCamera : MonoBehaviour { public GameObject cursor; private IEnumerator currentMove; // Use this for initialization void Start () { } // Update is called once per frame void Update () { //this.transform.position.z = -10; //NO } public void scootTo(Vector3 endpos) { if (currentMove != null) { //if we're moving, fuck that StopCoroutine (currentMove); } Debug.Log ("Scoot TO:"); Debug.Log(endpos); currentMove = SmoothMove (this.transform.position, endpos, 5.0); StartCoroutine (currentMove); } IEnumerator SmoothMove(Vector3 startpos, Vector3 endpos, double seconds) { double t = 0.0; endpos.z = this.transform.position.z; //NEVER move forward or backward (Hack because we are in 2D) while ( t <= 1.0 ) { //Debug.Log ("t=" + t); t += Time.deltaTime/seconds; transform.position = Vector3.Lerp(startpos, endpos, Mathf.SmoothStep((float) 0.0, (float) 1.0, (float) t)); //Debug.Log (transform.position); yield return null; //WHY } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MainCamera : MonoBehaviour { public GameObject cursor; private IEnumerator currentMove; // Use this for initialization void Start () { } // Update is called once per frame void Update () { //this.transform.position.z = -10; //NO } public void scootTo(Vector3 endpos) { double time = .6; bool skipEaseIn = false; if (currentMove != null) { //if we're moving, fuck that StopCoroutine (currentMove); skipEaseIn = true; } Debug.Log ("Scoot TO:"); Debug.Log(endpos); currentMove = SmoothMove (this.transform.position, endpos, time, skipEaseIn); StartCoroutine (currentMove); } IEnumerator SmoothMove(Vector3 startpos, Vector3 endpos, double seconds, bool skipEaseIn = false) { double t = 0.0; if (skipEaseIn) { //DO SOMETHING??? //t = 0.1; } endpos.z = this.transform.position.z; //NEVER move forward or backward (Hack because we are in 2D) while ( t <= 1.0 ) { t += Time.deltaTime/seconds; transform.position = Vector3.Lerp(startpos, endpos, Mathf.SmoothStep((float) 0.0, (float) 1.0, (float) t)); yield return null; //WHY } } }
Set default for Reminder mapping to 'JustUpcoming'.
// This file is Part of CalDavSynchronizer (http://outlookcaldavsynchronizer.sourceforge.net/) // Copyright (c) 2015 Gerhard Zehetbauer // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. using System; using System.Security.Cryptography; using System.Text; using System.Xml.Serialization; using CalDavSynchronizer.Implementation; using CalDavSynchronizer.Ui; namespace CalDavSynchronizer.Contracts { public class EventMappingConfiguration : MappingConfigurationBase { public ReminderMapping MapReminder { get; set; } public bool MapAttendees { get; set; } public bool MapBody { get; set; } public EventMappingConfiguration () { MapReminder = ReminderMapping.@true; MapAttendees = true; MapBody = true; } public override IConfigurationForm<MappingConfigurationBase> CreateConfigurationForm (IConfigurationFormFactory factory) { return factory.Create (this); } } }
// This file is Part of CalDavSynchronizer (http://outlookcaldavsynchronizer.sourceforge.net/) // Copyright (c) 2015 Gerhard Zehetbauer // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. using System; using System.Security.Cryptography; using System.Text; using System.Xml.Serialization; using CalDavSynchronizer.Implementation; using CalDavSynchronizer.Ui; namespace CalDavSynchronizer.Contracts { public class EventMappingConfiguration : MappingConfigurationBase { public ReminderMapping MapReminder { get; set; } public bool MapAttendees { get; set; } public bool MapBody { get; set; } public EventMappingConfiguration () { MapReminder = ReminderMapping.JustUpcoming; MapAttendees = true; MapBody = true; } public override IConfigurationForm<MappingConfigurationBase> CreateConfigurationForm (IConfigurationFormFactory factory) { return factory.Create (this); } } }
Add Win/Lose Scene Transition Hooks
using UnityEngine; using System.Collections; public class GUIBehavior : MonoBehaviour { public Texture barTexture; public wolf wolfData; public int boxWidth = 34; public int boxHeight = 30; void OnGUI () { //Print the bar GUI.Box (new Rect(Screen.width - barTexture.width - 18,10,barTexture.width + 8, barTexture.height + 8),barTexture); //Print the box GUI.Box (new Rect(Screen.width - barTexture.width / 2 - 14 - boxWidth / 2 , 8f + .97f * barTexture.height * (100f - wolfData.GetTemp()) / 100f,boxWidth,boxHeight), ""); } }
using UnityEngine; using System.Collections; public class GUIBehavior : MonoBehaviour { public Texture barTexture; public wolf wolfData; public int boxWidth = 34; public int boxHeight = 30; void OnGUI () { //Print the bar GUI.Box (new Rect(Screen.width - barTexture.width - 18,10,barTexture.width + 8, barTexture.height + 8),barTexture); //Print the box GUI.Box (new Rect(Screen.width - barTexture.width / 2 - 14 - boxWidth / 2 , 8f + .97f * barTexture.height * (100f - wolfData.GetTemp()) / 100f,boxWidth,boxHeight), ""); } void Update () { if(Input.GetKey ("t")) { // TRIGGER THE WIN SCENE print ("STUFF"); } else if (Input.GetKey ("g")) { // TRIGGER THE LOSE SCENE print ("LOSE"); } } }
Set default wait interval for Run command to be 60 seconds
using ConDep.Dsl.SemanticModel; using ConDep.Dsl.SemanticModel.WebDeploy; using Microsoft.Web.Deployment; namespace ConDep.Dsl.Operations.Application.Execution.RunCmd { public class RunCmdProvider : WebDeployProviderBase { private const string NAME = "runCommand"; public RunCmdProvider(string command) { DestinationPath = command; } public override DeploymentProviderOptions GetWebDeploySourceProviderOptions() { return new DeploymentProviderOptions(NAME) { Path = DestinationPath }; } public override string Name { get { return NAME; } } public override DeploymentProviderOptions GetWebDeployDestinationProviderOptions() { var destProviderOptions = new DeploymentProviderOptions("Auto");// { Path = DestinationPath }; //DeploymentProviderSetting dontUseCmdExe; //if (destProviderOptions.ProviderSettings.TryGetValue("dontUseCommandExe", out dontUseCmdExe)) //{ // dontUseCmdExe.Value = true; //} return destProviderOptions; } public override bool IsValid(Notification notification) { return !string.IsNullOrWhiteSpace(DestinationPath) || string.IsNullOrWhiteSpace(SourcePath); } } }
using ConDep.Dsl.SemanticModel; using ConDep.Dsl.SemanticModel.WebDeploy; using Microsoft.Web.Deployment; namespace ConDep.Dsl.Operations.Application.Execution.RunCmd { public class RunCmdProvider : WebDeployProviderBase { private const string NAME = "runCommand"; public RunCmdProvider(string command) { DestinationPath = command; WaitIntervalInSeconds = 60; } public override DeploymentProviderOptions GetWebDeploySourceProviderOptions() { return new DeploymentProviderOptions(NAME) { Path = DestinationPath }; } public override string Name { get { return NAME; } } public override DeploymentProviderOptions GetWebDeployDestinationProviderOptions() { var destProviderOptions = new DeploymentProviderOptions("Auto");// { Path = DestinationPath }; //DeploymentProviderSetting dontUseCmdExe; //if (destProviderOptions.ProviderSettings.TryGetValue("dontUseCommandExe", out dontUseCmdExe)) //{ // dontUseCmdExe.Value = true; //} return destProviderOptions; } public override bool IsValid(Notification notification) { return !string.IsNullOrWhiteSpace(DestinationPath) || string.IsNullOrWhiteSpace(SourcePath); } } }
Fix path output for inputs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using MBEV = Microsoft.Build.Evaluation; using MBEX = Microsoft.Build.Execution; namespace MSBuildTracer { class ImportTracer { private MBEV.Project project; public ImportTracer(MBEV.Project project) { this.project = project; } public void Trace(MBEV.ResolvedImport import, int traceLevel = 0) { PrintImportInfo(import, traceLevel); foreach (var childImport in project.Imports.Where( i => string.Equals(i.ImportingElement.ContainingProject.FullPath, project.ResolveAllProperties(import.ImportingElement.Project), StringComparison.OrdinalIgnoreCase))) { Trace(childImport, traceLevel + 1); } } private void PrintImportInfo(MBEV.ResolvedImport import, int indentCount) { var indent = indentCount > 0 ? new StringBuilder().Insert(0, " ", indentCount).ToString() : ""; Console.WriteLine($"{indent}{import.ImportingElement.Location.Line}: {project.ResolveAllProperties(import.ImportingElement.Project)}"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using MBEV = Microsoft.Build.Evaluation; using MBEX = Microsoft.Build.Execution; namespace MSBuildTracer { class ImportTracer { private MBEV.Project project; public ImportTracer(MBEV.Project project) { this.project = project; } public void Trace(MBEV.ResolvedImport import, int traceLevel = 0) { PrintImportInfo(import, traceLevel); foreach (var childImport in project.Imports.Where( i => string.Equals(i.ImportingElement.ContainingProject.FullPath, project.ResolveAllProperties(import.ImportingElement.Project), StringComparison.OrdinalIgnoreCase))) { Trace(childImport, traceLevel + 1); } } private void PrintImportInfo(MBEV.ResolvedImport import, int indentCount) { var indent = indentCount > 0 ? new StringBuilder().Insert(0, " ", indentCount).ToString() : ""; Console.WriteLine($"{indent}{import.ImportingElement.Location.Line}: {project.ResolveAllProperties(import.ImportedProject.Location.File)}"); } } }
Fix compilation error introduced with my previous fix
// // NSUrlConnection.cs: // Author: // Miguel de Icaza // using System; using System.Reflection; using System.Collections; using System.Runtime.InteropServices; using MonoMac.ObjCRuntime; namespace MonoMac.Foundation { public partial class NSUrlConnection { static Selector selSendSynchronousRequestReturningResponseError = new Selector ("sendSynchronousRequest:returningResponse:error:"); unsafe static NSData SendSynchronousRequest (NSUrlRequest request, out NSUrlResponse response, out NSError error) { IntPtr responseStorage = IntPtr.Zero; IntPtr errorStorage = IntPtr.Zero; void *resp = &responseStorage; void *errp = &errorStorage; IntPtr rhandle = (IntPtr) resp; IntPtr ehandle = (IntPtr) errp; var res = Messaging.IntPtr_objc_msgSend_IntPtr_IntPtr_IntPtr ( class_ptr, selSendSynchronousRequestReturningResponseError.Handle, request.Handle, rhandle, ehandle); if (responseStorage != IntPtr.Zero) response = (NSUrlResponse) Runtime.GetNSObject (responseStorage); else response = null; if (errorStorage != IntPtr.Zero) error = (NSUrlResponse) Runtime.GetNSObject (errorStorage); else error = null; return (NSData) Runtime.GetNSObject (res); } } }
// // NSUrlConnection.cs: // Author: // Miguel de Icaza // using System; using System.Reflection; using System.Collections; using System.Runtime.InteropServices; using MonoMac.ObjCRuntime; namespace MonoMac.Foundation { public partial class NSUrlConnection { static Selector selSendSynchronousRequestReturningResponseError = new Selector ("sendSynchronousRequest:returningResponse:error:"); public unsafe static NSData SendSynchronousRequest (NSUrlRequest request, out NSUrlResponse response, out NSError error) { IntPtr responseStorage = IntPtr.Zero; IntPtr errorStorage = IntPtr.Zero; void *resp = &responseStorage; void *errp = &errorStorage; IntPtr rhandle = (IntPtr) resp; IntPtr ehandle = (IntPtr) errp; var res = Messaging.IntPtr_objc_msgSend_IntPtr_IntPtr_IntPtr ( class_ptr, selSendSynchronousRequestReturningResponseError.Handle, request.Handle, rhandle, ehandle); if (responseStorage != IntPtr.Zero) response = (NSUrlResponse) Runtime.GetNSObject (responseStorage); else response = null; if (errorStorage != IntPtr.Zero) error = (NSError) Runtime.GetNSObject (errorStorage); else error = null; return (NSData) Runtime.GetNSObject (res); } } }
Add descriptions to enum members
// 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. namespace osu.Game.Beatmaps { /// <summary> /// The type of countdown shown before the start of gameplay on a given beatmap. /// </summary> public enum CountdownType { None = 0, Normal = 1, HalfSpeed = 2, DoubleSpeed = 3 } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.ComponentModel; namespace osu.Game.Beatmaps { /// <summary> /// The type of countdown shown before the start of gameplay on a given beatmap. /// </summary> public enum CountdownType { None = 0, [Description("Normal")] Normal = 1, [Description("Half speed")] HalfSpeed = 2, [Description("Double speed")] DoubleSpeed = 3 } }
Add comment about ParentPid check.
using System; using O365.Security.ETW; namespace hiddentreasure_etw_demo { public static class RemoteThreadInjection { public static UserTrace CreateTrace() { var filter = new EventFilter(Filter .EventIdIs(3)); filter.OnEvent += (IEventRecord r) => { var sourcePID = r.ProcessId; var targetPID = r.GetUInt32("ProcessID"); if (sourcePID != targetPID) { var createdTID = r.GetUInt32("ThreadID"); var fmt = "Possible thread injection! - SourcePID: {0}, TargetPID: {1}, CreatedTID: {2}"; Console.WriteLine(fmt, sourcePID, targetPID, createdTID); } }; var provider = new Provider("Microsoft-Windows-Kernel-Process"); provider.AddFilter(filter); var trace = new UserTrace(); trace.Enable(provider); return trace; } } }
using System; using O365.Security.ETW; namespace hiddentreasure_etw_demo { public static class RemoteThreadInjection { public static UserTrace CreateTrace() { var filter = new EventFilter(Filter .EventIdIs(3)); filter.OnEvent += (IEventRecord r) => { var sourcePID = r.ProcessId; var targetPID = r.GetUInt32("ProcessID"); if (sourcePID != targetPID) { // This is where you'd check that the target process's // parent PID isn't the source PID. I've left it off for // brevity since .NET doesn't provide an easy way to get // parent PID :(. var createdTID = r.GetUInt32("ThreadID"); var fmt = "Possible thread injection! - SourcePID: {0}, TargetPID: {1}, CreatedTID: {2}"; Console.WriteLine(fmt, sourcePID, targetPID, createdTID); } }; var provider = new Provider("Microsoft-Windows-Kernel-Process"); provider.AddFilter(filter); var trace = new UserTrace(); trace.Enable(provider); return trace; } } }
Add parameter to the public method
using BruTile.Predefined; using BruTile.Web; using Mapsui.Layers; namespace Mapsui.Utilities { public static class OpenStreetMap { private const string DefaultUserAgent = "Default Mapsui user-agent"; private static readonly BruTile.Attribution OpenStreetMapAttribution = new BruTile.Attribution( "© OpenStreetMap contributors", "https://www.openstreetmap.org/copyright"); public static TileLayer CreateTileLayer() { return new TileLayer(CreateTileSource()) { Name = "OpenStreetMap" }; } private static HttpTileSource CreateTileSource(string userAgent = DefaultUserAgent) { return new HttpTileSource(new GlobalSphericalMercator(), "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", new[] { "a", "b", "c" }, name: "OpenStreetMap", attribution: OpenStreetMapAttribution, userAgent: userAgent); } } }
using BruTile.Predefined; using BruTile.Web; using Mapsui.Layers; namespace Mapsui.Utilities { public static class OpenStreetMap { private const string DefaultUserAgent = "Default Mapsui user-agent"; private static readonly BruTile.Attribution OpenStreetMapAttribution = new BruTile.Attribution( "© OpenStreetMap contributors", "https://www.openstreetmap.org/copyright"); public static TileLayer CreateTileLayer(string userAgent = DefaultUserAgent) { return new TileLayer(CreateTileSource(userAgent)) { Name = "OpenStreetMap" }; } private static HttpTileSource CreateTileSource(string userAgent) { return new HttpTileSource(new GlobalSphericalMercator(), "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", new[] { "a", "b", "c" }, name: "OpenStreetMap", attribution: OpenStreetMapAttribution, userAgent: userAgent); } } }
Improve performance for realtime API
using PubNubMessaging.Core; using System; using Utf8Json; namespace BitFlyer.Apis { public class RealtimeApi { private readonly Pubnub _pubnub; public RealtimeApi() { _pubnub = new Pubnub("nopublishkey", BitFlyerConstants.SubscribeKey); } public void Subscribe<T>(string channel, Action<T> onReceive, Action<string> onConnect, Action<string, Exception> onError) { _pubnub.Subscribe( channel, s => OnReceiveMessage(s, onReceive, onError), onConnect, error => { onError(error.Message, error.DetailedDotNetException); }); } private void OnReceiveMessage<T>(string result, Action<T> onReceive, Action<string, Exception> onError) { if (string.IsNullOrWhiteSpace(result)) { return; } var deserializedMessage = _pubnub.JsonPluggableLibrary.DeserializeToListOfObject(result); if (deserializedMessage == null || deserializedMessage.Count <= 0) { return; } var subscribedObject = deserializedMessage[0]; if (subscribedObject == null) { return; } var resultActualMessage = _pubnub.JsonPluggableLibrary.SerializeToJsonString(subscribedObject); T deserialized; try { deserialized = JsonSerializer.Deserialize<T>(resultActualMessage); } catch (Exception ex) { onError(ex.Message, ex); return; } onReceive(deserialized); } } }
using PubNubMessaging.Core; using System; using System.Text; using Utf8Json; namespace BitFlyer.Apis { public class RealtimeApi { private readonly Pubnub _pubnub; public RealtimeApi() { _pubnub = new Pubnub("nopublishkey", BitFlyerConstants.SubscribeKey); } public void Subscribe<T>(string channel, Action<T> onReceive, Action<string> onConnect, Action<string, Exception> onError) { _pubnub.Subscribe( channel, s => OnReceiveMessage(s, onReceive, onError), onConnect, error => { onError(error.Message, error.DetailedDotNetException); }); } private void OnReceiveMessage<T>(string result, Action<T> onReceive, Action<string, Exception> onError) { if (string.IsNullOrWhiteSpace(result)) { return; } var reader = new JsonReader(Encoding.UTF8.GetBytes(result)); reader.ReadIsBeginArrayWithVerify(); T deserialized; try { deserialized = JsonSerializer.Deserialize<T>(ref reader); } catch (Exception ex) { onError(ex.Message, ex); return; } onReceive(deserialized); } } }
Revert "Fix D rank displaying as F"
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System.ComponentModel; namespace osu.Game.Scoring { public enum ScoreRank { [Description(@"F")] F, [Description(@"D")] D, [Description(@"C")] C, [Description(@"B")] B, [Description(@"A")] A, [Description(@"S")] S, [Description(@"SPlus")] SH, [Description(@"SS")] X, [Description(@"SSPlus")] XH, } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System.ComponentModel; namespace osu.Game.Scoring { public enum ScoreRank { [Description(@"F")] F, [Description(@"F")] D, [Description(@"C")] C, [Description(@"B")] B, [Description(@"A")] A, [Description(@"S")] S, [Description(@"SPlus")] SH, [Description(@"SS")] X, [Description(@"SSPlus")] XH, } }
Build script now creates individual zip file packages to align with the NuGet packages and semantic versioning.
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.18033 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyVersion("3.0.0.0")] [assembly: AssemblyFileVersion("3.0.0.0")] [assembly: AssemblyConfiguration("Release built on 2013-02-22 14:39")] [assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")]
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.18033 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyVersion("3.0.0.0")] [assembly: AssemblyFileVersion("3.0.0.0")] [assembly: AssemblyConfiguration("Release built on 2013-02-28 02:03")] [assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")]
Add test data seeder to DbContext.
using System; using System.Data.Entity; using System.Collections.Generic; using System.Linq; using System.Web; namespace NoteFolder.Models { public class FileDbContext : DbContext { public DbSet<File> Files { get; set; } } public class File { public int ID { get; set; } public string Name { get; set; } public string Description { get; set; } public string Text { get; set; } public bool IsFolder { get; set; } public DateTime TimeCreated {get; set; } public DateTime TimeLastEdited { get; set; } public virtual File Parent { get; set; } public virtual ICollection<File> Children { get; set; } } }
using System; using System.Data.Entity; using System.Collections.Generic; using System.Linq; using System.Web; namespace NoteFolder.Models { public class FileTestInit : DropCreateDatabaseAlways<FileDbContext> { protected override void Seed(FileDbContext db) { var docs = new File { Name = "Documents", Description = "", IsFolder = true }; var proj = new File { Name = "Projects", Description = "", IsFolder = true }; var nf = new File { Name = "NoteFolder", Description = "Note organization", IsFolder = true }; var sln = new File { Name = "NoteFolder.sln", Description = "", IsFolder = false, Text = "<Solution text>" }; var source = new File { Name = "Source", Description = "", IsFolder = true }; var cs = new File { Name = "NoteFolder.cs", Description = "", IsFolder = false, Text = "<Source code>" }; proj.SetParent(docs); nf.SetParent(proj); sln.SetParent(nf); source.SetParent(nf); cs.SetParent(source); db.Files.AddRange(new File[] {docs, proj, nf, sln, source, cs }); base.Seed(db); } } public static class FileDebugExtensions { public static void SetParent(this File f, File parent) { f.Parent = parent; parent.Children.Add(f); } } public class FileDbContext : DbContext { public DbSet<File> Files { get; set; } public FileDbContext() { Database.SetInitializer(new FileTestInit()); } } public class File { public int ID { get; set; } public string Name { get; set; } public string Description { get; set; } public string Text { get; set; } public bool IsFolder { get; set; } public DateTime TimeCreated {get; set; } public DateTime TimeLastEdited { get; set; } public virtual File Parent { get; set; } public virtual ICollection<File> Children { get; set; } } }
Reduce default bucket count for HTTP request duration to 16
namespace Prometheus.HttpMetrics { public sealed class HttpRequestDurationOptions : HttpMetricsOptionsBase { private const string DefaultName = "http_request_duration_seconds"; private const string DefaultHelp = "Provides the duration in seconds of HTTP requests from an ASP.NET application."; public Histogram Histogram { get; set; } = Metrics.CreateHistogram(DefaultName, DefaultHelp, new HistogramConfiguration { Buckets = Histogram.ExponentialBuckets(0.0001, 1.5, 36), LabelNames = HttpRequestLabelNames.All }); } }
namespace Prometheus.HttpMetrics { public sealed class HttpRequestDurationOptions : HttpMetricsOptionsBase { private const string DefaultName = "http_request_duration_seconds"; private const string DefaultHelp = "Provides the duration in seconds of HTTP requests from an ASP.NET application."; public Histogram Histogram { get; set; } = Metrics.CreateHistogram(DefaultName, DefaultHelp, new HistogramConfiguration { Buckets = Histogram.ExponentialBuckets(0.001, 2, 16), LabelNames = HttpRequestLabelNames.All }); } }
Use boxenterprise.net when viewing file of folder from Acumatica
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using PX.Data; using PX.SM.BoxStorageProvider; using PX.Common; public partial class Pages_SM_SM202670 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string folderID = Request.QueryString["FolderID"]; string fileID = Request.QueryString["FileID"]; if (!String.IsNullOrEmpty(folderID) && !String.IsNullOrEmpty(fileID)) { fraContent.Attributes["src"] = "https://box.com/embed_widget/000000000000/files/0/f/" + folderID + "/1/f_" + fileID; } else if (!String.IsNullOrEmpty(folderID)) { fraContent.Attributes["src"] = "https://box.com/embed_widget/000000000000/files/0/f/" + folderID; } else { Response.Write("Error. Missing FolderID/FileID Parameters."); return; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using PX.Data; using PX.SM.BoxStorageProvider; using PX.Common; public partial class Pages_SM_SM202670 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string folderID = Request.QueryString["FolderID"]; string fileID = Request.QueryString["FileID"]; if (!String.IsNullOrEmpty(folderID) && !String.IsNullOrEmpty(fileID)) { fraContent.Attributes["src"] = "https://boxenterprise.net/embed_widget/000000000000/files/0/f/" + folderID + "/1/f_" + fileID; } else if (!String.IsNullOrEmpty(folderID)) { fraContent.Attributes["src"] = "https://boxenterprise.net/embed_widget/000000000000/files/0/f/" + folderID; } else { Response.Write("Error. Missing FolderID/FileID Parameters."); return; } } }
Allow control over references being added
using System.IO; namespace Cassette.BundleProcessing { public abstract class ParseReferences<T> : IBundleProcessor<T> where T : Bundle { public void Process(T bundle) { foreach (var asset in bundle.Assets) { if (ShouldParseAsset(asset)) { ParseAssetReferences(asset); } } } protected virtual bool ShouldParseAsset(IAsset asset) { return true; } void ParseAssetReferences(IAsset asset) { string code; using (var reader = new StreamReader(asset.OpenStream())) { code = reader.ReadToEnd(); } var commentParser = CreateCommentParser(); var referenceParser = CreateReferenceParser(commentParser); var references = referenceParser.Parse(code, asset); foreach (var reference in references) { asset.AddReference(reference.Path, reference.LineNumber); } } internal virtual ReferenceParser CreateReferenceParser(ICommentParser commentParser) { return new ReferenceParser(commentParser); } protected abstract ICommentParser CreateCommentParser(); } }
using System.IO; namespace Cassette.BundleProcessing { public abstract class ParseReferences<T> : IBundleProcessor<T> where T : Bundle { public void Process(T bundle) { foreach (var asset in bundle.Assets) { if (ShouldParseAsset(asset)) { ParseAssetReferences(asset); } } } protected virtual bool ShouldParseAsset(IAsset asset) { return true; } protected virtual bool ShouldAddReference(string referencePath) { return true; } void ParseAssetReferences(IAsset asset) { string code; using (var reader = new StreamReader(asset.OpenStream())) { code = reader.ReadToEnd(); } var commentParser = CreateCommentParser(); var referenceParser = CreateReferenceParser(commentParser); var references = referenceParser.Parse(code, asset); foreach (var reference in references) { if (ShouldAddReference(reference.Path)) { asset.AddReference(reference.Path, reference.LineNumber); } } } internal virtual ReferenceParser CreateReferenceParser(ICommentParser commentParser) { return new ReferenceParser(commentParser); } protected abstract ICommentParser CreateCommentParser(); } }
Update Tests to reflect attribute move
using Consola.Library; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Tests.Scriptables { public class Progeny : Scriptable { [Description("Simple Name Field")] public string Name { get; set; } } }
using Consola.Library; using Consola.Library.util; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Tests.Scriptables { public class Progeny : Scriptable { [Description("Simple Name Field")] public string Name { get; set; } } }
Set thread count to 1 in kestrel options.
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; namespace CompetitionPlatform { public class Program { public static void Main(string[] args) { var host = new WebHostBuilder() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseStartup<Startup>() .Build(); host.Run(); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; namespace CompetitionPlatform { public class Program { public static void Main(string[] args) { var host = new WebHostBuilder() .UseKestrel(opts => opts.ThreadCount = 1) .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseStartup<Startup>() .Build(); host.Run(); } } }
Fix unique control name for WPF
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="StringExtensions.cs" company="Catel development team"> // Copyright (c) 2008 - 2015 Catel development team. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Catel { using System; /// <summary> /// String extensions. /// </summary> public static class StringExtensions { /// <summary> /// Gets the a unique name for a control. This is sometimes required in some frameworks. /// <para /> /// The name is made unique by appending a unique guid. /// </summary> /// <param name="controlName">Name of the control.</param> /// <returns>System.String.</returns> public static string GetUniqueControlName(this string controlName) { var name = string.Format("{0}_{1}", controlName, Guid.NewGuid()); return name; } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="StringExtensions.cs" company="Catel development team"> // Copyright (c) 2008 - 2015 Catel development team. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Catel { using System; /// <summary> /// String extensions. /// </summary> public static class StringExtensions { /// <summary> /// Gets the a unique name for a control. This is sometimes required in some frameworks. /// <para /> /// The name is made unique by appending a unique guid. /// </summary> /// <param name="controlName">Name of the control.</param> /// <returns>System.String.</returns> public static string GetUniqueControlName(this string controlName) { var random = Guid.NewGuid().ToString(); random = random.Replace("-", string.Empty); var name = string.Format("{0}_{1}", controlName, random); return name; } } }
Add route to support children
using Orders.com.Web.Api.Filters; using System.Web.Http; namespace Orders.com.Web.Api { public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API configuration and services GlobalConfiguration.Configuration.DependencyResolver = new NinjectResolver(NinjectWebCommon.CreateKernel()); // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } } }
using Orders.com.Web.Api.Filters; using System.Web.Http; namespace Orders.com.Web.Api { public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API configuration and services GlobalConfiguration.Configuration.DependencyResolver = new NinjectResolver(NinjectWebCommon.CreateKernel()); // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "children", routeTemplate: "api/{controller}/{id}/{action}", defaults: new { id = RouteParameter.Optional } ); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } } }
Add LocationCompleter to HDInsight cmdlets
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // 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 Microsoft.Azure.Commands.HDInsight.Commands; using Microsoft.Azure.Management.HDInsight.Models; using System.Management.Automation; namespace Microsoft.Azure.Commands.HDInsight { [Cmdlet( VerbsCommon.Get, Constants.CommandNames.AzureHDInsightProperties), OutputType( typeof(CapabilitiesResponse))] public class GetAzureHDInsightPropertiesCommand : HDInsightCmdletBase { #region Input Parameter Definitions [Parameter( Position = 0, Mandatory = true, HelpMessage = "Gets or sets the datacenter location for the cluster.")] public string Location { get; set; } #endregion public override void ExecuteCmdlet() { var result = HDInsightManagementClient.GetCapabilities(Location); WriteObject(result); } } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // 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 Microsoft.Azure.Commands.HDInsight.Commands; using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters; using Microsoft.Azure.Management.HDInsight.Models; using System.Management.Automation; namespace Microsoft.Azure.Commands.HDInsight { [Cmdlet( VerbsCommon.Get, Constants.CommandNames.AzureHDInsightProperties), OutputType( typeof(CapabilitiesResponse))] public class GetAzureHDInsightPropertiesCommand : HDInsightCmdletBase { #region Input Parameter Definitions [Parameter( Position = 0, Mandatory = true, HelpMessage = "Gets or sets the datacenter location for the cluster.")] [LocationCompleter("Microsoft.HDInsight/locations/capabilities")] public string Location { get; set; } #endregion public override void ExecuteCmdlet() { var result = HDInsightManagementClient.GetCapabilities(Location); WriteObject(result); } } }
Add messageworker start to main()
using System; using System.Threading; using System.Net; using System.Net.Sockets; using System.Text.RegularExpressions; using System.Text; using transf.Log; namespace transf { class Program { /// <summary> /// Prompts for a nickname until a valid nickname is found. /// </summary> /// <returns>The valid nickname retrieved from user input</returns> public static string GetNickname() { string prompt = "Type a nickname (4-16 chars, alphanum only): "; string nickname = ""; do { Console.Write (prompt); nickname = Console.ReadLine(); } while(!Regex.IsMatch (nickname, "[a-zA-Z0-9]{4,16}")); return nickname; } public static void Main (string[] args) { // This should be the first thing that's done Logger.Instance = new Logger (Console.Out); Logger.Instance.LogLevel = LogLevel.Verbose; // up the verbosity const int PORT = 44444; string nickname = GetNickname (); Logger.WriteDebug (Logger.GROUP_APP, "Using nickname {0}", nickname); DiscoveryWorker discWorker = new DiscoveryWorker (); discWorker.Start (PORT, nickname); discWorker.Join (); } } }
using System; using System.Threading; using System.Net; using System.Net.Sockets; using System.Text.RegularExpressions; using System.Text; using transf.Log; namespace transf { class Program { /// <summary> /// Prompts for a nickname until a valid nickname is found. /// </summary> /// <returns>The valid nickname retrieved from user input</returns> public static string GetNickname() { string prompt = "Type a nickname (4-16 chars, alphanum only): "; string nickname = ""; do { Console.Write (prompt); nickname = Console.ReadLine(); } while(!Regex.IsMatch (nickname, "[a-zA-Z0-9]{4,16}")); return nickname; } public static void Main (string[] args) { // This should be the first thing that's done Logger.Instance = new Logger (Console.Out); Logger.Instance.LogLevel = LogLevel.Verbose; // up the verbosity const int PORT = 44444; string nickname = GetNickname (); Logger.WriteDebug (Logger.GROUP_APP, "Using nickname {0}", nickname); // Start a discovery worker and message worker MessageWorker msgWorker = MessageWorker.Instance; msgWorker.Start(PORT); DiscoveryWorker discWorker = new DiscoveryWorker (); discWorker.Start (PORT, nickname); discWorker.Join (); } } }
Allow for saving of simulations before the slime has fully expanded
using Gtk; using NLog; using SlimeSimulation.Controller.WindowController.Templates; namespace SlimeSimulation.View.WindowComponent.SimulationControlComponent { internal class GrowthPhaseControlBox : AbstractSimulationControlBox { private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); public GrowthPhaseControlBox(SimulationStepAbstractWindowController simulationStepAbstractWindowController, Window parentWindow) { AddControls(simulationStepAbstractWindowController, parentWindow); } private void AddControls(SimulationStepAbstractWindowController simulationStepAbstractWindowController, Window parentWindow) { Add(new SimulationStepButton(simulationStepAbstractWindowController, parentWindow)); Add(new SimulationStepUntilFullyGrownComponent(simulationStepAbstractWindowController, parentWindow)); } } }
using Gtk; using NLog; using SlimeSimulation.Controller.WindowController.Templates; namespace SlimeSimulation.View.WindowComponent.SimulationControlComponent { internal class GrowthPhaseControlBox : AbstractSimulationControlBox { private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); public GrowthPhaseControlBox(SimulationStepAbstractWindowController simulationStepAbstractWindowController, Window parentWindow) { AddControls(simulationStepAbstractWindowController, parentWindow); } private void AddControls(SimulationStepAbstractWindowController simulationStepAbstractWindowController, Window parentWindow) { Add(new SimulationStepButton(simulationStepAbstractWindowController, parentWindow)); Add(new SimulationStepUntilFullyGrownComponent(simulationStepAbstractWindowController, parentWindow)); Add(new SimulationSaveComponent(simulationStepAbstractWindowController.SimulationController, parentWindow)); } } }
Add check box for show in library or not
@model IPagedList<MMLibrarySystem.Models.BookListController.BookListItem> @{ ViewBag.Title = "Book List"; } @using (Ajax.BeginForm(new AjaxOptions() { HttpMethod = "GET", InsertionMode = InsertionMode.Replace, UpdateTargetId = "bookListContainer" })) { <fieldset style="border:1px solid black;padding: 1em"> <legend style="display: inline" >Filter</legend> Book name or description: <input type="search" name="searchTerm" /> Show books in library @Html.CheckBox("showInLibrary") </fieldset> <input type="submit" value="Search by name or description" /> } @Html.Partial("_BookList", Model)
@model IPagedList<MMLibrarySystem.Models.BookListController.BookListItem> @{ ViewBag.Title = "Book List"; } @using (Ajax.BeginForm(new AjaxOptions() { HttpMethod = "GET", InsertionMode = InsertionMode.Replace, UpdateTargetId = "bookListContainer" })) { <fieldset style="border:1px solid black;padding: 1em"> <legend style="display: inline">Filter</legend> Book name or description: <input type="search" name="searchTerm" /> Show books in library @Html.CheckBox("showInLibrary") </fieldset> <input type="submit" value="Search by name or description" /> } @Html.Partial("_BookList", Model)
Send a POST to light up the HockeyGoalLight
using System.Diagnostics; namespace GOALWorker { public static class LightNotifier { //TODO: Jared Implement call to each light here for their team public static void NotifyLightsForTeam(string teamname) { Trace.TraceInformation("GOALWorker is Sending Light Request for {0}", teamname); } } }
using System.Diagnostics; using System.Net; using System.Text; using System.IO; namespace GOALWorker { public static class LightNotifier { //TODO: Jared Implement call to each light here for their team public static void NotifyLightsForTeam(string teamname) { Trace.TraceInformation("GOALWorker is Sending Light Request for {0}", teamname); WebRequest request = WebRequest.Create("https://api.spark.io/v1/devices/DEVICEID/score"); request.Method = "POST"; string postData = "access_token=ACCESSTOKEN&params=0%2C255%2C0"; byte[] byteArray = Encoding.UTF8.GetBytes(postData); request.ContentType = "application/x-www-form-urlencoded"; // Set the ContentLength property of the WebRequest. // Set the ContentLength property of the WebRequest. request.ContentLength = byteArray.Length; // Get the request stream. Stream dataStream = request.GetRequestStream(); // Write the data to the request stream. dataStream.Write(byteArray, 0, byteArray.Length); // Close the Stream object. dataStream.Close(); // Get the response. request.GetResponse(); } } }
Remove error in case the searchString is empty
@model Tigwi.UI.Models.IAccountModel @{ ViewBag.Title = "ShowAccount"; } @section LeftInfos { <p>Oh Hai @Model.Name</p> @if(User.Identity.IsAuthenticated) { @Html.Partial("_FollowPerson", Model) @Html.Partial("_AccountFollowedPublicLists", Model) } } @Html.Partial("_ViewPostList", Model.PersonalList.PostsAfter(DateTime.MinValue, 10))
@model Tigwi.UI.Models.IAccountModel @{ ViewBag.Title = "ShowAccount"; } @section LeftInfos { <h3>@Model.Name</h3> <p>@Model.Description</p> @if(User.Identity.IsAuthenticated) { @Html.Partial("_FollowPerson", Model) @Html.Partial("_AccountFollowedPublicLists", Model) } } @Html.Partial("_ViewPostList", Model.PersonalList.PostsAfter(DateTime.MinValue, 10))