commit
stringlengths
40
40
old_file
stringlengths
4
237
new_file
stringlengths
4
237
old_contents
stringlengths
1
4.24k
new_contents
stringlengths
1
4.87k
subject
stringlengths
15
778
message
stringlengths
15
8.75k
lang
stringclasses
266 values
license
stringclasses
13 values
repos
stringlengths
5
127k
666375f685f9fba1a4f201df6fdc6ec641cd639f
SlimeSimulation/View/WindowComponent/SimulationControlComponent/AdaptionPhaseControlBox.cs
SlimeSimulation/View/WindowComponent/SimulationControlComponent/AdaptionPhaseControlBox.cs
using Gtk; using NLog; using SlimeSimulation.Controller.WindowController.Templates; namespace SlimeSimulation.View.WindowComponent.SimulationControlComponent { class AdaptionPhaseControlBox : AbstractSimulationControlBox { private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); public AdaptionPhaseControlBox(SimulationStepAbstractWindowController simulationStepAbstractWindowController, Window parentWindow) { AddControls(simulationStepAbstractWindowController, parentWindow); } private void AddControls(SimulationStepAbstractWindowController simulationStepAbstractWindowController, Window parentWindow) { var controlInterfaceStartingValues = simulationStepAbstractWindowController.SimulationControlInterfaceValues; Add(new SimulationStepButton(simulationStepAbstractWindowController, parentWindow)); Add(new SimulationStepNumberOfTimesComponent(simulationStepAbstractWindowController, parentWindow, controlInterfaceStartingValues)); Add(new ShouldFlowResultsBeDisplayedControlComponent(controlInterfaceStartingValues)); Add(new ShouldStepFromAllSourcesAtOnceControlComponent(controlInterfaceStartingValues)); Add(new SimulationSaveComponent(simulationStepAbstractWindowController.SimulationController, parentWindow)); } } }
using Gtk; using NLog; using SlimeSimulation.Controller.WindowController.Templates; namespace SlimeSimulation.View.WindowComponent.SimulationControlComponent { class AdaptionPhaseControlBox : AbstractSimulationControlBox { private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); public AdaptionPhaseControlBox(SimulationStepAbstractWindowController simulationStepAbstractWindowController, Window parentWindow) { AddControls(simulationStepAbstractWindowController, parentWindow); } private void AddControls(SimulationStepAbstractWindowController simulationStepAbstractWindowController, Window parentWindow) { var controlInterfaceStartingValues = simulationStepAbstractWindowController.SimulationControlInterfaceValues; var container = new Table(6, 1, true); container.Attach(new SimulationStepButton(simulationStepAbstractWindowController, parentWindow), 0, 1, 0, 1); container.Attach(new SimulationStepNumberOfTimesComponent(simulationStepAbstractWindowController, parentWindow, controlInterfaceStartingValues), 0, 1, 1, 3); container.Attach(new ShouldFlowResultsBeDisplayedControlComponent(controlInterfaceStartingValues), 0, 1, 3, 4); container.Attach(new ShouldStepFromAllSourcesAtOnceControlComponent(controlInterfaceStartingValues), 0, 1, 4, 5); container.Attach(new SimulationSaveComponent(simulationStepAbstractWindowController.SimulationController, parentWindow), 0, 1, 5, 6); Add(container); } } }
Add some changes to UI to make spacing equal for components
Add some changes to UI to make spacing equal for components
C#
apache-2.0
willb611/SlimeSimulation
6008e6c42040709fa2aefa3f886e563bca316e24
osu.Framework.Tests/Audio/AudioCollectionManagerTest.cs
osu.Framework.Tests/Audio/AudioCollectionManagerTest.cs
// 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 { private class TestingAdjustableAudioComponent : AdjustableAudioComponent { } [Test] public void TestDisposalWhileItemsAreAddedDoesNotThrowInvalidOperationException() { var manager = new AudioCollectionManager<AdjustableAudioComponent>(); // add a huge amount of items to the queue for (int i = 0; i < 10000; i++) manager.AddItem(new TestingAdjustableAudioComponent()); // in a seperate thread start processing the queue new Thread(() => manager.Update()).Start(); // wait a little for beginning of the update to start Thread.Sleep(4); Assert.DoesNotThrow(() => manager.Dispose()); } } }
// 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 AudioCollectionManager<AdjustableAudioComponent>(); // add a huge amount of items to the queue for (int i = 0; i < 10000; i++) manager.AddItem(new TestingAdjustableAudioComponent()); // in a seperate thread start processing the queue new Thread(() => manager.Update()).Start(); // wait a little for beginning of the update to start Thread.Sleep(4); Assert.DoesNotThrow(() => manager.Dispose()); } private class TestingAdjustableAudioComponent : AdjustableAudioComponent { } } }
Move test component to bottom of class
Move test component to bottom of class
C#
mit
peppy/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,ppy/osu-framework,ZLima12/osu-framework,ZLima12/osu-framework,ppy/osu-framework,peppy/osu-framework
92986caa7accd6980c698f7772fa70d81d2b39d4
ERMine.Core/Modeling/Attribute.cs
ERMine.Core/Modeling/Attribute.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ERMine.Core.Modeling { public class Attribute : IEntityRelationship { public string Label { get; set; } public string DataType { get; set; } public Domain Domain { get; set; } public bool IsNullable { get; set; } public bool IsSparse { get; set; } public bool IsImmutable { get; set; } public KeyType Key { get; set; } public bool IsPartOfPrimaryKey { get { return Key == KeyType.Primary; } set { Key = value ? KeyType.Primary : KeyType.None; } } public bool IsPartOfPartialKey { get { return Key == KeyType.Partial; } set { Key = value ? KeyType.Partial : KeyType.None; } } public bool IsMultiValued { get; set; } public bool IsDerived { get; set; } public string DerivedFormula { get; set; } public bool IsDefault { get; set; } public string DefaultFormula { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ERMine.Core.Modeling { public class Attribute : IEntityRelationship { public string Label { get; set; } public string DataType { get; set; } public Domain Domain { get; set; } public bool IsConstrainedDomain { get { return Domain != null; } } public bool IsNullable { get; set; } public bool IsSparse { get; set; } public bool IsImmutable { get; set; } public KeyType Key { get; set; } public bool IsPartOfPrimaryKey { get { return Key == KeyType.Primary; } set { Key = value ? KeyType.Primary : KeyType.None; } } public bool IsPartOfPartialKey { get { return Key == KeyType.Partial; } set { Key = value ? KeyType.Partial : KeyType.None; } } public bool IsMultiValued { get; set; } public bool IsDerived { get; set; } public string DerivedFormula { get; set; } public bool IsDefault { get; set; } public string DefaultFormula { get; set; } } }
Add quick check for attached domain
Add quick check for attached domain
C#
apache-2.0
Seddryck/ERMine,Seddryck/ERMine
7dad561c96fb3bc32bb330c549a0ef4fca2bad93
PS.Mothership.Core/PS.Mothership.Core.Common/Dto/Application/OpportunitySummaryDto.cs
PS.Mothership.Core/PS.Mothership.Core.Common/Dto/Application/OpportunitySummaryDto.cs
using PS.Mothership.Core.Common.Template.Gen; using PS.Mothership.Core.Common.Template.Opp; using System; using System.Runtime.Serialization; namespace PS.Mothership.Core.Common.Dto.Application { [DataContract] public class OpportunitySummaryDto { [DataMember] public Guid OpportunityGuid { get; set; } [DataMember] public double Credit { get; set; } [DataMember] public double Debit { get; set; } [DataMember] public OppTypeOfTransactionEnum TypeOfTransactionKey { get; set; } [DataMember] public string Vendor { get; set; } [DataMember] public string Model { get; set; } [DataMember] public GenOpportunityStatusEnum OpportunityStatusKey { get; set; } [DataMember] public string ContractLengthDescription { get; set; } } }
using PS.Mothership.Core.Common.Template.Gen; using PS.Mothership.Core.Common.Template.Opp; using System; using System.Runtime.Serialization; namespace PS.Mothership.Core.Common.Dto.Application { [DataContract] public class OpportunitySummaryDto { [DataMember] public Guid OpportunityGuid { get; set; } [DataMember] public double Credit { get; set; } [DataMember] public double Debit { get; set; } [DataMember] public OppTypeOfTransactionEnum TypeOfTransactionKey { get; set; } [DataMember] public string ProductType { get; set; } [DataMember] public GenOpportunityStatusEnum OpportunityStatusKey { get; set; } [DataMember] public string ContractLengthDescription { get; set; } } }
Revert to use ProductType since this is all that is needed in the summary, as it is the only thing shown in the opportunity summary, in the offer page
Revert to use ProductType since this is all that is needed in the summary, as it is the only thing shown in the opportunity summary, in the offer page
C#
mit
Paymentsense/Dapper.SimpleSave
ce2d6b6b2f91a5e494b8038216be8a3eb881c223
Bex/Extensions/UriExtensions.cs
Bex/Extensions/UriExtensions.cs
using System; using System.Collections.Generic; using System.Linq; using System.Net; namespace Bex.Extensions { internal static class UriExtensions { internal static IEnumerable<KeyValuePair<string, string>> QueryString(this Uri uri) { var uriString = uri.IsAbsoluteUri ? uri.AbsoluteUri : uri.OriginalString; var queryIndex = uriString.IndexOf("?", StringComparison.OrdinalIgnoreCase); if (queryIndex == -1) { return Enumerable.Empty<KeyValuePair<string, string>>(); } var query = uriString.Substring(queryIndex + 1); return query.Split('&') .Where(x => !string.IsNullOrEmpty(x)) .Select(x => x.Split('=')) .Select(x => new KeyValuePair<string, string>(WebUtility.UrlDecode(x[0]), x.Length == 2 && !string.IsNullOrEmpty(x[1]) ? WebUtility.UrlDecode(x[1]) : null)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; namespace Bex.Extensions { internal static class UriExtensions { internal static IEnumerable<KeyValuePair<string, string>> QueryString(this Uri uri) { if (string.IsNullOrEmpty(uri.Query)) { return Enumerable.Empty<KeyValuePair<string, string>>(); } var query = uri.Query.TrimStart('?'); return query.Split('&') .Where(x => !string.IsNullOrEmpty(x)) .Select(x => x.Split('=')) .Select(x => new KeyValuePair<string, string>(WebUtility.UrlDecode(x[0]), x.Length == 2 && !string.IsNullOrEmpty(x[1]) ? WebUtility.UrlDecode(x[1]) : null)); } } }
Use the Query property of the Uri
Use the Query property of the Uri
C#
mit
ScottIsAFool/Bex,jamesmcroft/Bex
5f1d902ffcfe5fa5540edc741bc4caa77313b0e6
ExCSS/Properties/AssemblyInfo.cs
ExCSS/Properties/AssemblyInfo.cs
using System.Reflection; 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("ExCSS Parser")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ExCSS CSS Parser")] [assembly: AssemblyCopyright("")] [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("eb4daa16-725f-4c8f-9d74-b9b569d57f42")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("2.0.2")] [assembly: AssemblyFileVersion("2.0.2")]
using System.Reflection; 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("ExCSS Parser")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ExCSS CSS Parser")] [assembly: AssemblyCopyright("")] [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("eb4daa16-725f-4c8f-9d74-b9b569d57f42")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("2.0.3")] [assembly: AssemblyFileVersion("2.0.3")]
Align assembly verions with package release 2.0.3
Align assembly verions with package release 2.0.3 Current NuGet package release is at 2.0.3 (https://www.nuget.org/packages/ExCSS/2.0.3) but the assembly version attributes still reflect version 2.0.2.
C#
mit
bfreese/ExCSS
896814a4276302c5ed7cd43daf7faf24e64d435d
Octokit/Helpers/AcceptHeaders.cs
Octokit/Helpers/AcceptHeaders.cs
namespace Octokit { public static class AcceptHeaders { public const string StableVersion = "application/vnd.github.v3"; public const string StableVersionHtml = "application/vnd.github.html"; public const string RedirectsPreviewThenStableVersionJson = "application/vnd.github.quicksilver-preview+json; charset=utf-8, application/vnd.github.v3+json; charset=utf-8"; public const string LicensesApiPreview = "application/vnd.github.drax-preview+json"; public const string ProtectedBranchesApiPreview = "application/vnd.github.loki-preview+json"; public const string StarCreationTimestamps = "application/vnd.github.v3.star+json"; public const string IssueLockingUnlockingApiPreview = "application/vnd.github.the-key-preview+json"; public const string CommitReferenceSha1Preview = "application/vnd.github.chitauri-preview+sha"; public const string SquashCommitPreview = "application/vnd.github.polaris-preview+json"; public const string MigrationsApiPreview = " application/vnd.github.wyandotte-preview+json"; public const string OrganizationPermissionsPreview = "application/vnd.github.ironman-preview+json"; } }
using System.Diagnostics.CodeAnalysis; namespace Octokit { public static class AcceptHeaders { public const string StableVersion = "application/vnd.github.v3"; public const string StableVersionHtml = "application/vnd.github.html"; public const string RedirectsPreviewThenStableVersionJson = "application/vnd.github.quicksilver-preview+json; charset=utf-8, application/vnd.github.v3+json; charset=utf-8"; public const string LicensesApiPreview = "application/vnd.github.drax-preview+json"; public const string ProtectedBranchesApiPreview = "application/vnd.github.loki-preview+json"; public const string StarCreationTimestamps = "application/vnd.github.v3.star+json"; public const string IssueLockingUnlockingApiPreview = "application/vnd.github.the-key-preview+json"; public const string CommitReferenceSha1Preview = "application/vnd.github.chitauri-preview+sha"; public const string SquashCommitPreview = "application/vnd.github.polaris-preview+json"; public const string MigrationsApiPreview = " application/vnd.github.wyandotte-preview+json"; public const string OrganizationPermissionsPreview = "application/vnd.github.ironman-preview+json"; [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Gpg")] public const string GpgKeysPreview = "application/vnd.github.cryptographer-preview+sha"; } }
Add GPG Keys API preview header
Add GPG Keys API preview header
C#
mit
shiftkey-tester-org-blah-blah/octokit.net,shiftkey/octokit.net,shana/octokit.net,dampir/octokit.net,octokit/octokit.net,rlugojr/octokit.net,shiftkey-tester/octokit.net,TattsGroup/octokit.net,alfhenrik/octokit.net,ivandrofly/octokit.net,ivandrofly/octokit.net,thedillonb/octokit.net,Sarmad93/octokit.net,devkhan/octokit.net,shana/octokit.net,octokit/octokit.net,shiftkey/octokit.net,SmithAndr/octokit.net,Sarmad93/octokit.net,SmithAndr/octokit.net,eriawan/octokit.net,thedillonb/octokit.net,khellang/octokit.net,TattsGroup/octokit.net,dampir/octokit.net,devkhan/octokit.net,editor-tools/octokit.net,alfhenrik/octokit.net,M-Zuber/octokit.net,shiftkey-tester/octokit.net,eriawan/octokit.net,M-Zuber/octokit.net,adamralph/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,rlugojr/octokit.net,gdziadkiewicz/octokit.net,khellang/octokit.net,editor-tools/octokit.net,gdziadkiewicz/octokit.net
20cfa5d83fbe783e3f0520c216c871ccc27d17c8
osu.Game/Overlays/Settings/Sections/DebugSettings/GeneralSettings.cs
osu.Game/Overlays/Settings/Sections/DebugSettings/GeneralSettings.cs
// 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.Configuration; using osu.Framework.Graphics; using osu.Framework.Localisation; using osu.Framework.Screens; using osu.Game.Localisation; using osu.Game.Screens; using osu.Game.Screens.Import; namespace osu.Game.Overlays.Settings.Sections.DebugSettings { public class GeneralSettings : SettingsSubsection { protected override LocalisableString Header => DebugSettingsStrings.GeneralHeader; [BackgroundDependencyLoader(true)] private void load(FrameworkDebugConfigManager config, FrameworkConfigManager frameworkConfig, IPerformFromScreenRunner performer) { Children = new Drawable[] { new SettingsCheckbox { LabelText = DebugSettingsStrings.ShowLogOverlay, Current = frameworkConfig.GetBindable<bool>(FrameworkSetting.ShowLogOverlay) }, new SettingsCheckbox { LabelText = DebugSettingsStrings.BypassFrontToBackPass, Current = config.GetBindable<bool>(DebugSetting.BypassFrontToBackPass) } }; Add(new SettingsButton { Text = DebugSettingsStrings.ImportFiles, Action = () => performer?.PerformFromScreen(menu => menu.Push(new FileImportScreen())) }); } } }
// 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.Configuration; using osu.Framework.Graphics; using osu.Framework.Localisation; using osu.Framework.Screens; using osu.Game.Localisation; using osu.Game.Screens; using osu.Game.Screens.Import; namespace osu.Game.Overlays.Settings.Sections.DebugSettings { public class GeneralSettings : SettingsSubsection { protected override LocalisableString Header => DebugSettingsStrings.GeneralHeader; [BackgroundDependencyLoader(true)] private void load(FrameworkDebugConfigManager config, FrameworkConfigManager frameworkConfig, IPerformFromScreenRunner performer) { Children = new Drawable[] { new SettingsCheckbox { LabelText = DebugSettingsStrings.ShowLogOverlay, Current = frameworkConfig.GetBindable<bool>(FrameworkSetting.ShowLogOverlay) }, new SettingsCheckbox { LabelText = DebugSettingsStrings.BypassFrontToBackPass, Current = config.GetBindable<bool>(DebugSetting.BypassFrontToBackPass) }, new SettingsButton { Text = DebugSettingsStrings.ImportFiles, Action = () => performer?.PerformFromScreen(menu => menu.Push(new FileImportScreen())) }, new SettingsButton { Text = @"Run latency comparer", Action = () => performer?.PerformFromScreen(menu => menu.Push(new LatencyComparerScreen())) } }; } } }
Add button to access latency comparer from game
Add button to access latency comparer from game
C#
mit
peppy/osu,ppy/osu,ppy/osu,peppy/osu,ppy/osu,peppy/osu
3ce30673473fd124c536d786fb31bee70f96c9f1
src/AppHarbor.Tests/TextWriterCustomization.cs
src/AppHarbor.Tests/TextWriterCustomization.cs
using System; using System.IO; using Ploeh.AutoFixture; namespace AppHarbor.Tests { public class TextWriterCustomization : ICustomization { public void Customize(IFixture fixture) { fixture.Customize<TextWriter>(x => x.FromFactory(() => { return Console.Out; })); } } }
using System.IO; using Moq; using Ploeh.AutoFixture; namespace AppHarbor.Tests { public class TextWriterCustomization : ICustomization { public void Customize(IFixture fixture) { var textWriterMock = new Mock<TextWriter>(); fixture.Customize<TextWriter>(x => x.FromFactory(() => { return textWriterMock.Object; })); fixture.Customize<Mock<TextWriter>>(x => x.FromFactory(() => { return textWriterMock; })); } } }
Make sure to also customize Mock<TextWriter> and use same instance
Make sure to also customize Mock<TextWriter> and use same instance
C#
mit
appharbor/appharbor-cli
04c7bcb638909dbe83c1c0dfca36055a4ee464d9
src/Stripe/Services/Subscriptions/StripeSubscriptionUpdateOptions.cs
src/Stripe/Services/Subscriptions/StripeSubscriptionUpdateOptions.cs
using System; using Newtonsoft.Json; using System.Collections.Generic; namespace Stripe { public class StripeSubscriptionUpdateOptions : StripeSubscriptionCreateOptions { [JsonProperty("prorate")] public bool? Prorate { get; set; } } }
using System; using Newtonsoft.Json; using System.Collections.Generic; namespace Stripe { public class StripeSubscriptionUpdateOptions : StripeSubscriptionCreateOptions { [JsonProperty("prorate")] public bool? Prorate { get; set; } [JsonProperty("plan")] public string PlanId { get; set; } } }
Add "plan" to StripSubscriptionUpdateOptions so we can change plans.
Add "plan" to StripSubscriptionUpdateOptions so we can change plans.
C#
apache-2.0
haithemaraissia/stripe.net,DemocracyVenturesInc/stripe.net,weizensnake/stripe.net,duckwaffle/stripe.net,AvengingSyndrome/stripe.net,DemocracyVenturesInc/stripe.net,sidshetye/stripe.net,craigmckeachie/stripe.net,AvengingSyndrome/stripe.net,hattonpoint/stripe.net,Raganhar/stripe.net,agrogan/stripe.net,matthewcorven/stripe.net,matthewcorven/stripe.net,richardlawley/stripe.net,haithemaraissia/stripe.net,brentdavid2008/stripe.net,shirley-truong-volusion/stripe.net,weizensnake/stripe.net,sidshetye/stripe.net,chickenham/stripe.net,Raganhar/stripe.net,craigmckeachie/stripe.net,agrogan/stripe.net,chickenham/stripe.net,hattonpoint/stripe.net,shirley-truong-volusion/stripe.net,mathieukempe/stripe.net,mathieukempe/stripe.net,stripe/stripe-dotnet
2a1696b85d0307fa26d769623576d7ea3e42fedc
Server/LogExpire.cs
Server/LogExpire.cs
using System; using System.IO; namespace DarkMultiPlayerServer { public class LogExpire { private static string logDirectory { get { return Path.Combine(Server.universeDirectory, DarkLog.LogFolder); } } public static void ExpireLogs() { if (!Directory.Exists(logDirectory)) { //Screenshot directory is missing so there will be no screenshots to delete. return; } string[] logFiles = Directory.GetFiles(logDirectory); foreach (string logFile in logFiles) { Console.WriteLine("LogFile: " + logFile); //Check if the expireScreenshots setting is enabled if (Settings.settingsStore.expireLogs > 0) { //If the file is older than a day, delete it if (File.GetCreationTime(logFile).AddDays(Settings.settingsStore.expireLogs) < DateTime.Now) { DarkLog.Debug("Deleting saved log '" + logFile + "', reason: Expired!"); try { File.Delete(logFile); } catch (Exception e) { DarkLog.Error("Exception while trying to delete '" + logFile + "'!, Exception: " + e.Message); } } } } } } }
using System; using System.IO; namespace DarkMultiPlayerServer { public class LogExpire { private static string logDirectory { get { return Path.Combine(Server.universeDirectory, DarkLog.LogFolder); } } public static void ExpireLogs() { if (!Directory.Exists(logDirectory)) { //Screenshot directory is missing so there will be no screenshots to delete. return; } string[] logFiles = Directory.GetFiles(logDirectory); foreach (string logFile in logFiles) { //Check if the expireScreenshots setting is enabled if (Settings.settingsStore.expireLogs > 0) { //If the file is older than a day, delete it if (File.GetCreationTime(logFile).AddDays(Settings.settingsStore.expireLogs) < DateTime.Now) { DarkLog.Debug("Deleting saved log '" + logFile + "', reason: Expired!"); try { File.Delete(logFile); } catch (Exception e) { DarkLog.Error("Exception while trying to delete '" + logFile + "'!, Exception: " + e.Message); } } } } } } }
Remove debugging line. Sorry RockyTV!
Remove debugging line. Sorry RockyTV!
C#
mit
81ninja/DarkMultiPlayer,Dan-Shields/DarkMultiPlayer,godarklight/DarkMultiPlayer,81ninja/DarkMultiPlayer,rewdmister4/rewd-mod-packs,RockyTV/DarkMultiPlayer,Sanmilie/DarkMultiPlayer,RockyTV/DarkMultiPlayer,dsonbill/DarkMultiPlayer,Kerbas-ad-astra/DarkMultiPlayer,godarklight/DarkMultiPlayer
fe99bbd846a428da44f0a92ba6d4430a7f7811ff
Vocal/Core/JsonCommandLoader.cs
Vocal/Core/JsonCommandLoader.cs
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Vocal.Model; namespace Vocal.Core { public class JsonCommandLoader { const string DefaultConfigFile = "commandsTemplate.json"; const string WriteableConfigFile = "commands.json"; public static IEnumerable<IVoiceCommand> LoadCommandsFromConfiguration() { if(!File.Exists(WriteableConfigFile)) { CreateWriteableConfigFile(DefaultConfigFile, WriteableConfigFile); } if (!File.Exists(WriteableConfigFile)) throw new Exception($"There was an error creating the command configuration file {WriteableConfigFile}. You may need to create this file manually."); return JsonConvert.DeserializeObject<VoiceCommand[]>(File.ReadAllText(WriteableConfigFile)); } public static void CreateWriteableConfigFile(string source, string destination) { if (!File.Exists(source)) throw new Exception($"The source configuration file {source} does not exist. A writeable configuration cannot be created. See the documentation for more details."); File.Copy(source, destination); } } }
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using Vocal.Model; namespace Vocal.Core { public class JsonCommandLoader { const string AppDataFolder = "VocalBuildEngine"; const string DefaultConfigFile = "commandsTemplate.json"; const string WriteableCommandFile = "commands.json"; public static IEnumerable<IVoiceCommand> LoadCommandsFromConfiguration() { var commandFile = GetDefaultPath(WriteableCommandFile); if (!File.Exists(commandFile)) { var file = new FileInfo(commandFile); if (!Directory.Exists(file.Directory.FullName)) Directory.CreateDirectory(file.Directory.FullName); CreateWriteableConfigFile(DefaultConfigFile, commandFile); } if (!File.Exists(commandFile)) throw new Exception($"There was an error creating the command configuration file {commandFile}. You may need to create this file manually."); return JsonConvert.DeserializeObject<VoiceCommand[]>(File.ReadAllText(commandFile)); } public static void CreateWriteableConfigFile(string source, string destination) { if (!File.Exists(source)) throw new Exception($"The source configuration file {source} does not exist. A writeable configuration cannot be created. See the documentation for more details."); File.Copy(source, destination); } public static string GetDefaultPath(string fileName) { return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), AppDataFolder, fileName); } } }
Move command file to appdata
Move command file to appdata
C#
mit
adamsteinert/VoiceBuild
d9283b50d19a97a7b00886077467525f5ce618c3
FormFactory.Templates/Views/Shared/FormFactory/Property.FormFactory.ValueTypes.UploadedFile.cshtml
FormFactory.Templates/Views/Shared/FormFactory/Property.FormFactory.ValueTypes.UploadedFile.cshtml
@using FormFactory @model PropertyVm <input type="hidden" name="@Model.Name" id="MyFileSubmitPlaceHolder" />@*here to trick model binding into working :( *@ <input type="file" name="@Model.Name" @Model.Readonly() @Model.Disabled() />
@using FormFactory @model PropertyVm @if(!Model.Readonly) { <input type="hidden" name="@Model.Name" /> @*here to trick model binding into working :( *@ <input type="file" name="@Model.Name" @Model.Readonly() @Model.Disabled() /> }
Hide file input if readonly
Hide file input if readonly
C#
mit
mcintyre321/FormFactory,mcintyre321/FormFactory,mcintyre321/FormFactory
36ea8138bb4e7439945aecdcfb6e2e383de0c285
src/Workspaces/Core/Portable/Workspace/Host/PersistentStorage/IPersistentStorageLocationService.cs
src/Workspaces/Core/Portable/Workspace/Host/PersistentStorage/IPersistentStorageLocationService.cs
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Composition; using System.IO; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Serialization; namespace Microsoft.CodeAnalysis.Host { interface IPersistentStorageLocationService : IWorkspaceService { string TryGetStorageLocation(Solution solution); } [ExportWorkspaceService(typeof(IPersistentStorageLocationService)), Shared] internal class DefaultPersistentStorageLocationService : IPersistentStorageLocationService { [ImportingConstructor] public DefaultPersistentStorageLocationService() { } public string TryGetStorageLocation(Solution solution) { if (string.IsNullOrWhiteSpace(solution.FilePath)) return null; // Ensure that each unique workspace kind for any given solution has a unique // folder to store their data in. var checksums = new[] { Checksum.Create(solution.FilePath), Checksum.Create(solution.Workspace.Kind) }; var hashedName = Checksum.Create(WellKnownSynchronizationKind.Null, checksums).ToString(); var workingFolder = Path.Combine(Path.GetTempPath(), hashedName); return workingFolder; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Composition; using System.IO; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Serialization; namespace Microsoft.CodeAnalysis.Host { interface IPersistentStorageLocationService : IWorkspaceService { string TryGetStorageLocation(Solution solution); } [ExportWorkspaceService(typeof(IPersistentStorageLocationService)), Shared] internal class DefaultPersistentStorageLocationService : IPersistentStorageLocationService { [ImportingConstructor] public DefaultPersistentStorageLocationService() { } public string TryGetStorageLocation(Solution solution) { if (string.IsNullOrWhiteSpace(solution.FilePath)) return null; // Ensure that each unique workspace kind for any given solution has a unique // folder to store their data in. var checksums = new[] { Checksum.Create(solution.FilePath), Checksum.Create(solution.Workspace.Kind) }; var hashedName = Checksum.Create(WellKnownSynchronizationKind.Null, checksums).ToString(); var appDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData, Environment.SpecialFolderOption.Create); var workingFolder = Path.Combine(appDataFolder, "Roslyn", hashedName); return workingFolder; } } }
Switch to using LocalApplicationData folder
Switch to using LocalApplicationData folder
C#
mit
mavasani/roslyn,diryboy/roslyn,reaction1989/roslyn,shyamnamboodiripad/roslyn,sharwell/roslyn,KirillOsenkov/roslyn,jasonmalinowski/roslyn,tmat/roslyn,ErikSchierboom/roslyn,stephentoub/roslyn,aelij/roslyn,sharwell/roslyn,diryboy/roslyn,jmarolf/roslyn,heejaechang/roslyn,AmadeusW/roslyn,agocke/roslyn,brettfo/roslyn,genlu/roslyn,CyrusNajmabadi/roslyn,mavasani/roslyn,mavasani/roslyn,wvdd007/roslyn,genlu/roslyn,panopticoncentral/roslyn,wvdd007/roslyn,tmat/roslyn,bartdesmet/roslyn,tannergooding/roslyn,AlekseyTs/roslyn,physhi/roslyn,stephentoub/roslyn,KevinRansom/roslyn,KirillOsenkov/roslyn,eriawan/roslyn,wvdd007/roslyn,gafter/roslyn,gafter/roslyn,CyrusNajmabadi/roslyn,shyamnamboodiripad/roslyn,ErikSchierboom/roslyn,dotnet/roslyn,brettfo/roslyn,jasonmalinowski/roslyn,ErikSchierboom/roslyn,panopticoncentral/roslyn,aelij/roslyn,bartdesmet/roslyn,tannergooding/roslyn,panopticoncentral/roslyn,jmarolf/roslyn,abock/roslyn,bartdesmet/roslyn,AlekseyTs/roslyn,mgoertz-msft/roslyn,AmadeusW/roslyn,shyamnamboodiripad/roslyn,heejaechang/roslyn,davkean/roslyn,KevinRansom/roslyn,physhi/roslyn,abock/roslyn,reaction1989/roslyn,brettfo/roslyn,aelij/roslyn,mgoertz-msft/roslyn,heejaechang/roslyn,jasonmalinowski/roslyn,tannergooding/roslyn,mgoertz-msft/roslyn,sharwell/roslyn,CyrusNajmabadi/roslyn,diryboy/roslyn,AlekseyTs/roslyn,reaction1989/roslyn,eriawan/roslyn,weltkante/roslyn,dotnet/roslyn,AmadeusW/roslyn,abock/roslyn,gafter/roslyn,jmarolf/roslyn,dotnet/roslyn,stephentoub/roslyn,agocke/roslyn,agocke/roslyn,weltkante/roslyn,physhi/roslyn,eriawan/roslyn,davkean/roslyn,KirillOsenkov/roslyn,KevinRansom/roslyn,davkean/roslyn,tmat/roslyn,genlu/roslyn,weltkante/roslyn
c4c360f0331de13506bda9571bc59144a5b6f0d8
src/StockportContentApi/ContentfulFactories/CommsContentfulFactory.cs
src/StockportContentApi/ContentfulFactories/CommsContentfulFactory.cs
using System.Collections.Generic; using StockportContentApi.ContentfulModels; using StockportContentApi.Model; namespace StockportContentApi.ContentfulFactories { public class CommsContentfulFactory : IContentfulFactory<ContentfulCommsHomepage, CommsHomepage> { private readonly IContentfulFactory<ContentfulCallToActionBanner, CallToActionBanner> _callToActionFactory; private readonly IContentfulFactory<ContentfulEvent, Event> _eventFactory; private readonly IContentfulFactory<IEnumerable<ContentfulBasicLink>, IEnumerable<BasicLink>> _basicLinkFactory; public CommsContentfulFactory( IContentfulFactory<ContentfulCallToActionBanner, CallToActionBanner> callToActionFactory, IContentfulFactory<ContentfulEvent, Event> eventFactory, IContentfulFactory<IEnumerable<ContentfulBasicLink>, IEnumerable<BasicLink>> basicLinkFactory) { _callToActionFactory = callToActionFactory; _eventFactory = eventFactory; _basicLinkFactory = basicLinkFactory; } public CommsHomepage ToModel(ContentfulCommsHomepage model) { var callToActionBanner = _callToActionFactory.ToModel(model.CallToActionBanner); var displayEvent = _eventFactory.ToModel(model.WhatsOnInStockportEvent); var basicLinks = _basicLinkFactory.ToModel(model.UsefullLinks); return new CommsHomepage( model.Title, model.LatestNewsHeader, model.TwitterFeedHeader, model.InstagramFeedTitle, model.InstagramLink, model.FacebookFeedTitle, basicLinks, displayEvent, callToActionBanner ); } } }
using System.Collections.Generic; using StockportContentApi.ContentfulModels; using StockportContentApi.Model; namespace StockportContentApi.ContentfulFactories { public class CommsContentfulFactory : IContentfulFactory<ContentfulCommsHomepage, CommsHomepage> { private readonly IContentfulFactory<ContentfulCallToActionBanner, CallToActionBanner> _callToActionFactory; private readonly IContentfulFactory<ContentfulEvent, Event> _eventFactory; private readonly IContentfulFactory<IEnumerable<ContentfulBasicLink>, IEnumerable<BasicLink>> _basicLinkFactory; public CommsContentfulFactory( IContentfulFactory<ContentfulCallToActionBanner, CallToActionBanner> callToActionFactory, IContentfulFactory<ContentfulEvent, Event> eventFactory, IContentfulFactory<IEnumerable<ContentfulBasicLink>, IEnumerable<BasicLink>> basicLinkFactory) { _callToActionFactory = callToActionFactory; _eventFactory = eventFactory; _basicLinkFactory = basicLinkFactory; } public CommsHomepage ToModel(ContentfulCommsHomepage model) { var callToActionBanner = model.CallToActionBanner != null ? _callToActionFactory.ToModel(model.CallToActionBanner) : null; var displayEvent = _eventFactory.ToModel(model.WhatsOnInStockportEvent); var basicLinks = _basicLinkFactory.ToModel(model.UsefullLinks); return new CommsHomepage( model.Title, model.LatestNewsHeader, model.TwitterFeedHeader, model.InstagramFeedTitle, model.InstagramLink, model.FacebookFeedTitle, basicLinks, displayEvent, callToActionBanner ); } } }
Allow call to action banner to be optional
fix(Comms): Allow call to action banner to be optional
C#
mit
smbc-digital/iag-contentapi
a6381503661431715c2392ba65351de5cedafc1e
Source/Treenumerable/Properties/AssemblyInfo.cs
Source/Treenumerable/Properties/AssemblyInfo.cs
using System.Reflection; using System.Resources; 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("Treenumerable")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Jason Boyd")] [assembly: AssemblyProduct("Treenumerable")] [assembly: AssemblyCopyright("Copyright © Jason Boyd 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] [assembly: InternalsVisibleTo("Treenumerable.Tests")] // 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.2.0")] [assembly: AssemblyFileVersion("1.2.0")]
using System.Reflection; using System.Resources; 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("Treenumerable")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Jason Boyd")] [assembly: AssemblyProduct("Treenumerable")] [assembly: AssemblyCopyright("Copyright © Jason Boyd 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] [assembly: InternalsVisibleTo("Treenumerable.Tests")] // 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")] [assembly: AssemblyFileVersion("2.0.0")]
Update assembly version to 2.0.0
Update assembly version to 2.0.0
C#
mit
jasonmcboyd/Treenumerable
ad85cd64624756bf02bd9bc582b4a5adfee5cce9
src/OmniSharp.Host/MSBuild/Discovery/Providers/MonoInstanceProvider.cs
src/OmniSharp.Host/MSBuild/Discovery/Providers/MonoInstanceProvider.cs
using System; using System.Collections.Immutable; using System.IO; using Microsoft.Extensions.Logging; using OmniSharp.Utilities; namespace OmniSharp.MSBuild.Discovery.Providers { internal class MonoInstanceProvider : MSBuildInstanceProvider { public MonoInstanceProvider(ILoggerFactory loggerFactory) : base(loggerFactory) { } public override ImmutableArray<MSBuildInstance> GetInstances() { if (!PlatformHelper.IsMono) { return ImmutableArray<MSBuildInstance>.Empty; } var path = PlatformHelper.GetMonoMSBuildDirPath(); if (path == null) { return ImmutableArray<MSBuildInstance>.Empty; } var toolsPath = Path.Combine(path, "15.0", "bin"); if (!Directory.Exists(toolsPath)) { return ImmutableArray<MSBuildInstance>.Empty; } var propertyOverrides = ImmutableDictionary.CreateBuilder<string, string>(StringComparer.OrdinalIgnoreCase); var localMSBuildPath = FindLocalMSBuildDirectory(); if (localMSBuildPath != null) { var localRoslynPath = Path.Combine(localMSBuildPath, "Roslyn"); propertyOverrides.Add("CscToolPath", localRoslynPath); propertyOverrides.Add("CscToolExe", "csc.exe"); } return ImmutableArray.Create( new MSBuildInstance( "Mono", toolsPath, new Version(15, 0), DiscoveryType.Mono, propertyOverrides.ToImmutable())); } } }
using System; using System.Collections.Immutable; using System.IO; using Microsoft.Extensions.Logging; using OmniSharp.Utilities; namespace OmniSharp.MSBuild.Discovery.Providers { internal class MonoInstanceProvider : MSBuildInstanceProvider { public MonoInstanceProvider(ILoggerFactory loggerFactory) : base(loggerFactory) { } public override ImmutableArray<MSBuildInstance> GetInstances() { if (!PlatformHelper.IsMono) { return ImmutableArray<MSBuildInstance>.Empty; } var path = PlatformHelper.GetMonoMSBuildDirPath(); if (path == null) { return ImmutableArray<MSBuildInstance>.Empty; } var toolsPath = Path.Combine(path, "15.0", "bin"); if (!Directory.Exists(toolsPath)) { return ImmutableArray<MSBuildInstance>.Empty; } var propertyOverrides = ImmutableDictionary.CreateBuilder<string, string>(StringComparer.OrdinalIgnoreCase); var localMSBuildPath = FindLocalMSBuildDirectory(); if (localMSBuildPath != null) { var localRoslynPath = Path.Combine(localMSBuildPath, "15.0", "Bin", "Roslyn"); propertyOverrides.Add("CscToolPath", localRoslynPath); propertyOverrides.Add("CscToolExe", "csc.exe"); } return ImmutableArray.Create( new MSBuildInstance( "Mono", toolsPath, new Version(15, 0), DiscoveryType.Mono, propertyOverrides.ToImmutable())); } } }
Use correct path to MSBuild Roslyn folder on Mono
Use correct path to MSBuild Roslyn folder on Mono
C#
mit
OmniSharp/omnisharp-roslyn,OmniSharp/omnisharp-roslyn,DustinCampbell/omnisharp-roslyn,DustinCampbell/omnisharp-roslyn
1c7dde06474edb028de8def5b2905a9ccc02d85d
src/NTwitch.Core/ITwitchClient.cs
src/NTwitch.Core/ITwitchClient.cs
using System.Collections.Generic; using System.Threading.Tasks; namespace NTwitch { public interface ITwitchClient { ConnectionState ConnectionState { get; } Task<IChannel> GetChannelAsync(ulong id); Task<IEnumerable<ITopGame>> GetTopGames(TwitchPageOptions options = null); Task<IEnumerable<IIngest>> GetIngestsAsync(); Task<IEnumerable<IChannel>> FindChannelsAsync(string query, TwitchPageOptions options = null); Task<IEnumerable<IGame>> FindGamesAsync(string query, bool islive = true); Task<IStream> GetStreamAsync(ulong id, StreamType type = StreamType.All); Task<IEnumerable<IStream>> FindStreamsAsync(string query, bool hls = true, TwitchPageOptions options = null); Task<IEnumerable<IStream>> GetStreamsAsync(string game = null, ulong[] channelids = null, string language = null, StreamType type = StreamType.All, TwitchPageOptions options = null); Task<IEnumerable<IFeaturedStream>> GetFeaturedStreamsAsync(TwitchPageOptions options = null); Task<IEnumerable<IStreamSummary>> GetStreamSummaryAsync(string game); Task<IEnumerable<ITeamInfo>> GetTeamsAsync(TwitchPageOptions options = null); Task<IEnumerable<ITeam>> GetTeamAsync(string name); Task<IUser> GetUserAsync(ulong id); } }
using System.Collections.Generic; using System.Threading.Tasks; namespace NTwitch { public interface ITwitchClient { ConnectionState ConnectionState { get; } Task<IChannel> GetChannelAsync(ulong id); Task<IEnumerable<ITopGame>> GetTopGamesAsync(TwitchPageOptions options = null); Task<IEnumerable<IIngest>> GetIngestsAsync(); Task<IEnumerable<IChannel>> FindChannelsAsync(string query, TwitchPageOptions options = null); Task<IEnumerable<IGame>> FindGamesAsync(string query, bool islive = true); Task<IStream> GetStreamAsync(ulong id, StreamType type = StreamType.All); Task<IEnumerable<IStream>> FindStreamsAsync(string query, bool hls = true, TwitchPageOptions options = null); Task<IEnumerable<IStream>> GetStreamsAsync(string game = null, ulong[] channelids = null, string language = null, StreamType type = StreamType.All, TwitchPageOptions options = null); Task<IEnumerable<IFeaturedStream>> GetFeaturedStreamsAsync(TwitchPageOptions options = null); Task<IEnumerable<IStreamSummary>> GetStreamSummaryAsync(string game); Task<IEnumerable<ITeamInfo>> GetTeamsAsync(TwitchPageOptions options = null); Task<IEnumerable<ITeam>> GetTeamAsync(string name); Task<IUser> GetUserAsync(ulong id); } }
Add missing Async name to GetTopGames
Add missing Async name to GetTopGames
C#
mit
Aux/NTwitch,Aux/NTwitch
b86def3325c228f62c28c4a337f0839e51ba1259
Domain/SystemClock.cs
Domain/SystemClock.cs
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Diagnostics; namespace Microsoft.Its.Domain { /// <summary> /// Provides access to system time. /// </summary> [DebuggerStepThrough] public class SystemClock : IClock { public static readonly SystemClock Instance = new SystemClock(); private SystemClock() { } /// <summary> /// Gets the current time via <see cref="DateTimeOffset.Now" />. /// </summary> public DateTimeOffset Now() { return DateTimeOffset.Now; } public override string ToString() { return GetType() + ": " + Now().ToString("O"); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Diagnostics; namespace Microsoft.Its.Domain { /// <summary> /// Provides access to system time. /// </summary> [DebuggerStepThrough] public class SystemClock : IClock { public static readonly SystemClock Instance = new SystemClock(); private SystemClock() { } /// <summary> /// Gets the current time via <see cref="DateTimeOffset.Now" />. /// </summary> public DateTimeOffset Now() { return DateTimeOffset.UtcNow; } public override string ToString() { return GetType() + ": " + Now().ToString("O"); } } }
Update the systemclock to use UtcNow. This is because some of code use Month, Year properties of DateTimeOffset
Update the systemclock to use UtcNow. This is because some of code use Month, Year properties of DateTimeOffset
C#
mit
askheaves/Its.Cqrs,commonsensesoftware/Its.Cqrs,commonsensesoftware/Its.Cqrs,askheaves/Its.Cqrs,commonsensesoftware/Its.Cqrs,askheaves/Its.Cqrs
ac2a5002042999bc715b7cb143f240cb49597e11
src/StockportWebapp/Views/stockportgov/ContactUs/ThankYouMessage.cshtml
src/StockportWebapp/Views/stockportgov/ContactUs/ThankYouMessage.cshtml
@model string @{ ViewData["Title"] = "Thank you"; ViewData["og:title"] = "Thank you"; Layout = "../Shared/_Layout.cshtml"; } <div class="grid-container-full-width"> <div class="grid-container grid-100"> <div class="l-body-section-filled l-short-content mobile-grid-100 tablet-grid-100 grid-100"> <section aria-label="Thank you message" class="grid-100 mobile-grid-100"> <div class="l-content-container l-article-container"> <h1>Thank you for contacting us</h1> <p>We will aim to respond to your enquiry within 10 working days.</p> <stock-button href="@Model">Return to previous page</stock-button> </div> </section> </div> </div> </div>
@model string @{ ViewData["Title"] = "Thank you"; ViewData["og:title"] = "Thank you"; Layout = "../Shared/_Layout.cshtml"; } <div class="grid-container-full-width"> <div class="grid-container grid-100"> <div class="l-body-section-filled l-short-content mobile-grid-100 tablet-grid-100 grid-100"> <section aria-label="Thank you message" class="grid-100 mobile-grid-100"> <div class="l-content-container l-article-container"> <h1>Thank you for contacting us</h1> <p>We will endeavour to respond to your enquiry within 10 working days.</p> <stock-button href="@Model">Return To Previous Page</stock-button> </div> </section> </div> </div> </div>
Revert "Gary changed wording per content request"
Revert "Gary changed wording per content request" This reverts commit 6236a41d67d021860f6073aa5a1ad72cccd52bc9.
C#
mit
smbc-digital/iag-webapp,smbc-digital/iag-webapp,smbc-digital/iag-webapp
4d0ccc57991b723620695cf5ae7f3640dd6fd588
TapBoxWebApplication/TapBoxWebjob/MailSender.cs
TapBoxWebApplication/TapBoxWebjob/MailSender.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Net; using System.Net.Mail; using SendGrid; using TapBoxCommon.Models; using Microsoft.Azure; namespace TapBoxWebjob { class MailSender { public static void SendMailToOwner(Device NotifierDevice, int SensorValue) { SendGridMessage myMessage = new SendGridMessage(); myMessage.AddTo(NotifierDevice.OwnerMailAddress); myMessage.From = new MailAddress("sjost@hsr.ch", "Samuel Jost"); myMessage.Subject = "Notification from your Tapbox"; Console.WriteLine($"Device: {NotifierDevice.DeviceName} - Sensor Value: {SensorValue}"); if (SensorValue < 20) { Console.WriteLine("Your Mailbox is Empty"); return; } else if (SensorValue < 300) { Console.WriteLine("You have some Mail"); myMessage.Text = "You have some Mail in your device "+NotifierDevice.DeviceName; } else if (SensorValue > 300) { Console.WriteLine("You have A Lot of Mail"); myMessage.Text = "You have a lot of Mail in your device " + NotifierDevice.DeviceName; } var apiKey = CloudConfigurationManager.GetSetting("SendGrid.API_Key"); var transportWeb = new Web(apiKey); // Send the email, which returns an awaitable task. transportWeb.DeliverAsync(myMessage); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Net; using System.Net.Mail; using SendGrid; using TapBoxCommon.Models; using Microsoft.Azure; namespace TapBoxWebjob { class MailSender { public static void SendMailToOwner(Device NotifierDevice, int SensorValue) { SendGridMessage myMessage = new SendGridMessage(); myMessage.AddTo(NotifierDevice.OwnerMailAddress); myMessage.From = new MailAddress("sjost@hsr.ch", "Samuel Jost"); myMessage.Subject = "Notification from your Tapbox"; Console.WriteLine($"Device: {NotifierDevice.DeviceName} - Sensor Value: {SensorValue}"); if (SensorValue < 100) { Console.WriteLine("Your Mailbox is Empty"); return; } else if (SensorValue < 300) { Console.WriteLine("You have some Mail"); myMessage.Text = "You have some Mail in your device "+NotifierDevice.DeviceName; } else if (SensorValue > 300) { Console.WriteLine("You have A Lot of Mail"); myMessage.Text = "You have a lot of Mail in your device " + NotifierDevice.DeviceName; } var apiKey = CloudConfigurationManager.GetSetting("SendGrid.API_Key"); var transportWeb = new Web(apiKey); // Send the email, which returns an awaitable task. transportWeb.DeliverAsync(myMessage); } } }
Change Sensor level to 100
Change Sensor level to 100
C#
mit
rehrbar/ChallP2TapBox,rehrbar/ChallP2TapBox,rehrbar/ChallP2TapBox,rehrbar/ChallP2TapBox,rehrbar/ChallP2TapBox
6515a6377e48ccec843ca6605fb89a6c2f37f2fa
Source/Csla.Wp/PortedAttributes.cs
Source/Csla.Wp/PortedAttributes.cs
using System; namespace Csla { internal class BrowsableAttribute : Attribute { public BrowsableAttribute(bool flag) { } } internal class DisplayAttribute : Attribute { public string Name { get; set; } public bool AutoGenerateField { get; set; } public DisplayAttribute(bool AutoGenerateField = false, string Name = "") { this.AutoGenerateField = AutoGenerateField; this.Name = Name; } } }
//----------------------------------------------------------------------- // <copyright file="PortedAttributes.cs" company="Marimer LLC"> // Copyright (c) Marimer LLC. All rights reserved. // Website: http://www.lhotka.net/cslanet/ // </copyright> // <summary>Dummy implementations of .NET attributes missing in WP7.</summary> //----------------------------------------------------------------------- using System; namespace Csla { internal class BrowsableAttribute : Attribute { public BrowsableAttribute(bool flag) { } } internal class DisplayAttribute : Attribute { public string Name { get; set; } public bool AutoGenerateField { get; set; } public DisplayAttribute(bool AutoGenerateField = false, string Name = "") { this.AutoGenerateField = AutoGenerateField; this.Name = Name; } } }
Add missing comment block. bugid: 812
Add missing comment block. bugid: 812
C#
mit
ronnymgm/csla-light,rockfordlhotka/csla,BrettJaner/csla,rockfordlhotka/csla,jonnybee/csla,BrettJaner/csla,MarimerLLC/csla,ronnymgm/csla-light,JasonBock/csla,jonnybee/csla,BrettJaner/csla,jonnybee/csla,JasonBock/csla,ronnymgm/csla-light,MarimerLLC/csla,MarimerLLC/csla,rockfordlhotka/csla,JasonBock/csla
9901a01f0bf883a5689dc0f531facf042d9b8feb
src/FeatureSwitcher.AwsConfiguration/Models/BehaviourCacheItem.cs
src/FeatureSwitcher.AwsConfiguration/Models/BehaviourCacheItem.cs
using System; using FeatureSwitcher.AwsConfiguration.Behaviours; namespace FeatureSwitcher.AwsConfiguration.Models { internal class BehaviourCacheItem { public IBehaviour Behaviour { get; } public DateTime CacheTimeout { get; } public bool IsExpired => this.CacheTimeout < DateTime.UtcNow; public BehaviourCacheItem(IBehaviour behaviour, TimeSpan cacheTime) { Behaviour = behaviour; CacheTimeout = DateTime.UtcNow.Add(cacheTime); } public void ExtendCache() { CacheTimeout.Add(TimeSpan.FromMinutes(1)); } } }
using System; using FeatureSwitcher.AwsConfiguration.Behaviours; namespace FeatureSwitcher.AwsConfiguration.Models { internal class BehaviourCacheItem { public IBehaviour Behaviour { get; } public DateTime CacheTimeout { get; private set; } public bool IsExpired => this.CacheTimeout < DateTime.UtcNow; public BehaviourCacheItem(IBehaviour behaviour, TimeSpan cacheTime) { Behaviour = behaviour; CacheTimeout = DateTime.UtcNow.Add(cacheTime); } public void ExtendCache() { CacheTimeout = CacheTimeout.Add(TimeSpan.FromMinutes(1)); } } }
Fix bug: Ensure CacheTimeout is actually set when extending cache.
Fix bug: Ensure CacheTimeout is actually set when extending cache.
C#
apache-2.0
queueit/FeatureSwitcher.AwsConfiguration
5af7e8db71eb0133aad4d46f0571db1168952522
TruckRouter/Program.cs
TruckRouter/Program.cs
using TruckRouter.Models; var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); builder.Services.AddTransient<IMazeSolver, MazeSolverBFS>(); var app = builder.Build(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); app.UseDeveloperExceptionPage(); } else { app.UseHttpsRedirection(); app.UseAuthorization(); } app.UseHttpsRedirection(); app.UseAuthorization(); app.MapControllers(); app.Run();
using TruckRouter.Models; var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); builder.Services.AddTransient<IMazeSolver, MazeSolverBFS>(); var app = builder.Build(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); app.UseDeveloperExceptionPage(); } else { app.UseHttpsRedirection(); app.UseAuthorization(); } app.MapControllers(); app.Run();
Remove code that unconditionally enable https redirects and authorization
Remove code that unconditionally enable https redirects and authorization
C#
mit
surlycoder/truck-router
4c822bbdd11c58e1d2fb959240643d51d6ba893d
src/SyncTrayzor/Syncthing/ApiClient/SyncthingHttpClientHandler.cs
src/SyncTrayzor/Syncthing/ApiClient/SyncthingHttpClientHandler.cs
using NLog; using System.Net.Http; using System.Threading; using System.Threading.Tasks; namespace SyncTrayzor.Syncthing.ApiClient { public class SyncthingHttpClientHandler : WebRequestHandler { private static readonly Logger logger = LogManager.GetCurrentClassLogger(); public SyncthingHttpClientHandler() { // We expect Syncthing to return invalid certs this.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true; } protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var response = await base.SendAsync(request, cancellationToken); if (response.IsSuccessStatusCode) logger.Trace(() => response.Content.ReadAsStringAsync().Result.Trim()); else logger.Warn("Non-successful status code. {0} {1}", response, (await response.Content.ReadAsStringAsync()).Trim()); return response; } } }
using NLog; using System.Net.Http; using System.Threading; using System.Threading.Tasks; namespace SyncTrayzor.Syncthing.ApiClient { public class SyncthingHttpClientHandler : WebRequestHandler { private static readonly Logger logger = LogManager.GetCurrentClassLogger(); public SyncthingHttpClientHandler() { // We expect Syncthing to return invalid certs this.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true; } protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var response = await base.SendAsync(request, cancellationToken); // We're getting null bodies from somewhere: try and figure out where var responseString = await response.Content.ReadAsStringAsync(); if (responseString == null) logger.Warn($"Null response received from {request.RequestUri}. {response}. Content (again): {response.Content.ReadAsStringAsync()}"); if (response.IsSuccessStatusCode) logger.Trace(() => response.Content.ReadAsStringAsync().Result.Trim()); else logger.Warn("Non-successful status code. {0} {1}", response, (await response.Content.ReadAsStringAsync()).Trim()); return response; } } }
Add logging in case of null response from Syncthing
Add logging in case of null response from Syncthing
C#
mit
canton7/SyncTrayzor,canton7/SyncTrayzor,canton7/SyncTrayzor
71cd91a9d07508d2170cbf50759e703c97ae9b5e
src/Host/Client/Impl/Extensions/AboutHostExtensions.cs
src/Host/Client/Impl/Extensions/AboutHostExtensions.cs
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System; using System.Reflection; using Microsoft.Common.Core; using Microsoft.R.Host.Protocol; namespace Microsoft.R.Host.Client { public static class AboutHostExtensions { private static Version _localVersion; static AboutHostExtensions() { _localVersion = typeof(AboutHost).GetTypeInfo().Assembly.GetName().Version; } public static string IsHostVersionCompatible(this AboutHost aboutHost) { if (_localVersion.Major != 0 || _localVersion.Minor != 0) { // Filter out debug builds var serverVersion = new Version(aboutHost.Version.Major, aboutHost.Version.Minor); var clientVersion = new Version(_localVersion.Major, _localVersion.Minor); if (serverVersion > clientVersion) { return Resources.Error_RemoteVersionHigher.FormatInvariant(aboutHost.Version, _localVersion); } if (serverVersion < clientVersion) { return Resources.Error_RemoteVersionLower.FormatInvariant(aboutHost.Version, _localVersion); } } return null; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System; using System.Reflection; using Microsoft.Common.Core; using Microsoft.R.Host.Protocol; namespace Microsoft.R.Host.Client { public static class AboutHostExtensions { private static Version _localVersion; static AboutHostExtensions() { _localVersion = typeof(AboutHost).GetTypeInfo().Assembly.GetName().Version; } public static string IsHostVersionCompatible(this AboutHost aboutHost) { #if !DEBUG if (_localVersion.Major != 0 || _localVersion.Minor != 0) { // Filter out debug builds var serverVersion = new Version(aboutHost.Version.Major, aboutHost.Version.Minor); var clientVersion = new Version(_localVersion.Major, _localVersion.Minor); if (serverVersion > clientVersion) { return Resources.Error_RemoteVersionHigher.FormatInvariant(aboutHost.Version, _localVersion); } if (serverVersion < clientVersion) { return Resources.Error_RemoteVersionLower.FormatInvariant(aboutHost.Version, _localVersion); } } #endif return null; } } }
Allow debug mode to connect to any version of remote.
Allow debug mode to connect to any version of remote.
C#
mit
MikhailArkhipov/RTVS,AlexanderSher/RTVS,AlexanderSher/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS,AlexanderSher/RTVS,MikhailArkhipov/RTVS,MikhailArkhipov/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS,karthiknadig/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS
83fdedd0856c4e85f99bdc6ff2225504a247e552
RedGate.AppHost.Remoting/ClientChannelSinkProviderForParticularServer.cs
RedGate.AppHost.Remoting/ClientChannelSinkProviderForParticularServer.cs
using System.Runtime.Remoting.Channels; namespace RedGate.AppHost.Remoting { internal class ClientChannelSinkProviderForParticularServer : IClientChannelSinkProvider { private readonly IClientChannelSinkProvider m_Upstream; private readonly string m_Url; internal ClientChannelSinkProviderForParticularServer(IClientChannelSinkProvider upstream, string id) { if (upstream == null) throw new ArgumentNullException("upstream"); if (String.IsNullOrEmpty(id)) throw new ArgumentNullException("id"); m_Upstream = upstream; m_Url = string.Format("ipc://{0}", id); } public IClientChannelSinkProvider Next { get { return m_Upstream.Next; } set { m_Upstream.Next = value; } } public IClientChannelSink CreateSink(IChannelSender channel, string url, object remoteChannelData) { return url == m_Url ? m_Upstream.CreateSink(channel, url, remoteChannelData) : null; } } }
using System; using System.Runtime.Remoting.Channels; namespace RedGate.AppHost.Remoting { internal class ClientChannelSinkProviderForParticularServer : IClientChannelSinkProvider { private readonly IClientChannelSinkProvider m_Upstream; private readonly string m_Url; internal ClientChannelSinkProviderForParticularServer(IClientChannelSinkProvider upstream, string id) { if (upstream == null) throw new ArgumentNullException("upstream"); if (String.IsNullOrEmpty(id)) throw new ArgumentNullException("id"); m_Upstream = upstream; m_Url = string.Format("ipc://{0}", id); } public IClientChannelSinkProvider Next { get { return m_Upstream.Next; } set { m_Upstream.Next = value; } } public IClientChannelSink CreateSink(IChannelSender channel, string url, object remoteChannelData) { //Returning null indicates that the sink cannot be created as per Microsoft documentation return url == m_Url ? m_Upstream.CreateSink(channel, url, remoteChannelData) : null; } } }
Document why null is ok here
Document why null is ok here
C#
apache-2.0
red-gate/RedGate.AppHost,nycdotnet/RedGate.AppHost
d3af3ff05dad12e8c9b7d894b011f623b1f3851a
BatteryCommander.Common/Models/Rank.cs
BatteryCommander.Common/Models/Rank.cs
using System.ComponentModel.DataAnnotations; namespace BatteryCommander.Common.Models { public enum Rank { [Display(Name = "PVT")] E1 = 1, [Display(Name = "PV2")] E2 = 2, [Display(Name = "PFC")] E3 = 3, [Display(Name = "SPC")] E4 = 4, [Display(Name = "SGT")] E5 = 5, [Display(Name = "SSG")] E6 = 6, [Display(Name = "SFC")] E7 = 7, [Display(Name = "1SG")] E8 = 8, Cadet = 9, [Display(Name = "2LT")] O1 = 10, [Display(Name = "1LT")] O2 = 11, [Display(Name = "CPT")] O3 = 12, [Display(Name = "MAJ")] O4 = 13, [Display(Name = "LTC")] O5 = 14, [Display(Name = "COL")] O6 = 15 } }
using System.ComponentModel.DataAnnotations; namespace BatteryCommander.Common.Models { public enum Rank { [Display(Name = "PVT")] E1 = 1, [Display(Name = "PV2")] E2 = 2, [Display(Name = "PFC")] E3 = 3, [Display(Name = "SPC")] E4 = 4, [Display(Name = "SGT")] E5 = 5, [Display(Name = "SSG")] E6 = 6, [Display(Name = "SFC")] E7 = 7, [Display(Name = "1SG")] E8 = 8, [Display(Name = "CDT")] Cadet = 9, [Display(Name = "2LT")] O1 = 10, [Display(Name = "1LT")] O2 = 11, [Display(Name = "CPT")] O3 = 12, [Display(Name = "MAJ")] O4 = 13, [Display(Name = "LTC")] O5 = 14, [Display(Name = "COL")] O6 = 15 } }
Add a display property for cadet rank
Add a display property for cadet rank
C#
mit
mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander
41cf2b9575075b07d8aa55607ddfdf8c78766f22
src/Common/CommonAssemblyInfo.cs
src/Common/CommonAssemblyInfo.cs
using System.Reflection; [assembly: AssemblyCompany("Immo Landwerth")] [assembly: AssemblyProduct("NuProj")] [assembly: AssemblyCopyright("Copyright © Immo Landwerth")] [assembly: AssemblyTrademark("")] [assembly : AssemblyMetadata("PreRelease", "Beta")] [assembly : AssemblyMetadata("ProjectUrl", "http://nuproj.codeplex.com")] [assembly : AssemblyMetadata("LicenseUrl", "http://nuproj.codeplex.com/license")] [assembly: AssemblyVersion("0.9.2.0")] [assembly: AssemblyFileVersion("0.9.2.0")]
using System.Reflection; [assembly: AssemblyCompany("Immo Landwerth")] [assembly: AssemblyProduct("NuProj")] [assembly: AssemblyCopyright("Copyright © Immo Landwerth")] [assembly: AssemblyTrademark("")] [assembly : AssemblyMetadata("PreRelease", "Beta")] [assembly : AssemblyMetadata("ProjectUrl", "http://github.com/terrajobst/nuproj")] [assembly : AssemblyMetadata("LicenseUrl", "https://raw.githubusercontent.com/terrajobst/nuproj/master/LICENSE")] [assembly: AssemblyVersion("0.9.2.0")] [assembly: AssemblyFileVersion("0.9.2.0")]
Update project and license URLs
Update project and license URLs
C#
mit
PedroLamas/nuproj,faustoscardovi/nuproj,kovalikp/nuproj,DavidAnson/nuproj,DavidAnson/nuproj,AArnott/nuproj,nuproj/nuproj,NN---/nuproj,ericstj/nuproj,oliver-feng/nuproj,zbrad/nuproj
b88c441d8be6cbd2c2707938369539ef61dccf08
src/AppHarbor/AppHarborInstaller.cs
src/AppHarbor/AppHarborInstaller.cs
using System.Reflection; using Castle.MicroKernel.Registration; using Castle.MicroKernel.Resolvers.SpecializedResolvers; using Castle.MicroKernel.SubSystems.Configuration; using Castle.Windsor; namespace AppHarbor { public class AppHarborInstaller : IWindsorInstaller { public void Install(IWindsorContainer container, IConfigurationStore store) { container.Kernel.Resolver.AddSubResolver(new CollectionResolver(container.Kernel)); container.Register(AllTypes.FromThisAssembly() .BasedOn<ICommand>()); container.Register(Component .For<IAccessTokenConfiguration>() .ImplementedBy<AccessTokenConfiguration>()); container.Register(Component .For<AppHarborClient>() .UsingFactoryMethod(x => { var accessTokenConfiguration = container.Resolve<AccessTokenConfiguration>(); return new AppHarborClient(accessTokenConfiguration.GetAccessToken()); })); container.Register(Component .For<CommandDispatcher>() .UsingFactoryMethod(x => { return new CommandDispatcher(Assembly.GetExecutingAssembly().GetExportedTypes(), container.Kernel); })); container.Register(Component .For<IFileSystem>() .ImplementedBy<PhysicalFileSystem>() .LifeStyle.Transient); } } }
using System.Reflection; using Castle.MicroKernel.Registration; using Castle.MicroKernel.Resolvers.SpecializedResolvers; using Castle.MicroKernel.SubSystems.Configuration; using Castle.Windsor; namespace AppHarbor { public class AppHarborInstaller : IWindsorInstaller { public void Install(IWindsorContainer container, IConfigurationStore store) { container.Kernel.Resolver.AddSubResolver(new CollectionResolver(container.Kernel)); container.Register(AllTypes.FromThisAssembly() .BasedOn<ICommand>()); container.Register(Component .For<IAccessTokenConfiguration>() .ImplementedBy<AccessTokenConfiguration>()); container.Register(Component .For<IAppHarborClient>() .UsingFactoryMethod(x => { return new AppHarborClient(accessTokenConfiguration.GetAccessToken()); })); container.Register(Component .For<CommandDispatcher>() .UsingFactoryMethod(x => { return new CommandDispatcher(Assembly.GetExecutingAssembly().GetExportedTypes(), container.Kernel); })); container.Register(Component .For<IFileSystem>() .ImplementedBy<PhysicalFileSystem>() .LifeStyle.Transient); } } }
Make sure to register interface rather than implementation
Make sure to register interface rather than implementation
C#
mit
appharbor/appharbor-cli
2b33c5cfd75fc979f259a2eceab3f5ff5a8ae191
src/Umbraco.Web/Trees/MemberTypeTreeController.cs
src/Umbraco.Web/Trees/MemberTypeTreeController.cs
using System.Collections.Generic; using System.Linq; using System.Net.Http.Formatting; using Umbraco.Core; using Umbraco.Web.Models.Trees; using Umbraco.Web.WebApi.Filters; namespace Umbraco.Web.Trees { [CoreTree(TreeGroup =Constants.Trees.Groups.Settings)] [UmbracoTreeAuthorize(Constants.Trees.MemberTypes)] [Tree(Constants.Applications.Settings, Constants.Trees.MemberTypes, null, sortOrder: 2)] public class MemberTypeTreeController : MemberTypeAndGroupTreeControllerBase { protected override IEnumerable<TreeNode> GetTreeNodesFromService(string id, FormDataCollection queryStrings) { return Services.MemberTypeService.GetAll() .OrderBy(x => x.Name) .Select(dt => CreateTreeNode(dt, Constants.ObjectTypes.MemberType, id, queryStrings, "icon-item-arrangement", false)); } } }
using System.Collections.Generic; using System.Linq; using System.Net.Http.Formatting; using Umbraco.Core; using Umbraco.Web.Models.Trees; using Umbraco.Web.WebApi.Filters; namespace Umbraco.Web.Trees { [CoreTree(TreeGroup = Constants.Trees.Groups.Settings)] [UmbracoTreeAuthorize(Constants.Trees.MemberTypes)] [Tree(Constants.Applications.Settings, Constants.Trees.MemberTypes, null, sortOrder: 2)] public class MemberTypeTreeController : MemberTypeAndGroupTreeControllerBase { protected override TreeNode CreateRootNode(FormDataCollection queryStrings) { var root = base.CreateRootNode(queryStrings); //check if there are any member types root.HasChildren = Services.MemberTypeService.GetAll().Any(); return root; } protected override IEnumerable<TreeNode> GetTreeNodesFromService(string id, FormDataCollection queryStrings) { return Services.MemberTypeService.GetAll() .OrderBy(x => x.Name) .Select(dt => CreateTreeNode(dt, Constants.ObjectTypes.MemberType, id, queryStrings, "icon-item-arrangement", false)); } } }
Fix for chekcing the children belonging to MemberType tree.
Fix for chekcing the children belonging to MemberType tree.
C#
mit
WebCentrum/Umbraco-CMS,tcmorris/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,arknu/Umbraco-CMS,robertjf/Umbraco-CMS,abjerner/Umbraco-CMS,KevinJump/Umbraco-CMS,KevinJump/Umbraco-CMS,leekelleher/Umbraco-CMS,leekelleher/Umbraco-CMS,robertjf/Umbraco-CMS,dawoe/Umbraco-CMS,abjerner/Umbraco-CMS,madsoulswe/Umbraco-CMS,tompipe/Umbraco-CMS,umbraco/Umbraco-CMS,rasmuseeg/Umbraco-CMS,bjarnef/Umbraco-CMS,lars-erik/Umbraco-CMS,tcmorris/Umbraco-CMS,lars-erik/Umbraco-CMS,mattbrailsford/Umbraco-CMS,mattbrailsford/Umbraco-CMS,hfloyd/Umbraco-CMS,rasmuseeg/Umbraco-CMS,dawoe/Umbraco-CMS,marcemarc/Umbraco-CMS,marcemarc/Umbraco-CMS,bjarnef/Umbraco-CMS,umbraco/Umbraco-CMS,WebCentrum/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,hfloyd/Umbraco-CMS,lars-erik/Umbraco-CMS,NikRimington/Umbraco-CMS,rasmuseeg/Umbraco-CMS,marcemarc/Umbraco-CMS,tompipe/Umbraco-CMS,KevinJump/Umbraco-CMS,abjerner/Umbraco-CMS,bjarnef/Umbraco-CMS,madsoulswe/Umbraco-CMS,mattbrailsford/Umbraco-CMS,WebCentrum/Umbraco-CMS,robertjf/Umbraco-CMS,abjerner/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,abryukhov/Umbraco-CMS,abryukhov/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,tcmorris/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,leekelleher/Umbraco-CMS,hfloyd/Umbraco-CMS,marcemarc/Umbraco-CMS,madsoulswe/Umbraco-CMS,tompipe/Umbraco-CMS,arknu/Umbraco-CMS,arknu/Umbraco-CMS,tcmorris/Umbraco-CMS,tcmorris/Umbraco-CMS,robertjf/Umbraco-CMS,umbraco/Umbraco-CMS,umbraco/Umbraco-CMS,lars-erik/Umbraco-CMS,dawoe/Umbraco-CMS,arknu/Umbraco-CMS,marcemarc/Umbraco-CMS,dawoe/Umbraco-CMS,mattbrailsford/Umbraco-CMS,NikRimington/Umbraco-CMS,KevinJump/Umbraco-CMS,robertjf/Umbraco-CMS,leekelleher/Umbraco-CMS,NikRimington/Umbraco-CMS,abryukhov/Umbraco-CMS,KevinJump/Umbraco-CMS,dawoe/Umbraco-CMS,hfloyd/Umbraco-CMS,lars-erik/Umbraco-CMS,hfloyd/Umbraco-CMS,tcmorris/Umbraco-CMS,bjarnef/Umbraco-CMS,abryukhov/Umbraco-CMS,leekelleher/Umbraco-CMS
d455ab9ffe38b35765aa84b0d6bb08e65ec99dd5
CupCake.DefaultCommands/Commands/User/KickCommand.cs
CupCake.DefaultCommands/Commands/User/KickCommand.cs
using CupCake.Command; using CupCake.Command.Source; using CupCake.Permissions; using CupCake.Players; namespace CupCake.DefaultCommands.Commands.User { public sealed class KickCommand : UserCommandBase { [MinGroup(Group.Trusted)] [Label("kick", "kickplayer")] [CorrectUsage("[player] [reason]")] protected override void Run(IInvokeSource source, ParsedCommand message) { this.RequireOwner(); Player player = this.GetPlayerOrSelf(source, message); this.RequireSameRank(source, player); this.Chatter.Kick(player.Username, message.GetTrail(1)); } } }
using System.Runtime.InteropServices; using CupCake.Command; using CupCake.Command.Source; using CupCake.Permissions; using CupCake.Players; namespace CupCake.DefaultCommands.Commands.User { public sealed class KickCommand : UserCommandBase { [MinGroup(Group.Trusted)] [Label("kick", "kickplayer")] [CorrectUsage("[player] [reason]")] protected override void Run(IInvokeSource source, ParsedCommand message) { this.RequireOwner(); Player player = this.GetPlayerOrSelf(source, message); this.RequireSameRank(source, player); this.Chatter.ChatService.Kick(source.Name, player.Username, (message.Count > 1 ? message.GetTrail(1) : "Tsk tsk tsk")); } } }
Add default kick message, inform who the kicker was
Add default kick message, inform who the kicker was
C#
mit
Yonom/CupCake
895e517809b21089cf6182c39476b6169f40d3fc
src/IntelliTect.Coalesce.Tests/TargetClasses/TestDbContext/TestDbContext.cs
src/IntelliTect.Coalesce.Tests/TargetClasses/TestDbContext/TestDbContext.cs
using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Text; namespace IntelliTect.Coalesce.Tests.TargetClasses.TestDbContext { [Coalesce] public class TestDbContext : DbContext { public DbSet<Person> People { get; set; } public DbSet<Case> Cases { get; set; } public DbSet<Company> Companies { get; set; } public DbSet<Product> Products { get; set; } public DbSet<CaseProduct> CaseProducts { get; set; } public DbSet<ComplexModel> ComplexModels { get; set; } public DbSet<Test> Tests { get; set; } public TestDbContext() : this(Guid.NewGuid().ToString()) { } public TestDbContext(string memoryDatabaseName) : base(new DbContextOptionsBuilder<TestDbContext>().UseInMemoryDatabase(memoryDatabaseName).Options) { } public TestDbContext(DbContextOptions<TestDbContext> options) : base(options) { } } }
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; using System; using System.Collections.Generic; using System.Text; namespace IntelliTect.Coalesce.Tests.TargetClasses.TestDbContext { [Coalesce] public class TestDbContext : DbContext { public DbSet<Person> People { get; set; } public DbSet<Case> Cases { get; set; } public DbSet<Company> Companies { get; set; } public DbSet<Product> Products { get; set; } public DbSet<CaseProduct> CaseProducts { get; set; } public DbSet<ComplexModel> ComplexModels { get; set; } public DbSet<Test> Tests { get; set; } public TestDbContext() : this(Guid.NewGuid().ToString()) { } public TestDbContext(string memoryDatabaseName) : base(new DbContextOptionsBuilder<TestDbContext>().UseInMemoryDatabase(memoryDatabaseName).ConfigureWarnings(w => { #if NET5_0_OR_GREATER w.Ignore(CoreEventId.NavigationBaseIncludeIgnored); #endif }).Options) { } public TestDbContext(DbContextOptions<TestDbContext> options) : base(options) { } } }
Fix tests - apparently CoreEventId.NavigationBaseIncludeIgnored now defaults to Error in EF Core 6.
Fix tests - apparently CoreEventId.NavigationBaseIncludeIgnored now defaults to Error in EF Core 6.
C#
apache-2.0
IntelliTect/Coalesce,IntelliTect/Coalesce,IntelliTect/Coalesce,IntelliTect/Coalesce
885f548a34c2d6ab01e33be5a92f841efe40ef6c
src/Package/Impl/Options/R/Commands/SetupRemoteCommand.cs
src/Package/Impl/Options/R/Commands/SetupRemoteCommand.cs
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System; using System.ComponentModel.Design; using System.Diagnostics; using Microsoft.VisualStudio.R.Package.Commands; using Microsoft.VisualStudio.R.Packages.R; namespace Microsoft.VisualStudio.R.Package.Options.R.Tools { public sealed class SetupRemoteCommand : MenuCommand { private const string _remoteSetupPage = "http://aka.ms/rtvs-remote"; public SetupRemoteCommand() : base(OnCommand, new CommandID(RGuidList.RCmdSetGuid, RPackageCommandId.icmdSetupRemote)) { } public static void OnCommand(object sender, EventArgs args) { Process.Start(_remoteSetupPage); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System; using System.ComponentModel.Design; using System.Diagnostics; using Microsoft.VisualStudio.R.Package.Commands; using Microsoft.VisualStudio.R.Packages.R; namespace Microsoft.VisualStudio.R.Package.Options.R.Tools { public sealed class SetupRemoteCommand : MenuCommand { private const string _remoteSetupPage = "https://aka.ms/rtvs-remote-setup-instructions"; public SetupRemoteCommand() : base(OnCommand, new CommandID(RGuidList.RCmdSetGuid, RPackageCommandId.icmdSetupRemote)) { } public static void OnCommand(object sender, EventArgs args) { Process.Start(_remoteSetupPage); } } }
Fix link to remote R setup
Fix link to remote R setup
C#
mit
MikhailArkhipov/RTVS,karthiknadig/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS,AlexanderSher/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,MikhailArkhipov/RTVS,karthiknadig/RTVS
ad301dfb7f6d2bf80ff75252eeec0c903a43661a
Pequot/SerializableSettings.cs
Pequot/SerializableSettings.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; using System.Xml.Serialization; namespace Pequot { [XmlRoot("settings")] public class SerializableSettings : Dictionary<string, string>, IXmlSerializable { #region IXmlSerializable Members public System.Xml.Schema.XmlSchema GetSchema() { return null; } public void ReadXml(System.Xml.XmlReader reader) { bool wasEmpty = reader.IsEmptyElement; reader.Read(); if (wasEmpty) return; while (reader.NodeType != System.Xml.XmlNodeType.EndElement) { string key = XmlConvert.DecodeName(reader.Name); string value = reader.ReadString(); this.Add(key, value); reader.Read(); } reader.ReadEndElement(); } public void WriteXml(System.Xml.XmlWriter writer) { foreach (String key in this.Keys) { writer.WriteStartElement(XmlConvert.EncodeName(key)); writer.WriteString(this[key]); writer.WriteEndElement(); } } #endregion } }
using System; using System.Collections.Generic; using System.Xml; using System.Xml.Serialization; namespace Pequot { [XmlRoot("settings")] public class SerializableSettings : Dictionary<string, string>, IXmlSerializable { #region IXmlSerializable Members public System.Xml.Schema.XmlSchema GetSchema() { return null; } public void ReadXml(XmlReader reader) { bool wasEmpty = reader.IsEmptyElement; reader.Read(); if (wasEmpty) return; while (reader.NodeType != XmlNodeType.EndElement) { // Convert from human-readable element names (see below) string key = XmlConvert.DecodeName(reader.Name.Replace("___", "_x0020_").Replace("__x005F__", "___")); string value = reader.ReadString(); if(key!=null) { if(ContainsKey(key)) // update if already exists this[key] = value; else Add(key, value); } reader.Read(); } reader.ReadEndElement(); } public void WriteXml(XmlWriter writer) { foreach (String key in Keys) { // Convert to human-readable element names by substituting three underscores for an encoded space (2nd Replace) // and making sure existing triple-underscores will not cause confusion by substituting with partial encoding string encoded = XmlConvert.EncodeName(key); if (encoded == null) continue; writer.WriteStartElement(encoded.Replace("___", "__x005F__").Replace("_x0020_", "___")); writer.WriteString(this[key]); writer.WriteEndElement(); } } #endregion } }
Make saved settings more readable
Make saved settings more readable Still to do: make converter for old format
C#
mit
NJAldwin/Pequot
3b188bbea82e43d1ea7b421ae8bd0b0080143bf4
test/WindowsStore/MainPage.xaml.cs
test/WindowsStore/MainPage.xaml.cs
namespace Nine.Application.WindowsStore.Test { using System; using System.Reflection; using Windows.UI.Xaml.Controls; using Xunit; using Xunit.Abstractions; public sealed partial class MainPage : Page, IMessageSink { public MainPage() { InitializeComponent(); Loaded += async (a, b) => { await new PortableTestExecutor().RunAll(this, typeof(AppUITest).GetTypeInfo().Assembly); }; } public bool OnMessage(IMessageSinkMessage message) { Output.Text = message.ToString(); return true; } } }
namespace Nine.Application.WindowsStore.Test { using System; using System.Reflection; using Windows.UI.Xaml.Controls; using Xunit; using Xunit.Abstractions; public sealed partial class MainPage : Page, IMessageSink { public MainPage() { InitializeComponent(); } public bool OnMessage(IMessageSinkMessage message) { Output.Text = message.ToString(); return true; } } }
Remove windows store test runner
Remove windows store test runner
C#
mit
yufeih/Nine.Application,studio-nine/Nine.Application
8400e8ca7c32ce44a0b8051311bec2cc6f80f138
test/support/BaseTestFormats.cs
test/support/BaseTestFormats.cs
using Xunit; using System.Globalization; using System.Threading; namespace CronExpressionDescriptor.Test.Support { public abstract class BaseTestFormats { protected virtual string GetLocale() { return "en-US"; } protected string GetDescription(string expression) { return GetDescription(expression, new Options()); } protected string GetDescription(string expression, Options options) { options.Locale = this.GetLocale(); return ExpressionDescriptor.GetDescription(expression, options); } } }
using Xunit; using System.Globalization; using System.Threading; namespace CronExpressionDescriptor.Test.Support { public abstract class BaseTestFormats { protected virtual string GetLocale() { return "en-US"; } protected string GetDescription(string expression, bool verbose = false) { return GetDescription(expression, new Options() { Verbose = verbose }); } protected string GetDescription(string expression, Options options) { options.Locale = this.GetLocale(); return ExpressionDescriptor.GetDescription(expression, options); } } }
Add verbose option for tests
Add verbose option for tests
C#
mit
bradyholt/cron-expression-descriptor,bradyholt/cron-expression-descriptor
7907b2bde9cc7056d0fd1e47128f9b13dfc18f5b
Assets/Scripts/Trampoline.cs
Assets/Scripts/Trampoline.cs
using UnityEngine; using System.Collections; public class Trampoline : MonoBehaviour { public float velocityX; public float velocityY; public Input button; void OnTriggerStay2D(Collider2D other) { if (other.gameObject.tag == "Player") { if(button){ other.rigidbody2D.AddForce(new Vector2(velocityX,velocityY)); //other.rigidbody2D.velocity+=new Vector2(velocityX,velocityY); } } } }
using UnityEngine; using System.Collections; public class Trampoline : MonoBehaviour { public float velocityX; public float velocityY; void OnTriggerStay2D(Collider2D other) { if (other.gameObject.tag == "Player") { other.rigidbody2D.AddForce(new Vector2(velocityX,velocityY)); //other.rigidbody2D.velocity+=new Vector2(velocityX,velocityY); } } }
Revert "Tried to Figure Out Button: Failed"
Revert "Tried to Figure Out Button: Failed" This reverts commit 22e4c8b1b383f6ef364cbf8209c1026530bc9414.
C#
apache-2.0
aarya123/IshanGame
88d1cbdf7c4a242be0dfcea7ecd96b0773972a84
SampleApplication/Program.cs
SampleApplication/Program.cs
using System; using Microsoft.SPOT; using MicroTweet; using System.Net; using System.Threading; namespace SampleApplication { public class Program { public static void Main() { // Wait for DHCP while (IPAddress.GetDefaultLocalAddress() == IPAddress.Any) Thread.Sleep(50); // Update the current time (since Twitter OAuth API requests require a valid timestamp) DateTime utcTime = Sntp.GetCurrentUtcTime(); Microsoft.SPOT.Hardware.Utility.SetLocalTime(utcTime); // Set up application and user credentials // Visit https://apps.twitter.com/ to create a new Twitter application and get API keys/user access tokens var appCredentials = new OAuthApplicationCredentials() { ConsumerKey = "YOUR_CONSUMER_KEY_HERE", ConsumerSecret = "YOUR_CONSUMER_SECRET_HERE", }; var userCredentials = new OAuthUserCredentials() { AccessToken = "YOUR_ACCESS_TOKEN", AccessTokenSecret = "YOUR_ACCESS_TOKEN_SECRET", }; // Create new Twitter client with these credentials var twitter = new TwitterClient(appCredentials, userCredentials); // Send a tweet twitter.SendTweet("Trying out MicroTweet!"); } } }
using System; using Microsoft.SPOT; using MicroTweet; using System.Net; using System.Threading; namespace SampleApplication { public class Program { public static void Main() { // Wait for DHCP while (IPAddress.GetDefaultLocalAddress() == IPAddress.Any) Thread.Sleep(50); // Update the current time (since Twitter OAuth API requests require a valid timestamp) DateTime utcTime = Sntp.GetCurrentUtcTime(); Microsoft.SPOT.Hardware.Utility.SetLocalTime(utcTime); // Set up application and user credentials // Visit https://apps.twitter.com/ to create a new Twitter application and get API keys/user access tokens var appCredentials = new OAuthApplicationCredentials() { ConsumerKey = "YOUR_CONSUMER_KEY_HERE", ConsumerSecret = "YOUR_CONSUMER_SECRET_HERE", }; var userCredentials = new OAuthUserCredentials() { AccessToken = "YOUR_ACCESS_TOKEN", AccessTokenSecret = "YOUR_ACCESS_TOKEN_SECRET", }; // Create new Twitter client with these credentials var twitter = new TwitterClient(appCredentials, userCredentials); // Send a tweet var tweet = twitter.SendTweet("Trying out MicroTweet!"); if (tweet != null) Debug.Print("Posted tweet with ID: " + tweet.ID); else Debug.Print("Could not send tweet."); } } }
Modify sample application to show details about the posted tweet
Modify sample application to show details about the posted tweet
C#
apache-2.0
misenhower/MicroTweet
7ee02c4b38da37f996e740e6821159d3c98ca8f4
Ooui.Forms/Renderers/ScrollViewRenderer.cs
Ooui.Forms/Renderers/ScrollViewRenderer.cs
using System; using System.ComponentModel; using Ooui.Forms.Extensions; using Xamarin.Forms; namespace Ooui.Forms.Renderers { public class ScrollViewRenderer : ViewRenderer<ScrollView, Div> { protected override void OnElementChanged (ElementChangedEventArgs<ScrollView> e) { base.OnElementChanged (e); this.Style.Overflow = "scroll"; } protected override void OnElementPropertyChanged (object sender, PropertyChangedEventArgs e) { base.OnElementPropertyChanged (sender, e); } } }
using System; using System.ComponentModel; using Ooui.Forms.Extensions; using Xamarin.Forms; namespace Ooui.Forms.Renderers { public class ScrollViewRenderer : VisualElementRenderer<ScrollView> { bool disposed = false; protected override void OnElementChanged (ElementChangedEventArgs<ScrollView> e) { if (e.OldElement != null) { e.OldElement.ScrollToRequested -= Element_ScrollToRequested; } if (e.NewElement != null) { Style.Overflow = "scroll"; e.NewElement.ScrollToRequested += Element_ScrollToRequested; } base.OnElementChanged (e); } protected override void Dispose (bool disposing) { base.Dispose (disposing); if (disposing && !disposed) { if (Element != null) { Element.ScrollToRequested -= Element_ScrollToRequested; } disposed = true; } } void Element_ScrollToRequested (object sender, ScrollToRequestedEventArgs e) { var oe = (ITemplatedItemsListScrollToRequestedEventArgs)e; var item = oe.Item; var group = oe.Group; if (e.Mode == ScrollToMode.Position) { Send (Ooui.Message.Set (Id, "scrollTop", e.ScrollY)); Send (Ooui.Message.Set (Id, "scrollLeft", e.ScrollX)); } else { switch (e.Position) { case ScrollToPosition.Start: Send (Ooui.Message.Set (Id, "scrollTop", 0)); break; case ScrollToPosition.End: Send (Ooui.Message.Set (Id, "scrollTop", new Ooui.Message.PropertyReference { TargetId = Id, Key = "scrollHeight" })); break; } } } } }
Add ScrollTo support to ScrollView
Add ScrollTo support to ScrollView
C#
mit
praeclarum/Ooui,praeclarum/Ooui,praeclarum/Ooui
039f0dd5716d16db57f2f70cc7040d8ed3e80f0d
Properties/AssemblyInfo.cs
Properties/AssemblyInfo.cs
using System; using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Autofac.Extras.Multitenant")] [assembly: AssemblyDescription("Autofac multitenancy support library.")] [assembly: ComVisible(false)]
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Autofac.Extras.Multitenant")] [assembly: ComVisible(false)]
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.
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.
C#
mit
autofac/Autofac.Multitenant
3b6a8d803a5507a21e936ae991b8d6fea5a46ef8
WebAPI.API/App_Start/ModelBindingConfig.cs
WebAPI.API/App_Start/ModelBindingConfig.cs
using System.Web.Http.Controllers; using System.Web.Http.ModelBinding; using WebAPI.API.ModelBindings.Providers; namespace WebAPI.API { public class ModelBindingConfig { public static void RegisterModelBindings(ServicesContainer services) { services.Add(typeof (ModelBinderProvider), new GeocodeOptionsModelBindingProvider()); services.Add(typeof (ModelBinderProvider), new RouteMilepostOptionsModelBindingProvider()); services.Add(typeof (ModelBinderProvider), new SearchOptionsModelBindingProvider()); services.Add(typeof (ModelBinderProvider), new ReverseMilepostOptionsModelBindingProvider()); } } }
using System.Web.Http.Controllers; using System.Web.Http.ModelBinding; using WebAPI.API.ModelBindings.Providers; namespace WebAPI.API { public class ModelBindingConfig { public static void RegisterModelBindings(ServicesContainer services) { services.Add(typeof (ModelBinderProvider), new GeocodeOptionsModelBindingProvider()); services.Add(typeof (ModelBinderProvider), new ArcGisOnlineOptionsModelBindingProvide()); services.Add(typeof (ModelBinderProvider), new RouteMilepostOptionsModelBindingProvider()); services.Add(typeof (ModelBinderProvider), new SearchOptionsModelBindingProvider()); services.Add(typeof (ModelBinderProvider), new ReverseMilepostOptionsModelBindingProvider()); } } }
Add model binder to binding config
Add model binder to binding config
C#
mit
agrc/api.mapserv.utah.gov,agrc/api.mapserv.utah.gov,agrc/api.mapserv.utah.gov,agrc/api.mapserv.utah.gov
1826965ea15fe44ecd590b60f43c72686eb4b51a
src/VisualStudio/Core/Def/Utilities/IVsEditorAdaptersFactoryServiceExtensions.cs
src/VisualStudio/Core/Def/Utilities/IVsEditorAdaptersFactoryServiceExtensions.cs
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Utilities { internal static class IVsEditorAdaptersFactoryServiceExtensions { public static IOleUndoManager TryGetUndoManager( this IVsEditorAdaptersFactoryService editorAdaptersFactoryService, Workspace workspace, DocumentId contextDocumentId, CancellationToken cancellationToken) { var document = workspace.CurrentSolution.GetDocument(contextDocumentId); var text = document.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken); var textSnapshot = text.FindCorrespondingEditorTextSnapshot(); var textBuffer = textSnapshot?.TextBuffer; return editorAdaptersFactoryService.TryGetUndoManager(textBuffer); } public static IOleUndoManager TryGetUndoManager( this IVsEditorAdaptersFactoryService editorAdaptersFactoryService, ITextBuffer subjectBuffer) { if (subjectBuffer != null) { var adapter = editorAdaptersFactoryService.GetBufferAdapter(subjectBuffer); if (adapter != null) { if (ErrorHandler.Succeeded(adapter.GetUndoManager(out var manager))) { return manager; } } } return null; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Utilities { internal static class IVsEditorAdaptersFactoryServiceExtensions { public static IOleUndoManager TryGetUndoManager( this IVsEditorAdaptersFactoryService editorAdaptersFactoryService, Workspace workspace, DocumentId contextDocumentId, CancellationToken cancellationToken) { var document = workspace.CurrentSolution.GetDocument(contextDocumentId); var text = document?.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken); var textSnapshot = text.FindCorrespondingEditorTextSnapshot(); var textBuffer = textSnapshot?.TextBuffer; return editorAdaptersFactoryService.TryGetUndoManager(textBuffer); } public static IOleUndoManager TryGetUndoManager( this IVsEditorAdaptersFactoryService editorAdaptersFactoryService, ITextBuffer subjectBuffer) { if (subjectBuffer != null) { var adapter = editorAdaptersFactoryService?.GetBufferAdapter(subjectBuffer); if (adapter != null) { if (ErrorHandler.Succeeded(adapter.GetUndoManager(out var manager))) { return manager; } } } return null; } } }
Address null ref when we can't get an Undo manager.
Address null ref when we can't get an Undo manager.
C#
mit
mattwar/roslyn,Hosch250/roslyn,jasonmalinowski/roslyn,tannergooding/roslyn,aelij/roslyn,jmarolf/roslyn,AmadeusW/roslyn,pdelvo/roslyn,stephentoub/roslyn,agocke/roslyn,pdelvo/roslyn,mattwar/roslyn,TyOverby/roslyn,CyrusNajmabadi/roslyn,Giftednewt/roslyn,mattscheffer/roslyn,drognanar/roslyn,khyperia/roslyn,aelij/roslyn,diryboy/roslyn,genlu/roslyn,MichalStrehovsky/roslyn,tmat/roslyn,KevinRansom/roslyn,jcouv/roslyn,Giftednewt/roslyn,reaction1989/roslyn,mgoertz-msft/roslyn,swaroop-sridhar/roslyn,paulvanbrenk/roslyn,DustinCampbell/roslyn,amcasey/roslyn,dpoeschl/roslyn,bkoelman/roslyn,mavasani/roslyn,yeaicc/roslyn,Hosch250/roslyn,diryboy/roslyn,abock/roslyn,mmitche/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,lorcanmooney/roslyn,jasonmalinowski/roslyn,Giftednewt/roslyn,AnthonyDGreen/roslyn,CaptainHayashi/roslyn,shyamnamboodiripad/roslyn,zooba/roslyn,amcasey/roslyn,lorcanmooney/roslyn,sharwell/roslyn,brettfo/roslyn,Hosch250/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,ErikSchierboom/roslyn,KirillOsenkov/roslyn,cston/roslyn,physhi/roslyn,abock/roslyn,KevinRansom/roslyn,yeaicc/roslyn,tmeschter/roslyn,jeffanders/roslyn,dpoeschl/roslyn,CaptainHayashi/roslyn,orthoxerox/roslyn,TyOverby/roslyn,jcouv/roslyn,dotnet/roslyn,tannergooding/roslyn,weltkante/roslyn,agocke/roslyn,drognanar/roslyn,jeffanders/roslyn,CyrusNajmabadi/roslyn,xasx/roslyn,mmitche/roslyn,genlu/roslyn,KirillOsenkov/roslyn,stephentoub/roslyn,heejaechang/roslyn,physhi/roslyn,weltkante/roslyn,sharwell/roslyn,bartdesmet/roslyn,khyperia/roslyn,AmadeusW/roslyn,swaroop-sridhar/roslyn,heejaechang/roslyn,zooba/roslyn,eriawan/roslyn,KirillOsenkov/roslyn,jmarolf/roslyn,abock/roslyn,jamesqo/roslyn,nguerrera/roslyn,mattwar/roslyn,OmarTawfik/roslyn,MattWindsor91/roslyn,srivatsn/roslyn,jeffanders/roslyn,drognanar/roslyn,tmat/roslyn,wvdd007/roslyn,jamesqo/roslyn,mavasani/roslyn,AlekseyTs/roslyn,diryboy/roslyn,xasx/roslyn,panopticoncentral/roslyn,MattWindsor91/roslyn,MichalStrehovsky/roslyn,xasx/roslyn,physhi/roslyn,akrisiun/roslyn,aelij/roslyn,eriawan/roslyn,wvdd007/roslyn,MattWindsor91/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,VSadov/roslyn,mgoertz-msft/roslyn,zooba/roslyn,CyrusNajmabadi/roslyn,robinsedlaczek/roslyn,cston/roslyn,tmeschter/roslyn,genlu/roslyn,tvand7093/roslyn,nguerrera/roslyn,bkoelman/roslyn,bartdesmet/roslyn,weltkante/roslyn,amcasey/roslyn,mattscheffer/roslyn,khyperia/roslyn,paulvanbrenk/roslyn,agocke/roslyn,OmarTawfik/roslyn,eriawan/roslyn,jcouv/roslyn,swaroop-sridhar/roslyn,davkean/roslyn,dotnet/roslyn,tmat/roslyn,jasonmalinowski/roslyn,jkotas/roslyn,bartdesmet/roslyn,nguerrera/roslyn,gafter/roslyn,AlekseyTs/roslyn,mmitche/roslyn,MattWindsor91/roslyn,gafter/roslyn,kelltrick/roslyn,srivatsn/roslyn,reaction1989/roslyn,davkean/roslyn,bkoelman/roslyn,DustinCampbell/roslyn,jkotas/roslyn,tvand7093/roslyn,srivatsn/roslyn,wvdd007/roslyn,pdelvo/roslyn,tvand7093/roslyn,panopticoncentral/roslyn,dotnet/roslyn,AlekseyTs/roslyn,mavasani/roslyn,orthoxerox/roslyn,yeaicc/roslyn,kelltrick/roslyn,stephentoub/roslyn,AnthonyDGreen/roslyn,heejaechang/roslyn,gafter/roslyn,kelltrick/roslyn,sharwell/roslyn,tannergooding/roslyn,cston/roslyn,paulvanbrenk/roslyn,robinsedlaczek/roslyn,OmarTawfik/roslyn,TyOverby/roslyn,VSadov/roslyn,lorcanmooney/roslyn,CaptainHayashi/roslyn,ErikSchierboom/roslyn,orthoxerox/roslyn,akrisiun/roslyn,reaction1989/roslyn,robinsedlaczek/roslyn,brettfo/roslyn,jmarolf/roslyn,KevinRansom/roslyn,panopticoncentral/roslyn,ErikSchierboom/roslyn,shyamnamboodiripad/roslyn,MichalStrehovsky/roslyn,jkotas/roslyn,davkean/roslyn,brettfo/roslyn,jamesqo/roslyn,DustinCampbell/roslyn,VSadov/roslyn,AmadeusW/roslyn,mattscheffer/roslyn,tmeschter/roslyn,mgoertz-msft/roslyn,dpoeschl/roslyn,shyamnamboodiripad/roslyn,akrisiun/roslyn,AnthonyDGreen/roslyn
345430ab39d45f7d47231b080472bb660c364e0a
osu.Game.Rulesets.Mania/Skinning/Argon/ArgonHitTarget.cs
osu.Game.Rulesets.Mania/Skinning/Argon/ArgonHitTarget.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Game.Rulesets.Mania.Skinning.Default; using osuTK.Graphics; namespace osu.Game.Rulesets.Mania.Skinning.Argon { public class ArgonHitTarget : CompositeDrawable { [BackgroundDependencyLoader] private void load() { RelativeSizeAxes = Axes.X; Height = DefaultNotePiece.NOTE_HEIGHT; InternalChildren = new[] { new Box { RelativeSizeAxes = Axes.Both, Alpha = 0.3f, Blending = BlendingParameters.Additive, Colour = Color4.White }, }; } } }
// 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.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Game.Rulesets.Mania.Skinning.Default; using osu.Game.Rulesets.UI.Scrolling; using osuTK.Graphics; namespace osu.Game.Rulesets.Mania.Skinning.Argon { public class ArgonHitTarget : CompositeDrawable { private readonly IBindable<ScrollingDirection> direction = new Bindable<ScrollingDirection>(); [BackgroundDependencyLoader] private void load(IScrollingInfo scrollingInfo) { RelativeSizeAxes = Axes.X; Height = DefaultNotePiece.NOTE_HEIGHT; InternalChildren = new[] { new Box { RelativeSizeAxes = Axes.Both, Alpha = 0.3f, Blending = BlendingParameters.Additive, Colour = Color4.White }, }; direction.BindTo(scrollingInfo.Direction); direction.BindValueChanged(onDirectionChanged, true); } private void onDirectionChanged(ValueChangedEvent<ScrollingDirection> direction) { Anchor = Origin = direction.NewValue == ScrollingDirection.Up ? Anchor.TopLeft : Anchor.BottomLeft; } } }
Fix argon hit target area not being aligned correctly
Fix argon hit target area not being aligned correctly
C#
mit
peppy/osu,peppy/osu,ppy/osu,ppy/osu,ppy/osu,peppy/osu
c8900f4f4610519ff6de5ca721ae5649681628cc
src/Fixie/ClassExecution.cs
src/Fixie/ClassExecution.cs
using System; using System.Collections.Generic; namespace Fixie { public class ClassExecution { public ClassExecution(ExecutionPlan executionPlan, Type testClass, CaseExecution[] caseExecutions) { ExecutionPlan = executionPlan; TestClass = testClass; CaseExecutions = caseExecutions; } public ExecutionPlan ExecutionPlan { get; private set; } public Type TestClass { get; private set; } public IReadOnlyList<CaseExecution> CaseExecutions { get; private set; } public void FailCases(Exception exception) { foreach (var caseExecution in CaseExecutions) caseExecution.Fail(exception); } } }
using System; using System.Collections.Generic; namespace Fixie { public class ClassExecution { public ClassExecution(ExecutionPlan executionPlan, Type testClass, IReadOnlyList<CaseExecution> caseExecutions) { ExecutionPlan = executionPlan; TestClass = testClass; CaseExecutions = caseExecutions; } public ExecutionPlan ExecutionPlan { get; private set; } public Type TestClass { get; private set; } public IReadOnlyList<CaseExecution> CaseExecutions { get; private set; } public void FailCases(Exception exception) { foreach (var caseExecution in CaseExecutions) caseExecution.Fail(exception); } } }
Declare array parameter as an IReadOnlyList<T> since the array need not be used as mutable.
Declare array parameter as an IReadOnlyList<T> since the array need not be used as mutable.
C#
mit
EliotJones/fixie,Duohong/fixie,bardoloi/fixie,bardoloi/fixie,fixie/fixie,KevM/fixie,JakeGinnivan/fixie
cde72f385cb18e3d1c6e8ebcd10e6e7177592c57
SampleDiscoverableModule/Program.cs
SampleDiscoverableModule/Program.cs
using System; using RSB; using RSB.Diagnostics; using RSB.Transports.RabbitMQ; namespace SampleDiscoverableModule { class Program { static void Main(string[] args) { var bus = new Bus(RabbitMqTransport.FromConfigurationFile()); var diagnostics = new BusDiagnostics(bus,"SampleDiscoverableModule"); diagnostics.RegisterSubsystemHealthChecker("sampleSubsystem1", () => true); Console.ReadLine(); } } }
using System; using System.Threading; using RSB; using RSB.Diagnostics; using RSB.Transports.RabbitMQ; namespace SampleDiscoverableModule { class Program { static void Main(string[] args) { var bus = new Bus(RabbitMqTransport.FromConfigurationFile()); bus.UseBusDiagnostics("SampleDiscoverableModule", diagnostics => { diagnostics.RegisterSubsystemHealthChecker("sampleSubsystem1", () => { Thread.Sleep(6000); return true; }); }); Console.ReadLine(); } } }
Refactor to use UseBusDiagnostics extension
Refactor to use UseBusDiagnostics extension
C#
bsd-3-clause
tomaszkiewicz/rsb
7956070a562990a7ac8b3c57861ad725efeb93d1
AudioSharp.Config/ConfigHandler.cs
AudioSharp.Config/ConfigHandler.cs
using System; using System.Collections.Generic; using System.IO; using System.Windows.Input; using AudioSharp.Utils; using Newtonsoft.Json; namespace AudioSharp.Config { public class ConfigHandler { public static void SaveConfig(Configuration config) { string json = JsonConvert.SerializeObject(config); File.WriteAllText(Path.Combine(FileUtils.AppDataFolder, "settings.json"), json); } public static Configuration ReadConfig() { string path = Path.Combine(FileUtils.AppDataFolder, "settings.json"); if (File.Exists(path)) { string json = File.ReadAllText(path); return JsonConvert.DeserializeObject<Configuration>(json); } return new Configuration() { RecordingsFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyMusic), RecordingPrefix = "Recording", NextRecordingNumber = 1, AutoIncrementRecordingNumber = true, OutputFormat = "wav", ShowTrayIcon = true, GlobalHotkeys = new Dictionary<HotkeyUtils.HotkeyType, Tuple<Key, ModifierKeys>>(), RecordingSettingsPanelVisible = true, RecordingOutputPanelVisible = true }; } } }
using System; using System.Collections.Generic; using System.IO; using System.Windows.Input; using AudioSharp.Utils; using Newtonsoft.Json; namespace AudioSharp.Config { public class ConfigHandler { public static void SaveConfig(Configuration config) { string json = JsonConvert.SerializeObject(config); File.WriteAllText(Path.Combine(FileUtils.AppDataFolder, "settings.json"), json); } public static Configuration ReadConfig() { string path = Path.Combine(FileUtils.AppDataFolder, "settings.json"); if (File.Exists(path)) { string json = File.ReadAllText(path); return JsonConvert.DeserializeObject<Configuration>(json); } return new Configuration() { RecordingsFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyMusic), RecordingPrefix = "Recording{n}", NextRecordingNumber = 1, AutoIncrementRecordingNumber = true, OutputFormat = "wav", ShowTrayIcon = true, GlobalHotkeys = new Dictionary<HotkeyUtils.HotkeyType, Tuple<Key, ModifierKeys>>(), RecordingSettingsPanelVisible = true, RecordingOutputPanelVisible = true }; } } }
Include the recording number in the default format
Include the recording number in the default format
C#
mit
Heufneutje/AudioSharp,Heufneutje/HeufyAudioRecorder
eb4a6351706a99a682778e8b8841c80a075dffa8
JoinRpg.Web.Test/EnumTests.cs
JoinRpg.Web.Test/EnumTests.cs
using JoinRpg.Domain; using JoinRpg.Services.Interfaces; using JoinRpg.TestHelpers; using JoinRpg.Web.Models; using Xunit; namespace JoinRpg.Web.Test { public class EnumTests { [Fact] public void ProblemEnum() { EnumerationTestHelper.CheckEnums<UserExtensions.AccessReason, AccessReason>(); EnumerationTestHelper.CheckEnums<ProjectFieldViewType, DataModel.ProjectFieldType>(); EnumerationTestHelper.CheckEnums<ClaimStatusView, DataModel.Claim.Status>(); EnumerationTestHelper.CheckEnums<FinanceOperationActionView, FinanceOperationAction>(); } } }
using JoinRpg.Domain; using JoinRpg.Services.Interfaces; using JoinRpg.TestHelpers; using JoinRpg.Web.Models; using Xunit; namespace JoinRpg.Web.Test { public class EnumTests { [Fact] public void AccessReason() => EnumerationTestHelper.CheckEnums<UserExtensions.AccessReason, AccessReason>(); [Fact] public void ProjectFieldType() => EnumerationTestHelper.CheckEnums<ProjectFieldViewType, DataModel.ProjectFieldType>(); [Fact] public void ClaimStatus() => EnumerationTestHelper.CheckEnums<ClaimStatusView, DataModel.Claim.Status>(); [Fact] public void FinanceOperation() => EnumerationTestHelper.CheckEnums<FinanceOperationActionView, FinanceOperationAction>(); } }
Split enum test to 4 separate
Split enum test to 4 separate
C#
mit
joinrpg/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,leotsarev/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net
3864da3fcbfb045b7d86f703a0d5d95f84b1db1f
src/BmpListener/Bgp/IPAddrPrefix.cs
src/BmpListener/Bgp/IPAddrPrefix.cs
using System; using System.Net; namespace BmpListener.Bgp { public class IPAddrPrefix { public IPAddrPrefix(byte[] data, int offset, AddressFamily afi = AddressFamily.IP) { DecodeFromBytes(data, offset, afi); } internal int ByteLength { get { return 1 + (Length + 7) / 8; } } public int Length { get; private set; } public IPAddress Prefix { get; private set; } public override string ToString() { return ($"{Prefix}/{Length}"); } public void DecodeFromBytes(byte[] data, int offset, AddressFamily afi = AddressFamily.IP) { Length = data[offset]; var byteLength = (Length + 7) / 8; var ipBytes = afi == AddressFamily.IP ? new byte[4] : new byte[16]; Array.Copy(data, offset + 1, ipBytes, 0, byteLength); Prefix = new IPAddress(ipBytes); } } }
using System; using System.Linq; using System.Net; namespace BmpListener.Bgp { public class IPAddrPrefix { // RFC 4721 4.3 // The Type field indicates the length in bits of the IP address prefix. public int Length { get; private set; } public IPAddress Prefix { get; private set; } public override string ToString() { return ($"{Prefix}/{Length}"); } public static (IPAddrPrefix prefix, int byteLength) Decode(byte[] data, int offset, AddressFamily afi) { var bitLength = data[offset]; var byteLength = (bitLength + 7) / 8; var ipBytes = afi == AddressFamily.IP ? new byte[4] : new byte[16]; Array.Copy(data, offset + 1, ipBytes, 0, byteLength); var prefix = new IPAddress(ipBytes); var ipAddrPrefix = new IPAddrPrefix { Length = bitLength, Prefix = prefix }; return (ipAddrPrefix, byteLength + 1); } public static (IPAddrPrefix prefix, int byteLength) Decode(ArraySegment<byte> data, int offset, AddressFamily afi) { byte bitLength = data.First(); var ipBytes = afi == AddressFamily.IP ? new byte[4] : new byte[16]; offset += data.Offset; return Decode(data.Array, data.Offset, afi); } } }
Return prefix and byte length
Return prefix and byte length
C#
mit
mstrother/BmpListener
ea7f46fcbdd81d287bce2d3df41bdd9b2e8b5108
src/StephJob/Views/Home/Data.cshtml
src/StephJob/Views/Home/Data.cshtml
@{ ViewData["Title"] = "Data sources"; } <h2>@ViewData["Title"]</h2> <h3>@ViewData["Message"]</h3>
@{ ViewData["Title"] = "Data sources"; } <h2>@ViewData["Title"]</h2> <h3>@ViewData["Message"]</h3> http://www.oxfordmartin.ox.ac.uk/downloads/academic/The_Future_of_Employment.pdf
Add FutureEmployment to data sources.
Add FutureEmployment to data sources.
C#
mit
FrancisGrignon/StephJob,FrancisGrignon/StephJob,FrancisGrignon/StephJob,FrancisGrignon/StephJob,FrancisGrignon/StephJob
d41952471670f8482f91dc6f09d82f825b4c4a18
ISWebTest/Views/Home/Index.cshtml
ISWebTest/Views/Home/Index.cshtml
@{ Layout = null; @using ISWebTest.ExtensionMethods; @using ISWebTest.Controllers; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title></title> </head> <body> <div> <a href="@{Url.Action<HomeController>(nameof(HomeController.Analyze))}">TEST</a> </div> </body> </html>
 @using ISWebTest.ExtensionMethods; @using ISWebTest.Controllers; <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title></title> </head> <body> <div> <a href="@(Url.Action<HomeController>(nameof(HomeController.Analyze)))">TEST</a> </div> </body> </html>
Clean up syntax of index page
Clean up syntax of index page
C#
mit
MrDoomBringer/ISWebTest
58977bcc80b26d202adad1e5d454cc747f7ad18c
src/ifvm.core/Execution/Interpreter.cs
src/ifvm.core/Execution/Interpreter.cs
using IFVM.Core; namespace IFVM.Execution { public partial class Interpreter { public static uint Execute(Function function) { return 0; } } }
using System; using IFVM.Ast; using IFVM.Collections; using IFVM.Core; using IFVM.FlowAnalysis; namespace IFVM.Execution { public partial class Interpreter { public static uint Execute(Function function, Machine machine) { var cfg = ControlFlowGraph.Compute(function.Body); var block = cfg.GetBlock(cfg.EntryBlock.Successors[0]); var result = 0u; while (!block.IsExit) { var nextBlockId = block.ID.GetNext(); foreach (var statement in block.Statements) { var jump = false; void HandleReturnStatement(AstReturnStatement returnStatement) { result = Execute(returnStatement.Expression, machine); nextBlockId = BlockId.Exit; jump = true; } void HandleJumpStatement(AstJumpStatement jumpStatement) { nextBlockId = new BlockId(jumpStatement.Label.Index); jump = true; } // Handle control flow switch (statement.Kind) { case AstNodeKind.ReturnStatement: HandleReturnStatement((AstReturnStatement)statement); break; case AstNodeKind.JumpStatement: HandleJumpStatement((AstJumpStatement)statement); break; case AstNodeKind.BranchStatement: { var branchStatement = (AstBranchStatement)statement; var condition = Execute(branchStatement.Condition, machine); if (condition == 1) { switch (branchStatement.Statement.Kind) { case AstNodeKind.ReturnStatement: HandleReturnStatement((AstReturnStatement)branchStatement.Statement); break; case AstNodeKind.JumpStatement: HandleJumpStatement((AstJumpStatement)branchStatement.Statement); break; default: throw new InvalidOperationException($"Invalid statement kind for branch: {branchStatement.Statement.Kind}"); } } continue; } } if (jump) { break; } Execute(statement, machine); } block = cfg.GetBlock(nextBlockId); } return result; } private static uint Execute(AstExpression expression, Machine machine) { switch (expression.Kind) { default: throw new InvalidOperationException($"Invalid expression kind: {expression.Kind}"); } } private static void Execute(AstStatement statement, Machine machine) { switch (statement.Kind) { case AstNodeKind.LabelStatement: break; default: throw new InvalidOperationException($"Invalid statement kind: {statement.Kind}"); } } } }
Add interpreter with skeleton game loop
Add interpreter with skeleton game loop
C#
mit
DustinCampbell/ifvm
efe39e43f5338b0cf5d1a1b9deeaa22a788e6267
test/Microsoft.AspNet.Routing.Tests/RouteOptionsTests.cs
test/Microsoft.AspNet.Routing.Tests/RouteOptionsTests.cs
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using Microsoft.AspNet.Http; using Microsoft.Framework.DependencyInjection; using Microsoft.Framework.OptionsModel; using Xunit; namespace Microsoft.AspNet.Routing.Tests { public class RouteOptionsTests { [Fact] public void ConstraintMap_SettingNullValue_Throws() { // Arrange var options = new RouteOptions(); // Act & Assert var ex = Assert.Throws<ArgumentNullException>(() => options.ConstraintMap = null); Assert.Equal("The 'ConstraintMap' property of 'Microsoft.AspNet.Routing.RouteOptions' must not be null." + Environment.NewLine + "Parameter name: value", ex.Message); } [Fact] public void ConfigureRouting_ConfiguresOptionsProperly() { // Arrange var services = new ServiceCollection().AddOptions(); // Act services.ConfigureRouting(options => options.ConstraintMap.Add("foo", typeof(TestRouteConstraint))); var serviceProvider = services.BuildServiceProvider(); // Assert var accessor = serviceProvider.GetRequiredService<IOptions<RouteOptions>>(); Assert.Equal("TestRouteConstraint", accessor.Options.ConstraintMap["foo"].Name); } private class TestRouteConstraint : IRouteConstraint { public TestRouteConstraint(string pattern) { Pattern = pattern; } public string Pattern { get; private set; } public bool Match(HttpContext httpContext, IRouter route, string routeKey, IDictionary<string, object> values, RouteDirection routeDirection) { throw new NotImplementedException(); } } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using Microsoft.AspNet.Http; using Microsoft.Framework.DependencyInjection; using Microsoft.Framework.OptionsModel; using Xunit; namespace Microsoft.AspNet.Routing.Tests { public class RouteOptionsTests { [Fact] public void ConfigureRouting_ConfiguresOptionsProperly() { // Arrange var services = new ServiceCollection().AddOptions(); // Act services.ConfigureRouting(options => options.ConstraintMap.Add("foo", typeof(TestRouteConstraint))); var serviceProvider = services.BuildServiceProvider(); // Assert var accessor = serviceProvider.GetRequiredService<IOptions<RouteOptions>>(); Assert.Equal("TestRouteConstraint", accessor.Options.ConstraintMap["foo"].Name); } private class TestRouteConstraint : IRouteConstraint { public TestRouteConstraint(string pattern) { Pattern = pattern; } public string Pattern { get; private set; } public bool Match(HttpContext httpContext, IRouter route, string routeKey, IDictionary<string, object> values, RouteDirection routeDirection) { throw new NotImplementedException(); } } } }
Remove test the `[NotNull]` move makes irrelevant
Remove test the `[NotNull]` move makes irrelevant
C#
apache-2.0
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
d324a2fda62f0b6b0d6ea2498b5443b96cfe39f4
Dbot.Utility/Settings.cs
Dbot.Utility/Settings.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Dbot.Utility { public static class Settings { public const int MessageLogSize = 200; // aka context size public static readonly TimeSpan UserCommandInterval = TimeSpan.FromSeconds(10); public const int SelfSpamSimilarity = 75; public const int LongSpamSimilarity = 75; public const int SelfSpamContextLength = 15; public const int LongSpamContextLength = 26; public const int LongSpamMinimumLength = 40; public const int LongSpamLongerBanMultiplier = 3; public const double NukeStringDelta = 0.7; public const int NukeLoopWait = 2000; public const int AegisLoopWait = 250; public const int NukeDefaultDuration = 30; public static bool IsMono; public static string Timezone; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Dbot.Utility { public static class Settings { public const int MessageLogSize = 200; // aka context size public static readonly TimeSpan UserCommandInterval = TimeSpan.FromSeconds(10); public const int SelfSpamSimilarity = 75; public const int LongSpamSimilarity = 75; public const int SelfSpamContextLength = 15; public const int LongSpamContextLength = 26; public const int LongSpamMinimumLength = 40; public const int LongSpamLongerBanMultiplier = 3; public const double NukeStringDelta = 0.7; public const int NukeLoopWait = 0; public const int AegisLoopWait = 0; public const int NukeDefaultDuration = 30; public static bool IsMono; public static string Timezone; } }
Set NukeLoopWait and AegisLoopWait to 0 as per sztanpet.
Set NukeLoopWait and AegisLoopWait to 0 as per sztanpet.
C#
mit
destinygg/bot
20a50ddb6e0639adc5980a4e2c6c85ad2c4d13aa
osu.Game.Tests/Visual/UserInterface/TestSceneFirstRunScreenUIScale.cs
osu.Game.Tests/Visual/UserInterface/TestSceneFirstRunScreenUIScale.cs
// 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.Screens; using osu.Game.Overlays.FirstRunSetup; namespace osu.Game.Tests.Visual.UserInterface { public class TestSceneFirstRunScreenUIScale : OsuManualInputManagerTestScene { public TestSceneFirstRunScreenUIScale() { AddStep("load screen", () => { Child = new ScreenStack(new ScreenUIScale()); }); } } }
// 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.Screens; using osu.Game.Overlays; using osu.Game.Overlays.FirstRunSetup; namespace osu.Game.Tests.Visual.UserInterface { public class TestSceneFirstRunScreenUIScale : OsuManualInputManagerTestScene { [Cached] private OverlayColourProvider colourProvider = new OverlayColourProvider(OverlayColourScheme.Purple); public TestSceneFirstRunScreenUIScale() { AddStep("load screen", () => { Child = new ScreenStack(new ScreenUIScale()); }); } } }
Add missing `OverlayColourProvider` in test scene
Add missing `OverlayColourProvider` in test scene
C#
mit
ppy/osu,ppy/osu,peppy/osu,NeoAdonis/osu,peppy/osu,peppy/osu,ppy/osu,NeoAdonis/osu,NeoAdonis/osu
6ef848c6489f428a5f2f57f9196a96ee2aa9a8b9
Farity.Tests/AlwaysTests.cs
Farity.Tests/AlwaysTests.cs
using Xunit; namespace Farity.Tests { public class AlwaysTests { [Fact] public void AlwaysReturnsAFunctionThatReturnsTheSameValueAlways() { var answerToLifeUniverseAndEverything = F.Always(42); var answer = answerToLifeUniverseAndEverything(); Assert.Equal(answer, answerToLifeUniverseAndEverything()); Assert.Equal(answer, answerToLifeUniverseAndEverything(1)); Assert.Equal(answer, answerToLifeUniverseAndEverything("string", null)); Assert.Equal(answer, answerToLifeUniverseAndEverything(null, "str", 3)); Assert.Equal(answer, answerToLifeUniverseAndEverything(null, null, null, null)); } } }
using Xunit; namespace Farity.Tests { public class AlwaysTests { [Fact] public void AlwaysReturnsAFunctionThatReturnsTheSameValueAlways() { const int expected = 42; var answerToLifeUniverseAndEverything = F.Always(expected); Assert.Equal(expected, answerToLifeUniverseAndEverything()); Assert.Equal(expected, answerToLifeUniverseAndEverything(1)); Assert.Equal(expected, answerToLifeUniverseAndEverything("string", null)); Assert.Equal(expected, answerToLifeUniverseAndEverything(null, "str", 3)); Assert.Equal(expected, answerToLifeUniverseAndEverything(null, null, null, null)); } } }
Use expected in tests for F.Always
Use expected in tests for F.Always
C#
mit
farity/farity
0c4ea4beb102d0df710c94472a2fc92ed8e36e20
osu.Game.Tournament.Tests/TestCaseBeatmapPanel.cs
osu.Game.Tournament.Tests/TestCaseBeatmapPanel.cs
// 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.Framework.Graphics; using osu.Game.Beatmaps; using osu.Game.Online.API; using osu.Game.Online.API.Requests; using osu.Game.Online.API.Requests.Responses; using osu.Game.Rulesets; using osu.Game.Tests.Visual; using osu.Game.Tournament.Components; namespace osu.Game.Tournament.Tests { public class TestCaseBeatmapPanel : OsuTestCase { [Resolved] private APIAccess api { get; set; } = null; [Resolved] private RulesetStore rulesets { get; set; } = null; [BackgroundDependencyLoader] private void load() { var req = new GetBeatmapRequest(new BeatmapInfo { OnlineBeatmapID = 1091460 }); req.Success += success; api.Queue(req); } private void success(APIBeatmap apiBeatmap) { var beatmap = apiBeatmap.ToBeatmap(rulesets); Add(new TournamentBeatmapPanel(beatmap) { Anchor = Anchor.Centre, Origin = Anchor.Centre }); } } }
// 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; using System.Collections.Generic; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Game.Beatmaps; using osu.Game.Online.API; using osu.Game.Online.API.Requests; using osu.Game.Online.API.Requests.Responses; using osu.Game.Rulesets; using osu.Game.Tests.Visual; using osu.Game.Tournament.Components; namespace osu.Game.Tournament.Tests { public class TestCaseBeatmapPanel : OsuTestCase { [Resolved] private APIAccess api { get; set; } = null; [Resolved] private RulesetStore rulesets { get; set; } = null; public override IReadOnlyList<Type> RequiredTypes => new[] { typeof(TournamentBeatmapPanel), }; [BackgroundDependencyLoader] private void load() { var req = new GetBeatmapRequest(new BeatmapInfo { OnlineBeatmapID = 1091460 }); req.Success += success; api.Queue(req); } private void success(APIBeatmap apiBeatmap) { var beatmap = apiBeatmap.ToBeatmap(rulesets); Add(new TournamentBeatmapPanel(beatmap) { Anchor = Anchor.Centre, Origin = Anchor.Centre }); } } }
Allow dynamic recompilation of beatmap panel testcase
Allow dynamic recompilation of beatmap panel testcase
C#
mit
smoogipoo/osu,2yangk23/osu,ppy/osu,johnneijzen/osu,peppy/osu-new,NeoAdonis/osu,NeoAdonis/osu,peppy/osu,peppy/osu,smoogipoo/osu,ppy/osu,ZLima12/osu,2yangk23/osu,UselessToucan/osu,ppy/osu,smoogipoo/osu,UselessToucan/osu,peppy/osu,UselessToucan/osu,NeoAdonis/osu,johnneijzen/osu,ZLima12/osu,EVAST9919/osu,EVAST9919/osu,smoogipooo/osu
347fd38f00c06d47c807c7b8f921e2c17674a746
Framework/Lokad.Cqrs.Portable/Feature.FilePartition/FileQueueWriter.cs
Framework/Lokad.Cqrs.Portable/Feature.FilePartition/FileQueueWriter.cs
#region (c) 2010-2011 Lokad - CQRS for Windows Azure - New BSD License // Copyright (c) Lokad 2010-2011, http://www.lokad.com // This code is released as Open Source under the terms of the New BSD Licence #endregion using System; using System.IO; using Lokad.Cqrs.Core.Outbox; namespace Lokad.Cqrs.Feature.FilePartition { public sealed class FileQueueWriter : IQueueWriter { readonly DirectoryInfo _folder; readonly IEnvelopeStreamer _streamer; public string Name { get; private set; } public FileQueueWriter(DirectoryInfo folder, string name, IEnvelopeStreamer streamer) { _folder = folder; _streamer = streamer; Name = name; } public void PutMessage(ImmutableEnvelope envelope) { var fileName = string.Format("{0:yyyy-MM-dd-HH-mm-ss-ffff}-{1}", envelope.CreatedOnUtc, Guid.NewGuid()); var full = Path.Combine(_folder.FullName, fileName); var data = _streamer.SaveEnvelopeData(envelope); File.WriteAllBytes(full, data); } } }
#region (c) 2010-2011 Lokad - CQRS for Windows Azure - New BSD License // Copyright (c) Lokad 2010-2011, http://www.lokad.com // This code is released as Open Source under the terms of the New BSD Licence #endregion using System; using System.IO; using System.Threading; using Lokad.Cqrs.Core.Outbox; namespace Lokad.Cqrs.Feature.FilePartition { public sealed class FileQueueWriter : IQueueWriter { readonly DirectoryInfo _folder; readonly IEnvelopeStreamer _streamer; public string Name { get; private set; } public readonly string Suffix ; public FileQueueWriter(DirectoryInfo folder, string name, IEnvelopeStreamer streamer) { _folder = folder; _streamer = streamer; Name = name; Suffix = Guid.NewGuid().ToString().Substring(0, 4); } static long UniversalCounter; public void PutMessage(ImmutableEnvelope envelope) { var id = Interlocked.Increment(ref UniversalCounter); var fileName = string.Format("{0:yyyy-MM-dd-HH-mm-ss}-{1:00000000}-{2}", envelope.CreatedOnUtc, id, Suffix); var full = Path.Combine(_folder.FullName, fileName); var data = _streamer.SaveEnvelopeData(envelope); File.WriteAllBytes(full, data); } } }
Fix order of high-frequency messages on file queues
Fix order of high-frequency messages on file queues
C#
bsd-3-clause
modulexcite/lokad-cqrs
b43857a149128b11f73b0a72a26497468592fe66
src/Glimpse.Agent.Connection.Http/Broker/RemoteHttpMessagePublisher.cs
src/Glimpse.Agent.Connection.Http/Broker/RemoteHttpMessagePublisher.cs
using System; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; namespace Glimpse.Agent { public class RemoteHttpMessagePublisher : IMessagePublisher, IDisposable { private readonly HttpClient _httpClient; private readonly HttpClientHandler _httpHandler; public RemoteHttpMessagePublisher() { _httpHandler = new HttpClientHandler(); _httpClient = new HttpClient(_httpHandler); } public void PublishMessage(IMessage message) { var content = new StringContent("Hello"); // TODO: Try shifting to async and await // TODO: Find out what happened to System.Net.Http.Formmating - PostAsJsonAsync _httpClient.PostAsJsonAsync("http://localhost:15999/Glimpse/Agent", message) .ContinueWith(requestTask => { // Get HTTP response from completed task. HttpResponseMessage response = requestTask.Result; // Check that response was successful or throw exception response.EnsureSuccessStatusCode(); // Read response asynchronously as JsonValue and write out top facts for each country var result = response.Content.ReadAsStringAsync().Result; }); } public void Dispose() { _httpClient.Dispose(); _httpHandler.Dispose(); } } }
using System; using System.Net.Http; namespace Glimpse.Agent { public class RemoteHttpMessagePublisher : IMessagePublisher, IDisposable { private readonly HttpClient _httpClient; private readonly HttpClientHandler _httpHandler; public RemoteHttpMessagePublisher() { _httpHandler = new HttpClientHandler(); _httpClient = new HttpClient(_httpHandler); } public void PublishMessage(IMessage message) { var content = new StringContent("Hello"); // TODO: Try shifting to async and await // TODO: Find out what happened to System.Net.Http.Formmating - PostAsJsonAsync _httpClient.PostAsJsonAsync("http://localhost:15999/Glimpse/Agent", message) .ContinueWith(requestTask => { // Get HTTP response from completed task. HttpResponseMessage response = requestTask.Result; // Check that response was successful or throw exception response.EnsureSuccessStatusCode(); // Read response asynchronously as JsonValue and write out top facts for each country var result = response.Content.ReadAsStringAsync().Result; }); } public void Dispose() { _httpClient.Dispose(); _httpHandler.Dispose(); } } }
Remove not used using statements
Remove not used using statements
C#
mit
mike-kaufman/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,pranavkm/Glimpse.Prototype,zanetdev/Glimpse.Prototype,pranavkm/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,Glimpse/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,zanetdev/Glimpse.Prototype,zanetdev/Glimpse.Prototype,pranavkm/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,Glimpse/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,zanetdev/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,Glimpse/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,Glimpse/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,pranavkm/Glimpse.Prototype
dee3636469cb2c74b534a855ab798f6d20b7b0c7
AntlrGrammarEditor/Grammar.cs
AntlrGrammarEditor/Grammar.cs
using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.Collections.Generic; using System.IO; namespace AntlrGrammarEditor { public class Grammar { public const string AntlrDotExt = ".g4"; public const string ProjectDotExt = ".age"; public const string LexerPostfix = "Lexer"; public const string ParserPostfix = "Parser"; public string Name { get; set; } public string Root { get; set; } public string FileExtension { get; set; } = "txt"; public HashSet<Runtime> Runtimes = new HashSet<Runtime>(); public bool SeparatedLexerAndParser { get; set; } public bool CaseInsensitive { get; set; } public bool Preprocessor { get; set; } public bool PreprocessorCaseInsensitive { get; set; } public string PreprocessorRoot { get; set; } public bool PreprocessorSeparatedLexerAndParser { get; set; } public List<string> Files { get; set; } = new List<string>(); public List<string> TextFiles { get; set; } = new List<string>(); public string Directory { get; set; } = ""; } }
using System.Collections.Generic; namespace AntlrGrammarEditor { public enum CaseInsensitiveType { None, lower, UPPER } public class Grammar { public const string AntlrDotExt = ".g4"; public const string LexerPostfix = "Lexer"; public const string ParserPostfix = "Parser"; public string Name { get; set; } public string Root { get; set; } public string FileExtension { get; set; } = "txt"; public HashSet<Runtime> Runtimes = new HashSet<Runtime>(); public bool SeparatedLexerAndParser { get; set; } public CaseInsensitiveType CaseInsensitiveType { get; set; } public bool Preprocessor { get; set; } public bool PreprocessorCaseInsensitive { get; set; } public string PreprocessorRoot { get; set; } public bool PreprocessorSeparatedLexerAndParser { get; set; } public List<string> Files { get; set; } = new List<string>(); public List<string> TextFiles { get; set; } = new List<string>(); public string Directory { get; set; } = ""; } }
Add CaseInsensitiveType (None, lower, UPPER)
Add CaseInsensitiveType (None, lower, UPPER)
C#
apache-2.0
KvanTTT/DAGE,KvanTTT/DAGE,KvanTTT/DAGE,KvanTTT/DAGE,KvanTTT/DAGE,KvanTTT/DAGE,KvanTTT/DAGE
bed4efc295198e08e5e992bef278e02369bf30d1
ParallelWorkshop/Ex08DiyReaderWriterLock/PossibleSolution/InterlockedReaderWriterLock.cs
ParallelWorkshop/Ex08DiyReaderWriterLock/PossibleSolution/InterlockedReaderWriterLock.cs
using System; using System.Threading; namespace Lurchsoft.ParallelWorkshop.Ex08DiyReaderWriterLock.PossibleSolution { /// <summary> /// A scary low-level reader-writer lock implementation. /// <para> /// This one does not block, though it does yield. It will spin the CPU until the lock is available. However, by doing /// so, it avoids the cost of synchronisation and is much faster than a blocking lock. /// </para> /// </summary> public class InterlockedReaderWriterLock : IReaderWriterLock { private const int OneWriter = 1 << 16; private int counts; public void EnterReadLock() { while (true) { int cur = Interlocked.Increment(ref counts); if ((cur & 0xFFFF0000) == 0) { return; } Interlocked.Decrement(ref counts); Thread.Yield(); } } public void ExitReadLock() { Interlocked.Decrement(ref counts); } public void EnterWriteLock() { while (true) { int cur = Interlocked.Add(ref counts, OneWriter); if (cur == OneWriter) { return; } Interlocked.Add(ref counts, -OneWriter); Thread.Yield(); } } public void ExitWriteLock() { Interlocked.Add(ref counts, -OneWriter); } } }
using System.Threading; namespace Lurchsoft.ParallelWorkshop.Ex08DiyReaderWriterLock.PossibleSolution { /// <summary> /// A scary low-level reader-writer lock implementation. /// <para> /// This one does not block, though it does yield. It will spin the CPU until the lock is available. However, by doing /// so, it avoids the cost of synchronisation and is much faster than a blocking lock. /// </para> /// </summary> public class InterlockedReaderWriterLock : IReaderWriterLock { private const int OneWriter = 1 << 28; private int counts; public void EnterReadLock() { while (true) { int cur = Interlocked.Increment(ref counts); if ((cur & 0xF0000000) == 0) { return; } Interlocked.Decrement(ref counts); Thread.Yield(); } } public void ExitReadLock() { Interlocked.Decrement(ref counts); } public void EnterWriteLock() { while (true) { int cur = Interlocked.Add(ref counts, OneWriter); if (cur == OneWriter) { return; } Interlocked.Add(ref counts, -OneWriter); Thread.Yield(); } } public void ExitWriteLock() { Interlocked.Add(ref counts, -OneWriter); } } }
Allow more of the word for the reader count, as the writer count will always be v small
Allow more of the word for the reader count, as the writer count will always be v small
C#
apache-2.0
peterchase/parallel-workshop
ce45ee726d998e11c41300a5e4bad74e4a633800
Assets/Scripts/UI/TabletUI.cs
Assets/Scripts/UI/TabletUI.cs
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; [RequireComponent(typeof(GridLayoutGroup))] public class TabletUI : MonoBehaviour, ITablet { public ITabletCell TopLeft { get { return topLeft; } set { topLeft.SetState(value); } } public ITabletCell TopRight { get { return topRight; } set { topRight.SetState(value); } } public ITabletCell BottomLeft { get { return bottomLeft; } set { bottomLeft.SetState(value); } } public ITabletCell BottomRight { get { return bottomRight; } set { bottomRight.SetState(value); } } private TabletCellUI topLeft; private TabletCellUI topRight; private TabletCellUI bottomLeft; private TabletCellUI bottomRight; void Start() { GetComponent<GridLayoutGroup>().startCorner = GridLayoutGroup.Corner.UpperLeft; GetComponent<GridLayoutGroup>().startAxis = GridLayoutGroup.Axis.Horizontal; TabletCellUI[] cells = GetComponentsInChildren<TabletCellUI>(); if (cells.Length != 4) throw new Exception("Expected 4 TabletCellUI components in children, but found " + cells.Length); topLeft = cells[0]; topRight = cells[1]; bottomLeft = cells[2]; bottomRight = cells[3]; topLeft.parent = this; topRight.parent = this; bottomLeft.parent = this; bottomRight.parent = this; } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; [RequireComponent(typeof(GridLayoutGroup))] public class TabletUI : MonoBehaviour, ITablet { public ITabletCell TopLeft { get { return topLeft; } set { topLeft.SetState(value); } } public ITabletCell TopRight { get { return topRight; } set { topRight.SetState(value); } } public ITabletCell BottomLeft { get { return bottomLeft; } set { bottomLeft.SetState(value); } } public ITabletCell BottomRight { get { return bottomRight; } set { bottomRight.SetState(value); } } private TabletCellUI topLeft; private TabletCellUI topRight; private TabletCellUI bottomLeft; private TabletCellUI bottomRight; void Start() { GetComponent<GridLayoutGroup>().startCorner = GridLayoutGroup.Corner.UpperLeft; GetComponent<GridLayoutGroup>().startAxis = GridLayoutGroup.Axis.Horizontal; TabletCellUI[] cells = GetComponentsInChildren<TabletCellUI>(); if (cells.Length != 4) throw new Exception("Expected 4 TabletCellUI components in children, but found " + cells.Length); topLeft = cells[0]; topRight = cells[1]; bottomLeft = cells[2]; bottomRight = cells[3]; topLeft.parent = this; topRight.parent = this; bottomLeft.parent = this; bottomRight.parent = this; this.SetState(GlobalInput.InputTablet); } }
Make input tablet start states be set right
Make input tablet start states be set right
C#
mit
knexer/Chinese-Rooms-what-do-they-know-do-they-know-things-lets-find-out
051422d2c59d391a10843d26bc9a08b39c0236fb
src/Atata.Configuration.Json/JsonConfigMapper.cs
src/Atata.Configuration.Json/JsonConfigMapper.cs
using System; namespace Atata { public static class JsonConfigMapper { public static AtataContextBuilder Map<TConfig>(TConfig config, AtataContextBuilder builder) where TConfig : JsonConfig<TConfig> { if (config.BaseUrl != null) builder.UseBaseUrl(config.BaseUrl); if (config.RetryTimeout != null) builder.UseRetryTimeout(TimeSpan.FromSeconds(config.RetryTimeout.Value)); if (config.RetryInterval != null) builder.UseRetryInterval(TimeSpan.FromSeconds(config.RetryInterval.Value)); if (config.AssertionExceptionTypeName != null) builder.UseAssertionExceptionType(Type.GetType(config.AssertionExceptionTypeName)); if (config.UseNUnitTestName) builder.UseNUnitTestName(); if (config.LogNUnitError) builder.LogNUnitError(); if (config.TakeScreenshotOnNUnitError) { if (config.TakeScreenshotOnNUnitErrorTitle != null) builder.TakeScreenshotOnNUnitError(config.TakeScreenshotOnNUnitErrorTitle); else builder.TakeScreenshotOnNUnitError(); } return builder; } } }
using System; namespace Atata { public static class JsonConfigMapper { public static AtataContextBuilder Map<TConfig>(TConfig config, AtataContextBuilder builder) where TConfig : JsonConfig<TConfig> { if (config.BaseUrl != null) builder.UseBaseUrl(config.BaseUrl); if (config.RetryTimeout != null) builder.UseRetryTimeout(TimeSpan.FromSeconds(config.RetryTimeout.Value)); if (config.RetryInterval != null) builder.UseRetryInterval(TimeSpan.FromSeconds(config.RetryInterval.Value)); if (config.AssertionExceptionTypeName != null) builder.UseAssertionExceptionType(Type.GetType(config.AssertionExceptionTypeName)); if (config.UseNUnitTestName) builder.UseNUnitTestName(); if (config.LogNUnitError) builder.LogNUnitError(); if (config.TakeScreenshotOnNUnitError) { if (config.TakeScreenshotOnNUnitErrorTitle != null) builder.TakeScreenshotOnNUnitError(config.TakeScreenshotOnNUnitErrorTitle); else builder.TakeScreenshotOnNUnitError(); } if (config.LogConsumers != null) { foreach (var item in config.LogConsumers) MapLogConsumer(item, builder); } return builder; } private static void MapLogConsumer(LogConsumerJsonSection logConsumerSection, AtataContextBuilder builder) { Type type = ResolveLogConsumerType(logConsumerSection.TypeName); ILogConsumer logConsumer = (ILogConsumer)Activator.CreateInstance(type); if (logConsumerSection.MinLevel != null) ; if (logConsumerSection.SectionFinish == false) ; } private static Type ResolveLogConsumerType(string typeName) { //// Check log consumer aliases. return Type.GetType(typeName); } } }
Add basic mapping functionality of log consumers
Add basic mapping functionality of log consumers
C#
apache-2.0
atata-framework/atata-configuration-json
b884ed2a3d8b8fd50412134a3f162a84c1c29417
osu.Game.Rulesets.Taiko.Tests/TestSceneDrumTouchInputArea.cs
osu.Game.Rulesets.Taiko.Tests/TestSceneDrumTouchInputArea.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using NUnit.Framework; using osu.Framework.Allocation; using osu.Game.Beatmaps; using osu.Game.Rulesets.Taiko.Objects; using osu.Game.Rulesets.Taiko.UI; namespace osu.Game.Rulesets.Taiko.Tests { [TestFixture] public class TestSceneDrumTouchInputArea : DrawableTaikoRulesetTestScene { protected const double NUM_HIT_OBJECTS = 10; protected const double HIT_OBJECT_TIME_SPACING_MS = 1000; [BackgroundDependencyLoader] private void load() { var drumTouchInputArea = new DrumTouchInputArea(); DrawableRuleset.KeyBindingInputManager.Add(drumTouchInputArea); drumTouchInputArea.ShowTouchControls(); } protected override IBeatmap CreateBeatmap(RulesetInfo ruleset) { List<TaikoHitObject> hitObjects = new List<TaikoHitObject>(); for (int i = 0; i < NUM_HIT_OBJECTS; i++) { hitObjects.Add(new Hit { StartTime = Time.Current + i * HIT_OBJECT_TIME_SPACING_MS, IsStrong = isOdd(i), Type = isOdd(i / 2) ? HitType.Centre : HitType.Rim }); } var beatmap = new Beatmap<TaikoHitObject> { BeatmapInfo = { Ruleset = ruleset }, HitObjects = hitObjects }; return beatmap; } private bool isOdd(int number) { return number % 2 == 0; } } }
// 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.Graphics; using osu.Framework.Testing; using osu.Game.Rulesets.Taiko.UI; using osu.Game.Tests.Visual; namespace osu.Game.Rulesets.Taiko.Tests { [TestFixture] public class TestSceneDrumTouchInputArea : OsuTestScene { [Cached] private TaikoInputManager taikoInputManager = new TaikoInputManager(new TaikoRuleset().RulesetInfo); private DrumTouchInputArea drumTouchInputArea = null!; [SetUpSteps] public void SetUpSteps() { AddStep("create drum", () => { Children = new Drawable[] { new InputDrum { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, Height = 0.5f, }, drumTouchInputArea = new DrumTouchInputArea { Anchor = Anchor.BottomCentre, Origin = Anchor.BottomCentre, Height = 0.5f, }, }; }); } [Test] public void TestDrum() { AddStep("show drum", () => drumTouchInputArea.Show()); } } }
Make test actually test drum behaviours
Make test actually test drum behaviours
C#
mit
peppy/osu,peppy/osu,ppy/osu,peppy/osu,ppy/osu,ppy/osu
1cf28524c59408e268e36ff74934597434349eeb
Compiler/Crayon/Workers/RunCbxFlagBuilderWorker.cs
Compiler/Crayon/Workers/RunCbxFlagBuilderWorker.cs
using Common; using Exporter; using System.Linq; namespace Crayon { // cmdLineFlags = Crayon::RunCbxFlagBuilder(command, buildContext) class RunCbxFlagBuilderWorker : AbstractCrayonWorker { public override CrayonWorkerResult DoWorkImpl(CrayonWorkerResult[] args) { ExportCommand command = (ExportCommand)args[0].Value; string finalCbxPath = (string)args[1].Value; string cbxFile = FileUtil.GetPlatformPath(finalCbxPath); int processId = System.Diagnostics.Process.GetCurrentProcess().Id; string runtimeArgs = string.Join(",", command.DirectRunArgs.Select(s => Utf8Base64.ToBase64(s))); string flags = cbxFile + " vmpid:" + processId; if (runtimeArgs.Length > 0) { flags += " runtimeargs:" + runtimeArgs; } return new CrayonWorkerResult() { Value = flags }; } } }
using Common; using Exporter; using System.Linq; namespace Crayon { // cmdLineFlags = Crayon::RunCbxFlagBuilder(command, buildContext) class RunCbxFlagBuilderWorker : AbstractCrayonWorker { public override CrayonWorkerResult DoWorkImpl(CrayonWorkerResult[] args) { ExportCommand command = (ExportCommand)args[0].Value; string finalCbxPath = (string)args[1].Value; string cbxFile = FileUtil.GetPlatformPath(finalCbxPath); int processId = System.Diagnostics.Process.GetCurrentProcess().Id; string runtimeArgs = string.Join(",", command.DirectRunArgs.Select(s => Utf8Base64.ToBase64(s))); string flags = "\"" + cbxFile + "\" vmpid:" + processId; if (runtimeArgs.Length > 0) { flags += " runtimeargs:" + runtimeArgs; } return new CrayonWorkerResult() { Value = flags }; } } }
Fix bug where running a project without export in a directory with a space was confusing the command line arg generator.
Fix bug where running a project without export in a directory with a space was confusing the command line arg generator. Fixes https://github.com/blakeohare/crayon/issues/203
C#
mit
blakeohare/crayon,blakeohare/crayon,blakeohare/crayon,blakeohare/crayon,blakeohare/crayon,blakeohare/crayon,blakeohare/crayon,blakeohare/crayon
d602877a423748b7daf7450f841cff91e6473a2a
src/Client/Rs317.Client.WF/Program.cs
src/Client/Rs317.Client.WF/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Rs317.Sharp { public static class Program { public static async Task Main(string[] args) { try { Console.WriteLine($"RS2 user client - release #{317} using Rs317.Sharp by Glader"); await StartClient(0, 0, true); } catch(Exception exception) { throw new InvalidOperationException($"Erorr: {exception.Message} \n\n Stack: {exception.StackTrace}"); } } private static async Task StartClient(int localWorldId, short portOffset, bool membersWorld) { Application.SetCompatibleTextRenderingDefault(false); Task clientRunningAwaitable = signlink.startpriv("127.0.0.1"); ClientConfiguration configuration = new ClientConfiguration(localWorldId, (short) (portOffset + 1), membersWorld); RsWinForm windowsFormApplication = new RsWinForm(765, 503); RsWinFormsClient client1 = new RsWinFormsClient(configuration, windowsFormApplication.CreateGraphics(), new DefaultWebSocketClientFactory()); windowsFormApplication.RegisterInputSubscriber(client1); client1.createClientFrame(765, 503); Application.Run(windowsFormApplication); await clientRunningAwaitable .ConfigureAwait(false); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Rs317.Sharp { public static class Program { public static async Task Main(string[] args) { try { Console.WriteLine($"RS2 user client - release #{317} using Rs317.Sharp by Glader"); await StartClient(0, 0, true); } catch(Exception exception) { throw new InvalidOperationException($"Erorr: {exception.Message} \n\n Stack: {exception.StackTrace}"); } } private static async Task StartClient(int localWorldId, short portOffset, bool membersWorld) { Application.SetCompatibleTextRenderingDefault(false); Task clientRunningAwaitable = signlink.startpriv("127.0.0.1"); ClientConfiguration configuration = new ClientConfiguration(localWorldId, (short) (portOffset + 1), membersWorld); RsWinForm windowsFormApplication = new RsWinForm(765, 503); RsWinFormsClient client1 = new RsWinFormsClient(configuration, windowsFormApplication.CreateGraphics()); windowsFormApplication.RegisterInputSubscriber(client1); client1.createClientFrame(765, 503); Application.Run(windowsFormApplication); await clientRunningAwaitable .ConfigureAwait(false); } } }
Remove test websocket code from WF implementation
Remove test websocket code from WF implementation
C#
mit
HelloKitty/317refactor
c1a74bb8e5cbd6e43456720e44ed3c323261cee7
Tests/Sources/Details/GlobalSetup.cs
Tests/Sources/Details/GlobalSetup.cs
/* ------------------------------------------------------------------------- */ // // Copyright (c) 2010 CubeSoft, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /* ------------------------------------------------------------------------- */ using Cube.Log; using NUnit.Framework; using System.Reflection; namespace Cube.FileSystem.Tests { /* --------------------------------------------------------------------- */ /// /// GlobalSetup /// /// <summary> /// NUnit で最初に実行する処理を記述するテストです。 /// </summary> /// /* --------------------------------------------------------------------- */ [SetUpFixture] public class GlobalSetup { /* ----------------------------------------------------------------- */ /// /// OneTimeSetup /// /// <summary> /// 一度だけ実行される初期化処理です。 /// </summary> /// /* ----------------------------------------------------------------- */ [OneTimeSetUp] public void OneTimeSetup() { Logger.Configure(); Logger.Info(typeof(GlobalSetup), Assembly.GetExecutingAssembly()); } } }
/* ------------------------------------------------------------------------- */ // // Copyright (c) 2010 CubeSoft, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /* ------------------------------------------------------------------------- */ using NUnit.Framework; using System.Reflection; namespace Cube.FileSystem.Tests { /* --------------------------------------------------------------------- */ /// /// GlobalSetup /// /// <summary> /// NUnit で最初に実行する処理を記述するテストです。 /// </summary> /// /* --------------------------------------------------------------------- */ [SetUpFixture] public class GlobalSetup { /* ----------------------------------------------------------------- */ /// /// OneTimeSetup /// /// <summary> /// 一度だけ実行される初期化処理です。 /// </summary> /// /* ----------------------------------------------------------------- */ [OneTimeSetUp] public void OneTimeSetup() { Logger.Configure(); Logger.Info(typeof(GlobalSetup), Assembly.GetExecutingAssembly()); } } }
Fix to apply for the library updates.
Fix to apply for the library updates.
C#
apache-2.0
cube-soft/Cube.Core,cube-soft/Cube.Core,cube-soft/Cube.FileSystem,cube-soft/Cube.FileSystem
ad5fbe9dfb5e3b08212641e3b8341b3a2fde772b
src/Tools/RPCGen.Tests/RPCGenTests.cs
src/Tools/RPCGen.Tests/RPCGenTests.cs
using Flood.Tools.RPCGen; using NUnit.Framework; using System; using System.IO; using System.Reflection; namespace RPCGen.Tests { [TestFixture] class RPCGenTests { [Test] public void MainTest() { string genDirectory = Path.Combine("..", "..", "gen", "RPCGen.Tests"); Directory.CreateDirectory(genDirectory); var sourceDllPath = Path.GetFullPath("RPCGen.Tests.Services.dll"); var destDllPath = Path.Combine(genDirectory, "RPCGen.Tests.Services.dll"); var sourcePdbPath = Path.GetFullPath("RPCGen.Tests.Services.pdb"); var destPdbPath = Path.Combine(genDirectory, "RPCGen.Tests.Services.pdb"); System.IO.File.Copy(sourceDllPath, destDllPath, true); if (File.Exists(sourcePdbPath)) System.IO.File.Copy(sourcePdbPath, destPdbPath, true); var args = new string[] { String.Format("-o={0}", genDirectory), destDllPath }; var ret = Flood.Tools.RPCGen.Program.Main(args); Assert.AreEqual(0, ret); } [Test] public void GenAPI() { string genDirectory = Path.Combine("..", "..", "gen", "RPCGen.Tests.API"); Directory.CreateDirectory(genDirectory); var sourceDllPath = Path.GetFullPath("RPCGen.Tests.Services.dll"); var destDllPath = Path.Combine(genDirectory, "RPCGen.Tests.Services.dll"); var rpcCompiler = new Compiler(sourceDllPath, genDirectory); rpcCompiler.Process(); rpcCompiler.CompileApi(destDllPath); } } }
using Flood.Tools.RPCGen; using NUnit.Framework; using System; using System.IO; using System.Reflection; namespace RPCGen.Tests { [TestFixture] class RPCGenTests { [Test] public void MainTest() { string genDirectory = Path.Combine("..", "..", "gen", "RPCGen.Tests"); Directory.CreateDirectory(genDirectory); var sourceDllPath = Path.GetFullPath("RPCGen.Tests.Services.dll"); var destDllPath = Path.Combine(genDirectory, "RPCGen.Tests.Services.dll"); var sourcePdbPath = Path.GetFullPath("RPCGen.Tests.Services.pdb"); var destPdbPath = Path.Combine(genDirectory, "RPCGen.Tests.Services.pdb"); System.IO.File.Copy(sourceDllPath, destDllPath, true); if (File.Exists(sourcePdbPath)) System.IO.File.Copy(sourcePdbPath, destPdbPath, true); var args = new string[] { String.Format("-o={0}", genDirectory), destDllPath }; var ret = Flood.Tools.RPCGen.Program.Main(args); Assert.AreEqual(0, ret); } } }
Remove test of no longer existing method CompileApi.
Remove test of no longer existing method CompileApi.
C#
bsd-2-clause
FloodProject/flood,FloodProject/flood,FloodProject/flood
c05584f864d0738bef5d771b267b9e4a66431b93
WordHunt/Games/Create/Repository/GameRepository.cs
WordHunt/Games/Create/Repository/GameRepository.cs
using Dapper; using System; using System.Collections.Generic; using System.Data; using System.Text; using WordHunt.Data.Connection; namespace WordHunt.Games.Create.Repository { public interface IGameRepository { void SaveGame(string name); } public class GameRepository : IGameRepository { private readonly IDbConnectionProvider connectionProvider; public GameRepository(IDbConnectionProvider connectionProvider) { this.connectionProvider = connectionProvider; } public void SaveGame(string name) { var connection = connectionProvider.GetConnection(); connection.Execute(@"INSERT INTO Words(LanguageId, Value) VALUES (@LanguageId, @Value)", new { LanguageId = 1, Value = name }); } } }
using Dapper; using System; using System.Collections.Generic; using System.Data; using System.Text; using WordHunt.Data.Connection; namespace WordHunt.Games.Create.Repository { public interface IGameRepository { void SaveGame(string name); } public class GameRepository : IGameRepository { private readonly IDbConnectionFactory connectionFactory; public GameRepository(IDbConnectionFactory connectionFactory) { this.connectionFactory = connectionFactory; } public void SaveGame(string name) { using (var connection = connectionFactory.CreateConnection()) { connection.Execute(@"INSERT INTO Words(LanguageId, Value) VALUES (@LanguageId, @Value)", new { LanguageId = 1, Value = name }); } } } }
Change usage of connection provider for connection factory.
Change usage of connection provider for connection factory.
C#
mit
Saaka/WordHunt,Saaka/WordHunt,Saaka/WordHunt,Saaka/WordHunt
b9c2959da75c0e825b4d688bffab9922d17426d5
src/Elasticsearch.Net/Responses/ServerException/ErrorCauseExtensions.cs
src/Elasticsearch.Net/Responses/ServerException/ErrorCauseExtensions.cs
using System; using System.Collections.Generic; namespace Elasticsearch.Net { internal static class ErrorCauseExtensions { public static void FillValues(this ErrorCause rootCause, IDictionary<string, object> dict) { if (dict == null) return; if (dict.TryGetValue("reason", out var reason)) rootCause.Reason = Convert.ToString(reason); if (dict.TryGetValue("type", out var type)) rootCause.Type = Convert.ToString(type); if (dict.TryGetValue("stack_trace", out var stackTrace)) rootCause.StackTrace = Convert.ToString(stackTrace); // if (dict.TryGetValue("index", out var index)) rootCause.Index = Convert.ToString(index); // if (dict.TryGetValue("resource.id", out var resourceId)) rootCause.ResourceId = Convert.ToString(resourceId); // if (dict.TryGetValue("resource.type", out var resourceType)) rootCause.ResourceType = Convert.ToString(resourceType); } } }
using System; using System.Collections.Generic; namespace Elasticsearch.Net { internal static class ErrorCauseExtensions { public static void FillValues(this ErrorCause rootCause, IDictionary<string, object> dict) { if (dict == null) return; if (dict.TryGetValue("reason", out var reason) && reason != null) rootCause.Reason = Convert.ToString(reason); if (dict.TryGetValue("type", out var type) && type != null) rootCause.Type = Convert.ToString(type); if (dict.TryGetValue("stack_trace", out var stackTrace) && stackTrace != null) rootCause.StackTrace = Convert.ToString(stackTrace); // if (dict.TryGetValue("index", out var index)) rootCause.Index = Convert.ToString(index); // if (dict.TryGetValue("resource.id", out var resourceId)) rootCause.ResourceId = Convert.ToString(resourceId); // if (dict.TryGetValue("resource.type", out var resourceType)) rootCause.ResourceType = Convert.ToString(resourceType); } } }
Convert ErrorCause properties only when not null
Convert ErrorCause properties only when not null
C#
apache-2.0
elastic/elasticsearch-net,elastic/elasticsearch-net
5efd138e526636e3be1f7c895768b7ddc2cda484
CircuitBreaker/CircuitBreakerStateStoreFactory.cs
CircuitBreaker/CircuitBreakerStateStoreFactory.cs
using System.Collections.Concurrent; namespace CircuitBreaker { public class CircuitBreakerStateStoreFactory { private static ConcurrentDictionary<string, ICircuitBreakerStateStore> _stateStores = new ConcurrentDictionary<string, ICircuitBreakerStateStore>(); internal static ICircuitBreakerStateStore GetCircuitBreakerStateStore(ICircuit circuit) { // There is only one type of ICircuitBreakerStateStore to return... // The ConcurrentDictionary keeps track of ICircuitBreakerStateStore objects (across threads) // For example, a store for a db connection, web service client, and NAS storage could exist if (!_stateStores.ContainsKey(circuit.GetType().Name)) { _stateStores.TryAdd(circuit.GetType().Name, new CircuitBreakerStateStore(circuit)); } return _stateStores[circuit.GetType().Name]; } // TODO: Add the ability for Circuit breaker stateStores to update the state in this dictionary? } }
using System; using System.Collections.Concurrent; namespace CircuitBreaker { public class CircuitBreakerStateStoreFactory { private static ConcurrentDictionary<Type, ICircuitBreakerStateStore> _stateStores = new ConcurrentDictionary<Type, ICircuitBreakerStateStore>(); internal static ICircuitBreakerStateStore GetCircuitBreakerStateStore(ICircuit circuit) { // There is only one type of ICircuitBreakerStateStore to return... // The ConcurrentDictionary keeps track of ICircuitBreakerStateStore objects (across threads) // For example, a store for a db connection, web service client, and NAS storage could exist if (!_stateStores.ContainsKey(circuit.GetType())) { _stateStores.TryAdd(circuit.GetType(), new CircuitBreakerStateStore(circuit)); } return _stateStores[circuit.GetType()]; } // TODO: Add the ability for Circuit breaker stateStores to update the state in this dictionary? } }
Use Type as a key...instead of a string.
Use Type as a key...instead of a string.
C#
mit
kylos101/CircuitBreaker
52651b9feccdcbd317c2c6f871fc4fe18c3a74cb
School/REPL/REPL.cs
School/REPL/REPL.cs
using System; using Mono.Terminal; namespace School.REPL { public class REPL { public REPL() { } public void Run() { Evaluator evaluator = new Evaluator(); LineEditor editor = new LineEditor("School"); Console.WriteLine("School REPL:"); string line; while ((line = editor.Edit("> ", "")) != null) { if (!String.IsNullOrWhiteSpace(line)) { try { Value value = evaluator.Evaluate(line); Console.WriteLine(value); } catch (Exception e) { Console.WriteLine(e); } } } } } }
using System; using Mono.Terminal; namespace School.REPL { public class REPL { public REPL() { } public void Run() { Evaluator evaluator = new Evaluator(); LineEditor editor = new LineEditor("School"); Console.WriteLine("School REPL:"); string line; while ((line = editor.Edit("> ", "")) != null) { if (String.IsNullOrWhiteSpace(line)) continue; try { Value value = evaluator.Evaluate(line); Console.WriteLine(value); } catch (Exception e) { Console.WriteLine(e); } } } } }
Use continue to reduce one indentation level.
Use continue to reduce one indentation level.
C#
apache-2.0
alldne/school,alldne/school
d487b6cc4507e853e68fc28611dfc2541491cab1
src/ProjectTemplates/Web.ProjectTemplates/content/Worker-CSharp/Program.cs
src/ProjectTemplates/Web.ProjectTemplates/content/Worker-CSharp/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace Company.Application1 { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureServices((hostContext, services) => { services.AddHostedService<Worker>(); }); } }
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Company.Application1; using IHost host = Host.CreateDefaultBuilder(args) .ConfigureServices(services => { services.AddHostedService<Worker>(); }) .Build(); await host.RunAsync();
Use top level program for the Worker template
Use top level program for the Worker template
C#
apache-2.0
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
ba9518a1636a7707312311bd213b951f59f0e632
elbgb.gameboy/Memory/Mappers/RomOnly.cs
elbgb.gameboy/Memory/Mappers/RomOnly.cs
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace elbgb.gameboy.Memory.Mappers { class RomOnly : Cartridge { public RomOnly(CartridgeHeader header, byte[] romData) : base(header, romData) { } public override byte ReadByte(ushort address) { return _romData[address]; } public override void WriteByte(ushort address, byte value) { return; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace elbgb.gameboy.Memory.Mappers { class RomOnly : Cartridge { public RomOnly(CartridgeHeader header, byte[] romData) : base(header, romData) { } public override byte ReadByte(ushort address) { if (address < 0x8000) { return _romData[address]; } else return 0x00; } public override void WriteByte(ushort address, byte value) { return; } } }
Return a value for reads from expansion RAM even though not present
Return a value for reads from expansion RAM even though not present
C#
mit
eightlittlebits/elbgb
c10a91a33ed488bdc57d219224fb86355b9c6266
osu.Game.Rulesets.Mania.Tests/Skinning/ColumnTestContainer.cs
osu.Game.Rulesets.Mania.Tests/Skinning/ColumnTestContainer.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Rulesets.Mania.UI; using osuTK.Graphics; namespace osu.Game.Rulesets.Mania.Tests.Skinning { /// <summary> /// A container to be used in a <see cref="ManiaSkinnableTestScene"/> to provide a resolvable <see cref="Column"/> dependency. /// </summary> public class ColumnTestContainer : Container { protected override Container<Drawable> Content => content; private readonly Container content; [Cached] private readonly Column column; public ColumnTestContainer(int column, ManiaAction action) { this.column = new Column(column) { Action = { Value = action }, AccentColour = Color4.Orange }; InternalChild = content = new ManiaInputManager(new ManiaRuleset().RulesetInfo, 4) { 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.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Rulesets.Mania.Beatmaps; using osu.Game.Rulesets.Mania.UI; using osuTK.Graphics; namespace osu.Game.Rulesets.Mania.Tests.Skinning { /// <summary> /// A container to be used in a <see cref="ManiaSkinnableTestScene"/> to provide a resolvable <see cref="Column"/> dependency. /// </summary> public class ColumnTestContainer : Container { protected override Container<Drawable> Content => content; private readonly Container content; [Cached] private readonly Column column; public ColumnTestContainer(int column, ManiaAction action) { this.column = new Column(column) { Action = { Value = action }, AccentColour = Color4.Orange, ColumnType = column % 2 == 0 ? ColumnType.Even : ColumnType.Odd }; InternalChild = content = new ManiaInputManager(new ManiaRuleset().RulesetInfo, 4) { RelativeSizeAxes = Axes.Both }; } } }
Add odd/even type to test scenes
Add odd/even type to test scenes
C#
mit
smoogipoo/osu,peppy/osu,UselessToucan/osu,peppy/osu,EVAST9919/osu,ppy/osu,UselessToucan/osu,ppy/osu,smoogipoo/osu,smoogipoo/osu,ppy/osu,EVAST9919/osu,smoogipooo/osu,NeoAdonis/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu,NeoAdonis/osu,peppy/osu-new
9224151ad6b072e404aa5893da569516e45caf4e
Quarks.Tests/PluralizeForCountTests.cs
Quarks.Tests/PluralizeForCountTests.cs
using Machine.Specifications; namespace Quarks.Tests { [Subject(typeof(Inflector))] public class When_using_pluralize_for_count { It should_pluralize_when_count_is_greater_than_two = () => "item".PluralizeForCount(2).ShouldEqual("items"); It should_pluralize_when_count_is_zero = () => "item".PluralizeForCount(0).ShouldEqual("items"); It should_not_pluralize_when_count_is_one = () => "item".PluralizeForCount(1).ShouldEqual("item"); } }
using Machine.Specifications; namespace Quarks.Tests { [Subject(typeof(Inflector))] class When_using_pluralize_for_count { It should_pluralize_when_count_is_greater_than_two = () => "item".PluralizeForCount(2).ShouldEqual("items"); It should_pluralize_when_count_is_zero = () => "item".PluralizeForCount(0).ShouldEqual("items"); It should_not_pluralize_when_count_is_one = () => "item".PluralizeForCount(1).ShouldEqual("item"); } }
Remove "public" access modifier from test class
Remove "public" access modifier from test class
C#
mit
shaynevanasperen/Quarks
86d8910e56eebcdab1ec6f9c12774638b7ff6287
src/Foundatio/Messaging/Message.cs
src/Foundatio/Messaging/Message.cs
using System; using System.Collections.Generic; namespace Foundatio.Messaging { public interface IMessage { string Type { get; } Type ClrType { get; } byte[] Data { get; } object GetBody(); IReadOnlyDictionary<string, string> Properties { get; } } public class Message : IMessage { private Lazy<object> _getBody; public Message(Func<object> getBody) { if (getBody == null) throw new ArgumentNullException("getBody"); _getBody = new Lazy<object>(getBody); } public string Type { get; set; } public Type ClrType { get; set; } public byte[] Data { get; set; } public object GetBody() => _getBody.Value; public IReadOnlyDictionary<string, string> Properties { get; set; } = new Dictionary<string, string>(); } }
using System; using System.Collections.Generic; using System.Diagnostics; namespace Foundatio.Messaging { public interface IMessage { string Type { get; } Type ClrType { get; } byte[] Data { get; } object GetBody(); IReadOnlyDictionary<string, string> Properties { get; } } [DebuggerDisplay("Type: {Type}")] public class Message : IMessage { private Lazy<object> _getBody; public Message(Func<object> getBody) { if (getBody == null) throw new ArgumentNullException("getBody"); _getBody = new Lazy<object>(getBody); } public string Type { get; set; } public Type ClrType { get; set; } public byte[] Data { get; set; } public object GetBody() => _getBody.Value; public IReadOnlyDictionary<string, string> Properties { get; set; } = new Dictionary<string, string>(); } }
Add message debugger display to show the message type
Add message debugger display to show the message type
C#
apache-2.0
FoundatioFx/Foundatio,exceptionless/Foundatio
d2e048c405a9e47bab82a211305bfff118edd26b
Assets/HoloToolkit/Utilities/Scripts/SingleInstance.cs
Assets/HoloToolkit/Utilities/Scripts/SingleInstance.cs
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using UnityEngine; namespace HoloToolkit.Unity { /// <summary> /// A simplified version of the Singleton class which doesn't depend on the Instance being set in Awake /// </summary> /// <typeparam name="T"></typeparam> public class SingleInstance<T> : MonoBehaviour where T : SingleInstance<T> { private static T _Instance; public static T Instance { get { if (_Instance == null) { T[] objects = Resources.FindObjectsOfTypeAll<T>(); if (objects.Length != 1) { Debug.LogErrorFormat("Expected exactly 1 {0} but found {1}", typeof(T).ToString(), objects.Length); } else { _Instance = objects[0]; } } return _Instance; } } /// <summary> /// Called by Unity when destroying a MonoBehaviour. Scripts that extend /// SingleInstance should be sure to call base.OnDestroy() to ensure the /// underlying static _Instance reference is properly cleaned up. /// </summary> protected virtual void OnDestroy() { _Instance = null; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using UnityEngine; namespace HoloToolkit.Unity { /// <summary> /// A simplified version of the Singleton class which doesn't depend on the Instance being set in Awake /// </summary> /// <typeparam name="T"></typeparam> public class SingleInstance<T> : MonoBehaviour where T : SingleInstance<T> { private static T _Instance; public static T Instance { get { if (_Instance == null) { T[] objects = FindObjectsOfType<T>(); if (objects.Length != 1) { Debug.LogErrorFormat("Expected exactly 1 {0} but found {1}", typeof(T).ToString(), objects.Length); } else { _Instance = objects[0]; } } return _Instance; } } /// <summary> /// Called by Unity when destroying a MonoBehaviour. Scripts that extend /// SingleInstance should be sure to call base.OnDestroy() to ensure the /// underlying static _Instance reference is properly cleaned up. /// </summary> protected virtual void OnDestroy() { _Instance = null; } } }
Revert "Instance isn't found if class is on a disabled GameObject."
Revert "Instance isn't found if class is on a disabled GameObject."
C#
mit
paseb/MixedRealityToolkit-Unity,NeerajW/HoloToolkit-Unity,paseb/HoloToolkit-Unity,out-of-pixel/HoloToolkit-Unity,HattMarris1/HoloToolkit-Unity,willcong/HoloToolkit-Unity
a35ef538916b89cdce5339399a14a58dd14f1144
src/Microsoft.VisualStudio.Editor.Razor/DefaultProjectPathProviderFactory.cs
src/Microsoft.VisualStudio.Editor.Razor/DefaultProjectPathProviderFactory.cs
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Razor; namespace Microsoft.VisualStudio.Editor.Razor { [System.Composition.Shared] [ExportWorkspaceService(typeof(ProjectPathProvider), ServiceLayer.Default)] internal class DefaultProjectPathProviderFactory : IWorkspaceServiceFactory { private readonly TextBufferProjectService _projectService; [ImportingConstructor] public DefaultProjectPathProviderFactory(TextBufferProjectService projectService) { if (projectService == null) { throw new ArgumentNullException(nameof(projectService)); } _projectService = projectService; } public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) { if (workspaceServices == null) { throw new ArgumentNullException(nameof(workspaceServices)); } return new DefaultProjectPathProvider(_projectService); } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Composition; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.VisualStudio.Editor.Razor { [Shared] [ExportWorkspaceServiceFactory(typeof(ProjectPathProvider), ServiceLayer.Default)] internal class DefaultProjectPathProviderFactory : IWorkspaceServiceFactory { private readonly TextBufferProjectService _projectService; [ImportingConstructor] public DefaultProjectPathProviderFactory(TextBufferProjectService projectService) { if (projectService == null) { throw new ArgumentNullException(nameof(projectService)); } _projectService = projectService; } public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) { if (workspaceServices == null) { throw new ArgumentNullException(nameof(workspaceServices)); } return new DefaultProjectPathProvider(_projectService); } } }
Fix mef attributes project path provider
Fix mef attributes project path provider
C#
apache-2.0
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
ded8af3269f9899308d85bfe46eea50df0b08180
src/DotNetPrerender/DotNetOpen.PrerenderModule/Constants.cs
src/DotNetPrerender/DotNetOpen.PrerenderModule/Constants.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DotNetOpen.PrerenderModule { public static class Constants { #region Const public const string PrerenderIOServiceUrl = "http://service.prerender.io/"; public const int DefaultPort = 80; public const string CrawlerUserAgentPattern = "(google)|(bing)|(Slurp)|(DuckDuckBot)|(YandexBot)|(baiduspider)|(Sogou)|(Exabot)|(ia_archiver)|(facebot)|(facebook)|(twitterbot)|(rogerbot)|(linkedinbot)|(embedly)|(quora)|(pinterest)|(slackbot)|(redditbot)|(Applebot)|(WhatsApp)|(flipboard)|(tumblr)|(bitlybot)|(Discordbot)"; public const string EscapedFragment = "_escaped_fragment_"; public const string HttpProtocol = "http://"; public const string HttpsProtocol = "https://"; public const string HttpHeader_XForwardedProto = "X-Forwarded-Proto"; public const string HttpHeader_XPrerenderToken = "X-Prerender-Token"; public const string AppSetting_UsePrestartForPrenderModule = "UsePrestartForPrenderModule"; #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DotNetOpen.PrerenderModule { public static class Constants { #region Const public const string PrerenderIOServiceUrl = "http://service.prerender.io/"; public const int DefaultPort = 80; public const string CrawlerUserAgentPattern = "(bingbot)|(googlebot)|(google)|(bing)|(Slurp)|(DuckDuckBot)|(YandexBot)|(baiduspider)|(Sogou)|(Exabot)|(ia_archiver)|(facebot)|(facebook)|(twitterbot)|(rogerbot)|(linkedinbot)|(embedly)|(quora)|(pinterest)|(slackbot)|(redditbot)|(Applebot)|(WhatsApp)|(flipboard)|(tumblr)|(bitlybot)|(Discordbot)"; public const string EscapedFragment = "_escaped_fragment_"; public const string HttpProtocol = "http://"; public const string HttpsProtocol = "https://"; public const string HttpHeader_XForwardedProto = "X-Forwarded-Proto"; public const string HttpHeader_XPrerenderToken = "X-Prerender-Token"; public const string AppSetting_UsePrestartForPrenderModule = "UsePrestartForPrenderModule"; #endregion } }
Add googlebot and bingbot to list of crawler user agents
Add googlebot and bingbot to list of crawler user agents Prerender.io docs recommend to upgrade these: https://prerender.io/documentation/google-support >>>Make sure to update your Prerender.io middleware or manually add googlebot and bingbot to the list of user agents being checked by your Prerender.io middleware. See the bottom of this page for examples on adding googlebot to your middleware. There have been some reported issues with Googlebot rendering JavaScript on the first request to a URL that still uses the ?_escaped_fragment_= protocol, so upgrading will prevent any issues by serving a prerendered page directly to Googlebot on the first request.
C#
mit
dingyuliang/prerender-dotnet,dingyuliang/prerender-dotnet,dingyuliang/prerender-dotnet
02498f854e43b3a3dae84e1ea0f427cd26179758
src/NadekoBot/Modules/Verification/Exceptions/Exceptions.cs
src/NadekoBot/Modules/Verification/Exceptions/Exceptions.cs
using System; namespace Mitternacht.Modules.Verification.Exceptions { public class UserAlreadyVerifyingException : Exception {} public class UserAlreadyVerifiedException : Exception {} public class UserCannotVerifyException : Exception { } //public class Exception : Exception { } }
using System; namespace Mitternacht.Modules.Verification.Exceptions { public class UserAlreadyVerifyingException : Exception { } public class UserAlreadyVerifiedException : Exception { } public class UserCannotVerifyException : Exception { } }
Remove unnecessary comment and format file.
Remove unnecessary comment and format file.
C#
mit
Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW
a9dade13f828536ab6bee0b36582e321a075df0c
src/CGO.Web/Areas/Admin/Views/Shared/_Layout.cshtml
src/CGO.Web/Areas/Admin/Views/Shared/_Layout.cshtml
<!DOCTYPE html> <html lang="en"> <head> <meta name="viewport" content="width=device-width" /> <title>@ViewBag.Title</title> @Styles.Render("~/Content/bootstrap.min.css") </head> <body> <div> @RenderBody() </div> @RenderSection("Scripts", false) </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta name="viewport" content="width=device-width" /> <title>@ViewBag.Title</title> @Styles.Render("~/Content/bootstrap.min.css") @Styles.Render("~/Content/bootstrap-responsive.min.css") @Styles.Render("~/bundles/font-awesome") <!-- HTML5 shim, for IE6-8 support of HTML5 elements --> <!--[if lt IE 9]> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> @Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/modernizr") @Scripts.Render("~/bundles/knockout") <script type="text/javascript"> Modernizr.load({ test: Modernizr.input.placeholder, nope: '/scripts/placeholder.js' }); Modernizr.load({ test: Modernizr.inputtypes.date, nope: '/scripts/datepicker.js' }); </script> </head> <body> <div> @RenderBody() </div> @RenderSection("Scripts", false) </body> </html>
Add styles and scripts to admin Layout.
Add styles and scripts to admin Layout. Bootstrap responsive stylesheet, plus jQuery, Modernizr, HTML5 shim, and Knockout.
C#
mit
alastairs/cgowebsite,alastairs/cgowebsite
7a41c564375bab8354c308320ff98d2a5603f661
VersionInfo.cs
VersionInfo.cs
using System.Reflection; [assembly: AssemblyCompany("Yin-Chun Wang")] [assembly: AssemblyCopyright("Copyright © Yin-Chun Wang 2014")] [assembly: AssemblyVersion(_ModernWPFVersionString.Release)] [assembly: AssemblyFileVersion(_ModernWPFVersionString.Build)] [assembly: AssemblyInformationalVersion(_ModernWPFVersionString.Build)] static class _ModernWPFVersionString { // keep this same in majors releases public const string Release = "1.0.0.0"; // change this for each nuget release public const string Build = "1.1.30"; }
using System.Reflection; [assembly: AssemblyCompany("Yin-Chun Wang")] [assembly: AssemblyCopyright("Copyright © Yin-Chun Wang 2014")] [assembly: AssemblyVersion(ModernWPF._ModernWPFVersionString.Release)] [assembly: AssemblyFileVersion(ModernWPF._ModernWPFVersionString.Build)] [assembly: AssemblyInformationalVersion(ModernWPF._ModernWPFVersionString.Build)] namespace ModernWPF { static class _ModernWPFVersionString { // keep this same in majors releases public const string Release = "1.0.0.0"; // change this for each nuget release public const string Build = "1.1.30"; } }
Put version info class under namespace.
Put version info class under namespace.
C#
mit
soukoku/ModernWPF
2124e6bcf7b450084cf66f10c5333772d314f268
Devkoes.VSJenkinsManager/Devkoes.JenkinsManager.VSPackage/ExposedServices/VisualStudioWindowsHandler.cs
Devkoes.VSJenkinsManager/Devkoes.JenkinsManager.VSPackage/ExposedServices/VisualStudioWindowsHandler.cs
using Devkoes.JenkinsManager.Model.Contract; using Devkoes.JenkinsManager.UI; using Devkoes.JenkinsManager.UI.Views; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using System; namespace Devkoes.JenkinsManager.VSPackage.ExposedServices { public class VisualStudioWindowHandler : IVisualStudioWindowHandler { public void ShowToolWindow() { // Get the instance number 0 of this tool window. This window is single instance so this instance // is actually the only one. // The last flag is set to true so that if the tool window does not exists it will be created. ToolWindowPane window = VSJenkinsManagerPackage.Instance.FindToolWindow(typeof(JenkinsToolWindow), 0, true); if ((null == window) || (null == window.Frame)) { throw new NotSupportedException(Resources.CanNotCreateWindow); } IVsWindowFrame windowFrame = (IVsWindowFrame)window.Frame; Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(windowFrame.Show()); } public void ShowSettingsWindow() { try { VSJenkinsManagerPackage.Instance.ShowOptionPage(typeof(UserOptionsHost)); } catch (Exception ex) { ServicesContainer.OutputWindowLogger.LogOutput("Showing settings panel failed:", ex); } } } }
using Devkoes.JenkinsManager.Model.Contract; using Devkoes.JenkinsManager.UI; using Devkoes.JenkinsManager.UI.Views; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using System; namespace Devkoes.JenkinsManager.VSPackage.ExposedServices { public class VisualStudioWindowHandler : IVisualStudioWindowHandler { public void ShowToolWindow() { // Get the instance number 0 of this tool window. This window is single instance so this instance // is actually the only one. // The last flag is set to true so that if the tool window does not exists it will be created. ToolWindowPane window = VSJenkinsManagerPackage.Instance.FindToolWindow(typeof(JenkinsToolWindow), 0, true); if ((null == window) || (null == window.Frame)) { throw new NotSupportedException(Resources.CanNotCreateWindow); } IVsWindowFrame windowFrame = (IVsWindowFrame)window.Frame; Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(windowFrame.Show()); } public void ShowSettingsWindow() { try { VSJenkinsManagerPackage.Instance.ShowOptionPage(typeof(UserOptionsHost)); } catch (Exception ex) { ServicesContainer.OutputWindowLogger.LogOutput( "Showing settings panel failed:", ex.ToString()); } } } }
Revert "Logging has new overload for exceptions, use it"
Revert "Logging has new overload for exceptions, use it" This reverts commit 2fe8666247d45c289a6a2ca4fb716f0d25d756f1.
C#
mit
tomkuijsten/vsjenkinsmanager
218b57ccf3db2243bbf7fa44a9c7544e1b935bc8
Assets/PJEI/Invaders/Scripts/Level.cs
Assets/PJEI/Invaders/Scripts/Level.cs
using UnityEngine; namespace PJEI.Invaders { public class Level : MonoBehaviour { public Alien[] lines; public int width = 11; public int pixelsBetweenAliens = 48; private Alien[] aliens; void Start() { StartCoroutine(InitGame()); } private System.Collections.IEnumerator InitGame() { aliens = new Alien[lines.Length * width]; for (int i = lines.Length - 1; i >= 0; --i) { for (int j = 0; j < width; ++j) { var alien = (Alien)Instantiate(lines[i]); alien.Initialize(new Vector2D(j - width / 2, -i + lines.Length / 2), i, pixelsBetweenAliens); aliens[i * width + j] = alien; yield return new WaitForSeconds(.1f); } } foreach (var alien in aliens) alien.Run(); } } }
using UnityEngine; namespace PJEI.Invaders { public class Level : MonoBehaviour { public Alien[] lines; public int width = 11; public int pixelsBetweenAliens = 48; private Alien[] aliens; void Start() { StartCoroutine(InitGame()); } private System.Collections.IEnumerator InitGame() { aliens = new Alien[lines.Length * width]; for (int i = lines.Length - 1; i >= 0; --i) { for (int j = 0; j < width; ++j) { var alien = (Alien)Instantiate(lines[i]); alien.Initialize(new Vector2D(j - width / 2, -i + lines.Length / 2), i, pixelsBetweenAliens); aliens[i * width + j] = alien; yield return new WaitForSeconds(.05f); } } foreach (var alien in aliens) alien.Run(); } } }
Speed up alien start up positioning.
Speed up alien start up positioning.
C#
unlicense
Elideb/PJEI
348286a19c4edba870b826f76a03e2f5c13d9a1f
test/Cronofy.Test/CronofyEnterpriseConnectAccountClientTests/AuthorizeUser.cs
test/Cronofy.Test/CronofyEnterpriseConnectAccountClientTests/AuthorizeUser.cs
using System; using NUnit.Framework; namespace Cronofy.Test.CronofyEnterpriseConnectAccountClientTests { internal sealed class AuthorizeUser : Base { [Test] public void CanAuthorizeUser() { const string email = "test@cronofy.com"; const string callbackUrl = "https://cronofy.com/test-callback"; const string scopes = "read_account list_calendars read_events create_event delete_event read_free_busy"; Http.Stub( HttpPost .Url("https://api.cronofy.com/v1/service_account_authorizations") .RequestHeader("Authorization", "Bearer " + AccessToken) .RequestHeader("Content-Type", "application/json; charset=utf-8") .RequestBodyFormat( "{{\"email\":\"{0}\"," + "\"callback_url\":\"{1}\"," + "\"scope\":\"{2}\"" + "}}", email, callbackUrl, scopes) .ResponseCode(202) ); Client.AuthorizeUser(email, callbackUrl, scopes); } } }
using System; using NUnit.Framework; namespace Cronofy.Test.CronofyEnterpriseConnectAccountClientTests { internal sealed class AuthorizeUser : Base { [Test] public void CanAuthorizeUser() { const string email = "test@cronofy.com"; const string callbackUrl = "https://cronofy.com/test-callback"; const string scopes = "read_account list_calendars read_events create_event delete_event read_free_busy"; Http.Stub( HttpPost .Url("https://api.cronofy.com/v1/service_account_authorizations") .RequestHeader("Authorization", "Bearer " + AccessToken) .RequestHeader("Content-Type", "application/json; charset=utf-8") .RequestBodyFormat( "{{\"email\":\"{0}\"," + "\"callback_url\":\"{1}\"," + "\"scope\":\"{2}\"" + "}}", email, callbackUrl, scopes) .ResponseCode(202) ); Client.AuthorizeUser(email, callbackUrl, scopes); } [Test] public void CanAuthorizeUserWithEnumerableScopes() { const string email = "test@test.com"; const string callbackUrl = "https://test.com/test-callback"; string[] scopes = { "read_account", "list_calendars", "read_events", "create_event", "delete_event", "read_free_busy" }; Http.Stub( HttpPost .Url("https://api.cronofy.com/v1/service_account_authorizations") .RequestHeader("Authorization", "Bearer " + AccessToken) .RequestHeader("Content-Type", "application/json; charset=utf-8") .RequestBodyFormat( "{{\"email\":\"{0}\"," + "\"callback_url\":\"{1}\"," + "\"scope\":\"{2}\"" + "}}", email, callbackUrl, String.Join(" ", scopes)) .ResponseCode(202) ); Client.AuthorizeUser(email, callbackUrl, scopes); } } }
Add test for Enterprise Connect Authorize User with enumerable string
Add test for Enterprise Connect Authorize User with enumerable string
C#
mit
cronofy/cronofy-csharp
fc6e7b4c5369bf296fd7026567dd67e4aaa3baa2
Mongo.Migration/Services/MongoDB/MongoRegistrator.cs
Mongo.Migration/Services/MongoDB/MongoRegistrator.cs
using System; using Mongo.Migration.Documents; using Mongo.Migration.Documents.Serializers; using Mongo.Migration.Services.Interceptors; using MongoDB.Bson; using MongoDB.Bson.Serialization; namespace Mongo.Migration.Services.MongoDB { internal class MongoRegistrator : IMongoRegistrator { private readonly MigrationInterceptorProvider _provider; private readonly DocumentVersionSerializer _serializer; public MongoRegistrator(DocumentVersionSerializer serializer, MigrationInterceptorProvider provider) { _serializer = serializer; _provider = provider; } public void Register() { BsonSerializer.RegisterSerializationProvider(_provider); try { BsonSerializer.RegisterSerializer(typeof(DocumentVersion), _serializer); } catch (BsonSerializationException Exception) { // Catch if Serializer was registered already, not great. But for testing it must be catched. } } } }
using System; using Mongo.Migration.Documents; using Mongo.Migration.Documents.Serializers; using Mongo.Migration.Services.Interceptors; using MongoDB.Bson; using MongoDB.Bson.Serialization; namespace Mongo.Migration.Services.MongoDB { internal class MongoRegistrator : IMongoRegistrator { private readonly MigrationInterceptorProvider _provider; private readonly DocumentVersionSerializer _serializer; public MongoRegistrator(DocumentVersionSerializer serializer, MigrationInterceptorProvider provider) { _serializer = serializer; _provider = provider; } public void Register() { RegisterSerializationProvider(); RegisterSerializer(); } private void RegisterSerializationProvider() { BsonSerializer.RegisterSerializationProvider(_provider); } private void RegisterSerializer() { var foundSerializer = BsonSerializer.LookupSerializer(_serializer.ValueType); if (foundSerializer == null) BsonSerializer.RegisterSerializer(_serializer.ValueType, _serializer); } } }
Use lookup before registering serializer
Use lookup before registering serializer
C#
mit
SRoddis/Mongo.Migration
5cdd7806d0de6049e26c9276c6311dea36b98595
src/Framework/PropellerMvcModel/Adapters/Image.cs
src/Framework/PropellerMvcModel/Adapters/Image.cs
using Sitecore.Data; using Sitecore.Data.Fields; using Sitecore.Data.Items; namespace Propeller.Mvc.Model.Adapters { public class Image : IFieldAdapter { public string Url { get; set; } public string Alt { get; set; } public void InitAdapter(Item item, ID propId) { ImageField image = item.Fields[propId]; if (image == null) return; var mediaItem = image.MediaDatabase.GetItem(image.MediaID); Url = Sitecore.Resources.Media.MediaManager.GetMediaUrl(mediaItem); Alt = image.Alt; } } }
using Sitecore; using Sitecore.Data; using Sitecore.Data.Fields; using Sitecore.Data.Items; namespace Propeller.Mvc.Model.Adapters { public class Image : IFieldAdapter { public string Url { get; set; } public string Alt { get; set; } public void InitAdapter(Item item, ID propId) { Url = string.Empty; Alt = string.Empty; ImageField image = item.Fields[propId]; if (image == null ||image.MediaID == ItemIDs.Null) return; var mediaItem = image.MediaDatabase.GetItem(image.MediaID); Url = Sitecore.Resources.Media.MediaManager.GetMediaUrl(mediaItem); Alt = image.Alt; } } }
Fix problem with image adapter when an item has empty standard values.
Fix problem with image adapter when an item has empty standard values.
C#
mit
galtrold/propeller.mvc,galtrold/propeller.mvc,galtrold/propeller.mvc,galtrold/propeller.mvc,galtrold/propeller.mvc
cbbc1cb30e5f70138a2e6c8f439a45b9fd6ef92b
asp-net-mvc-localization/asp-net-mvc-localization/Models/User.cs
asp-net-mvc-localization/asp-net-mvc-localization/Models/User.cs
using System.ComponentModel.DataAnnotations; using System; using asp_net_mvc_localization.Utils; using Newtonsoft.Json.Serialization; namespace asp_net_mvc_localization.Models { public class User { [Required] public string Username { get; set; } [Display] [Required] [MyEmailAddress] public string Email { get; set; } [Display] [Required] [MinLength(6)] [MaxLength(64)] public string Password { get; set; } [Display] [Range(1,125)] public int Age { get; set; } [Display] public DateTime Birthday { get; set; } [Display] [Required] [Range(0.1, 9.9)] public double Rand { get; set; } } }
using System.ComponentModel.DataAnnotations; using System; using asp_net_mvc_localization.Utils; using Newtonsoft.Json.Serialization; namespace asp_net_mvc_localization.Models { public class User { [Required] public string Username { get; set; } [Required] [MyEmailAddress] public string Email { get; set; } [Required] [MinLength(6)] [MaxLength(64)] public string Password { get; set; } [Range(1,125)] public int Age { get; set; } [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:d}")] public DateTime Birthday { get; set; } [Required] [Range(0.1, 9.9)] public double Rand { get; set; } } }
Delete [Display](all work's without it), fix Date format in Create
Delete [Display](all work's without it), fix Date format in Create
C#
mit
DevRainSolutions/asp-net-mvc-localization,DevRainSolutions/asp-net-mvc-localization,DevRainSolutions/asp-net-mvc-localization
2b8ade5615560cad060d1c5a197c680bdf21f948
JabbR/Nancy/ErrorPageHandler.cs
JabbR/Nancy/ErrorPageHandler.cs
using System.Linq; using JabbR.Services; using Nancy; using Nancy.ErrorHandling; using Nancy.ViewEngines; namespace JabbR.Nancy { public class ErrorPageHandler : DefaultViewRenderer, IStatusCodeHandler { private readonly IJabbrRepository _repository; public ErrorPageHandler(IViewFactory factory, IJabbrRepository repository) : base(factory) { _repository = repository; } public bool HandlesStatusCode(HttpStatusCode statusCode, NancyContext context) { // only handle 40x and 50x return (int)statusCode >= 400; } public void Handle(HttpStatusCode statusCode, NancyContext context) { string suggestRoomName = null; if (statusCode == HttpStatusCode.NotFound && context.Request.Url.Path.Count(e => e == '/') == 1) { // trim / from start of path var potentialRoomName = context.Request.Url.Path.Substring(1); if (_repository.GetRoomByName(potentialRoomName) != null) { suggestRoomName = potentialRoomName; } } var response = RenderView( context, "errorPage", new { Error = statusCode, ErrorCode = (int)statusCode, SuggestRoomName = suggestRoomName }); response.StatusCode = statusCode; context.Response = response; } } }
using System.Text.RegularExpressions; using JabbR.Services; using Nancy; using Nancy.ErrorHandling; using Nancy.ViewEngines; namespace JabbR.Nancy { public class ErrorPageHandler : DefaultViewRenderer, IStatusCodeHandler { private readonly IJabbrRepository _repository; public ErrorPageHandler(IViewFactory factory, IJabbrRepository repository) : base(factory) { _repository = repository; } public bool HandlesStatusCode(HttpStatusCode statusCode, NancyContext context) { // only handle 40x and 50x return (int)statusCode >= 400; } public void Handle(HttpStatusCode statusCode, NancyContext context) { string suggestRoomName = null; if (statusCode == HttpStatusCode.NotFound) { var match = Regex.Match(context.Request.Url.Path, "^/(rooms/)?(?<roomName>[^/]+)$", RegexOptions.IgnoreCase); if (match.Success) { var potentialRoomName = match.Groups["roomName"].Value; if (_repository.GetRoomByName(potentialRoomName) != null) { suggestRoomName = potentialRoomName; } } } var response = RenderView( context, "errorPage", new { Error = statusCode, ErrorCode = (int)statusCode, SuggestRoomName = suggestRoomName }); response.StatusCode = statusCode; context.Response = response; } } }
Support 404 url suggestions for /rooms/xyz in addition to /xyz.
Support 404 url suggestions for /rooms/xyz in addition to /xyz.
C#
mit
timgranstrom/JabbR,e10/JabbR,JabbR/JabbR,borisyankov/JabbR,18098924759/JabbR,yadyn/JabbR,SonOfSam/JabbR,SonOfSam/JabbR,M-Zuber/JabbR,M-Zuber/JabbR,18098924759/JabbR,borisyankov/JabbR,ajayanandgit/JabbR,yadyn/JabbR,mzdv/JabbR,borisyankov/JabbR,timgranstrom/JabbR,mzdv/JabbR,e10/JabbR,JabbR/JabbR,ajayanandgit/JabbR,yadyn/JabbR
8029dc421d1e04725b4f9b229b9c1e8c16c5500b
src/Nancy.Demo.Razor.Localization/Views/CultureView-de-DE.cshtml
src/Nancy.Demo.Razor.Localization/Views/CultureView-de-DE.cshtml
@inherits Nancy.ViewEngines.Razor.NancyRazorViewBase<dynamic> @{ Layout = "razor-layout.cshtml"; } <h1>You're here based on ther German culture set in HomeModule however the HomeModule only calls return View["CultureView"]. It uses View Location Conventions therefore there must be a file called CultureView-de-DE.cshtml</h1>
@inherits Nancy.ViewEngines.Razor.NancyRazorViewBase<dynamic> @{ Layout = "razor-layout.cshtml"; } <h1>You're here based on the German culture set in HomeModule however the HomeModule only calls return View["CultureView"]. It uses View Location Conventions therefore there must be a file called CultureView-de-DE.cshtml</h1>
Fix typo on CultureView-de-De in Localization Demo
Fix typo on CultureView-de-De in Localization Demo
C#
mit
jmptrader/Nancy,VQComms/Nancy,anton-gogolev/Nancy,damianh/Nancy,sloncho/Nancy,danbarua/Nancy,AlexPuiu/Nancy,nicklv/Nancy,jeff-pang/Nancy,grumpydev/Nancy,ccellar/Nancy,malikdiarra/Nancy,joebuschmann/Nancy,sloncho/Nancy,murador/Nancy,EIrwin/Nancy,hitesh97/Nancy,sadiqhirani/Nancy,phillip-haydon/Nancy,rudygt/Nancy,EliotJones/NancyTest,jonathanfoster/Nancy,adamhathcock/Nancy,jchannon/Nancy,VQComms/Nancy,horsdal/Nancy,charleypeng/Nancy,tparnell8/Nancy,AcklenAvenue/Nancy,xt0rted/Nancy,davidallyoung/Nancy,sadiqhirani/Nancy,fly19890211/Nancy,SaveTrees/Nancy,damianh/Nancy,cgourlay/Nancy,jchannon/Nancy,duszekmestre/Nancy,felipeleusin/Nancy,sloncho/Nancy,thecodejunkie/Nancy,jchannon/Nancy,jongleur1983/Nancy,fly19890211/Nancy,phillip-haydon/Nancy,guodf/Nancy,jchannon/Nancy,nicklv/Nancy,vladlopes/Nancy,lijunle/Nancy,Novakov/Nancy,EliotJones/NancyTest,daniellor/Nancy,nicklv/Nancy,phillip-haydon/Nancy,danbarua/Nancy,grumpydev/Nancy,khellang/Nancy,rudygt/Nancy,duszekmestre/Nancy,MetSystem/Nancy,Novakov/Nancy,MetSystem/Nancy,AIexandr/Nancy,charleypeng/Nancy,JoeStead/Nancy,asbjornu/Nancy,wtilton/Nancy,jmptrader/Nancy,xt0rted/Nancy,asbjornu/Nancy,SaveTrees/Nancy,albertjan/Nancy,joebuschmann/Nancy,ccellar/Nancy,tareq-s/Nancy,khellang/Nancy,adamhathcock/Nancy,davidallyoung/Nancy,duszekmestre/Nancy,charleypeng/Nancy,tareq-s/Nancy,joebuschmann/Nancy,AcklenAvenue/Nancy,NancyFx/Nancy,sroylance/Nancy,thecodejunkie/Nancy,phillip-haydon/Nancy,hitesh97/Nancy,vladlopes/Nancy,jeff-pang/Nancy,EliotJones/NancyTest,VQComms/Nancy,NancyFx/Nancy,albertjan/Nancy,thecodejunkie/Nancy,dbolkensteyn/Nancy,jmptrader/Nancy,thecodejunkie/Nancy,hitesh97/Nancy,JoeStead/Nancy,dbolkensteyn/Nancy,jonathanfoster/Nancy,NancyFx/Nancy,AIexandr/Nancy,sroylance/Nancy,joebuschmann/Nancy,MetSystem/Nancy,jchannon/Nancy,wtilton/Nancy,felipeleusin/Nancy,vladlopes/Nancy,Worthaboutapig/Nancy,tsdl2013/Nancy,horsdal/Nancy,dbabox/Nancy,khellang/Nancy,tareq-s/Nancy,blairconrad/Nancy,anton-gogolev/Nancy,xt0rted/Nancy,jongleur1983/Nancy,vladlopes/Nancy,JoeStead/Nancy,AlexPuiu/Nancy,ayoung/Nancy,jongleur1983/Nancy,khellang/Nancy,fly19890211/Nancy,tparnell8/Nancy,EliotJones/NancyTest,davidallyoung/Nancy,tparnell8/Nancy,albertjan/Nancy,jmptrader/Nancy,wtilton/Nancy,daniellor/Nancy,ccellar/Nancy,jonathanfoster/Nancy,dbolkensteyn/Nancy,tsdl2013/Nancy,anton-gogolev/Nancy,adamhathcock/Nancy,Worthaboutapig/Nancy,hitesh97/Nancy,cgourlay/Nancy,malikdiarra/Nancy,nicklv/Nancy,MetSystem/Nancy,grumpydev/Nancy,AIexandr/Nancy,blairconrad/Nancy,lijunle/Nancy,EIrwin/Nancy,duszekmestre/Nancy,damianh/Nancy,jongleur1983/Nancy,guodf/Nancy,ccellar/Nancy,Worthaboutapig/Nancy,sadiqhirani/Nancy,sadiqhirani/Nancy,grumpydev/Nancy,felipeleusin/Nancy,malikdiarra/Nancy,cgourlay/Nancy,murador/Nancy,jeff-pang/Nancy,ayoung/Nancy,murador/Nancy,EIrwin/Nancy,lijunle/Nancy,tsdl2013/Nancy,xt0rted/Nancy,anton-gogolev/Nancy,guodf/Nancy,AIexandr/Nancy,Novakov/Nancy,asbjornu/Nancy,jeff-pang/Nancy,davidallyoung/Nancy,Worthaboutapig/Nancy,horsdal/Nancy,cgourlay/Nancy,tareq-s/Nancy,dbabox/Nancy,horsdal/Nancy,davidallyoung/Nancy,dbabox/Nancy,blairconrad/Nancy,charleypeng/Nancy,felipeleusin/Nancy,asbjornu/Nancy,NancyFx/Nancy,jonathanfoster/Nancy,EIrwin/Nancy,tparnell8/Nancy,murador/Nancy,sloncho/Nancy,VQComms/Nancy,charleypeng/Nancy,rudygt/Nancy,AcklenAvenue/Nancy,ayoung/Nancy,asbjornu/Nancy,albertjan/Nancy,Novakov/Nancy,wtilton/Nancy,rudygt/Nancy,AIexandr/Nancy,sroylance/Nancy,fly19890211/Nancy,danbarua/Nancy,dbolkensteyn/Nancy,dbabox/Nancy,AlexPuiu/Nancy,AlexPuiu/Nancy,lijunle/Nancy,JoeStead/Nancy,VQComms/Nancy,blairconrad/Nancy,adamhathcock/Nancy,guodf/Nancy,sroylance/Nancy,SaveTrees/Nancy,SaveTrees/Nancy,danbarua/Nancy,daniellor/Nancy,tsdl2013/Nancy,malikdiarra/Nancy,daniellor/Nancy,ayoung/Nancy,AcklenAvenue/Nancy
b8e852a4736b281e10754edbaacb6403e3d2cae6
tests/Magick.NET.Tests/MagickNETTests/TheFeaturesProperty.cs
tests/Magick.NET.Tests/MagickNETTests/TheFeaturesProperty.cs
// Copyright 2013-2020 Dirk Lemstra <https://github.com/dlemstra/Magick.NET/> // // Licensed under the ImageMagick License (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // https://www.imagemagick.org/script/license.php // // Unless required by applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing permissions // and limitations under the License. using ImageMagick; using Xunit; namespace Magick.NET.Tests { public partial class MagickNETTests { public class TheFeaturesProperty { [Fact] public void ContainsExpectedFeatures() { var expected = "Cipher DPC "; #if Q16HDRI expected += "HDRI "; #endif #if WINDOWS_BUILD expected += "OpenCL "; #endif #if OPENMP expected += "OpenMP(2.0) "; #endif #if DEBUG_TEST expected = "Debug " + expected; #endif Assert.Equal(expected, MagickNET.Features); } } } }
// Copyright 2013-2020 Dirk Lemstra <https://github.com/dlemstra/Magick.NET/> // // Licensed under the ImageMagick License (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // https://www.imagemagick.org/script/license.php // // Unless required by applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing permissions // and limitations under the License. using ImageMagick; using Xunit; namespace Magick.NET.Tests { public partial class MagickNETTests { public class TheFeaturesProperty { [Fact] public void ContainsExpectedFeatures() { var expected = "Cipher DPC "; #if Q16HDRI expected += "HDRI "; #endif if (OperatingSystem.IsWindows) expected += "OpenCL "; #if OPENMP expected += "OpenMP(2.0) "; #endif #if DEBUG_TEST expected = "Debug " + expected; #endif Assert.Equal(expected, MagickNET.Features); } } } }
Use the new OperatingSystem class.
Use the new OperatingSystem class.
C#
apache-2.0
dlemstra/Magick.NET,dlemstra/Magick.NET
36bd8cdc0f3fc657a9dc0e6993005b7745df4bca
TempoDB.Tests/src/TempoDBTests.cs
TempoDB.Tests/src/TempoDBTests.cs
using NUnit.Framework; using RestSharp; namespace TempoDB.Tests { [TestFixture] public class TempoDBTests { [Test] public void Defaults() { var tempodb = new TempoDB("key", "secret"); Assert.AreEqual("key", tempodb.Key); Assert.AreEqual("secret", tempodb.Secret); Assert.AreEqual("api.tempo-db.com", tempodb.Host); Assert.AreEqual(443, tempodb.Port); Assert.AreEqual(true, tempodb.Secure); Assert.AreEqual("v1", tempodb.Version); Assert.AreNotEqual(null, tempodb.Client); Assert.IsInstanceOfType(typeof(RestClient), tempodb.Client); } } }
using NUnit.Framework; using RestSharp; namespace TempoDB.Tests { [TestFixture] public class TempoDBTests { [Test] public void Defaults() { var tempodb = new TempoDB("key", "secret"); Assert.AreEqual("key", tempodb.Key); Assert.AreEqual("secret", tempodb.Secret); Assert.AreEqual("api.tempo-db.com", tempodb.Host); Assert.AreEqual(443, tempodb.Port); Assert.AreEqual(true, tempodb.Secure); Assert.AreEqual("v1", tempodb.Version); Assert.IsNotNull(tempodb.Client); Assert.IsInstanceOfType(typeof(RestClient), tempodb.Client); } } }
Use the correct assertion for testing null
Use the correct assertion for testing null
C#
mit
tempodb/tempodb-net
4324cc9d01186a43493ab56bddd3d07d3e8e7c36
Storage/Azure/StorageAzureTests/BlobTests.cs
Storage/Azure/StorageAzureTests/BlobTests.cs
using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.IO; namespace StorageAzure.Tests { [TestClass()] public class BlobTests { public Boolean Exist(string fileName) { var container = new BlobContanier().Create(); var blob = container.GetBlockBlobReference(fileName); return blob.Exists(); } [TestMethod()] public void BlobPut() { var blob = new Blob(); var objeto = File.OpenRead(@"..\..\20160514_195832.jpg"); var fileName = Path.GetFileName(objeto.Name); blob.Put(objeto); objeto.Close(); Assert.IsTrue(Exist(fileName)); } [TestMethod()] public void BlobGet() { var blob = new Blob(); var fileName = "20160514_195832.jpg"; var fichero = blob.Get(fileName); Assert.IsNotNull(fichero); Assert.IsTrue(fichero.Length > 0); } [TestMethod()] public void BlobDelete() { var blob = new Blob(); var fileName = "20160514_195832.jpg"; blob.Delete(fileName); Assert.IsFalse(Exist(fileName)); } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.IO; namespace StorageAzure.Tests { [TestClass()] public class BlobTests { public Boolean Exist(string fileName) { var container = new BlobContanier().Create(); var blob = container.GetBlockBlobReference(fileName); return blob.Exists(); } [TestMethod()] public void BlobPut() { var blob = new Blob(); var objeto = File.OpenRead(@"..\..\20160514_195832.jpg"); var fileName = Path.GetFileName(objeto.Name); blob.Put(objeto); objeto.Close(); Assert.IsTrue(Exist(fileName)); } [TestMethod()] public void BlobPut_Fichero_de_55_Mb() { var blob = new Blob(); var objeto = File.OpenRead(@"..\..\20160512_194750.mp4"); var fileName = Path.GetFileName(objeto.Name); blob.Put(objeto); objeto.Close(); Assert.IsTrue(Exist(fileName)); } [TestMethod()] public void BlobGet() { var blob = new Blob(); var fileName = "20160514_195832.jpg"; var fichero = blob.Get(fileName); Assert.IsNotNull(fichero); Assert.IsTrue(fichero.Length > 0); } [TestMethod()] public void BlobDelete() { var blob = new Blob(); var fileName = "20160514_195832.jpg"; blob.Delete(fileName); Assert.IsFalse(Exist(fileName)); } } }
Test para comprobar qeu soporta ficheros de 55Mb.
Test para comprobar qeu soporta ficheros de 55Mb. Related Work Items: #44
C#
mit
JuanQuijanoAbad/UniversalSync,JuanQuijanoAbad/UniversalSync
908bf539b320acfa63b7c1b706617d5e3f3e099f
SkypeSharp/IUser.cs
SkypeSharp/IUser.cs
namespace SkypeSharp { public enum UserStatus { OnlineStatus, BuddyStatus, ReceivedAuthRequest } public interface IUser : ISkypeObject { string FullName { get; } string Language { get; } string Country { get; } string City { get; } void Authorize(); } }
namespace SkypeSharp { public enum UserStatus { OnlineStatus, BuddyStatus, ReceivedAuthRequest, IsAuthorized, IsBlocked, Timezone, NROF_AUTHED_BUDDIES } public interface IUser : ISkypeObject { string FullName { get; } string Language { get; } string Country { get; } string City { get; } void Authorize(); } }
Add some missing user statuses
Add some missing user statuses
C#
mit
Goz3rr/SkypeSharp
f7b519fe2c78254dd38d15ecc23025c2e9965e6e
bootstrapping/DefaultBuild.cs
bootstrapping/DefaultBuild.cs
using System; using System.Linq; using Nuke.Common; using Nuke.Common.Tools.MSBuild; using Nuke.Core; using static Nuke.Common.FileSystem.FileSystemTasks; using static Nuke.Common.Tools.MSBuild.MSBuildTasks; using static Nuke.Common.Tools.NuGet.NuGetTasks; using static Nuke.Core.EnvironmentInfo; // ReSharper disable CheckNamespace class DefaultBuild : GitHubBuild { public static void Main () => Execute<DefaultBuild> (x => x.Compile); Target Restore => _ => _ .Executes (() => { if (MSBuildVersion == Nuke.Common.Tools.MSBuild.MSBuildVersion.VS2017) MSBuild (s => DefaultSettings.MSBuildRestore); else NuGetRestore (SolutionFile); }); Target Compile => _ => _ .DependsOn (Restore) .Executes (() => MSBuild (s => DefaultSettings.MSBuildCompile .SetMSBuildVersion (MSBuildVersion))); MSBuildVersion? MSBuildVersion => !IsUnix ? GlobFiles (SolutionDirectory, "*.xproj").Any () ? Nuke.Common.Tools.MSBuild.MSBuildVersion.VS2015 : Nuke.Common.Tools.MSBuild.MSBuildVersion.VS2017 : default (MSBuildVersion); }
using System; using System.Linq; using Nuke.Common; using Nuke.Common.Tools.MSBuild; using Nuke.Core; using static Nuke.Common.FileSystem.FileSystemTasks; using static Nuke.Common.Tools.MSBuild.MSBuildTasks; using static Nuke.Common.Tools.NuGet.NuGetTasks; using static Nuke.Core.EnvironmentInfo; class DefaultBuild : GitHubBuild { public static void Main () => Execute<DefaultBuild>(x => x.Compile); Target Restore => _ => _ .Executes(() => { NuGetRestore(SolutionFile); if (MSBuildVersion == Nuke.Common.Tools.MSBuild.MSBuildVersion.VS2017) MSBuild(s => DefaultSettings.MSBuildRestore); }); Target Compile => _ => _ .DependsOn(Restore) .Executes(() => MSBuild(s => DefaultSettings.MSBuildCompile .SetMSBuildVersion(MSBuildVersion))); MSBuildVersion? MSBuildVersion => !IsUnix ? GlobFiles(SolutionDirectory, "*.xproj").Any() ? Nuke.Common.Tools.MSBuild.MSBuildVersion.VS2015 : Nuke.Common.Tools.MSBuild.MSBuildVersion.VS2017 : default(MSBuildVersion); }
Change NuGetRestore to be executed unconditionally.
Change NuGetRestore to be executed unconditionally.
C#
mit
nuke-build/nuke,nuke-build/nuke,nuke-build/nuke,nuke-build/nuke
ea0146dc85eae657cd72e3aae5b42baa9e0df16a
src/Cake.Core/Scripting/Processors/UsingStatementProcessor.cs
src/Cake.Core/Scripting/Processors/UsingStatementProcessor.cs
using System; using Cake.Core.IO; namespace Cake.Core.Scripting.Processors { /// <summary> /// Processor for using statements. /// </summary> public sealed class UsingStatementProcessor : LineProcessor { /// <summary> /// Initializes a new instance of the <see cref="UsingStatementProcessor"/> class. /// </summary> /// <param name="environment">The environment.</param> public UsingStatementProcessor(ICakeEnvironment environment) : base(environment) { } /// <summary> /// Processes the specified line. /// </summary> /// <param name="processor">The script processor.</param> /// <param name="context">The script processor context.</param> /// <param name="currentScriptPath">The current script path.</param> /// <param name="line">The line to process.</param> /// <returns> /// <c>true</c> if the processor handled the line; otherwise <c>false</c>. /// </returns> public override bool Process(IScriptProcessor processor, ScriptProcessorContext context, FilePath currentScriptPath, string line) { if (context == null) { throw new ArgumentNullException("context"); } var tokens = Split(line); if (tokens.Length <= 0) { return false; } if (!tokens[0].Equals("using", StringComparison.Ordinal)) { return false; } var @namespace = tokens[1].TrimEnd(';'); context.AddNamespace(@namespace); return true; } } }
using System; using Cake.Core.IO; namespace Cake.Core.Scripting.Processors { /// <summary> /// Processor for using statements. /// </summary> public sealed class UsingStatementProcessor : LineProcessor { /// <summary> /// Initializes a new instance of the <see cref="UsingStatementProcessor"/> class. /// </summary> /// <param name="environment">The environment.</param> public UsingStatementProcessor(ICakeEnvironment environment) : base(environment) { } /// <summary> /// Processes the specified line. /// </summary> /// <param name="processor">The script processor.</param> /// <param name="context">The script processor context.</param> /// <param name="currentScriptPath">The current script path.</param> /// <param name="line">The line to process.</param> /// <returns> /// <c>true</c> if the processor handled the line; otherwise <c>false</c>. /// </returns> public override bool Process(IScriptProcessor processor, ScriptProcessorContext context, FilePath currentScriptPath, string line) { if (context == null) { throw new ArgumentNullException("context"); } var tokens = Split(line); if (tokens.Length <= 1) { return false; } if (!tokens[0].Equals("using", StringComparison.Ordinal)) { return false; } var @namespace = tokens[1].TrimEnd(';'); if (@namespace.StartsWith("(")) { return false; } context.AddNamespace(@namespace); return true; } } }
Fix for using (IDisposable) statement
Fix for using (IDisposable) statement
C#
mit
phenixdotnet/cake,mholo65/cake,UnbelievablyRitchie/cake,gep13/cake,vlesierse/cake,yvschmid/cake,cake-build/cake,DixonD-git/cake,adamhathcock/cake,danielrozo/cake,ferventcoder/cake,daveaglick/cake,marcosnz/cake,UnbelievablyRitchie/cake,DavidDeSloovere/cake,devlead/cake,wallymathieu/cake,Invenietis/cake,daveaglick/cake,cake-build/cake,mholo65/cake,Invenietis/cake,gep13/cake,michael-wolfenden/cake,SharpeRAD/Cake,andycmaj/cake,RichiCoder1/cake,ferventcoder/cake,RehanSaeed/cake,SharpeRAD/Cake,danielrozo/cake,vlesierse/cake,thomaslevesque/cake,adamhathcock/cake,jrnail23/cake,jrnail23/cake,andycmaj/cake,michael-wolfenden/cake,Sam13/cake,RichiCoder1/cake,robgha01/cake,Sam13/cake,yvschmid/cake,Julien-Mialon/cake,phrusher/cake,thomaslevesque/cake,RehanSaeed/cake,robgha01/cake,Julien-Mialon/cake,patriksvensson/cake,marcosnz/cake,patriksvensson/cake,phrusher/cake,devlead/cake,phenixdotnet/cake
5ee7966318f426377361eadff32f2ac7d69f00b9
PacManGameTests/GameTimerTest.cs
PacManGameTests/GameTimerTest.cs
using System; using System.Threading; using FluentAssertions; using Moq; using NUnit.Framework; using PacManGame; namespace PacManGameTests { [TestFixture] public class GameTimerTest { [Test] public void GivenABoard3x4WithPacmanLookingUpAt1x2_When500msPass_ThenPacmanIsAt1x1() { //Arrange Board b = new Board(3, 4); ITimer gameTimer = new GameTimer(500); GameController gameController = new GameController(b, gameTimer); gameTimer.Start(); //Act Thread.Sleep(TimeSpan.FromMilliseconds(600)); // Assert b.PacMan.Position.Should().Be(new Position(1, 1)); } [Test] public void GivenABoardTickableAndAGameController_WhenTimerElapsed_ThenATickIsCalled() { //Arrange ITickable boardMock = Mock.Of<ITickable>(); FakeTimer timer = new FakeTimer(); GameController gameController = new GameController(boardMock, timer); //Act timer.OnElapsed(); //Assert Mock.Get(boardMock).Verify(b => b.Tick(), Times.Once); } } public class FakeTimer : ITimer { public event EventHandler Elapsed; public void Start() { throw new NotImplementedException(); } public void OnElapsed() { if (Elapsed != null) { Elapsed(this, new EventArgs()); } } } }
using System; using System.Threading; using FluentAssertions; using Moq; using NUnit.Framework; using PacManGame; namespace PacManGameTests { [TestFixture] public class GameTimerTest { [Test] public void GivenABoard3x4WithPacmanLookingUpAt1x2_When500msPass_ThenPacmanIsAt1x1() { //Arrange Board b = new Board(3, 4); ITimer gameTimer = new GameTimer(500); GameController gameController = new GameController(b, gameTimer); gameTimer.Start(); //Act Thread.Sleep(TimeSpan.FromMilliseconds(600)); // Assert b.PacMan.Position.Should().Be(new Position(1, 1)); } [Test] public void GivenABoardTickableAndAGameController_WhenTimerElapsed_ThenATickIsCalled() { //Arrange ITickable boardMock = Mock.Of<ITickable>(); ITimer timerMock = Mock.Of<ITimer>(); GameController gameController = new GameController(boardMock, timerMock); //Act Mock.Get(timerMock).Raise(t => t.Elapsed += null, new EventArgs()); //Assert Mock.Get(boardMock).Verify(b => b.Tick(), Times.Once); } } }
Use a stub of ITimer instead of an actual implementation
Use a stub of ITimer instead of an actual implementation
C#
mit
dotNetNocturne/Pacman_Episode1_GreenTeam
71ae0a66a104694499f728a502570feff1ee7f45
DebuggerFrontend/Program.cs
DebuggerFrontend/Program.cs
using CommandLineParser.Exceptions; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LSTools.DebuggerFrontend { class Program { static void Main(string[] args) { var logFile = new FileStream(@"C:\Dev\DOS\LS\LsLib\DebuggerFrontend\bin\Debug\DAP.log", FileMode.Create); var dap = new DAPStream(); dap.EnableLogging(logFile); var dapHandler = new DAPMessageHandler(dap); dapHandler.EnableLogging(logFile); try { dap.RunLoop(); } catch (Exception e) { using (var writer = new StreamWriter(logFile, Encoding.UTF8, 0x1000, true)) { writer.Write(e.ToString()); Console.WriteLine(e.ToString()); } } } } }
using CommandLineParser.Exceptions; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LSTools.DebuggerFrontend { class Program { static void Main(string[] args) { var currentPath = AppDomain.CurrentDomain.BaseDirectory; var logFile = new FileStream(currentPath + "\\DAP.log", FileMode.Create); var dap = new DAPStream(); dap.EnableLogging(logFile); var dapHandler = new DAPMessageHandler(dap); dapHandler.EnableLogging(logFile); try { dap.RunLoop(); } catch (Exception e) { using (var writer = new StreamWriter(logFile, Encoding.UTF8, 0x1000, true)) { writer.Write(e.ToString()); Console.WriteLine(e.ToString()); } } } } }
Fix hardcoded DAP log path
Fix hardcoded DAP log path
C#
mit
Norbyte/lslib,Norbyte/lslib,Norbyte/lslib
083a0cd14b980e5c79702bfc0cb14e75d96b222b
Source/Eto.Platform.Gtk/Forms/PixelLayoutHandler.cs
Source/Eto.Platform.Gtk/Forms/PixelLayoutHandler.cs
using System; using Eto.Forms; using Eto.Drawing; namespace Eto.Platform.GtkSharp { public class PixelLayoutHandler : GtkLayout<Gtk.Fixed, PixelLayout>, IPixelLayout { public PixelLayoutHandler() { Control = new Gtk.Fixed(); } public void Add(Control child, int x, int y) { IGtkControl ctl = ((IGtkControl)child.Handler); var gtkcontrol = (Gtk.Widget)child.ControlObject; Control.Put(gtkcontrol, x, y); ctl.Location = new Point(x, y); gtkcontrol.ShowAll(); } public void Move(Control child, int x, int y) { IGtkControl ctl = ((IGtkControl)child.Handler); if (ctl.Location.X != x || ctl.Location.Y != y) { Control.Move (child.GetContainerWidget (), x, y); ctl.Location = new Point(x, y); } } public void Remove(Control child) { Control.Remove (child.GetContainerWidget ()); } } }
using System; using Eto.Forms; using Eto.Drawing; namespace Eto.Platform.GtkSharp { public class PixelLayoutHandler : GtkLayout<Gtk.Fixed, PixelLayout>, IPixelLayout { public PixelLayoutHandler () { Control = new Gtk.Fixed (); } public void Add (Control child, int x, int y) { var ctl = ((IGtkControl)child.Handler); var gtkcontrol = child.GetContainerWidget (); Control.Put (gtkcontrol, x, y); ctl.Location = new Point (x, y); if (this.Control.Visible) gtkcontrol.ShowAll (); } public void Move (Control child, int x, int y) { var ctl = ((IGtkControl)child.Handler); if (ctl.Location.X != x || ctl.Location.Y != y) { Control.Move (child.GetContainerWidget (), x, y); ctl.Location = new Point (x, y); } } public void Remove (Control child) { Control.Remove (child.GetContainerWidget ()); } } }
Fix adding controls to PixelLayout with a different container object
Gtk: Fix adding controls to PixelLayout with a different container object
C#
bsd-3-clause
l8s/Eto,bbqchickenrobot/Eto-1,PowerOfCode/Eto,PowerOfCode/Eto,bbqchickenrobot/Eto-1,l8s/Eto,bbqchickenrobot/Eto-1,PowerOfCode/Eto,l8s/Eto