commit
stringlengths
40
40
subject
stringlengths
4
1.73k
repos
stringlengths
5
127k
old_file
stringlengths
2
751
new_file
stringlengths
2
751
new_contents
stringlengths
1
8.98k
old_contents
stringlengths
0
6.59k
license
stringclasses
13 values
lang
stringclasses
23 values
5c2be27ae32abe5ed174d84ab4cb4c33febb3f82
Remove unneeded usings
andrew-polk/BloomDesktop,andrew-polk/BloomDesktop,JohnThomson/BloomDesktop,gmartin7/myBloomFork,BloomBooks/BloomDesktop,gmartin7/myBloomFork,JohnThomson/BloomDesktop,JohnThomson/BloomDesktop,JohnThomson/BloomDesktop,gmartin7/myBloomFork,andrew-polk/BloomDesktop,andrew-polk/BloomDesktop,StephenMcConnel/BloomDesktop,StephenMcConnel/BloomDesktop,StephenMcConnel/BloomDesktop,StephenMcConnel/BloomDesktop,StephenMcConnel/BloomDesktop,BloomBooks/BloomDesktop,StephenMcConnel/BloomDesktop,BloomBooks/BloomDesktop,andrew-polk/BloomDesktop,gmartin7/myBloomFork,gmartin7/myBloomFork,JohnThomson/BloomDesktop,andrew-polk/BloomDesktop,gmartin7/myBloomFork,BloomBooks/BloomDesktop,BloomBooks/BloomDesktop,BloomBooks/BloomDesktop
src/BloomExe/CollectionTab/BloomLibraryLinkVerification.cs
src/BloomExe/CollectionTab/BloomLibraryLinkVerification.cs
using System; using System.Drawing; using System.Windows.Forms; using L10NSharp; namespace Bloom.CollectionTab { public partial class BloomLibraryLinkVerification : Form { public BloomLibraryLinkVerification() { InitializeComponent(); } private void Initialize() { // Set localized caption Text = LocalizationManager.GetString("CollectionTab.bloomLibraryLinkVerificationCaption", "Source Collection", "get this clicking on BloomLibrary.org link in source collection"); // Set localized message var msg = "Note: The Bloom Library contains shell books." + Environment.NewLine + Environment.NewLine; msg += "Your current collection is a \"source collection\", meaning it is for making shell books," + Environment.NewLine; msg += "not for translating them into the vernacular." + Environment.NewLine + Environment.NewLine; msg += "When you've made a shell, you can then upload it to the Bloom Library from the Publish tab."; _message.Text = LocalizationManager.GetString("CollectionTab.bloomLibraryLinkVerification", msg, "get this clicking on BloomLibrary.org link in source collection"); // Set information icon // Review: Could use a larger image here... _infoIcon.Image = SystemIcons.Information.ToBitmap(); } internal DialogResult GetVerification(IWin32Window owner) { Initialize(); return ShowDialog(owner); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Windows.Forms.VisualStyles; using L10NSharp; namespace Bloom.CollectionTab { public partial class BloomLibraryLinkVerification : Form { public BloomLibraryLinkVerification() { InitializeComponent(); } private void Initialize() { // Set localized caption Text = LocalizationManager.GetString("CollectionTab.bloomLibraryLinkVerificationCaption", "Source Collection", "get this clicking on BloomLibrary.org link in source collection"); // Set localized message var msg = "Note: The Bloom Library contains shell books." + Environment.NewLine + Environment.NewLine; msg += "Your current collection is a \"source collection\", meaning it is for making shell books," + Environment.NewLine; msg += "not for translating them into the vernacular." + Environment.NewLine + Environment.NewLine; msg += "When you've made a shell, you can then upload it to the Bloom Library from the Publish tab."; _message.Text = LocalizationManager.GetString("CollectionTab.bloomLibraryLinkVerification", msg, "get this clicking on BloomLibrary.org link in source collection"); // Set information icon // Review: Could use a larger image here... _infoIcon.Image = SystemIcons.Information.ToBitmap(); } internal DialogResult GetVerification(IWin32Window owner) { Initialize(); return ShowDialog(owner); } } }
mit
C#
82fda81707a7c746185b294a1f73b9f7e1f4ace1
Update the formatting analyzer to IDE0054
jasonmalinowski/roslyn,AmadeusW/roslyn,DustinCampbell/roslyn,heejaechang/roslyn,reaction1989/roslyn,AlekseyTs/roslyn,nguerrera/roslyn,physhi/roslyn,jmarolf/roslyn,agocke/roslyn,jasonmalinowski/roslyn,DustinCampbell/roslyn,abock/roslyn,xasx/roslyn,mavasani/roslyn,jasonmalinowski/roslyn,abock/roslyn,physhi/roslyn,CyrusNajmabadi/roslyn,VSadov/roslyn,eriawan/roslyn,diryboy/roslyn,eriawan/roslyn,abock/roslyn,panopticoncentral/roslyn,weltkante/roslyn,gafter/roslyn,sharwell/roslyn,davkean/roslyn,panopticoncentral/roslyn,davkean/roslyn,tmat/roslyn,wvdd007/roslyn,eriawan/roslyn,AmadeusW/roslyn,mavasani/roslyn,jcouv/roslyn,xasx/roslyn,mgoertz-msft/roslyn,AlekseyTs/roslyn,jmarolf/roslyn,davkean/roslyn,sharwell/roslyn,panopticoncentral/roslyn,KevinRansom/roslyn,jcouv/roslyn,CyrusNajmabadi/roslyn,MichalStrehovsky/roslyn,mgoertz-msft/roslyn,agocke/roslyn,wvdd007/roslyn,shyamnamboodiripad/roslyn,mgoertz-msft/roslyn,agocke/roslyn,ErikSchierboom/roslyn,heejaechang/roslyn,ErikSchierboom/roslyn,gafter/roslyn,dotnet/roslyn,mavasani/roslyn,sharwell/roslyn,jcouv/roslyn,aelij/roslyn,ErikSchierboom/roslyn,KirillOsenkov/roslyn,AmadeusW/roslyn,stephentoub/roslyn,CyrusNajmabadi/roslyn,nguerrera/roslyn,swaroop-sridhar/roslyn,MichalStrehovsky/roslyn,KirillOsenkov/roslyn,genlu/roslyn,bartdesmet/roslyn,dotnet/roslyn,KirillOsenkov/roslyn,gafter/roslyn,tannergooding/roslyn,tannergooding/roslyn,MichalStrehovsky/roslyn,weltkante/roslyn,KevinRansom/roslyn,swaroop-sridhar/roslyn,tannergooding/roslyn,shyamnamboodiripad/roslyn,DustinCampbell/roslyn,jmarolf/roslyn,VSadov/roslyn,reaction1989/roslyn,AlekseyTs/roslyn,wvdd007/roslyn,tmat/roslyn,genlu/roslyn,stephentoub/roslyn,genlu/roslyn,swaroop-sridhar/roslyn,dotnet/roslyn,weltkante/roslyn,heejaechang/roslyn,nguerrera/roslyn,xasx/roslyn,bartdesmet/roslyn,aelij/roslyn,stephentoub/roslyn,diryboy/roslyn,KevinRansom/roslyn,VSadov/roslyn,aelij/roslyn,brettfo/roslyn,physhi/roslyn,shyamnamboodiripad/roslyn,brettfo/roslyn,reaction1989/roslyn,brettfo/roslyn,bartdesmet/roslyn,diryboy/roslyn,tmat/roslyn
src/CodeStyle/Core/CodeFixes/AbstractFormattingAnalyzer.cs
src/CodeStyle/Core/CodeFixes/AbstractFormattingAnalyzer.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.IO; using System.Reflection; using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.CodeAnalysis.CodeStyle { internal abstract class AbstractFormattingAnalyzer : AbstractCodeStyleDiagnosticAnalyzer { internal const string FormattingDiagnosticId = "IDE0054"; static AbstractFormattingAnalyzer() { AppDomain.CurrentDomain.AssemblyResolve += HandleAssemblyResolve; } protected AbstractFormattingAnalyzer() : base( FormattingDiagnosticId, new LocalizableResourceString(nameof(CodeStyleResources.Formatting_analyzer_title), CodeStyleResources.ResourceManager, typeof(CodeStyleResources)), new LocalizableResourceString(nameof(CodeStyleResources.Formatting_analyzer_message), CodeStyleResources.ResourceManager, typeof(CodeStyleResources))) { } protected abstract Type GetAnalyzerImplType(); protected override void InitializeWorker(AnalysisContext context) { var analyzer = (AbstractFormattingAnalyzerImpl)Activator.CreateInstance(GetAnalyzerImplType(), Descriptor); analyzer.InitializeWorker(context); } private static Assembly HandleAssemblyResolve(object sender, ResolveEventArgs args) { switch (new AssemblyName(args.Name).Name) { case "Microsoft.CodeAnalysis.Workspaces": case "Microsoft.CodeAnalysis.CSharp.Workspaces": case "Microsoft.VisualStudio.CodingConventions": var result = Assembly.LoadFrom(Path.Combine(Path.GetDirectoryName(typeof(AbstractFormattingAnalyzer).Assembly.Location), "..\\workspaces", new AssemblyName(args.Name).Name + ".dll")); return result; default: 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; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.CodeAnalysis.CodeStyle { internal abstract class AbstractFormattingAnalyzer : AbstractCodeStyleDiagnosticAnalyzer { internal const string FormattingDiagnosticId = "IDE0051"; static AbstractFormattingAnalyzer() { AppDomain.CurrentDomain.AssemblyResolve += HandleAssemblyResolve; } protected AbstractFormattingAnalyzer() : base( FormattingDiagnosticId, new LocalizableResourceString(nameof(CodeStyleResources.Formatting_analyzer_title), CodeStyleResources.ResourceManager, typeof(CodeStyleResources)), new LocalizableResourceString(nameof(CodeStyleResources.Formatting_analyzer_message), CodeStyleResources.ResourceManager, typeof(CodeStyleResources))) { } protected abstract Type GetAnalyzerImplType(); protected override void InitializeWorker(AnalysisContext context) { var analyzer = (AbstractFormattingAnalyzerImpl)Activator.CreateInstance(GetAnalyzerImplType(), Descriptor); analyzer.InitializeWorker(context); } private static Assembly HandleAssemblyResolve(object sender, ResolveEventArgs args) { switch (new AssemblyName(args.Name).Name) { case "Microsoft.CodeAnalysis.Workspaces": case "Microsoft.CodeAnalysis.CSharp.Workspaces": case "Microsoft.VisualStudio.CodingConventions": var result = Assembly.LoadFrom(Path.Combine(Path.GetDirectoryName(typeof(AbstractFormattingAnalyzer).Assembly.Location), "..\\workspaces", new AssemblyName(args.Name).Name + ".dll")); return result; default: return null; } } } }
mit
C#
950d58f6de8d68fb5c9503e191cc1217e22126c4
Improve FDO->Mongo unit test even further
sillsdev/LfMerge,sillsdev/LfMerge,ermshiperete/LfMerge,sillsdev/LfMerge,ermshiperete/LfMerge,ermshiperete/LfMerge
src/LfMerge.Tests/Actions/UpdateFdoFromMongoActionTests.cs
src/LfMerge.Tests/Actions/UpdateFdoFromMongoActionTests.cs
// Copyright (c) 2016 SIL International // This software is licensed under the MIT license (http://opensource.org/licenses/MIT) using Autofac; using LfMerge.Actions; using LfMerge.LanguageForge.Model; using LfMerge.MongoConnector; using LfMerge.Tests; using MongoDB.Bson; using MongoDB.Driver; using Moq; using Newtonsoft.Json; using NUnit.Framework; using SIL.CoreImpl; using SIL.FieldWorks.Common.COMInterfaces; using SIL.FieldWorks.FDO; using System; namespace LfMerge.Tests.Actions { public class UpdateFdoFromMongoActionTests { public const string testProjectCode = "TestLangProj"; private TestEnvironment _env; private MongoConnectionDouble _conn; private MongoProjectRecordFactory _recordFactory; private UpdateFdoFromMongoDbAction sut; [SetUp] public void Setup() { //_env = new TestEnvironment(); _env = new TestEnvironment(testProjectCode: testProjectCode); _conn = MainClass.Container.Resolve<IMongoConnection>() as MongoConnectionDouble; if (_conn == null) throw new AssertionException("Fdo->Mongo tests need a mock MongoConnection in order to work."); _recordFactory = MainClass.Container.Resolve<MongoProjectRecordFactory>() as MongoProjectRecordFactoryDouble; if (_recordFactory == null) throw new AssertionException("Fdo->Mongo tests need a mock MongoProjectRecordFactory in order to work."); // TODO: If creating our own Mocks would be better than getting them from Autofac, do that instead. sut = new UpdateFdoFromMongoDbAction( _env.Settings, _env.Logger, _conn, _recordFactory ); } [TearDown] public void TearDown() { _env.Dispose(); } // TODO: Need to switch this test over to a Mongo double that keeps data, so it can handle grammar info [Test] public void Action_Should_UpdateDefinitions() { // Setup var lfProj = LanguageForgeProject.Create(_env.Settings, testProjectCode); var data = new SampleData(); string newDefinition = "New definition for this unit test"; data.bsonTestData["senses"][0]["definition"]["en"]["value"] = newDefinition; _conn.AddToMockData<LfLexEntry>(MagicStrings.LfCollectionNameForLexicon, data.bsonTestData); // Exercise sut.Run(lfProj); // Verify FdoCache cache = lfProj.FieldWorksProject.Cache; string expectedGuidStr = data.bsonTestData["guid"].AsString; string expectedShortName = data.bsonTestData["citationForm"].AsBsonDocument.GetElement(0).Value["value"].AsString; Guid expectedGuid = Guid.Parse(expectedGuidStr); var entry = cache.ServiceLocator.GetObject(expectedGuid) as ILexEntry; Assert.IsNotNull(entry); Assert.That(entry.Guid, Is.EqualTo(expectedGuid)); Assert.That(entry.ShortName, Is.EqualTo(expectedShortName)); Assert.That(entry.SensesOS[0].DefinitionOrGloss.BestAnalysisAlternative.Text, Is.EqualTo(newDefinition)); } } }
// Copyright (c) 2016 SIL International // This software is licensed under the MIT license (http://opensource.org/licenses/MIT) using Autofac; using LfMerge.Actions; using LfMerge.LanguageForge.Model; using LfMerge.MongoConnector; using LfMerge.Tests; using MongoDB.Bson; using MongoDB.Driver; using Moq; using Newtonsoft.Json; using NUnit.Framework; using SIL.CoreImpl; using SIL.FieldWorks.Common.COMInterfaces; using SIL.FieldWorks.FDO; using System; namespace LfMerge.Tests.Actions { public class UpdateFdoFromMongoActionTests { public const string testProjectCode = "TestLangProj"; private TestEnvironment _env; private MongoConnectionDouble _conn; private MongoProjectRecordFactory _recordFactory; private UpdateFdoFromMongoDbAction sut; [SetUp] public void Setup() { //_env = new TestEnvironment(); _env = new TestEnvironment(testProjectCode: testProjectCode); _conn = MainClass.Container.Resolve<IMongoConnection>() as MongoConnectionDouble; if (_conn == null) throw new AssertionException("Fdo->Mongo tests need a mock MongoConnection in order to work."); _recordFactory = MainClass.Container.Resolve<MongoProjectRecordFactory>() as MongoProjectRecordFactoryDouble; if (_recordFactory == null) throw new AssertionException("Fdo->Mongo tests need a mock MongoProjectRecordFactory in order to work."); // TODO: If creating our own Mocks would be better than getting them from Autofac, do that instead. sut = new UpdateFdoFromMongoDbAction( _env.Settings, _env.Logger, _conn, _recordFactory ); } [TearDown] public void TearDown() { _env.Dispose(); } // TODO: Need to switch this test over to a Mongo double that keeps data, so it can handle grammar info [Test] public void Action_Should_UpdateDefinitions() { // Setup var lfProj = LanguageForgeProject.Create(_env.Settings, testProjectCode); var data = new SampleData(); string newDefinition = "New definition for this unit test"; data.bsonTestData["senses"][0]["definition"]["en"]["value"] = newDefinition; _conn.AddToMockData<LfLexEntry>(MagicStrings.LfCollectionNameForLexicon, data.bsonTestData); // Exercise sut.Run(lfProj); // Verify FdoCache cache = lfProj.FieldWorksProject.Cache; string expectedGuidStr = data.bsonTestData["guid"].AsString; string expectedShortName = data.bsonTestData["citationForm"]["qaa-x-kal"]["value"].AsString; Guid expectedGuid = Guid.Parse(expectedGuidStr); var entry = cache.ServiceLocator.GetObject(expectedGuid) as ILexEntry; Assert.IsNotNull(entry); Assert.That(entry.Guid, Is.EqualTo(expectedGuid)); Assert.That(entry.ShortName, Is.EqualTo(expectedShortName)); Assert.That(entry.SensesOS[0].DefinitionOrGloss.BestAnalysisAlternative.Text, Is.EqualTo(newDefinition)); } } }
mit
C#
fb1c232eb576a4923273d318a30d9742cc03fabf
Apply date formatting
simonray/ContosoUniversity.vNext,simonray/ContosoUniversity.vNext
src/ContosoUniversity.Website/ViewModels/EnrollmentDateGroup.cs
src/ContosoUniversity.Website/ViewModels/EnrollmentDateGroup.cs
using System; using System.ComponentModel.DataAnnotations; namespace ContosoUniversity.ViewModels { public class EnrollmentDateGroup { [DataType(DataType.Date)] [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)] public DateTime? EnrollmentDate { get; set; } public int StudentCount { get; set; } } }
using System; using System.ComponentModel.DataAnnotations; namespace ContosoUniversity.ViewModels { public class EnrollmentDateGroup { [DataType(DataType.Date)] public DateTime? EnrollmentDate { get; set; } public int StudentCount { get; set; } } }
mit
C#
4f638ad744dd0cd58d8e26fbb7f3bc1f06e089aa
Fix correct dialog
fredatgithub/Matrix
TheMatrixHasYou/FormMain.cs
TheMatrixHasYou/FormMain.cs
using System; using System.Drawing; using System.Windows.Forms; namespace TheMatrixHasYou { public partial class FormMain : Form { public FormMain() { InitializeComponent(); } private readonly string[] _texte = {"Wake up Neo....", "The Matrix has you....", "Follow the white rabbit....", "Knock knock .." }; private int _numeroChaine; private int _nombreDeChaineTotal = 0; private int _curseurChaine; private void FormMain_Load(object sender, EventArgs e) { labelMatrix.ForeColor = Color.Green; labelMatrix.Size = new Size(new Point(14)); labelMatrix.Text = string.Empty; _nombreDeChaineTotal = _texte.Length; timer1.Interval = 200; } private void timer1_Tick(object sender, EventArgs e) { labelMatrix.Text += _texte[_numeroChaine].Substring(_curseurChaine, 1); if (_curseurChaine >= _texte[_numeroChaine].Length - 1) { labelMatrix.Text = string.Empty; if (_numeroChaine + 1 >= _texte.Length) { _numeroChaine = 0; _curseurChaine = 0; } else { _numeroChaine++; _curseurChaine = 0; } } else { _curseurChaine++; } } } }
using System; using System.Drawing; using System.Windows.Forms; namespace TheMatrixHasYou { public partial class FormMain : Form { public FormMain() { InitializeComponent(); } private readonly string[] _texte = {"Knock knock Neo..","Wake up Neo....", "The Matrix has you....", "Follow the white rabbit...." }; private int _numeroChaine; private int _nombreDeChaineTotal = 0; private int _curseurChaine; private void FormMain_Load(object sender, EventArgs e) { labelMatrix.ForeColor = Color.Green; labelMatrix.Size = new Size(new Point(14)); labelMatrix.Text = string.Empty; _nombreDeChaineTotal = _texte.Length; timer1.Interval = 200; } private void timer1_Tick(object sender, EventArgs e) { labelMatrix.Text += _texte[_numeroChaine].Substring(_curseurChaine, 1); if (_curseurChaine >= _texte[_numeroChaine].Length - 1) { labelMatrix.Text = string.Empty; if (_numeroChaine + 1 >= _texte.Length) { _numeroChaine = 0; _curseurChaine = 0; } else { _numeroChaine++; _curseurChaine = 0; } } else { _curseurChaine++; } } } }
mit
C#
d14fda084b65bc276dcab8b6eb96a2a786a0ca2d
Fix newlines in the first run experience message
harshjain2/cli,dasMulli/cli,MichaelSimons/cli,johnbeisner/cli,naamunds/cli,ravimeda/cli,jonsequitur/cli,naamunds/cli,naamunds/cli,svick/cli,MichaelSimons/cli,EdwardBlair/cli,weshaggard/cli,naamunds/cli,blackdwarf/cli,nguerrera/cli,Faizan2304/cli,weshaggard/cli,blackdwarf/cli,livarcocc/cli-1,weshaggard/cli,weshaggard/cli,Faizan2304/cli,dasMulli/cli,Faizan2304/cli,johnbeisner/cli,jonsequitur/cli,AbhitejJohn/cli,blackdwarf/cli,harshjain2/cli,svick/cli,ravimeda/cli,harshjain2/cli,MichaelSimons/cli,johnbeisner/cli,AbhitejJohn/cli,ravimeda/cli,livarcocc/cli-1,mlorbetske/cli,EdwardBlair/cli,nguerrera/cli,AbhitejJohn/cli,jonsequitur/cli,naamunds/cli,mlorbetske/cli,jonsequitur/cli,livarcocc/cli-1,AbhitejJohn/cli,nguerrera/cli,EdwardBlair/cli,MichaelSimons/cli,blackdwarf/cli,mlorbetske/cli,svick/cli,nguerrera/cli,mlorbetske/cli,dasMulli/cli,weshaggard/cli,MichaelSimons/cli
src/Microsoft.DotNet.Configurer/DotnetFirstTimeUseConfigurer.cs
src/Microsoft.DotNet.Configurer/DotnetFirstTimeUseConfigurer.cs
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.IO; using Microsoft.DotNet.Cli.Utils; using Microsoft.Extensions.EnvironmentAbstractions; namespace Microsoft.DotNet.Configurer { public class DotnetFirstTimeUseConfigurer { private IEnvironmentProvider _environmentProvider; private INuGetCachePrimer _nugetCachePrimer; private INuGetCacheSentinel _nugetCacheSentinel; public DotnetFirstTimeUseConfigurer( INuGetCachePrimer nugetCachePrimer, INuGetCacheSentinel nugetCacheSentinel, IEnvironmentProvider environmentProvider) { _nugetCachePrimer = nugetCachePrimer; _nugetCacheSentinel = nugetCacheSentinel; _environmentProvider = environmentProvider; } public void Configure() { if(ShouldPrimeNugetCache()) { PrintFirstTimeUseNotice(); _nugetCachePrimer.PrimeCache(); } } private void PrintFirstTimeUseNotice() { const string firstTimeUseWelcomeMessage = @"Welcome to .NET Core! --------------------- Learn more about .NET Core @ https://aka.ms/dotnet-docs. Use dotnet --help to see available commands or go to https://aka.ms/dotnet-cli-docs. Telemetry -------------- The .NET Core tools collect usage data in order to improve your experience. The data is anonymous and does not include commandline arguments. The data is collected by Microsoft and shared with the community. You can opt out of telemetry by setting a DOTNET_CLI_TELEMETRY_OPTOUT environment variable to 1 using your favorite shell. You can read more about .NET Core tools telemetry @ https://aka.ms/dotnet-cli-telemetry. Configuring... ------------------- A command is running to initially populate your local package cache, to improve restore speed and enable offline access. This command will take up to a minute to complete and will only happen once."; Reporter.Output.WriteLine(); Reporter.Output.WriteLine(firstTimeUseWelcomeMessage); } private bool ShouldPrimeNugetCache() { var skipFirstTimeExperience = _environmentProvider.GetEnvironmentVariableAsBool("DOTNET_SKIP_FIRST_TIME_EXPERIENCE", false); return !skipFirstTimeExperience && !_nugetCacheSentinel.Exists() && !_nugetCacheSentinel.InProgressSentinelAlreadyExists(); } } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.IO; using Microsoft.DotNet.Cli.Utils; using Microsoft.Extensions.EnvironmentAbstractions; namespace Microsoft.DotNet.Configurer { public class DotnetFirstTimeUseConfigurer { private IEnvironmentProvider _environmentProvider; private INuGetCachePrimer _nugetCachePrimer; private INuGetCacheSentinel _nugetCacheSentinel; public DotnetFirstTimeUseConfigurer( INuGetCachePrimer nugetCachePrimer, INuGetCacheSentinel nugetCacheSentinel, IEnvironmentProvider environmentProvider) { _nugetCachePrimer = nugetCachePrimer; _nugetCacheSentinel = nugetCacheSentinel; _environmentProvider = environmentProvider; } public void Configure() { if(ShouldPrimeNugetCache()) { PrintFirstTimeUseNotice(); _nugetCachePrimer.PrimeCache(); } } private void PrintFirstTimeUseNotice() { const string firstTimeUseWelcomeMessage = @"Welcome to .NET Core! --------------------- Learn more about .NET Core @ https://aka.ms/dotnet-docs. Use dotnet --help to see available commands or go to https://aka.ms/dotnet-cli-docs. Telemetry -------------- The .NET Core tools collect usage data in order to improve your experience. The data is anonymous and does not include commandline arguments. The data is collected by Microsoft and shared with the community. You can opt out of telemetry by setting a DOTNET_CLI_TELEMETRY_OPTOUT environment variable to 1 using your favorite shell. You can read more about .NET Core tools telemetry @ https://aka.ms/dotnet-cli-telemetry. Configuring... ------------------- A command is running to initially populate your local package cache, to improve restore speed and enable offline access. This command will take up to a minute to complete and will only happen once."; Reporter.Output.WriteLine(); Reporter.Output.WriteLine(firstTimeUseWelcomeMessage); } private bool ShouldPrimeNugetCache() { var skipFirstTimeExperience = _environmentProvider.GetEnvironmentVariableAsBool("DOTNET_SKIP_FIRST_TIME_EXPERIENCE", false); return !skipFirstTimeExperience && !_nugetCacheSentinel.Exists() && !_nugetCacheSentinel.InProgressSentinelAlreadyExists(); } } }
mit
C#
dd17fb4f844e280907598162de914fb75bf8e8da
Refactor message passing method.
nealterrell/NetrunnerOBS
Prototype/NetrunnerCardImageSourceFactory.cs
Prototype/NetrunnerCardImageSourceFactory.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using CLROBS; using System.Windows; namespace NetrunnerOBS { /// <summary> /// Factory registered with the OBS API so OBS can create our source object /// when needed. /// </summary> public class NetrunnerCardImageSourceFactory : AbstractImageSourceFactory { // Kind of hacky: a singleton CardWindow connects to all sources. static CardWindow mConfiguration; static List<NetrunnerCardImageSource> mSources = new List<NetrunnerCardImageSource>(); public NetrunnerCardImageSourceFactory() { ClassName = "CardImageSourceClass"; DisplayName = "Netrunner Card"; } public override ImageSource Create(XElement data) { // Clear the file data, so the stream always starts with a blank card. data.SetString("file", ""); var source = new NetrunnerCardImageSource(data); mSources.Add(source); return source; } public override bool ShowConfiguration(XElement data) { try { if (mConfiguration == null) { mConfiguration = new CardWindow(data); mConfiguration.CardChanged += mConfiguration_CardChanged; } mConfiguration.Show(); } catch (Exception e) { MessageBox.Show(e.ToString()); } return true; } void mConfiguration_CardChanged(object sender, CardChangedEventArgs e) { UpdateSourceSettings(); } private static void UpdateSourceSettings() { foreach (var source in mSources) source.UpdateSettings(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using CLROBS; using System.Windows; namespace NetrunnerOBS { /// <summary> /// Factory registered with the OBS API so OBS can create our source object /// when needed. /// </summary> public class NetrunnerCardImageSourceFactory : AbstractImageSourceFactory { // Kind of hacky: a singleton CardWindow connects to all sources. static CardWindow mConfiguration; static List<NetrunnerCardImageSource> mSources = new List<NetrunnerCardImageSource>(); public NetrunnerCardImageSourceFactory() { ClassName = "CardImageSourceClass"; DisplayName = "Netrunner Card"; } public override ImageSource Create(XElement data) { // Clear the file data, so the stream always starts with a blank card. data.SetString("file", ""); var source = new NetrunnerCardImageSource(data); mSources.Add(source); return source; } public override bool ShowConfiguration(XElement data) { try { if (mConfiguration == null) { mConfiguration = new CardWindow(data); mConfiguration.CardChanged += mConfiguration_CardChanged; } mConfiguration.Show(); } catch (Exception e) { MessageBox.Show(e.ToString()); } return true; } void mConfiguration_CardChanged(object sender, CardChangedEventArgs e) { foreach (var source in mSources) source.UpdateSettings(); } } }
mit
C#
ed7ce31aba08686c87569c39d9657683824e6291
change service return value
RopeLEAP/rope,RopeLEAP/rope,RopeLEAP/rope
RopeWebApp2/Controllers/RopeApiController.cs
RopeWebApp2/Controllers/RopeApiController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using RopeTest; using RopeWebApp2.Services; using RopeWebApp2.Models; namespace RopeWebApp2.Controllers { public class RopeApiController : ApiController { public HttpResponseMessage GetTestResults() { TestModel resultRope = new TestModel(); //InsertService insertService = new InsertService(); //insertService.ReadFiles(); //insertService.PrependToLargeStructures(50, 1); TestService testService = new Services.TestService(); testService.ReadFiles(); resultRope = testService.FillLargeStructures(5); return Request.CreateResponse(HttpStatusCode.OK, resultRope); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using RopeTest; using RopeWebApp2.Services; using RopeWebApp2.Models; namespace RopeWebApp2.Controllers { public class RopeApiController : ApiController { public HttpResponseMessage GetTestResults() { TestModel resultRope = new TestModel(); //InsertService insertService = new InsertService(); //insertService.ReadFiles(); //insertService.PrependToLargeStructures(50, 1); TestService testService = new Services.TestService(); testService.ReadFiles(); resultRope = testService.FillLargeStructures(5); return Request.CreateResponse(HttpStatusCode.OK, testService); } } }
mit
C#
9561ce6223cf98a93a5832a486b0f6fe4e7059a6
Fix broken db connection
schlos/denver-schedules-api,schlos/denver-schedules-api,codeforamerica/denver-schedules-api,codeforamerica/denver-schedules-api
Schedules.API/Repositories/RepositoryBase.cs
Schedules.API/Repositories/RepositoryBase.cs
using System; using System.Configuration; using System.Data.Common; using Npgsql; namespace Schedules.API.Repositories { public class RepositoryBase: IDisposable { private const string providerKey = "GEOSPATIAL-PROVIDER-NAME"; private const string connectionKey = "GEOSPATIAL-CONNECTION-STRING"; public DbConnection connection; public RepositoryBase () { connection = GetConnection (); } private DbConnection GetConnection() {// Reference: http://stackoverflow.com/questions/1046042/asp-net-how-to-create-a-connection-from-a-web-config-connectionstring var providerName = System.Environment.GetEnvironmentVariable (providerKey); var connectionString = System.Environment.GetEnvironmentVariable (connectionKey); var factory = DbProviderFactories.GetFactory (providerName); if(factory == null) throw new Exception("Could not obtain factory for provider \""+providerName+"\""); connection = factory.CreateConnection(); if (connection == null) throw new Exception("Could not obtain connection from factory for " + providerName); connection.ConnectionString = connectionString; connection.Open (); return connection; } public void Dispose() { if (connection != null) connection.Dispose (); } } }
using System; using System.Configuration; using System.Data.Common; using Npgsql; namespace Schedules.API.Repositories { public class RepositoryBase: IDisposable { private const string connectionName = "geospatial"; public DbConnection connection; public RepositoryBase () { connection = GetConnection (); } private DbConnection GetConnection() {// Reference: http://stackoverflow.com/questions/1046042/asp-net-how-to-create-a-connection-from-a-web-config-connectionstring var connectionString = ConfigurationManager.ConnectionStrings[connectionName]; var factory = DbProviderFactories.GetFactory (connectionString.ProviderName); if(factory == null) throw new Exception("Could not obtain factory for provider \""+connectionString.ProviderName+"\""); DbConnection connection = factory.CreateConnection(); if (connection == null) throw new Exception("Could not obtain connection from factory for " + connectionString.ProviderName); connection.ConnectionString = connectionString.ConnectionString; return connection; } public void Dispose() { if (connection != null) connection.Dispose (); } } }
mit
C#
dc23e29d137a1c27b89c3953ba402c065cb88904
Fix Typo in Unix Lock/Unlock PAL
kyulee1/coreclr,alexperovich/coreclr,jamesqo/coreclr,sjsinju/coreclr,tijoytom/coreclr,ruben-ayrapetyan/coreclr,poizan42/coreclr,cydhaselton/coreclr,yeaicc/coreclr,cshung/coreclr,hseok-oh/coreclr,ragmani/coreclr,krk/coreclr,mskvortsov/coreclr,neurospeech/coreclr,botaberg/coreclr,botaberg/coreclr,krytarowski/coreclr,ragmani/coreclr,James-Ko/coreclr,qiudesong/coreclr,wateret/coreclr,JosephTremoulet/coreclr,neurospeech/coreclr,AlexGhiondea/coreclr,gkhanna79/coreclr,russellhadley/coreclr,mmitche/coreclr,wateret/coreclr,cydhaselton/coreclr,cshung/coreclr,poizan42/coreclr,russellhadley/coreclr,JonHanna/coreclr,yizhang82/coreclr,pgavlin/coreclr,mmitche/coreclr,parjong/coreclr,gkhanna79/coreclr,yizhang82/coreclr,mskvortsov/coreclr,sjsinju/coreclr,YongseopKim/coreclr,tijoytom/coreclr,mskvortsov/coreclr,jamesqo/coreclr,sagood/coreclr,hseok-oh/coreclr,tijoytom/coreclr,wtgodbe/coreclr,YongseopKim/coreclr,hseok-oh/coreclr,yeaicc/coreclr,rartemev/coreclr,neurospeech/coreclr,YongseopKim/coreclr,krk/coreclr,YongseopKim/coreclr,sjsinju/coreclr,mmitche/coreclr,cshung/coreclr,kyulee1/coreclr,kyulee1/coreclr,sjsinju/coreclr,kyulee1/coreclr,tijoytom/coreclr,hseok-oh/coreclr,JonHanna/coreclr,krytarowski/coreclr,qiudesong/coreclr,yeaicc/coreclr,mmitche/coreclr,ragmani/coreclr,ragmani/coreclr,ruben-ayrapetyan/coreclr,wateret/coreclr,poizan42/coreclr,ruben-ayrapetyan/coreclr,James-Ko/coreclr,James-Ko/coreclr,cshung/coreclr,parjong/coreclr,YongseopKim/coreclr,JonHanna/coreclr,cydhaselton/coreclr,qiudesong/coreclr,krk/coreclr,neurospeech/coreclr,krytarowski/coreclr,krk/coreclr,alexperovich/coreclr,yizhang82/coreclr,James-Ko/coreclr,mskvortsov/coreclr,JosephTremoulet/coreclr,krk/coreclr,sjsinju/coreclr,JosephTremoulet/coreclr,cydhaselton/coreclr,poizan42/coreclr,botaberg/coreclr,mmitche/coreclr,ruben-ayrapetyan/coreclr,alexperovich/coreclr,cshung/coreclr,botaberg/coreclr,JosephTremoulet/coreclr,alexperovich/coreclr,dpodder/coreclr,wateret/coreclr,neurospeech/coreclr,cmckinsey/coreclr,sagood/coreclr,yeaicc/coreclr,cmckinsey/coreclr,rartemev/coreclr,yizhang82/coreclr,pgavlin/coreclr,russellhadley/coreclr,gkhanna79/coreclr,krytarowski/coreclr,AlexGhiondea/coreclr,qiudesong/coreclr,wateret/coreclr,ruben-ayrapetyan/coreclr,parjong/coreclr,ruben-ayrapetyan/coreclr,cydhaselton/coreclr,JosephTremoulet/coreclr,cmckinsey/coreclr,kyulee1/coreclr,russellhadley/coreclr,pgavlin/coreclr,AlexGhiondea/coreclr,dpodder/coreclr,cmckinsey/coreclr,mskvortsov/coreclr,gkhanna79/coreclr,ragmani/coreclr,poizan42/coreclr,sagood/coreclr,JonHanna/coreclr,neurospeech/coreclr,cmckinsey/coreclr,krytarowski/coreclr,sjsinju/coreclr,wtgodbe/coreclr,dpodder/coreclr,JosephTremoulet/coreclr,ragmani/coreclr,hseok-oh/coreclr,AlexGhiondea/coreclr,cmckinsey/coreclr,parjong/coreclr,krytarowski/coreclr,tijoytom/coreclr,YongseopKim/coreclr,pgavlin/coreclr,mmitche/coreclr,wateret/coreclr,gkhanna79/coreclr,krk/coreclr,AlexGhiondea/coreclr,wtgodbe/coreclr,pgavlin/coreclr,botaberg/coreclr,poizan42/coreclr,parjong/coreclr,russellhadley/coreclr,rartemev/coreclr,James-Ko/coreclr,wtgodbe/coreclr,jamesqo/coreclr,sagood/coreclr,yizhang82/coreclr,hseok-oh/coreclr,alexperovich/coreclr,mskvortsov/coreclr,qiudesong/coreclr,tijoytom/coreclr,cshung/coreclr,cydhaselton/coreclr,rartemev/coreclr,parjong/coreclr,pgavlin/coreclr,jamesqo/coreclr,yizhang82/coreclr,botaberg/coreclr,sagood/coreclr,sagood/coreclr,yeaicc/coreclr,dpodder/coreclr,cmckinsey/coreclr,rartemev/coreclr,rartemev/coreclr,russellhadley/coreclr,yeaicc/coreclr,JonHanna/coreclr,AlexGhiondea/coreclr,jamesqo/coreclr,alexperovich/coreclr,dpodder/coreclr,gkhanna79/coreclr,JonHanna/coreclr,yeaicc/coreclr,James-Ko/coreclr,jamesqo/coreclr,dpodder/coreclr,wtgodbe/coreclr,wtgodbe/coreclr,qiudesong/coreclr,kyulee1/coreclr
src/mscorlib/corefx/Interop/Unix/System.Native/Interop.Fcntl.cs
src/mscorlib/corefx/Interop/Unix/System.Native/Interop.Fcntl.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.InteropServices; internal static partial class Interop { internal static partial class Sys { internal enum LockType : short { F_WRLCK = 1, // exclusive or write lock F_UNLCK = 2 // unlock } [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_LockFileRegion", SetLastError=true)] internal static extern int LockFileRegion(SafeHandle fd, long offset, long length, LockType lockType); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.InteropServices; internal static partial class Interop { internal static partial class Sys { internal enum LockType : short { F_UNLCK = 2, // unlock F_WRLCK = 3 // exclusive or write lock } [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_LockFileRegion", SetLastError=true)] internal static extern int LockFileRegion(SafeHandle fd, long offset, long length, LockType lockType); } }
mit
C#
80d557570b9c4558b981c8fe6eb13afce08e00dd
Fix StyleCop warning SA1015 (closing generic brace spacing)
shimingsg/corefx,wtgodbe/corefx,ViktorHofer/corefx,shimingsg/corefx,wtgodbe/corefx,ericstj/corefx,shimingsg/corefx,wtgodbe/corefx,ViktorHofer/corefx,ericstj/corefx,wtgodbe/corefx,shimingsg/corefx,ViktorHofer/corefx,ViktorHofer/corefx,ericstj/corefx,wtgodbe/corefx,ViktorHofer/corefx,shimingsg/corefx,wtgodbe/corefx,ericstj/corefx,shimingsg/corefx,wtgodbe/corefx,ericstj/corefx,shimingsg/corefx,ericstj/corefx,ViktorHofer/corefx,ericstj/corefx,ViktorHofer/corefx
src/Common/src/CoreLib/System/Runtime/Intrinsics/Arm/Arm64/Sha1.PlatformNotSupported.cs
src/Common/src/CoreLib/System/Runtime/Intrinsics/Arm/Arm64/Sha1.PlatformNotSupported.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #pragma warning disable IDE0060 // unused parameters using System.Runtime.CompilerServices; namespace System.Runtime.Intrinsics.Arm.Arm64 { /// <summary> /// This class provides access to the Arm64 SHA1 Crypto intrinsics /// /// Arm64 CPU indicate support for this feature by setting /// ID_AA64ISAR0_EL1.SHA1 is 1 or better /// </summary> [CLSCompliant(false)] public static class Sha1 { public static bool IsSupported { [Intrinsic] get { return false; } } /// <summary> /// Performs SHA1 hash update choose form. /// vsha1cq_u32 (uint32x4_t hash_abcd, uint32_t hash_e, uint32x4_t wk) /// </summary> public static Vector128<uint> HashChoose(Vector128<uint> hash_abcd, uint hash_e, Vector128<uint> wk) { throw new PlatformNotSupportedException(); } /// <summary> /// Performs SHA1 hash update majority form. /// vsha1mq_u32 (uint32x4_t hash_abcd, uint32_t hash_e, uint32x4_t wk) /// </summary> public static Vector128<uint> HashMajority(Vector128<uint> hash_abcd, uint hash_e, Vector128<uint> wk) { throw new PlatformNotSupportedException(); } /// <summary> /// Performs SHA1 hash update parity form. /// vsha1pq_u32 (uint32x4_t hash_abcd, uint32_t hash_e, uint32x4_t wk) /// </summary> public static Vector128<uint> HashParity(Vector128<uint> hash_abcd, uint hash_e, Vector128<uint> wk) { throw new PlatformNotSupportedException(); } /// <summary> /// Performs SHA1 fixed rotate /// vsha1h_u32 (uint32_t hash_e) /// </summary> public static uint FixedRotate(uint hash_e) { throw new PlatformNotSupportedException(); } /// <summary> /// Performs SHA1 schedule update 0 /// vsha1su0q_u32 (uint32x4_t w0_3, uint32x4_t w4_7, uint32x4_t w8_11) /// </summary> public static Vector128<uint> SchedulePart1(Vector128<uint> w0_3, Vector128<uint> w4_7, Vector128<uint> w8_11) { throw new PlatformNotSupportedException(); } /// <summary> /// Performs SHA1 schedule update 1 /// vsha1su1q_u32 (uint32x4_t tw0_3, uint32x4_t w12_15) /// </summary> public static Vector128<uint> SchedulePart2(Vector128<uint> tw0_3, Vector128<uint> w12_15) { throw new PlatformNotSupportedException(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #pragma warning disable IDE0060 // unused parameters using System.Runtime.CompilerServices; namespace System.Runtime.Intrinsics.Arm.Arm64 { /// <summary> /// This class provides access to the Arm64 SHA1 Crypto intrinsics /// /// Arm64 CPU indicate support for this feature by setting /// ID_AA64ISAR0_EL1.SHA1 is 1 or better /// </summary> [CLSCompliant(false)] public static class Sha1 { public static bool IsSupported { [Intrinsic] get { return false; } } /// <summary> /// Performs SHA1 hash update choose form. /// vsha1cq_u32 (uint32x4_t hash_abcd, uint32_t hash_e, uint32x4_t wk) /// </summary> public static Vector128<uint> HashChoose(Vector128<uint> hash_abcd, uint hash_e, Vector128<uint>wk) { throw new PlatformNotSupportedException(); } /// <summary> /// Performs SHA1 hash update majority form. /// vsha1mq_u32 (uint32x4_t hash_abcd, uint32_t hash_e, uint32x4_t wk) /// </summary> public static Vector128<uint> HashMajority(Vector128<uint> hash_abcd, uint hash_e, Vector128<uint>wk) { throw new PlatformNotSupportedException(); } /// <summary> /// Performs SHA1 hash update parity form. /// vsha1pq_u32 (uint32x4_t hash_abcd, uint32_t hash_e, uint32x4_t wk) /// </summary> public static Vector128<uint> HashParity(Vector128<uint> hash_abcd, uint hash_e, Vector128<uint>wk) { throw new PlatformNotSupportedException(); } /// <summary> /// Performs SHA1 fixed rotate /// vsha1h_u32 (uint32_t hash_e) /// </summary> public static uint FixedRotate(uint hash_e) { throw new PlatformNotSupportedException(); } /// <summary> /// Performs SHA1 schedule update 0 /// vsha1su0q_u32 (uint32x4_t w0_3, uint32x4_t w4_7, uint32x4_t w8_11) /// </summary> public static Vector128<uint> SchedulePart1(Vector128<uint> w0_3, Vector128<uint> w4_7, Vector128<uint> w8_11) { throw new PlatformNotSupportedException(); } /// <summary> /// Performs SHA1 schedule update 1 /// vsha1su1q_u32 (uint32x4_t tw0_3, uint32x4_t w12_15) /// </summary> public static Vector128<uint> SchedulePart2(Vector128<uint> tw0_3, Vector128<uint> w12_15) { throw new PlatformNotSupportedException(); } } }
mit
C#
54a03946a6b8573fb6ef7e8b8718c4df10683b59
Remove {Os,Data}VolumeEncryptionSettingsText
zhencui/azure-powershell,zhencui/azure-powershell,AzureAutomationTeam/azure-powershell,yoavrubin/azure-powershell,atpham256/azure-powershell,yantang-msft/azure-powershell,Matt-Westphal/azure-powershell,krkhan/azure-powershell,krkhan/azure-powershell,nemanja88/azure-powershell,jtlibing/azure-powershell,arcadiahlyy/azure-powershell,arcadiahlyy/azure-powershell,yoavrubin/azure-powershell,pankajsn/azure-powershell,ankurchoubeymsft/azure-powershell,shuagarw/azure-powershell,Matt-Westphal/azure-powershell,hovsepm/azure-powershell,krkhan/azure-powershell,Matt-Westphal/azure-powershell,AzureRT/azure-powershell,jtlibing/azure-powershell,naveedaz/azure-powershell,atpham256/azure-powershell,seanbamsft/azure-powershell,ankurchoubeymsft/azure-powershell,krkhan/azure-powershell,seanbamsft/azure-powershell,rohmano/azure-powershell,arcadiahlyy/azure-powershell,naveedaz/azure-powershell,yoavrubin/azure-powershell,rohmano/azure-powershell,atpham256/azure-powershell,pankajsn/azure-powershell,atpham256/azure-powershell,yantang-msft/azure-powershell,hungmai-msft/azure-powershell,devigned/azure-powershell,zhencui/azure-powershell,CamSoper/azure-powershell,AzureRT/azure-powershell,pankajsn/azure-powershell,CamSoper/azure-powershell,arcadiahlyy/azure-powershell,ClogenyTechnologies/azure-powershell,jtlibing/azure-powershell,AzureAutomationTeam/azure-powershell,AzureAutomationTeam/azure-powershell,shuagarw/azure-powershell,yantang-msft/azure-powershell,akurmi/azure-powershell,hovsepm/azure-powershell,pankajsn/azure-powershell,rohmano/azure-powershell,nemanja88/azure-powershell,nemanja88/azure-powershell,AzureRT/azure-powershell,yantang-msft/azure-powershell,krkhan/azure-powershell,yoavrubin/azure-powershell,hungmai-msft/azure-powershell,atpham256/azure-powershell,akurmi/azure-powershell,devigned/azure-powershell,devigned/azure-powershell,alfantp/azure-powershell,alfantp/azure-powershell,rohmano/azure-powershell,yantang-msft/azure-powershell,devigned/azure-powershell,AzureRT/azure-powershell,alfantp/azure-powershell,hovsepm/azure-powershell,devigned/azure-powershell,atpham256/azure-powershell,hovsepm/azure-powershell,ClogenyTechnologies/azure-powershell,akurmi/azure-powershell,alfantp/azure-powershell,rohmano/azure-powershell,arcadiahlyy/azure-powershell,zhencui/azure-powershell,akurmi/azure-powershell,ClogenyTechnologies/azure-powershell,CamSoper/azure-powershell,naveedaz/azure-powershell,hovsepm/azure-powershell,krkhan/azure-powershell,naveedaz/azure-powershell,jtlibing/azure-powershell,seanbamsft/azure-powershell,naveedaz/azure-powershell,hungmai-msft/azure-powershell,AzureAutomationTeam/azure-powershell,zhencui/azure-powershell,nemanja88/azure-powershell,yantang-msft/azure-powershell,AzureAutomationTeam/azure-powershell,pankajsn/azure-powershell,ankurchoubeymsft/azure-powershell,ankurchoubeymsft/azure-powershell,Matt-Westphal/azure-powershell,seanbamsft/azure-powershell,ClogenyTechnologies/azure-powershell,nemanja88/azure-powershell,hungmai-msft/azure-powershell,devigned/azure-powershell,shuagarw/azure-powershell,hungmai-msft/azure-powershell,ClogenyTechnologies/azure-powershell,pankajsn/azure-powershell,seanbamsft/azure-powershell,jtlibing/azure-powershell,shuagarw/azure-powershell,rohmano/azure-powershell,seanbamsft/azure-powershell,AzureAutomationTeam/azure-powershell,AzureRT/azure-powershell,Matt-Westphal/azure-powershell,alfantp/azure-powershell,AzureRT/azure-powershell,akurmi/azure-powershell,naveedaz/azure-powershell,zhencui/azure-powershell,ankurchoubeymsft/azure-powershell,CamSoper/azure-powershell,shuagarw/azure-powershell,CamSoper/azure-powershell,yoavrubin/azure-powershell,hungmai-msft/azure-powershell
src/ResourceManager/Compute/Commands.Compute/Models/AzureDiskEncryptionStatusContext.cs
src/ResourceManager/Compute/Commands.Compute/Models/AzureDiskEncryptionStatusContext.cs
using Microsoft.Azure.Management.Compute.Models; using Newtonsoft.Json; namespace Microsoft.Azure.Commands.Compute.Models { enum EncryptionStatus { Encrypted, NotEncrypted, Unknown } class AzureDiskEncryptionStatusContext { public EncryptionStatus OsVolumeEncrypted { get; set; } public DiskEncryptionSettings OsVolumeEncryptionSettings { get; set; } public EncryptionStatus DataVolumesEncrypted { get; set; } } class AzureDiskEncryptionStatusLinuxContext { public EncryptionStatus OsVolumeEncrypted { get; set; } public DiskEncryptionSettings OsVolumeEncryptionSettings { get; set; } public DiskEncryptionSettings DataVolumeEncryptionSettings { get; set; } public EncryptionStatus DataVolumesEncrypted { get; set; } } }
using Microsoft.Azure.Management.Compute.Models; using Newtonsoft.Json; namespace Microsoft.Azure.Commands.Compute.Models { enum EncryptionStatus { Encrypted, NotEncrypted, Unknown } class AzureDiskEncryptionStatusContext { public EncryptionStatus OsVolumeEncrypted { get; set; } public DiskEncryptionSettings OsVolumeEncryptionSettings { get; set; } public EncryptionStatus DataVolumesEncrypted { get; set; } [JsonIgnore] public string OsVolumeEncryptionSettingsText { get { return JsonConvert.SerializeObject(OsVolumeEncryptionSettings, Formatting.Indented); } } } class AzureDiskEncryptionStatusLinuxContext { public EncryptionStatus OsVolumeEncrypted { get; set; } public DiskEncryptionSettings OsVolumeEncryptionSettings { get; set; } public DiskEncryptionSettings DataVolumeEncryptionSettings { get; set; } [JsonIgnore] public string OsVolumeEncryptionSettingsText { get { return JsonConvert.SerializeObject(OsVolumeEncryptionSettings, Formatting.Indented); } } [JsonIgnore] public string DataVolumeEncryptionSettingsText { get { return JsonConvert.SerializeObject(DataVolumeEncryptionSettings, Formatting.Indented); } } public EncryptionStatus DataVolumesEncrypted { get; set; } } }
apache-2.0
C#
523c0b1ca27649fd3411715d4bad18a80a98458b
simplify name
CaitSith2/KtaneTwitchPlays,samfun123/KtaneTwitchPlays
TwitchPlaysAssembly/Src/Audio/MusicPlayer.cs
TwitchPlaysAssembly/Src/Audio/MusicPlayer.cs
using UnityEngine; using System.Linq; using System.Collections; using System.Collections.Generic; public class MusicPlayer : MonoBehaviour { private static Dictionary<string, MusicPlayer> _musicPlayers = new Dictionary<string, MusicPlayer>(); public AudioSource startInterruptSound = null; public AudioSource musicLoopSound = null; public AudioSource endInterruptSound = null; private Coroutine _currentCoroutine; private void Awake() { _musicPlayers[name] = this; } public static MusicPlayer GetMusicPlayer(string name) { return _musicPlayers[name]; } public static MusicPlayer StartRandomMusic() { MusicPlayer player = _musicPlayers.Values.ElementAt(Random.Range(0, _musicPlayers.Values.Count)); player.StartMusic(); return player; } public static void StopAllMusic() { foreach (MusicPlayer player in _musicPlayers.Values) { player.StopMusic(); } } public void StartMusic() { if (_currentCoroutine != null) { StopCoroutine(_currentCoroutine); } _currentCoroutine = StartCoroutine(StartMusicCoroutine()); } public void StopMusic() { if (_currentCoroutine != null) { StopCoroutine(_currentCoroutine); } _currentCoroutine = StartCoroutine(EndMusicCoroutine()); } private IEnumerator StartMusicCoroutine() { if (musicLoopSound == null || musicLoopSound.isPlaying) { yield break; } InterruptMusic.Instance.SetMusicInterrupt(true); if (startInterruptSound != null) { startInterruptSound.time = 0.0f; startInterruptSound.Play(); yield return new WaitForSeconds(startInterruptSound.clip.length); } musicLoopSound.time = 0.0f; musicLoopSound.Play(); _currentCoroutine = null; } private IEnumerator EndMusicCoroutine() { if (musicLoopSound == null) { yield break; } if (musicLoopSound.isPlaying) { musicLoopSound.Stop(); if (endInterruptSound != null) { endInterruptSound.time = 0.0f; endInterruptSound.Play(); yield return new WaitForSeconds(endInterruptSound.clip.length); } } InterruptMusic.Instance.SetMusicInterrupt(false); _currentCoroutine = null; } }
using UnityEngine; using System.Linq; using System.Collections; using System.Collections.Generic; public class MusicPlayer : MonoBehaviour { private static Dictionary<string, MusicPlayer> _musicPlayers = new Dictionary<string, MusicPlayer>(); public AudioSource startInterruptSound = null; public AudioSource musicLoopSound = null; public AudioSource endInterruptSound = null; private Coroutine _currentCoroutine; private void Awake() { _musicPlayers[name] = this; } public static MusicPlayer GetMusicPlayer(string name) { return _musicPlayers[name]; } public static MusicPlayer StartRandomMusic() { MusicPlayer player = _musicPlayers.Values.ElementAt(UnityEngine.Random.Range(0, _musicPlayers.Values.Count)); player.StartMusic(); return player; } public static void StopAllMusic() { foreach (MusicPlayer player in _musicPlayers.Values) { player.StopMusic(); } } public void StartMusic() { if (_currentCoroutine != null) { StopCoroutine(_currentCoroutine); } _currentCoroutine = StartCoroutine(StartMusicCoroutine()); } public void StopMusic() { if (_currentCoroutine != null) { StopCoroutine(_currentCoroutine); } _currentCoroutine = StartCoroutine(EndMusicCoroutine()); } private IEnumerator StartMusicCoroutine() { if (musicLoopSound == null || musicLoopSound.isPlaying) { yield break; } InterruptMusic.Instance.SetMusicInterrupt(true); if (startInterruptSound != null) { startInterruptSound.time = 0.0f; startInterruptSound.Play(); yield return new WaitForSeconds(startInterruptSound.clip.length); } musicLoopSound.time = 0.0f; musicLoopSound.Play(); _currentCoroutine = null; } private IEnumerator EndMusicCoroutine() { if (musicLoopSound == null) { yield break; } if (musicLoopSound.isPlaying) { musicLoopSound.Stop(); if (endInterruptSound != null) { endInterruptSound.time = 0.0f; endInterruptSound.Play(); yield return new WaitForSeconds(endInterruptSound.clip.length); } } InterruptMusic.Instance.SetMusicInterrupt(false); _currentCoroutine = null; } }
mit
C#
3916ea80a23fe913145dd7ed8dc0f7695ceef9cd
Remove some debug spew.
mdavid/manos-spdy,jacksonh/manos,jmptrader/manos,jacksonh/manos,jacksonh/manos,jmptrader/manos,jacksonh/manos,jmptrader/manos,mdavid/manos-spdy,jmptrader/manos,mdavid/manos-spdy,jacksonh/manos,jmptrader/manos,jacksonh/manos,jmptrader/manos,jmptrader/manos,mdavid/manos-spdy,jacksonh/manos,mdavid/manos-spdy,jacksonh/manos,mdavid/manos-spdy,mdavid/manos-spdy,jmptrader/manos
src/Manos/Manos.Collections/ByteBuffer.cs
src/Manos/Manos.Collections/ByteBuffer.cs
// // Copyright (C) 2010 Jackson Harper (jackson@manosdemono.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // using System; namespace Manos.Collections { public class ByteBuffer { int length; int position; public byte [] Bytes; public ByteBuffer (byte [] bytes, int position, int length) { Bytes = bytes; this.position = position; this.length = length; } public byte CurrentByte { get { return Bytes [position]; } } public int Length { get { return length; } set { if (value > Bytes.Length) throw new ArgumentOutOfRangeException ("value", "Can not increase the size of a byte buffer."); if (value < 0) throw new ArgumentOutOfRangeException ("value", "Length must be zero or greater."); length = value; } } public int Position { get { return position; } set { if (value > length) throw new ArgumentOutOfRangeException ("value", "Position must be less than the array length."); if (value < 0) throw new ArgumentOutOfRangeException ("value", "Position must be zero or greater."); position = value; } } public byte ReadByte () { if (position >= length) throw new InvalidOperationException ("Read past end of ByteBuffer."); return Bytes [position++]; } } }
// // Copyright (C) 2010 Jackson Harper (jackson@manosdemono.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // using System; namespace Manos.Collections { public class ByteBuffer { int length; int position; public byte [] Bytes; public ByteBuffer (byte [] bytes, int position, int length) { Bytes = bytes; this.position = position; this.length = length; } public byte CurrentByte { get { return Bytes [position]; } } public int Length { get { return length; } set { if (value > Bytes.Length) throw new ArgumentOutOfRangeException ("value", "Can not increase the size of a byte buffer."); if (value < 0) throw new ArgumentOutOfRangeException ("value", "Length must be zero or greater."); length = value; } } public int Position { get { return position; } set { if (value > length) throw new ArgumentOutOfRangeException ("value", "Position must be less than the array length."); if (value < 0) throw new ArgumentOutOfRangeException ("value", "Position must be zero or greater."); Console.WriteLine ("updating position to: '{0}'", value); position = value; } } public byte ReadByte () { if (position >= length) throw new InvalidOperationException ("Read past end of ByteBuffer."); return Bytes [position++]; } } }
mit
C#
7a687f920986dcc867470934014fca618f72e9de
adjust textarea length should not more than 100
hatelove/MyMvcHomework,hatelove/MyMvcHomework,hatelove/MyMvcHomework
MyMoney/MyMoney/Models/ViewModels/AccountingViewModel.cs
MyMoney/MyMoney/Models/ViewModels/AccountingViewModel.cs
using MyMoney.Models.CustomValidationAttributes; using MyMoney.Models.Enums; using System; using System.ComponentModel.DataAnnotations; namespace MyMoney.Models.ViewModels { public class AccountingViewModel { [Display(Name = "金額")] [DisplayFormat(DataFormatString = "{0:N0}")] [Range(0, int.MaxValue, ErrorMessage = "{0}需為正整數")] [Required] public int Amount { get; set; } [Display(Name = "日期")] [DataType(DataType.Date)] [DisplayFormat(DataFormatString = "{0:yyyy/MM/dd}")] [Required] [DateBeforeToday(ErrorMessage = "{0}不可大於今天")] public DateTime Date { get; set; } [Display(Name = "備註")] [DataType(DataType.MultilineText)] [Required] [TextAreaStringLength(100, ErrorMessage = "{0}長度不得超過{1}")] public string Remark { get; set; } [Display(Name = "類別")] [Required] public AccountingType Type { get; set; } } }
using MyMoney.Models.CustomValidationAttributes; using MyMoney.Models.Enums; using System; using System.ComponentModel.DataAnnotations; namespace MyMoney.Models.ViewModels { public class AccountingViewModel { [Display(Name = "金額")] [DisplayFormat(DataFormatString = "{0:N0}")] [Range(0, int.MaxValue, ErrorMessage = "{0}需為正整數")] [Required] public int Amount { get; set; } [Display(Name = "日期")] [DataType(DataType.Date)] [DisplayFormat(DataFormatString = "{0:yyyy/MM/dd}")] [Required] [DateBeforeToday(ErrorMessage = "{0}不可大於今天")] public DateTime Date { get; set; } [Display(Name = "備註")] [DataType(DataType.MultilineText)] [Required] [TextAreaStringLength(3, ErrorMessage = "{0}長度不得超過{1}")] public string Remark { get; set; } [Display(Name = "類別")] [Required] public AccountingType Type { get; set; } } }
mit
C#
79c05c804db5749bfb58433960939a13059d8e0d
Improve SA1407 and SA1408 fix all provider
DotNetAnalyzers/StyleCopAnalyzers
StyleCop.Analyzers/StyleCop.Analyzers/MaintainabilityRules/SA1407SA1408FixAllProvider.cs
StyleCop.Analyzers/StyleCop.Analyzers/MaintainabilityRules/SA1407SA1408FixAllProvider.cs
// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. namespace StyleCop.Analyzers.MaintainabilityRules { using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using SpacingRules; using StyleCop.Analyzers.Helpers; internal sealed class SA1407SA1408FixAllProvider : DocumentBasedFixAllProvider { protected override string CodeActionTitle => MaintainabilityResources.SA1407SA1408CodeFix; protected override async Task<SyntaxNode> FixAllInDocumentAsync(FixAllContext fixAllContext, Document document) { var diagnostics = await fixAllContext.GetDocumentDiagnosticsAsync(document).ConfigureAwait(false); if (diagnostics.IsEmpty) { return null; } var root = await document.GetSyntaxRootAsync(fixAllContext.CancellationToken).ConfigureAwait(false); List<SyntaxNode> nodes = new List<SyntaxNode>(); foreach (var diagnostic in diagnostics) { SyntaxNode node = root.FindNode(diagnostic.Location.SourceSpan); if (node.IsMissing) { continue; } nodes.Add(node); } return root.ReplaceNodes(nodes, (originalNode, rewrittenNode) => this.AddParentheses(originalNode, rewrittenNode)); } private SyntaxNode AddParentheses(SyntaxNode originalNode, SyntaxNode rewrittenNode) { BinaryExpressionSyntax syntax = rewrittenNode as BinaryExpressionSyntax; if (syntax == null) { return rewrittenNode; } BinaryExpressionSyntax trimmedSyntax = syntax .WithoutTrivia(); return SyntaxFactory.ParenthesizedExpression(trimmedSyntax) .WithTriviaFrom(syntax) .WithoutFormatting(); } } }
// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. namespace StyleCop.Analyzers.MaintainabilityRules { using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using SpacingRules; using StyleCop.Analyzers.Helpers; internal sealed class SA1407SA1408FixAllProvider : DocumentBasedFixAllProvider { private static readonly SyntaxAnnotation NeedsParenthesisAnnotation = new SyntaxAnnotation("StyleCop.NeedsParenthesis"); protected override string CodeActionTitle => MaintainabilityResources.SA1407SA1408CodeFix; protected override async Task<SyntaxNode> FixAllInDocumentAsync(FixAllContext fixAllContext, Document document) { var diagnostics = await fixAllContext.GetDocumentDiagnosticsAsync(document).ConfigureAwait(false); if (diagnostics.IsEmpty) { return null; } var newDocument = document; var root = await newDocument.GetSyntaxRootAsync(fixAllContext.CancellationToken).ConfigureAwait(false); // First annotate all expressions that need parenthesis with a temporary annotation. // With this annotation we can find the nodes that need parenthesis even if // the source span changes. foreach (var diagnostic in diagnostics) { SyntaxNode node = root.FindNode(diagnostic.Location.SourceSpan); if (node.IsMissing) { continue; } root = root.ReplaceNode(node, node.WithAdditionalAnnotations(NeedsParenthesisAnnotation)); } return root.ReplaceNodes(root.GetAnnotatedNodes(NeedsParenthesisAnnotation), this.AddParentheses); } private SyntaxNode AddParentheses(SyntaxNode originalNode, SyntaxNode rewrittenNode) { BinaryExpressionSyntax syntax = rewrittenNode as BinaryExpressionSyntax; if (syntax == null) { return rewrittenNode; } BinaryExpressionSyntax trimmedSyntax = syntax .WithoutTrivia() .WithoutAnnotations(NeedsParenthesisAnnotation.Kind); return SyntaxFactory.ParenthesizedExpression(trimmedSyntax) .WithTriviaFrom(syntax) .WithoutFormatting(); } } }
mit
C#
74225c5e0d7d5f8f61303ff8398c6c9f2ff71c48
Add variable types
missionpinball/unity-bcp-server
Assets/BCP/Scripts/PlayMaker/GetBCPMachineVariableChange.cs
Assets/BCP/Scripts/PlayMaker/GetBCPMachineVariableChange.cs
using UnityEngine; using System; using HutongGames.PlayMaker; using TooltipAttribute = HutongGames.PlayMaker.TooltipAttribute; using BCP.SimpleJSON; /// <summary> /// Custom PlayMaker action for MPF that sends an Event when an MPF 'machine_variable' command is received /// (when the machine variable changes). /// </summary> [ActionCategory("BCP")] [Tooltip("Sends an Event when an MPF 'machine_variable' command is received.")] public class GetBCPMachineVariableChange : FsmStateAction { [RequiredField] [UIHint(UIHint.Variable)] [Tooltip("The name of the MPF machine variable to listen for")] public string machineVariableName; [UIHint(UIHint.Variable)] [Tooltip("The string variable to receive the new value of the specified MPF machine variable")] public FsmString stringValue; [UIHint(UIHint.Variable)] [Tooltip("The int variable to receive the new value of the specified MPF machine variable")] public FsmInt intValue; [UIHint(UIHint.Variable)] [Tooltip("The float variable to receive the new value of the specified MPF machine variable")] public FsmFloat floatValue; [UIHint(UIHint.Variable)] [Tooltip("The boolean variable to receive the new value of the specified MPF machine variable")] public FsmBool boolValue; [UIHint(UIHint.Variable)] [Tooltip("The PlayMaker event to send when an MPF 'machine_variable' command is received")] public FsmEvent sendEvent; /// <summary> /// Resets this instance to default values. /// </summary> public override void Reset() { machineVariableName = null; stringValue = null; intValue = null; floatValue = null; boolValue = null; sendEvent = null; } /// <summary> /// Called when the state becomes active. Adds the MPF BCP 'machine_variable' event handler. /// </summary> public override void OnEnter() { base.OnEnter(); BcpMessageController.OnMachineVariable += MachineVariable; } /// <summary> /// Called before leaving the current state. Removes the MPF BCP 'machine_variable' event handler. /// </summary> public override void OnExit() { BcpMessageController.OnMachineVariable -= MachineVariable; base.OnExit(); } /// <summary> /// Event handler called when a machine variable event is received. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="MachineVariableMessageEventArgs"/> instance containing the event data.</param> public void MachineVariable(object sender, MachineVariableMessageEventArgs e) { // Determine if this machine variable message is the one we are interested in. If so, send specified FSM event. if (!String.IsNullOrEmpty(machineVariableName) && e.Name == machineVariableName) { JSONNode variable = e.Value; if (variable != null) { if (stringValue != null && !stringValue.IsNone) stringValue.Value = variable.Value; if (intValue != null && !intValue.IsNone) intValue.Value = variable.AsInt; if (floatValue != null && !floatValue.IsNone) floatValue.Value = variable.AsFloat; if (boolValue != null && !boolValue.IsNone) boolValue.Value = variable.AsBool; } Fsm.Event(sendEvent); } } }
using UnityEngine; using System; using HutongGames.PlayMaker; using TooltipAttribute = HutongGames.PlayMaker.TooltipAttribute; /// <summary> /// Custom PlayMaker action for MPF that sends an Event when an MPF 'machine_variable' command is received /// (when the machine variable changes). /// </summary> [ActionCategory("BCP")] [Tooltip("Sends an Event when an MPF 'machine_variable' command is received.")] public class GetBCPMachineVariableChange : FsmStateAction { [RequiredField] [UIHint(UIHint.Variable)] [Tooltip("The name of the MPF machine variable to listen for")] public string machineVariableName; [RequiredField] [UIHint(UIHint.Variable)] [Tooltip("The variable to receive the value of the specified MPF machine variable")] public FsmString value; [UIHint(UIHint.Variable)] [Tooltip("The PlayMaker event to send when an MPF 'machine_variable' command is received")] public FsmEvent sendEvent; /// <summary> /// Resets this instance to default values. /// </summary> public override void Reset() { machineVariableName = null; value = null; sendEvent = null; } /// <summary> /// Called when the state becomes active. Adds the MPF BCP 'machine_variable' event handler. /// </summary> public override void OnEnter() { base.OnEnter(); BcpMessageController.OnMachineVariable += MachineVariable; } /// <summary> /// Called before leaving the current state. Removes the MPF BCP 'machine_variable' event handler. /// </summary> public override void OnExit() { BcpMessageController.OnMachineVariable -= MachineVariable; base.OnExit(); } /// <summary> /// Event handler called when a machine variable event is received. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="MachineVariableMessageEventArgs"/> instance containing the event data.</param> public void MachineVariable(object sender, MachineVariableMessageEventArgs e) { // Determine if this machine variable message is the one we are interested in. If so, send specified FSM event. if (!String.IsNullOrEmpty(machineVariableName) && e.Name == machineVariableName) { if (!value.IsNone) value.Value = e.Value; Fsm.Event(sendEvent); } } }
mit
C#
6c47efb2a0197f0772049b1f94359beee8867fc3
Update version number
yas-mnkornym/TaihaToolkit
source/TaihaToolkit.Core/Properties/AssemblyInfo.cs
source/TaihaToolkit.Core/Properties/AssemblyInfo.cs
using System.Resources; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // アセンブリに関する一般情報は以下の属性セットをとおして制御されます。 // アセンブリに関連付けられている情報を変更するには、 // これらの属性値を変更してください。 [assembly: AssemblyTitle("TaihaToolkit.Core")] [assembly: AssemblyDescription("大破してすまない")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("スタジオ大破")] [assembly: AssemblyProduct("TaihaToolkit.Core")] [assembly: AssemblyCopyright("Copyright (C) スタジオ大破 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("")] // アセンブリのバージョン情報は、以下の 4 つの値で構成されています: // // メジャー バージョン // マイナー バージョン // ビルド番号 // リビジョン // // すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を // 既定値にすることができます: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.2.0.*")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: InternalsVisibleTo("TaihaToolkit.Core.Tests")]
using System.Resources; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // アセンブリに関する一般情報は以下の属性セットをとおして制御されます。 // アセンブリに関連付けられている情報を変更するには、 // これらの属性値を変更してください。 [assembly: AssemblyTitle("TaihaToolkit.Core")] [assembly: AssemblyDescription("大破してすまない")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("スタジオ大破")] [assembly: AssemblyProduct("TaihaToolkit.Core")] [assembly: AssemblyCopyright("Copyright (C) スタジオ大破 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("")] // アセンブリのバージョン情報は、以下の 4 つの値で構成されています: // // メジャー バージョン // マイナー バージョン // ビルド番号 // リビジョン // // すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を // 既定値にすることができます: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.1.2.*")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: InternalsVisibleTo("TaihaToolkit.Core.Tests")]
mit
C#
949cca9405acb7cd99a06508a244facffe0c0f75
Improve Local Toast notifier
Odonno/Modern-GitHub
GitHub/GitHub.Services/Concrete/LocalNotificationService.cs
GitHub/GitHub.Services/Concrete/LocalNotificationService.cs
using Windows.Data.Xml.Dom; using Windows.UI.Notifications; using GitHub.Services.Abstract; namespace GitHub.Services.Concrete { public class LocalNotificationService : ILocalNotificationService { public void SendNotification(string title, string content) { // Send any notification (Tile, Toast, Badge) SendToastNotification(title, content); } private void SendToastNotification(string title, string content) { // get toast notifier var toastNotifier = ToastNotificationManager.CreateToastNotifier(); // create notification form XmlDocument toastXml; if (string.IsNullOrWhiteSpace(title)) { toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText01); var toastTextElements = toastXml.GetElementsByTagName("text"); toastTextElements[0].AppendChild(toastXml.CreateTextNode(content)); } else { toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText02); var toastTextElements = toastXml.GetElementsByTagName("text"); toastTextElements[0].AppendChild(toastXml.CreateTextNode(title)); toastTextElements[1].AppendChild(toastXml.CreateTextNode(content)); } // create the notification from the template before var toastNotification = new ToastNotification(toastXml); // show notif toastNotifier.Show(toastNotification); } private void SendBadgeUpdate(int value) { // get badge updater var badgeUpdater = BadgeUpdateManager.CreateBadgeUpdaterForApplication(); // create badge form var badgeXml = BadgeUpdateManager.GetTemplateContent(BadgeTemplateType.BadgeNumber); var badgeElement = ((XmlElement)badgeXml.SelectSingleNode("/badge")); badgeElement.SetAttribute("value", value.ToString()); // create the notification from the template before var badgeNotification = new BadgeNotification(badgeXml); // show badge badgeUpdater.Update(badgeNotification); } } }
using Windows.Data.Xml.Dom; using Windows.UI.Notifications; using GitHub.Services.Abstract; namespace GitHub.Services.Concrete { public class LocalNotificationService : ILocalNotificationService { public void SendNotification(string title, string content) { // Send any notification (Tile, Toast, Badge) SendToastNotification(title, content); } private void SendToastNotification(string title, string content) { // get toast notifier var toastNotifier = ToastNotificationManager.CreateToastNotifier(); // create notification form var toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText02); var toastTextElements = toastXml.GetElementsByTagName("text"); toastTextElements[0].AppendChild(toastXml.CreateTextNode(title)); toastTextElements[1].AppendChild(toastXml.CreateTextNode(content)); // create the notification from the template before var toastNotification = new ToastNotification(toastXml); // show notif toastNotifier.Show(toastNotification); } private void SendBadgeUpdate(int value) { // get badge updater var badgeUpdater = BadgeUpdateManager.CreateBadgeUpdaterForApplication(); // create badge form var badgeXml = BadgeUpdateManager.GetTemplateContent(BadgeTemplateType.BadgeNumber); var badgeElement = ((XmlElement)badgeXml.SelectSingleNode("/badge")); badgeElement.SetAttribute("value", value.ToString()); // create the notification from the template before var badgeNotification = new BadgeNotification(badgeXml); // show badge badgeUpdater.Update(badgeNotification); } } }
apache-2.0
C#
9de047cfebbaacce21f6371033514b14150773da
Fix usings
BrutalCode/NLog,snakefoot/NLog,littlesmilelove/NLog,AndreGleichner/NLog,tohosnet/NLog,bjornbouetsmith/NLog,bryjamus/NLog,ie-zero/NLog,kevindaub/NLog,tetrodoxin/NLog,hubo0831/NLog,bjornbouetsmith/NLog,luigiberrettini/NLog,luigiberrettini/NLog,littlesmilelove/NLog,MoaidHathot/NLog,UgurAldanmaz/NLog,bhaeussermann/NLog,ie-zero/NLog,AndreGleichner/NLog,breyed/NLog,NLog/NLog,sean-gilliam/NLog,hubo0831/NLog,nazim9214/NLog,MartinTherriault/NLog,bryjamus/NLog,nazim9214/NLog,304NotModified/NLog,michaeljbaird/NLog,kevindaub/NLog,bhaeussermann/NLog,MoaidHathot/NLog,michaeljbaird/NLog,MartinTherriault/NLog,tetrodoxin/NLog,breyed/NLog,tohosnet/NLog,BrutalCode/NLog,UgurAldanmaz/NLog
src/NLog/Internal/StringBuilderExt.cs
src/NLog/Internal/StringBuilderExt.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using NLog.Config; namespace NLog.Internal { /// <summary> /// Helpers for <see cref="StringBuilder"/>, which is used in e.g. layout renderers. /// </summary> internal static class StringBuilderExt { /// <summary> /// Append a value and use formatProvider of <paramref name="logEvent"/> or <paramref name="configuration"/> to convert to string. /// </summary> /// <param name="builder"></param> /// <param name="o">value to append.</param> /// <param name="logEvent">current logEvent for FormatProvider.</param> /// <param name="configuration">Configuration for DefaultCultureInfo</param> public static void Append(this StringBuilder builder, object o, LogEventInfo logEvent, LoggingConfiguration configuration) { var formatProvider = logEvent.FormatProvider; if (formatProvider == null && configuration != null) { formatProvider = configuration.DefaultCultureInfo; } builder.Append(Convert.ToString(o, formatProvider)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NLog.Config; namespace NLog.Internal { /// <summary> /// Helpers for <see cref="StringBuilder"/>, which is used in e.g. layout renderers. /// </summary> internal static class StringBuilderExt { /// <summary> /// Append a value and use formatProvider of <paramref name="logEvent"/> or <paramref name="configuration"/> to convert to string. /// </summary> /// <param name="builder"></param> /// <param name="o">value to append.</param> /// <param name="logEvent">current logEvent for FormatProvider.</param> /// <param name="configuration">Configuration for DefaultCultureInfo</param> public static void Append(this StringBuilder builder, object o, LogEventInfo logEvent, LoggingConfiguration configuration) { var formatProvider = logEvent.FormatProvider; if (formatProvider == null && configuration != null) { formatProvider = configuration.DefaultCultureInfo; } builder.Append(Convert.ToString(o, formatProvider)); } } }
bsd-3-clause
C#
649ebe5866a5ae6b1fe18e62995ab7a6d02bbe30
Test query by id
VictorNicollet/SocialToolBox
SocialToolBox.Core.Tests/Entity/Web/EntityPage/view_page.cs
SocialToolBox.Core.Tests/Entity/Web/EntityPage/view_page.cs
using NUnit.Framework; using SocialToolBox.Core.Database; using SocialToolBox.Core.Mocks.Entity; using SocialToolBox.Core.Present; using SocialToolBox.Core.Web.Response; namespace SocialToolBox.Core.Tests.Entity.Web.EntityPage { [TestFixture] public class view_page : MockFixture { [Test] public void get_empty() { var response = (WebResponsePage) Facet.View.Query(Id.Parse("40404040404").ToArgs()).Run(); Assert.IsTrue(response.Page is NotFound); } [Test] public void get_bob() { var response = (WebResponsePage) Facet.View.Query(EntityModuleMock.IdBob.ToArgs()).Run(); Assert.IsTrue(response.Page is HtmlString); Assert.AreEqual(EntityModuleMock.NameBob, response.Page.ToString()); } } }
using NUnit.Framework; using SocialToolBox.Core.Database; using SocialToolBox.Core.Present; using SocialToolBox.Core.Web.Response; namespace SocialToolBox.Core.Tests.Entity.Web.EntityPage { [TestFixture] public class view_page : MockFixture { [Test] public void get_empty() { var response = (WebResponsePage) Facet.View.Query(Id.Parse("40404040404").ToArgs()).Run(); Assert.IsTrue(response.Page is NotFound); } } }
mit
C#
c12e0bd48fad29cbe3595bae3eb1f6b51f9f90c8
Use LINQ Work Item #1799
CslaGenFork/CslaGenFork,CslaGenFork/CslaGenFork,CslaGenFork/CslaGenFork,CslaGenFork/CslaGenFork
trunk/Solutions/CslaGenFork/Metadata/ChildPropertyCollection.cs
trunk/Solutions/CslaGenFork/Metadata/ChildPropertyCollection.cs
using System.Collections.Generic; using System.Linq; namespace CslaGenerator.Metadata { public class ChildPropertyCollection : List<ChildProperty> { public ChildProperty Find(string name) { if (name == string.Empty) return null; /*foreach (var c in this) { if (c.Name.Equals(name)) return c; } return null;*/ return this.FirstOrDefault(c => c.Name.Equals(name)); } public ChildProperty FindType(string typeName) { if (typeName == string.Empty) return null; /*foreach (var c in this) { if (c.TypeName.Equals(typeName)) return c; } return null;*/ return this.FirstOrDefault(c => c.TypeName.Equals(typeName)); } public bool Contains(string name) { return (Find(name) != null); } } }
using System.Collections.Generic; namespace CslaGenerator.Metadata { public class ChildPropertyCollection : List<ChildProperty> { public ChildProperty Find(string name) { foreach (var c in this) { if (c.Name.Equals(name)) return c; } return null; } public ChildProperty FindType(string typeName) { foreach (var c in this) { if (c.TypeName.Equals(typeName)) return c; } return null; } public bool Contains(string name) { return (Find(name) != null); } } }
mit
C#
ad4f5e45bb7d48694c752a90d7ddf464ef4c8600
add jobid validation
mzrimsek/resume-site-api
Web/Models/JobProjectModels/AddUpdateJobProjectViewModel.cs
Web/Models/JobProjectModels/AddUpdateJobProjectViewModel.cs
using System.ComponentModel.DataAnnotations; namespace Web.Models.JobProjectModels { public class AddUpdateJobProjectViewModel { [Required] [Range(1, double.PositiveInfinity, ErrorMessage = "Invalid Job ID")] public int JobId { get; set; } [Required] public string Name { get; set; } [Required] public string Description { get; set; } } }
using System.ComponentModel.DataAnnotations; namespace Web.Models.JobProjectModels { public class AddUpdateJobProjectViewModel { [Required] public int JobId { get; set; } [Required] public string Name { get; set; } [Required] public string Description { get; set; } } }
mit
C#
3c901984bd33638411e3a53bb0219f5674185bf4
Allow redirectUrl and custom layout on home page
brondavies/wwwplatform.net,brondavies/wwwplatform.net,brondavies/wwwplatform.net
src/web/Controllers/HomeController.cs
src/web/Controllers/HomeController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using wwwplatform.Extensions; using wwwplatform.Models; namespace wwwplatform.Controllers { public class HomeController : BaseController { public ActionResult Index() { var page = SitePage.GetAvailablePages(db, User, UserManager, RoleManager, true, false, false).Where(p => p.HomePage == true).FirstOrDefault(); if (page == null) { if (db.ActiveSitePages.Where(p => p.HomePage == true).Any()) { return new HttpUnauthorizedResult("Access Denied"); } return RedirectToAction("Setup"); } if (!string.IsNullOrEmpty(page.RedirectUrl)) { return Redirect(page.RedirectUrl); } ViewBag.Layout = page.Layout; return View(page); } public ActionResult Setup() { return View(); } public ActionResult Upgrade() { ApplicationDbContext.Upgrade(); return RedirectToAction("Index"); } public ActionResult Uninstall() { if (Request.IsLocal) { var config = new Migrations.Configuration(); config.Uninstall(db); } return RedirectToAction("Index"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using wwwplatform.Extensions; using wwwplatform.Models; namespace wwwplatform.Controllers { public class HomeController : BaseController { public ActionResult Index() { var page = SitePage.GetAvailablePages(db, User, UserManager, RoleManager, true, false, false).Where(p => p.HomePage == true).FirstOrDefault(); if (page == null) { if (db.ActiveSitePages.Where(p => p.HomePage == true).Any()) { return new HttpUnauthorizedResult("Access Denied"); } return RedirectToAction("Setup"); } return View(page); } public ActionResult Setup() { return View(); } public ActionResult Upgrade() { ApplicationDbContext.Upgrade(); return RedirectToAction("Index"); } public ActionResult Uninstall() { if (Request.IsLocal) { var config = new Migrations.Configuration(); config.Uninstall(db); } return RedirectToAction("Index"); } } }
apache-2.0
C#
a92e361164334b6faa3669c34a8e14e2fb7aa39d
Remove Test1Async
Asesjix/Zammad-Client
test/Zammad.Client.Tests/UnitTest1.cs
test/Zammad.Client.Tests/UnitTest1.cs
using System; using System.Threading.Tasks; using Xunit; namespace Zammad.Client.Tests { public class UnitTest1 { [Fact] public async Task Test1Async() { } } }
using System; using System.Threading.Tasks; using Xunit; namespace Zammad.Client.Tests { public class UnitTest1 { [Fact] public async Task Test1Async() { var account = ZammadAccount.CreateTokenAccount("http", "zammad-soft", "vatTlijkbmZYcIYQ1qhw8t6FIENwclwXYKQKPah34GKlolMb5e7jzZdxYjHY-IMP"); var groupClient = account.CreateGroupClient(); var groupList = await groupClient.GetGroupListAsync(); var notificationClient = account.CreateOnlineNotificationClient(); var notificationList = await notificationClient.GetOnlineNotificationListAsync(); var organizationClient = account.CreateOrganizationClient(); var organizationList = await organizationClient.GetOrganizationListAsync(); var ticketClient = account.CreateTicketClient(); var ticketList = await ticketClient.GetTicketListAsync(); var ticketArticleList = await ticketClient.GetTicketArticleListAsync(); var ticketPriorityList = await ticketClient.GetTicketPriorityListAsync(); var ticketStateList = await ticketClient.GetTicketStateListAsync(); var userClient = account.CreateUserClient(); var userList = await userClient.GetUserListAsync(); } } }
apache-2.0
C#
7cb73eb73575bb36110de3653652b798247167f5
Replace the caching queue in the GlobalSongCache with a much simpler and more resource-friendly semaphore
flagbug/Espera,punker76/Espera
Espera/Espera.Core/Management/GlobalSongCache.cs
Espera/Espera.Core/Management/GlobalSongCache.cs
using Rareform.Validation; using System.Threading; using System.Threading.Tasks; namespace Espera.Core.Management { internal sealed class GlobalSongCacheQueue { private static GlobalSongCacheQueue instance; private readonly SemaphoreSlim countblock; private GlobalSongCacheQueue() { this.countblock = new SemaphoreSlim(10, 10); } public static GlobalSongCacheQueue Instance { get { return instance ?? (instance = new GlobalSongCacheQueue()); } } public void Enqueue(Song song) { if (song == null) Throw.ArgumentNullException(() => song); Task.Factory.StartNew(() => { this.countblock.Wait(); song.LoadToCache(); this.countblock.Release(); }); } } }
using System.Collections.Concurrent; using System.Threading; using System.Threading.Tasks; using Rareform.Validation; namespace Espera.Core.Management { internal sealed class GlobalSongCacheQueue { private static GlobalSongCacheQueue instance; private readonly ConcurrentQueue<Song> cachingQueue; private GlobalSongCacheQueue() { this.cachingQueue = new ConcurrentQueue<Song>(); for (int i = 0; i < 10; i++) { Task.Factory.StartNew(Cache, TaskCreationOptions.LongRunning); } } public static GlobalSongCacheQueue Instance { get { return instance ?? (instance = new GlobalSongCacheQueue()); } } public void Enqueue(Song song) { if (song == null) Throw.ArgumentNullException(() => song); this.cachingQueue.Enqueue(song); } private void Cache() { while (true) { Song song; if (this.cachingQueue.TryDequeue(out song)) { song.LoadToCache(); } else { Thread.Sleep(500); } } } } }
mit
C#
07d3afef35f6ec477d8ab5868012e745ba14db4f
Update SplitPanes.cs
maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET
Examples/CSharp/Worksheets/Display/SplitPanes.cs
Examples/CSharp/Worksheets/Display/SplitPanes.cs
using System.IO; using Aspose.Cells; namespace Aspose.Cells.Examples.Worksheets.Display { public class SplitPanes { public static void Main(string[] args) { //ExStart:1 // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); //Instantiate a new workbook and Open a template file Workbook book = new Workbook(dataDir + "Book1.xls"); //Set the active cell book.Worksheets[0].ActiveCell = "A20"; //Split the worksheet window book.Worksheets[0].Split(); //Save the excel file book.Save(dataDir + "Splitted_out1.out.xls"); //ExEnd:1 } } }
using System.IO; using Aspose.Cells; namespace Aspose.Cells.Examples.Worksheets.Display { public class SplitPanes { public static void Main(string[] args) { // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); //Instantiate a new workbook and Open a template file Workbook book = new Workbook(dataDir + "Book1.xls"); //Set the active cell book.Worksheets[0].ActiveCell = "A20"; //Split the worksheet window book.Worksheets[0].Split(); //Save the excel file book.Save(dataDir + "Splitted_out1.out.xls"); } } }
mit
C#
3fb3e51c45ad1b4bce96d5cf4eff778b93a03e8b
add test for Solve()
wwylele/Picrosser
test/SolverTest.cs
test/SolverTest.cs
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using Picrosser; using System.Collections.Generic; using System.Linq; using System.IO; namespace PicrosserTest { [TestClass] public class SolverTest { [TestMethod] public void TestSolveBySearching() { Question question = new Question("1 1\n1 1\n1 1\n1 1\n\n1 1\n1 1\n1 1\n1 1"); int count = 0; foreach(var s in Solver.SolveBySearching(question)) { ++count; Assert.IsTrue(question.VerifySolution(s)); } Assert.AreEqual(2, count); } [TestMethod] public void TestSolveSimple() { string text = "", line; int sec = 0; StreamReader file = new StreamReader("..\\..\\..\\Examples\\example1.txt"); while(sec < 2) { line = file.ReadLine(); if(line == null) line = ""; text += line + "\n"; if(line.Equals("")) ++sec; } file.Close(); Question question = new Question(text); Solver solver = new Solver(); Assert.AreEqual(Solver.ResultEnum.FINISHED, solver.Solve(question)); Assert.IsTrue(question.VerifySolution(Solver.ConvertToPureSolution(solver.pixelStates))); } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using Picrosser; using System.Collections.Generic; using System.Linq; namespace PicrosserTest { [TestClass] public class SolverTest { [TestMethod] public void TestSolveBySearching() { Question question = new Question("1 1\n1 1\n1 1\n1 1\n\n1 1\n1 1\n1 1\n1 1"); int count = 0; foreach(var s in Solver.SolveBySearching(question)) { ++count; Assert.IsTrue(question.VerifySolution(s)); } Assert.AreEqual(count, 2); } } }
mit
C#
f561312ea936d5dd8e85567ab803a16c36e3ff73
Clarify comment about MSBuildLoadContext test
mono/msbuild,sean-gilliam/msbuild,sean-gilliam/msbuild,AndyGerlicher/msbuild,cdmihai/msbuild,rainersigwald/msbuild,sean-gilliam/msbuild,rainersigwald/msbuild,cdmihai/msbuild,rainersigwald/msbuild,mono/msbuild,cdmihai/msbuild,AndyGerlicher/msbuild,AndyGerlicher/msbuild,cdmihai/msbuild,mono/msbuild,sean-gilliam/msbuild,rainersigwald/msbuild,AndyGerlicher/msbuild,mono/msbuild
src/MSBuild.UnitTests/ValidateAssemblyLoadContext.cs
src/MSBuild.UnitTests/ValidateAssemblyLoadContext.cs
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #if FEATURE_ASSEMBLYLOADCONTEXT using Microsoft.Build.Framework; using Microsoft.Build.Shared; using Microsoft.Build.Utilities; using System.Runtime.Loader; namespace Microsoft.Build.UnitTests { public class ValidateAssemblyLoadContext : Task { public override bool Execute() { var thisLoadContext = AssemblyLoadContext.GetLoadContext(typeof(ValidateAssemblyLoadContext).Assembly); // The straightforward implementation of this check: // if (thisLoadContext is MSBuildLoadContext context) // fails here because MSBuildLoadContext (in this test assembly) is from MSBuild.exe via // IVT, but the one that actually gets used for task isolation is in Microsoft.Build.dll. // This probably doesn't need to be how it is forever: https://github.com/microsoft/msbuild/issues/5041 if (thisLoadContext.GetType().FullName == typeof(MSBuildLoadContext).FullName) { #if NETCOREAPP && !NETCOREAPP2_1 // TODO: enable this functionality when targeting .NET Core 3.0+ if (!thisLoadContext.Name.EndsWith(typeof(ValidateAssemblyLoadContext).Assembly.GetName().Name + ".dll")) { Log.LogError($"Unexpected AssemblyLoadContext name: \"{thisLoadContext.Name}\", but the current executing assembly was {typeof(ValidateAssemblyLoadContext).Assembly.GetName().Name}"); } else { Log.LogMessage(MessageImportance.High, $"Task {nameof(ValidateAssemblyLoadContext)} loaded in AssemblyLoadContext named {thisLoadContext.Name}"); } #endif } else { Log.LogError($"Load context was a {thisLoadContext.GetType().AssemblyQualifiedName} instead of an {typeof(MSBuildLoadContext).AssemblyQualifiedName}"); } return !Log.HasLoggedErrors; } } } #endif
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #if FEATURE_ASSEMBLYLOADCONTEXT using Microsoft.Build.Framework; using Microsoft.Build.Shared; using Microsoft.Build.Utilities; using System.Runtime.Loader; namespace Microsoft.Build.UnitTests { public class ValidateAssemblyLoadContext : Task { public override bool Execute() { var thisLoadContext = AssemblyLoadContext.GetLoadContext(typeof(ValidateAssemblyLoadContext).Assembly); // Check by name because this always reports false, presumably due to ALC shenanigans: // if (thisLoadContext is MSBuildLoadContext context) if (thisLoadContext.GetType().FullName == typeof(MSBuildLoadContext).FullName) { #if NETCOREAPP && !NETCOREAPP2_1 // TODO: enable this functionality when targeting .NET Core 3.0+ if (!thisLoadContext.Name.EndsWith(typeof(ValidateAssemblyLoadContext).Assembly.GetName().Name + ".dll")) { Log.LogError($"Unexpected AssemblyLoadContext name: \"{thisLoadContext.Name}\", but the current executing assembly was {typeof(ValidateAssemblyLoadContext).Assembly.GetName().Name}"); } else { Log.LogMessage(MessageImportance.High, $"Task {nameof(ValidateAssemblyLoadContext)} loaded in AssemblyLoadContext named {thisLoadContext.Name}"); } #endif } else { Log.LogError($"Load context was a {thisLoadContext.GetType().AssemblyQualifiedName} instead of an {typeof(MSBuildLoadContext).AssemblyQualifiedName}"); } return !Log.HasLoggedErrors; } } } #endif
mit
C#
ffbd0804f023ecb353e86c859730807d81c8d3dc
make naming in assembly more consistant hassymbol's'
mono/debugger-libs,mono/debugger-libs
Mono.Debugging/Mono.Debugging.Client/Assembly.cs
Mono.Debugging/Mono.Debugging.Client/Assembly.cs
// // Assembly.cs // // Author: // Jonathan Chang <t-jochang@microsoft.com> // // Copyright (c) 2022 // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; namespace Mono.Debugging.Client { public class Assembly { public Assembly (string name, string path, bool optimized, bool userCode, string symbolStatus, string symbolFile, int? order, string version, string timestamp, string address, string process, string appdomain, long? processId, bool hasSymbol = false, bool isDynamic = false) { Name = name; Path = path; Optimized = optimized; SymbolStatus = symbolStatus; SymbolFile = symbolFile; Order = order.GetValueOrDefault (-1); TimeStamp = timestamp; Address = address; Process = process; AppDomain = appdomain; Version = version; UserCode = userCode; ProcessId = processId; IsDynamic = isDynamic; HasSymbols = hasSymbol; } public Assembly (string path) { Path = path; } public string Name { get; private set; } public string Path { get; private set; } public bool Optimized { get; private set; } public bool UserCode { get; private set; } public string SymbolStatus { get; private set; } public string SymbolFile { get; private set; } public int Order { get; private set; } = -1; public string Version { get; private set; } public string TimeStamp { get; private set; } public string Address { get; private set; } public string Process { get; private set; } public string AppDomain { get; private set; } public long? ProcessId { get; private set; } = -1; public bool HasSymbols { get; private set; } public bool IsDynamic { get; private set; } } }
// // Assembly.cs // // Author: // Jonathan Chang <t-jochang@microsoft.com> // // Copyright (c) 2022 // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; namespace Mono.Debugging.Client { public class Assembly { public Assembly (string name, string path, bool optimized, bool userCode, string symbolStatus, string symbolFile, int? order, string version, string timestamp, string address, string process, string appdomain, long? processId, bool hasSymbol = false, bool isDynamic = false) { Name = name; Path = path; Optimized = optimized; SymbolStatus = symbolStatus; SymbolFile = symbolFile; Order = order.GetValueOrDefault (-1); TimeStamp = timestamp; Address = address; Process = process; AppDomain = appdomain; Version = version; UserCode = userCode; ProcessId = processId; IsDynamic = isDynamic; HasSymbol = hasSymbol; } public Assembly (string path) { Path = path; } public string Name { get; private set; } public string Path { get; private set; } public bool Optimized { get; private set; } public bool UserCode { get; private set; } public string SymbolStatus { get; private set; } public string SymbolFile { get; private set; } public int Order { get; private set; } = -1; public string Version { get; private set; } public string TimeStamp { get; private set; } public string Address { get; private set; } public string Process { get; private set; } public string AppDomain { get; private set; } public long? ProcessId { get; private set; } = -1; public bool HasSymbol { get; private set; } public bool IsDynamic { get; private set; } } }
mit
C#
a621f74a8b36d18b6a464c7c8edec98311bd3044
Fix DocAsUpsert test: id was not specified
robertlyson/elasticsearch-net,tkirill/elasticsearch-net,abibell/elasticsearch-net,RossLieberman/NEST,TheFireCookie/elasticsearch-net,elastic/elasticsearch-net,wawrzyn/elasticsearch-net,tkirill/elasticsearch-net,SeanKilleen/elasticsearch-net,LeoYao/elasticsearch-net,DavidSSL/elasticsearch-net,geofeedia/elasticsearch-net,mac2000/elasticsearch-net,amyzheng424/elasticsearch-net,amyzheng424/elasticsearch-net,junlapong/elasticsearch-net,azubanov/elasticsearch-net,CSGOpenSource/elasticsearch-net,KodrAus/elasticsearch-net,amyzheng424/elasticsearch-net,RossLieberman/NEST,faisal00813/elasticsearch-net,UdiBen/elasticsearch-net,wawrzyn/elasticsearch-net,abibell/elasticsearch-net,adam-mccoy/elasticsearch-net,Grastveit/NEST,mac2000/elasticsearch-net,SeanKilleen/elasticsearch-net,ststeiger/elasticsearch-net,robrich/elasticsearch-net,elastic/elasticsearch-net,jonyadamit/elasticsearch-net,gayancc/elasticsearch-net,abibell/elasticsearch-net,joehmchan/elasticsearch-net,mac2000/elasticsearch-net,faisal00813/elasticsearch-net,junlapong/elasticsearch-net,geofeedia/elasticsearch-net,jonyadamit/elasticsearch-net,junlapong/elasticsearch-net,wawrzyn/elasticsearch-net,jonyadamit/elasticsearch-net,TheFireCookie/elasticsearch-net,LeoYao/elasticsearch-net,KodrAus/elasticsearch-net,tkirill/elasticsearch-net,KodrAus/elasticsearch-net,starckgates/elasticsearch-net,adam-mccoy/elasticsearch-net,gayancc/elasticsearch-net,SeanKilleen/elasticsearch-net,adam-mccoy/elasticsearch-net,gayancc/elasticsearch-net,CSGOpenSource/elasticsearch-net,UdiBen/elasticsearch-net,robertlyson/elasticsearch-net,azubanov/elasticsearch-net,LeoYao/elasticsearch-net,DavidSSL/elasticsearch-net,Grastveit/NEST,robrich/elasticsearch-net,UdiBen/elasticsearch-net,DavidSSL/elasticsearch-net,cstlaurent/elasticsearch-net,faisal00813/elasticsearch-net,cstlaurent/elasticsearch-net,starckgates/elasticsearch-net,robertlyson/elasticsearch-net,joehmchan/elasticsearch-net,TheFireCookie/elasticsearch-net,RossLieberman/NEST,azubanov/elasticsearch-net,cstlaurent/elasticsearch-net,Grastveit/NEST,joehmchan/elasticsearch-net,starckgates/elasticsearch-net,ststeiger/elasticsearch-net,robrich/elasticsearch-net,ststeiger/elasticsearch-net,CSGOpenSource/elasticsearch-net,geofeedia/elasticsearch-net
src/Tests/Nest.Tests.Integration/Core/UpdateTests.cs
src/Tests/Nest.Tests.Integration/Core/UpdateTests.cs
using NUnit.Framework; using Nest.Tests.MockData.Domain; namespace Nest.Tests.Integration.Core { [TestFixture] public class UpdateIntegrationTests : IntegrationTests { [Test] public void TestUpdate() { var project = this._client.Source<ElasticsearchProject>(s => s.Id(1)); Assert.NotNull(project); Assert.Greater(project.LOC, 0); var loc = project.LOC; this._client.Update<ElasticsearchProject>(u => u .Object(project) .Script("ctx._source.loc += 10") .RetryOnConflict(5) .Refresh() ); project = this._client.Source<ElasticsearchProject>(s => s.Id(1)); Assert.AreEqual(project.LOC, loc + 10); Assert.AreNotEqual(project.Version, "1"); } public class ElasticsearchProjectLocUpdate { public int Id { get; set; } [ElasticProperty(Name="loc",AddSortField=true)] public int LOC { get; set; } } [Test] public void DocAsUpsert() { var project = this._client.Source<ElasticsearchProject>(s => s.Id(1)); Assert.NotNull(project); Assert.Greater(project.LOC, 0); var loc = project.LOC; this._client.Update<ElasticsearchProject, ElasticsearchProjectLocUpdate>(u => u .Id(1) .Document(new ElasticsearchProjectLocUpdate { Id = project.Id, LOC = project.LOC + 10 }) .DocAsUpsert() .Refresh() ); project = this._client.Source<ElasticsearchProject>(s => s.Id(1)); Assert.AreEqual(project.LOC, loc + 10); Assert.AreNotEqual(project.Version, "1"); } } }
using NUnit.Framework; using Nest.Tests.MockData.Domain; namespace Nest.Tests.Integration.Core { [TestFixture] public class UpdateIntegrationTests : IntegrationTests { [Test] public void TestUpdate() { var project = this._client.Source<ElasticsearchProject>(s => s.Id(1)); Assert.NotNull(project); Assert.Greater(project.LOC, 0); var loc = project.LOC; this._client.Update<ElasticsearchProject>(u => u .Object(project) .Script("ctx._source.loc += 10") .RetryOnConflict(5) .Refresh() ); project = this._client.Source<ElasticsearchProject>(s => s.Id(1)); Assert.AreEqual(project.LOC, loc + 10); Assert.AreNotEqual(project.Version, "1"); } public class ElasticsearchProjectLocUpdate { public int Id { get; set; } [ElasticProperty(Name="loc",AddSortField=true)] public int LOC { get; set; } } [Test] public void DocAsUpsert() { var project = this._client.Source<ElasticsearchProject>(s => s.Id(1)); Assert.NotNull(project); Assert.Greater(project.LOC, 0); var loc = project.LOC; this._client.Update<ElasticsearchProject, ElasticsearchProjectLocUpdate>(u => u .Document(new ElasticsearchProjectLocUpdate { Id = project.Id, LOC = project.LOC + 10 }) .DocAsUpsert() .Refresh() ); project = this._client.Source<ElasticsearchProject>(s => s.Id(1)); Assert.AreEqual(project.LOC, loc + 10); Assert.AreNotEqual(project.Version, "1"); } } }
apache-2.0
C#
2d2122137f88bc606a8d744637e07bc6addaa4e6
Handle null id for Cars/Details action
aromdee04/tdd-carfuel,aromdee04/tdd-carfuel,aromdee04/tdd-carfuel
CarFuel/Controllers/CarsController.cs
CarFuel/Controllers/CarsController.cs
using CarFuel.Models; using CarFuel.Services; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Microsoft.AspNet.Identity; using CarFuel.DataAccess; using System.Net; namespace CarFuel.Controllers { public class CarsController : Controller { //private static List<Car> cars = new List<Car>(); private ICarDb db; private CarService carService; public CarsController() { db = new CarDb(); carService = new CarService(db); } [Authorize] public ActionResult Index() { var userId = new Guid(User.Identity.GetUserId()); IEnumerable<Car> cars = carService.GetCarsByMember(userId); return View(cars); } [Authorize] public ActionResult Create() { return View(); } [HttpPost] [Authorize] public ActionResult Create(Car item) { var userId = new Guid(User.Identity.GetUserId()); try { carService.AddCar(item, userId); } catch (OverQuotaException ex) { TempData["error"] = ex.Message; } return RedirectToAction("Index"); } public ActionResult Details(Guid? Id) { if (Id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadGateway); } var userId = new Guid(User.Identity.GetUserId()); var c = carService.GetCarsByMember(userId).SingleOrDefault(x => x.Id == Id); return View(c); } } }
using CarFuel.Models; using CarFuel.Services; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Microsoft.AspNet.Identity; using CarFuel.DataAccess; namespace CarFuel.Controllers { public class CarsController : Controller { //private static List<Car> cars = new List<Car>(); private ICarDb db; private CarService carService; public CarsController() { db = new CarDb(); carService = new CarService(db); } [Authorize] public ActionResult Index() { var userId = new Guid(User.Identity.GetUserId()); IEnumerable<Car> cars = carService.GetCarsByMember(userId); return View(cars); } [Authorize] public ActionResult Create() { return View(); } [HttpPost] [Authorize] public ActionResult Create(Car item) { var userId = new Guid(User.Identity.GetUserId()); try { carService.AddCar(item, userId); } catch (OverQuotaException ex) { TempData["error"] = ex.Message; } return RedirectToAction("Index"); } public ActionResult Details(Guid Id) { var userId = new Guid(User.Identity.GetUserId()); var c = carService.GetCarsByMember(userId).SingleOrDefault(x => x.Id == Id); return View(c); } } }
mit
C#
aecfd114000c3f9978ea31d4aedd81bdb23c4a9b
Fix typos in Interactivity enum.
Alan-Lun/git-p3
Cli-CredentialHelper/Interactivity.cs
Cli-CredentialHelper/Interactivity.cs
namespace Microsoft.TeamFoundation.CredentialHelper { /// <summary> /// Level of interactivity allowed and enabled. /// </summary> internal enum Interactivity { /// <summary> /// Present an interactive logon prompt when necessary, otherwise use cached credentials /// </summary> Auto, /// <summary> /// Always present an interactive logon prompt regardless if cached credentials exist /// </summary> Always, /// <summary> /// Never present an present an interactive logon prompt, fail without cached credentials /// </summary> Never } }
namespace Microsoft.TeamFoundation.CredentialHelper { /// <summary> /// Level of interactivity allowed and enabled. /// </summary> internal enum Interactivity { /// <summary> /// Present an interactive logon prompt when necissary, otherwise used cached credentials /// </summary> Auto, /// <summary> /// Always present an interactive logon prompt regardless of if cached credentials exist /// </summary> Always, /// <summary> /// Never present an present an interactive logon prompt, fail without cached credentals /// </summary> Never } }
mit
C#
32c5cab5ad4ce7043d3c27cded2929775794d528
Make AliasMatcher implement IAliasMatcher
appharbor/appharbor-cli
src/AppHarbor/AliasMatcher.cs
src/AppHarbor/AliasMatcher.cs
using System; namespace AppHarbor { public class AliasMatcher : IAliasMatcher { public Type GetMatchedType(string commandArgument) { throw new NotImplementedException(); } } }
namespace AppHarbor { public class AliasMatcher { } }
mit
C#
e76eb1641a28232570398124ee7b9a9b8f38d134
Address review comment.
github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql
csharp/extractor/Semmle.Extraction/Symbol.cs
csharp/extractor/Semmle.Extraction/Symbol.cs
namespace Semmle.Extraction { /// <summary> /// An abstract symbol, which encapsulates a data type (such as a C# symbol). /// </summary> /// <typeparam name="Initializer">The type of the symbol.</typeparam> public abstract class CachedEntity<Initializer> : ICachedEntity { public CachedEntity(Context context, Initializer init) { Context = context; symbol = init; } public Label Label { get; set; } public abstract Microsoft.CodeAnalysis.Location ReportingLocation { get; } public override string ToString() => Label.ToString(); public abstract void Populate(); public Context Context { get; private set; } public Initializer symbol { get; private set; } object ICachedEntity.UnderlyingObject => symbol; public abstract IId Id { get; } public abstract bool NeedsPopulation { get; } /// <summary> /// Runs the given action <paramref name="a"/>, guarding for trap duplication /// based on the ID an location of this entity. /// </summary> protected void WithDuplicationGuard(System.Action a, IEntity location) { var key = new Key(this, location); Context.WithDuplicationGuard(key, a); } public override int GetHashCode() => symbol.GetHashCode(); public override bool Equals(object obj) { var other = obj as CachedEntity<Initializer>; return other?.GetType() == GetType() && Equals(other.symbol, symbol); } public abstract TrapStackBehaviour TrapStackBehaviour { get; } } }
namespace Semmle.Extraction { /// <summary> /// An abstract symbol, which encapsulates a data type (such as a C# symbol). /// </summary> /// <typeparam name="Initializer">The type of the symbol.</typeparam> public abstract class CachedEntity<Initializer> : ICachedEntity { public CachedEntity(Context context, Initializer init) { Context = context; symbol = init; } public Label Label { get; set; } public abstract Microsoft.CodeAnalysis.Location ReportingLocation { get; } public override string ToString() => Label.ToString(); public abstract void Populate(); public Context Context { get; private set; } public Initializer symbol { get; private set; } object ICachedEntity.UnderlyingObject => symbol; public abstract IId Id { get; } public abstract bool NeedsPopulation { get; } /// <summary> /// Runs the given action <paramref name="a"/>, guarding for trap duplication /// based on the ID an location of this entity. /// </summary> protected void WithDuplicationGuard(System.Action a, IEntity location) { var key = new Key(this, location); Context.WithDuplicationGuard(key, a); } public override int GetHashCode() => symbol.GetHashCode(); public override bool Equals(object obj) { var other = obj as CachedEntity<Initializer>; return other != null && other.GetType() == GetType() && Equals(other.symbol, symbol); } public abstract TrapStackBehaviour TrapStackBehaviour { get; } } }
mit
C#
8f4b3131d9faff844bf4ea128aacbb53f5e076b0
remove Test from test names
jgraber/ForgetTheMilk,jgraber/ForgetTheMilk,jgraber/ForgetTheMilk
ForgetTheMilk/ConsoleVerification/CreateTaskTests.cs
ForgetTheMilk/ConsoleVerification/CreateTaskTests.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using ForgetTheMilk.Controllers; using NUnit.Framework; namespace ConsoleVerification { public class CreateTaskTests : AssertionHelper { [Test] public void DescriptionAndNoDueDate() { var input = "Pickup the groceries"; var task = new Task(input, default(DateTime)); Expect(task.Description, Is.EqualTo(input)); Assert.AreEqual(null, task.DueDate); } [Test] public void MayDueDateDoesWrapYear() { var input = "Pickup the groceries may 5 - as of 2015-05-31"; var today = new DateTime(2015, 5, 31); var task = new Task(input, today); Expect(task.DueDate, Is.EqualTo(new DateTime(2016, 5, 5))); } [Test] public void MayDueDateDoesNotWrapYear() { var input = "Pickup the groceries may 5 - as of 2015-05-04"; var today = new DateTime(2015, 5, 4); var task = new Task(input, today); Expect(task.DueDate, Is.EqualTo(new DateTime(DateTime.Today.Year, 5, 5))); } [Test] [TestCase("Groceries jan 5", 1)] [TestCase("Groceries feb 5", 2)] [TestCase("Groceries mar 5", 3)] [TestCase("Groceries apr 5", 4)] [TestCase("Groceries may 5", 5)] [TestCase("Groceries jun 5", 6)] [TestCase("Groceries jul 5", 7)] [TestCase("Groceries aug 5", 8)] [TestCase("Groceries sep 5", 9)] [TestCase("Groceries oct 5", 10)] [TestCase("Groceries nov 5", 11)] [TestCase("Groceries dec 5", 12)] public void DueDate(string input, int expectedMonth) { var today = new DateTime(2015, 5, 31); var task = new Task(input, today); Expect(task.DueDate, Is.Not.Null); Expect(task.DueDate.Value.Month, Is.EqualTo(expectedMonth)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using ForgetTheMilk.Controllers; using NUnit.Framework; namespace ConsoleVerification { public class CreateTaskTests : AssertionHelper { [Test] public void TestDescriptionAndNoDueDate() { var input = "Pickup the groceries"; var task = new Task(input, default(DateTime)); Expect(task.Description, Is.EqualTo(input)); Assert.AreEqual(null, task.DueDate); } [Test] public void TestMayDueDateDoesWrapYear() { var input = "Pickup the groceries may 5 - as of 2015-05-31"; var today = new DateTime(2015, 5, 31); var task = new Task(input, today); Expect(task.DueDate, Is.EqualTo(new DateTime(2016, 5, 5))); } [Test] public void TestMayDueDateDoesNotWrapYear() { var input = "Pickup the groceries may 5 - as of 2015-05-04"; var today = new DateTime(2015, 5, 4); var task = new Task(input, today); Expect(task.DueDate, Is.EqualTo(new DateTime(DateTime.Today.Year, 5, 5))); } [Test] [TestCase("Groceries jan 5", 1)] [TestCase("Groceries feb 5", 2)] [TestCase("Groceries mar 5", 3)] [TestCase("Groceries apr 5", 4)] [TestCase("Groceries may 5", 5)] [TestCase("Groceries jun 5", 6)] [TestCase("Groceries jul 5", 7)] [TestCase("Groceries aug 5", 8)] [TestCase("Groceries sep 5", 9)] [TestCase("Groceries oct 5", 10)] [TestCase("Groceries nov 5", 11)] [TestCase("Groceries dec 5", 12)] public void DueDate(string input, int expectedMonth) { var today = new DateTime(2015, 5, 31); var task = new Task(input, today); Expect(task.DueDate, Is.Not.Null); Expect(task.DueDate.Value.Month, Is.EqualTo(expectedMonth)); } } }
apache-2.0
C#
b63b71ab30e897c4a7d5064829cdb3c8688fd144
Add a test that actually validates if keys are set as expected.
keenlabs/keen-sdk-net
Keen.NetStandard.Test/ProjectSettingsProviderTest.cs
Keen.NetStandard.Test/ProjectSettingsProviderTest.cs
using System; using NUnit.Framework; namespace Keen.NetStandard.Tests { [TestFixture] class ProjectSettingsProviderTest { [Test] public void Settings_DefaultInputs_Success() { Assert.DoesNotThrow(() => new ProjectSettingsProvider("X", null)); } [Test] public void Settings_AllNull_Success() { Assert.DoesNotThrow(() => new ProjectSettingsProvider(null)); } [Test] public void SettingsProviderEnv_VarsNotSet_Throws() { Environment.SetEnvironmentVariable(KeenConstants.KeenProjectId, null); Environment.SetEnvironmentVariable(KeenConstants.KeenMasterKey, null); Environment.SetEnvironmentVariable(KeenConstants.KeenWriteKey, null); Environment.SetEnvironmentVariable(KeenConstants.KeenReadKey, null); var settings = new ProjectSettingsProviderEnv(); Assert.Throws<KeenException>(() => new KeenClient(settings)); } [Test] public void SettingsProviderEnv_VarsSet_Success() { Environment.SetEnvironmentVariable(KeenConstants.KeenProjectId, "X"); Environment.SetEnvironmentVariable(KeenConstants.KeenMasterKey, "X"); Environment.SetEnvironmentVariable(KeenConstants.KeenWriteKey, "X"); Environment.SetEnvironmentVariable(KeenConstants.KeenReadKey, "X"); var settings = new ProjectSettingsProviderEnv(); Assert.DoesNotThrow(() => new KeenClient(settings)); } [Test] public void SettingsProviderEnv_VarsSet_SettingsAreCorrect() { var projectId = "projectId"; var masterKey = "masterKey"; var writeKey = "writeKey"; var readKey = "readKey"; Environment.SetEnvironmentVariable(KeenConstants.KeenProjectId, projectId); Environment.SetEnvironmentVariable(KeenConstants.KeenMasterKey, masterKey); Environment.SetEnvironmentVariable(KeenConstants.KeenWriteKey, writeKey); Environment.SetEnvironmentVariable(KeenConstants.KeenReadKey, readKey); var settings = new ProjectSettingsProviderEnv(); Assert.AreEqual(settings.ProjectId, projectId, "Project id wasn't properly set"); Assert.AreEqual(settings.MasterKey, masterKey, "Master key wasn't properly set"); Assert.AreEqual(settings.WriteKey, writeKey, "Write key wasn't properly set"); Assert.AreEqual(settings.ReadKey, readKey, "Read key wasn't properly set"); } } }
using System; using NUnit.Framework; namespace Keen.NetStandard.Tests { [TestFixture] class ProjectSettingsProviderTest { [Test] public void Settings_DefaultInputs_Success() { Assert.DoesNotThrow(() => new ProjectSettingsProvider("X", null)); } [Test] public void Settings_AllNull_Success() { Assert.DoesNotThrow(() => new ProjectSettingsProvider(null)); } [Test] public void SettingsProviderEnv_VarsNotSet_Throws() { Environment.SetEnvironmentVariable(KeenConstants.KeenProjectId, null); Environment.SetEnvironmentVariable(KeenConstants.KeenMasterKey, null); Environment.SetEnvironmentVariable(KeenConstants.KeenWriteKey, null); Environment.SetEnvironmentVariable(KeenConstants.KeenReadKey, null); var settings = new ProjectSettingsProviderEnv(); Assert.Throws<KeenException>(() => new KeenClient(settings)); } [Test] public void SettingsProviderEnv_VarsSet_Success() { Environment.SetEnvironmentVariable(KeenConstants.KeenProjectId, "X"); Environment.SetEnvironmentVariable(KeenConstants.KeenMasterKey, "X"); Environment.SetEnvironmentVariable(KeenConstants.KeenWriteKey, "X"); Environment.SetEnvironmentVariable(KeenConstants.KeenReadKey, "X"); var settings = new ProjectSettingsProviderEnv(); Assert.DoesNotThrow(() => new KeenClient(settings)); } } }
mit
C#
157f42d16f4632a85ca96b1c07dc3b1c0c99b16c
Update ObjectFillerTest.cs
blmeyers/ObjectFiller.NET,DoubleLinePartners/ObjectFiller.NET,Tynamix/ObjectFiller.NET,HerrLoesch/ObjectFiller.NET
ObjectFiller.Test/ObjectFillerTest.cs
ObjectFiller.Test/ObjectFillerTest.cs
using System; using System.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; using ObjectFiller.Test.TestPoco.Person; using Tynamix.ObjectFiller; namespace ObjectFiller.Test { [TestClass] public class ObjectFillerTest { [TestMethod] public void TestFillPerson() { Person p = new Person(); Filler<Person> filler = new Filler<Person>(); filler.Setup() .OnType<IAddress>().CreateInstanceOf<Address>() .OnType<string>().Use(new MnemonicString(10)) .OnProperty(person => person.FirstName).Use(new MnemonicString(1)) .OnProperty(person => person.LastName).Use(new RandomListItem<string>(new List<string>() { "Maik", "Tom", "Anton" })) .OnProperty(person => person.Age).Use(() => new Random().Next(12, 83)) .SetupFor<Address>() .OnProperty(x => x.City, x => x.Country).IgnoreIt(); Person pFilled = filler.Fill(p); } } }
using System; using System.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; using ObjectFiller.Test.TestPoco.Person; using Tynamix.ObjectFiller; namespace ObjectFiller.Test { [TestClass] public class ObjectFillerTest { [TestMethod] public void TestFillPerson() { Person p = new Person(); Filler<Person> filler = new Filler<Person>(); filler.Setup() .OnType<IAddress>().Register<Address>() .OnType<string>().Use(new MnemonicString(10)) .OnProperty(person => person.FirstName).Use(new MnemonicString(1)) .OnProperty(person => person.LastName).Use(new RandomListItem<string>(new List<string>() { "Maik", "Tom", "Anton" })) .OnProperty(person => person.Age).Use(() => new Random().Next(12, 83)) .SetupFor<Address>() .OnProperty(x => x.City, x => x.Country).IgnoreIt(); Person pFilled = filler.Fill(p); } } }
mit
C#
f160904f2088478c6eff12769a3ae2963ce6e4ee
Add integration test for same.
marek-vysoky/box-windows-sdk-v2,box/box-windows-sdk-v2,iLovebooks100per/box-windows-sdk-v2,varungu/box-windows-sdk-v2,JogyBlack/box-windows-sdk-v2,themanfrommsu/Box1
Box.V2.Test.Integration/BoxUsersManagerTestIntegration.cs
Box.V2.Test.Integration/BoxUsersManagerTestIntegration.cs
using System; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using Box.V2.Models; using System.Threading.Tasks; namespace Box.V2.Test.Integration { [TestClass] public class BoxUsersManagerTestIntegration : BoxResourceManagerTestIntegration { [TestMethod] public async Task UsersInformation_LiveSession_ValidResponse() { BoxUser user = await _client.UsersManager.GetCurrentUserInformationAsync(); Assert.AreEqual("215917383", user.Id); Assert.AreEqual("Box Windows", user.Name); Assert.AreEqual("boxwinintegration@gmail.com", user.Login, true); } [TestMethod] public async Task EnterpriseUsersInformation_LiveSession_ValidResponse() { BoxCollection<BoxUser> users = await _client.UsersManager.GetEnterpriseUsersAsync("jhoerr"); Assert.AreEqual(users.TotalCount, 1); Assert.AreEqual(users.Entries.First().Name, "John Hoerr"); Assert.AreEqual(users.Entries.First().Login, "jhoerr@iu.edu"); } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using Box.V2.Models; using System.Threading.Tasks; namespace Box.V2.Test.Integration { [TestClass] public class BoxUsersManagerTestIntegration : BoxResourceManagerTestIntegration { [TestMethod] public async Task UsersInformation_LiveSession_ValidResponse() { BoxUser user = await _client.UsersManager.GetCurrentUserInformationAsync(); Assert.AreEqual("215917383", user.Id); Assert.AreEqual("Box Windows", user.Name); Assert.AreEqual("boxwinintegration@gmail.com", user.Login, true); } } }
apache-2.0
C#
bf85f4affb1eca46513b17dd2442b40df78cce32
Fix editor crashing when loading a beatmap for an unsupported ruleset
peppy/osu-new,smoogipoo/osu,peppy/osu,UselessToucan/osu,NeoAdonis/osu,ppy/osu,peppy/osu,smoogipoo/osu,UselessToucan/osu,ppy/osu,smoogipoo/osu,johnneijzen/osu,EVAST9919/osu,smoogipooo/osu,UselessToucan/osu,johnneijzen/osu,NeoAdonis/osu,NeoAdonis/osu,2yangk23/osu,peppy/osu,2yangk23/osu,ppy/osu,EVAST9919/osu
osu.Game/Screens/Edit/Compose/ComposeScreen.cs
osu.Game/Screens/Edit/Compose/ComposeScreen.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.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Rulesets.Edit; using osu.Game.Screens.Edit.Compose.Components.Timeline; using osu.Game.Skinning; namespace osu.Game.Screens.Edit.Compose { public class ComposeScreen : EditorScreenWithTimeline { private HitObjectComposer composer; protected override Drawable CreateMainContent() { var ruleset = Beatmap.Value.BeatmapInfo.Ruleset?.CreateInstance(); composer = ruleset?.CreateHitObjectComposer(); if (ruleset == null || composer == null) return new ScreenWhiteBox.UnderConstructionMessage(ruleset == null ? "This beatmap" : $"{ruleset.Description}'s composer"); var beatmapSkinProvider = new BeatmapSkinProvidingContainer(Beatmap.Value.Skin); // the beatmapSkinProvider is used as the fallback source here to allow the ruleset-specific skin implementation // full access to all skin sources. var rulesetSkinProvider = new SkinProvidingContainer(ruleset.CreateLegacySkinProvider(beatmapSkinProvider)); // load the skinning hierarchy first. // this is intentionally done in two stages to ensure things are in a loaded state before exposing the ruleset to skin sources. return beatmapSkinProvider.WithChild(rulesetSkinProvider.WithChild(composer)); } protected override Drawable CreateTimelineContent() => composer == null ? base.CreateTimelineContent() : new TimelineHitObjectDisplay(composer.EditorBeatmap); } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Rulesets.Edit; using osu.Game.Screens.Edit.Compose.Components.Timeline; using osu.Game.Skinning; namespace osu.Game.Screens.Edit.Compose { public class ComposeScreen : EditorScreenWithTimeline { private HitObjectComposer composer; protected override Drawable CreateMainContent() { var ruleset = Beatmap.Value.BeatmapInfo.Ruleset?.CreateInstance(); composer = ruleset?.CreateHitObjectComposer(); if (ruleset == null || composer == null) return new ScreenWhiteBox.UnderConstructionMessage(ruleset == null ? "This beatmap" : $"{ruleset.Description}'s composer"); var beatmapSkinProvider = new BeatmapSkinProvidingContainer(Beatmap.Value.Skin); // the beatmapSkinProvider is used as the fallback source here to allow the ruleset-specific skin implementation // full access to all skin sources. var rulesetSkinProvider = new SkinProvidingContainer(ruleset.CreateLegacySkinProvider(beatmapSkinProvider)); // load the skinning hierarchy first. // this is intentionally done in two stages to ensure things are in a loaded state before exposing the ruleset to skin sources. return beatmapSkinProvider.WithChild(rulesetSkinProvider.WithChild(composer)); } protected override Drawable CreateTimelineContent() => new TimelineHitObjectDisplay(composer.EditorBeatmap); } }
mit
C#
8da499fb0fc1b1e0febcac88cccda792707a5da6
Add proper test coverage
peppy/osu,ppy/osu,peppy/osu,peppy/osu,ppy/osu,ppy/osu
osu.Game.Tests/Visual/Online/TestSceneExternalLinkButton.cs
osu.Game.Tests/Visual/Online/TestSceneExternalLinkButton.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. #nullable disable using osu.Framework.Graphics; using osu.Game.Graphics.Cursor; using osu.Game.Graphics.UserInterface; using osuTK; namespace osu.Game.Tests.Visual.Online { public class TestSceneExternalLinkButton : OsuTestScene { public TestSceneExternalLinkButton() { Child = new OsuContextMenuContainer { RelativeSizeAxes = Axes.Both, Child = new ExternalLinkButton("https://osu.ppy.sh/home") { Size = new Vector2(50), Anchor = Anchor.Centre, Origin = Anchor.Centre, } }; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable disable using osu.Game.Graphics.UserInterface; using osuTK; namespace osu.Game.Tests.Visual.Online { public class TestSceneExternalLinkButton : OsuTestScene { public TestSceneExternalLinkButton() { Child = new ExternalLinkButton("https://osu.ppy.sh/home") { Size = new Vector2(50) }; } } }
mit
C#
c2bdce80c9da0fab181b6b87b4a0eb3da8c65d51
Use FFXIResourceManager.GetAreaName() instead of relying on the special behaviour of FFXIResourceManager.GetResourceString().
graspee/polutils,Vicrelant/polutils,graspee/polutils,Vicrelant/polutils
PlayOnline.FFXI.Utils.StrangeApparatus/MainWindow.cs
PlayOnline.FFXI.Utils.StrangeApparatus/MainWindow.cs
// $Id$ // Copyright 2004-2010 Tim Van Holder // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. // You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" // BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and limitations under the License. using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using PlayOnline.Core; using PlayOnline.FFXI; namespace PlayOnline.FFXI.Utils.StrangeApparatus { public partial class MainWindow : Form { public MainWindow() { this.InitializeComponent(); } // The values to add to the digits do not match the element numbers used in the item data, // but instead match the order of the days (FEWWILLDie). private byte[] ElementOffsets = new byte[] { 0, 3, 5, 2, 1, 4, 6, 7 }; // The area numbers where the strange apparatuses are located. private ushort[] AreaIDs = new ushort[] { 191, 196, 197, 193, 195, 194, 200, 198 }; private void btnGenerateCodes_Click(object sender, EventArgs e) { this.lvCodes.Items.Clear(); if (this.txtCharacterName.Text.Length < 3) { MessageBox.Show(this, I18N.GetText("Dialog:NameTooShort"), I18N.GetText("Title:NameTooShort"), MessageBoxButtons.OK, MessageBoxIcon.Error); return; } byte[] Digits = new byte[4]; for (byte i = 0; i < 3; ++i) { char C = Char.ToUpperInvariant(this.txtCharacterName.Text[i]); if (C < 'A' || C > 'Z') { MessageBox.Show(this, I18N.GetText("Dialog:InvalidName"), I18N.GetText("Title:InvalidName"), MessageBoxButtons.OK, MessageBoxIcon.Error); return; } Digits[i] = (byte) (C - 'A'); } Digits[3] = (byte) ((Digits[0] + Digits[1] + Digits[2]) % 100); for (byte i = 0; i < 8; ++i) { ListViewItem LVI = this.lvCodes.Items.Add(FFXIResourceManager.GetAreaName(this.AreaIDs[i])); LVI.SubItems.Add(new NamedEnum((Element) this.ElementOffsets[i]).ToString()); LVI.SubItems.Add(new NamedEnum((ElementColor) this.ElementOffsets[i]).ToString()); LVI.SubItems.Add(String.Format("{0:00}{1:00}{2:00}{3:00}", Digits[0] + i, Digits[1] + i, Digits[2] + i, (Digits[3] + 4 * i) % 100)); } } } }
// $Id$ // Copyright 2004-2010 Tim Van Holder // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. // You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" // BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and limitations under the License. using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using PlayOnline.Core; using PlayOnline.FFXI; namespace PlayOnline.FFXI.Utils.StrangeApparatus { public partial class MainWindow : Form { public MainWindow() { this.InitializeComponent(); } // The values to add to the digits do not match the element numbers used in the item data, // but instead match the order of the days (FEWWILLDie). private byte[] ElementOffsets = new byte[] { 0, 3, 5, 2, 1, 4, 6, 7 }; // The area numbers where the strange apparatuses are located. private byte[] AreaIDs = new byte[] { 191, 196, 197, 193, 195, 194, 200, 198 }; private void btnGenerateCodes_Click(object sender, EventArgs e) { this.lvCodes.Items.Clear(); if (this.txtCharacterName.Text.Length < 3) { MessageBox.Show(this, I18N.GetText("Dialog:NameTooShort"), I18N.GetText("Title:NameTooShort"), MessageBoxButtons.OK, MessageBoxIcon.Error); return; } byte[] Digits = new byte[4]; for (byte i = 0; i < 3; ++i) { char C = Char.ToUpperInvariant(this.txtCharacterName.Text[i]); if (C < 'A' || C > 'Z') { MessageBox.Show(this, I18N.GetText("Dialog:InvalidName"), I18N.GetText("Title:InvalidName"), MessageBoxButtons.OK, MessageBoxIcon.Error); return; } Digits[i] = (byte) (C - 'A'); } Digits[3] = (byte) ((Digits[0] + Digits[1] + Digits[2]) % 100); for (byte i = 0; i < 8; ++i) { ListViewItem LVI = this.lvCodes.Items.Add(FFXIResourceManager.GetResourceString(0x00020000U + this.AreaIDs[i])); LVI.SubItems.Add(new NamedEnum((Element) this.ElementOffsets[i]).ToString()); LVI.SubItems.Add(new NamedEnum((ElementColor) this.ElementOffsets[i]).ToString()); LVI.SubItems.Add(String.Format("{0:00}{1:00}{2:00}{3:00}", Digits[0] + i, Digits[1] + i, Digits[2] + i, (Digits[3] + 4 * i) % 100)); } } } }
apache-2.0
C#
e37b34c96a246190e7d413f168ae7610bced7155
add extension method
aritchie/bluetoothle,aritchie/bluetoothle
Plugin.BluetoothLE.Abstractions/Extensions_Device.cs
Plugin.BluetoothLE.Abstractions/Extensions_Device.cs
using System; using System.Reactive.Linq; namespace Plugin.BluetoothLE { public static partial class Extensions { public static IObservable<IGattCharacteristic> GetKnownCharacteristics(this IDevice device, Guid serviceUuid, params Guid[] characteristicIds) => device .GetKnownService(serviceUuid) .FirstOrDefaultAsync() .SelectMany(x => x.GetKnownCharacteristics(characteristicIds)); public static IObservable<IGattCharacteristic> WhenAnyCharacteristicDiscovered(this IDevice device) => device.WhenServiceDiscovered().SelectMany(x => x.WhenCharacteristicDiscovered()); public static IObservable<IGattDescriptor> WhenAnyDescriptorDiscovered(this IDevice device) => device.WhenAnyCharacteristicDiscovered().SelectMany(x => x.WhenDescriptorDiscovered()); public static bool IsPairingAvailable(this IDevice device) => device.Features.HasFlag(DeviceFeatures.PairingRequests); public static bool IsMtuRequestAvailable(this IDevice device) => device.Features.HasFlag(DeviceFeatures.MtuRequests); public static bool IsReliableTransactionsAvailable(this IDevice device) => device.Features.HasFlag(DeviceFeatures.ReliableTransactions); } }
using System; using System.Reactive.Linq; namespace Plugin.BluetoothLE { public static partial class Extensions { public static IObservable<IGattCharacteristic> WhenAnyCharacteristicDiscovered(this IDevice device) { return device.WhenServiceDiscovered().SelectMany(x => x.WhenCharacteristicDiscovered()); } public static IObservable<IGattDescriptor> WhenAnyDescriptorDiscovered(this IDevice device) { return device.WhenAnyCharacteristicDiscovered().SelectMany(x => x.WhenDescriptorDiscovered()); } public static bool IsPairingAvailable(this IDevice device) { return device.Features.HasFlag(DeviceFeatures.PairingRequests); } public static bool IsMtuRequestAvailable(this IDevice device) { return device.Features.HasFlag(DeviceFeatures.MtuRequests); } public static bool IsReliableTransactionsAvailable(this IDevice device) { return device.Features.HasFlag(DeviceFeatures.ReliableTransactions); } } }
mit
C#
cee79d0c3aa9fb23c0df65d905dc81411355870e
remove buffer clear
ntent-ad/Metrics.NET,DeonHeyns/Metrics.NET,mnadel/Metrics.NET,alhardy/Metrics.NET,Liwoj/Metrics.NET,Liwoj/Metrics.NET,MetaG8/Metrics.NET,etishor/Metrics.NET,mnadel/Metrics.NET,alhardy/Metrics.NET,cvent/Metrics.NET,MetaG8/Metrics.NET,DeonHeyns/Metrics.NET,huoxudong125/Metrics.NET,huoxudong125/Metrics.NET,Recognos/Metrics.NET,cvent/Metrics.NET,etishor/Metrics.NET,Recognos/Metrics.NET,MetaG8/Metrics.NET,ntent-ad/Metrics.NET
Src/Metrics/Reporters/StringReport.cs
Src/Metrics/Reporters/StringReport.cs
using System; using System.Text; using System.Threading; using Metrics.MetricData; namespace Metrics.Reporters { public class StringReport : HumanReadableReport { public static string RenderMetrics(MetricsData metricsData, Func<HealthStatus> healthStatus) { var report = new StringReport(); report.RunReport(metricsData, healthStatus, CancellationToken.None); return report.Result; } private StringBuilder buffer = null; protected override void StartReport(string contextName, DateTime timestamp) { this.buffer = new StringBuilder(); base.StartReport(contextName, timestamp); } protected override void WriteLine(string line, params string[] args) { this.buffer.AppendLine(string.Format(line, args)); } protected override void EndReport(string contextName, DateTime timestamp) { base.EndReport(contextName, timestamp); } public string Result { get { return this.buffer.ToString(); } } } }
using System; using System.Text; using System.Threading; using Metrics.MetricData; namespace Metrics.Reporters { public class StringReport : HumanReadableReport { public static string RenderMetrics(MetricsData metricsData, Func<HealthStatus> healthStatus) { var report = new StringReport(); report.RunReport(metricsData, healthStatus, CancellationToken.None); return report.Result; } private StringBuilder buffer = null; protected override void StartReport(string contextName, DateTime timestamp) { this.buffer = new StringBuilder(); base.StartReport(contextName, timestamp); } protected override void WriteLine(string line, params string[] args) { this.buffer.AppendLine(string.Format(line, args)); } protected override void EndReport(string contextName, DateTime timestamp) { base.EndReport(contextName, timestamp); this.buffer = null; } public string Result { get { return this.buffer.ToString(); } } } }
apache-2.0
C#
93dbfd14826a4eec1f2c30a5f72d588da4f6420a
Make Master/Detail sample not rely on WPF magic
canton7/Stylet,canton7/Stylet
Samples/Stylet.Samples.MasterDetail/EmployeeModel.cs
Samples/Stylet.Samples.MasterDetail/EmployeeModel.cs
using System; namespace Stylet.Samples.MasterDetail { public class EmployeeModel : PropertyChangedBase { private string _name; public string Name { get { return this._name; } set { this.SetAndNotify(ref this._name, value); } } } }
using System; namespace Stylet.Samples.MasterDetail { public class EmployeeModel { public string Name { get; set; } } }
mit
C#
65c80434d83b500e46aad3c66e34a099c1445cc6
Update demo
sunkaixuan/SqlSugar
Src/Asp.NetCore2/SqlSeverTest/SqlSeverTest/Config.cs
Src/Asp.NetCore2/SqlSeverTest/SqlSeverTest/Config.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OrmTest { /// <summary> /// Setting up the database name does not require you to create the database /// 设置好数据库名不需要你去手动建库 /// </summary> public class Config { /// <summary> /// Account have permission to create database /// 用有建库权限的数据库账号 /// </summary> public static string ConnectionString = "server=.;uid=sa;pwd=@jhl85661501;database=SQLSUGAR4XTEST"; /// <summary> /// Account have permission to create database /// 用有建库权限的数据库账号 /// </summary> public static string ConnectionString2 = "server=.;uid=sa;pwd==@jhl85661501;database=SQLSUGAR4XTEST2"; /// <summary> /// Account have permission to create database /// 用有建库权限的数据库账号 /// </summary> public static string ConnectionString3 = "server=.;uid=sa;pwd==@jhl85661501;database=SQLSUGAR4XTEST3"; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OrmTest { /// <summary> /// Setting up the database name does not require you to create the database /// 设置好数据库名不需要你去手动建库 /// </summary> public class Config { /// <summary> /// Account have permission to create database /// 用有建库权限的数据库账号 /// </summary> public static string ConnectionString = "server=.;uid=sa;pwd=haosql;database=SQLSUGAR4XTEST"; /// <summary> /// Account have permission to create database /// 用有建库权限的数据库账号 /// </summary> public static string ConnectionString2 = "server=.;uid=sa;pwd=haosql;database=SQLSUGAR4XTEST2"; /// <summary> /// Account have permission to create database /// 用有建库权限的数据库账号 /// </summary> public static string ConnectionString3 = "server=.;uid=sa;pwd=haosql;database=SQLSUGAR4XTEST3"; } }
apache-2.0
C#
e59ad9a5971adc1cb16c81af04cb8f0829193631
expand to container
darrenkopp/SassyStudio
SassyStudio.2012/Intellisense/CompletionContextBuilder.cs
SassyStudio.2012/Intellisense/CompletionContextBuilder.cs
using System.Collections.Generic; using System.ComponentModel.Composition; using Microsoft.VisualStudio.Text; using SassyStudio.Compiler.Parsing; using SassyStudio.Editor; namespace SassyStudio.Intellisense { interface ICompletionContextBuilder { SassCompletionContext Create(ITrackingSpan span, SassEditorDocument document); } [Export(typeof(ICompletionContextBuilder))] class CompletionContextBuilder : ICompletionContextBuilder { public SassCompletionContext Create(ITrackingSpan span, SassEditorDocument document) { var tree = document.Tree; var text = new SnapshotTextProvider(tree.SourceText); var position = span.GetStartPoint(tree.SourceText).Position; var current = tree.Items.FindItemContainingPosition(position); if (current != null && current is TokenItem) current = current.Parent; var path = CreateTraversalPath(current); return new SassCompletionContext(tree.SourceText, span, current, path); } static IEnumerable<ComplexItem> CreateTraversalPath(ParseItem item) { var path = new LinkedList<ComplexItem>(); if (item == null) return path; Logger.Log(string.Format("Current Type: {0}", item.GetType().Name)); var current = (item as ComplexItem) ?? item.Parent; while (current != null) { path.AddLast(current); current = current.Parent; } return path; } } }
using System.Collections.Generic; using System.ComponentModel.Composition; using Microsoft.VisualStudio.Text; using SassyStudio.Compiler.Parsing; using SassyStudio.Editor; namespace SassyStudio.Intellisense { interface ICompletionContextBuilder { SassCompletionContext Create(ITrackingSpan span, SassEditorDocument document); } [Export(typeof(ICompletionContextBuilder))] class CompletionContextBuilder : ICompletionContextBuilder { public SassCompletionContext Create(ITrackingSpan span, SassEditorDocument document) { var tree = document.Tree; var text = new SnapshotTextProvider(tree.SourceText); var position = span.GetStartPoint(tree.SourceText).Position; var current = tree.Items.FindItemContainingPosition(position); var path = CreateTraversalPath(current); return new SassCompletionContext(tree.SourceText, span, current, path); } static IEnumerable<ComplexItem> CreateTraversalPath(ParseItem item) { var path = new LinkedList<ComplexItem>(); if (item == null) return path; Logger.Log(string.Format("Current Type: {0}", item.GetType().Name)); var current = (item as ComplexItem) ?? item.Parent; while (current != null) { path.AddLast(current); current = current.Parent; } return path; } } }
mit
C#
ca08a19c409e4a454a0d6a66d7ce57d2ea845228
Rename mod to modIcon
NeoAdonis/osu,ppy/osu,peppy/osu-new,ppy/osu,smoogipoo/osu,peppy/osu,UselessToucan/osu,smoogipoo/osu,smoogipoo/osu,peppy/osu,UselessToucan/osu,UselessToucan/osu,smoogipooo/osu,peppy/osu,NeoAdonis/osu,NeoAdonis/osu,ppy/osu
osu.Game.Tournament/Components/TournamentModDisplay.cs
osu.Game.Tournament/Components/TournamentModDisplay.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.Linq; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Sprites; using osu.Framework.Graphics.Textures; using osu.Game.Rulesets; using osu.Game.Rulesets.UI; using osu.Game.Tournament.Models; using osuTK; namespace osu.Game.Tournament.Components { public class TournamentModDisplay : CompositeDrawable { public string ModAcronym; [Resolved] private LadderInfo ladderInfo { get; set; } [Resolved] private RulesetStore rulesets { get; set; } [BackgroundDependencyLoader] private void load(TextureStore textures) { var texture = textures.Get($"mods/{ModAcronym}"); if (texture != null) { AddInternal(new Sprite { FillMode = FillMode.Fit, RelativeSizeAxes = Axes.Both, Anchor = Anchor.CentreRight, Origin = Anchor.CentreRight, Texture = texture }); } else { var modIcon = rulesets.GetRuleset(ladderInfo.Ruleset.Value.ID ?? 0).CreateInstance().GetAllMods().FirstOrDefault(mod => mod.Acronym == ModAcronym); AddInternal(new ModIcon(modIcon) { Anchor = Anchor.Centre, Origin = Anchor.Centre, Scale = new Vector2(0.5f) }); } } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Linq; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Sprites; using osu.Framework.Graphics.Textures; using osu.Game.Rulesets; using osu.Game.Rulesets.UI; using osu.Game.Tournament.Models; using osuTK; namespace osu.Game.Tournament.Components { public class TournamentModDisplay : CompositeDrawable { public string ModAcronym; [Resolved] private LadderInfo ladderInfo { get; set; } [Resolved] private RulesetStore rulesets { get; set; } [BackgroundDependencyLoader] private void load(TextureStore textures) { var texture = textures.Get($"mods/{ModAcronym}"); if (texture != null) { AddInternal(new Sprite { FillMode = FillMode.Fit, RelativeSizeAxes = Axes.Both, Anchor = Anchor.CentreRight, Origin = Anchor.CentreRight, Texture = texture }); } else { var mod = rulesets.GetRuleset(ladderInfo.Ruleset.Value.ID ?? 0).CreateInstance().GetAllMods().FirstOrDefault(mod => mod.Acronym == ModAcronym); AddInternal(new ModIcon(mod) { Anchor = Anchor.Centre, Origin = Anchor.Centre, Scale = new Vector2(0.5f) }); } } } }
mit
C#
a2b4f05ebe311527ec77351c293f5a111e5535a7
add border radius and shadow
UselessToucan/osu,UselessToucan/osu,ppy/osu,peppy/osu,NeoAdonis/osu,peppy/osu-new,UselessToucan/osu,NeoAdonis/osu,NeoAdonis/osu,peppy/osu,ppy/osu,ppy/osu,smoogipoo/osu,peppy/osu,smoogipooo/osu,smoogipoo/osu,smoogipoo/osu
osu.Game/Overlays/Changelog/ChangelogSupporterPromo.cs
osu.Game/Overlays/Changelog/ChangelogSupporterPromo.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.Extensions.Color4Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Effects; using osu.Framework.Graphics.Shapes; using osuTK; using osuTK.Graphics; namespace osu.Game.Overlays.Changelog { public class ChangelogSupporterPromo : CompositeDrawable { public ChangelogSupporterPromo() { RelativeSizeAxes = Axes.X; AutoSizeAxes = Axes.Y; Padding = new MarginPadding { Vertical = 20, Horizontal = 50, }; InternalChildren = new Drawable[] { new Container { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Masking = true, CornerRadius = 6, EdgeEffect = new EdgeEffectParameters { Type = EdgeEffectType.Shadow, Colour = Color4.Black.Opacity(0.25f), Offset = new Vector2(0, 1), Radius = 3, }, Children = new Drawable[] { new Box { RelativeSizeAxes = Axes.Both, Colour = Color4.Black.Opacity(0.3f), }, new FillFlowContainer { RelativeSizeAxes = Axes.X, Height = 200, }, } }, }; } } }
// 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.Extensions.Color4Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osuTK.Graphics; namespace osu.Game.Overlays.Changelog { public class ChangelogSupporterPromo : CompositeDrawable { public ChangelogSupporterPromo() { RelativeSizeAxes = Axes.X; AutoSizeAxes = Axes.Y; Padding = new MarginPadding { Vertical = 20, Horizontal = 50, }; InternalChildren = new Drawable[] { new Container { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Children = new Drawable[] { new Box { RelativeSizeAxes = Axes.Both, Colour = Color4.Black.Opacity(0.3f), }, new FillFlowContainer { RelativeSizeAxes = Axes.X, Height = 200, }, } }, }; } } }
mit
C#
2274b90d8248420495387cb24e611fdfff3e0422
delete active class
alisonvogel12/personalsite,alisonvogel12/personalsite
AlisonVogel.Web/Views/Shared/NavBar.cshtml
AlisonVogel.Web/Views/Shared/NavBar.cshtml
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script> </head> <body> <nav class="nav navbar hidden visible-xs"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#collapsedNav"> <span class="icon-bar navbar-inverse"></span> <span class="icon-bar navbar-inverse"></span> <span class="icon-bar navbar-inverse"></span> </button> </div> <div class="collapse navbar-collapse" id="collapsedNav"> <ul class="nav navbar-nav"> <li>@Html.ActionLink("Home", "Index", "Home")</li> <li>@Html.ActionLink("About", "Index", "About")</li> <li>@Html.ActionLink("Resume", "Index", "Resume")</li> <li>@Html.ActionLink("Community", "Index", "Community")</li> </ul> </div> </div> </nav> </body> </html> <div> </div><div id="navs" class="hidden-xs" style="text-align: center; font-size: medium;"> <ul> <li>@Html.ActionLink("Home", "Index", "Home")</li> <li>@Html.ActionLink("About", "Index", "About")</li> <li>@Html.ActionLink("Resume", "Index", "Resume")</li> <li>@Html.ActionLink("Community", "Index", "Community")</li> </ul> </div> </div>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script> </head> <body> <nav class="nav navbar hidden visible-xs"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#collapsedNav"> <span class="icon-bar navbar-inverse"></span> <span class="icon-bar navbar-inverse"></span> <span class="icon-bar navbar-inverse"></span> </button> </div> <div class="collapse navbar-collapse" id="collapsedNav"> <ul class="nav navbar-nav"> <li>@Html.ActionLink("Home", "Index", "Home")</li> <li>@Html.ActionLink("About", "Index", "About")</li> <li>@Html.ActionLink("Resume", "Index", "Resume")</li> <li>@Html.ActionLink("Community", "Index", "Community")</li> </ul> </div> </div> </nav> </body> </html> <div> </div><div id="navs" class="hidden-xs" style="text-align: center; font-size: medium;"> <ul> <li>@Html.ActionLink("Home", "Index", "Home")</li> <li>@Html.ActionLink("About", "Index", "About", new {@class = "active"})</li> <li>@Html.ActionLink("Resume", "Index", "Resume")</li> <li>@Html.ActionLink("Community", "Index", "Community")</li> </ul> </div> </div>
mit
C#
a1298834b991576f4dbd9b5fcd330deca8233724
Update EthGetUncleByBlockNumberAndIndex.cs
Nethereum/Nethereum,Nethereum/Nethereum,Nethereum/Nethereum,Nethereum/Nethereum,Nethereum/Nethereum
src/Nethereum.RPC/Eth/Uncles/EthGetUncleByBlockNumberAndIndex.cs
src/Nethereum.RPC/Eth/Uncles/EthGetUncleByBlockNumberAndIndex.cs
using System.Threading.Tasks; using EdjCase.JsonRpc.Core; using Nethereum.Hex.HexTypes; using Nethereum.JsonRpc.Client; using Nethereum.RPC.Eth.DTOs; namespace Nethereum.RPC.Eth.Uncles { /// <Summary> /// eth_getUncleCountByBlockHash /// Returns the number of uncles in a block from a block matching the given block hash. /// Parameters /// DATA, 32 Bytes - hash of a block /// params: [ /// '0xb903239f8543d04b5dc1ba6579132b143087c68db1b2168786408fcbce568238' /// ] /// Returns /// QUANTITY - integer of the number of uncles in this block. /// Example /// Request /// curl -X POST --data /// '{"jsonrpc":"2.0","method":"eth_getUncleCountByBlockHash","params":["0xb903239f8543d04b5dc1ba6579132b143087c68db1b2168786408fcbce568238"],"id"Block:1}' /// Result /// { /// "id":1, /// "jsonrpc": "2.0", /// "result": "0x1" // 1 /// } /// </Summary> public class EthGetUncleByBlockNumberAndIndex : RpcRequestResponseHandler<BlockWithTransactionHashes> { public EthGetUncleByBlockNumberAndIndex(IClient client) : base(client, ApiMethods.eth_getUncleByBlockNumberAndIndex.ToString()) { } public Task<BlockWithTransactionHashes> SendRequestAsync(HexBigInteger blockNumber, HexBigInteger uncleIndex, object id = null) { return base.SendRequestAsync(id, blockNumber, uncleIndex); } public RpcRequest BuildRequest(HexBigInteger blockNumber, HexBigInteger uncleIndex, object id = null) { return base.BuildRequest(id, blockNumber, uncleIndex); } } }
using System.Threading.Tasks; using EdjCase.JsonRpc.Core; using Nethereum.Hex.HexTypes; using Nethereum.JsonRpc.Client; using Nethereum.RPC.Eth.DTOs; namespace Nethereum.RPC.Eth.Uncles { /// <Summary> /// eth_getUncleCountByBlockHash /// Returns the number of uncles in a block from a block matching the given block hash. /// Parameters /// DATA, 32 Bytes - hash of a block /// params: [ /// '0xb903239f8543d04b5dc1ba6579132b143087c68db1b2168786408fcbce568238' /// ] /// Returns /// QUANTITY - integer of the number of uncles in this block. /// Example /// Request /// curl -X POST --data /// '{"jsonrpc":"2.0","method":"eth_getUncleCountByBlockHash","params":["0xb903239f8543d04b5dc1ba6579132b143087c68db1b2168786408fcbce568238"],"id"Block:1}' /// Result /// { /// "id":1, /// "jsonrpc": "2.0", /// "result": "0x1" // 1 /// } /// </Summary> public class EthGetUncleByBlockNumberAndIndex : RpcRequestResponseHandler<BlockWithTransactionHashes> { public EthGetUncleByBlockNumberAndIndex(IClient client) : base(client, ApiMethods.eth_getUncleByBlockNumberAndIndex.ToString()) { } public Task<BlockWithTransactionHashes> SendRequestAsync(HexBigInteger BlockNumber, HexBigInteger UncleIndex, object id = null) { return base.SendRequestAsync(id, BlockNumber, UncleIndex); } public RpcRequest BuildRequest(HexBigInteger BlockNumber, HexBigInteger UncleIndex, object id = null) { return base.BuildRequest(id, BlockNumber, UncleIndex); } } }
mit
C#
82d5a1338e32d32fcd7cc48f2fc95b628520bea0
Use preprocessor check for editor mode to fix build failure
mysticfall/Alensia
Assets/Alensia/Demo/Controller/MainMenu.cs
Assets/Alensia/Demo/Controller/MainMenu.cs
using Alensia.Core.UI; using UniRx; using UnityEngine; #if UNITY_EDITOR using UnityEditor; #endif namespace Alensia.Demo.Controller { public class MainMenu : Box { protected readonly CompositeDisposable Observers; public MainMenu(IUIManager manager) : base( new BoxLayout(BoxLayout.BoxOrientation.Vertical), manager) { Observers = new CompositeDisposable(); } protected override void Initialize() { base.Initialize(); Text = "Main Menu"; var btnQuit = new Button(Manager) { Text = "Quit to Desktop", Padding = new RectOffset(30, 30, 10, 10), Color = UnityEngine.Color.red }; var btnDismiss = new Button(Manager) { Text = "Return to Game", Padding = new RectOffset(30, 30, 10, 10) }; Add(btnQuit); Add(btnDismiss); this.Pack(); this.CenterOnScreen(); btnQuit.Clicked .Subscribe(_ => OnQuit()) .AddTo(Observers); btnDismiss.Clicked .Subscribe(_ => OnDismiss()) .AddTo(Observers); } protected virtual void OnQuit() { Dispose(); #if UNITY_EDITOR EditorApplication.isPlaying = false; #else Application.Quit(); #endif } protected virtual void OnDismiss() => Dispose(); private void Dispose() { Manager.Remove(this); Observers.Dispose(); } } }
using Alensia.Core.UI; using UniRx; using UnityEditor; using UnityEngine; namespace Alensia.Demo.Controller { public class MainMenu : Box { protected readonly CompositeDisposable Observers; public MainMenu(IUIManager manager) : base( new BoxLayout(BoxLayout.BoxOrientation.Vertical), manager) { Observers = new CompositeDisposable(); } protected override void Initialize() { base.Initialize(); Text = "Main Menu"; var btnQuit = new Button(Manager) { Text = "Quit to Desktop", Padding = new RectOffset(30, 30, 10, 10), Color = UnityEngine.Color.red }; var btnDismiss = new Button(Manager) { Text = "Return to Game", Padding = new RectOffset(30, 30, 10, 10) }; Add(btnQuit); Add(btnDismiss); this.Pack(); this.CenterOnScreen(); btnQuit.Clicked .Subscribe(_ => OnQuit()) .AddTo(Observers); btnDismiss.Clicked .Subscribe(_ => OnDismiss()) .AddTo(Observers); } protected virtual void OnQuit() { Dispose(); if (EditorApplication.isPlaying) { EditorApplication.isPlaying = false; } else { Application.Quit(); } } protected virtual void OnDismiss() => Dispose(); private void Dispose() { Manager.Remove(this); Observers.Dispose(); } } }
apache-2.0
C#
e6c57e24bb0b5eccbfbb8c1187c7f9e9b101eb50
use tenant id as the value for facility owner field
dzimchuk/book-fast,dzimchuk/book-fast,dzimchuk/book-fast
src/BookFast/Infrastructure/SecurityContextProvider.cs
src/BookFast/Infrastructure/SecurityContextProvider.cs
using System.Security.Claims; using BookFast.Business; namespace BookFast.Infrastructure { internal class SecurityContextProvider : ISecurityContext, ISecurityContextAcceptor { private const string TenantIdClaimType = "book-fast-tenant-id"; public ClaimsPrincipal Principal { get; set; } public string GetCurrentUser() { if (Principal == null) throw new System.Exception("Principal has not been initialized."); return Principal.GetUserName(); } public string GetCurrentTenant() { if (Principal == null) throw new System.Exception("Principal has not been initialized."); var tenantClaim = Principal.FindFirst(TenantIdClaimType); if (tenantClaim == null) throw new System.Exception("No tenant claim found."); return tenantClaim.Value; } } }
using System.Security.Claims; using BookFast.Business; namespace BookFast.Infrastructure { internal class SecurityContextProvider : ISecurityContext, ISecurityContextAcceptor { public ClaimsPrincipal Principal { get; set; } public string GetCurrentUser() { if (Principal == null) throw new System.Exception("Principal has not been initialized."); return Principal.GetUserName(); } public string GetCurrentTenant() { if (Principal == null) throw new System.Exception("Principal has not been initialized."); return Principal.GetUserName(); } } }
mit
C#
a224d820de1f5dfbd8cbaba378cb59b6510d0d7c
Set version to 2.0
enkol/IS24RestApi,mganss/IS24RestApi
IS24RestApi/Properties/AssemblyInfo.cs
IS24RestApi/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("IS24RestApi")] [assembly: AssemblyDescription("Client for the Immobilienscout24 REST API")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Michael Ganss")] [assembly: AssemblyProduct("IS24RestApi")] [assembly: AssemblyCopyright("Copyright © 2013-2014 IS24RestApi project contributors")] [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("ce77545e-5fbe-4b4d-bf1f-1c5d4532070a")] // 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.*")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("IS24RestApi")] [assembly: AssemblyDescription("Client for the Immobilienscout24 REST API")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Michael Ganss")] [assembly: AssemblyProduct("IS24RestApi")] [assembly: AssemblyCopyright("Copyright © 2013-2014 IS24RestApi project contributors")] [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("ce77545e-5fbe-4b4d-bf1f-1c5d4532070a")] // 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.3.*")]
apache-2.0
C#
b02b1b3345a7d0c67a6c37faea9f548c94379671
Remove unused import in Startup
amoerie/teamcity-theatre,amoerie/teamcity-theatre,amoerie/teamcity-theatre,amoerie/teamcity-theatre,amoerie/teamcity-theatre
src/TeamCityTheatre.Web/Startup.cs
src/TeamCityTheatre.Web/Startup.cs
using System; using System.Reflection; using Autofac; using Autofac.Extensions.DependencyInjection; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using TeamCityTheatre.Core; using TeamCityTheatre.Core.Options; namespace TeamCityTheatre.Web { public class Startup { public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); if (env.IsDevelopment()) { builder.AddUserSecrets<Startup>(); } Configuration = builder.Build(); } public IConfigurationRoot Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public IServiceProvider ConfigureServices(IServiceCollection services) { services.AddRouting(options => options.LowercaseUrls = true); // Add framework services. services.AddMvc(); // Add appsettings services.Configure<ConnectionOptions>(Configuration.GetSection("Connection")); services.Configure<StorageOptions>(Configuration.GetSection("Storage")); // Create the AutoFac container builder. var builder = new ContainerBuilder(); // Register dependencies, populate the services from // the collection, and build the container. If you want // to dispose of the container at the end of the app, // be sure to keep a reference to it as a property or field. builder.RegisterModule<CoreModule>(); // Copy entries from prepared IServiceCollection builder.Populate(services); var applicationContainer = builder.Build(); // Create the IServiceProvider based on the container. return new AutofacServiceProvider(applicationContainer); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseBrowserLink(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "action", template: "{action=Index}", defaults: new { controller = "Home" }); routes.MapRoute( name: "controller+action", template: "{controller}/{action}/{id?}"); }); } } }
using System; using Autofac; using Autofac.Extensions.DependencyInjection; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using TeamCityTheatre.Core; using TeamCityTheatre.Core.Options; namespace TeamCityTheatre.Web { public class Startup { public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); if (env.IsDevelopment()) { builder.AddUserSecrets<Startup>(); } Configuration = builder.Build(); } public IConfigurationRoot Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public IServiceProvider ConfigureServices(IServiceCollection services) { services.AddRouting(options => options.LowercaseUrls = true); // Add framework services. services.AddMvc(); // Add appsettings services.Configure<ConnectionOptions>(Configuration.GetSection("Connection")); services.Configure<StorageOptions>(Configuration.GetSection("Storage")); // Create the AutoFac container builder. var builder = new ContainerBuilder(); // Register dependencies, populate the services from // the collection, and build the container. If you want // to dispose of the container at the end of the app, // be sure to keep a reference to it as a property or field. builder.RegisterModule<CoreModule>(); // Copy entries from prepared IServiceCollection builder.Populate(services); var applicationContainer = builder.Build(); // Create the IServiceProvider based on the container. return new AutofacServiceProvider(applicationContainer); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseBrowserLink(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "action", template: "{action=Index}", defaults: new { controller = "Home" }); routes.MapRoute( name: "controller+action", template: "{controller}/{action}/{id?}"); }); } } }
mit
C#
6a3ca717c9dbaa8e50d877f73cc268b0285223f6
Test git credentials
SimoPrG/Web-Services-and-Cloud-Homework,SimoPrG/Web-Services-and-Cloud-Homework,SimoPrG/Web-Services-and-Cloud-Homework
ConsumingWebServices/NewsClient/Program.cs
ConsumingWebServices/NewsClient/Program.cs
// Write a console application, which searches for news articles by given a query string and a count // of articles to retrieve. The application should ask the user for input and print the Titles and // URLs of the articles. For news articles search, use the Feedzilla API and use one of WebClient, // HttpWebRequest or HttpClient. namespace NewsClient { using System; using System.Linq; using System.Net.Http; using Newtonsoft.Json.Linq; public class Program { public static void Main() { Console.Write("Search for (hint: eum): "); string query = Console.ReadLine(); int n = GetPositiveNumberFromConsoleUser("Number of news (there are 5 eums total): "); PrintNews(query, n); Console.WriteLine("Wait for the news and then press any key to continue...\n"); Console.ReadKey(true); } private static int GetPositiveNumberFromConsoleUser(string message) { int n; do { Console.Write(message); } while (!(int.TryParse(Console.ReadLine(), out n) && n > 0)); return n; } static async void PrintNews(string query, int n) { var httpClient = new HttpClient { BaseAddress = new Uri("http://jsonplaceholder.typicode.com/") }; JArray.Parse(await httpClient.GetStringAsync("posts")) .Where(news => ((string)news["title"]).Contains(query)) .Select(news => new { Title = news["title"], Body = news["body"] }) .Take(n) .ToList() .ForEach(news => Console.WriteLine($"Title:\n{news.Title}\nBody:\n{news.Body}\n")); } } }
// Write a console application, which searches for news articles by given a query string and a count // of articles to retrieve. The application should ask the user for input and print the Titles and // URLs of the articles. For news articles search, use the Feedzilla API and use one of WebClient, // HttpWebRequest or HttpClient. namespace NewsClient { using System; using System.Linq; using System.Net.Http; using Newtonsoft.Json.Linq; public class Program { public static void Main() { Console.Write("Search for (hint: eum): "); string query = Console.ReadLine(); int n = GetPositiveNumberFromConsoleUser("Number of news (there are 5 eums total): "); PrintNews(query, n); Console.WriteLine("Wait for the news and then press any key to continue...\n"); Console.ReadKey(true); } private static int GetPositiveNumberFromConsoleUser(string message) { int n; do { Console.Write(message); } while (!(int.TryParse(Console.ReadLine(), out n) && n > 0)); return n; } static async void PrintNews(string query, int n) { var httpClient = new HttpClient(); httpClient.BaseAddress = new Uri("http://jsonplaceholder.typicode.com/"); JArray.Parse(await httpClient.GetStringAsync("posts")) .Where(news => ((string)news["title"]).Contains(query)) .Select(news => new { Title = news["title"], Body = news["body"] }) .Take(n) .ToList() .ForEach(news => Console.WriteLine($"Title:\n{news.Title}\nBody:\n{news.Body}\n")); } } }
mit
C#
612d17066fc99ceecf207c73b1a1a0ba1e8503e2
Add assembly description.
Bitmapped/UmbCanonicalUrlRedirect,Bitmapped/UmbCanonicalUrlRedirect,Bitmapped/UmbCanonicalUrlRedirect
src/UmbCanonicalUrlRedirect/Properties/AssemblyInfo.cs
src/UmbCanonicalUrlRedirect/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("UmbCanonicalUrlRedirect")] [assembly: AssemblyDescription("Umbraco package to force rewrite of canonical URLs.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Brian M. Powell")] [assembly: AssemblyProduct("UmbCanonicalUrlRedirect")] [assembly: AssemblyCopyright("Copyright ©2016, Brian M. Powell. All rights reserved.")] [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("0c46be12-a569-43a6-a9bf-d89e694e5de7")] // 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.1.0")] [assembly: AssemblyFileVersion("1.2.1.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("UmbCanonicalUrlRedirect")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Brian M. Powell")] [assembly: AssemblyProduct("UmbCanonicalUrlRedirect")] [assembly: AssemblyCopyright("Copyright ©2016, Brian M. Powell. All rights reserved.")] [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("0c46be12-a569-43a6-a9bf-d89e694e5de7")] // 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.1.0")] [assembly: AssemblyFileVersion("1.2.1.0")]
mit
C#
b7d6d1352ccfee1d9e5e140174ec5fe2dfc76df5
Update AssemblyInfo
paulcbetts/LinqToAwait
LinqToAwait/Properties/AssemblyInfo.cs
LinqToAwait/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("LinqToAwait")] [assembly: AssemblyDescription("LINQ operators built to work with async/await, based on Rx")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Paul Betts")] [assembly: AssemblyProduct("LinqToAwait")] [assembly: AssemblyCopyright("Copyright © Paul Betts 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.8.0.0")] [assembly: AssemblyFileVersion("0.8.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("LinqToAwait")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("LinqToAwait")] [assembly: AssemblyCopyright("Copyright © Microsoft 2012")] [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("246b0342-9a17-4a52-a7e8-1a9bd745c741")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#
2d1b668eae3fe54b31eab14908196575e9195e5e
Handle case where no facts are published.
Kentico/Deliver-Dancing-Goat-.NET-MVC,Kentico/Deliver-Dancing-Goat-.NET-MVC,Kentico/cloud-sample-app-net,Kentico/cloud-sample-app-net,Kentico/cloud-sample-app-net
DancingGoat/Controllers/AboutController.cs
DancingGoat/Controllers/AboutController.cs
using System.Threading.Tasks; using System.Web.Mvc; using DancingGoat.Models; using System.Collections.Generic; using KenticoCloud.Delivery; namespace DancingGoat.Controllers { public class AboutController : ControllerBase { public async Task<ActionResult> Index() { var response = await client.GetItemAsync<AboutUs>("about_us"); var viewModel = new AboutUsViewModel { FactViewModels = MapFactsAboutUs(response) }; return View(viewModel); } private IList<FactAboutUsViewModel> MapFactsAboutUs(DeliveryItemResponse<AboutUs> response) { var facts = new List<FactAboutUsViewModel>(); if (response.Item == null) { return facts; } int i = 0; foreach (var fact in response.Item.Facts) { var factViewModel = new FactAboutUsViewModel { Fact = (FactAboutUs)fact }; if (i++ % 2 == 0) { factViewModel.Odd = true; } facts.Add(factViewModel); } return facts; } } }
using System.Threading.Tasks; using System.Web.Mvc; using DancingGoat.Models; using System.Collections.Generic; namespace DancingGoat.Controllers { public class AboutController : ControllerBase { public async Task<ActionResult> Index() { var response = await client.GetItemAsync<AboutUs>("about_us"); var viewModel = new AboutUsViewModel { FactViewModels = new List<FactAboutUsViewModel>() }; int i = 0; foreach (var fact in response.Item?.Facts) { var factViewModel = new FactAboutUsViewModel { Fact = (FactAboutUs)fact }; if (i++ % 2 == 0) { factViewModel.Odd = true; } viewModel.FactViewModels.Add(factViewModel); } return View(viewModel); } } }
mit
C#
6c0358ef91e6b7c248a0610a88bbe997bfbe6acf
use PostgreSQLConnection not MSSQLConnection
n8allan/Dataphor,n8allan/Dataphor,DBCG/Dataphor,n8allan/Dataphor,n8allan/Dataphor,DBCG/Dataphor,DBCG/Dataphor,n8allan/Dataphor,DBCG/Dataphor,n8allan/Dataphor,DBCG/Dataphor,DBCG/Dataphor
Dataphor/DAE.PGSQL/PGSQLStoreConnection.cs
Dataphor/DAE.PGSQL/PGSQLStoreConnection.cs
/* Alphora Dataphor Copyright 2000-2008 Alphora This file is licensed under a modified BSD-license which can be found here: http://dataphor.org/dataphor_license.txt */ #define USESQLCONNECTION using System; using System.IO; using System.Text; using System.Collections.Generic; #if USESQLCONNECTION using Alphora.Dataphor.DAE.Connection; using Alphora.Dataphor.DAE.Connection.PGSQL; #else using System.Data; using System.Data.Common; using System.Data.SqlClient; #endif namespace Alphora.Dataphor.DAE.Store.PGSQL { public class PostgreSQLStoreConnection : SQLStoreConnection { public PostgreSQLStoreConnection(PostgreSQLStore AStore) : base(AStore) { } #if USESQLCONNECTION protected override SQLConnection InternalCreateConnection() { return new PostgreSQLConnection(Store.ConnectionString); } #else protected override DbConnection InternalCreateConnection() { return new SqlConnection(Store.ConnectionString); } #endif public override bool HasTable(string ATableName) { return ((int)this.ExecuteScalar(String.Format("select count(*) from INFORMATION_SCHEMA.TABLES where TABLE_NAME = '{0}'", ATableName)) != 0); } } }
/* Alphora Dataphor Copyright 2000-2008 Alphora This file is licensed under a modified BSD-license which can be found here: http://dataphor.org/dataphor_license.txt */ #define USESQLCONNECTION using System; using System.IO; using System.Text; using System.Collections.Generic; #if USESQLCONNECTION using Alphora.Dataphor.DAE.Connection; #else using System.Data; using System.Data.Common; using System.Data.SqlClient; #endif namespace Alphora.Dataphor.DAE.Store.PGSQL { public class PostgreSQLStoreConnection : SQLStoreConnection { public PostgreSQLStoreConnection(PostgreSQLStore AStore) : base(AStore) { } #if USESQLCONNECTION protected override SQLConnection InternalCreateConnection() { return new MSSQLConnection(Store.ConnectionString); } #else protected override DbConnection InternalCreateConnection() { return new SqlConnection(Store.ConnectionString); } #endif public override bool HasTable(string ATableName) { return ((int)this.ExecuteScalar(String.Format("select count(*) from INFORMATION_SCHEMA.TABLES where TABLE_NAME = '{0}'", ATableName)) != 0); } } }
bsd-3-clause
C#
82b9d6eee5d7ff5bf318764ccef3c8d77cac5c2e
Set Version Numer for 3.0.3.1
baynezy/SiteWarmer
SiteWarmer/SiteWarmer.Core/Properties/AssemblyInfo.cs
SiteWarmer/SiteWarmer.Core/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("SiteWarmer.Core")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SiteWarmer.Core")] [assembly: AssemblyCopyright("Copyright © 2013")] [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("f28abe61-e729-4553-b910-8604c9046a97")] // 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("3.0.3.1")] [assembly: AssemblyFileVersion("3.0.3.1")]
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("SiteWarmer.Core")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SiteWarmer.Core")] [assembly: AssemblyCopyright("Copyright © 2013")] [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("f28abe61-e729-4553-b910-8604c9046a97")] // 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("3.0.4.0")] [assembly: AssemblyFileVersion("3.0.4.0")]
apache-2.0
C#
6ea3f263b542a64ef051a22ae064f5c7e97ea4a2
Fix random name generation and slightly refactor it.
krille90/unitystation,fomalsd/unitystation,fomalsd/unitystation,Necromunger/unitystation,Necromunger/unitystation,Necromunger/unitystation,Necromunger/unitystation,krille90/unitystation,Necromunger/unitystation,krille90/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,Necromunger/unitystation
UnityProject/Assets/Scripts/Managers/StringManager.cs
UnityProject/Assets/Scripts/Managers/StringManager.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class StringManager : MonoBehaviour { private static StringManager stringManager; public static StringManager Instance { get { if (stringManager == null) { stringManager = FindObjectOfType<StringManager>(); } return stringManager; } } public Dictionary<string, List<string>> textObjects = new Dictionary<string, List<string>>(); public List<TextAsset> nameTextFiles; void Start() { for (int i = 0; i < nameTextFiles.Count; i++) { string[] lines = nameTextFiles[i].text.Split( new[] { "\r\n", "\r", "\n" }, System.StringSplitOptions.None); textObjects.Add(nameTextFiles[i].name, new List<string>(lines)); } } public static string GetRandomMaleName(){ return GetRandomName(Gender.Male); } public static string GetRandomFemaleName(){ return GetRandomName(Gender.Female); } /// <summary> /// Combines a random first and last name depending on gender, uses both male and female names if gender is Nueter /// </summary> public static string GetRandomName(Gender gender) { if (gender == Gender.Neuter) gender = Random.value > 0.5f ? Gender.Male : Gender.Female; //Uses random gendered name if Nueter var genderKey = gender.ToString().ToLowerInvariant(); //ToLowerInvariant because ToLower has different behaviour based on culture var firstName = Instance.textObjects[$"first_{genderKey}"][Random.Range(0, Instance.textObjects[$"first_{genderKey}"].Count)]; //Random.Range is max exclusive and as such .Count can be used directly var lastName = Instance.textObjects["last" ][Random.Range(0, Instance.textObjects["last" ].Count)]; return $"{firstName} {lastName}"; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Text.RegularExpressions; public class StringManager : MonoBehaviour { private static StringManager stringManager; public static StringManager Instance { get { if (stringManager == null) { stringManager = FindObjectOfType<StringManager>(); } return stringManager; } } public Dictionary<string, List<string>> textObjects = new Dictionary<string, List<string>>(); public List<TextAsset> nameTextFiles; void Start() { for (int i = 0; i < nameTextFiles.Count; i++) { string[] lines = Regex.Split(nameTextFiles[i].text, "\n|\r|\r\n"); textObjects.Add(nameTextFiles[i].name, new List<string>(lines)); } } public static string GetRandomMaleName(){ var newName = Instance.textObjects["first_male"] [Random.Range(0,Instance.textObjects["first_male"].Count - 1)]; newName += " " + Instance.textObjects["last"] [Random.Range(0,Instance.textObjects["last"].Count - 1)]; return newName; } public static string GetRandomFemaleName(){ var newName = Instance.textObjects["first_female"] [Random.Range(0,Instance.textObjects["first_female"].Count - 1)]; newName += " " + Instance.textObjects["last"] [Random.Range(0,Instance.textObjects["last"].Count - 1)]; return newName; } }
agpl-3.0
C#
0db12621e1b887e7487e169ca7baa897372b2f42
fix MacOs build where the default affinity is 0 or we can't read it for some reason..
PerfDotNet/BenchmarkDotNet,ig-sinicyn/BenchmarkDotNet,Ky7m/BenchmarkDotNet,adamsitnik/BenchmarkDotNet,alinasmirnova/BenchmarkDotNet,Ky7m/BenchmarkDotNet,ig-sinicyn/BenchmarkDotNet,adamsitnik/BenchmarkDotNet,adamsitnik/BenchmarkDotNet,PerfDotNet/BenchmarkDotNet,alinasmirnova/BenchmarkDotNet,alinasmirnova/BenchmarkDotNet,ig-sinicyn/BenchmarkDotNet,Ky7m/BenchmarkDotNet,Ky7m/BenchmarkDotNet,alinasmirnova/BenchmarkDotNet,adamsitnik/BenchmarkDotNet,ig-sinicyn/BenchmarkDotNet,PerfDotNet/BenchmarkDotNet
tests/BenchmarkDotNet.Tests/CharacteristicPresenterTests.cs
tests/BenchmarkDotNet.Tests/CharacteristicPresenterTests.cs
using System; using System.Linq; using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Characteristics; using BenchmarkDotNet.Columns; using BenchmarkDotNet.Configs; using BenchmarkDotNet.Jobs; using BenchmarkDotNet.Portability; using BenchmarkDotNet.Running; using Xunit; namespace BenchmarkDotNet.Tests { public class CharacteristicPresenterTests { [Fact] public void ProcessorAffinityIsPrintedAsBitMask() { var jobWithAffinity = Job.Default.WithAffinity((IntPtr) 1); var expected = "1".PadLeft(Environment.ProcessorCount, '0'); var printed = CharacteristicPresenter.SummaryPresenter.ToPresentation(jobWithAffinity, EnvironmentMode.AffinityCharacteristic); Assert.Equal(expected, printed); } [Fact] public void ProcessorAffinityIsPrintedAsBitMaskEvenWhenNotSet() { var jobWithoutAffinity = Job.Default; var benchmarkCase = BenchmarkConverter.TypeToBenchmarks( typeof(CharacteristicPresenterTests), DefaultConfig.Instance.With(jobWithoutAffinity)).BenchmarksCases.Single(); var column = new JobCharacteristicColumn(EnvironmentMode.AffinityCharacteristic); var expected = Convert.ToString((int)RuntimeInformation.GetCurrentAffinity(), 2).PadLeft(Environment.ProcessorCount, '1'); var printed = column.GetValue(summary: null, benchmarkCase); Assert.Equal(expected, printed); } [Benchmark] public void Mehtod() { } } }
using System; using System.Linq; using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Characteristics; using BenchmarkDotNet.Columns; using BenchmarkDotNet.Configs; using BenchmarkDotNet.Jobs; using BenchmarkDotNet.Running; using Xunit; namespace BenchmarkDotNet.Tests { public class CharacteristicPresenterTests { [Fact] public void ProcessorAffinityIsPrintedAsBitMask() { var jobWithAffinity = Job.Default.WithAffinity((IntPtr) 1); var expected = "1".PadLeft(Environment.ProcessorCount, '0'); var printed = CharacteristicPresenter.SummaryPresenter.ToPresentation(jobWithAffinity, EnvironmentMode.AffinityCharacteristic); Assert.Equal(expected, printed); } [Fact] public void ProcessorAffinityIsPrintedAsBitMaskEvenWhenNotSet() { var jobWithoutAffinity = Job.Default; var benchmarkCase = BenchmarkConverter.TypeToBenchmarks( typeof(CharacteristicPresenterTests), DefaultConfig.Instance.With(jobWithoutAffinity)).BenchmarksCases.Single(); var column = new JobCharacteristicColumn(EnvironmentMode.AffinityCharacteristic); var expected = "1".PadLeft(Environment.ProcessorCount, '1'); var printed = column.GetValue(summary: null, benchmarkCase); Assert.Equal(expected, printed); } [Benchmark] public void Mehtod() { } } }
mit
C#
7097496fe16f013e9f6ea38becf1fe45ae887bdf
Update _Layout.cshtml
jbubriski/npoi-mvc-sample-app
NpoiSample/Views/Shared/_Layout.cshtml
NpoiSample/Views/Shared/_Layout.cshtml
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>@ViewBag.Title - NPOI Sample App</title> <link href="~/Content/Site.css" rel="stylesheet" type="text/css" /> <link href="~/Content/bootstrap.min.css" rel="stylesheet" type="text/css" /> <script src="~/Scripts/modernizr-2.6.2.js"></script> </head> <body> <div class="navbar navbar-inverse navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> @Html.ActionLink("Application name", "Index", "Home", null, new { @class = "navbar-brand" }) </div> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> </ul> </div> </div> </div> <div class="container body-content"> @RenderBody() <hr /> <footer> <p>&copy; @DateTime.Now.Year - NPOI Sample App</p> </footer> </div> <script src="~/Scripts/jquery-1.10.2.min.js"></script> <script src="~/Scripts/bootstrap.min.js"></script> </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>@ViewBag.Title - My ASP.NET Application</title> <link href="~/Content/Site.css" rel="stylesheet" type="text/css" /> <link href="~/Content/bootstrap.min.css" rel="stylesheet" type="text/css" /> <script src="~/Scripts/modernizr-2.6.2.js"></script> </head> <body> <div class="navbar navbar-inverse navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> @Html.ActionLink("Application name", "Index", "Home", null, new { @class = "navbar-brand" }) </div> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> </ul> </div> </div> </div> <div class="container body-content"> @RenderBody() <hr /> <footer> <p>&copy; @DateTime.Now.Year - NPOI Sample</p> </footer> </div> <script src="~/Scripts/jquery-1.10.2.min.js"></script> <script src="~/Scripts/bootstrap.min.js"></script> </body> </html>
mit
C#
d80a5162eddecaf17368e730e98832084c46e452
Make template more consistent
theprash/FSharp.Formatting,tpetricek/FSharp.Formatting,tpetricek/FSharp.Formatting,theprash/FSharp.Formatting,mktange/FSharp.Formatting,tpetricek/FSharp.Formatting,mktange/FSharp.Formatting,tpetricek/FSharp.Formatting,mktange/FSharp.Formatting,mktange/FSharp.Formatting,theprash/FSharp.Formatting,tpetricek/FSharp.Formatting,theprash/FSharp.Formatting,theprash/FSharp.Formatting,theprash/FSharp.Formatting,mktange/FSharp.Formatting,tpetricek/FSharp.Formatting,mktange/FSharp.Formatting
misc/templates/reference/part-members.cshtml
misc/templates/reference/part-members.cshtml
@if (Enumerable.Count(Model.Members) > 0) { <h3>@Model.Header</h3> <table class="table table-bordered member-list"> <thead> <tr><td>@Model.TableHeader</td><td>Description</td></tr> </thead> <tbody> @foreach (var it in Model.Members) { <tr> <td class="member-name"> @{ var id = Html.UniqueID().ToString(); } <code onmouseout="hideTip(event, '@id', @id)" onmouseover="showTip(event, '@id', @id)"> @Html.Encode(it.Details.FormatUsage(40)) </code> <div class="tip" id="@id"> <strong>Signature:</strong> @Html.Encode(it.Details.Signature)<br /> @if (!it.Details.Modifiers.IsEmpty) { <strong>Modifiers:</strong> @it.Details.FormatModifiers<br /> } @if (!it.Details.TypeArguments.IsEmpty) { <strong>Type parameters:</strong> @it.Details.FormatTypeArguments } </div> </td> <td class="xmldoc"> @if (!String.IsNullOrEmpty(it.Details.FormatSourceLocation)) { <a href="@it.Details.FormatSourceLocation" class="github-link"> <img src="../content/img/github.png" class="normal" /> <img src="../content/img/github-blue.png" class="hover" /> </a> } @it.Comment.FullText @if (!String.IsNullOrEmpty(it.Details.FormatCompiledName)) { @:<p>CompiledName: <code>@it.Details.FormatCompiledName</code></p> } </td> </tr> } </tbody> </table> }
@if (Enumerable.Count(Model.Members) > 0) { <h3>@Model.Header</h3> <table class="table table-bordered member-list"> <thead> <tr><td>@Model.TableHeader</td><td>Description</td></tr> </thead> <tbody> @foreach (var it in Model.Members) { <tr> <td class="member-name"> @{ var id = Html.UniqueID().ToString(); } <code onmouseout="hideTip(event, '@id', @id)" onmouseover="showTip(event, '@id', @id)"> @Html.Encode(it.Details.FormatUsage(40)) </code> <div class="tip" id="@id"> <strong>Signature:</strong> @Html.Encode(it.Details.Signature)<br /> @if (!it.Details.Modifiers.IsEmpty) { <strong>Modifiers:</strong> @it.Details.FormatModifiers<br /> } @if (!it.Details.TypeArguments.IsEmpty) { <strong>Type parameters:</strong> @it.Details.FormatTypeArguments } </div> </td> <td class="xmldoc"> @if (!String.IsNullOrEmpty(it.Details.FormatSourceLocation)) { <a href="@it.Details.FormatSourceLocation" class="github-link"> <img src="../content/img/github.png" class="normal" /> <img src="../content/img/github-blue.png" class="hover" /> </a> } @it.Comment.FullText @if (!String.IsNullOrEmpty(it.Details.FormatCompiledName)) { @:<p>CompiledName: <strong>@it.Details.FormatCompiledName</strong></p> } </td> </tr> } </tbody> </table> }
apache-2.0
C#
d3e388f33849442a4ae58dbd016000c0e22a1ba9
fix line ending and indenting.
fredericDelaporte/nhibernate-core,RogerKratz/nhibernate-core,nhibernate/nhibernate-core,ngbrown/nhibernate-core,nkreipke/nhibernate-core,fredericDelaporte/nhibernate-core,gliljas/nhibernate-core,RogerKratz/nhibernate-core,RogerKratz/nhibernate-core,gliljas/nhibernate-core,ManufacturingIntelligence/nhibernate-core,hazzik/nhibernate-core,nkreipke/nhibernate-core,ManufacturingIntelligence/nhibernate-core,fredericDelaporte/nhibernate-core,RogerKratz/nhibernate-core,hazzik/nhibernate-core,alobakov/nhibernate-core,nkreipke/nhibernate-core,nhibernate/nhibernate-core,hazzik/nhibernate-core,nhibernate/nhibernate-core,ManufacturingIntelligence/nhibernate-core,gliljas/nhibernate-core,nhibernate/nhibernate-core,livioc/nhibernate-core,alobakov/nhibernate-core,ngbrown/nhibernate-core,gliljas/nhibernate-core,lnu/nhibernate-core,lnu/nhibernate-core,fredericDelaporte/nhibernate-core,livioc/nhibernate-core,lnu/nhibernate-core,ngbrown/nhibernate-core,alobakov/nhibernate-core,livioc/nhibernate-core,hazzik/nhibernate-core
src/NHibernate.Test/DebugConnectionProvider.cs
src/NHibernate.Test/DebugConnectionProvider.cs
using System; using System.Collections; using System.Collections.Generic; using System.Data; using NHibernate.Connection; namespace NHibernate.Test { /// <summary> /// This connection provider keeps a list of all open connections, /// it is used when testing to check that tests clean up after themselves. /// </summary> public class DebugConnectionProvider : DriverConnectionProvider { private ISet<IDbConnection> connections = new HashSet<IDbConnection>(); public override IDbConnection GetConnection() { try { IDbConnection connection = base.GetConnection(); connections.Add(connection); return connection; } catch (Exception e) { throw new HibernateException("Could not open connection to: " + ConnectionString, e); } } public override void CloseConnection(IDbConnection conn) { base.CloseConnection(conn); connections.Remove(conn); } public bool HasOpenConnections { get { // check to see if all connections that were at one point opened // have been closed through the CloseConnection // method if (connections.Count == 0) { // there are no connections, either none were opened or // all of the closings went through CloseConnection. return false; } else { // Disposing of an ISession does not call CloseConnection (should it???) // so a Diposed of ISession will leave an IDbConnection in the list but // the IDbConnection will be closed (atleast with MsSql it works this way). foreach (IDbConnection conn in connections) { if (conn.State != ConnectionState.Closed) { return true; } } // all of the connections have been Disposed and were closed that way // or they were Closed through the CloseConnection method. return false; } } } public void CloseAllConnections() { while (connections.Count != 0) { IEnumerator en = connections.GetEnumerator(); en.MoveNext(); CloseConnection(en.Current as IDbConnection); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Data; using NHibernate.Connection; namespace NHibernate.Test { /// <summary> /// This connection provider keeps a list of all open connections, /// it is used when testing to check that tests clean up after themselves. /// </summary> public class DebugConnectionProvider : DriverConnectionProvider { private ISet<IDbConnection> connections = new HashSet<IDbConnection>(); public override IDbConnection GetConnection() { try { IDbConnection connection = base.GetConnection(); connections.Add(connection); return connection; } catch (Exception e) { throw new HibernateException("Could not open connection to: " + ConnectionString, e); } } public override void CloseConnection(IDbConnection conn) { base.CloseConnection(conn); connections.Remove(conn); } public bool HasOpenConnections { get { // check to see if all connections that were at one point opened // have been closed through the CloseConnection // method if (connections.Count == 0) { // there are no connections, either none were opened or // all of the closings went through CloseConnection. return false; } else { // Disposing of an ISession does not call CloseConnection (should it???) // so a Diposed of ISession will leave an IDbConnection in the list but // the IDbConnection will be closed (atleast with MsSql it works this way). foreach (IDbConnection conn in connections) { if (conn.State != ConnectionState.Closed) { return true; } } // all of the connections have been Disposed and were closed that way // or they were Closed through the CloseConnection method. return false; } } } public void CloseAllConnections() { while (connections.Count != 0) { IEnumerator en = connections.GetEnumerator(); en.MoveNext(); CloseConnection(en.Current as IDbConnection); } } } }
lgpl-2.1
C#
d491df361068a16b4b1ac9d99b320376d571dba9
Add TODO
OvidiuCaba/StatisticsRomania,OvidiuCaba/StatisticsRomania,OvidiuCaba/StatisticsRomania,OvidiuCaba/StatisticsRomania
src/StatisticsRomania/StatisticsRomania/App.cs
src/StatisticsRomania/StatisticsRomania/App.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using StatisticsRomania.Views; using Xamarin.Forms; using SQLite.Net.Async; namespace StatisticsRomania { // TODO: new functionalities: // - export data // - fix issues on rotating // - forecast: https://azure.microsoft.com/en-us/documentation/articles/machine-learning-what-is-machine-learning/ public class App : Application { public static string SqliteFilename = "database.db3"; public static SQLiteAsyncConnection AsyncDb; // Note: change the values when new data is added [in the future we might automatically get the data from API, so no rush to optimize here] public static int LastYearAvailableData = 2015; public static int LastMonthAvailableData = 10; public App() { // The root page of your application MainPage = new RootPage(); } protected override void OnStart() { // Handle when your app starts } protected override void OnSleep() { // Handle when your app sleeps } protected override void OnResume() { // Handle when your app resumes } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using StatisticsRomania.Views; using Xamarin.Forms; using SQLite.Net.Async; namespace StatisticsRomania { // TODO: new functionalities: // - export data // - fix issues on rotating public class App : Application { public static string SqliteFilename = "database.db3"; public static SQLiteAsyncConnection AsyncDb; // Note: change the values when new data is added [in the future we might automatically get the data from API, so no rush to optimize here] public static int LastYearAvailableData = 2015; public static int LastMonthAvailableData = 10; public App() { // The root page of your application MainPage = new RootPage(); } protected override void OnStart() { // Handle when your app starts } protected override void OnSleep() { // Handle when your app sleeps } protected override void OnResume() { // Handle when your app resumes } } }
mit
C#
dcd16b6f56b60a0dec8eb964c3d51c82918b7c8b
Make way for future improvements
pabloengine/pablo
Pablo/Graphics/BaseTypes/StrokeType.cs
Pablo/Graphics/BaseTypes/StrokeType.cs
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Copyright (c) 2015, MPL Ali Taheri Moghaddar ali.taheri.m@gmail.com */ namespace Pablo.Graphics { /// <summary> /// Determines the pattern of a line. /// </summary> public enum StrokeType { /// <summary> /// This produces a solid continuous line. /// </summary> Solid, /// <summary> /// This produces a dashed line. /// </summary> Dashed, /// <summary> /// This produces a zigzag line. /// </summary> Zigzag, } }
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Copyright (c) 2015, MPL Ali Taheri Moghaddar ali.taheri.m@gmail.com */ namespace Pablo.Graphics { /// <summary> /// Determines the pattern of a line. /// </summary> public enum StrokeType { /// <summary> /// This produces a solid continuous line. /// </summary> Solid, /// <summary> /// This produces a dashed line. /// </summary> Dashed, /// <summary> /// This produces a dash-dotted line. /// </summary> DashDot, } }
mpl-2.0
C#
de59a61f9a4df32019e1af50b7c070a78e702a28
Update GenericHostBuilderExtensions.cs (#26386)
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
src/DefaultBuilder/src/GenericHostBuilderExtensions.cs
src/DefaultBuilder/src/GenericHostBuilderExtensions.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 Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore; namespace Microsoft.Extensions.Hosting { /// <summary> /// Extension methods for configuring the <see cref="IHostBuilder" />. /// </summary> public static class GenericHostBuilderExtensions { /// <summary> /// Configures a <see cref="IHostBuilder" /> with defaults for hosting a web app. /// </summary> /// <remarks> /// The following defaults are applied to the <see cref="IHostBuilder"/>: /// <list type="bullet"> /// <item><description>use Kestrel as the web server and configure it using the application's configuration providers</description></item> /// <item><description>configure <see cref="IWebHostEnvironment.WebRootFileProvider"/> to include static web assets from projects referenced by the entry assembly during development</description></item> /// <item><description>adds the HostFiltering middleware</description></item> /// <item><description>adds the ForwardedHeaders middleware if ASPNETCORE_FORWARDEDHEADERS_ENABLED=true,</description></item> /// <item><description>enable IIS integration</description></item> /// </list> /// </remarks> /// <param name="builder">The <see cref="IHostBuilder" /> instance to configure.</param> /// <param name="configure">The configure callback</param> /// <returns>A reference to the <paramref name="builder"/> after the operation has completed.</returns> public static IHostBuilder ConfigureWebHostDefaults(this IHostBuilder builder, Action<IWebHostBuilder> configure) { if (configure is null) { throw new ArgumentNullException(nameof(configure)); } return builder.ConfigureWebHost(webHostBuilder => { WebHost.ConfigureWebDefaults(webHostBuilder); configure(webHostBuilder); }); } } }
using System; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore; namespace Microsoft.Extensions.Hosting { /// <summary> /// Extension methods for configuring the IWebHostBuilder. /// </summary> public static class GenericHostBuilderExtensions { /// <summary> /// Initializes a new instance of the <see cref="IWebHostBuilder"/> class with pre-configured defaults. /// </summary> /// <remarks> /// The following defaults are applied to the <see cref="IWebHostBuilder"/>: /// use Kestrel as the web server and configure it using the application's configuration providers, /// configure the <see cref="IWebHostEnvironment.WebRootFileProvider"/> to map static web assets when <see cref="IHostEnvironment.EnvironmentName"/> is 'Development' using the entry assembly, /// adds the HostFiltering middleware, /// adds the ForwardedHeaders middleware if ASPNETCORE_FORWARDEDHEADERS_ENABLED=true, /// and enable IIS integration. /// </remarks> /// <param name="builder">The <see cref="IHostBuilder" /> instance to configure</param> /// <param name="configure">The configure callback</param> /// <returns>The <see cref="IHostBuilder"/> for chaining.</returns> public static IHostBuilder ConfigureWebHostDefaults(this IHostBuilder builder, Action<IWebHostBuilder> configure) { if (configure is null) { throw new ArgumentNullException(nameof(configure)); } return builder.ConfigureWebHost(webHostBuilder => { WebHost.ConfigureWebDefaults(webHostBuilder); configure(webHostBuilder); }); } } }
apache-2.0
C#
58df33e73815de838bb98161dc7a60c8005fe3d6
Set Default-LogLevel to Debug since Trace isn't really logged onto the console.
ExRam/ExRam.Gremlinq
ExRam.Gremlinq.Providers.WebSocket/QueryLoggingOptions.cs
ExRam.Gremlinq.Providers.WebSocket/QueryLoggingOptions.cs
using Microsoft.Extensions.Logging; using Newtonsoft.Json; namespace ExRam.Gremlinq.Providers.WebSocket { public readonly struct QueryLoggingOptions { public static readonly QueryLoggingOptions Default = new QueryLoggingOptions(LogLevel.Debug, QueryLoggingVerbosity.QueryOnly, Formatting.None); public QueryLoggingOptions(LogLevel logLevel, QueryLoggingVerbosity verbosity, Formatting formatting) { LogLevel = logLevel; Verbosity = verbosity; Formatting = formatting; } public QueryLoggingOptions SetLogLevel(LogLevel logLevel) { return new QueryLoggingOptions(logLevel, Verbosity, Formatting); } public QueryLoggingOptions SetQueryLoggingVerbosity(QueryLoggingVerbosity verbosity) { return new QueryLoggingOptions(LogLevel, verbosity, Formatting); } public QueryLoggingOptions SetFormatting(Formatting formatting) { return new QueryLoggingOptions(LogLevel, Verbosity, formatting); } public LogLevel LogLevel { get; } public Formatting Formatting { get; } public QueryLoggingVerbosity Verbosity { get; } } }
using Microsoft.Extensions.Logging; using Newtonsoft.Json; namespace ExRam.Gremlinq.Providers.WebSocket { public readonly struct QueryLoggingOptions { public static readonly QueryLoggingOptions Default = new QueryLoggingOptions(LogLevel.Trace, QueryLoggingVerbosity.QueryOnly, Formatting.None); public QueryLoggingOptions(LogLevel logLevel, QueryLoggingVerbosity verbosity, Formatting formatting) { LogLevel = logLevel; Verbosity = verbosity; Formatting = formatting; } public QueryLoggingOptions SetLogLevel(LogLevel logLevel) { return new QueryLoggingOptions(logLevel, Verbosity, Formatting); } public QueryLoggingOptions SetQueryLoggingVerbosity(QueryLoggingVerbosity verbosity) { return new QueryLoggingOptions(LogLevel, verbosity, Formatting); } public QueryLoggingOptions SetFormatting(Formatting formatting) { return new QueryLoggingOptions(LogLevel, Verbosity, formatting); } public LogLevel LogLevel { get; } public Formatting Formatting { get; } public QueryLoggingVerbosity Verbosity { get; } } }
mit
C#
b841dc19248fb2602792afc532148103bcf64255
Handle running on GCP transparently
jskeet/nodatime,malcolmr/nodatime,malcolmr/nodatime,BenJenkinson/nodatime,malcolmr/nodatime,nodatime/nodatime,malcolmr/nodatime,nodatime/nodatime,jskeet/nodatime,BenJenkinson/nodatime
src/NodaTime.Web/Providers/GoogleCredentialProvider.cs
src/NodaTime.Web/Providers/GoogleCredentialProvider.cs
// Copyright 2016 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using Google.Apis.Auth.OAuth2; using Microsoft.Azure.KeyVault; using Microsoft.Extensions.Configuration; using Microsoft.IdentityModel.Clients.ActiveDirectory; using System; using System.IO; using System.Text; using static Microsoft.Azure.KeyVault.KeyVaultClient; namespace NodaTime.Web.Providers { public class GoogleCredentialProvider { public static GoogleCredential FetchCredential(IConfiguration configuration) { string foo = configuration["foo"]; // Use the default credentials if the environment variable is set. if (Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS") != null) { return GoogleCredential.GetApplicationDefault(); } // If we've got an Azure KeyVault configuration, we'll use that string secretUri = configuration["APPSETTING_SecretUri"]; string clientId = configuration["APPSETTING_ClientId"]; string clientSecret = configuration["APPSETTING_ClientSecret"]; // But if none of the environment variables has been specified, expect that // we're running on Google Cloud Platform with implicit credentials. if (secretUri == null && clientId == null && clientSecret == null) { return GoogleCredential.GetApplicationDefault(); } ClientCredential credential = new ClientCredential(clientId, clientSecret); var secret = GetKeyVaultSecret(credential, secretUri); return GoogleCredential.FromStream(new MemoryStream(Encoding.UTF8.GetBytes(secret))); } // See https://docs.microsoft.com/en-us/azure/key-vault/key-vault-use-from-web-application private static string GetKeyVaultSecret(ClientCredential credential, string secretUri) { AuthenticationCallback callback = async (string authority, string resource, string scope) => { var authContext = new AuthenticationContext(authority); AuthenticationResult result = await authContext.AcquireTokenAsync(resource, credential); if (result == null) { throw new InvalidOperationException("Failed to obtain the JWT token"); } return result.AccessToken; }; var kv = new KeyVaultClient(callback); return kv.GetSecretAsync(secretUri).Result.Value; } } }
// Copyright 2016 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using Google.Apis.Auth.OAuth2; using Microsoft.Azure.KeyVault; using Microsoft.Extensions.Configuration; using Microsoft.IdentityModel.Clients.ActiveDirectory; using System; using System.IO; using System.Text; using static Microsoft.Azure.KeyVault.KeyVaultClient; namespace NodaTime.Web.Providers { public class GoogleCredentialProvider { public static GoogleCredential FetchCredential(IConfiguration configuration) { // Use the default credentials if the environment variable is set. if (Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS") != null) { return GoogleCredential.GetApplicationDefaultAsync().Result; } string secretUri = configuration["APPSETTING_SecretUri"]; string clientId = configuration["APPSETTING_ClientId"]; string clientSecret = configuration["APPSETTING_ClientSecret"]; ClientCredential credential = new ClientCredential(clientId, clientSecret); var secret = GetKeyVaultSecret(credential, secretUri); return GoogleCredential.FromStream(new MemoryStream(Encoding.UTF8.GetBytes(secret))); } // See https://docs.microsoft.com/en-us/azure/key-vault/key-vault-use-from-web-application private static string GetKeyVaultSecret(ClientCredential credential, string secretUri) { AuthenticationCallback callback = async (string authority, string resource, string scope) => { var authContext = new AuthenticationContext(authority); AuthenticationResult result = await authContext.AcquireTokenAsync(resource, credential); if (result == null) { throw new InvalidOperationException("Failed to obtain the JWT token"); } return result.AccessToken; }; var kv = new KeyVaultClient(callback); return kv.GetSecretAsync(secretUri).Result.Value; } } }
apache-2.0
C#
ce6cc4264027b543793490cade64b621c12e5f11
fix doc error
killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,DDReaper/MixedRealityToolkit-Unity
Assets/MixedRealityToolkit/Utilities/Editor/FileUtilities.cs
Assets/MixedRealityToolkit/Utilities/Editor/FileUtilities.cs
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System.IO; using UnityEditor; using UnityEngine; namespace Microsoft.MixedReality.Toolkit.Utilities.Editor { /// <summary> /// A set of utilities for working with files. /// </summary> public static class FileUtilities { /// <summary> /// Locates the files that match the specified name within the Assets folder (application data path) structure. /// </summary> /// <param name="fileName">The name of the file to locate (ex: "TestFile.asmdef")</param> /// <returns>Array of FileInfo objects representing the located file(s).</returns> public static FileInfo[] FindFilesInAssets(string fileName) { DirectoryInfo root = new DirectoryInfo(Application.dataPath); return FindFiles(fileName, root); } /// <summary> /// Locates the files that match the specified name within the package cache folder structure. /// </summary> /// <param name="fileName">The name of the file to locate (ex: "TestFile.asmdef")</param> /// <returns>Array of FileInfo objects representing the located file(s).</returns> public static FileInfo[] FindFilesInPackageCache(string fileName) { DirectoryInfo root = GetPackageCache(); return FindFiles(fileName, root); } /// <summary> /// Gets the package cache folder of this project. /// </summary> /// <returns> /// A DirectoryInfo object that describes the package cache folder. /// </returns> public static DirectoryInfo GetPackageCache() { string packageCacheFolderName = @"Library\PackageCache"; DirectoryInfo projectRoot = new DirectoryInfo(Application.dataPath).Parent; return new DirectoryInfo(Path.Combine(projectRoot.FullName, packageCacheFolderName)); } /// <summary> /// Finds all files matching the specified name. /// </summary> /// <param name="fileName">The name of the file to locate (ex: "TestFile.asmdef")</param> /// <param name="root">The folder in which to perform the search.</param> /// <returns>Array of FileInfo objects containing the search results.</returns> private static FileInfo[] FindFiles(string fileName, DirectoryInfo root) { return root.GetFiles(fileName, SearchOption.AllDirectories); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System.IO; using UnityEditor; using UnityEngine; namespace Microsoft.MixedReality.Toolkit.Utilities.Editor { /// <summary> /// A set of utilities for working with files. /// </summary> public static class FileUtilities { /// <summary> /// Locates the files that match the specified name within the Assets folder (application data path) structure. /// </summary> /// <param name="fileName">The name of the file to locate (ex: "TestFile.asmdef")</param> /// <returns>Array of FileInfo objects representing the located file(s).</returns> public static FileInfo[] FindFilesInAssets(string fileName) { DirectoryInfo root = new DirectoryInfo(Application.dataPath); return FindFiles(fileName, root); } /// <summary> /// Locates the files that match the specified name within the package cache folder structure. /// </summary> /// <param name="fileName">The name of the file to locate (ex: "TestFile.asmdef")</param> /// <returns>Array of FileInfo objects representing the located file(s).</returns> public static FileInfo[] FindFilesInPackageCache(string fileName) { DirectoryInfo root = GetPackageCache(); return FindFiles(fileName, root); } /// <summary> /// Gets the package cache folder of this project. /// </summary> /// <returns> /// A <see href="https://docs.microsoft.com/dotnet/api/system.io.directoryinfo"/>DirectoryInfo</see> object that describes the package cache folder. /// </returns> public static DirectoryInfo GetPackageCache() { string packageCacheFolderName = @"Library\PackageCache"; DirectoryInfo projectRoot = new DirectoryInfo(Application.dataPath).Parent; return new DirectoryInfo(Path.Combine(projectRoot.FullName, packageCacheFolderName)); } /// <summary> /// Finds all files matching the specified name. /// </summary> /// <param name="fileName">The name of the file to locate (ex: "TestFile.asmdef")</param> /// <param name="root">The folder in which to perform the search.</param> /// <returns>Array of FileInfo objects containing the search results.</returns> private static FileInfo[] FindFiles(string fileName, DirectoryInfo root) { return root.GetFiles(fileName, SearchOption.AllDirectories); } } }
mit
C#
c511a67e7a4553ce2128864454a2dea5cf865aca
Fix tournament POST not wrapping return value in an object.
Jaecen/Peregrine,Jaecen/Peregrine,Jaecen/Peregrine
src/Peregrine.Web/Controllers/TournamentsController.cs
src/Peregrine.Web/Controllers/TournamentsController.cs
using System; using System.Linq; using System.Web.Http; using Peregrine.Data; namespace Peregrine.Web.Controllers { [RoutePrefix("api/tournaments")] public class TournamentsController : ApiController { [Route] public IHttpActionResult Get() { using(var dataContext = new DataContext()) { var tournamentKeys = dataContext .Tournaments .Select(tournament => tournament.Key) .ToArray(); return Ok(new { keys = tournamentKeys, }); } } [Route] public IHttpActionResult Post() { using(var dataContext = new DataContext()) { var tournament = dataContext .Tournaments .Add(new Tournament { Key = Guid.NewGuid(), }); dataContext.SaveChanges(); return CreatedAtRoute( "tournament-get", new { tournamentKey = tournament.Key }, new { tournament = new { key = tournament.Key, } }); } } } }
using System; using System.Linq; using System.Web.Http; using Peregrine.Data; namespace Peregrine.Web.Controllers { [RoutePrefix("api/tournaments")] public class TournamentsController : ApiController { [Route] public IHttpActionResult Get() { using(var dataContext = new DataContext()) { var tournamentKeys = dataContext .Tournaments .Select(tournament => tournament.Key) .ToArray(); return Ok(new { keys = tournamentKeys, }); } } [Route] public IHttpActionResult Post() { using(var dataContext = new DataContext()) { var tournament = dataContext .Tournaments .Add(new Tournament { Key = Guid.NewGuid(), }); dataContext.SaveChanges(); return CreatedAtRoute( "tournament-get", new { tournamentKey = tournament.Key }, new { key = tournament.Key }); } } } }
mit
C#
6a2483a60ec253c85a5375a2a26bb06c4a6c1d11
configure await + comments
undergroundwires/SafeOrbit
src/SafeOrbit/Infrastructure/Extensions/TaskContext.cs
src/SafeOrbit/Infrastructure/Extensions/TaskContext.cs
using System; using System.Diagnostics; using System.Threading.Tasks; namespace SafeOrbit.Extensions { public static class TaskContext { /// <summary> /// Executes an async Task&lt;T&gt; method which has a T return type synchronously /// </summary> /// <typeparam name="T">Return Type</typeparam> /// <param name="task">Task&lt;T&gt; method to execute</param> /// <returns>Returns the waited result of the task</returns> [DebuggerHidden] public static T RunSync<T>(this Func<Task<T>> task) => task == null ? throw new ArgumentNullException(nameof(task)) : task.RunOnDefaultScheduler().RunSync(); /// <summary> /// Executes an async Task method which has a void return value synchronously /// </summary> /// <param name="task">Task method to execute</param> [DebuggerHidden] public static void RunSync(this Func<Task> task) => task.RunOnDefaultScheduler().RunSync(); [DebuggerHidden] private static void RunSync(this Task task) => // task.GetAwaiter().GetResult() : // Run sync & fixes stack traces on exceptions https://referencesource.microsoft.com/#mscorlib/system/runtime/compilerservices/TaskAwaiter.cs,ca9850c71672bd54 task.ConfigureAwait(false).GetAwaiter().GetResult(); [DebuggerHidden] private static T RunSync<T>(this Task<T> task) => task == null ? throw new ArgumentNullException(nameof(task)) : task.ConfigureAwait(false).GetAwaiter().GetResult(); } }
using System; using System.Diagnostics; using System.Threading.Tasks; namespace SafeOrbit.Extensions { public static class TaskContext { [DebuggerHidden] public static T RunSync<T>(this Func<Task<T>> func) => func == null ? throw new ArgumentNullException(nameof(func)) : func.RunOnDefaultScheduler().RunSync(); [DebuggerHidden] public static void RunSync(this Func<Task> func) => func.RunOnDefaultScheduler().RunSync(); // task.GetAwaiter().GetResult() : // Run sync & fixes stack traces on exceptions https://referencesource.microsoft.com/#mscorlib/system/runtime/compilerservices/TaskAwaiter.cs,ca9850c71672bd54 [DebuggerHidden] private static void RunSync(this Task task) => task.GetAwaiter().GetResult(); [DebuggerHidden] private static T RunSync<T>(this Task<T> task) => task == null ? throw new ArgumentNullException(nameof(task)) : task.GetAwaiter().GetResult(); } }
mit
C#
15f1153658d89af7098cb838899311492ff8da7c
Update Console Program with a Condition - Update GetRoleMessage
penblade/Training.CSharpWorkshop
Training.CSharpWorkshop/Program.cs
Training.CSharpWorkshop/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Training.CSharpWorkshop { public class Program { public static void Main(string[] args) { Process(); } public static void Process() { Console.WriteLine("Welcome to the C# Workshop."); Console.WriteLine("Please enter your user name: "); var userName = Console.ReadLine(); Console.WriteLine(); Console.WriteLine("Hello " + userName + "."); Console.WriteLine(GetRoleMessage(userName)); Console.WriteLine(); Console.WriteLine("Press enter to continue."); Console.ReadLine(); } public static string GetRoleMessage(string userName) { string role; if (userName == "Andrew") { role = "Admin"; } else { role = "Guest"; } return String.Format("Role: {0}.", role); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Training.CSharpWorkshop { public class Program { public static void Main(string[] args) { Process(); } public static void Process() { Console.WriteLine("Welcome to the C# Workshop."); Console.WriteLine("Please enter your user name: "); var userName = Console.ReadLine(); Console.WriteLine(); Console.WriteLine("Hello " + userName + "."); Console.WriteLine(GetRoleMessage(userName)); Console.WriteLine(); Console.WriteLine("Press enter to continue."); Console.ReadLine(); } public static string GetRoleMessage(string userName) { return "Role: Admin."; } } }
mit
C#
26eae84d179dbe175a876bc91d8a2018244b7d7d
Update the TryGetJointPose docs to accurately describe the set of inputs it can take.
DDReaper/MixedRealityToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity
Assets/MixedRealityToolkit/Providers/Hands/HandJointUtils.cs
Assets/MixedRealityToolkit/Providers/Hands/HandJointUtils.cs
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using Microsoft.MixedReality.Toolkit.Utilities; namespace Microsoft.MixedReality.Toolkit.Input { public static class HandJointUtils { /// <summary> /// Tries to get the the pose of the requested joint for the first controller with the specified handedness. /// </summary> /// <param name="joint">The requested joint</param> /// <param name="handedness">The specific hand of interest. This should be either Handedness.Left or Handedness.Right</param> /// <param name="pose">The output pose data</param> public static bool TryGetJointPose(TrackedHandJoint joint, Handedness handedness, out MixedRealityPose pose) { IMixedRealityHand hand = FindHand(handedness); if (hand != null) { return hand.TryGetJoint(joint, out pose); } pose = MixedRealityPose.ZeroIdentity; return false; } /// <summary> /// Find the first detected hand controller with matching handedness. /// </summary> /// <remarks> /// The given handeness should be either Handedness.Left or Handedness.Right. /// </remarks> public static IMixedRealityHand FindHand(Handedness handedness) { foreach (var detectedController in MixedRealityToolkit.InputSystem.DetectedControllers) { var hand = detectedController as IMixedRealityHand; if (hand != null) { if (detectedController.ControllerHandedness == handedness) { return hand; } } } return null; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using Microsoft.MixedReality.Toolkit.Utilities; namespace Microsoft.MixedReality.Toolkit.Input { public static class HandJointUtils { /// <summary> /// Try to find the first matching hand controller and return the pose of the requested joint for that hand. /// </summary> public static bool TryGetJointPose(TrackedHandJoint joint, Handedness handedness, out MixedRealityPose pose) { IMixedRealityHand hand = FindHand(handedness); if (hand != null) { return hand.TryGetJoint(joint, out pose); } pose = MixedRealityPose.ZeroIdentity; return false; } /// <summary> /// Find the first detected hand controller with matching handedness. /// </summary> public static IMixedRealityHand FindHand(Handedness handedness) { foreach (var detectedController in MixedRealityToolkit.InputSystem.DetectedControllers) { var hand = detectedController as IMixedRealityHand; if (hand != null) { if (detectedController.ControllerHandedness == handedness) { return hand; } } } return null; } } }
mit
C#
0d51b4f26823c870ac09c298fa499f68156766f3
add action link to pc/si code allocation
ndrmc/cats,ndrmc/cats,ndrmc/cats
Web/Areas/Logistics/Views/DispatchAllocation/Index.cshtml
Web/Areas/Logistics/Views/DispatchAllocation/Index.cshtml
@using Kendo.Mvc.UI @using LanguageHelpers.Localization @{ ViewBag.Title = "Index"; Layout = "~/Views/Shared/_MainLayout.cshtml"; } <fieldset> <legend> @Translator.Translate("Dispatch allocation") </legend> </fieldset> @section LeftBar{ @Html.Partial("_AllocationLeftBar") } @{ var ddl = Html.Kendo().DropDownList() .Name("category") .OptionLabel("Select a product...") .DataTextField("Name") .DataValueField("AdminUnitID") .HtmlAttributes(new {style = "width:200px"}) .Events(e => e.Change("regionsChange")) .DataSource(source => source.Read("GetRegions", "DispatchAllocation")); ddl.Render(); //displays the dropdown list var selected = ddl.ToComponent().Value;//gets the selected value } <div style="float: right; margin-right: 100px"> <div class="btn-group"> <button class="btn">Action</button> <button class="btn dropdown-toggle" data-toggle="dropdown"> <span class="caret"></span> </button> <ul class="dropdown-menu"> <li> <a href="@Url.Action("Hub", "DispatchAllocation",new {regionid = ViewBag.regionId})">hub allocation</a></li> <li><a href="@Url.Action("getIndexList", "SIAllocation", new { Area = "Logistics", regionid = ViewBag.regionId })">PC/SI code allocation</a></li> <li><a href="#">Generate TR</a></li> <li><a href="#"></a></li> </ul> </div> </div> <fieldset> <legend> @Translator.Translate("Allocated amount by Region and Hub") </legend> </fieldset> <div id ="HubAllocationPartial"> @Html.Partial("HubAllocation",(int)ViewBag.regionId) </div> <br/> <br/> <fieldset> <legend> @Translator.Translate("Hub allocated requisitions") </legend> </fieldset> <fieldset> <legend> <span style="font-size: small"> @Translator.Translate(" Requisition to be allocated PC/SI code")</span> </legend> </fieldset> <div id="ProjectCodeAllocationPartial"> @Html.Partial("AllocateProjectCode",(int)ViewBag.regionId) </div> <script> function regionsChange(e) { e.preventDefault(); var value = this.value(); window.location = null; window.location = "@Url.Action("RegionId", "DispatchAllocation")" + "?id=" + value; } </script>
@using Kendo.Mvc.UI @using LanguageHelpers.Localization @{ ViewBag.Title = "Index"; Layout = "~/Views/Shared/_MainLayout.cshtml"; } <fieldset> <legend> @Translator.Translate("Dispatch allocation") </legend> </fieldset> @section LeftBar{ @Html.Partial("_AllocationLeftBar") } @{ var ddl = Html.Kendo().DropDownList() .Name("category") .OptionLabel("Select a product...") .DataTextField("Name") .DataValueField("AdminUnitID") .HtmlAttributes(new {style = "width:200px"}) .Events(e => e.Change("regionsChange")) .DataSource(source => source.Read("GetRegions", "DispatchAllocation")); ddl.Render(); //displays the dropdown list var selected = ddl.ToComponent().Value;//gets the selected value } <div style="float: right; margin-right: 100px"> <div class="btn-group"> <button class="btn">Action</button> <button class="btn dropdown-toggle" data-toggle="dropdown"> <span class="caret"></span> </button> <ul class="dropdown-menu"> <li> <a href="@Url.Action("Hub", "DispatchAllocation",new {regionid = ViewBag.regionId})">hub allocation</a></li> <li><a href="#">pc/si code allocation</a></li> <li><a href="#">Generate TR</a></li> <li><a href="#"></a></li> </ul> </div> </div> <fieldset> <legend> @Translator.Translate("Allocated amount by Region and Hub") </legend> </fieldset> <div id ="HubAllocationPartial"> @Html.Partial("HubAllocation",(int)ViewBag.regionId) </div> <br/> <br/> <fieldset> <legend> @Translator.Translate("Hub allocated requisitions") </legend> </fieldset> <fieldset> <legend> <span style="font-size: small"> @Translator.Translate(" Requisition to be allocated PC/SI code")</span> </legend> </fieldset> <div id="ProjectCodeAllocationPartial"> @Html.Partial("AllocateProjectCode",(int)ViewBag.regionId) </div> <script> function regionsChange(e) { e.preventDefault(); var value = this.value(); window.location = null; window.location = "@Url.Action("RegionId", "DispatchAllocation")" + "?id=" + value; } </script>
apache-2.0
C#
942981956e6324508347d981008ab9b8359ca3a8
Update version
MarimerLLC/csla,rockfordlhotka/csla,MarimerLLC/csla,rockfordlhotka/csla,rockfordlhotka/csla,MarimerLLC/csla
Source/Csla.Axml.Android/Resources/Resource.Designer.cs
Source/Csla.Axml.Android/Resources/Resource.Designer.cs
#pragma warning disable 1591 //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ [assembly: global::Android.Runtime.ResourceDesignerAttribute("Csla.Axml.Resource", IsApplication=false)] namespace Csla.Axml { [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Android.Build.Tasks", "13.0.0.73")] public partial class Resource { static Resource() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } public partial class Attribute { static Attribute() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private Attribute() { } } public partial class String { // aapt resource value: 0x7F010000 public static int ApplicationName = 2130771968; static String() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private String() { } } } } #pragma warning restore 1591
#pragma warning disable 1591 //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ [assembly: global::Android.Runtime.ResourceDesignerAttribute("Csla.Axml.Resource", IsApplication=false)] namespace Csla.Axml { [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Android.Build.Tasks", "12.3.99.16")] public partial class Resource { static Resource() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } public partial class Attribute { static Attribute() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private Attribute() { } } public partial class String { // aapt resource value: 0x7F010000 public static int ApplicationName = 2130771968; static String() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private String() { } } } } #pragma warning restore 1591
mit
C#
6b7cb46ddaf9518e9f876535a86f385ed0db1a26
Add null hit windows
UselessToucan/osu,peppy/osu,ppy/osu,NeoAdonis/osu,NeoAdonis/osu,NeoAdonis/osu,peppy/osu,ppy/osu,smoogipoo/osu,smoogipoo/osu,UselessToucan/osu,smoogipoo/osu,peppy/osu-new,peppy/osu,UselessToucan/osu,smoogipooo/osu,ppy/osu
osu.Game.Rulesets.Osu/Objects/SpinnerTick.cs
osu.Game.Rulesets.Osu/Objects/SpinnerTick.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.Game.Audio; using osu.Game.Rulesets.Judgements; using osu.Game.Rulesets.Osu.Judgements; using osu.Game.Rulesets.Scoring; namespace osu.Game.Rulesets.Osu.Objects { public class SpinnerTick : OsuHitObject { public SpinnerTick() { Samples.Add(new HitSampleInfo { Name = "spinnerbonus" }); } public override Judgement CreateJudgement() => new OsuSpinnerTickJudgement(); protected override HitWindows CreateHitWindows() => null; } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Game.Audio; using osu.Game.Rulesets.Judgements; using osu.Game.Rulesets.Osu.Judgements; namespace osu.Game.Rulesets.Osu.Objects { public class SpinnerTick : OsuHitObject { public SpinnerTick() { Samples.Add(new HitSampleInfo { Name = "spinnerbonus" }); } public override Judgement CreateJudgement() => new OsuSpinnerTickJudgement(); } }
mit
C#
47781b053ee1e0c7ee5a8c6bbc37a75b23d70d77
Fix file system test failure (#735)
mjrousos/dotnet-apiport,Microsoft/dotnet-apiport,Microsoft/dotnet-apiport,conniey/dotnet-apiport,Microsoft/dotnet-apiport,mjrousos/dotnet-apiport,conniey/dotnet-apiport,conniey/dotnet-apiport
tests/ApiPort/ApiPortVS.Tests/ApiPortVSPackageTests.cs
tests/ApiPort/ApiPortVS.Tests/ApiPortVSPackageTests.cs
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using ApiPortVS.Analyze; using Microsoft.Fx.Portability.Reporting; using NSubstitute; using System.IO; using Xunit; namespace ApiPortVS.Tests { public class ApiPortVSPackageTests { [InlineData("analyzable.exe", true)] [InlineData("analyzable.dll", true)] [InlineData("analyzable.vshost.exe", false)] [Theory] public static void FileHasAnalyzableExtensionTest(string filename, bool expected) { var fileSystem = Substitute.For<IFileSystem>(); fileSystem.GetFileExtension(Arg.Any<string>()).Returns(arg => { var path = arg.Arg<string>(); return Path.GetExtension(path); }); var package = new ProjectAnalyzer( null, null, null, null, null, fileSystem, null, null); Assert.Equal(expected, package.FileHasAnalyzableExtension(filename)); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using ApiPortVS.Analyze; using ApiPortVS.Contracts; using Microsoft.Fx.Portability.Reporting; using NSubstitute; using System.IO; using System.Threading.Tasks; using Xunit; namespace ApiPortVS.Tests { public class ApiPortVSPackageTests { [Fact] public static void FileHasAnalyzableExtension_FileIsExe_ReturnsTrue() { var filename = "analyzable.exe"; var package = GetProjectAnalyzer(); var result = package.FileHasAnalyzableExtension(filename); Assert.True(result); } [Fact] public static void FileHasAnalyzableExtension_FileIsDll_ReturnsTrue() { var filename = "analyzable.dll"; var package = GetProjectAnalyzer(); var result = package.FileHasAnalyzableExtension(filename); Assert.True(result); } [Fact] public static void FileHasAnalyzableExtension_FilenameContainsVshost_ReturnsFalse() { var filename = "analyzable.vshost.exe"; var package = GetProjectAnalyzer(); var result = package.FileHasAnalyzableExtension(filename); Assert.False(result); } private static ProjectAnalyzer GetProjectAnalyzer() { var threadingService = Substitute.For<IVSThreadingService>(); threadingService.SwitchToMainThreadAsync().Returns(Task.CompletedTask); var fileSystem = Substitute.For<IFileSystem>(); fileSystem.GetFileExtension(Arg.Any<string>()).Returns(arg => { var path = arg.Arg<string>(); return Path.GetExtension(path); }); return new ProjectAnalyzer( null, null, null, null, null, fileSystem, null, null, threadingService); } } }
mit
C#
79cba6895750f6eec1fee7da55c5313d5e1050fe
Allow Selction via Move Adorner
icsharpcode/WpfDesigner,leocereus/WpfDesigner
WpfDesign.Designer/Project/Controls/PanelMoveAdorner.cs
WpfDesign.Designer/Project/Controls/PanelMoveAdorner.cs
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System.Windows.Controls; using System.Windows; using System.Windows.Input; using ICSharpCode.WpfDesign.Designer.Services; using System.Windows.Media; using ICSharpCode.WpfDesign.Designer.Converters; using System.Windows.Data; using ICSharpCode.WpfDesign.UIExtensions; namespace ICSharpCode.WpfDesign.Designer.Controls { public class PanelMoveAdorner : Control { static PanelMoveAdorner() { DefaultStyleKeyProperty.OverrideMetadata(typeof(PanelMoveAdorner), new FrameworkPropertyMetadata(typeof(PanelMoveAdorner))); } private ScaleTransform scaleTransform; public PanelMoveAdorner(DesignItem item) { this.item = item; scaleTransform = new ScaleTransform(1.0, 1.0); this.LayoutTransform = scaleTransform; } DesignItem item; protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e) { e.Handled = true; //item.Services.Selection.SetSelectedComponents(new DesignItem [] { item }, SelectionTypes.Auto); new DragMoveMouseGesture(item, false, true).Start(item.Services.DesignPanel, e); } public override void OnApplyTemplate() { base.OnApplyTemplate(); var bnd = new Binding("IsVisible") {Source = item.Component}; bnd.Converter = CollapsedWhenFalse.Instance; BindingOperations.SetBinding(this, UIElement.VisibilityProperty, bnd); var surface = this.TryFindParent<DesignSurface>(); if (surface != null && surface.ZoomControl != null) { bnd = new Binding("CurrentZoom") {Source = surface.ZoomControl}; bnd.Converter = InvertedZoomConverter.Instance; BindingOperations.SetBinding(scaleTransform, ScaleTransform.ScaleXProperty, bnd); BindingOperations.SetBinding(scaleTransform, ScaleTransform.ScaleYProperty, bnd); } } } }
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System.Windows.Controls; using System.Windows; using System.Windows.Input; using ICSharpCode.WpfDesign.Designer.Services; using System.Windows.Media; using ICSharpCode.WpfDesign.Designer.Converters; using System.Windows.Data; using ICSharpCode.WpfDesign.UIExtensions; namespace ICSharpCode.WpfDesign.Designer.Controls { public class PanelMoveAdorner : Control { static PanelMoveAdorner() { DefaultStyleKeyProperty.OverrideMetadata(typeof(PanelMoveAdorner), new FrameworkPropertyMetadata(typeof(PanelMoveAdorner))); } private ScaleTransform scaleTransform; public PanelMoveAdorner(DesignItem item) { this.item = item; scaleTransform = new ScaleTransform(1.0, 1.0); this.LayoutTransform = scaleTransform; } DesignItem item; protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e) { e.Handled = true; //item.Services.Selection.SetSelectedComponents(new DesignItem [] { item }, SelectionTypes.Auto); new DragMoveMouseGesture(item, false).Start(item.Services.DesignPanel, e); } public override void OnApplyTemplate() { base.OnApplyTemplate(); var bnd = new Binding("IsVisible") {Source = item.Component}; bnd.Converter = CollapsedWhenFalse.Instance; BindingOperations.SetBinding(this, UIElement.VisibilityProperty, bnd); var surface = this.TryFindParent<DesignSurface>(); if (surface != null && surface.ZoomControl != null) { bnd = new Binding("CurrentZoom") {Source = surface.ZoomControl}; bnd.Converter = InvertedZoomConverter.Instance; BindingOperations.SetBinding(scaleTransform, ScaleTransform.ScaleXProperty, bnd); BindingOperations.SetBinding(scaleTransform, ScaleTransform.ScaleYProperty, bnd); } } } }
mit
C#
08c9ddf97b957762f9fceb321e5fd9e7c619c465
Add GridContainerContent.ContentChanged event
peppy/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,peppy/osu-framework,ppy/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,peppy/osu-framework
osu.Framework/Graphics/Containers/GridContainerContent.cs
osu.Framework/Graphics/Containers/GridContainerContent.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; namespace osu.Framework.Graphics.Containers { public class GridContainerContent { public event Action ContentChanged; public GridContainerContent(Drawable[][] drawables) { _ = new ArrayWrapper<ArrayWrapper<Drawable>> { _ = new ArrayWrapper<Drawable>[drawables?.Length ?? 0] }; _.ArrayElementChanged += onArrayElementChanged; if (drawables != null) { for (int i = 0; i < drawables.Length; i++) { if (drawables[i] != null) { this[i] = new ArrayWrapper<Drawable> { _ = new Drawable[drawables[i].Length] }; this[i].ArrayElementChanged += onArrayElementChanged; for (int j = 0; j < drawables[i].Length; j++) { this[i][j] = drawables[i][j]; } } } } } private void onArrayElementChanged() { ContentChanged?.Invoke(); } public ArrayWrapper<ArrayWrapper<Drawable>> _ { get; } public ArrayWrapper<Drawable> this[int index] { get => _[index]; set => _[index] = value; } public class ArrayWrapper<T> { public event Action ArrayElementChanged; public T[] _ { get; set; } public T this[int index] { get => _[index]; set { _[index] = value; ArrayElementChanged?.Invoke(); } } } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. namespace osu.Framework.Graphics.Containers { public class GridContainerContent { public GridContainerContent(Drawable[][] drawables) { _ = new ArrayWrapper<Drawable>[drawables?.Length ?? 0]; if (drawables != null) { for (int i = 0; i < drawables.Length; i++) { if (drawables[i] != null) { _[i] = new ArrayWrapper<Drawable> { _ = new Drawable[drawables[i].Length] }; for (int j = 0; j < drawables[i].Length; j++) { _[i][j] = drawables[i][j]; } } } } } public ArrayWrapper<Drawable>[] _ { get; set; } public ArrayWrapper<Drawable> this[int index] { get => _[index]; set => _[index] = value; } public class ArrayWrapper<T> { public T[] _ { get; set; } public T this[int index] { get => _[index]; set => _[index] = value; } } } }
mit
C#
fbd7177e8d843d78934c36223d3616b8f3183219
Update IPricingStrategy.cs
tiksn/TIKSN-Framework
TIKSN.Core/Finance/IPricingStrategy.cs
TIKSN.Core/Finance/IPricingStrategy.cs
namespace TIKSN.Finance { public interface IPricingStrategy { decimal EstimateMarketPrice(decimal basePrice); Money EstimateMarketPrice(Money basePrice); } }
namespace TIKSN.Finance { public interface IPricingStrategy { decimal EstimateMarketPrice(decimal basePrice); Money EstimateMarketPrice(Money basePrice); } }
mit
C#
9b25dde0a76e8ede17efb742c4941a9d20d6bae5
Test many to many modelling.
SilkStack/Silk.Data.SQL.ORM
Silk.Data.SQL.ORM.Tests/ManyToManyTests.cs
Silk.Data.SQL.ORM.Tests/ManyToManyTests.cs
using Microsoft.VisualStudio.TestTools.UnitTesting; using Silk.Data.SQL.ORM.Modelling; using System; using System.Collections.Generic; using System.Linq; namespace Silk.Data.SQL.ORM.Tests { [TestClass] public class ManyToManyTests { private EntityModel<PocoWithManyRelationships> _conventionDrivenModel = TestDb.CreateDomainAndModel<PocoWithManyRelationships>(builder => { builder.AddDataEntity<RelationshipTypeA>(); builder.AddDataEntity<RelationshipTypeB>(); }); [TestMethod] public void ConventionDrivenModelModelsManyToMany() { var model = _conventionDrivenModel; Assert.AreEqual(3, model.Fields.Length); Assert.AreEqual(3, model.Schema.Tables.Count); var fieldForRelationshipA = model.Fields.FirstOrDefault(q => q.Name == "RelationshipA"); var fieldForRelationshipB = model.Fields.FirstOrDefault(q => q.Name == "RelationshipB"); Assert.IsNotNull(fieldForRelationshipA); Assert.IsNotNull(fieldForRelationshipA.Relationship); Assert.ReferenceEquals(model.Domain.GetEntityModel<RelationshipTypeA>(), fieldForRelationshipA.Relationship.ForeignModel); Assert.AreEqual(RelationshipType.ManyToMany, fieldForRelationshipA.Relationship.RelationshipType); Assert.IsNull(fieldForRelationshipA.Storage); Assert.IsNotNull(fieldForRelationshipB); Assert.IsNotNull(fieldForRelationshipB.Relationship); Assert.ReferenceEquals(model.Domain.GetEntityModel<RelationshipTypeB>(), fieldForRelationshipB.Relationship.ForeignModel); Assert.AreEqual(RelationshipType.ManyToMany, fieldForRelationshipB.Relationship.RelationshipType); Assert.IsNull(fieldForRelationshipB.Storage); Assert.AreEqual(1, model.Schema.EntityTable.DataFields.Length); var idField = model.Schema.EntityTable.DataFields.FirstOrDefault(q => q.Name == "Id"); Assert.IsNotNull(idField); Assert.AreEqual(typeof(Guid), idField.DataType); Assert.IsTrue(idField.Storage.IsAutoGenerate); Assert.IsTrue(idField.Storage.IsPrimaryKey); var relationshipATable = model.Schema.RelationshipTables.FirstOrDefault(q => q.TableName == "PocoWithManyRelationshipsToRelationshipTypeA"); Assert.AreEqual(2, relationshipATable.DataFields.Length); var modelIdField = relationshipATable.DataFields.FirstOrDefault(q => q.Name == "PocoWithManyRelationships_Id"); Assert.IsNotNull(modelIdField); Assert.AreEqual(typeof(Guid), modelIdField.DataType); var relationshipIdField = relationshipATable.DataFields.FirstOrDefault(q => q.Name == "RelationshipTypeA_Id"); Assert.IsNotNull(relationshipIdField); Assert.AreEqual(typeof(int), relationshipIdField.DataType); var relationshipBTable = model.Schema.RelationshipTables.FirstOrDefault(q => q.TableName == "PocoWithManyRelationshipsToRelationshipTypeB"); Assert.AreEqual(2, relationshipBTable.DataFields.Length); modelIdField = relationshipBTable.DataFields.FirstOrDefault(q => q.Name == "PocoWithManyRelationships_Id"); Assert.IsNotNull(modelIdField); Assert.AreEqual(typeof(Guid), modelIdField.DataType); relationshipIdField = relationshipBTable.DataFields.FirstOrDefault(q => q.Name == "RelationshipTypeB_Id"); Assert.IsNotNull(relationshipIdField); Assert.AreEqual(typeof(Guid), relationshipIdField.DataType); } private class PocoWithManyRelationships { public Guid Id { get; private set; } public List<RelationshipTypeA> RelationshipA { get; set; } = new List<RelationshipTypeA>(); public RelationshipTypeB[] RelationshipB { get; set; } = new RelationshipTypeB[0]; } private class RelationshipTypeA { public int Id { get; private set; } public int Data { get; set; } } private class RelationshipTypeB { public Guid Id { get; private set; } public int Data { get; set; } } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using Silk.Data.SQL.ORM.Modelling; using System; using System.Collections.Generic; namespace Silk.Data.SQL.ORM.Tests { [TestClass] public class ManyToManyTests { private EntityModel<PocoWithManyRelationships> _conventionDrivenModel = TestDb.CreateDomainAndModel<PocoWithManyRelationships>(builder => { builder.AddDataEntity<RelationshipTypeA>(); builder.AddDataEntity<RelationshipTypeB>(); }); [TestMethod] public void ConventionDrivenModelModelsManyToMany() { var model = _conventionDrivenModel; Assert.AreEqual(3, model.Fields.Length); Assert.AreEqual(3, model.Schema.Tables.Count); Assert.Fail("Test not complete"); } private class PocoWithManyRelationships { public Guid Id { get; private set; } public List<RelationshipTypeA> RelationshipA { get; set; } = new List<RelationshipTypeA>(); public RelationshipTypeB[] RelationshipB { get; set; } = new RelationshipTypeB[0]; } private class RelationshipTypeA { public int Id { get; private set; } public int Data { get; set; } } private class RelationshipTypeB { public Guid Id { get; private set; } public int Data { get; set; } } } }
mit
C#
e4b4d1d94a129f9e86284f60a0f957e41c4bcc46
Move call to UseFluentActions before UseMvc in hello world sample project
ExplicitlyImplicit/AspNetCore.Mvc.FluentActions,ExplicitlyImplicit/AspNetCore.Mvc.FluentActions
samples/HelloWorld/Startup.cs
samples/HelloWorld/Startup.cs
using ExplicitlyImpl.AspNetCore.Mvc.FluentActions; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; namespace HelloWorld { public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddMvc().AddFluentActions(); } public void Configure(IApplicationBuilder app) { app.UseFluentActions(actions => { actions.RouteGet("/").To(() => "Hello World!"); }); app.UseMvc(); } } }
using ExplicitlyImpl.AspNetCore.Mvc.FluentActions; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; namespace HelloWorld { public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddMvc().AddFluentActions(); } public void Configure(IApplicationBuilder app) { app.UseMvc(); app.UseFluentActions(actions => { actions.RouteGet("/").To(() => "Hello World!"); }); } } }
mit
C#
6dc0f3b720e78f5f965ee2e5211e5a39c3788657
Load fonts over https if using https
johanhelsing/vaskelista,johanhelsing/vaskelista
Vaskelista/Views/Shared/_Layout.cshtml
Vaskelista/Views/Shared/_Layout.cshtml
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>@ViewBag.Title - Vaskelista</title> @Styles.Render("~/Content/css") @Mvc.RazorTools.BundleManager.Styles.Render() @Styles.Render("~/Content/less") @Scripts.Render("~/bundles/modernizr") <link href='//fonts.googleapis.com/css?family=Patrick+Hand+SC|Schoolbell' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Roboto:400,100,700' rel='stylesheet' type='text/css' /> <link rel="shortcut icon" href="../favicon.ico" /> </head> <body> <main class="main container body-content"> @RenderBody() </main> @Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/bootstrap") @RenderSection("scripts", required: false) </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>@ViewBag.Title - Vaskelista</title> @Styles.Render("~/Content/css") @Mvc.RazorTools.BundleManager.Styles.Render() @Styles.Render("~/Content/less") @Scripts.Render("~/bundles/modernizr") <link href='http://fonts.googleapis.com/css?family=Patrick+Hand+SC|Schoolbell' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Roboto:400,100,700' rel='stylesheet' type='text/css' /> <link rel="shortcut icon" href="../favicon.ico" /> </head> <body> <main class="main container body-content"> @RenderBody() </main> @Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/bootstrap") @RenderSection("scripts", required: false) </body> </html>
mit
C#
aa083036575e435ffb6406a778c06d822c3a6270
Build and publish nuget package
rlyczynski/XSerializer,QuickenLoans/XSerializer
XSerializer/Properties/AssemblyInfo.cs
XSerializer/Properties/AssemblyInfo.cs
using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("XSerializer")] [assembly: AssemblyDescription("Advanced, high-performance XML and JSON serializers")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Quicken Loans")] [assembly: AssemblyProduct("XSerializer")] [assembly: AssemblyCopyright("Copyright © Quicken Loans 2013-2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("5aeaebd0-35de-424c-baa9-ba6d65fa3409")] [assembly: CLSCompliant(true)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.1.0.0")] [assembly: AssemblyFileVersion("0.3.2")] [assembly: AssemblyInformationalVersion("0.3.2")] #if !BUILD [assembly: InternalsVisibleTo("XSerializer.Tests")] [assembly: InternalsVisibleTo("XSerializer.PerformanceTests")] #endif
using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("XSerializer")] [assembly: AssemblyDescription("Advanced, high-performance XML and JSON serializers")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Quicken Loans")] [assembly: AssemblyProduct("XSerializer")] [assembly: AssemblyCopyright("Copyright © Quicken Loans 2013-2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("5aeaebd0-35de-424c-baa9-ba6d65fa3409")] [assembly: CLSCompliant(true)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.1.0.0")] [assembly: AssemblyFileVersion("0.3.1")] [assembly: AssemblyInformationalVersion("0.3.1")] #if !BUILD [assembly: InternalsVisibleTo("XSerializer.Tests")] [assembly: InternalsVisibleTo("XSerializer.PerformanceTests")] #endif
mit
C#
a12bbcc4b4cddf7e3377c49c9712a9c4843c53ab
use appropriate check method
aloisdeniel/Mvvmicro
Sources/Mvvmicro/Dependencies/Container.cs
Sources/Mvvmicro/Dependencies/Container.cs
namespace Mvvmicro { using System; using System.Collections.Generic; public class Container : IContainer { #region Default private static Lazy<IContainer> instance = new Lazy<IContainer>(() => new Container()); /// <summary> /// Gets the default container. /// </summary> /// <value>The default.</value> public static IContainer Default => instance.Value; #endregion #region Fields private Dictionary<Type, object> instances = new Dictionary<Type, object>(); private Dictionary<Type, Tuple<bool, Func<object>>> factories = new Dictionary<Type, Tuple<bool, Func<object>>>(); #endregion #region Methods public T Get<T>() { var factory = this.factories[typeof(T)]; if (factory.Item1) { if (instances.TryGetValue(typeof(T), out object instance)) { return (T)instance; } var newInstance = factory.Item2(); instances[typeof(T)] = newInstance; return (T)newInstance; } return (T)factory.Item2(); } public void Register<T>(Func<IContainer, T> factory, bool isInstance = false) { this.factories[typeof(T)] = new Tuple<bool, Func<object>>(isInstance, () => factory(this)); } public bool IsRegistered<T>() => factories.ContainsKey(typeof(T)); public T New<T>() => (T)this.factories[typeof(T)].Item2(); #endregion } }
namespace Mvvmicro { using System; using System.Collections.Generic; public class Container : IContainer { #region Default private static Lazy<IContainer> instance = new Lazy<IContainer>(() => new Container()); /// <summary> /// Gets the default container. /// </summary> /// <value>The default.</value> public static IContainer Default => instance.Value; #endregion #region Fields private Dictionary<Type, object> instances = new Dictionary<Type, object>(); private Dictionary<Type, Tuple<bool, Func<object>>> factories = new Dictionary<Type, Tuple<bool, Func<object>>>(); #endregion #region Methods public T Get<T>() { var factory = this.factories[typeof(T)]; if (factory.Item1) { if (instances.TryGetValue(typeof(T), out object instance)) { return (T)instance; } var newInstance = factory.Item2(); instances[typeof(T)] = newInstance; return (T)newInstance; } return (T)factory.Item2(); } public void Register<T>(Func<IContainer, T> factory, bool isInstance = false) { this.factories[typeof(T)] = new Tuple<bool, Func<object>>(isInstance, () => factory(this)); } public bool IsRegistered<T>() { try { var factory = this.factories[typeof(T)]; return true; } catch (KeyNotFoundException) { return false; } } public T New<T>() => (T)this.factories[typeof(T)].Item2(); #endregion } }
mit
C#
9bfd599892678c090408c021f7a6a213536b562d
Remove a superfluous 'unsafe'
Tragetaschen/DbusCore
src/Dbus/UnixFdStream.cs
src/Dbus/UnixFdStream.cs
using System; using System.IO; using System.Runtime.InteropServices; namespace Dbus { internal class UnixFdStream : Stream { private readonly SafeHandle safeHandle; private readonly SocketOperations socketOperations; public UnixFdStream(SafeHandle safeHandle, SocketOperations socketOperations) { this.safeHandle = safeHandle; this.socketOperations = socketOperations; socketOperations.SetNonblocking(safeHandle); } public override bool CanRead => true; public override bool CanSeek => false; public override bool CanWrite => true; public override long Length => throw new NotImplementedException(); public override long Position { get; set; } public override void Flush() { } public override int Read(byte[] buffer, int offset, int count) => socketOperations.Read(safeHandle, buffer, offset, count); public override long Seek(long offset, SeekOrigin origin) => 0; public override void SetLength(long value) { } public override void Write(byte[] buffer, int offset, int count) => socketOperations.Send(safeHandle, buffer, offset, count); protected override void Dispose(bool disposing) { if (safeHandle != null) safeHandle.Close(); base.Dispose(disposing); } } }
using System; using System.IO; using System.Runtime.InteropServices; namespace Dbus { internal class UnixFdStream : Stream { private readonly SafeHandle safeHandle; private readonly SocketOperations socketOperations; public UnixFdStream(SafeHandle safeHandle, SocketOperations socketOperations) { this.safeHandle = safeHandle; this.socketOperations = socketOperations; socketOperations.SetNonblocking(safeHandle); } public override bool CanRead => true; public override bool CanSeek => false; public override bool CanWrite => true; public override long Length => throw new NotImplementedException(); public override long Position { get; set; } public override void Flush() { } public override unsafe int Read(byte[] buffer, int offset, int count) => socketOperations.Read(safeHandle, buffer, offset, count); public override long Seek(long offset, SeekOrigin origin) => 0; public override void SetLength(long value) { } public override void Write(byte[] buffer, int offset, int count) => socketOperations.Send(safeHandle, buffer, offset, count); protected override void Dispose(bool disposing) { if (safeHandle != null) safeHandle.Close(); base.Dispose(disposing); } } }
mit
C#
fd128b5c7b9ec16219a2720fb43e4b790377c8c4
Implement Lookup, Define API
yanhkim/mime.net
Mime.cs
Mime.cs
using System; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; namespace mime.net { public static class Mime { private static Dictionary<string, string> types = new Dictionary<string, string>(); private static bool loaded; public static string Lookup(string path) { string ext = ExtractExtension(path), mime; if (!Types.TryGetValue(ext, out mime)) { mime = DefaultType; } return mime; } private static string ExtractExtension(string path) { return Regex.Replace(path, @".*[\.\/\\]", String.Empty).ToLower(); } private static Dictionary<string, string> Types { get { if (loaded) return types; Load(Properties.Resources.mimeTypes); Load(Properties.Resources.nodeTypes); loaded = true; DefaultType = Lookup("bin"); return types; } } private static void Load(string content) { var map = new Dictionary<string, IEnumerable<string>>(); var lines = Regex.Split(content, @"[\r\n]+"); foreach (var line in lines) { var striped = Regex.Replace(line, @"\s*#.*|^\s*|\s*$", String.Empty); var fields = Regex.Split(striped, @"\s+"); if (fields[0] == String.Empty) { continue; } var list = new List<string>(fields); var ext = list[0]; list.RemoveAt(0); map[ext] = list; } Define(map); } public static void Define(IDictionary<string, IEnumerable<string>> map) { foreach (var type in map) { var exts = type.Value; foreach (var ext in exts) { types[ext] = type.Key; } } } public static string DefaultType { get; set; } } }
using System; using System.Collections.Generic; using System.Text; namespace mime.net { public static class Mime { public static string Lookup(string path) { throw new NotImplementedException(); } } }
mit
C#
5b1b12a85fead60c4f5ef874cf78d2492f718225
fix completion bug.
hecomi/uREPL
Assets/uREPL/Scripts/GuiParts/CompletionItem.cs
Assets/uREPL/Scripts/GuiParts/CompletionItem.cs
using UnityEngine; using UnityEngine.UI; using System.Collections.Generic; using System.Linq; namespace uREPL { public class CompletionItem : MonoBehaviour { public Text markText; public Text completionText; public Image colorIndicator; public Color32 hasDescriptionColor = new Color32(200, 30, 70, 255); public Color32 markColor = Color.gray; public Color32 hitTextColor = Color.white; public Color32 bgColor = Color.black; public Color32 highlightedBgColor = new Color32(30, 30, 30, 200); public string description = ""; public bool hasDescription { get { return !string.IsNullOrEmpty(description); } } private string completion_; public string completion { get { return completion_; } } private Image image_; void Awake() { image_ = GetComponent<Image>(); } void Update() { if (hasDescription) { colorIndicator.color = hasDescriptionColor; } } public void SetHighlight(bool isHighlighted) { image_.color = isHighlighted ? highlightedBgColor : bgColor; } public void SetCompletion(string code, string prefix) { completion_ = string.IsNullOrEmpty(prefix) ? code : code.Substring(prefix.Length); var hitTextColorHex = hitTextColor.r.ToString("X2") + hitTextColor.g.ToString("X2") + hitTextColor.b.ToString("X2") + hitTextColor.a.ToString("X2"); completionText.text = string.Format( "<b><color=#{2}>{0}</color></b>{1}", prefix, completion_, hitTextColorHex.ToString()); } public void SetMark(string mark, Color32 color) { markText.text = mark; markText.color = color; } } }
using UnityEngine; using UnityEngine.UI; using System.Collections.Generic; using System.Linq; namespace uREPL { public class CompletionItem : MonoBehaviour { public Text markText; public Text completionText; public Image colorIndicator; public Color32 hasDescriptionColor = new Color32(200, 30, 70, 255); public Color32 markColor = Color.gray; public Color32 hitTextColor = Color.white; public Color32 bgColor = Color.black; public Color32 highlightedBgColor = new Color32(30, 30, 30, 200); public string description = ""; public bool hasDescription { get { return !string.IsNullOrEmpty(description); } } private string completion_; public string completion { get { return completion_; } } private Image image_; void Awake() { image_ = GetComponent<Image>(); } void Update() { if (hasDescription) { colorIndicator.color = hasDescriptionColor; } } public void SetHighlight(bool isHighlighted) { image_.color = isHighlighted ? highlightedBgColor : bgColor; } public void SetCompletion(string code, string prefix) { completion_ = string.IsNullOrEmpty(prefix) ? code : code.Replace(prefix, ""); var hitTextColorHex = hitTextColor.r.ToString("X2") + hitTextColor.g.ToString("X2") + hitTextColor.b.ToString("X2") + hitTextColor.a.ToString("X2"); completionText.text = string.Format( "<b><color=#{2}>{0}</color></b>{1}", prefix, completion_, hitTextColorHex.ToString()); } public void SetMark(string mark, Color32 color) { markText.text = mark; markText.color = color; } } }
mit
C#
7d4c5999f663cccc47f84211d7ac58bf838c1bbc
Add description in test case.
NeoAdonis/osu,DrabWeb/osu,johnneijzen/osu,2yangk23/osu,johnneijzen/osu,ZLima12/osu,smoogipoo/osu,peppy/osu,NeoAdonis/osu,Frontear/osuKyzer,smoogipoo/osu,DrabWeb/osu,ppy/osu,naoey/osu,UselessToucan/osu,peppy/osu-new,UselessToucan/osu,ZLima12/osu,Nabile-Rahmani/osu,2yangk23/osu,EVAST9919/osu,EVAST9919/osu,smoogipooo/osu,NeoAdonis/osu,Damnae/osu,UselessToucan/osu,ppy/osu,Drezi126/osu,peppy/osu,ppy/osu,peppy/osu,smoogipoo/osu,DrabWeb/osu,naoey/osu,naoey/osu
osu.Desktop.VisualTests/Tests/TestCaseUserProfile.cs
osu.Desktop.VisualTests/Tests/TestCaseUserProfile.cs
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using osu.Framework.Graphics; using osu.Framework.Testing; using osu.Game.Overlays; using osu.Game.Users; namespace osu.Desktop.VisualTests.Tests { internal class TestCaseUserProfile : TestCase { public override string Description => "Tests user's profile page."; public override void Reset() { base.Reset(); var userpage = new UserProfile(new User { Username = @"peppy", Id = 2, Country = new Country { FlagName = @"AU" }, CoverUrl = @"https://osu.ppy.sh/images/headers/profile-covers/c3.jpg" }) { Anchor = Anchor.Centre, Origin = Anchor.Centre, Width = 800, Height = 500 }; Add(userpage); AddStep("Toggle", userpage.ToggleVisibility); } } }
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using osu.Framework.Graphics; using osu.Framework.Testing; using osu.Game.Overlays; using osu.Game.Users; namespace osu.Desktop.VisualTests.Tests { internal class TestCaseUserProfile : TestCase { public override void Reset() { base.Reset(); var userpage = new UserProfile(new User { Username = @"peppy", Id = 2, Country = new Country { FlagName = @"AU" }, CoverUrl = @"https://osu.ppy.sh/images/headers/profile-covers/c3.jpg" }) { Anchor = Anchor.Centre, Origin = Anchor.Centre, Width = 800, Height = 500 }; Add(userpage); AddStep("Toggle", userpage.ToggleVisibility); } } }
mit
C#
6f7c7ea4384744673e02298a75b20897ebfcabe2
change Addin name to better reflect intention with NUnit attribute "RequiredAddin"
concordion/concordion-net,ShaKaRee/concordion-net,ShaKaRee/concordion-net,concordion/concordion-net,concordion/concordion-net,ShaKaRee/concordion-net
Concordion.Integration.NUnit/Addin/SuiteBuilderAddin.cs
Concordion.Integration.NUnit/Addin/SuiteBuilderAddin.cs
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using NUnit.Core; using NUnit.Core.Extensibility; namespace Concordion.Integration.NUnit.Addin { [NUnitAddin(Name = "ConcordionNUnitAddin", Description = "Runs Concordion Tests with NUnit", Type = ExtensionType.Core)] public class SuiteBuilderAddin : ISuiteBuilder, IAddin { #region Implementation of ISuiteBuilder public bool CanBuildFrom(Type type) { return Reflect.HasAttribute(type, "Concordion.Integration.ConcordionTestAttribute", false); } public Test BuildFrom(Type type) { var testSuite = new TestSuite(type); testSuite.Add(new ConcordionTest(type)); NUnitFramework.ApplyCommonAttributes(type, testSuite); return testSuite; } #endregion #region Implementation of IAddin public bool Install(IExtensionHost host) { IExtensionPoint extensionPoint = host.GetExtensionPoint("SuiteBuilders"); if (extensionPoint == null) return false; extensionPoint.Install(this); return true; } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using NUnit.Core; using NUnit.Core.Extensibility; namespace Concordion.Integration.NUnit.Addin { [NUnitAddin(Name = "Concordion Test Runner", Description = "Runs Concordion Tests with NUnit", Type = ExtensionType.Core)] public class SuiteBuilderAddin : ISuiteBuilder, IAddin { #region Implementation of ISuiteBuilder public bool CanBuildFrom(Type type) { return Reflect.HasAttribute(type, "Concordion.Integration.ConcordionTestAttribute", false); } public Test BuildFrom(Type type) { var testSuite = new TestSuite(type); testSuite.Add(new ConcordionTest(type)); NUnitFramework.ApplyCommonAttributes(type, testSuite); return testSuite; } #endregion #region Implementation of IAddin public bool Install(IExtensionHost host) { IExtensionPoint extensionPoint = host.GetExtensionPoint("SuiteBuilders"); if (extensionPoint == null) return false; extensionPoint.Install(this); return true; } #endregion } }
apache-2.0
C#
7a6a3d40b24350e799fe23050115069dccd3df49
Add ReleaseInternal method. Change Release method. Rearrange logic of Dispose method. Return current object instance from Validate method.
Archie-Yang/PcscDotNet
src/PcscDotNet/PcscContext.cs
src/PcscDotNet/PcscContext.cs
using System; namespace PcscDotNet { public class PcscContext : IDisposable { private SCardContext _handle; private readonly Pcsc _pcsc; private readonly IPcscProvider _provider; public bool IsDisposed { get; private set; } = false; public bool IsEstablished => _handle.HasValue; public Pcsc Pcsc => _pcsc; public PcscContext(Pcsc pcsc) { _pcsc = pcsc; _provider = pcsc.Provider; } public PcscContext(Pcsc pcsc, SCardScope scope) : this(pcsc) { Establish(scope); } ~PcscContext() { Dispose(); } public void Dispose() { if (IsDisposed) return; ReleaseInternal(); IsDisposed = true; GC.SuppressFinalize(this); } public unsafe PcscContext Establish(SCardScope scope) { if (IsDisposed) throw new ObjectDisposedException(nameof(PcscContext), nameof(Establish)); if (IsEstablished) throw new InvalidOperationException("Context has been established."); SCardContext handle; _provider.SCardEstablishContext(scope, null, null, &handle).ThrowIfNotSuccess(); _handle = handle; return this; } public PcscContext Release() { if (IsDisposed) throw new ObjectDisposedException(nameof(PcscContext), nameof(Release)); ReleaseInternal(); return this; } public PcscContext Validate() { if (IsDisposed) throw new ObjectDisposedException(nameof(PcscContext), nameof(Validate)); _provider.SCardIsValidContext(_handle).ThrowIfNotSuccess(); return this; } private void ReleaseInternal() { if (!IsEstablished) return; _provider.SCardReleaseContext(_handle).ThrowIfNotSuccess(); _handle = SCardContext.Default; } } }
using System; namespace PcscDotNet { public class PcscContext : IDisposable { private SCardContext _handle; private readonly Pcsc _pcsc; private readonly IPcscProvider _provider; public bool IsDisposed { get; private set; } = false; public bool IsEstablished => _handle.HasValue; public Pcsc Pcsc => _pcsc; public PcscContext(Pcsc pcsc) { _pcsc = pcsc; _provider = pcsc.Provider; } public PcscContext(Pcsc pcsc, SCardScope scope) : this(pcsc) { Establish(scope); } ~PcscContext() { Dispose(); } public unsafe PcscContext Establish(SCardScope scope) { if (IsDisposed) throw new ObjectDisposedException(nameof(PcscContext), nameof(Establish)); if (IsEstablished) throw new InvalidOperationException("Context has been established."); SCardContext handle; _provider.SCardEstablishContext(scope, null, null, &handle).ThrowIfNotSuccess(); _handle = handle; return this; } public PcscContext Release() { if (IsDisposed) throw new ObjectDisposedException(nameof(PcscContext), nameof(Release)); if (IsEstablished) { _provider.SCardReleaseContext(_handle).ThrowIfNotSuccess(); _handle = SCardContext.Default; } return this; } public void Validate() { if (IsDisposed) throw new ObjectDisposedException(nameof(PcscContext), nameof(Validate)); _provider.SCardIsValidContext(_handle).ThrowIfNotSuccess(); } public void Dispose() { if (IsDisposed) return; Release(); GC.SuppressFinalize(this); IsDisposed = true; } } }
mit
C#
8ef74ec4ffaefc89c15d1c02ea323daf3739d749
allow selected row background color to be overriden.
grokys/Perspex,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,akrisiun/Perspex,wieslawsoltes/Perspex,jkoritzinsky/Perspex,jkoritzinsky/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,Perspex/Perspex,SuperJMN/Avalonia,SuperJMN/Avalonia,Perspex/Perspex,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,grokys/Perspex,wieslawsoltes/Perspex,SuperJMN/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia
src/Avalonia.DataGrid.Themes.Default/DefaultTheme.xaml.cs
src/Avalonia.DataGrid.Themes.Default/DefaultTheme.xaml.cs
using Avalonia; using Avalonia.Controls; using Avalonia.Markup.Xaml; using Avalonia.Styling; namespace Avalonia.DataGrid.Themes.Default { public class DefaultTheme : Styles { public DefaultTheme() { this.InitializeComponent(); } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } } }
using Avalonia; using Avalonia.Controls; using Avalonia.Markup.Xaml; using Avalonia.Styling; namespace Avalonia.Themes.DataGrid.Default { public class DefaultTheme : Styles { public DefaultTheme() { this.InitializeComponent(); } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } } }
mit
C#
f892bce7ca41a4679e6d8052017e687d83c26432
Rollback now uses the changes field of the change collection instead of traverse flat.
georghinkel/NMF,NMFCode/NMF
Models/Models/NMFTransaction.cs
Models/Models/NMFTransaction.cs
using System; using System.Linq; using System.Transactions; using NMF.Expressions; using NMF.Models.Evolution; using NMF.Models.Repository; namespace NMF.Models { class NMFTransaction : IDisposable { private bool _committed; private readonly ExecutionEngine _engine = ExecutionEngine.Current; private readonly ModelChangeRecorder _recorder = new ModelChangeRecorder(); private IModelRepository _repository; //private TransactionScope _scope; public NMFTransaction(IModelElement rootElement) { if (rootElement == null) throw new ArgumentNullException(nameof(rootElement)); _repository = rootElement.Model.Repository; _recorder.Start(rootElement); //_scope = new TransactionScope(); _engine.BeginTransaction(); } public void Commit() { //if (_scope == null) throw new InvalidOperationException(); _engine.CommitTransaction(); _committed = true; //_scope.Complete(); } public void Rollback() { var modelChanges = _recorder.GetModelChanges().Changes; _recorder.Stop(); modelChanges.Reverse(); foreach (var change in modelChanges) change.Invert(_repository); _engine.RollbackTransaction(); } public void Dispose() { if (!_committed) Rollback(); //if (_scope != null) //{ // _scope.Dispose(); // _scope = null; //} } } }
using System; using System.Linq; using System.Transactions; using NMF.Expressions; using NMF.Models.Evolution; using NMF.Models.Repository; namespace NMF.Models { class NMFTransaction : IDisposable { private bool _committed; private readonly ExecutionEngine _engine = ExecutionEngine.Current; private readonly ModelChangeRecorder _recorder = new ModelChangeRecorder(); private IModelRepository _repository; //private TransactionScope _scope; public NMFTransaction(IModelElement rootElement) { if (rootElement == null) throw new ArgumentNullException(nameof(rootElement)); _repository = rootElement.Model.Repository; _recorder.Start(rootElement); //_scope = new TransactionScope(); _engine.BeginTransaction(); } public void Commit() { //if (_scope == null) throw new InvalidOperationException(); _engine.CommitTransaction(); _committed = true; //_scope.Complete(); } public void Rollback() { var modelChanges = _recorder.GetModelChanges().TraverseFlat().Reverse(); _recorder.Stop(); foreach (var change in modelChanges) change.Invert(_repository); _engine.RollbackTransaction(); } public void Dispose() { if (!_committed) Rollback(); //if (_scope != null) //{ // _scope.Dispose(); // _scope = null; //} } } }
bsd-3-clause
C#
bbc6ce27f2d75cb53e741b645e32ca781bddf48d
Update ShapeStateTypeConverter.cs
Core2D/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D
src/Serializer.Xaml/Converters/ShapeStateTypeConverter.cs
src/Serializer.Xaml/Converters/ShapeStateTypeConverter.cs
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Globalization; #if NETSTANDARD1_3 using System.ComponentModel; #endif using Core2D.Shape; using Portable.Xaml.ComponentModel; namespace Serializer.Xaml.Converters { /// <summary> /// Defines <see cref="ShapeState"/> type converter. /// </summary> internal class ShapeStateTypeConverter : TypeConverter { /// <inheritdoc/> public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { return sourceType == typeof(string); } /// <inheritdoc/> public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { return destinationType == typeof(string); } /// <inheritdoc/> public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { return ShapeState.Parse((string)value); } /// <inheritdoc/> public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { var state = value as ShapeState; if (state != null) { return state.ToString(); } throw new NotSupportedException(); } } }
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Globalization; #if NETSTANDARD1_3 using System.ComponentModel; #else using Portable.Xaml.ComponentModel; #endif using Core2D.Shape; namespace Serializer.Xaml.Converters { /// <summary> /// Defines <see cref="ShapeState"/> type converter. /// </summary> internal class ShapeStateTypeConverter : TypeConverter { /// <inheritdoc/> public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { return sourceType == typeof(string); } /// <inheritdoc/> public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { return destinationType == typeof(string); } /// <inheritdoc/> public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { return ShapeState.Parse((string)value); } /// <inheritdoc/> public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { var state = value as ShapeState; if (state != null) { return state.ToString(); } throw new NotSupportedException(); } } }
mit
C#
82dc912cdaa038c0172279986e2c77caca63cadf
Update GetAllEquipmentItemsQuery.cs
NinjaVault/NinjaHive,NinjaVault/NinjaHive
NinjaHive.Contract/Queries/GetAllEquipmentItemsQuery.cs
NinjaHive.Contract/Queries/GetAllEquipmentItemsQuery.cs
using NinjaHive.Contract.DTOs; using NinjaHive.Core; namespace NinjaHive.Contract.Queries { public class GetAllEquipmentItemsQuery : IQuery<EquipmentItem[]> { } }
using NinjaHive.Contract.DTOs; using NinjaHive.Core; namespace NinjaHive.Contract.Queries { public class GetAllEquipmentItemsQuery : IQuery<EquipmentItem[]> { } }
apache-2.0
C#
1fc0e2a766367b46798d01cec3e6da9f26173c99
Add attribute usage limitation on RouteInheritAttribute.
lijunle/Nancy.AttributeRouting,lijunle/Nancy.AttributeRouting
Nancy.AttributeRouting/RouteInheritAttribute.cs
Nancy.AttributeRouting/RouteInheritAttribute.cs
namespace Nancy.AttributeRouting { using System; using System.Reflection; /// <summary> /// <see cref="RouteInheritAttribute"/> indicates a type inherit another type's routing /// information, including routing prefix, view prefix and before hooks. /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface)] public class RouteInheritAttribute : Attribute { private readonly Type type; /// <summary> /// Initializes a new instance of the <see cref="RouteInheritAttribute"/> class. /// </summary> /// <param name="type">The type to inherit its routing information.</param> public RouteInheritAttribute(Type type) { this.type = type; } internal static Type GetAncestorType(Type type) { var attr = type.GetCustomAttribute<RouteInheritAttribute>(inherit: false); return attr == null ? null : attr.type; } } }
namespace Nancy.AttributeRouting { using System; using System.Reflection; /// <summary> /// <see cref="RouteInheritAttribute"/> indicates a type inherit another type's routing /// information, including routing prefix, view prefix and before hooks. /// </summary> public class RouteInheritAttribute : Attribute { private readonly Type type; /// <summary> /// Initializes a new instance of the <see cref="RouteInheritAttribute"/> class. /// </summary> /// <param name="type">The type to inherit its routing information.</param> public RouteInheritAttribute(Type type) { this.type = type; } internal static Type GetAncestorType(Type type) { var attr = type.GetCustomAttribute<RouteInheritAttribute>(inherit: false); return attr == null ? null : attr.type; } } }
mit
C#
0bfa1e8009fd1897d307bb7aab66b277355b7d1a
update version
prodot/ReCommended-Extension
Sources/ReCommendedExtension/Properties/AssemblyInfo.cs
Sources/ReCommendedExtension/Properties/AssemblyInfo.cs
using System.Reflection; using ReCommendedExtension; // 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(ZoneMarker.ExtensionName)] [assembly: AssemblyDescription(ZoneMarker.ExtensionDescription)] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("prodot GmbH")] [assembly: AssemblyProduct(ZoneMarker.ExtensionId)] [assembly: AssemblyCopyright("© 2012-2020 prodot GmbH")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("5.0.0.0")] [assembly: AssemblyFileVersion("5.0.0")]
using System.Reflection; using ReCommendedExtension; // 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(ZoneMarker.ExtensionName)] [assembly: AssemblyDescription(ZoneMarker.ExtensionDescription)] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("prodot GmbH")] [assembly: AssemblyProduct(ZoneMarker.ExtensionId)] [assembly: AssemblyCopyright("© 2012-2020 prodot GmbH")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("4.2.1.0")] [assembly: AssemblyFileVersion("4.2.1")]
apache-2.0
C#