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
f5138a9ba1b07f3df2d491ecd1ab1dc2bab1fb73
Update CronExtension.cs
WeihanLi/WeihanLi.Common,WeihanLi/WeihanLi.Common,WeihanLi/WeihanLi.Common
src/WeihanLi.Common/Extensions/CronExtension.cs
src/WeihanLi.Common/Extensions/CronExtension.cs
using System; using System.Collections.Generic; using WeihanLi.Common.Helpers.Cron; // ReSharper disable once CheckNamespace namespace WeihanLi.Extensions { public static class CronExtension { /// <summary> /// GetNextOccurrence /// </summary> /// <param name="expression">cron expression</param> /// <returns>next occurrence time</returns> public static DateTimeOffset? GetNextOccurrence(this CronExpression expression) { return expression?.GetNextOccurrence(DateTimeOffset.UtcNow, TimeZoneInfo.Utc); } /// <summary> /// GetNextOccurrence /// </summary> /// <param name="expression">cron expression</param> /// <param name="timeZoneInfo">timeZoneInfo</param> /// <returns>next occurrence time</returns> public static DateTimeOffset? GetNextOccurrence(this CronExpression expression, TimeZoneInfo timeZoneInfo) { return expression.GetNextOccurrence(DateTimeOffset.UtcNow, timeZoneInfo); } /// <summary> /// GetNextOccurrence /// </summary> /// <param name="expression">cron expression</param> /// <param name="period">next period</param> /// <returns>next occurrence times</returns> public static IEnumerable<DateTimeOffset> GetNextOccurrences(this CronExpression expression, TimeSpan period) { return expression?.GetOccurrences(DateTime.UtcNow, fromUtc.Add(period), TimeZoneInfo.Utc); } /// <summary> /// GetNextOccurrence /// </summary> /// <param name="expression">cron expression</param> /// <param name="period">next period</param> /// <param name="timeZoneInfo">timeZoneInfo</param> /// <returns>next occurrence times</returns> public static IEnumerable<DateTimeOffset> GetNextOccurrences(this CronExpression expression, TimeSpan period, TimeZoneInfo timeZoneInfo) { return expression.GetOccurrences(DateTime.UtcNow, fromUtc.Add(period), timeZoneInfo); } } }
using System; using System.Collections.Generic; using WeihanLi.Common.Helpers.Cron; // ReSharper disable once CheckNamespace namespace WeihanLi.Extensions { public static class CronExtension { /// <summary> /// GetNextOccurrence /// </summary> /// <param name="expression">cron expression</param> /// <returns>next occurrence time</returns> public static DateTimeOffset? GetNextOccurrence(this CronExpression expression) { return expression?.GetNextOccurrence(DateTimeOffset.UtcNow, TimeZoneInfo.Utc); } /// <summary> /// GetNextOccurrence /// </summary> /// <param name="expression">cron expression</param> /// <param name="timeZoneInfo">timeZoneInfo</param> /// <returns>next occurrence time</returns> public static DateTimeOffset? GetNextOccurrence(this CronExpression expression, TimeZoneInfo timeZoneInfo) { return expression.GetNextOccurrence(DateTimeOffset.UtcNow, timeZoneInfo); } /// <summary> /// GetNextOccurrence /// </summary> /// <param name="expression">cron expression</param> /// <param name="period">next period</param> /// <returns>next occurrence times</returns> public static IEnumerable<DateTimeOffset> GetNextOccurrences(this CronExpression expression, TimeSpan period) { var fromUtc = DateTime.UtcNow; return expression?.GetOccurrences(fromUtc, fromUtc.Add(period), TimeZoneInfo.Utc); } /// <summary> /// GetNextOccurrence /// </summary> /// <param name="expression">cron expression</param> /// <param name="period">next period</param> /// <param name="timeZoneInfo">timeZoneInfo</param> /// <returns>next occurrence times</returns> public static IEnumerable<DateTimeOffset> GetNextOccurrences(this CronExpression expression, TimeSpan period, TimeZoneInfo timeZoneInfo) { var fromUtc = DateTime.UtcNow; return expression.GetOccurrences(fromUtc, fromUtc.Add(period), timeZoneInfo); } } }
mit
C#
fd502f1b14823c795ba84a12d5a5a75b926b3a74
Remove the legacy support and switch to MEF-provided JoinableTaskContext
MobileEssentials/Merq
src/Vsix/Merq.Vsix/Components/AsyncManagerProvider.cs
src/Vsix/Merq.Vsix/Components/AsyncManagerProvider.cs
using System; using System.ComponentModel; using System.ComponentModel.Composition; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Merq.Properties; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Threading; namespace Merq { /// <summary> /// We switch the implementation of the async manager depending /// on the Visual Studio version. /// </summary> [PartCreationPolicy (CreationPolicy.Shared)] internal class AsyncManagerProvider { [ImportingConstructor] public AsyncManagerProvider ([Import] JoinableTaskContext context) { AsyncManager = new AsyncManager(context); } /// <summary> /// Exports the <see cref="IAsyncManager"/>. /// </summary> [Export] public IAsyncManager AsyncManager { get; } } }
using System; using System.ComponentModel; using System.ComponentModel.Composition; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Merq.Properties; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Threading; namespace Merq { /// <summary> /// We switch the implementation of the async manager depending /// on the Visual Studio version. /// </summary> [PartCreationPolicy (CreationPolicy.Shared)] internal class AsyncManagerProvider { IServiceProvider serviceProvider; Lazy<IAsyncManager> manager; /// <summary> /// Initializes the provider with the given VS services. /// </summary> /// <param name="serviceProvider"></param> [ImportingConstructor] public AsyncManagerProvider ([Import (typeof (SVsServiceProvider))] IServiceProvider serviceProvider) { this.serviceProvider = serviceProvider; manager = new Lazy<IAsyncManager> (() => CreateAsyncManager ()); } /// <summary> /// Exports the <see cref="IAsyncManager"/>. /// </summary> [Export] public IAsyncManager AsyncManager => manager.Value; IAsyncManager CreateAsyncManager () { // NOTE: under VS2012, an installer should install the Microsoft.VisualStudio.Threading.Downlevel.vsix // from the Microsoft.VisualStudio.Threading.DownlevelInstaller nuget package via an MSI. // VS2012 case var context = (JoinableTaskContext)serviceProvider.GetService(typeof(SVsJoinableTaskContext)); if (context != null) return new AsyncManager (context); // VS2013+ case var schedulerService = (IVsTaskSchedulerService2)serviceProvider.GetService(typeof(SVsTaskSchedulerService)); if (schedulerService != null) return new AsyncManager ((JoinableTaskContext)schedulerService.GetAsyncTaskContext ()); throw new NotSupportedException(Strings.AsyncManagerProvider.NoTaskContext); } } } namespace Microsoft.VisualStudio.Threading { /// <summary> /// The legacy VS2012 type serving as the service guid for acquiring an instance of JoinableTaskContext. /// </summary> [Guid("8767A7D4-ECFC-4627-8FC0-A1685E3B0493")] public interface SVsJoinableTaskContext { } } namespace Microsoft.VisualStudio.Shell.Interop { /// <summary> /// Internal. /// </summary> [ComImport, Guid("8176DC77-36E2-4987-955B-9F63C6F3F229"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), TypeIdentifier] public interface IVsTaskSchedulerService2 { /// <summary> /// Internal. /// </summary> [return: MarshalAs(UnmanagedType.IUnknown)] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] object GetAsyncTaskContext(); } }
mit
C#
1bc5f3618417a15fe1fd0f44e705e4911d5adacd
Adjust test usage
NeoAdonis/osu,peppy/osu,peppy/osu,ppy/osu,NeoAdonis/osu,ppy/osu,smoogipoo/osu,UselessToucan/osu,smoogipoo/osu,ppy/osu,NeoAdonis/osu,smoogipooo/osu,peppy/osu,peppy/osu-new,UselessToucan/osu,UselessToucan/osu,smoogipoo/osu
osu.Game.Rulesets.Catch.Tests/CatchSkinColourDecodingTest.cs
osu.Game.Rulesets.Catch.Tests/CatchSkinColourDecodingTest.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 NUnit.Framework; using osu.Framework.IO.Stores; using osu.Game.Rulesets.Catch.Skinning; using osu.Game.Skinning; using osuTK.Graphics; namespace osu.Game.Rulesets.Catch.Tests { [TestFixture] public class CatchSkinColourDecodingTest { [Test] public void TestCatchSkinColourDecoding() { var store = new NamespacedResourceStore<byte[]>(new DllResourceStore(GetType().Assembly), "Resources/special-skin"); var rawSkin = new TestLegacySkin(new SkinInfo { Name = "special-skin" }, store); var skinSource = new SkinProvidingContainer(rawSkin); var skin = new CatchLegacySkinTransformer(skinSource); Assert.AreEqual(new Color4(232, 185, 35, 255), skin.GetConfig<CatchSkinColour, Color4>(CatchSkinColour.HyperDash)?.Value); Assert.AreEqual(new Color4(232, 74, 35, 255), skin.GetConfig<CatchSkinColour, Color4>(CatchSkinColour.HyperDashAfterImage)?.Value); Assert.AreEqual(new Color4(0, 255, 255, 255), skin.GetConfig<CatchSkinColour, Color4>(CatchSkinColour.HyperDashFruit)?.Value); } private class TestLegacySkin : LegacySkin { public TestLegacySkin(SkinInfo skin, IResourceStore<byte[]> storage) // Bypass LegacySkinResourceStore to avoid returning null for retrieving files due to bad skin info (SkinInfo.Files = null). : base(skin, storage, null, "skin.ini") { } } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Framework.IO.Stores; using osu.Game.Rulesets.Catch.Skinning; using osu.Game.Skinning; using osuTK.Graphics; namespace osu.Game.Rulesets.Catch.Tests { [TestFixture] public class CatchSkinColourDecodingTest { [Test] public void TestCatchSkinColourDecoding() { var store = new NamespacedResourceStore<byte[]>(new DllResourceStore(GetType().Assembly), "Resources/special-skin"); var rawSkin = new TestLegacySkin(new SkinInfo { Name = "special-skin" }, store); var skin = new CatchLegacySkinTransformer(rawSkin); Assert.AreEqual(new Color4(232, 185, 35, 255), skin.GetConfig<CatchSkinColour, Color4>(CatchSkinColour.HyperDash)?.Value); Assert.AreEqual(new Color4(232, 74, 35, 255), skin.GetConfig<CatchSkinColour, Color4>(CatchSkinColour.HyperDashAfterImage)?.Value); Assert.AreEqual(new Color4(0, 255, 255, 255), skin.GetConfig<CatchSkinColour, Color4>(CatchSkinColour.HyperDashFruit)?.Value); } private class TestLegacySkin : LegacySkin { public TestLegacySkin(SkinInfo skin, IResourceStore<byte[]> storage) // Bypass LegacySkinResourceStore to avoid returning null for retrieving files due to bad skin info (SkinInfo.Files = null). : base(skin, storage, null, "skin.ini") { } } } }
mit
C#
b1b01c1fb6afcc55c5326c2e99c3f396a88866a5
Update SebastianFeldmann.cs
planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell
src/Firehose.Web/Authors/SebastianFeldmann.cs
src/Firehose.Web/Authors/SebastianFeldmann.cs
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using System.Web; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class SebastianFeldmann : IAmACommunityMember { public string FirstName => "Sebastian"; public string LastName => "Feldmann"; public string ShortBioOrTagLine => "sysadmin"; public string StateOrRegion => "Bremen, Germany"; public string EmailAddress => "sebastian@feldmann.io"; public string TwitterHandle => "sebfieldman"; public string GravatarHash => ""; public string GitHubHandle => ""; public GeoPosition Position => new GeoPosition(53.073635, 8.806422); public Uri WebSite => new Uri("http://blog.feldmann.io/"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("http://blog.feldmann.io/feed/"); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using System.Web; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class SebastianFeldmann : IAmACommunityMember { public string FirstName => "Sebastian"; public string LastName => "Feldmann"; public string ShortBioOrTagLine => "sysadmin"; public string StateOrRegion => "Bremen, Germany"; public string EmailAddress => "sebastian@feldmann.io"; public string TwitterHandle => "sebfieldman"; public Uri WebSite => new Uri("http://blog.feldmann.io/"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("http://blog.feldmann.io/feed/"); } } } }
mit
C#
80c5e1468fab6658bdc4fe3e287b93ec27aaeaac
Remove www
planetxamarin/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin
src/Firehose.Web/Authors/StefanDeVogelaere.cs
src/Firehose.Web/Authors/StefanDeVogelaere.cs
using System; using System.Collections.Generic; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class StefanDeVogelaere : IAmACommunityMember { public string FirstName => "Stefan"; public string GitHubHandle => "stefandevo"; public string LastName => "de Vogelaere"; public string ShortBioOrTagLine => ""; public string StateOrRegion => "Wommelgem, Belgium"; public string EmailAddress => "stefan.de.vogelaere@gmail.com"; public string TwitterHandle => "stefandevo"; public Uri WebSite => new Uri("https://stefandevo.com"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://stefandevo.com/feed/"); } } public string GravatarHash => "c91dbad10c922f0fef71e9e2df15b763"; public GeoPosition Position => new GeoPosition(51.2021680, 4.5219650); } }
using System; using System.Collections.Generic; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class StefanDeVogelaere : IAmACommunityMember { public string FirstName => "Stefan"; public string GitHubHandle => "stefandevo"; public string LastName => "de Vogelaere"; public string ShortBioOrTagLine => ""; public string StateOrRegion => "Wommelgem, Belgium"; public string EmailAddress => "stefan.de.vogelaere@gmail.com"; public string TwitterHandle => "stefandevo"; public Uri WebSite => new Uri("https://www.stefandevo.com"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://www.stefandevo.com/feed/"); } } public string GravatarHash => "c91dbad10c922f0fef71e9e2df15b763"; public GeoPosition Position => new GeoPosition(51.2021680, 4.5219650); } }
mit
C#
a323ab0d4b677d93b1171dceb5b49f76bab1d9f1
Rephrase the Skipped sample to use runtime skips rather than declarative skips, demonstrating how runtime skips are superior: we have case-by-case skippability, implicit skips by conditionally avoiding executing a case, and the ability to avoid instantiating a test class if it is entirely marked as skipped.
fixie/fixie
src/Fixie.Samples/Skipped/CustomConvention.cs
src/Fixie.Samples/Skipped/CustomConvention.cs
namespace Fixie.Samples.Skipped { using System; public class CustomConvention : Convention { public CustomConvention() { Classes .InTheSameNamespaceAs(typeof(CustomConvention)) .NameEndsWith("Tests"); Methods .OrderBy(x => x.Name, StringComparer.Ordinal); ClassExecution .Lifecycle<SkipLifecycle>(); } class SkipLifecycle : Lifecycle { public void Execute(TestClass testClass, Action<CaseAction> runCases) { var skipClass = testClass.Type.Has<SkipAttribute>(); var instance = skipClass ? null : testClass.Construct(); runCases(@case => { var skipMethod = @case.Method.Has<SkipAttribute>(); if (skipClass) @case.Skip("Whole class skipped"); else if (!skipMethod) @case.Execute(instance); }); instance.Dispose(); } } } }
namespace Fixie.Samples.Skipped { using System; using System.Reflection; public class CustomConvention : Convention { public CustomConvention() { Classes .InTheSameNamespaceAs(typeof(CustomConvention)) .NameEndsWith("Tests"); Methods .OrderBy(x => x.Name, StringComparer.Ordinal); CaseExecution .Skip(SkipDueToClassLevelSkipAttribute, @case => "Whole class skipped") .Skip(SkipDueToMethodLevelSkipAttribute); ClassExecution .Lifecycle<CreateInstancePerClass>(); } static bool SkipDueToClassLevelSkipAttribute(MethodInfo testMethod) => testMethod.DeclaringType.Has<SkipAttribute>(); static bool SkipDueToMethodLevelSkipAttribute(MethodInfo testMethod) => testMethod.Has<SkipAttribute>(); } }
mit
C#
a192d0f7257b2a89d3ba3fb387b75572b5fdebc8
Simplify AssertException value formatting now that those cases are better handled by MatchException.
fixie/fixie
src/Fixie.Tests/Assertions/AssertException.cs
src/Fixie.Tests/Assertions/AssertException.cs
namespace Fixie.Tests.Assertions { using System; using System.Collections.Generic; using System.Text; using static System.Environment; public class AssertException : Exception { public static string FilterStackTraceAssemblyPrefix = typeof(AssertException).Namespace + "."; public AssertException(string message) : base(message) { } public AssertException(object? expected, object? actual) : base(ExpectationMessage(expected, actual)) { } static string ExpectationMessage(object? expected, object? actual) { var message = new StringBuilder(); message.AppendLine($"Expected: {expected?.ToString() ?? "null"}"); message.Append($"Actual: {actual?.ToString() ?? "null"}"); return message.ToString(); } public override string? StackTrace => FilterStackTrace(base.StackTrace); static string? FilterStackTrace(string? stackTrace) { if (stackTrace == null) return null; var results = new List<string>(); foreach (var line in Lines(stackTrace)) { var trimmedLine = line.TrimStart(); if (!trimmedLine.StartsWith("at " + FilterStackTraceAssemblyPrefix)) results.Add(line); } return string.Join(NewLine, results.ToArray()); } static string[] Lines(string input) { return input.Split(new[] {NewLine}, StringSplitOptions.None); } } }
namespace Fixie.Tests.Assertions { using System; using System.Collections.Generic; using System.Text; using static System.Environment; public class AssertException : Exception { public static string FilterStackTraceAssemblyPrefix = typeof(AssertException).Namespace + "."; public AssertException(string message) : base(message) { } public AssertException(object? expected, object? actual) : base(ExpectationMessage(expected, actual)) { } static string ExpectationMessage(object? expected, object? actual) { var message = new StringBuilder(); var actualStr = actual == null ? null : ConvertToString(actual); var expectedStr = expected == null ? null : ConvertToString(expected); message.AppendLine($"Expected: {FormatMultiLine(expectedStr ?? "(null)")}"); message.Append($"Actual: {FormatMultiLine(actualStr ?? "(null)")}"); return message.ToString(); } static string? ConvertToString(object value) { if (value is Array valueArray) { var valueStrings = new List<string>(); foreach (var valueObject in valueArray) valueStrings.Add(valueObject?.ToString() ?? "(null)"); return value.GetType().FullName + $" {{{NewLine}{string.Join("," + NewLine, valueStrings.ToArray())}{NewLine}}}"; } return value.ToString(); } static string FormatMultiLine(string value) => value.Replace(NewLine, NewLine + " "); public override string? StackTrace => FilterStackTrace(base.StackTrace); static string? FilterStackTrace(string? stackTrace) { if (stackTrace == null) return null; var results = new List<string>(); foreach (var line in Lines(stackTrace)) { var trimmedLine = line.TrimStart(); if (!trimmedLine.StartsWith("at " + FilterStackTraceAssemblyPrefix)) results.Add(line); } return string.Join(NewLine, results.ToArray()); } static string[] Lines(string input) { return input.Split(new[] {NewLine}, StringSplitOptions.None); } } }
mit
C#
023a0b6b055a24cb758102ac17a2cdff04d332d4
Order the files and dirs
devedse/DeveImageOptimizer
DeveImageOptimizer/Helpers/FileHelperMethods.cs
DeveImageOptimizer/Helpers/FileHelperMethods.cs
using DeveImageOptimizer.State.StoringProcessedDirectories; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace DeveImageOptimizer.Helpers { public static class FileHelperMethods { public static void SafeDeleteTempFile(string path) { try { if (File.Exists(path)) { File.Delete(path); } } catch (Exception ex) { Console.WriteLine($"Warning: Couldn't remove tempfile at path: '{path}'. Exception:{Environment.NewLine}{ex}"); } } public static IEnumerable<FileAndCountOfFilesInDirectory> RecurseFiles(string directory, Func<string, bool> filter = null) { if (filter == null) { filter = t => true; } var files = Directory.GetFiles(directory).Where(filter).OrderBy(t => t).ToList(); foreach (var file in files) { yield return new FileAndCountOfFilesInDirectory() { FilePath = file, DirectoryPath = directory, CountOfFilesInDirectory = files.Count }; } var directories = Directory.GetDirectories(directory).OrderBy(t => t).ToList(); foreach (var subDirectory in directories) { var recursedFIles = RecurseFiles(subDirectory, filter); foreach (var subFile in recursedFIles) { yield return subFile; } } } } }
using DeveImageOptimizer.State.StoringProcessedDirectories; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace DeveImageOptimizer.Helpers { public static class FileHelperMethods { public static void SafeDeleteTempFile(string path) { try { if (File.Exists(path)) { File.Delete(path); } } catch (Exception ex) { Console.WriteLine($"Warning: Couldn't remove tempfile at path: '{path}'. Exception:{Environment.NewLine}{ex}"); } } public static IEnumerable<FileAndCountOfFilesInDirectory> RecurseFiles(string directory, Func<string, bool> filter = null) { if (filter == null) { filter = t => true; } var files = Directory.GetFiles(directory).Where(filter).ToList(); foreach (var file in files) { yield return new FileAndCountOfFilesInDirectory() { FilePath = file, DirectoryPath = directory, CountOfFilesInDirectory = files.Count }; } var directories = Directory.GetDirectories(directory); foreach (var subDirectory in directories) { var recursedFIles = RecurseFiles(subDirectory, filter); foreach (var subFile in recursedFIles) { yield return subFile; } } } } }
mit
C#
2b522a74e565ed2329858ef2e8f60a924d5513de
Fix failing test for abstract get-set indexer
JakeGinnivan/ApiApprover
src/PublicApiGenerator/PropertyNameBuilder.cs
src/PublicApiGenerator/PropertyNameBuilder.cs
using System; using System.CodeDom; using Mono.Cecil; namespace PublicApiGenerator { public static class PropertyNameBuilder { public static string AugmentPropertyNameWithPropertyModifierMarkerTemplate(PropertyDefinition propertyDefinition, MemberAttributes getAccessorAttributes, MemberAttributes setAccessorAttributes) { string name = propertyDefinition.Name; if (getAccessorAttributes != setAccessorAttributes || propertyDefinition.DeclaringType.IsInterface || propertyDefinition.HasParameters) { return name; } var isNew = propertyDefinition.IsNew(typeDef => typeDef?.Properties, e => e.Name.Equals(propertyDefinition.Name, StringComparison.Ordinal)); return ModifierMarkerNameBuilder.Build(propertyDefinition.GetMethod, getAccessorAttributes, isNew, name, CodeNormalizer.PropertyModifierMarkerTemplate); } } }
using System; using System.CodeDom; using Mono.Cecil; namespace PublicApiGenerator { public static class PropertyNameBuilder { public static string AugmentPropertyNameWithPropertyModifierMarkerTemplate(PropertyDefinition propertyDefinition, MemberAttributes getAccessorAttributes, MemberAttributes setAccessorAttributes) { string name = propertyDefinition.Name; if (getAccessorAttributes != setAccessorAttributes || propertyDefinition.DeclaringType.IsInterface) { return name; } var isNew = propertyDefinition.IsNew(typeDef => typeDef?.Properties, e => e.Name.Equals(propertyDefinition.Name, StringComparison.Ordinal)); return ModifierMarkerNameBuilder.Build(propertyDefinition.GetMethod, getAccessorAttributes, isNew, name, CodeNormalizer.PropertyModifierMarkerTemplate); } } }
mit
C#
64061631467878f31f5b31015674b079f55c3837
Update assembly info for Image change
AzureAutomationTeam/azure-powershell,devigned/azure-powershell,devigned/azure-powershell,ClogenyTechnologies/azure-powershell,ClogenyTechnologies/azure-powershell,ClogenyTechnologies/azure-powershell,devigned/azure-powershell,devigned/azure-powershell,AzureAutomationTeam/azure-powershell,ClogenyTechnologies/azure-powershell,ClogenyTechnologies/azure-powershell,devigned/azure-powershell,AzureAutomationTeam/azure-powershell,AzureAutomationTeam/azure-powershell,AzureAutomationTeam/azure-powershell,devigned/azure-powershell,AzureAutomationTeam/azure-powershell
src/ResourceManager/Compute/Commands.Compute/Properties/AssemblyInfo.cs
src/ResourceManager/Compute/Commands.Compute/Properties/AssemblyInfo.cs
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Microsoft Azure Powershell - Compute Resource Provider")] [assembly: AssemblyCompany(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyCompany)] [assembly: AssemblyProduct(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyProduct)] [assembly: AssemblyCopyright(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyCopyright)] [assembly: ComVisible(false)] [assembly: CLSCompliant(false)] [assembly: Guid("91792853-487B-4DC2-BE6C-DD09A0A1BC10")] [assembly: AssemblyVersion("4.3.1")] [assembly: AssemblyFileVersion("4.3.1")] #if SIGN [assembly: InternalsVisibleTo("Microsoft.Azure.Commands.Compute.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] #else [assembly: InternalsVisibleTo("Microsoft.Azure.Commands.Compute.Test")] #endif
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Microsoft Azure Powershell - Compute Resource Provider")] [assembly: AssemblyCompany(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyCompany)] [assembly: AssemblyProduct(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyProduct)] [assembly: AssemblyCopyright(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyCopyright)] [assembly: ComVisible(false)] [assembly: CLSCompliant(false)] [assembly: Guid("91792853-487B-4DC2-BE6C-DD09A0A1BC10")] [assembly: AssemblyVersion("4.3.0")] [assembly: AssemblyFileVersion("4.3.0")] #if SIGN [assembly: InternalsVisibleTo("Microsoft.Azure.Commands.Compute.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] #else [assembly: InternalsVisibleTo("Microsoft.Azure.Commands.Compute.Test")] #endif
apache-2.0
C#
064faeb08543ff79e3caccad41a7953ebd71dff5
Update version in .dll
magico13/MagiCore
MagiCore/Properties/AssemblyInfo.cs
MagiCore/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("MagiCore")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MagiCore")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("581f4a71-3afa-45f7-aa77-9fafe8640983")] // 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.1.0.0")] [assembly: AssemblyFileVersion("1.1.0.0")] [assembly: AssemblyInformationalVersion("1.0.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("MagiCore")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MagiCore")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("581f4a71-3afa-45f7-aa77-9fafe8640983")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0.0")]
mit
C#
227cc5846e8068e9d1d85f94965b8e37d5d74c4c
Fix #44 freezing NativeListener on mono 4.2.1
xplicit/HyperFastCgi,xplicit/HyperFastCgi,xplicit/HyperFastCgi
src/HyperFastCgi/Listeners/NativeListener.cs
src/HyperFastCgi/Listeners/NativeListener.cs
using System; using System.Runtime.InteropServices; using HyperFastCgi.Interfaces; using HyperFastCgi.Configuration; using HyperFastCgi.Transports; using HyperFastCgi.Helpers.Logging; using System.Threading; namespace HyperFastCgi.Listeners { [Config(typeof(ListenerConfig))] public class NativeListener : IWebListener { IApplicationServer server; ListenerConfig config; #region IWebListener implementation public void Configure(object config, IApplicationServer server, Type listenerTransport, object listenerTransportConfig, Type appHostTransport, object appHostTransportConfig ) { this.server = server; this.config = config as ListenerConfig; } public int Listen () { Logger.Write (LogLevel.Debug,"Listening on port: {0}", config.Port); Logger.Write (LogLevel.Debug,"Listening on address: {0}", config.Address); int retval = NativeListener.Listen ((ushort)config.Family, config.Address, (ushort)config.Port); //retval == 0 when no error occured if (retval == 0) { new Thread (_ => NativeListener.ProcessLoop ()).Start (); } return retval; } public void Shutdown () { NativeListener.InternalShutdown (); } public IApplicationServer Server { get { return server;} } public IListenerTransport Transport { get { return null; } } public Type AppHostTransportType { get { return typeof(NativeTransport); } } #endregion [DllImport("libhfc-native", EntryPoint="Listen")] private extern static int Listen(ushort family, string addr, ushort port); [DllImport("libhfc-native", EntryPoint="Shutdown")] private extern static void InternalShutdown(); [DllImport("libhfc-native", EntryPoint="ProcessLoop")] private extern static void ProcessLoop(); } }
using System; using System.Runtime.InteropServices; using HyperFastCgi.Interfaces; using HyperFastCgi.Configuration; using HyperFastCgi.Transports; using HyperFastCgi.Helpers.Logging; using System.Threading; namespace HyperFastCgi.Listeners { [Config(typeof(ListenerConfig))] public class NativeListener : IWebListener { IApplicationServer server; ListenerConfig config; #region IWebListener implementation public void Configure(object config, IApplicationServer server, Type listenerTransport, object listenerTransportConfig, Type appHostTransport, object appHostTransportConfig ) { this.server = server; this.config = config as ListenerConfig; } public int Listen () { Logger.Write (LogLevel.Debug,"Listening on port: {0}", config.Port); Logger.Write (LogLevel.Debug,"Listening on address: {0}", config.Address); int retval = NativeListener.Listen ((ushort)config.Family, config.Address, (ushort)config.Port); //retval == 0 when no error occured if (retval == 0) { ThreadPool.QueueUserWorkItem (_ => NativeListener.ProcessLoop ()); } return retval; } public void Shutdown () { NativeListener.InternalShutdown (); } public IApplicationServer Server { get { return server;} } public IListenerTransport Transport { get { return null; } } public Type AppHostTransportType { get { return typeof(NativeTransport); } } #endregion [DllImport("libhfc-native", EntryPoint="Listen")] private extern static int Listen(ushort family, string addr, ushort port); [DllImport("libhfc-native", EntryPoint="Shutdown")] private extern static void InternalShutdown(); [DllImport("libhfc-native", EntryPoint="ProcessLoop")] private extern static void ProcessLoop(); } }
mit
C#
3f743e128e79f4f8476ea36fcba602380b1cc1dc
Comment update to verify webhook
GusJassal/agri-nmp,GusJassal/agri-nmp,GusJassal/agri-nmp,GusJassal/agri-nmp
PDF/src/PDF.Server/Controllers/PDFController.cs
PDF/src/PDF.Server/Controllers/PDFController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.EntityFrameworkCore; using PDF.Models; using Microsoft.AspNetCore.Http; using Newtonsoft.Json; using Microsoft.Extensions.Logging; using Microsoft.AspNetCore.NodeServices; namespace PDF.Controllers { public class PDFRequest { public string html { get; set; } } public class JSONResponse { public string type; public byte[] data; } [Route("api/[controller]")] public class PDFController : Controller { private readonly IConfiguration Configuration; private readonly DbAppContext _context; private readonly IHttpContextAccessor _httpContextAccessor; private string userId; private string guid; private string directory; protected ILogger _logger; public PDFController(IHttpContextAccessor httpContextAccessor, IConfigurationRoot configuration, ILoggerFactory loggerFactory) { Configuration = configuration; _httpContextAccessor = httpContextAccessor; userId = getFromHeaders("SM_UNIVERSALID"); guid = getFromHeaders("SMGOV_USERGUID"); directory = getFromHeaders("SM_AUTHDIRNAME"); _logger = loggerFactory.CreateLogger(typeof(PDFController)); } private string getFromHeaders(string key) { string result = null; if (Request.Headers.ContainsKey(key)) { result = Request.Headers[key]; } return result; } [HttpPost] [Route("BuildPDF")] public async Task<IActionResult> BuildPDF([FromServices] INodeServices nodeServices, [FromBody] PDFRequest rawdata ) { JSONResponse result = null; var options = new { format="letter", orientation= "landscape" }; // execute the Node.js component to generate PDF result = await nodeServices.InvokeAsync<JSONResponse>("./pdf.js", rawdata.html, options); return new FileContentResult(result.data, "application/pdf"); } protected HttpRequest Request { get { return _httpContextAccessor.HttpContext.Request; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.EntityFrameworkCore; using PDF.Models; using Microsoft.AspNetCore.Http; using Newtonsoft.Json; using Microsoft.Extensions.Logging; using Microsoft.AspNetCore.NodeServices; namespace PDF.Controllers { public class PDFRequest { public string html { get; set; } } public class JSONResponse { public string type; public byte[] data; } [Route("api/[controller]")] public class PDFController : Controller { private readonly IConfiguration Configuration; private readonly DbAppContext _context; private readonly IHttpContextAccessor _httpContextAccessor; private string userId; private string guid; private string directory; protected ILogger _logger; public PDFController(IHttpContextAccessor httpContextAccessor, IConfigurationRoot configuration, ILoggerFactory loggerFactory) { Configuration = configuration; _httpContextAccessor = httpContextAccessor; userId = getFromHeaders("SM_UNIVERSALID"); guid = getFromHeaders("SMGOV_USERGUID"); directory = getFromHeaders("SM_AUTHDIRNAME"); _logger = loggerFactory.CreateLogger(typeof(PDFController)); } private string getFromHeaders(string key) { string result = null; if (Request.Headers.ContainsKey(key)) { result = Request.Headers[key]; } return result; } [HttpPost] [Route("BuildPDF")] public async Task<IActionResult> BuildPDF([FromServices] INodeServices nodeServices, [FromBody] PDFRequest rawdata ) { JSONResponse result = null; var options = new { format="letter", orientation= "landscape" }; // execute the Node.js component result = await nodeServices.InvokeAsync<JSONResponse>("./pdf.js", rawdata.html, options); return new FileContentResult(result.data, "application/pdf"); } protected HttpRequest Request { get { return _httpContextAccessor.HttpContext.Request; } } } }
apache-2.0
C#
e3e9fe5580d13ef921f485c554f5409c0230264e
Update System Programming Lab2 Sybmol.cs
pugachAG/univ,pugachAG/univ,pugachAG/univ
SystemProgramming/Lab2/Lab2/Automaton/Sybmol.cs
SystemProgramming/Lab2/Lab2/Automaton/Sybmol.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lab2.Automaton { public abstract class SymbolBase { } public class CharSymbol : SymbolBase { public char Value { get; set; } public CharSymbol(char value) { this.Value = value; } public override int GetHashCode() { return Value.GetHashCode(); } public override bool Equals(object obj) { CharSymbol ch = obj as CharSymbol; if(ch != null) return Value.Equals(ch.Value); return false; } public override string ToString() { return Value.ToString(); } } public class EpsilonSymbol : SymbolBase { private static EpsilonSymbol instance = new EpsilonSymbol(); public static EpsilonSymbol Instance { get { return instance; } } private EpsilonSymbol() { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lab2.Automaton { public abstract class SymbolBase { } public class CharSymbol : SymbolBase { public char Value { get; set; } public CharSymbol(char value) { this.Value = value; } public override int GetHashCode() { return Value.GetHashCode(); } public override bool Equals(object obj) { CharSymbol ch = obj as CharSymbol; if(ch != null) return Value.Equals(ch.Value); return false; } public override string ToString() { return Value.ToString(); } } public class EpsilonSymbol : SymbolBase { } }
mit
C#
f41c94f70d623c3ca6620b9e35d6699e2dc186f0
Remove usings
lovewitty/SDammann.WebApi.Versioning,Sebazzz/SDammann.WebApi.Versioning,yonglehou/SDammann.WebApi.Versioning,Sebazzz/SDammann.WebApi.Versioning,Sebazzz/SDammann.WebApi.Versioning,yonglehou/SDammann.WebApi.Versioning,lovewitty/SDammann.WebApi.Versioning,yonglehou/SDammann.WebApi.Versioning,Sebazzz/SDammann.WebApi.Versioning,lovewitty/SDammann.WebApi.Versioning
src/SDammann.WebApi.Versioning/Documentation/VersionedApiExplorer.cs
src/SDammann.WebApi.Versioning/Documentation/VersionedApiExplorer.cs
namespace SDammann.WebApi.Versioning.Documentation { using System; using System.Collections.ObjectModel; using System.Web.Http; using System.Web.Http.Description; /// <summary> /// Represents an <see cref="IApiExplorer" /> that supports API versioning /// </summary> public class VersionedApiExplorer : IApiExplorer { private const string ActionVariableName = "action"; private const string ControllerVariableName = "controller"; private readonly Lazy<Collection<ApiDescription>> _apiDescriptions; private readonly HttpConfiguration _configuration; private readonly ApiExplorer _defaultApiExplorer; /// <summary> /// Initializes a new instance of the <see cref="T:System.Object" /> class. /// </summary> public VersionedApiExplorer(HttpConfiguration configuration) { this._configuration = configuration; this._defaultApiExplorer = new ApiExplorer(this._configuration); this._apiDescriptions = new Lazy<Collection<ApiDescription>>(() => this._defaultApiExplorer.ApiDescriptions); } /// <summary> /// Gets the API descriptions. The descriptions are initialized on the first access. /// </summary> public Collection<ApiDescription> ApiDescriptions { get { return this._apiDescriptions.Value; } } } }
namespace SDammann.WebApi.Versioning.Documentation { using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.Contracts; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Reflection; using System.Text.RegularExpressions; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using System.Web.Http.Dispatcher; using System.Web.Http.ModelBinding.Binders; using System.Web.Http.Routing; using System.Web.Http.Services; /// <summary> /// Represents an <see cref="IApiExplorer"/> that supports API versioning /// </summary> public class VersionedApiExplorer : IApiExplorer { private readonly ApiExplorer _defaultApiExplorer; private readonly HttpConfiguration _configuration; private readonly Lazy<Collection<ApiDescription>> _apiDescriptions; private const string ActionVariableName = "action"; private const string ControllerVariableName = "controller"; /// <summary> /// Initializes a new instance of the <see cref="T:System.Object"/> class. /// </summary> public VersionedApiExplorer(HttpConfiguration configuration) { this._configuration = configuration; this._defaultApiExplorer = new ApiExplorer(this._configuration); this._apiDescriptions = new Lazy<Collection<ApiDescription>>(() => this._defaultApiExplorer.ApiDescriptions); } /// <summary> /// Gets the API descriptions. The descriptions are initialized on the first access. /// </summary> public Collection<ApiDescription> ApiDescriptions { get { return this._apiDescriptions.Value; } } } }
apache-2.0
C#
cb82e493ff5e3926d5f370d2096387c7b13e523a
Update MainPage.xaml.cs
shrutinambiar/xamarin-forms-tinted-image
CrossPlatformTintedImage/CrossPlatformTintedImage/CrossPlatformTintedImage/MainPage.xaml.cs
CrossPlatformTintedImage/CrossPlatformTintedImage/CrossPlatformTintedImage/MainPage.xaml.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; namespace CrossPlatformTintedImage { public partial class MainPage : ContentPage { bool shouldTint = true; public MainPage() { InitializeComponent(); } void UpdateTint() { if (redSlider == null || greenSlider == null || blueSlider == null) return; tintedImage.TintColor = shouldTint ? Color.FromRgb((int)redSlider.Value, (int)greenSlider.Value, (int)blueSlider.Value) : Color.Transparent; } void OnSliderValueChanged(object sender, ValueChangedEventArgs e) { UpdateTint(); } void OnTintSwitchToggled(object sender, ToggledEventArgs e) { shouldTint = e.Value; UpdateTint(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; namespace CrossPlatformTintedImage { public partial class MainPage : ContentPage { bool shouldTint = true; public MainPage() { InitializeComponent(); } void UpdateTint() { if (redSlider == null || greenSlider == null || blueSlider == null) return; tintedImage.TintColor = shouldTint ? Color.FromRgb((int)redSlider.Value, (int)greenSlider.Value, (int)blueSlider.Value) : Color.Transparent; } void OnSliderValueChanged(object sender, ValueChangedEventArgs e) { UpdateTint(); } void OnTintSwitchToggled(object sender, ToggledEventArgs e) { shouldTint = e.Value; UpdateTint(); } } }
mit
C#
8922c908e33f55286e9e5f2dc40304b5e941e2c1
Solve build related issue
Promact/trappist,Promact/trappist,Promact/trappist,Promact/trappist,Promact/trappist
Trappist/src/Promact.Trappist.Repository/Questions/QuestionRepository.cs
Trappist/src/Promact.Trappist.Repository/Questions/QuestionRepository.cs
using System.Collections.Generic; using Promact.Trappist.DomainModel.Models.Question; using System.Linq; using Promact.Trappist.DomainModel.DbContext; namespace Promact.Trappist.Repository.Questions { public class QuestionRepository : IQuestionRepository { private readonly TrappistDbContext _dbContext; public QuestionRepository(TrappistDbContext dbContext) { _dbContext = dbContext; } /// <summary> /// Get all questions /// </summary> /// <returns>Question list</returns> public List<SingleMultipleAnswerQuestion> GetAllQuestions() { var question = _dbContext.SingleMultipleAnswerQuestion.ToList(); return question; } /// <summary> /// Add single multiple answer question into SingleMultipleAnswerQuestion model /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <param name="singleMultipleAnswerQuestionOption"></param> public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption) { _dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion); _dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOption); _dbContext.SaveChanges(); } /// <summary> /// Add single multiple answer question into SingleMultipleAnswerQuestion model /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <param name="singleMultipleAnswerQuestionOption"></param> public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption) { _dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion); _dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOption); _dbContext.SaveChanges(); } /// <summary> /// Add single multiple answer question into SingleMultipleAnswerQuestion model /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <param name="singleMultipleAnswerQuestionOption"></param> public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption) { _dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion); _dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOption); _dbContext.SaveChanges(); } } }
using System.Collections.Generic; using Promact.Trappist.DomainModel.Models.Question; using System.Linq; using Promact.Trappist.DomainModel.DbContext; namespace Promact.Trappist.Repository.Questions { public class QuestionRepository : IQuestionRepository { private readonly TrappistDbContext _dbContext; public QuestionRepository(TrappistDbContext dbContext) { _dbContext = dbContext; } /// <summary> /// Get all questions /// </summary> /// <returns>Question list</returns> public List<SingleMultipleAnswerQuestion> GetAllQuestions() { var question = _dbContext.SingleMultipleAnswerQuestion.ToList(); return question; } /// <summary> /// Add single multiple answer question into SingleMultipleAnswerQuestion model /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <param name="singleMultipleAnswerQuestionOption"></param> public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption) { _dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion); _dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOption); _dbContext.SaveChanges(); } /// <summary> /// Add single multiple answer question into SingleMultipleAnswerQuestion model /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <param name="singleMultipleAnswerQuestionOption"></param> public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption) { _dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion); _dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOption); _dbContext.SaveChanges(); } /// <summary> /// Add single multiple answer question into SingleMultipleAnswerQuestion model /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption) { _dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion); _dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOption); _dbContext.SaveChanges(); } } }
mit
C#
51564d04c02665b7db3abad47d04fe1079a77905
Remove a test that tests Dictionary
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
test/Microsoft.AspNet.Mvc.Core.Test/MvcOptionsTest.cs
test/Microsoft.AspNet.Mvc.Core.Test/MvcOptionsTest.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 Xunit; namespace Microsoft.AspNet.Mvc { public class MvcOptionsTest { [Fact] public void MaxValidationError_ThrowsIfValueIsOutOfRange() { // Arrange var options = new MvcOptions(); // Act & Assert var ex = Assert.Throws<ArgumentOutOfRangeException>(() => options.MaxModelValidationErrors = -1); Assert.Equal("value", ex.ParamName); } } }
// 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 Xunit; namespace Microsoft.AspNet.Mvc { public class MvcOptionsTest { [Fact] public void MaxValidationError_ThrowsIfValueIsOutOfRange() { // Arrange var options = new MvcOptions(); // Act & Assert var ex = Assert.Throws<ArgumentOutOfRangeException>(() => options.MaxModelValidationErrors = -1); Assert.Equal("value", ex.ParamName); } [Fact] public void ThrowsWhenMultipleCacheProfilesWithSameNameAreAdded() { // Arrange var options = new MvcOptions(); options.CacheProfiles.Add("HelloWorld", new CacheProfile { Duration = 10 }); // Act & Assert var ex = Assert.Throws<ArgumentException>( () => options.CacheProfiles.Add("HelloWorld", new CacheProfile { Duration = 5 })); Assert.Equal("An item with the same key has already been added.", ex.Message); } } }
apache-2.0
C#
0c6833ca95636f0d6806f078ada43e61a1e0e01c
Update smoke test for microgenerator
jskeet/google-cloud-dotnet,googleapis/google-cloud-dotnet,jskeet/google-cloud-dotnet,googleapis/google-cloud-dotnet,googleapis/google-cloud-dotnet,jskeet/google-cloud-dotnet,jskeet/google-cloud-dotnet,jskeet/gcloud-dotnet,jskeet/google-cloud-dotnet
apis/Google.Cloud.Asset.V1/Google.Cloud.Asset.V1.SmokeTests/AssetServiceSmokeTest.cs
apis/Google.Cloud.Asset.V1/Google.Cloud.Asset.V1.SmokeTests/AssetServiceSmokeTest.cs
// Copyright 2019 Google LLC // // 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 // // https://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. // Note: this is not currently generated, but is intended to take // the same form as regular generated smoke tests. namespace Google.Cloud.Asset.V1.SmokeTests { using Google.Api.Gax.ResourceNames; using Google.Protobuf.WellKnownTypes; using System; public class AssetServiceSmokeTest { public static int Main(string[] args) { // Read projectId from args if (args.Length != 1) { Console.WriteLine("Usage: Project ID must be passed as first argument."); Console.WriteLine(); return 1; } string projectId = args[0]; // Create client AssetServiceClient client = AssetServiceClient.Create(); // Initialize request argument(s) var request = new BatchGetAssetsHistoryRequest { ParentAsResourceName = new ProjectName(projectId), ContentType = ContentType.Resource, ReadTimeWindow = new TimeWindow { StartTime = DateTime.UtcNow.AddDays(-1).ToTimestamp() }, }; // Call API method client.BatchGetAssetsHistory(request); // Success Console.WriteLine("Smoke test passed OK"); return 0; } } }
// Copyright 2019 Google LLC // // 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 // // https://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. // Note: this is not currently generated, but is intended to take // the same form as regular generated smoke tests. namespace Google.Cloud.Asset.V1.SmokeTests { using Google.Api.Gax; using Google.Api.Gax.Grpc; using Google.Api.Gax.ResourceNames; using Google.Protobuf.WellKnownTypes; using Grpc.Core; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Threading; using System.Threading.Tasks; public class AssetServiceSmokeTest { public static int Main(string[] args) { // Read projectId from args if (args.Length != 1) { Console.WriteLine("Usage: Project ID must be passed as first argument."); Console.WriteLine(); return 1; } string projectId = args[0]; // Create client AssetServiceClient client = AssetServiceClient.Create(); // Initialize request argument(s) var request = new BatchGetAssetsHistoryRequest { ParentAsProjectName = new ProjectName(projectId), ContentType = ContentType.Resource, ReadTimeWindow = new TimeWindow { StartTime = DateTime.UtcNow.AddDays(-1).ToTimestamp() }, }; // Call API method client.BatchGetAssetsHistory(request); // Success Console.WriteLine("Smoke test passed OK"); return 0; } } }
apache-2.0
C#
ec57ae3ec69f3996311379e3da4f405e50bbbee0
Update VCardController.cs - Added missing paren for metadata
nihaue/SampleNdefParserApiApp,nihaue/SampleNdefParserApiApp
QuickLearn.Samples/QuickLearn.Samples.NDEFApiApp/Controllers/VCardController.cs
QuickLearn.Samples/QuickLearn.Samples.NDEFApiApp/Controllers/VCardController.cs
using NdefLibrary.Ndef; using QuickLearn.Samples.NdefApiApp.Models; using Swashbuckle.Swagger.Annotations; using System; using System.IO; using System.Linq; using System.Net; using System.Web.Http; using TRex.Metadata; using VcardLibrary; namespace QuickLearn.Samples.NdefApiApp.Controllers { [RoutePrefix("vcard")] public class VCardController : ApiController { [Route, HttpGet] [Metadata("Read vCard from NDEF", "Reads the first record within the NDEF message as a vCard and returns the name and email contained")] [SwaggerResponse(HttpStatusCode.OK, "vCard data successfully read from NDEF message", typeof(VCardModel))] [SwaggerResponse(HttpStatusCode.BadRequest, "Attempt to parse data failed")] public IHttpActionResult Get([Metadata("Base64 NDEF Message", "Base64 encoded NDEF message which contains a vCard record as the first record")] string b64Content) { NdefMessage ndefMessage = null; try { ndefMessage = NdefMessage.FromByteArray(Convert.FromBase64String(b64Content)); } catch { return BadRequest("Could not parse NDEF message"); } var firstRecord = ndefMessage.FirstOrDefault(); if (firstRecord.CheckSpecializedType(true) != typeof(NdefVcardRecordBase)) return BadRequest("First record in NDEF message was not a vCard record"); using (var contentStream = new MemoryStream(firstRecord.Payload)) { using (var reader = new StreamReader(contentStream)) { vCard card = new vCard(reader); return Ok(new VCardModel() { EmailAddress = card.EmailAddresses.Any() ? card.EmailAddresses.FirstOrDefault().Address : string.Empty, FamilyName = card.FamilyName, GivenName = card.GivenName }); } } } } }
using NdefLibrary.Ndef; using QuickLearn.Samples.NdefApiApp.Models; using Swashbuckle.Swagger.Annotations; using System; using System.IO; using System.Linq; using System.Net; using System.Web.Http; using TRex.Metadata; using VcardLibrary; namespace QuickLearn.Samples.NdefApiApp.Controllers { [RoutePrefix("vcard")] public class VCardController : ApiController { [Route, HttpGet] [Metadata("Read vCard from NDEF", "Reads the first record within the NDEF message as a vCard and returns the name and email contained")] [SwaggerResponse(HttpStatusCode.OK, "vCard data successfully read from NDEF message", typeof(VCardModel))] [SwaggerResponse(HttpStatusCode.BadRequest, "Attempt to parse data failed")] public IHttpActionResult Get([Metadata("Base64 NDEF Message", "Base64 encoded NDEF message which contains a vCard record as the first record"] string b64Content) { NdefMessage ndefMessage = null; try { ndefMessage = NdefMessage.FromByteArray(Convert.FromBase64String(b64Content)); } catch { return BadRequest("Could not parse NDEF message"); } var firstRecord = ndefMessage.FirstOrDefault(); if (firstRecord.CheckSpecializedType(true) != typeof(NdefVcardRecordBase)) return BadRequest("First record in NDEF message was not a vCard record"); using (var contentStream = new MemoryStream(firstRecord.Payload)) { using (var reader = new StreamReader(contentStream)) { vCard card = new vCard(reader); return Ok(new VCardModel() { EmailAddress = card.EmailAddresses.Any() ? card.EmailAddresses.FirstOrDefault().Address : string.Empty, FamilyName = card.FamilyName, GivenName = card.GivenName }); } } } } }
mit
C#
ec6cf902a061f3db3239bf0d795d60f25c9ce4c3
Update Install9ParametersEditor.xaml.cs
Sitecore/Sitecore-Instance-Manager
src/SIM.Tool.Windows/UserControls/Install/ParametersEditor/Install9ParametersEditor.xaml.cs
src/SIM.Tool.Windows/UserControls/Install/ParametersEditor/Install9ParametersEditor.xaml.cs
using SIM.Sitecore9Installer; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace SIM.Tool.Windows.UserControls.Install.ParametersEditor { /// <summary> /// Interaction logic for Install9ParametersEditor.xaml /// </summary> public partial class Install9ParametersEditor : Window { public Install9ParametersEditor() { InitializeComponent(); } private void Window_Loaded(object sender, RoutedEventArgs e) { var tasker = this.DataContext as Tasker; List<TasksModel> model = new List<TasksModel>(); model.Add(new TasksModel("Global", args.Tasker.GlobalParams)); foreach (PowerShellTask task in args.Tasker.Tasks.Where(t=>t.ShouldRun)) { if (!tasker.UnInstall || (tasker.UnInstall && task.SupportsUninstall())) { model.Add(new TasksModel(task.Name, task.LocalParams)); } } this.InstallationParameters.DataContext = model; this.InstallationParameters.SelectedIndex = 0; } private void ScrollViewer_PreviewMouseWheel(object sender, MouseWheelEventArgs e) { ScrollViewer scrollviewer = sender as ScrollViewer; if (e.Delta > 0) scrollviewer.LineLeft(); else scrollviewer.LineRight(); e.Handled = true; } private class TasksModel { public TasksModel(string Name, List<InstallParam> Params) { this.Name = Name; this.Params = Params; } public string Name { get; } public List<InstallParam> Params { get; } } private void Btn_Close_Click(object sender, RoutedEventArgs e) { this.Close(); } } }
using SIM.Sitecore9Installer; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace SIM.Tool.Windows.UserControls.Install.ParametersEditor { /// <summary> /// Interaction logic for Install9ParametersEditor.xaml /// </summary> public partial class Install9ParametersEditor : Window { public Install9ParametersEditor() { InitializeComponent(); } private void Window_Loaded(object sender, RoutedEventArgs e) { var tasker = this.DataContext as Tasker; List<TasksModel> model = new List<TasksModel>(); model.Add(new TasksModel("Global", args.Tasker.GlobalParams)); { if (!tasker.UnInstall || (tasker.UnInstall && task.SupportsUninstall())) { model.Add(new TasksModel(task.Name, task.LocalParams)); } } this.InstallationParameters.DataContext = model; this.InstallationParameters.SelectedIndex = 0; } private void ScrollViewer_PreviewMouseWheel(object sender, MouseWheelEventArgs e) { ScrollViewer scrollviewer = sender as ScrollViewer; if (e.Delta > 0) scrollviewer.LineLeft(); else scrollviewer.LineRight(); e.Handled = true; } private class TasksModel { public TasksModel(string Name, List<InstallParam> Params) { this.Name = Name; this.Params = Params; } public string Name { get; } public List<InstallParam> Params { get; } } private void Btn_Close_Click(object sender, RoutedEventArgs e) { this.Close(); } } }
mit
C#
6200ef87d39e71a2ae06e41f3cc9ac8ef05d7621
Update twitter handle
planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell
src/Firehose.Web/Authors/FrancoisxavierCat.cs
src/Firehose.Web/Authors/FrancoisxavierCat.cs
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using System.Web; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class FrancoisxavierCat : IAmAMicrosoftMVP, IFilterMyBlogPosts { public string FirstName => "Francois-Xavier"; public string LastName => "Cat"; public string ShortBioOrTagLine => "Systems Engineer, Microsoft MVP, French PowerShell UserGroup Organizer"; public string StateOrRegion => "San Francisco Bay, CA, USA"; public string EmailAddress => string.Empty; public string TwitterHandle => "lazywinadmin"; public string GitHubHandle => "lazywinadmin"; public string GravatarHash => "d0f72a655be62f8c34d4d1e3c5ba278a"; public GeoPosition Position => new GeoPosition(37.5545405,-122.2699152); public Uri WebSite => new Uri("https://lazywinadmin.com"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("http://feeds.feedburner.com/lazywinadmin"); } } public bool Filter(SyndicationItem item) { // This filters out only the posts that have the "PowerShell" category return item.Categories.Any(c => c.Name.ToLowerInvariant().Equals("powershell")); } } }
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using System.Web; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class FrancoisxavierCat : IAmAMicrosoftMVP, IFilterMyBlogPosts { public string FirstName => "Francois-Xavier"; public string LastName => "Cat"; public string ShortBioOrTagLine => "Systems Engineer, Microsoft MVP, French PowerShell UserGroup Organizer"; public string StateOrRegion => "San Francisco Bay, CA, USA"; public string EmailAddress => string.Empty; public string TwitterHandle => "lazywinadm"; public string GitHubHandle => "lazywinadmin"; public string GravatarHash => "d0f72a655be62f8c34d4d1e3c5ba278a"; public GeoPosition Position => new GeoPosition(37.5545405,-122.2699152); public Uri WebSite => new Uri("https://lazywinadmin.com"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("http://feeds.feedburner.com/lazywinadmin"); } } public bool Filter(SyndicationItem item) { // This filters out only the posts that have the "PowerShell" category return item.Categories.Any(c => c.Name.ToLowerInvariant().Equals("powershell")); } } }
mit
C#
74c369c25ea866ff71350346d6c33d1d383e2593
Add Semaphore creation extension methods that take an ACL (#42377)
cshung/coreclr,cshung/coreclr,cshung/coreclr,cshung/coreclr,cshung/coreclr,cshung/coreclr
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.Semaphore.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.Semaphore.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. #nullable enable using Microsoft.Win32.SafeHandles; using System; using System.Runtime.InteropServices; internal static partial class Interop { internal static partial class Kernel32 { [DllImport(Libraries.Kernel32, EntryPoint = "OpenSemaphoreW", SetLastError = true, CharSet = CharSet.Unicode)] internal static extern SafeWaitHandle OpenSemaphore(uint desiredAccess, bool inheritHandle, string name); [DllImport(Libraries.Kernel32, EntryPoint = "CreateSemaphoreExW", SetLastError = true, CharSet = CharSet.Unicode)] internal static extern SafeWaitHandle CreateSemaphoreEx(IntPtr lpSecurityAttributes, int initialCount, int maximumCount, string? name, uint flags, uint desiredAccess); [DllImport(Libraries.Kernel32, SetLastError = true)] internal static extern bool ReleaseSemaphore(SafeWaitHandle handle, int releaseCount, out int previousCount); } }
// 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 Microsoft.Win32.SafeHandles; using System; using System.Runtime.InteropServices; internal static partial class Interop { internal static partial class Kernel32 { [DllImport(Interop.Libraries.Kernel32, EntryPoint = "OpenSemaphoreW", SetLastError = true, CharSet = CharSet.Unicode)] internal static extern SafeWaitHandle OpenSemaphore(uint desiredAccess, bool inheritHandle, string name); [DllImport(Libraries.Kernel32, EntryPoint = "CreateSemaphoreExW", SetLastError = true, CharSet = CharSet.Unicode)] internal static extern SafeWaitHandle CreateSemaphoreEx(IntPtr lpSecurityAttributes, int initialCount, int maximumCount, string? name, uint flags, uint desiredAccess); [DllImport(Interop.Libraries.Kernel32, SetLastError = true)] internal static extern bool ReleaseSemaphore(SafeWaitHandle handle, int releaseCount, out int previousCount); } }
mit
C#
f8373bf961c59ae5b9dd149cda168169dfa93164
Fix bug where childeren are closed when parent cannot be closed
Caliburn-Micro/Caliburn.Micro,serenabenny/Caliburn.Micro
src/Caliburn.Micro.Core/DefaultCloseStrategy.cs
src/Caliburn.Micro.Core/DefaultCloseStrategy.cs
using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace Caliburn.Micro { /// <summary> /// Used to gather the results from multiple child elements which may or may not prevent closing. /// </summary> /// <typeparam name="T">The type of child element.</typeparam> public class DefaultCloseStrategy<T> : ICloseStrategy<T> { readonly bool closeConductedItemsWhenConductorCannotClose; /// <summary> /// Creates an instance of the class. /// </summary> /// <param name="closeConductedItemsWhenConductorCannotClose">Indicates that even if all conducted items are not closable, those that are should be closed. The default is FALSE.</param> public DefaultCloseStrategy(bool closeConductedItemsWhenConductorCannotClose = false) { this.closeConductedItemsWhenConductorCannotClose = closeConductedItemsWhenConductorCannotClose; } /// <inheritdoc /> public async Task<ICloseResult<T>> ExecuteAsync(IEnumerable<T> toClose, CancellationToken cancellationToken = default) { var closeable = new List<T>(); var closeCanOccur = true; foreach(var child in toClose) { if (child is IGuardClose guard) { var canClose = await guard.CanCloseAsync(cancellationToken); if (canClose) { closeable.Add(child); } closeCanOccur = closeCanOccur && canClose; } else { closeable.Add(child); } } if (!this.closeConductedItemsWhenConductorCannotClose) { closeable.Clear(); } return new CloseResult<T>(closeCanOccur, closeable); } } }
using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace Caliburn.Micro { /// <summary> /// Used to gather the results from multiple child elements which may or may not prevent closing. /// </summary> /// <typeparam name="T">The type of child element.</typeparam> public class DefaultCloseStrategy<T> : ICloseStrategy<T> { readonly bool closeConductedItemsWhenConductorCannotClose; /// <summary> /// Creates an instance of the class. /// </summary> /// <param name="closeConductedItemsWhenConductorCannotClose">Indicates that even if all conducted items are not closable, those that are should be closed. The default is FALSE.</param> public DefaultCloseStrategy(bool closeConductedItemsWhenConductorCannotClose = false) { this.closeConductedItemsWhenConductorCannotClose = closeConductedItemsWhenConductorCannotClose; } /// <inheritdoc /> public async Task<ICloseResult<T>> ExecuteAsync(IEnumerable<T> toClose, CancellationToken cancellationToken = default) { var closeable = new List<T>(); var closeCanOccur = true; foreach(var child in toClose) { if (child is IGuardClose guard) { var canClose = await guard.CanCloseAsync(cancellationToken); if (canClose) { closeable.Add(child); } closeCanOccur = closeCanOccur && canClose; } else { closeable.Add(child); } } return new CloseResult<T>(closeCanOccur, closeable); } } }
mit
C#
5c7e09c05f177c3cec72d95f4dcab8f0c7c33ac3
Update Global.asax.cs
ellern/champs-room,ellern/champs-room
src/Global.asax.cs
src/Global.asax.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; namespace ChampsRoom { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { ViewEngines.Engines.Clear(); ViewEngines.Engines.Add(new RazorViewEngine()); AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; namespace ChampsRoom { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { THIS WON*T BUILD ViewEngines.Engines.Clear(); ViewEngines.Engines.Add(new RazorViewEngine()); AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } } }
mit
C#
a723791611c2232a87bf58c14cf9b9258c486cbd
fix version number
nerai/CMenu
src/ConsoleMenu/Properties/AssemblyInfo.cs
src/ConsoleMenu/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 ("NConsoleMenu")] [assembly: AssemblyDescription ("Console menus are easy to build, complex menus are supported, and using them is simple and quick.")] [assembly: AssemblyConfiguration ("")] [assembly: AssemblyCompany ("Sebastian Heuchler")] [assembly: AssemblyProduct ("NConsoleMenu")] [assembly: AssemblyCopyright ("Copyright © 2014-18 Sebastian Heuchler")] [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 ("24ec1c30-cf90-41d3-9763-2da3951aa6b2")] // 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.9.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 ("NConsoleMenu")] [assembly: AssemblyDescription ("Console menus are easy to build, complex menus are supported, and using them is simple and quick.")] [assembly: AssemblyConfiguration ("")] [assembly: AssemblyCompany ("Sebastian Heuchler")] [assembly: AssemblyProduct ("NConsoleMenu")] [assembly: AssemblyCopyright ("Copyright © 2014-18 Sebastian Heuchler")] [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 ("24ec1c30-cf90-41d3-9763-2da3951aa6b2")] // 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.9.0.1")]
mit
C#
3fd2436722cffe8eb806fe7fedbaacaff18eb61a
Make GitHhb pane register link work.
github/VisualStudio,github/VisualStudio,github/VisualStudio
src/GitHub.App/ViewModels/LoggedOutViewModel.cs
src/GitHub.App/ViewModels/LoggedOutViewModel.cs
using System; using System.ComponentModel.Composition; using GitHub.Exports; using GitHub.Extensions; using GitHub.Models; using System.Reactive.Linq; using GitHub.Services; using GitHub.UI; using GitHub.ViewModels; using ReactiveUI; using System.Reactive; using System.Reactive.Subjects; using GitHub.Info; namespace GitHub.VisualStudio.UI.Views { /// <summary> /// The view model for the "Sign in to GitHub" view in the GitHub pane. /// </summary> [ExportViewModel(ViewType = UIViewType.LoggedOut)] [PartCreationPolicy(CreationPolicy.NonShared)] public class LoggedOutViewModel : BaseViewModel, ILoggedOutViewModel { IUIProvider uiProvider; IVisualStudioBrowser browser; /// <summary> /// Initializes a new instance of the <see cref="LoggedOutViewModel"/> class. /// </summary> [ImportingConstructor] public LoggedOutViewModel(IUIProvider uiProvider, IVisualStudioBrowser browser) { this.uiProvider = uiProvider; this.browser = browser; SignIn = ReactiveCommand.Create(); SignIn.Subscribe(_ => OnSignIn()); Register = ReactiveCommand.Create(); Register.Subscribe(_ => OnRegister()); } /// <inheritdoc/> public IReactiveCommand<object> SignIn { get; } /// <inheritdoc/> public IReactiveCommand<object> Register { get; } /// <summary> /// Called when the <see cref="SignIn"/> command is executed. /// </summary> private void OnSignIn() { // Show the Sign In dialog. We don't need to listen to the outcome of this: the parent // GitHubPaneViewModel will listen to RepositoryHosts.IsLoggedInToAnyHost and close // this view when the user logs in. uiProvider.SetupUI(UIControllerFlow.Authentication, null); uiProvider.RunUI(); } /// <summary> /// Called when the <see cref="Register"/> command is executed. /// </summary> private void OnRegister() { browser.OpenUrl(GitHubUrls.Pricing); } } }
using System; using System.ComponentModel.Composition; using GitHub.Exports; using GitHub.Extensions; using GitHub.Models; using System.Reactive.Linq; using GitHub.Services; using GitHub.UI; using GitHub.ViewModels; using ReactiveUI; using System.Reactive; using System.Reactive.Subjects; namespace GitHub.VisualStudio.UI.Views { /// <summary> /// The view model for the "Sign in to GitHub" view in the GitHub pane. /// </summary> [ExportViewModel(ViewType = UIViewType.LoggedOut)] [PartCreationPolicy(CreationPolicy.NonShared)] public class LoggedOutViewModel : BaseViewModel, ILoggedOutViewModel { IUIProvider uiProvider; /// <summary> /// Initializes a new instance of the <see cref="LoggedOutViewModel"/> class. /// </summary> [ImportingConstructor] public LoggedOutViewModel(IUIProvider uiProvider) { this.uiProvider = uiProvider; SignIn = ReactiveCommand.Create(); SignIn.Subscribe(_ => OnSignIn()); Register = ReactiveCommand.Create(); } /// <inheritdoc/> public IReactiveCommand<object> SignIn { get; } /// <inheritdoc/> public IReactiveCommand<object> Register { get; } /// <summary> /// Called when the <see cref="SignIn"/> command is executed. /// </summary> private void OnSignIn() { // Show the Sign In dialog. We don't need to listen to the outcome of this: the parent // GitHubPaneViewModel will listen to RepositoryHosts.IsLoggedInToAnyHost and close // this view when the user logs in. uiProvider.SetupUI(UIControllerFlow.Authentication, null); uiProvider.RunUI(); } } }
mit
C#
ad64470f2b9fdd7f82570f9a7faa77868dfd8965
Implement Sound nugget
feliwir/openSage,feliwir/openSage
src/OpenSage.Game/FX/FXNuggets/SoundFXNugget.cs
src/OpenSage.Game/FX/FXNuggets/SoundFXNugget.cs
using OpenSage.Audio; using OpenSage.Content; using OpenSage.Data.Ini; namespace OpenSage.FX { public sealed class SoundFXNugget : FXNugget { internal static SoundFXNugget Parse(IniParser parser) => parser.ParseBlock(FieldParseTable); private static readonly IniParseTable<SoundFXNugget> FieldParseTable = FXNuggetFieldParseTable.Concat(new IniParseTable<SoundFXNugget> { { "Name", (parser, x) => x.Value = parser.ParseAudioEventReference() } }); public LazyAssetReference<BaseAudioEventInfo> Value { get; private set; } internal override void Execute(FXListExecutionContext context) { context.GameContext.AudioSystem.PlayAudioEvent(Value.Value); } } }
using OpenSage.Data.Ini; namespace OpenSage.FX { public sealed class SoundFXNugget : FXNugget { internal static SoundFXNugget Parse(IniParser parser) => parser.ParseBlock(FieldParseTable); private static readonly IniParseTable<SoundFXNugget> FieldParseTable = FXNuggetFieldParseTable.Concat(new IniParseTable<SoundFXNugget> { { "Name", (parser, x) => x.Name = parser.ParseAssetReference() } }); public string Name { get; private set; } } }
mit
C#
252874ca95b3b314512544f8cfc4ec1caa701df0
Update server side API for single multiple answer question
Promact/trappist,Promact/trappist,Promact/trappist,Promact/trappist,Promact/trappist
Trappist/src/Promact.Trappist.Core/Controllers/QuestionsController.cs
Trappist/src/Promact.Trappist.Core/Controllers/QuestionsController.cs
using Microsoft.AspNetCore.Mvc; using Promact.Trappist.DomainModel.Models.Question; using Promact.Trappist.Repository.Questions; using System; namespace Promact.Trappist.Core.Controllers { [Route("api/question")] public class QuestionsController : Controller { private readonly IQuestionRepository _questionsRepository; public QuestionsController(IQuestionRepository questionsRepository) { _questionsRepository = questionsRepository; } [HttpGet] /// <summary> /// Gets all questions /// </summary> /// <returns>Questions list</returns> public IActionResult GetQuestions() { var questions = _questionsRepository.GetAllQuestions(); return Json(questions); } [HttpPost] /// <summary> /// Add single multiple answer question into SingleMultipleAnswerQuestion model /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <returns></returns> public IActionResult AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion) { _questionsRepository.AddSingleMultipleAnswerQuestion(singleMultipleAnswerQuestion); return Ok(); } /// <summary> /// Add options of single multiple answer question to SingleMultipleAnswerQuestionOption model /// </summary> /// <param name="singleMultipleAnswerQuestionOption"></param> /// <returns></returns> public IActionResult AddSingleMultipleAnswerQuestionOption(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption) { _questionsRepository.AddSingleMultipleAnswerQuestionOption(singleMultipleAnswerQuestionOption); return Ok(); } } }
using Microsoft.AspNetCore.Mvc; using Promact.Trappist.DomainModel.Models.Question; using Promact.Trappist.Repository.Questions; using System; namespace Promact.Trappist.Core.Controllers { [Route("api/question")] public class QuestionsController : Controller { private readonly IQuestionRepository _questionsRepository; public QuestionsController(IQuestionRepository questionsRepository) { _questionsRepository = questionsRepository; } [HttpGet] /// <summary> /// Gets all questions /// </summary> /// <returns>Questions list</returns> public IActionResult GetQuestions() { var questions = _questionsRepository.GetAllQuestions(); return Json(questions); } [HttpPost] /// <summary> /// /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <returns></returns> public IActionResult AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion) { _questionsRepository.AddSingleMultipleAnswerQuestion(singleMultipleAnswerQuestion); return Ok(); } /// <summary> /// /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <returns></returns> public IActionResult AddSingleMultipleAnswerQuestionOption(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption) { _questionsRepository.AddSingleMultipleAnswerQuestionOption(singleMultipleAnswerQuestionOption); return Ok(); } } }
mit
C#
dabe180213755f165a14e483c5dd6d23199dceb6
Use correct queue name in length commands
InEngine-NET/InEngine.NET,InEngine-NET/InEngine.NET,InEngine-NET/InEngine.NET
src/InEngine.Core/Queue/Commands/Length.cs
src/InEngine.Core/Queue/Commands/Length.cs
using System; using CommandLine; namespace InEngine.Core.Queue.Commands { public class Length : AbstractCommand { public override void Run() { var broker = Broker.Make(); var leftPadding = 15; Warning("Primary Queue:"); InfoText("Pending".PadLeft(leftPadding)); Line(broker.GetPrimaryWaitingQueueLength().ToString().PadLeft(10)); InfoText("In-progress".PadLeft(leftPadding)); Line(broker.GetPrimaryProcessingQueueLength().ToString().PadLeft(10)); ErrorText("Failed".PadLeft(leftPadding)); Line(broker.GetPrimaryFailedQueueLength().ToString().PadLeft(10)); Newline(); Warning("Secondary Queue:"); InfoText("Pending".PadLeft(leftPadding)); Line(broker.GetSecondaryWaitingQueueLength().ToString().PadLeft(10)); InfoText("In-progress".PadLeft(leftPadding)); Line(broker.GetSecondaryProcessingQueueLength().ToString().PadLeft(10)); ErrorText("Failed".PadLeft(leftPadding)); Line(broker.GetSecondaryFailedQueueLength().ToString().PadLeft(10)); Newline(); } } }
using System; using CommandLine; namespace InEngine.Core.Queue.Commands { public class Length : AbstractCommand { public override void Run() { var broker = Broker.Make(); var leftPadding = 15; Warning("Primary Queue:"); InfoText("Pending".PadLeft(leftPadding)); Line(broker.GetPrimaryWaitingQueueLength().ToString().PadLeft(10)); InfoText("In-progress".PadLeft(leftPadding)); Line(broker.GetPrimaryProcessingQueueLength().ToString().PadLeft(10)); ErrorText("Failed".PadLeft(leftPadding)); Line(broker.GetPrimaryProcessingQueueLength().ToString().PadLeft(10)); Newline(); Warning("Secondary Queue:"); InfoText("Pending".PadLeft(leftPadding)); Line(broker.GetSecondaryWaitingQueueLength().ToString().PadLeft(10)); InfoText("In-progress".PadLeft(leftPadding)); Line(broker.GetSecondaryProcessingQueueLength().ToString().PadLeft(10)); ErrorText("Failed".PadLeft(leftPadding)); Line(broker.GetSecondaryProcessingQueueLength().ToString().PadLeft(10)); Newline(); } } }
mit
C#
d15eb90c27593692b2b252656fcbd2e297d8d268
clean up
BigBabay/AsyncConverter,BigBabay/AsyncConverter
AsyncConverter/AsyncHelpers/AwaitEliders/MethodAwaitElider.cs
AsyncConverter/AsyncHelpers/AwaitEliders/MethodAwaitElider.cs
using JetBrains.ProjectModel; using JetBrains.ReSharper.Psi.CSharp; using JetBrains.ReSharper.Psi.CSharp.Tree; namespace AsyncConverter.AsyncHelpers.AwaitEliders { [SolutionComponent] internal class MethodAwaitElider : ICustomAwaitElider { public bool CanElide(ICSharpDeclaration declarationOrClosure) => declarationOrClosure is IMethodDeclaration; public void Elide(ICSharpDeclaration declarationOrClosure, ICSharpExpression awaitExpression) { var factory = CSharpElementFactory.GetInstance(awaitExpression); var methodDeclaration = declarationOrClosure as IMethodDeclaration; if (methodDeclaration == null) return; methodDeclaration.SetAsync(false); if (methodDeclaration.Body != null) { var statement = factory.CreateStatement("return $0;", awaitExpression); awaitExpression.GetContainingStatement()?.ReplaceBy(statement); } else methodDeclaration.ArrowClause?.SetExpression(awaitExpression); } } }
using JetBrains.ProjectModel; using JetBrains.ReSharper.Psi.CSharp; using JetBrains.ReSharper.Psi.CSharp.Tree; namespace AsyncConverter.AsyncHelpers.AwaitEliders { [SolutionComponent] internal class MethodAwaitElider : ICustomAwaitElider { public bool CanElide(ICSharpDeclaration declarationOrClosure) => declarationOrClosure is IMethodDeclaration; public void Elide(ICSharpDeclaration declarationOrClosure, ICSharpExpression awaitExpression) { var factory = CSharpElementFactory.GetInstance(awaitExpression); var methodDeclaration = declarationOrClosure as IMethodDeclaration; if (methodDeclaration == null) return; methodDeclaration.SetAsync(false); if (methodDeclaration.Body != null) { var statement = factory.CreateStatement("return $0;", awaitExpression); awaitExpression.GetContainingStatement()?.ReplaceBy(statement); } else methodDeclaration.ArrowClause?.SetExpression(awaitExpression); } } }
mit
C#
126660e6d19c43701750619910d94ed10b13bfae
modify update
SoftFx/FDK,SoftFx/FDK,SoftFx/FDK,SoftFx/FDK,SoftFx/FDK,SoftFx/FDK,SoftFx/FDK,SoftFx/FDK
Examples/CSharp/DataTradeExamples/ModifyTradeRecordExample.cs
Examples/CSharp/DataTradeExamples/ModifyTradeRecordExample.cs
namespace DataTradeExamples { using System; using SoftFX.Extended; class ModifyTradeRecordExample : Example { public ModifyTradeRecordExample(string address, string username, string password) : base(address, username, password) { } protected override void RunExample() { var position0 = this.Trade.Server.SendOrder("EURUSD", TradeCommand.Market, TradeRecordSide.Buy, 0, 1000000, null, null, null, null, null, null, null); var position1 = position0.Modify(null, null, null, 2, null, null, null, null); Console.WriteLine("Opened position = {0}", position0); Console.WriteLine("Modified position = {0}", position1); var limit0 = this.Trade.Server.SendOrder("EURUSD", TradeCommand.Market, TradeRecordSide.Buy, 1, 1000000, null, null, null, null, null, null, null); var limit1 = limit0.Modify(null, null, null, 2, null, null, null, null); Console.WriteLine("Opened limit order = {0}", limit0); Console.WriteLine("Modified limit order = {0}", limit1); var stop0 = this.Trade.Server.SendOrder("EURUSD", TradeCommand.Market, TradeRecordSide.Buy, 1.8, 1000000, null, null, null, null, null, null, null); var stop1 = stop0.Modify(null, null, null, 2, null, null, null, null); Console.WriteLine("Opened stop order = {0}", stop0); Console.WriteLine("Modified stop order = {0}", stop1); } } }
namespace DataTradeExamples { using System; using SoftFX.Extended; class ModifyTradeRecordExample : Example { public ModifyTradeRecordExample(string address, string username, string password) : base(address, username, password) { } protected override void RunExample() { var position0 = this.Trade.Server.SendOrder("EURUSD", TradeCommand.Market, TradeRecordSide.Buy, 0, 1000000, null, null, null, null, null, null, null); var position1 = position0.Modify(null, null, null, 2, null); Console.WriteLine("Opened position = {0}", position0); Console.WriteLine("Modified position = {0}", position1); var limit0 = this.Trade.Server.SendOrder("EURUSD", TradeCommand.Market, TradeRecordSide.Buy, 1, 1000000, null, null, null, null, null, null, null); var limit1 = limit0.Modify(null, null, null, 2, null); Console.WriteLine("Opened limit order = {0}", limit0); Console.WriteLine("Modified limit order = {0}", limit1); var stop0 = this.Trade.Server.SendOrder("EURUSD", TradeCommand.Market, TradeRecordSide.Buy, 1.8, 1000000, null, null, null, null, null, null, null); var stop1 = stop0.Modify(null, null, null, 2, null); Console.WriteLine("Opened stop order = {0}", stop0); Console.WriteLine("Modified stop order = {0}", stop1); } } }
mit
C#
91396e561f44c6992a359071d62ef64da78bbaa4
Deal with IDE1006
hfloyd/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,leekelleher/Umbraco-CMS,abryukhov/Umbraco-CMS,bjarnef/Umbraco-CMS,madsoulswe/Umbraco-CMS,tcmorris/Umbraco-CMS,leekelleher/Umbraco-CMS,mattbrailsford/Umbraco-CMS,tompipe/Umbraco-CMS,mattbrailsford/Umbraco-CMS,tcmorris/Umbraco-CMS,tcmorris/Umbraco-CMS,robertjf/Umbraco-CMS,KevinJump/Umbraco-CMS,KevinJump/Umbraco-CMS,NikRimington/Umbraco-CMS,hfloyd/Umbraco-CMS,robertjf/Umbraco-CMS,dawoe/Umbraco-CMS,abjerner/Umbraco-CMS,dawoe/Umbraco-CMS,marcemarc/Umbraco-CMS,WebCentrum/Umbraco-CMS,marcemarc/Umbraco-CMS,rasmuseeg/Umbraco-CMS,lars-erik/Umbraco-CMS,marcemarc/Umbraco-CMS,dawoe/Umbraco-CMS,rasmuseeg/Umbraco-CMS,hfloyd/Umbraco-CMS,hfloyd/Umbraco-CMS,abjerner/Umbraco-CMS,abryukhov/Umbraco-CMS,mattbrailsford/Umbraco-CMS,umbraco/Umbraco-CMS,KevinJump/Umbraco-CMS,abjerner/Umbraco-CMS,bjarnef/Umbraco-CMS,madsoulswe/Umbraco-CMS,arknu/Umbraco-CMS,marcemarc/Umbraco-CMS,KevinJump/Umbraco-CMS,robertjf/Umbraco-CMS,KevinJump/Umbraco-CMS,abryukhov/Umbraco-CMS,WebCentrum/Umbraco-CMS,rasmuseeg/Umbraco-CMS,NikRimington/Umbraco-CMS,umbraco/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,lars-erik/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,hfloyd/Umbraco-CMS,robertjf/Umbraco-CMS,mattbrailsford/Umbraco-CMS,tcmorris/Umbraco-CMS,umbraco/Umbraco-CMS,arknu/Umbraco-CMS,arknu/Umbraco-CMS,dawoe/Umbraco-CMS,bjarnef/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,dawoe/Umbraco-CMS,tompipe/Umbraco-CMS,leekelleher/Umbraco-CMS,umbraco/Umbraco-CMS,tcmorris/Umbraco-CMS,madsoulswe/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,bjarnef/Umbraco-CMS,arknu/Umbraco-CMS,lars-erik/Umbraco-CMS,leekelleher/Umbraco-CMS,WebCentrum/Umbraco-CMS,abryukhov/Umbraco-CMS,tcmorris/Umbraco-CMS,marcemarc/Umbraco-CMS,NikRimington/Umbraco-CMS,lars-erik/Umbraco-CMS,robertjf/Umbraco-CMS,tompipe/Umbraco-CMS,lars-erik/Umbraco-CMS,abjerner/Umbraco-CMS,leekelleher/Umbraco-CMS
src/Umbraco.Web/Properties/AssemblyInfo.cs
src/Umbraco.Web/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Umbraco.Web")] [assembly: AssemblyDescription("Umbraco Web")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Umbraco CMS")] [assembly: ComVisible(false)] [assembly: Guid("ce9d3539-299e-40d3-b605-42ac423e24fa")] // Umbraco Cms [assembly: InternalsVisibleTo("Umbraco.Web.UI")] [assembly: InternalsVisibleTo("Umbraco.Tests")] [assembly: InternalsVisibleTo("Umbraco.Tests.Benchmarks")] [assembly: InternalsVisibleTo("Umbraco.VisualStudio")] // fixme - what is this? [assembly: InternalsVisibleTo("Umbraco.ModelsBuilder")] // fixme - why? [assembly: InternalsVisibleTo("Umbraco.ModelsBuilder.AspNet")] // fixme - why? // Allow this to be mocked in our unit tests [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] // Umbraco Deploy [assembly: InternalsVisibleTo("Umbraco.Deploy")] [assembly: InternalsVisibleTo("Umbraco.Deploy.UI")] [assembly: InternalsVisibleTo("Umbraco.Deploy.Cloud")] // Umbraco Forms [assembly: InternalsVisibleTo("Umbraco.Forms.Core")] [assembly: InternalsVisibleTo("Umbraco.Forms.Core.Providers")] [assembly: InternalsVisibleTo("Umbraco.Forms.Web")] // Umbraco Headless [assembly: InternalsVisibleTo("Umbraco.Headless")] // v8 [assembly: InternalsVisibleTo("Umbraco.Compat7")] // code analysis // IDE1006 is broken, wants _value syntax for consts, etc - and it's even confusing ppl at MS, kill it [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "~_~")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Umbraco.Web")] [assembly: AssemblyDescription("Umbraco Web")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Umbraco CMS")] [assembly: ComVisible(false)] [assembly: Guid("ce9d3539-299e-40d3-b605-42ac423e24fa")] // Umbraco Cms [assembly: InternalsVisibleTo("Umbraco.Web.UI")] [assembly: InternalsVisibleTo("Umbraco.Tests")] [assembly: InternalsVisibleTo("Umbraco.Tests.Benchmarks")] [assembly: InternalsVisibleTo("Umbraco.VisualStudio")] // fixme - what is this? [assembly: InternalsVisibleTo("Umbraco.ModelsBuilder")] // fixme - why? [assembly: InternalsVisibleTo("Umbraco.ModelsBuilder.AspNet")] // fixme - why? // Allow this to be mocked in our unit tests [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] // Umbraco Deploy [assembly: InternalsVisibleTo("Umbraco.Deploy")] [assembly: InternalsVisibleTo("Umbraco.Deploy.UI")] [assembly: InternalsVisibleTo("Umbraco.Deploy.Cloud")] // Umbraco Forms [assembly: InternalsVisibleTo("Umbraco.Forms.Core")] [assembly: InternalsVisibleTo("Umbraco.Forms.Core.Providers")] [assembly: InternalsVisibleTo("Umbraco.Forms.Web")] // Umbraco Headless [assembly: InternalsVisibleTo("Umbraco.Headless")] // v8 [assembly: InternalsVisibleTo("Umbraco.Compat7")]
mit
C#
1f62bfa91f89d3c73517fdcc477b1c94e6c5f763
add CheckChangesOnUpdate option
linpiero/Serenity,volkanceylan/Serenity,volkanceylan/Serenity,WasimAhmad/Serenity,linpiero/Serenity,WasimAhmad/Serenity,rolembergfilho/Serenity,linpiero/Serenity,linpiero/Serenity,dfaruque/Serenity,dfaruque/Serenity,dfaruque/Serenity,dfaruque/Serenity,WasimAhmad/Serenity,rolembergfilho/Serenity,dfaruque/Serenity,linpiero/Serenity,rolembergfilho/Serenity,rolembergfilho/Serenity,rolembergfilho/Serenity,WasimAhmad/Serenity,volkanceylan/Serenity,volkanceylan/Serenity,WasimAhmad/Serenity,volkanceylan/Serenity
Serenity.Data/Mapping/MasterDetailRelationAttribute.cs
Serenity.Data/Mapping/MasterDetailRelationAttribute.cs
using System; namespace Serenity.Data.Mapping { [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)] public sealed class MasterDetailRelationAttribute : Attribute { public MasterDetailRelationAttribute(string foreignKey) { Check.NotNullOrEmpty(foreignKey, "MasterDetailRelation.ForeignKey"); this.ForeignKey = foreignKey; this.CheckChangesOnUpdate = true; } public string ForeignKey { get; private set; } public bool CheckChangesOnUpdate { get; set; } } }
using System; namespace Serenity.Data.Mapping { [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)] public sealed class MasterDetailRelationAttribute : Attribute { public MasterDetailRelationAttribute(string foreignKey) { Check.NotNullOrEmpty(foreignKey, "MasterDetailRelation.ForeignKey"); this.ForeignKey = foreignKey; } public string ForeignKey { get; private set; } } }
mit
C#
5de6b2f16f885a167fd27757d4b1b75c303ca63e
Remove unnecessary extensions
mrahhal/Konsola
src/Konsola/Parsing/IConsole.cs
src/Konsola/Parsing/IConsole.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Konsola.Parsing { public interface IConsole { void Write(WriteKind kind, string value); } public static class ConsoleExtensions { public static void WriteLine(this IConsole @this, WriteKind kind, string value) { @this.Write(kind, value + Environment.NewLine); } public static void WriteLine(this IConsole @this) { @this.WriteLine(WriteKind.Normal, string.Empty); } public static void Write(this IConsole @this, string value) { @this.Write(WriteKind.Normal, value); } public static void Write(this IConsole @this, string format, params object[] args) { @this.Write(WriteKind.Normal, string.Format(format, args)); } public static void WriteLine(this IConsole @this, string value) { @this.WriteLine(WriteKind.Normal, value); } public static void WriteLine(this IConsole @this, string format, params object[] args) { @this.WriteLine(WriteKind.Normal, string.Format(format, args)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Konsola.Parsing { public interface IConsole { void Write(WriteKind kind, string value); } public static class ConsoleExtensions { public static void WriteLine(this IConsole @this, WriteKind kind, string value) { @this.Write(kind, value + Environment.NewLine); } public static void WriteLine(this IConsole @this) { @this.WriteLine(WriteKind.Normal, string.Empty); } public static void Write(this IConsole @this, string value) { @this.Write(WriteKind.Normal, value); } public static void Write(this IConsole @this, string format, params object[] args) { @this.Write(WriteKind.Normal, string.Format(format, args)); } public static void WriteLine(this IConsole @this, string value) { @this.WriteLine(WriteKind.Normal, value); } public static void WriteLine(this IConsole @this, string format, params object[] args) { @this.WriteLine(WriteKind.Normal, string.Format(format, args)); } public static void WriteJustified(this IConsole @this, int padding, string format, params object[] args) { @this.WriteJustified(padding, string.Format(format, args)); } public static void WriteJustified(this IConsole @this, int padding, string value) { @this.WriteJustified(WriteKind.Normal, padding, value); } public static void WriteJustified(this IConsole @this, WriteKind kind, int padding, string format, params object[] args) { @this.WriteJustified(kind, padding, string.Format(format, args)); } } }
mit
C#
f0a5c37dadbfa13ee67510af03c7cd5ad91e7277
Add a request type
flagbug/Espera.Network
Espera.Network/NetworkMessageType.cs
Espera.Network/NetworkMessageType.cs
namespace Espera.Network { public enum NetworkMessageType { Push, Response, Request } }
namespace Espera.Network { public enum NetworkMessageType { Push, Response } }
mit
C#
f438421d00ee231c0ed6ac0222f13c0a3cfe847c
Use chevron down for drop downs.
bigfont/orchard-cms-modules-and-themes,bigfont/orchard-cms-modules-and-themes,bigfont/orchard-cms-modules-and-themes,bigfont/orchard-cms-modules-and-themes,bigfont/orchard-cms-modules-and-themes
Orchard.Source.1.8.1/src/Orchard.Web/Themes/Bootstrap_3_2_0_Base/Views/MenuItem.cshtml
Orchard.Source.1.8.1/src/Orchard.Web/Themes/Bootstrap_3_2_0_Base/Views/MenuItem.cshtml
@{ // odd formatting in this file is to cause more attractive results in the output. var items = Enumerable.Cast<dynamic>((System.Collections.IEnumerable)Model); } @{ if (!HasText(Model.Text)) { @DisplayChildren(Model) } else { if ((bool)Model.Selected) { Model.Classes.Add("current"); Model.Classes.Add("active"); // for bootstrap } if (items.Any()) { Model.Classes.Add("dropdown"); // for bootstrap and/or font-awesome Model.BootstrapAttributes = "data-toggle='dropdown'"; Model.BootstrapIcon = "<span class='glyphicon glyphicon-chevron-down'></span>"; } @* morphing the shape to keep Model untouched*@ Model.Metadata.Alternates.Clear(); Model.Metadata.Type = "MenuItemLink"; @* render the menu item only if it has some content *@ var renderedMenuItemLink = Display(Model); if (HasText(renderedMenuItemLink)) { var tag = Tag(Model, "li"); @tag.StartElement @renderedMenuItemLink if (items.Any()) { <ul class="dropdown-menu"> @DisplayChildren(Model) </ul> } @tag.EndElement } } }
@{ // odd formatting in this file is to cause more attractive results in the output. var items = Enumerable.Cast<dynamic>((System.Collections.IEnumerable)Model); } @{ if (!HasText(Model.Text)) { @DisplayChildren(Model) } else { if ((bool)Model.Selected) { Model.Classes.Add("current"); Model.Classes.Add("active"); // for bootstrap } if (items.Any()) { Model.Classes.Add("dropdown"); // for bootstrap and/or font-awesome Model.BootstrapAttributes = "data-toggle='dropdown'"; Model.BootstrapIcon = "<span class='glyphicon glyphicon-hand-down'></span>"; } @* morphing the shape to keep Model untouched*@ Model.Metadata.Alternates.Clear(); Model.Metadata.Type = "MenuItemLink"; @* render the menu item only if it has some content *@ var renderedMenuItemLink = Display(Model); if (HasText(renderedMenuItemLink)) { var tag = Tag(Model, "li"); @tag.StartElement @renderedMenuItemLink if (items.Any()) { <ul class="dropdown-menu"> @DisplayChildren(Model) </ul> } @tag.EndElement } } }
bsd-3-clause
C#
d22a1865c92e796e1de94900e092607091ffc9c7
bump up assembly version
Azure/durabletask,affandar/durabletask,yonglehou/durabletask,ddobric/durabletask,jasoneilts/durabletask
Framework/Properties/AssemblyInfo.cs
Framework/Properties/AssemblyInfo.cs
// ---------------------------------------------------------------------------------- // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Durable Task Framework")] [assembly: AssemblyDescription( @"This package provides a C# based durable Task framework for writing long running applications." )] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Durable Task Framework")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("1d626d8b-330b-4c6a-b689-c0fefbeb99cd")] [assembly: AssemblyVersion("1.0.0.1")] [assembly: AssemblyFileVersion("1.0.0.1")] [assembly: InternalsVisibleTo("FrameworkUnitTests")]
// ---------------------------------------------------------------------------------- // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Durable Task Framework")] [assembly: AssemblyDescription( @"This package provides a C# based durable Task framework for writing long running applications." )] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Durable Task Framework")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("1d626d8b-330b-4c6a-b689-c0fefbeb99cd")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: InternalsVisibleTo("FrameworkUnitTests")]
apache-2.0
C#
d65510a95f7e44c401b1a6934493c658cfe8717a
fix ContractReferenceAssemblyAttribute tfm (#187)
theraot/Theraot
Framework.Core/System/Diagnostics/Contracts/ContractReferenceAssemblyAttribute.cs
Framework.Core/System/Diagnostics/Contracts/ContractReferenceAssemblyAttribute.cs
#if LESSTHAN_NET40 // 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. namespace System.Diagnostics.Contracts { /// <summary> /// Attribute that specifies that an assembly is a reference assembly with contracts. /// </summary> [AttributeUsage(AttributeTargets.Assembly)] public sealed class ContractReferenceAssemblyAttribute : Attribute { // Empty } } #endif
#if LESSTHAN_NET45 // 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. namespace System.Diagnostics.Contracts { /// <summary> /// Attribute that specifies that an assembly is a reference assembly with contracts. /// </summary> [AttributeUsage(AttributeTargets.Assembly)] public sealed class ContractReferenceAssemblyAttribute : Attribute { // Empty } } #endif
mit
C#
f98c463365120a1786c3c2ad0edbb5dba027813c
Fix warning.
DustinCampbell/roslyn,brettfo/roslyn,swaroop-sridhar/roslyn,physhi/roslyn,davkean/roslyn,brettfo/roslyn,MichalStrehovsky/roslyn,reaction1989/roslyn,jmarolf/roslyn,KirillOsenkov/roslyn,physhi/roslyn,agocke/roslyn,jasonmalinowski/roslyn,tmat/roslyn,VSadov/roslyn,shyamnamboodiripad/roslyn,mavasani/roslyn,AlekseyTs/roslyn,swaroop-sridhar/roslyn,heejaechang/roslyn,ErikSchierboom/roslyn,MichalStrehovsky/roslyn,mgoertz-msft/roslyn,diryboy/roslyn,VSadov/roslyn,KevinRansom/roslyn,aelij/roslyn,swaroop-sridhar/roslyn,mavasani/roslyn,agocke/roslyn,mgoertz-msft/roslyn,abock/roslyn,MichalStrehovsky/roslyn,gafter/roslyn,tmat/roslyn,AmadeusW/roslyn,shyamnamboodiripad/roslyn,stephentoub/roslyn,sharwell/roslyn,tannergooding/roslyn,DustinCampbell/roslyn,abock/roslyn,ErikSchierboom/roslyn,wvdd007/roslyn,AlekseyTs/roslyn,bartdesmet/roslyn,abock/roslyn,tannergooding/roslyn,gafter/roslyn,KevinRansom/roslyn,panopticoncentral/roslyn,dotnet/roslyn,CyrusNajmabadi/roslyn,tmat/roslyn,nguerrera/roslyn,ErikSchierboom/roslyn,wvdd007/roslyn,tannergooding/roslyn,nguerrera/roslyn,genlu/roslyn,nguerrera/roslyn,AmadeusW/roslyn,agocke/roslyn,wvdd007/roslyn,reaction1989/roslyn,eriawan/roslyn,jmarolf/roslyn,weltkante/roslyn,KirillOsenkov/roslyn,gafter/roslyn,panopticoncentral/roslyn,shyamnamboodiripad/roslyn,bartdesmet/roslyn,mgoertz-msft/roslyn,davkean/roslyn,heejaechang/roslyn,jasonmalinowski/roslyn,eriawan/roslyn,jasonmalinowski/roslyn,AmadeusW/roslyn,physhi/roslyn,diryboy/roslyn,VSadov/roslyn,dotnet/roslyn,eriawan/roslyn,jcouv/roslyn,reaction1989/roslyn,weltkante/roslyn,sharwell/roslyn,heejaechang/roslyn,jmarolf/roslyn,KirillOsenkov/roslyn,weltkante/roslyn,stephentoub/roslyn,AlekseyTs/roslyn,davkean/roslyn,DustinCampbell/roslyn,bartdesmet/roslyn,CyrusNajmabadi/roslyn,CyrusNajmabadi/roslyn,sharwell/roslyn,aelij/roslyn,genlu/roslyn,mavasani/roslyn,aelij/roslyn,diryboy/roslyn,jcouv/roslyn,genlu/roslyn,jcouv/roslyn,panopticoncentral/roslyn,dotnet/roslyn,KevinRansom/roslyn,brettfo/roslyn,stephentoub/roslyn
src/EditorFeatures/CSharp/Wrapping/SeparatedSyntaxList/CSharpParameterWrapper.cs
src/EditorFeatures/CSharp/Wrapping/SeparatedSyntaxList/CSharpParameterWrapper.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.Linq; using Microsoft.CodeAnalysis.CSharp.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Editor.Wrapping.SeparatedSyntaxList { internal partial class CSharpParameterWrapper : AbstractCSharpSeparatedSyntaxListWrapper<BaseParameterListSyntax, ParameterSyntax> { protected override string ListName => FeaturesResources.parameter_list; protected override string ItemNamePlural => FeaturesResources.parameters; protected override string ItemNameSingular => FeaturesResources.parameter; protected override SeparatedSyntaxList<ParameterSyntax> GetListItems(BaseParameterListSyntax listSyntax) => listSyntax.Parameters; protected override BaseParameterListSyntax TryGetApplicableList(SyntaxNode node) => CSharpSyntaxGenerator.GetParameterList(node); protected override bool PositionIsApplicable( SyntaxNode root, int position, SyntaxNode declaration, BaseParameterListSyntax listSyntax) { // CSharpSyntaxGenerator.GetParameterList synthesizes a parameter list for simple-lambdas. // In that case, we're not applicable in that list. if (declaration.Kind() == SyntaxKind.SimpleLambdaExpression) { return false; } var generator = CSharpSyntaxGenerator.Instance; var attributes = generator.GetAttributes(declaration); // We want to offer this feature in the header of the member. For now, we consider // the header to be the part after the attributes, to the end of the parameter list. var firstToken = attributes?.Count > 0 ? attributes.Last().GetLastToken().GetNextToken() : declaration.GetFirstToken(); var lastToken = listSyntax.GetLastToken(); var headerSpan = TextSpan.FromBounds(firstToken.SpanStart, lastToken.Span.End); return headerSpan.IntersectsWith(position); } } }
// 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.Composition; using System.Linq; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Editor.Wrapping.SeparatedSyntaxList { internal partial class CSharpParameterWrapper : AbstractCSharpSeparatedSyntaxListWrapper<BaseParameterListSyntax, ParameterSyntax> { protected override string ListName => FeaturesResources.parameter_list; protected override string ItemNamePlural => FeaturesResources.parameters; protected override string ItemNameSingular => FeaturesResources.parameter; protected override SeparatedSyntaxList<ParameterSyntax> GetListItems(BaseParameterListSyntax listSyntax) => listSyntax.Parameters; protected override BaseParameterListSyntax TryGetApplicableList(SyntaxNode node) => CSharpSyntaxGenerator.GetParameterList(node); protected override bool PositionIsApplicable( SyntaxNode root, int position, SyntaxNode declaration, BaseParameterListSyntax listSyntax) { // CSharpSyntaxGenerator.GetParameterList synthesizes a parameter list for simple-lambdas. // In that case, we're not applicable in that list. if (declaration.Kind() == SyntaxKind.SimpleLambdaExpression) { return false; } var generator = CSharpSyntaxGenerator.Instance; var attributes = generator.GetAttributes(declaration); // We want to offer this feature in the header of the member. For now, we consider // the header to be the part after the attributes, to the end of the parameter list. var firstToken = attributes?.Count > 0 ? attributes.Last().GetLastToken().GetNextToken() : declaration.GetFirstToken(); var lastToken = listSyntax.GetLastToken(); var headerSpan = TextSpan.FromBounds(firstToken.SpanStart, lastToken.Span.End); return headerSpan.IntersectsWith(position); } } }
mit
C#
2c34c866895a6520be7e9ba59f201d8ac60f0f69
Fix automapper configuration
LachezarTomov/CastService,LachezarTomov/CastService,LachezarTomov/CastService
CastService/Web/CastService.Web/Global.asax.cs
CastService/Web/CastService.Web/Global.asax.cs
using CastService.Web.Infrastructure.Mapping; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Web; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; namespace CastService.Web { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); var autoMapperConfig = new AutoMapperConfig(Assembly.GetExecutingAssembly()); autoMapperConfig.Execute(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; namespace CastService.Web { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } } }
apache-2.0
C#
a3db59cf847a6f0d69180b42e1760cae585f2edc
Update CustomersService.cs
ServiceStack/ServiceStack.Examples,zhaokunfay/ServiceStack.Examples,zhaokunfay/ServiceStack.Examples,ServiceStack/ServiceStack.Examples,ServiceStack/ServiceStack.Examples,zhaokunfay/ServiceStack.Examples,ServiceStack/ServiceStack.Examples,zhaokunfay/ServiceStack.Examples
src/ServiceStack.Northwind/ServiceStack.Northwind.ServiceInterface/CustomersService.cs
src/ServiceStack.Northwind/ServiceStack.Northwind.ServiceInterface/CustomersService.cs
namespace ServiceStack.Northwind.ServiceInterface { using ServiceStack.Northwind.ServiceModel.Operations; using ServiceStack.Northwind.ServiceModel.Types; using ServiceStack.OrmLite; using ServiceStack.ServiceInterface; public class CustomersService : Service { public CustomersResponse Get(Customers request) { return new CustomersResponse { Customers = Db.Select<Customer>() }; } } }
namespace ServiceStack.Northwind.ServiceInterface { using ServiceStack.Northwind.ServiceModel.Operations; using ServiceStack.Northwind.ServiceModel.Types; using ServiceStack.OrmLite; using ServiceStack.ServiceInterface; public class CustomersService : Service { public IDbConnectionFactory DbFactory { get; set; } public CustomersResponse Get(Customers request) { return new CustomersResponse { Customers = Db.Select<Customer>() }; } } }
bsd-3-clause
C#
cf15e0e3be075017065a1a691f12e487e4a383eb
Fix failure to format error message
tannergooding/roslyn,brettfo/roslyn,genlu/roslyn,bartdesmet/roslyn,aelij/roslyn,AmadeusW/roslyn,ErikSchierboom/roslyn,diryboy/roslyn,stephentoub/roslyn,shyamnamboodiripad/roslyn,KirillOsenkov/roslyn,tannergooding/roslyn,panopticoncentral/roslyn,heejaechang/roslyn,ErikSchierboom/roslyn,weltkante/roslyn,tannergooding/roslyn,mgoertz-msft/roslyn,brettfo/roslyn,jasonmalinowski/roslyn,AlekseyTs/roslyn,wvdd007/roslyn,KevinRansom/roslyn,stephentoub/roslyn,jasonmalinowski/roslyn,AmadeusW/roslyn,gafter/roslyn,jasonmalinowski/roslyn,KirillOsenkov/roslyn,KevinRansom/roslyn,bartdesmet/roslyn,KevinRansom/roslyn,mavasani/roslyn,wvdd007/roslyn,eriawan/roslyn,heejaechang/roslyn,sharwell/roslyn,ErikSchierboom/roslyn,tmat/roslyn,shyamnamboodiripad/roslyn,gafter/roslyn,physhi/roslyn,CyrusNajmabadi/roslyn,mgoertz-msft/roslyn,panopticoncentral/roslyn,brettfo/roslyn,wvdd007/roslyn,tmat/roslyn,dotnet/roslyn,mavasani/roslyn,weltkante/roslyn,mavasani/roslyn,physhi/roslyn,aelij/roslyn,jmarolf/roslyn,sharwell/roslyn,dotnet/roslyn,diryboy/roslyn,gafter/roslyn,diryboy/roslyn,jmarolf/roslyn,eriawan/roslyn,weltkante/roslyn,jmarolf/roslyn,heejaechang/roslyn,stephentoub/roslyn,dotnet/roslyn,genlu/roslyn,AlekseyTs/roslyn,sharwell/roslyn,KirillOsenkov/roslyn,physhi/roslyn,CyrusNajmabadi/roslyn,AmadeusW/roslyn,genlu/roslyn,AlekseyTs/roslyn,panopticoncentral/roslyn,aelij/roslyn,tmat/roslyn,shyamnamboodiripad/roslyn,CyrusNajmabadi/roslyn,bartdesmet/roslyn,mgoertz-msft/roslyn,eriawan/roslyn
src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Lightup/SyntaxFactoryEx.cs
src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Lightup/SyntaxFactoryEx.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 Microsoft.CodeAnalysis.CSharp.Syntax; #if CODE_STYLE using System; using System.Linq; using System.Linq.Expressions; using System.Reflection; #endif namespace Microsoft.CodeAnalysis.CSharp.Shared.Lightup { internal static class SyntaxFactoryEx { #if CODE_STYLE private static readonly Func<TypeSyntax, PatternSyntax> TypePatternAccessor; static SyntaxFactoryEx() { var typePatternMethods = typeof(SyntaxFactory).GetTypeInfo().GetDeclaredMethods(nameof(TypePattern)); var typePatternMethod = typePatternMethods.FirstOrDefault(method => method.GetParameters().Length == 1); if (typePatternMethod is object) { var typeParameter = Expression.Parameter(typeof(TypeSyntax), "type"); var expression = Expression.Lambda<Func<TypeSyntax, PatternSyntax>>( Expression.Call( typePatternMethod, typeParameter), typeParameter); TypePatternAccessor = expression.Compile(); } else { TypePatternAccessor = ThrowNotSupportedOnFallback<TypeSyntax, PatternSyntax>(nameof(SyntaxFactory), nameof(TypePattern)); } } public static PatternSyntax TypePattern(TypeSyntax type) { return TypePatternAccessor(type); } private static Func<T, TResult> ThrowNotSupportedOnFallback<T, TResult>(string typeName, string methodName) { return _ => throw new NotSupportedException(string.Format(CSharpCompilerExtensionsResources._0_1_is_not_supported_in_this_version, typeName, methodName)); } #else public static PatternSyntax TypePattern(TypeSyntax type) => SyntaxFactory.TypePattern(type); #endif } }
// 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 Microsoft.CodeAnalysis.CSharp.Syntax; #if CODE_STYLE using System; using System.Linq; using System.Linq.Expressions; using System.Reflection; #endif namespace Microsoft.CodeAnalysis.CSharp.Shared.Lightup { internal static class SyntaxFactoryEx { #if CODE_STYLE private static readonly Func<TypeSyntax, PatternSyntax> TypePatternAccessor; static SyntaxFactoryEx() { var typePatternMethods = typeof(SyntaxFactory).GetTypeInfo().GetDeclaredMethods(nameof(TypePattern)); var typePatternMethod = typePatternMethods.FirstOrDefault(method => method.GetParameters().Length == 1); if (typePatternMethod is object) { var typeParameter = Expression.Parameter(typeof(TypeSyntax), "type"); var expression = Expression.Lambda<Func<TypeSyntax, PatternSyntax>>( Expression.Call( typePatternMethod, typeParameter), typeParameter); TypePatternAccessor = expression.Compile(); } else { TypePatternAccessor = ThrowNotSupportedOnFallback<TypeSyntax, PatternSyntax>(nameof(SyntaxFactory), nameof(TypePattern)); } } public static PatternSyntax TypePattern(TypeSyntax type) { return TypePatternAccessor(type); } #pragma warning disable IDE0060 // Remove unused parameter private static Func<T, TResult> ThrowNotSupportedOnFallback<T, TResult>(string typeName, string methodName) #pragma warning restore IDE0060 // Remove unused parameter { return _ => throw new NotSupportedException(CSharpCompilerExtensionsResources._0_1_is_not_supported_in_this_version); } #else public static PatternSyntax TypePattern(TypeSyntax type) => SyntaxFactory.TypePattern(type); #endif } }
mit
C#
9d44a2fba4b65bcb50ae1bdfeaee0ed2ea8d0fd5
Use runtime information
axelheer/nein-linq,BenJenkinson/nein-linq
test/NeinLinq.Tests/EntityAsyncQuery/Context.cs
test/NeinLinq.Tests/EntityAsyncQuery/Context.cs
using NeinLinq.Fakes.DbAsyncQuery; using Microsoft.EntityFrameworkCore; using System.Runtime.InteropServices; namespace NeinLinq.Tests.EntityAsyncQuery { public class Context : DbContext { public DbSet<Dummy> Dummies { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { optionsBuilder.UseSqlServer(@"Data Source=(localdb)\MSSQLLocalDB; Initial Catalog=NeinLinq.EntityFrameworkCore; Integrated Security=true;"); } else { optionsBuilder.UseInMemoryDatabase("NeinLinq.EntityFrameworkCore"); } } public void ResetDatabase() { Database.EnsureCreated(); Dummies.RemoveRange(Dummies); SaveChanges(); } } }
using NeinLinq.Fakes.DbAsyncQuery; using Microsoft.EntityFrameworkCore; using System; namespace NeinLinq.Tests.EntityAsyncQuery { public class Context : DbContext { public DbSet<Dummy> Dummies { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (Environment.GetEnvironmentVariable("OS") == "Windows_NT") { optionsBuilder.UseSqlServer(@"Data Source=(localdb)\MSSQLLocalDB; Initial Catalog=NeinLinq.EntityFrameworkCore; Integrated Security=true;"); } else { optionsBuilder.UseInMemoryDatabase("NeinLinq.EntityFrameworkCore"); } } public void ResetDatabase() { Database.EnsureCreated(); Dummies.RemoveRange(Dummies); SaveChanges(); } } }
mit
C#
35b9a7e59f7705c92161f5d62148ab33af02aec5
Remove IAcknowledgedResponse implementation from IRevertModelSnapshotResponse
elastic/elasticsearch-net,elastic/elasticsearch-net
src/Nest/XPack/MachineLearning/RevertModelSnapshot/RevertModelSnapshotResponse.cs
src/Nest/XPack/MachineLearning/RevertModelSnapshot/RevertModelSnapshotResponse.cs
using System.Runtime.Serialization; namespace Nest { public interface IRevertModelSnapshotResponse : IResponse { [DataMember(Name ="model")] ModelSnapshot Model { get; } } public class RevertModelSnapshotResponse : ResponseBase, IRevertModelSnapshotResponse { public ModelSnapshot Model { get; internal set; } } }
using System.Runtime.Serialization; namespace Nest { public interface IRevertModelSnapshotResponse : IAcknowledgedResponse { [DataMember(Name ="model")] ModelSnapshot Model { get; } } public class RevertModelSnapshotResponse : AcknowledgedResponseBase, IRevertModelSnapshotResponse { public ModelSnapshot Model { get; internal set; } } }
apache-2.0
C#
3ab7807f315292c6000d612074327a9e93afe4f3
Rename Length property
mstrother/BmpListener
BmpListener/Bmp/BmpHeader.cs
BmpListener/Bmp/BmpHeader.cs
using System; using System.Linq; using BmpListener; using BmpListener.Extensions; namespace BmpListener.Bmp { public class BmpHeader { private readonly int bmpVersion = 3; public BmpHeader(byte[] data) { Version = data.First(); if (Version != bmpVersion) { throw new NotSupportedException("version error"); } MessageLength = data.ToInt32(1); MessageType = (BmpMessage.Type)data.ElementAt(5); } public byte Version { get; } public int MessageLength { get; } public BmpMessage.Type MessageType { get; } } }
using System; using System.Linq; using BmpListener; using BmpListener.Extensions; namespace BmpListener.Bmp { public class BmpHeader { private readonly int bmpVersion = 3; public BmpHeader(byte[] data) { Version = data.First(); if (Version != bmpVersion) { throw new NotSupportedException("version error"); } Length = data.ToInt32(1); MessageType = (BmpMessage.Type)data.ElementAt(5); } public byte Version { get; } public int Length { get; } public BmpMessage.Type MessageType { get; } } }
mit
C#
17b8963cf8db3f908359905bded8907f49398503
simplify CreateSpriteText in markdown table cell
smoogipoo/osu,UselessToucan/osu,NeoAdonis/osu,smoogipooo/osu,UselessToucan/osu,NeoAdonis/osu,ppy/osu,ppy/osu,peppy/osu-new,peppy/osu,peppy/osu,smoogipoo/osu,NeoAdonis/osu,smoogipoo/osu,peppy/osu,UselessToucan/osu,ppy/osu
osu.Game/Graphics/Containers/Markdown/OsuMarkdownTableCell.cs
osu.Game/Graphics/Containers/Markdown/OsuMarkdownTableCell.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 Markdig.Extensions.Tables; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers.Markdown; using osu.Framework.Graphics.Shapes; using osu.Framework.Graphics.Sprites; using osu.Game.Overlays; namespace osu.Game.Graphics.Containers.Markdown { public class OsuMarkdownTableCell : MarkdownTableCell { private readonly bool isHeading; public OsuMarkdownTableCell(TableCell cell, TableColumnDefinition definition, bool isHeading) : base(cell, definition) { this.isHeading = isHeading; Masking = false; BorderThickness = 0; } [BackgroundDependencyLoader] private void load(OverlayColourProvider colourProvider) { var border = new Box { RelativeSizeAxes = Axes.X, }; if (isHeading) { border.Colour = colourProvider.Background3; border.Height = 2; border.Anchor = Anchor.BottomLeft; border.Origin = Anchor.BottomLeft; } else { border.Colour = colourProvider.Background4; border.Height = 1; border.Anchor = Anchor.TopLeft; border.Origin = Anchor.TopLeft; } AddInternal(border); } public override MarkdownTextFlowContainer CreateTextFlow() => new TableCellTextFlowContainer { Weight = isHeading ? FontWeight.Bold : FontWeight.Regular, Padding = new MarginPadding(10), }; private class TableCellTextFlowContainer : OsuMarkdownTextFlowContainer { public FontWeight Weight { get; set; } protected override SpriteText CreateSpriteText() => base.CreateSpriteText().With(t => t.Font = t.Font.With(weight: Weight)); } } }
// 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 Markdig.Extensions.Tables; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers.Markdown; using osu.Framework.Graphics.Shapes; using osu.Framework.Graphics.Sprites; using osu.Game.Overlays; namespace osu.Game.Graphics.Containers.Markdown { public class OsuMarkdownTableCell : MarkdownTableCell { private readonly bool isHeading; public OsuMarkdownTableCell(TableCell cell, TableColumnDefinition definition, bool isHeading) : base(cell, definition) { this.isHeading = isHeading; Masking = false; BorderThickness = 0; } [BackgroundDependencyLoader] private void load(OverlayColourProvider colourProvider) { var border = new Box { RelativeSizeAxes = Axes.X, }; if (isHeading) { border.Colour = colourProvider.Background3; border.Height = 2; border.Anchor = Anchor.BottomLeft; border.Origin = Anchor.BottomLeft; } else { border.Colour = colourProvider.Background4; border.Height = 1; border.Anchor = Anchor.TopLeft; border.Origin = Anchor.TopLeft; } AddInternal(border); } public override MarkdownTextFlowContainer CreateTextFlow() => new TableCellTextFlowContainer { Weight = isHeading ? FontWeight.Bold : FontWeight.Regular, Padding = new MarginPadding(10), }; private class TableCellTextFlowContainer : OsuMarkdownTextFlowContainer { public FontWeight Weight { get; set; } protected override SpriteText CreateSpriteText() { var spriteText = base.CreateSpriteText(); spriteText.Font = spriteText.Font.With(weight: Weight); return spriteText; } } } }
mit
C#
4768697e72847ab94da6aa6655033b29df26f075
Clean up Course Level tests to follow style cop
CodeBlueDev/CodeBlueDev.PluralSight.Core.Models
Source/CodeBlueDev.PluralSight.Core.Models.Test/CourseLevelDeserializationTests.cs
Source/CodeBlueDev.PluralSight.Core.Models.Test/CourseLevelDeserializationTests.cs
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="CourseLevelDeserializationTests.cs" company="CodeBlueDev"> // All rights reserved. // </copyright> // <summary> // Tests deserialization of PluralSight CourseLevel values. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace CodeBlueDev.PluralSight.Core.Models.Test { using System; using Newtonsoft.Json; using NUnit.Framework; /// <summary> /// Tests deserialization of PluralSight CourseLevel values. /// </summary> [TestFixture] public class CourseLevelDeserializationTests { /// <summary> /// Tests if a JSON block for a 'Beginner' Course Level can be deserialized to the appropriate CourseLevel enum value. /// </summary> [Category("Course Level")] [Test] public void BeginnerCourseLevelJsonShouldDeserializeIntoCourseLevelEnum() { // Arrange const string json = @"""Beginner"""; // Act CourseLevel courseLevel = JsonConvert.DeserializeObject<CourseLevel>(json); // Assert Assert.IsTrue(Enum.IsDefined(typeof(CourseLevel), courseLevel)); } /// <summary> /// Tests if a JSON block for an 'Intermediate' Course Level can be deserialize to the appropriate CourseLevel enum value. /// </summary> [Category("Course Level")] [Test] public void IntermediateCourseLevelJsonShouldDeserializeIntoCourseLevelEnum() { // Arrange const string json = @"""Intermediate"""; // Act CourseLevel courseLevel = JsonConvert.DeserializeObject<CourseLevel>(json); // Assert Assert.IsTrue(Enum.IsDefined(typeof(CourseLevel), courseLevel)); } /// <summary> /// Tests if a JSON block for an 'Advanced' Course Level can deserialized to the appropriate CourseLevel enum value. /// </summary> [Category("Course Level")] [Test] public void AdvancedCourseLevelJsonShouldDeserializeIntoCourseLevelEnum() { // Arrange const string json = @"""Advanced"""; // Act CourseLevel courseLevel = JsonConvert.DeserializeObject<CourseLevel>(json); // Assert Assert.IsTrue(Enum.IsDefined(typeof(CourseLevel), courseLevel)); } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="CourseLevelDeserializationTests.cs" company="CodeBlueDev"> // All rights reserved. // </copyright> // <summary> // Tests deserialization of PluralSight CourseLevel values. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace CodeBlueDev.PluralSight.Core.Models.Test { using System; using Newtonsoft.Json; using NUnit.Framework; /// <summary> /// Tests deserialization of PluralSight CourseLevel values. /// </summary> [TestFixture] public class CourseLevelDeserializationTests { /// <summary> /// Tests if a JSON block for a 'Beginner' Course Level can be deserialized to the appropriate CourseLevel enum value. /// </summary> [Test, Category("Course Level")] public void BeginnerCourseLevelJsonShouldDeserializeIntoCourseLevelEnum() { // Arrange const string Json = @"""Beginner"""; // Act CourseLevel courseLevel = JsonConvert.DeserializeObject<CourseLevel>(Json); // Assert Assert.IsTrue(Enum.IsDefined(typeof(CourseLevel), courseLevel)); } /// <summary> /// Tests if a JSON block for an 'Intermediate' Course Level can be deserialize to the appropriate CourseLevel enum value. /// </summary> [Test, Category("Course Level")] public void IntermediateCourseLevelJsonShouldDeserializeIntoCourseLevelEnum() { // Arrange const string Json = @"""Intermediate"""; // Act CourseLevel courseLevel = JsonConvert.DeserializeObject<CourseLevel>(Json); // Assert Assert.IsTrue(Enum.IsDefined(typeof(CourseLevel), courseLevel)); } /// <summary> /// Tests if a JSON block for an 'Advanced' Course Level can deserialized to the appropriate CourseLevel enum value. /// </summary> [Test, Category("Course Level")] public void AdvancedCourseLevelJsonShouldDeserializeIntoCourseLevelEnum() { // Arrange const string Json = @"""Advanced"""; // Act CourseLevel courseLevel = JsonConvert.DeserializeObject<CourseLevel>(Json); // Assert Assert.IsTrue(Enum.IsDefined(typeof(CourseLevel), courseLevel)); } } }
mit
C#
f012f13ea1846a36543a2cf81df0ca3174f08ddd
remove unused property 'OnCreate'.
jwChung/Experimentalism,jwChung/Experimentalism
test/ExperimentUnitTest/FakeTestFixture.cs
test/ExperimentUnitTest/FakeTestFixture.cs
using System; namespace Jwc.Experiment { public class FakeTestFixture : ITestFixture { private readonly string _stringValue = Guid.NewGuid().ToString(); private readonly string _intValue = Guid.NewGuid().ToString(); private readonly Func<object, object> _onCreate; public FakeTestFixture() { _onCreate = r => { var type = r as Type; if (type != null) { if (type == typeof(string)) { return _stringValue; } if (type == typeof(int)) { return _intValue; } } throw new NotSupportedException(); }; } public string StringValue { get { return _stringValue; } } public string IntValue { get { return _intValue; } } public object Create(object request) { return _onCreate(request); } } }
using System; namespace Jwc.Experiment { public class FakeTestFixture : ITestFixture { private readonly string _stringValue = Guid.NewGuid().ToString(); private readonly string _intValue = Guid.NewGuid().ToString(); private readonly Func<object, object> _onCreate; public FakeTestFixture() { _onCreate = r => { var type = r as Type; if (type != null) { if (type == typeof(string)) { return _stringValue; } if (type == typeof(int)) { return _intValue; } } throw new NotSupportedException(); }; } public Func<object, object> OnCreate { get { return _onCreate; } } public string StringValue { get { return _stringValue; } } public string IntValue { get { return _intValue; } } public object Create(object request) { return OnCreate(request); } } }
mit
C#
2e64e0b28e5c38dec426f13542b8fa9dd1ddbe3e
use backing field instead of auto property.
jwChung/Experimentalism,jwChung/Experimentalism
test/ExperimentUnitTest/FakeTestFixture.cs
test/ExperimentUnitTest/FakeTestFixture.cs
using System; namespace Jwc.Experiment { public class FakeTestFixture : ITestFixture { private Func<object, object> _onCreate = x => null; public Func<object, object> OnCreate { get { return _onCreate; } set { _onCreate = value; } } public object Create(object request) { return OnCreate(request); } } }
using System; namespace Jwc.Experiment { public class FakeTestFixture : ITestFixture { public Func<object, object> OnCreate { get; set; } public object Create(object request) { return OnCreate(request); } } }
mit
C#
98621c507f28275a1ca3f37703d6022f0b85cea7
set uwp min size to 1,1
bit-foundation/bit-framework,bit-foundation/bit-framework,bit-foundation/bit-framework,bit-foundation/bit-framework
src/CSharpClient/Bit.CSharpClient.Prism/UWP/BitApplication.cs
src/CSharpClient/Bit.CSharpClient.Prism/UWP/BitApplication.cs
#if UWP using Bit.ViewModel; using System.Linq; using System.Reflection; using Windows.Foundation; using Windows.UI.ViewManagement; using Windows.UI.Xaml; using Xamarin.Essentials; namespace Bit.UWP { public class BitApplication : Windows.UI.Xaml.Application { public BitApplication() { UnhandledException += BitApplication_UnhandledException; } private void BitApplication_UnhandledException(object sender, UnhandledExceptionEventArgs e) { e.Handled = true; BitExceptionHandler.Current.OnExceptionReceived(e.Exception); } /// <summary> /// Configures VersionTracking | RgPluginsPopup | BitCSharpClientControls (DatePicker, Checkbox, RadioButton, Frame) | Set Min Width & Height /// </summary> protected virtual void UseDefaultConfiguration() { VersionTracking.Track(); Rg.Plugins.Popup.Popup.Init(); BitCSharpClientControls.Init(); ApplicationView.GetForCurrentView().SetPreferredMinSize(new Size { Height = 1, Width = 1 }); } /// <summary> /// BitCSharpClientControls | RgPluginsPopup /// </summary> protected virtual Assembly[] GetBitRendererAssemblies() { return new[] { typeof(BitCSharpClientControls).GetTypeInfo().Assembly } .Union(Rg.Plugins.Popup.Popup.GetExtraAssemblies()) .ToArray(); } } } #endif
#if UWP using Bit.ViewModel; using System.Linq; using System.Reflection; using Windows.UI.Xaml; using Xamarin.Essentials; namespace Bit.UWP { public class BitApplication : Windows.UI.Xaml.Application { public BitApplication() { UnhandledException += BitApplication_UnhandledException; } private void BitApplication_UnhandledException(object sender, UnhandledExceptionEventArgs e) { e.Handled = true; BitExceptionHandler.Current.OnExceptionReceived(e.Exception); } /// <summary> /// Configures VersionTracking | RgPluginsPopup | BitCSharpClientControls (DatePicker, Checkbox, RadioButton, Frame) /// </summary> protected virtual void UseDefaultConfiguration() { VersionTracking.Track(); Rg.Plugins.Popup.Popup.Init(); BitCSharpClientControls.Init(); } /// <summary> /// BitCSharpClientControls | RgPluginsPopup /// </summary> protected virtual Assembly[] GetBitRendererAssemblies() { return new[] { typeof(BitCSharpClientControls).GetTypeInfo().Assembly } .Union(Rg.Plugins.Popup.Popup.GetExtraAssemblies()) .ToArray(); } } } #endif
mit
C#
5526e465b450aa7cf8dc2e4d5065dd25fef78434
Fix formatting
CyrusNajmabadi/roslyn,jasonmalinowski/roslyn,jasonmalinowski/roslyn,mavasani/roslyn,jasonmalinowski/roslyn,shyamnamboodiripad/roslyn,shyamnamboodiripad/roslyn,CyrusNajmabadi/roslyn,dotnet/roslyn,bartdesmet/roslyn,dotnet/roslyn,dotnet/roslyn,bartdesmet/roslyn,mavasani/roslyn,shyamnamboodiripad/roslyn,CyrusNajmabadi/roslyn,bartdesmet/roslyn,mavasani/roslyn
src/Features/CSharp/Portable/ConvertToRecord/CSharpConvertToRecordRefactoringProvider.cs
src/Features/CSharp/Portable/ConvertToRecord/CSharpConvertToRecordRefactoringProvider.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.Composition; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.CSharp.ConvertToRecord { [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.ConvertToRecord), Shared] internal sealed class CSharpConvertToRecordRefactoringProvider : CodeRefactoringProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpConvertToRecordRefactoringProvider() { } public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, _, cancellationToken) = context; if (!context.Options.GetOptions(document.Project.Services).EnableConvertToRecord) { return; } var typeDeclaration = await context.TryGetRelevantNodeAsync<TypeDeclarationSyntax>().ConfigureAwait(false); if (typeDeclaration == null) { return; } var action = await ConvertToRecordEngine .GetCodeActionAsync(document, typeDeclaration, cancellationToken).ConfigureAwait(false); if (action != null) { context.RegisterRefactoring(action); } } } }
// 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.Composition; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.CSharp.ConvertToRecord { [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.ConvertToRecord), Shared] internal sealed class CSharpConvertToRecordRefactoringProvider : CodeRefactoringProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpConvertToRecordRefactoringProvider() { } public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, _, cancellationToken) = context; if (!context.Options.GetOptions(document.Project.Services).EnableConvertToRecord) { return; } var typeDeclaration = await context.TryGetRelevantNodeAsync<TypeDeclarationSyntax>().ConfigureAwait(false); if (typeDeclaration == null) { return; } var action = await ConvertToRecordEngine .GetCodeActionAsync(document, typeDeclaration, cancellationToken).ConfigureAwait(false); if (action != null) { context.RegisterRefactoring(action); } } } }
mit
C#
957f483a35629f069ad13cc7d97ccaca7ee2f078
Call Dispose on TestCluster
ASP-NET-Core-Boilerplate/Templates,ASP-NET-Core-Boilerplate/Templates,RehanSaeed/ASP.NET-MVC-Boilerplate,ASP-NET-MVC-Boilerplate/Templates,RehanSaeed/ASP.NET-MVC-Boilerplate,ASP-NET-Core-Boilerplate/Templates,RehanSaeed/ASP.NET-MVC-Boilerplate,ASP-NET-MVC-Boilerplate/Templates
Source/OrleansTemplate/Tests/OrleansTemplate.Server.IntegrationTest/Fixtures/ClusterFixture.cs
Source/OrleansTemplate/Tests/OrleansTemplate.Server.IntegrationTest/Fixtures/ClusterFixture.cs
namespace OrleansTemplate.Server.IntegrationTest.Fixtures { using System; using Orleans.TestingHost; public class ClusterFixture : IDisposable { public ClusterFixture() { var builder = new TestClusterBuilder(); builder.AddClientBuilderConfigurator<TestClientBuilderConfigurator>(); builder.AddSiloBuilderConfigurator<TestSiloBuilderConfigurator>(); this.Cluster = builder.Build(); this.Cluster.Deploy(); } public TestCluster Cluster { get; } // Switch to IAsyncDisposable.DisposeAsync and call Cluster.DisposeAsync in .NET Core 3.0. public void Dispose() => this.Cluster.Dispose(); } }
namespace OrleansTemplate.Server.IntegrationTest.Fixtures { using System; using Orleans.TestingHost; public class ClusterFixture : IDisposable { public ClusterFixture() { var builder = new TestClusterBuilder(); builder.AddClientBuilderConfigurator<TestClientBuilderConfigurator>(); builder.AddSiloBuilderConfigurator<TestSiloBuilderConfigurator>(); this.Cluster = builder.Build(); this.Cluster.Deploy(); } public void Dispose() => this.Cluster.StopAllSilos(); public TestCluster Cluster { get; private set; } } }
mit
C#
5b1ef65cf97589d162917af6693aac044170e225
Normalize variables for Tile
XNAWizards/mst-boredom-remover
mst-boredom-remover/mst-boredom-remover/engine/Tile.cs
mst-boredom-remover/mst-boredom-remover/engine/Tile.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace mst_boredom_remover { class Tile { public int id; public Position position; public TileType tileType; public enum TileModifier { Blazing, Freezing, Windy }; public List<TileModifier> tileModifiers; public List<Tile> neighbors; public int temp; // TROLOLOL } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace mst_boredom_remover { class Tile { public int id; public Position position; public TileType tile_type; public enum TileModifier { Blazing, Freezing, Windy }; public List<TileModifier> tile_modifiers; public List<Tile> neighbors; public int temp; // TROLOLOL } }
mpl-2.0
C#
8e0f525588a5d0e997b5a15da50045ebbb719434
Rewrite existing test scene somewhat
ppy/osu,peppy/osu-new,peppy/osu,peppy/osu,smoogipooo/osu,smoogipoo/osu,smoogipoo/osu,smoogipoo/osu,UselessToucan/osu,ppy/osu,NeoAdonis/osu,NeoAdonis/osu,UselessToucan/osu,UselessToucan/osu,ppy/osu,NeoAdonis/osu,peppy/osu
osu.Game.Tests/Visual/Gameplay/TestSceneStarCounter.cs
osu.Game.Tests/Visual/Gameplay/TestSceneStarCounter.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 NUnit.Framework; using osu.Framework.Graphics; using osu.Framework.Utils; using osu.Game.Graphics.Sprites; using osu.Game.Graphics.UserInterface; using osuTK; namespace osu.Game.Tests.Visual.Gameplay { [TestFixture] public class TestSceneStarCounter : OsuTestScene { private readonly StarCounter starCounter; private readonly OsuSpriteText starsLabel; public TestSceneStarCounter() { starCounter = new StarCounter { Origin = Anchor.Centre, Anchor = Anchor.Centre, }; Add(starCounter); starsLabel = new OsuSpriteText { Origin = Anchor.Centre, Anchor = Anchor.Centre, Scale = new Vector2(2), Y = 50, }; Add(starsLabel); setStars(5); AddRepeatStep("random value", () => setStars(RNG.NextSingle() * (starCounter.StarCount + 1)), 10); AddStep("stop animation", () => starCounter.StopAnimation()); AddStep("reset", () => setStars(0)); } private void setStars(float stars) { starCounter.Current = stars; starsLabel.Text = starCounter.Current.ToString("0.00"); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Framework.Graphics; using osu.Framework.Graphics.Sprites; using osu.Framework.Utils; using osu.Game.Graphics.Sprites; using osu.Game.Graphics.UserInterface; using osuTK; namespace osu.Game.Tests.Visual.Gameplay { [TestFixture] public class TestSceneStarCounter : OsuTestScene { public TestSceneStarCounter() { StarCounter stars = new StarCounter { Origin = Anchor.Centre, Anchor = Anchor.Centre, Current = 5, }; Add(stars); SpriteText starsLabel = new OsuSpriteText { Origin = Anchor.Centre, Anchor = Anchor.Centre, Scale = new Vector2(2), Y = 50, Text = stars.Current.ToString("0.00"), }; Add(starsLabel); AddRepeatStep(@"random value", delegate { stars.Current = RNG.NextSingle() * (stars.StarCount + 1); starsLabel.Text = stars.Current.ToString("0.00"); }, 10); AddStep(@"Stop animation", delegate { stars.StopAnimation(); }); AddStep(@"Reset", delegate { stars.Current = 0; starsLabel.Text = stars.Current.ToString("0.00"); }); } } }
mit
C#
7656d0fb3f206ff1d6a65417b5fc71d4adb1d9f6
Fix NullReferenceException when using the NLogLogger default constructor
D3-LucaPiombino/MassTransit,jsmale/MassTransit
src/Loggers/MassTransit.NLogIntegration/Logging/NLogLogger.cs
src/Loggers/MassTransit.NLogIntegration/Logging/NLogLogger.cs
// Copyright 2007-2015 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // 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. namespace MassTransit.NLogIntegration.Logging { using System; using System.Collections.Concurrent; using MassTransit.Logging; using NLog; public class NLogLogger : MassTransit.Logging.ILogger { readonly Func<string, NLog.Logger> _logFactory; readonly ConcurrentDictionary<string, NLogLog> _logs; public NLogLogger(LogFactory factory) { _logFactory = factory.GetLogger; _logs = new ConcurrentDictionary<string, NLogLog>(); } public NLogLogger() { _logFactory = LogManager.GetLogger; _logs = new ConcurrentDictionary<string, NLogLog>(); } public ILog Get(string name) { return _logs.GetOrAdd(name, x => new NLogLog(_logFactory(x), x)); } public void Shutdown() { foreach (var log in _logs.Values) { log.Shutdown(); } } public static void Use() { MassTransit.Logging.Logger.UseLogger(new NLogLogger()); } } }
// Copyright 2007-2015 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // 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. namespace MassTransit.NLogIntegration.Logging { using System; using System.Collections.Concurrent; using MassTransit.Logging; using NLog; public class NLogLogger : MassTransit.Logging.ILogger { readonly Func<string, NLog.Logger> _logFactory; readonly ConcurrentDictionary<string, NLogLog> _logs; public NLogLogger(LogFactory factory) { _logFactory = factory.GetLogger; _logs = new ConcurrentDictionary<string, NLogLog>(); } public NLogLogger() { _logFactory = LogManager.GetLogger; } public ILog Get(string name) { return _logs.GetOrAdd(name, x => new NLogLog(_logFactory(x), x)); } public void Shutdown() { foreach (var log in _logs.Values) { log.Shutdown(); } } public static void Use() { MassTransit.Logging.Logger.UseLogger(new NLogLogger()); } } }
apache-2.0
C#
e3a37688e5079e1086b1cf628a2559c2c9e4aca1
Remove unnecessary blank line
xuweixuwei/corefx,weltkante/corefx,brett25/corefx,ViktorHofer/corefx,xuweixuwei/corefx,parjong/corefx,cartermp/corefx,KrisLee/corefx,alexandrnikitin/corefx,stone-li/corefx,Priya91/corefx-1,andyhebear/corefx,stephenmichaelf/corefx,twsouthwick/corefx,billwert/corefx,akivafr123/corefx,richlander/corefx,CherryCxldn/corefx,alphonsekurian/corefx,twsouthwick/corefx,gabrielPeart/corefx,spoiledsport/corefx,stephenmichaelf/corefx,shimingsg/corefx,scott156/corefx,DnlHarvey/corefx,jhendrixMSFT/corefx,vrassouli/corefx,vs-team/corefx,jmhardison/corefx,matthubin/corefx,bitcrazed/corefx,oceanho/corefx,Jiayili1/corefx,viniciustaveira/corefx,iamjasonp/corefx,mafiya69/corefx,Chrisboh/corefx,nchikanov/corefx,Petermarcu/corefx,chaitrakeshav/corefx,weltkante/corefx,MaggieTsang/corefx,billwert/corefx,shrutigarg/corefx,kyulee1/corefx,larsbj1988/corefx,690486439/corefx,alexperovich/corefx,wtgodbe/corefx,mmitche/corefx,kkurni/corefx,mokchhya/corefx,CherryCxldn/corefx,CloudLens/corefx,rajansingh10/corefx,josguil/corefx,chenkennt/corefx,Priya91/corefx-1,ViktorHofer/corefx,vrassouli/corefx,benjamin-bader/corefx,stone-li/corefx,nchikanov/corefx,claudelee/corefx,alexperovich/corefx,benpye/corefx,jhendrixMSFT/corefx,chenxizhang/corefx,alphonsekurian/corefx,DnlHarvey/corefx,parjong/corefx,shrutigarg/corefx,uhaciogullari/corefx,mafiya69/corefx,ptoonen/corefx,iamjasonp/corefx,Chrisboh/corefx,iamjasonp/corefx,MaggieTsang/corefx,Ermiar/corefx,zhenlan/corefx,richlander/corefx,axelheer/corefx,zmaruo/corefx,manu-silicon/corefx,the-dwyer/corefx,Chrisboh/corefx,elijah6/corefx,yizhang82/corefx,krk/corefx,stormleoxia/corefx,gabrielPeart/corefx,shmao/corefx,mazong1123/corefx,dotnet-bot/corefx,Petermarcu/corefx,the-dwyer/corefx,YoupHulsebos/corefx,Jiayili1/corefx,wtgodbe/corefx,jhendrixMSFT/corefx,bitcrazed/corefx,Ermiar/corefx,mafiya69/corefx,iamjasonp/corefx,gkhanna79/corefx,bpschoch/corefx,yizhang82/corefx,josguil/corefx,akivafr123/corefx,lggomez/corefx,rahku/corefx,cnbin/corefx,Jiayili1/corefx,benpye/corefx,stephenmichaelf/corefx,akivafr123/corefx,nbarbettini/corefx,ravimeda/corefx,alexandrnikitin/corefx,tijoytom/corefx,andyhebear/corefx,jeremymeng/corefx,Petermarcu/corefx,tijoytom/corefx,VPashkov/corefx,kkurni/corefx,seanshpark/corefx,YoupHulsebos/corefx,vs-team/corefx,nbarbettini/corefx,vidhya-bv/corefx-sorting,vidhya-bv/corefx-sorting,twsouthwick/corefx,oceanho/corefx,mazong1123/corefx,SGuyGe/corefx,mellinoe/corefx,Yanjing123/corefx,nchikanov/corefx,huanjie/corefx,manu-silicon/corefx,dotnet-bot/corefx,kkurni/corefx,Alcaro/corefx,elijah6/corefx,destinyclown/corefx,ptoonen/corefx,jcme/corefx,Yanjing123/corefx,seanshpark/corefx,MaggieTsang/corefx,mazong1123/corefx,dhoehna/corefx,misterzik/corefx,nbarbettini/corefx,690486439/corefx,richlander/corefx,akivafr123/corefx,lydonchandra/corefx,jmhardison/corefx,VPashkov/corefx,axelheer/corefx,tstringer/corefx,zhenlan/corefx,mokchhya/corefx,jlin177/corefx,uhaciogullari/corefx,fffej/corefx,alexperovich/corefx,billwert/corefx,gkhanna79/corefx,ravimeda/corefx,tijoytom/corefx,claudelee/corefx,Petermarcu/corefx,lggomez/corefx,akivafr123/corefx,larsbj1988/corefx,jeremymeng/corefx,adamralph/corefx,rjxby/corefx,dtrebbien/corefx,kyulee1/corefx,janhenke/corefx,Yanjing123/corefx,ellismg/corefx,tstringer/corefx,viniciustaveira/corefx,krytarowski/corefx,huanjie/corefx,krk/corefx,parjong/corefx,dhoehna/corefx,elijah6/corefx,chaitrakeshav/corefx,khdang/corefx,vidhya-bv/corefx-sorting,Priya91/corefx-1,wtgodbe/corefx,claudelee/corefx,jhendrixMSFT/corefx,alexandrnikitin/corefx,Ermiar/corefx,billwert/corefx,DnlHarvey/corefx,khdang/corefx,alexandrnikitin/corefx,pallavit/corefx,arronei/corefx,jeremymeng/corefx,690486439/corefx,ptoonen/corefx,josguil/corefx,wtgodbe/corefx,shimingsg/corefx,jlin177/corefx,DnlHarvey/corefx,EverlessDrop41/corefx,rjxby/corefx,rajansingh10/corefx,zhangwenquan/corefx,gkhanna79/corefx,Winsto/corefx,jlin177/corefx,MaggieTsang/corefx,rjxby/corefx,krytarowski/corefx,mazong1123/corefx,benjamin-bader/corefx,ellismg/corefx,Alcaro/corefx,marksmeltzer/corefx,mokchhya/corefx,VPashkov/corefx,dsplaisted/corefx,JosephTremoulet/corefx,pgavlin/corefx,FiveTimesTheFun/corefx,lggomez/corefx,alphonsekurian/corefx,claudelee/corefx,shahid-pk/corefx,huanjie/corefx,thiagodin/corefx,arronei/corefx,shrutigarg/corefx,ViktorHofer/corefx,kkurni/corefx,benpye/corefx,ViktorHofer/corefx,mafiya69/corefx,dkorolev/corefx,shahid-pk/corefx,krytarowski/corefx,matthubin/corefx,dotnet-bot/corefx,anjumrizwi/corefx,shiftkey-tester/corefx,kyulee1/corefx,janhenke/corefx,viniciustaveira/corefx,ravimeda/corefx,shiftkey-tester/corefx,destinyclown/corefx,Winsto/corefx,kkurni/corefx,spoiledsport/corefx,manu-silicon/corefx,thiagodin/corefx,shmao/corefx,mellinoe/corefx,Petermarcu/corefx,shahid-pk/corefx,nbarbettini/corefx,stephenmichaelf/corefx,the-dwyer/corefx,seanshpark/corefx,shiftkey-tester/corefx,fernando-rodriguez/corefx,ericstj/corefx,ViktorHofer/corefx,erpframework/corefx,cydhaselton/corefx,MaggieTsang/corefx,ericstj/corefx,zmaruo/corefx,mellinoe/corefx,JosephTremoulet/corefx,CloudLens/corefx,elijah6/corefx,fernando-rodriguez/corefx,zhenlan/corefx,alphonsekurian/corefx,BrennanConroy/corefx,destinyclown/corefx,dtrebbien/corefx,chenxizhang/corefx,benpye/corefx,xuweixuwei/corefx,stone-li/corefx,JosephTremoulet/corefx,DnlHarvey/corefx,erpframework/corefx,n1ghtmare/corefx,lggomez/corefx,adamralph/corefx,kyulee1/corefx,krk/corefx,comdiv/corefx,rahku/corefx,richlander/corefx,jlin177/corefx,rubo/corefx,cartermp/corefx,weltkante/corefx,pallavit/corefx,lggomez/corefx,Petermarcu/corefx,kkurni/corefx,PatrickMcDonald/corefx,MaggieTsang/corefx,richlander/corefx,seanshpark/corefx,alexperovich/corefx,dotnet-bot/corefx,Alcaro/corefx,andyhebear/corefx,alexperovich/corefx,zhenlan/corefx,nelsonsar/corefx,uhaciogullari/corefx,ericstj/corefx,pgavlin/corefx,jhendrixMSFT/corefx,twsouthwick/corefx,pallavit/corefx,dhoehna/corefx,stone-li/corefx,jlin177/corefx,Priya91/corefx-1,stone-li/corefx,shana/corefx,gregg-miskelly/corefx,mokchhya/corefx,marksmeltzer/corefx,BrennanConroy/corefx,mmitche/corefx,shmao/corefx,PatrickMcDonald/corefx,thiagodin/corefx,rjxby/corefx,mmitche/corefx,Priya91/corefx-1,pallavit/corefx,Ermiar/corefx,gkhanna79/corefx,shmao/corefx,dtrebbien/corefx,khdang/corefx,yizhang82/corefx,mellinoe/corefx,josguil/corefx,KrisLee/corefx,fffej/corefx,mazong1123/corefx,billwert/corefx,mokchhya/corefx,twsouthwick/corefx,nbarbettini/corefx,matthubin/corefx,benjamin-bader/corefx,erpframework/corefx,rjxby/corefx,khdang/corefx,ericstj/corefx,ericstj/corefx,the-dwyer/corefx,twsouthwick/corefx,SGuyGe/corefx,ellismg/corefx,billwert/corefx,cnbin/corefx,cydhaselton/corefx,parjong/corefx,cartermp/corefx,rahku/corefx,ravimeda/corefx,gregg-miskelly/corefx,nbarbettini/corefx,weltkante/corefx,axelheer/corefx,Priya91/corefx-1,elijah6/corefx,shimingsg/corefx,Chrisboh/corefx,fffej/corefx,comdiv/corefx,ravimeda/corefx,s0ne0me/corefx,janhenke/corefx,fffej/corefx,fgreinacher/corefx,DnlHarvey/corefx,vs-team/corefx,the-dwyer/corefx,dhoehna/corefx,chenxizhang/corefx,bitcrazed/corefx,dotnet-bot/corefx,dotnet-bot/corefx,janhenke/corefx,pgavlin/corefx,scott156/corefx,shimingsg/corefx,ptoonen/corefx,richlander/corefx,wtgodbe/corefx,dkorolev/corefx,SGuyGe/corefx,zmaruo/corefx,stormleoxia/corefx,tijoytom/corefx,seanshpark/corefx,bpschoch/corefx,lydonchandra/corefx,Ermiar/corefx,ellismg/corefx,nelsonsar/corefx,iamjasonp/corefx,Ermiar/corefx,rubo/corefx,mafiya69/corefx,benjamin-bader/corefx,vijaykota/corefx,manu-silicon/corefx,dsplaisted/corefx,dhoehna/corefx,Frank125/corefx,alphonsekurian/corefx,shrutigarg/corefx,popolan1986/corefx,n1ghtmare/corefx,ViktorHofer/corefx,krytarowski/corefx,Jiayili1/corefx,mazong1123/corefx,stephenmichaelf/corefx,bpschoch/corefx,YoupHulsebos/corefx,vidhya-bv/corefx-sorting,weltkante/corefx,alexperovich/corefx,zhangwenquan/corefx,DnlHarvey/corefx,cydhaselton/corefx,krytarowski/corefx,rahku/corefx,690486439/corefx,YoupHulsebos/corefx,ViktorHofer/corefx,jhendrixMSFT/corefx,manu-silicon/corefx,mellinoe/corefx,Frank125/corefx,heXelium/corefx,popolan1986/corefx,lggomez/corefx,rajansingh10/corefx,ptoonen/corefx,larsbj1988/corefx,tstringer/corefx,misterzik/corefx,690486439/corefx,heXelium/corefx,JosephTremoulet/corefx,chenkennt/corefx,shimingsg/corefx,dkorolev/corefx,shana/corefx,Petermarcu/corefx,scott156/corefx,parjong/corefx,dotnet-bot/corefx,josguil/corefx,manu-silicon/corefx,jeremymeng/corefx,CloudLens/corefx,shmao/corefx,gregg-miskelly/corefx,mazong1123/corefx,jlin177/corefx,lydonchandra/corefx,ericstj/corefx,gkhanna79/corefx,the-dwyer/corefx,cartermp/corefx,ravimeda/corefx,krk/corefx,Jiayili1/corefx,gregg-miskelly/corefx,lggomez/corefx,matthubin/corefx,alexperovich/corefx,rubo/corefx,Jiayili1/corefx,ellismg/corefx,zhangwenquan/corefx,scott156/corefx,jmhardison/corefx,vijaykota/corefx,gkhanna79/corefx,cydhaselton/corefx,rahku/corefx,fgreinacher/corefx,Jiayili1/corefx,vrassouli/corefx,weltkante/corefx,shahid-pk/corefx,stephenmichaelf/corefx,vs-team/corefx,arronei/corefx,tijoytom/corefx,mmitche/corefx,nbarbettini/corefx,marksmeltzer/corefx,mafiya69/corefx,wtgodbe/corefx,benpye/corefx,SGuyGe/corefx,shana/corefx,EverlessDrop41/corefx,viniciustaveira/corefx,JosephTremoulet/corefx,tijoytom/corefx,iamjasonp/corefx,alphonsekurian/corefx,CherryCxldn/corefx,KrisLee/corefx,manu-silicon/corefx,lydonchandra/corefx,benjamin-bader/corefx,benjamin-bader/corefx,KrisLee/corefx,SGuyGe/corefx,PatrickMcDonald/corefx,axelheer/corefx,YoupHulsebos/corefx,vidhya-bv/corefx-sorting,misterzik/corefx,brett25/corefx,krytarowski/corefx,oceanho/corefx,ptoonen/corefx,Chrisboh/corefx,YoupHulsebos/corefx,yizhang82/corefx,dtrebbien/corefx,FiveTimesTheFun/corefx,zhenlan/corefx,wtgodbe/corefx,vrassouli/corefx,nchikanov/corefx,pallavit/corefx,cnbin/corefx,rubo/corefx,huanjie/corefx,shahid-pk/corefx,bpschoch/corefx,khdang/corefx,comdiv/corefx,jcme/corefx,anjumrizwi/corefx,richlander/corefx,rahku/corefx,krk/corefx,krk/corefx,mmitche/corefx,zhenlan/corefx,krytarowski/corefx,EverlessDrop41/corefx,nelsonsar/corefx,krk/corefx,brett25/corefx,shmao/corefx,stormleoxia/corefx,spoiledsport/corefx,pallavit/corefx,chaitrakeshav/corefx,SGuyGe/corefx,adamralph/corefx,jhendrixMSFT/corefx,iamjasonp/corefx,comdiv/corefx,janhenke/corefx,Yanjing123/corefx,nchikanov/corefx,YoupHulsebos/corefx,bitcrazed/corefx,tstringer/corefx,cartermp/corefx,weltkante/corefx,gkhanna79/corefx,s0ne0me/corefx,yizhang82/corefx,PatrickMcDonald/corefx,rajansingh10/corefx,popolan1986/corefx,CherryCxldn/corefx,shiftkey-tester/corefx,fgreinacher/corefx,cydhaselton/corefx,marksmeltzer/corefx,brett25/corefx,cydhaselton/corefx,seanshpark/corefx,marksmeltzer/corefx,zhenlan/corefx,CloudLens/corefx,nchikanov/corefx,tstringer/corefx,n1ghtmare/corefx,yizhang82/corefx,Frank125/corefx,dhoehna/corefx,nelsonsar/corefx,twsouthwick/corefx,seanshpark/corefx,heXelium/corefx,rjxby/corefx,fernando-rodriguez/corefx,elijah6/corefx,n1ghtmare/corefx,rubo/corefx,Ermiar/corefx,uhaciogullari/corefx,shana/corefx,s0ne0me/corefx,cydhaselton/corefx,larsbj1988/corefx,oceanho/corefx,parjong/corefx,thiagodin/corefx,jcme/corefx,heXelium/corefx,MaggieTsang/corefx,shimingsg/corefx,dsplaisted/corefx,chenkennt/corefx,stone-li/corefx,dkorolev/corefx,JosephTremoulet/corefx,PatrickMcDonald/corefx,anjumrizwi/corefx,jcme/corefx,zmaruo/corefx,mmitche/corefx,josguil/corefx,gabrielPeart/corefx,vijaykota/corefx,mellinoe/corefx,s0ne0me/corefx,stephenmichaelf/corefx,stormleoxia/corefx,pgavlin/corefx,benpye/corefx,Chrisboh/corefx,axelheer/corefx,the-dwyer/corefx,ravimeda/corefx,khdang/corefx,shmao/corefx,dhoehna/corefx,billwert/corefx,jeremymeng/corefx,Alcaro/corefx,marksmeltzer/corefx,yizhang82/corefx,nchikanov/corefx,rahku/corefx,fgreinacher/corefx,axelheer/corefx,parjong/corefx,ptoonen/corefx,ellismg/corefx,Yanjing123/corefx,janhenke/corefx,elijah6/corefx,gabrielPeart/corefx,tijoytom/corefx,jcme/corefx,stone-li/corefx,rjxby/corefx,jlin177/corefx,bitcrazed/corefx,shimingsg/corefx,jcme/corefx,tstringer/corefx,alphonsekurian/corefx,shahid-pk/corefx,FiveTimesTheFun/corefx,cartermp/corefx,marksmeltzer/corefx,n1ghtmare/corefx,cnbin/corefx,jmhardison/corefx,alexandrnikitin/corefx,chaitrakeshav/corefx,andyhebear/corefx,mokchhya/corefx,anjumrizwi/corefx,Frank125/corefx,erpframework/corefx,VPashkov/corefx,zhangwenquan/corefx,mmitche/corefx,Winsto/corefx,BrennanConroy/corefx,JosephTremoulet/corefx,ericstj/corefx
src/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexTree.cs
src/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexTree.cs
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // RegexTree is just a wrapper for a node tree with some // global information attached. using System.Collections.Generic; namespace System.Text.RegularExpressions { internal sealed class RegexTree { internal RegexTree(RegexNode root, Dictionary<Int32, Int32> caps, Int32[] capnumlist, int captop, Dictionary<String, Int32> capnames, String[] capslist, RegexOptions opts) { _root = root; _caps = caps; _capnumlist = capnumlist; _capnames = capnames; _capslist = capslist; _captop = captop; _options = opts; } internal readonly RegexNode _root; internal readonly Dictionary<Int32, Int32> _caps; internal readonly Int32[] _capnumlist; internal readonly Dictionary<String, Int32> _capnames; internal readonly String[] _capslist; internal readonly RegexOptions _options; internal readonly int _captop; #if DEBUG internal void Dump() { _root.Dump(); } internal bool Debug { get { return (_options & RegexOptions.Debug) != 0; } } #endif } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // RegexTree is just a wrapper for a node tree with some // global information attached. using System.Collections.Generic; namespace System.Text.RegularExpressions { internal sealed class RegexTree { internal RegexTree(RegexNode root, Dictionary<Int32, Int32> caps, Int32[] capnumlist, int captop, Dictionary<String, Int32> capnames, String[] capslist, RegexOptions opts) { _root = root; _caps = caps; _capnumlist = capnumlist; _capnames = capnames; _capslist = capslist; _captop = captop; _options = opts; } internal readonly RegexNode _root; internal readonly Dictionary<Int32, Int32> _caps; internal readonly Int32[] _capnumlist; internal readonly Dictionary<String, Int32> _capnames; internal readonly String[] _capslist; internal readonly RegexOptions _options; internal readonly int _captop; #if DEBUG internal void Dump() { _root.Dump(); } internal bool Debug { get { return (_options & RegexOptions.Debug) != 0; } } #endif } }
mit
C#
81c559986f3cfcc582621de0991972b5975befda
Change AsNoFilter() query parameter type to IQueryable<T>
zzzprojects/EntityFramework-Plus
src/shared/Z.EF.Plus.QueryFilterInterceptor.Shared/Extensions/IDbSet.AsNoFilter.cs
src/shared/Z.EF.Plus.QueryFilterInterceptor.Shared/Extensions/IDbSet.AsNoFilter.cs
// Description: Entity Framework Bulk Operations & Utilities (EF Bulk SaveChanges, Insert, Update, Delete, Merge | LINQ Query Cache, Deferred, Filter, IncludeFilter, IncludeOptimize | Audit) // Website & Documentation: https://github.com/zzzprojects/Entity-Framework-Plus // Forum & Issues: https://github.com/zzzprojects/EntityFramework-Plus/issues // License: https://github.com/zzzprojects/EntityFramework-Plus/blob/master/LICENSE // More projects: http://www.zzzprojects.com/ // Copyright © ZZZ Projects Inc. 2014 - 2016. All rights reserved. using System.Linq; namespace Z.EntityFramework.Plus { public static partial class QueryInterceptorFilterExtensions { /// <summary>Return the orginal query before the context was filtered.</summary> /// <typeparam name="T">The type of elements of the query.</typeparam> /// <param name="query">The filtered query from which the original query should be retrieved.</param> /// <returns>The orginal query before the context was filtered.</returns> public static IQueryable<T> AsNoFilter<T>(this IQueryable<T> query) where T : class { return QueryFilterManager.HookFilter(query, QueryFilterManager.DisableAllFilter); } } }
// Description: Entity Framework Bulk Operations & Utilities (EF Bulk SaveChanges, Insert, Update, Delete, Merge | LINQ Query Cache, Deferred, Filter, IncludeFilter, IncludeOptimize | Audit) // Website & Documentation: https://github.com/zzzprojects/Entity-Framework-Plus // Forum & Issues: https://github.com/zzzprojects/EntityFramework-Plus/issues // License: https://github.com/zzzprojects/EntityFramework-Plus/blob/master/LICENSE // More projects: http://www.zzzprojects.com/ // Copyright © ZZZ Projects Inc. 2014 - 2016. All rights reserved. using System.Data.Entity; using System.Linq; namespace Z.EntityFramework.Plus { public static partial class QueryInterceptorFilterExtensions { /// <summary>Return the orginal query before the context was filtered.</summary> /// <typeparam name="T">The type of elements of the query.</typeparam> /// <param name="query">The filtered query from which the original query should be retrieved.</param> /// <returns>The orginal query before the context was filtered.</returns> public static IQueryable<T> AsNoFilter<T>(this IDbSet<T> query) where T : class { return QueryFilterManager.HookFilter(query, QueryFilterManager.DisableAllFilter); } } }
mit
C#
b42d071d6210ae70b69d93dd2ba669646f865ebe
Print answer after first run
xPaw/adventofcode-solutions,xPaw/adventofcode-solutions,xPaw/adventofcode-solutions
2021/Answers/Program.cs
2021/Answers/Program.cs
using System; using System.Diagnostics; using System.Globalization; using System.Text; using AdventOfCode2021; Console.OutputEncoding = Encoding.UTF8; CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture; var day = DateTime.Today.Day; var runs = 1; if (args.Length > 0) { if (args[0] != "today" && !int.TryParse(args[0], out day)) { Console.Error.WriteLine("Usage: [day [runs]]"); return 1; } if (args.Length > 1) { if (!int.TryParse(args[1], out runs)) { Console.Error.WriteLine("Usage: <day> [runs]"); return 1; } } } Console.Write("Day: "); Console.WriteLine(day); var data = await Solver.LoadData(day); var type = Solver.GetSolutionType(day); await Solver.SolveExample(day, type); Console.WriteLine(); double total = 0; double max = 0; double min = double.MaxValue; var stopWatch = new Stopwatch(); stopWatch.Restart(); var (part1, part2) = Solver.Solve(type, data); stopWatch.Stop(); Console.Write("Part 1: "); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine(part1); Console.ResetColor(); Console.Write("Part 2: "); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine(part2); Console.ResetColor(); for (var i = 1; i < runs; i++) { stopWatch.Restart(); (part1, part2) = Solver.Solve(type, data); stopWatch.Stop(); var elapsed = stopWatch.Elapsed.TotalMilliseconds; total += elapsed; if (min > elapsed) { min = elapsed; } if (max < elapsed) { max = elapsed; } } if (part1 == part2) { Console.WriteLine("This should never happen, just here so compiler doesn't optimize away"); } Console.WriteLine(); Console.Write("Time: "); if (runs > 1) { Console.ForegroundColor = ConsoleColor.Blue; Console.Write("{0:N6}", total / runs); Console.ResetColor(); Console.Write("ms average for "); Console.ForegroundColor = ConsoleColor.Blue; Console.Write(runs); Console.ResetColor(); Console.WriteLine(" runs"); Console.Write("Min : "); Console.ForegroundColor = ConsoleColor.Blue; Console.Write("{0:N6}", min); Console.ResetColor(); Console.WriteLine("ms"); Console.Write("Max : "); Console.ForegroundColor = ConsoleColor.Blue; Console.Write("{0:N6}", max); Console.ResetColor(); Console.WriteLine("ms"); } else { Console.ForegroundColor = ConsoleColor.Blue; Console.Write("{0:N6}", stopWatch.Elapsed.TotalMilliseconds); Console.ResetColor(); Console.WriteLine("ms"); } return 0;
using System; using System.Diagnostics; using System.Globalization; using System.Text; using AdventOfCode2021; Console.OutputEncoding = Encoding.UTF8; CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture; var day = DateTime.Today.Day; var runs = 1; if (args.Length > 0) { if (args[0] != "today" && !int.TryParse(args[0], out day)) { Console.Error.WriteLine("Usage: [day [runs]]"); return 1; } if (args.Length > 1) { if (!int.TryParse(args[1], out runs)) { Console.Error.WriteLine("Usage: <day> [runs]"); return 1; } } } Console.Write("Day: "); Console.WriteLine(day); string part1 = string.Empty; string part2 = string.Empty; var data = await Solver.LoadData(day); var type = Solver.GetSolutionType(day); await Solver.SolveExample(day, type); Console.WriteLine(); double total = 0; double max = 0; double min = double.MaxValue; var stopWatch = new Stopwatch(); for (var i = 0; i < runs; i++) { stopWatch.Restart(); (part1, part2) = Solver.Solve(type, data); stopWatch.Stop(); var elapsed = stopWatch.Elapsed.TotalMilliseconds; total += elapsed; if (min > elapsed) { min = elapsed; } if (max < elapsed) { max = elapsed; } } stopWatch.Stop(); Console.Write("Part 1: "); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine(part1); Console.ResetColor(); Console.Write("Part 2: "); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine(part2); Console.ResetColor(); Console.WriteLine(); Console.Write("Time: "); if (runs > 1) { Console.ForegroundColor = ConsoleColor.Blue; Console.Write("{0:N6}", total / runs); Console.ResetColor(); Console.Write("ms average for "); Console.ForegroundColor = ConsoleColor.Blue; Console.Write(runs); Console.ResetColor(); Console.WriteLine(" runs"); Console.Write("Min : "); Console.ForegroundColor = ConsoleColor.Blue; Console.Write("{0:N6}", min); Console.ResetColor(); Console.WriteLine("ms"); Console.Write("Max : "); Console.ForegroundColor = ConsoleColor.Blue; Console.Write("{0:N6}", max); Console.ResetColor(); Console.WriteLine("ms"); } else { Console.ForegroundColor = ConsoleColor.Blue; Console.Write("{0:N6}", stopWatch.Elapsed.TotalMilliseconds); Console.ResetColor(); Console.WriteLine("ms"); } return 0;
unlicense
C#
d3b6bf1e21355ec28cb3a01ad72a329528ad5668
fix mismatched variable name
ajepst/XlsToEf,ajepst/XlsToEf,ajepst/XlsToEf
src/XlsToEf.Example/ExampleBaseClassIdField/BuildXlsxOrderTableMatcher.cs
src/XlsToEf.Example/ExampleBaseClassIdField/BuildXlsxOrderTableMatcher.cs
using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using MediatR; using XlsToEf.Example.Domain; using XlsToEf.Import; namespace XlsToEf.Example.ExampleBaseClassIdField { public class BuildXlsxOrderTableMatcher : IAsyncRequestHandler<XlsxOrderColumnMatcherQuery, ImportColumnData> { private readonly IExcelIoWrapper _excelIoWrapper; public BuildXlsxOrderTableMatcher(IExcelIoWrapper excelIoWrapper) { _excelIoWrapper = excelIoWrapper; } public async Task<ImportColumnData> Handle(XlsxOrderColumnMatcherQuery message) { message.FilePath = Path.GetTempPath() + message.FileName; var order = new Order(); var columnData = new ImportColumnData { XlsxColumns = (await _excelIoWrapper.GetImportColumnData(message)).ToArray(), FileName = message.FileName, TableColumns = new Dictionary<string, SingleColumnData> { {PropertyNameHelper.GetPropertyName(() => order.Id), new SingleColumnData("Order ID")}, {PropertyNameHelper.GetPropertyName(() => order.OrderDate), new SingleColumnData("Order Date")}, } }; return columnData; } } }
using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using MediatR; using XlsToEf.Example.Domain; using XlsToEf.Import; namespace XlsToEf.Example.ExampleBaseClassIdField { public class BuildXlsxOrderTableMatcher : IAsyncRequestHandler<XlsxOrderColumnMatcherQuery, ImportColumnData> { private readonly IExcelIoWrapper _excelIoWrapper; public BuildXlsxOrderTableMatcher(IExcelIoWrapper excelIoWrapper) { _excelIoWrapper = excelIoWrapper; } public async Task<ImportColumnData> Handle(XlsxOrderColumnMatcherQuery message) { message.FilePath = Path.GetTempPath() + message.FileName; var unit = new Order(); var columnData = new ImportColumnData { XlsxColumns = (await _excelIoWrapper.GetImportColumnData(message)).ToArray(), FileName = message.FileName, TableColumns = new Dictionary<string, SingleColumnData> { {PropertyNameHelper.GetPropertyName(() => unit.Id), new SingleColumnData("Unit ID")}, {PropertyNameHelper.GetPropertyName(() => unit.OrderDate), new SingleColumnData("Order Date")}, } }; return columnData; } } }
mit
C#
61772452a7b6842c4cff0c5bf1bfa75733df2d38
Revert Multiple_DropDownList.cshtml, it will post a empty value that will effect the post value.
lingxyd/CMS,jtm789/CMS,jtm789/CMS,techwareone/Kooboo-CMS,lingxyd/CMS,Kooboo/CMS,andyshao/CMS,Kooboo/CMS,techwareone/Kooboo-CMS,lingxyd/CMS,Kooboo/CMS,jtm789/CMS,techwareone/Kooboo-CMS,andyshao/CMS,andyshao/CMS
Kooboo.CMS/Kooboo.CMS.Web/Views/Shared/EditorTemplates/Multiple_DropDownList.cshtml
Kooboo.CMS/Kooboo.CMS.Web/Views/Shared/EditorTemplates/Multiple_DropDownList.cshtml
@model object @{ Layout = ViewBag.Layout ?? "_TR.cshtml"; ViewData.TemplateInfo.HtmlFieldPrefix = ViewData.TemplateInfo.HtmlFieldPrefix.Replace(ViewData.ModelMetadata.PropertyName, "").Trim('.'); var propertyName = ViewData["name"] == null ? ViewData.ModelMetadata.PropertyName : ViewData["name"].ToString(); var editorHtmlAttributes = Html.GetUnobtrusiveValidationAttributes(propertyName, ViewData.ModelMetadata).Merge("multiple", "multiple").Merge(ViewData.ModelMetadata.AdditionalValues, true); var htmlAttributes = ViewBag.HtmlAttributes; if (htmlAttributes != null) { if (htmlAttributes is IDictionary<string, object>) { editorHtmlAttributes.Merge((IDictionary<string, object>)htmlAttributes); } else { editorHtmlAttributes.Merge(new RouteValueDictionary(htmlAttributes)); } } } @Html.DropDownList(propertyName, ViewData.ModelMetadata.GetDataSource() .GetSelectListItems(ViewContext.RequestContext, "").SetActiveItem(Model), editorHtmlAttributes) @Html.ValidationMessage(ViewData.ModelMetadata, new { name = ViewData["name"] }) @if (!string.IsNullOrEmpty(ViewData.ModelMetadata.Description)) { <em class="tip">@Html.Raw(ViewData.ModelMetadata.Description.Localize())</em> } <script> //当应用了select2时,默认的select标签会被隐藏 //而jquery.validate默认情况下会忽略并不验证":hidden"的元素 //jquery.unobtrusive.validation实际上只是对jquery.validate的一个包装,它会在document.ready时对表单执行验证配置, //所以,必须在document.ready之前先设置jquery.validate的忽略选项为空,让它对所有元素进行验证 if (jQuery && jQuery.validator) { jQuery.validator.defaults.ignore = ""; } jQuery(function ($) { $("#@ViewData.TemplateInfo.GetFullHtmlFieldId(propertyName)").select2(); }); </script>
@model object @{ Layout = ViewBag.Layout ?? "_TR.cshtml"; ViewData.TemplateInfo.HtmlFieldPrefix = ViewData.TemplateInfo.HtmlFieldPrefix.Replace(ViewData.ModelMetadata.PropertyName, "").Trim('.'); var propertyName = ViewData["name"] == null ? ViewData.ModelMetadata.PropertyName : ViewData["name"].ToString(); var editorHtmlAttributes = Html.GetUnobtrusiveValidationAttributes(propertyName, ViewData.ModelMetadata).Merge("multiple", "multiple").Merge(ViewData.ModelMetadata.AdditionalValues, true); var htmlAttributes = ViewBag.HtmlAttributes; if (htmlAttributes != null) { if (htmlAttributes is IDictionary<string, object>) { editorHtmlAttributes.Merge((IDictionary<string, object>)htmlAttributes); } else { editorHtmlAttributes.Merge(new RouteValueDictionary(htmlAttributes)); } } } @Html.DropDownList(propertyName, ViewData.ModelMetadata.GetDataSource() .GetSelectListItems(ViewContext.RequestContext, "").SetActiveItem(Model), editorHtmlAttributes) @Html.Hidden(propertyName) @Html.ValidationMessage(ViewData.ModelMetadata, new { name = ViewData["name"] }) @if (!string.IsNullOrEmpty(ViewData.ModelMetadata.Description)) { <em class="tip">@Html.Raw(ViewData.ModelMetadata.Description.Localize())</em> } <script> //当应用了select2时,默认的select标签会被隐藏 //而jquery.validate默认情况下会忽略并不验证":hidden"的元素 //jquery.unobtrusive.validation实际上只是对jquery.validate的一个包装,它会在document.ready时对表单执行验证配置, //所以,必须在document.ready之前先设置jquery.validate的忽略选项为空,让它对所有元素进行验证 if (jQuery && jQuery.validator) { jQuery.validator.defaults.ignore = ""; } jQuery(function ($) { $("#@ViewData.TemplateInfo.GetFullHtmlFieldId(propertyName)").select2(); }); </script>
bsd-3-clause
C#
fd41470449ec7f3dfb0564b9db430b78fe8f5a92
Update regex to find resource name & type from path (#2028)
amarzavery/AutoRest,Azure/autorest,veronicagg/autorest,veronicagg/autorest,lmazuel/autorest,dsgouda/autorest,lmazuel/autorest,sergey-shandar/autorest,amarzavery/AutoRest,vishrutshah/autorest,jianghaolu/AutoRest,dsgouda/autorest,amarzavery/AutoRest,ljhljh235/AutoRest,lmazuel/autorest,ljhljh235/AutoRest,jianghaolu/AutoRest,jhancock93/autorest,dsgouda/autorest,jianghaolu/AutoRest,brjohnstmsft/autorest,sergey-shandar/autorest,jhancock93/autorest,ljhljh235/AutoRest,amarzavery/AutoRest,sergey-shandar/autorest,jhancock93/autorest,jhendrixMSFT/autorest,veronicagg/autorest,vishrutshah/autorest,jhancock93/autorest,vishrutshah/autorest,veronicagg/autorest,ljhljh235/AutoRest,Azure/autorest,Azure/autorest,dsgouda/autorest,fearthecowboy/autorest,veronicagg/autorest,amarzavery/AutoRest,veronicagg/autorest,lmazuel/autorest,lmazuel/autorest,sergey-shandar/autorest,jianghaolu/AutoRest,vishrutshah/autorest,fearthecowboy/autorest,lmazuel/autorest,dsgouda/autorest,amarzavery/AutoRest,veronicagg/autorest,jhancock93/autorest,lmazuel/autorest,lmazuel/autorest,veronicagg/autorest,sergey-shandar/autorest,olydis/autorest,jianghaolu/AutoRest,ljhljh235/AutoRest,vishrutshah/autorest,amarzavery/AutoRest,amarzavery/AutoRest,vishrutshah/autorest,jhancock93/autorest,dsgouda/autorest,jianghaolu/AutoRest,sergey-shandar/autorest,jhendrixMSFT/autorest,olydis/autorest,jhancock93/autorest,sergey-shandar/autorest,jhendrixMSFT/autorest,ljhljh235/AutoRest,jianghaolu/AutoRest,Azure/autorest,ljhljh235/AutoRest,dsgouda/autorest,vishrutshah/autorest,amarzavery/AutoRest,vishrutshah/autorest,jianghaolu/AutoRest,brjohnstmsft/autorest,veronicagg/autorest,jhancock93/autorest,vishrutshah/autorest,sergey-shandar/autorest,jhancock93/autorest,lmazuel/autorest,jianghaolu/AutoRest,jhendrixMSFT/autorest,sergey-shandar/autorest,ljhljh235/AutoRest,dsgouda/autorest,dsgouda/autorest
src/modeler/AutoRest.Swagger/Validation/Core/JsonValidationLogListener.cs
src/modeler/AutoRest.Swagger/Validation/Core/JsonValidationLogListener.cs
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using AutoRest.Core.Logging; using AutoRest.Swagger.Validation.Core; using Newtonsoft.Json; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace AutoRest.Swagger.Logging.Core { public class JsonValidationLogListener : ILogListener { private readonly List<Dictionary<string, string>> rawMessageCollection = new List<Dictionary<string, string>>(); private static readonly Regex resPathPattern = new Regex(@"/providers/(?<providerNamespace>[^{/]+)/((?<resourceType>[^{/]+)/)?"); public void Log(LogMessage message) { var validationMessage = message as ValidationMessage; if (validationMessage != null && message.Severity > Category.Debug) { string path = validationMessage.Path.ObjectPath.Path .OfType<ObjectPathPartProperty>() .Select(p => p.Property) .SkipWhile(p => p != "paths") .Skip(1) .FirstOrDefault(); var pathComponents = resPathPattern.Match(path ?? ""); var pathComponentProviderNamespace = pathComponents.Groups["providerNamespace"]; var pathComponentResourceType = pathComponents.Groups["resourceType"]; var rawMessage = new Dictionary<string, string>(); rawMessage["type"] = validationMessage.Severity.ToString(); rawMessage["code"] = validationMessage.Rule.GetType().Name; rawMessage["message"] = validationMessage.Message; rawMessage["jsonref"] = validationMessage.Path.JsonReference; rawMessage["json-path"] = validationMessage.Path.ReadablePath; rawMessage["id"] = validationMessage.Rule.Id; rawMessage["validationCategory"] = validationMessage.Rule.ValidationCategory.ToString(); rawMessage["providerNamespace"] = pathComponentProviderNamespace.Success ? pathComponentProviderNamespace.Value : null; rawMessage["resourceType"] = pathComponentResourceType.Success ? pathComponentResourceType.Value : null; rawMessageCollection.Add(rawMessage); } } public string GetValidationMessagesAsJson() => JsonConvert.SerializeObject(rawMessageCollection, Formatting.Indented); } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using AutoRest.Core.Logging; using AutoRest.Swagger.Validation.Core; using Newtonsoft.Json; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace AutoRest.Swagger.Logging.Core { public class JsonValidationLogListener : ILogListener { private readonly List<Dictionary<string, string>> rawMessageCollection = new List<Dictionary<string, string>>(); private readonly Regex resPathPattern = new Regex(@"/providers/(?<providerNamespace>[^{/]+)/((?<resourceType>[^{/]+)/)?"); public void Log(LogMessage message) { var validationMessage = message as ValidationMessage; if (validationMessage != null && message.Severity > Category.Debug) { string path = validationMessage.Path.ObjectPath.Path .OfType<ObjectPathPartProperty>() .Select(p => p.Property) .SkipWhile(p => p != "paths") .Skip(1) .FirstOrDefault(); var pathComponents = resPathPattern.Match(path ?? ""); var pathComponentProviderNamespace = pathComponents.Groups["providerNamespace"]; var pathComponentResourceType = pathComponents.Groups["resourceType"]; var rawMessage = new Dictionary<string, string>(); rawMessage["type"] = validationMessage.Severity.ToString(); rawMessage["code"] = validationMessage.Rule.GetType().Name; rawMessage["message"] = validationMessage.Message; rawMessage["jsonref"] = validationMessage.Path.JsonReference; rawMessage["json-path"] = validationMessage.Path.ReadablePath; rawMessage["id"] = validationMessage.Rule.Id; rawMessage["validationCategory"] = validationMessage.Rule.ValidationCategory.ToString(); rawMessage["providerNamespace"] = pathComponentProviderNamespace.Success ? pathComponentProviderNamespace.Value : null; rawMessage["resourceType"] = pathComponentResourceType.Success ? pathComponentResourceType.Value : null; rawMessageCollection.Add(rawMessage); } } public string GetValidationMessagesAsJson() => JsonConvert.SerializeObject(rawMessageCollection, Formatting.Indented); } }
mit
C#
4581432a4812dd07744601b13febd3969a6d4237
Fix warning
mvdwetering/BlpFiletype
BlpFiletype/BlpFileType.cs
BlpFiletype/BlpFileType.cs
using PaintDotNet; using PaintDotNet.Data; using SereniaBLPLib; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PdnBlpFileType { public class BlpFileType : FileType { public BlpFileType() : base("BLP image file", new FileTypeOptions() { LoadExtensions = new string[] { ".blp" }, }) { } protected override Document OnLoad(Stream input) { using (var b = new BlpFile(input)) { return Document.FromImage(b.GetBitmap(0)); } } } public class BlpFileTypeFactory : IFileTypeFactory { public FileType[] GetFileTypeInstances() { return new FileType[] { new BlpFileType() }; } } }
using PaintDotNet; using PaintDotNet.Data; using SereniaBLPLib; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PdnBlpFileType { public class BlpFileType : FileType { public BlpFileType() : base("BLP image file", new FileTypeOptions() { LoadExtensions = new string[] { ".blp" }, }) { } protected override Document OnLoad(Stream input) { BlpFile b = new BlpFile(input); return Document.FromImage(b.GetBitmap(0)); } } public class BlpFileTypeFactory : IFileTypeFactory { public FileType[] GetFileTypeInstances() { return new FileType[] { new BlpFileType() }; } } }
mit
C#
f986ecb4d1770e83dcbd9e91870bd0f1121ca2de
Fix invalid example test name for dictionaries exercise
exercism/xcsharp,exercism/xcsharp
exercises/concept/dictionaries/.meta/Example.cs
exercises/concept/dictionaries/.meta/Example.cs
using System; using System.Collections.Generic; public static class DialingCodes { public static Dictionary<int, string> GetEmptyDictionary() { return new Dictionary<int, string>(); } public static Dictionary<int, string> GetExistingDictionary() { return new Dictionary<int, string> { {1, "United States of America"}, {55, "Brazil"}, {91, "India"} }; } public static Dictionary<int, string> AddCountryToEmptyDictionary(int CountryCode, string CountryName) { return new Dictionary<int, string>() { { CountryCode, CountryName } }; } public static Dictionary<int, string> AddCountryToExistingDictionary( Dictionary<int, string> existingDictionary, int countryCode, string countryName) { existingDictionary[countryCode] = countryName; return existingDictionary; } public static string GetCountryNameFromDictionary( Dictionary<int, string> existingDictionary, int countryCode) { if (existingDictionary.ContainsKey(countryCode)) { return existingDictionary[countryCode]; } else { return string.Empty; } } public static Dictionary<int, string> UpdateDictionary( Dictionary<int, string> existingDictionary, int countryCode, string countryName) { if (existingDictionary.ContainsKey(countryCode)) { existingDictionary[countryCode] = countryName; } return existingDictionary; } public static Dictionary<int, string> RemoveCountryFromDictionary( Dictionary<int, string> existingDictionary, int countryCode) { existingDictionary.Remove(countryCode); return existingDictionary; } public static bool CheckCodeExists(Dictionary<int, string> existingDictionary, int countryCode) { return existingDictionary.ContainsKey(countryCode); } public static string FindLongestCountryName(Dictionary<int, string> existingDictionary) { string longestCountryName = string.Empty; foreach (string countryName in existingDictionary.Values) { if (countryName.Length > longestCountryName.Length) { longestCountryName = countryName; } } return longestCountryName; } }
using System; using System.Collections.Generic; public static class DialingCodes_example { public static Dictionary<int, string> GetEmptyDictionary() { return new Dictionary<int, string>(); } public static Dictionary<int, string> GetExistingDictionary() { return new Dictionary<int, string> { {1, "United States of America"}, {55, "Brazil"}, {91, "India"} }; } public static Dictionary<int, string> AddCountryToEmptyDictionary(int CountryCode, string CountryName) { return new Dictionary<int, string>() { { CountryCode, CountryName } }; } public static Dictionary<int, string> AddCountryToExistingDictionary( Dictionary<int, string> existingDictionary, int countryCode, string countryName) { existingDictionary[countryCode] = countryName; return existingDictionary; } public static string GetCountryNameFromDictionary( Dictionary<int, string> existingDictionary, int countryCode) { if (existingDictionary.ContainsKey(countryCode)) { return existingDictionary[countryCode]; } else { return string.Empty; } } public static Dictionary<int, string> UpdateDictionary( Dictionary<int, string> existingDictionary, int countryCode, string countryName) { if (existingDictionary.ContainsKey(countryCode)) { existingDictionary[countryCode] = countryName; } return existingDictionary; } public static Dictionary<int, string> RemoveCountryFromDictionary( Dictionary<int, string> existingDictionary, int countryCode) { existingDictionary.Remove(countryCode); return existingDictionary; } public static bool CheckCodeExists(Dictionary<int, string> existingDictionary, int countryCode) { return existingDictionary.ContainsKey(countryCode); } public static string FindLongestCountryName(Dictionary<int, string> existingDictionary) { string longestCountryName = string.Empty; foreach (string countryName in existingDictionary.Values) { if (countryName.Length > longestCountryName.Length) { longestCountryName = countryName; } } return longestCountryName; } }
mit
C#
fe199f2b38e9d9a89333870001cdf568c56bb685
Fix get entry assembly (#182)
NServiceBusSqlPersistence/NServiceBus.SqlPersistence
src/SqlPersistence/ScriptLocation.cs
src/SqlPersistence/ScriptLocation.cs
using System; using System.IO; using System.Reflection; using NServiceBus; static class ScriptLocation { public static string FindScriptDirectory(SqlDialect dialect) { var currentDirectory = GetCurrentDirectory(); return Path.Combine(currentDirectory, "NServiceBus.Persistence.Sql", dialect.Name); } static string GetCurrentDirectory() { var entryAssembly = Assembly.GetEntryAssembly(); if (entryAssembly == null) { return AppDomain.CurrentDomain.BaseDirectory; } var codeBase = entryAssembly.CodeBase; return Directory.GetParent(new Uri(codeBase).LocalPath).FullName; } public static void ValidateScriptExists(string createScript) { if (!File.Exists(createScript)) { throw new Exception($"Expected '{createScript}' to exist. It is possible it was not deployed with the endpoint or NServiceBus.Persistence.Sql.MsBuild nuget was not included in the project."); } } }
using System; using System.IO; using System.Reflection; using NServiceBus; static class ScriptLocation { public static string FindScriptDirectory(SqlDialect dialect) { var codeBase = Assembly.GetEntryAssembly().CodeBase; var currentDirectory = Directory.GetParent(new Uri(codeBase).LocalPath).FullName; return Path.Combine(currentDirectory, "NServiceBus.Persistence.Sql", dialect.Name); } public static void ValidateScriptExists(string createScript) { if (!File.Exists(createScript)) { throw new Exception($"Expected '{createScript}' to exist. It is possible it was not deployed with the endpoint or NServiceBus.Persistence.Sql.MsBuild nuget was not included in the project."); } } }
mit
C#
acfa18bf23eacec9ff042c833dde2324375d21de
Add usage of IsShip check
iridinite/shiftdrive
Client/Asteroid.cs
Client/Asteroid.cs
/* ** Project ShiftDrive ** (C) Mika Molenkamp, 2016. */ using System; using System.IO; using Microsoft.Xna.Framework; namespace ShiftDrive { /// <summary> /// A <seealso cref="GameObject"/> representing a single asteroid. /// </summary> internal sealed class Asteroid : GameObject { private float angularVelocity; public Asteroid() { type = ObjectType.Asteroid; facing = Utils.RNG.Next(0, 360); spritename = "map/asteroid"; color = Color.White; bounding = 8f; } public override void Update(GameState world, float deltaTime) { base.Update(world, deltaTime); facing += angularVelocity * deltaTime; angularVelocity *= (float)Math.Pow(0.8f, deltaTime); // re-transmit object if it's moving around changed = changed || angularVelocity > 0.01f; } protected override void OnCollision(GameObject other, Vector2 normal, float penetration) { // spin around! angularVelocity += (1f + penetration * 4f) * (float)(Utils.RNG.NextDouble() * 2.0 - 1.0); // asteroids shouldn't move so much if ships bump into them, because // they should look heavy and sluggish this.velocity += normal * penetration; if (!other.IsShip()) { this.position += normal * penetration; } } public override bool IsTerrain() { return true; } public override void Serialize(BinaryWriter writer) { base.Serialize(writer); writer.Write(angularVelocity); } public override void Deserialize(BinaryReader reader) { base.Deserialize(reader); angularVelocity = reader.ReadSingle(); } } }
/* ** Project ShiftDrive ** (C) Mika Molenkamp, 2016. */ using System; using System.IO; using Microsoft.Xna.Framework; namespace ShiftDrive { /// <summary> /// A <seealso cref="GameObject"/> representing a single asteroid. /// </summary> internal sealed class Asteroid : GameObject { private float angularVelocity; public Asteroid() { type = ObjectType.Asteroid; facing = Utils.RNG.Next(0, 360); spritename = "map/asteroid"; color = Color.White; bounding = 8f; } public override void Update(GameState world, float deltaTime) { base.Update(world, deltaTime); facing += angularVelocity * deltaTime; angularVelocity *= (float)Math.Pow(0.8f, deltaTime); // re-transmit object if it's moving around changed = changed || angularVelocity > 0.01f; } protected override void OnCollision(GameObject other, Vector2 normal, float penetration) { // spin around! angularVelocity += (1f + penetration * 4f) * (float)(Utils.RNG.NextDouble() * 2.0 - 1.0); // asteroids shouldn't move so much if ships bump into them, because // they should look heavy and sluggish this.velocity += normal * penetration; if (other.type != ObjectType.AIShip && other.type != ObjectType.PlayerShip) { this.position += normal * penetration; } } public override bool IsTerrain() { return true; } public override void Serialize(BinaryWriter writer) { base.Serialize(writer); writer.Write(angularVelocity); } public override void Deserialize(BinaryReader reader) { base.Deserialize(reader); angularVelocity = reader.ReadSingle(); } } }
bsd-3-clause
C#
21f8bf5f5af1f9058879f34ae111eeb28fc8f8ff
Add constructor to reference
contentful/contentful.net
Contentful.Core/Models/Management/Reference.cs
Contentful.Core/Models/Management/Reference.cs
using System; using System.Collections.Generic; using System.Text; namespace Contentful.Core.Models.Management { /// <summary> /// Represents a reference link returned from the Contentful API. /// Allows you to easily model reference fields when creating new entries. /// </summary> public class Reference { /// <summary> /// Initializes a new Reference. /// </summary> public Reference() { } /// <summary> /// Initializes a new Reference. /// </summary> /// <param name="linkType">The linktype of the reference. Normally one of <see cref="SystemLinkTypes"/>.</param> /// <param name="id">The id of the item which is being referenced.</param> public Reference(string linkType, string id) { Sys = new ReferenceProperties { LinkType = linkType, Id = id }; } /// <summary> /// The properties for this reference. /// </summary> public ReferenceProperties Sys { get; set; } } /// <summary> /// Encapsulates the three properties that a <see cref="Reference"/> consists of. /// </summary> public class ReferenceProperties { /// <summary> /// The type of object, for references this is always "Link". /// </summary> public string Type => "Link"; /// <summary> /// The type of link. Normally one of <see cref="SystemLinkTypes"/>. /// </summary> public string LinkType { get; set; } /// <summary> /// The id of the item which is being referenced. /// </summary> public string Id { get; set; } } }
using System; using System.Collections.Generic; using System.Text; namespace Contentful.Core.Models.Management { /// <summary> /// Represents a reference link returned from the Contentful API. /// Allows you to easily model reference fields when creating new entries. /// </summary> public class Reference { /// <summary> /// The properties for this reference. /// </summary> public ReferenceProperties Sys { get; set; } } /// <summary> /// Encapsulates the three properties that a <see cref="Reference"/> consists of. /// </summary> public class ReferenceProperties { /// <summary> /// The type of object, for references this is always "Link". /// </summary> public string Type => "Link"; /// <summary> /// The type of link. Normally one of <see cref="SystemLinkTypes"/>. /// </summary> public string LinkType { get; set; } /// <summary> /// The if of the item which is being referenced. /// </summary> public string Id { get; set; } } }
mit
C#
f9fdf228b384046e48baa6daba396318a1ea9f24
Enable test parallelization on local.
CXuesong/WikiClientLibrary
UnitTestProject1/Assembly.cs
UnitTestProject1/Assembly.cs
using Xunit; // This is a work-around for #11. // https://github.com/CXuesong/WikiClientLibrary/issues/11 // We are using Bot Password on CI, which may naturally evade the issue. // [assembly: CollectionBehavior(DisableTestParallelization = true)]
using Xunit; // This is a work-around for #11. // https://github.com/CXuesong/WikiClientLibrary/issues/11 // We are using Bot Password on CI, which may naturally evade the issue. #if !ENV_CI_BUILD [assembly: CollectionBehavior(DisableTestParallelization = true)] #endif
apache-2.0
C#
d3750b47cde9114fdf99b0967db328f8a0f02585
Add error handling.
brianrob/coretests,brianrob/coretests
managed/machine_info/Program.cs
managed/machine_info/Program.cs
using System; using System.IO; namespace machine_info { class Program { static void Main(string[] args) { foreach(DriveInfo driveInfo in DriveInfo.GetDrives()) { try { Console.WriteLine($"Name: {driveInfo.Name}, Format: {driveInfo.DriveFormat}, Type: {driveInfo.DriveType}, Name: {driveInfo.Name}, VolumeLabel: {driveInfo.VolumeLabel}, TotalSize: {driveInfo.TotalSize}, TotalFreeSpace: {driveInfo.TotalFreeSpace}, AvailableFreeSpace {driveInfo.AvailableFreeSpace}"); } catch { Console.WriteLine($"Warning: Could not fetch details for {driveInfo.Name}."); } } } } }
using System; using System.IO; namespace machine_info { class Program { static void Main(string[] args) { foreach(DriveInfo driveInfo in DriveInfo.GetDrives()) { Console.WriteLine($"Name: {driveInfo.Name}, Format: {driveInfo.DriveFormat}, Type: {driveInfo.DriveType}, Name: {driveInfo.Name}, VolumeLabel: {driveInfo.VolumeLabel}, TotalSize: {driveInfo.TotalSize}, TotalFreeSpace: {driveInfo.TotalFreeSpace}, AvailableFreeSpace {driveInfo.AvailableFreeSpace}"); } Console.ReadKey(); } } }
mit
C#
c78de4c7a94c4a647f6b6991b744fca865188b64
Add documentation line.
dimitardanailov/TwitterBackupBackendAndAngularjs,dimitardanailov/TwitterBackupBackendAndAngularjs,dimitardanailov/TwitterBackupBackendAndAngularjs
TwitterWebApplicationRepositories/MongoDb/MongoDbRepository.cs
TwitterWebApplicationRepositories/MongoDb/MongoDbRepository.cs
using ClientConfigurations; using MongoDB.Driver; using MongoDB.Driver.Builders; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TwitterWebApplicationRepositories { /// <summary> /// This implementation used the MongoDB C# Driver, see /// http://www.mongodb.org/display/DOCS/CSharp+Driver+Tutorial /// </summary> public class MongoDbRepository<TEntity> where TEntity : class { // These three classes are supposed to be thread-safe, see // http://www.mongodb.org/display/DOCS/CSharp+Driver+Tutorial#CSharpDriverTutorial-Threadsafety protected MongoClient _client; protected MongoServer _server; protected MongoDatabase _database; protected MongoCollection<TEntity> _entities; public MongoDbRepository(string collection) { _client = new MongoClient(DatabaseSettings.MongoDBServerLocation); // Get a reference to a server object from the Mongo client _server = _client.GetServer(); _database = _server.GetDatabase(DatabaseSettings.MongoDBDatabase, WriteConcern.Unacknowledged); _entities = _database.GetCollection<TEntity>(collection); } public IEnumerable<TEntity> GetAllEntities() { return _entities.FindAll(); } public TEntity GetEntity(string id) { IMongoQuery query = Query.EQ("_id", id); return _entities.Find(query).FirstOrDefault(); } public bool RemoveEntity(string id) { IMongoQuery query = Query.EQ("_id", id); WriteConcernResult result = _entities.Remove(query); return result.DocumentsAffected == 1; } } }
using ClientConfigurations; using MongoDB.Driver; using MongoDB.Driver.Builders; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TwitterWebApplicationRepositories { /// <summary> /// This implementation used the MongoDB C# Driver, see /// http://www.mongodb.org/display/DOCS/CSharp+Driver+Tutorial /// </summary> public class MongoDbRepository<TEntity> where TEntity : class { // These three classes are supposed to be thread-safe, see // http://www.mongodb.org/display/DOCS/CSharp+Driver+Tutorial#CSharpDriverTutorial-Threadsafety protected MongoClient _client; protected MongoServer _server; protected MongoDatabase _database; protected MongoCollection<TEntity> _entities; public MongoDbRepository(string collection) { _client = new MongoClient(DatabaseSettings.MongoDBServerLocation); _server = _client.GetServer(); _database = _server.GetDatabase(DatabaseSettings.MongoDBDatabase, WriteConcern.Unacknowledged); _entities = _database.GetCollection<TEntity>(collection); } public IEnumerable<TEntity> GetAllEntities() { return _entities.FindAll(); } public TEntity GetEntity(string id) { IMongoQuery query = Query.EQ("_id", id); return _entities.Find(query).FirstOrDefault(); } public bool RemoveEntity(string id) { IMongoQuery query = Query.EQ("_id", id); WriteConcernResult result = _entities.Remove(query); return result.DocumentsAffected == 1; } } }
mit
C#
24e2c69804f88cc55b40395df6161727973cffc4
add a simple null check for json element
brnkhy/MapzenGo,brnkhy/MapzenGo
Assets/MapzenGo/Models/Factories/Factory.cs
Assets/MapzenGo/Models/Factories/Factory.cs
using System; using System.Collections.Generic; using System.Linq; using Assets.MapzenGo.Models.Plugins; using UnityEngine; namespace MapzenGo.Models.Factories { public class Factory : Plugin { public bool MergeMeshes; public float Order = 1; public virtual string XmlTag {get { return ""; } } public virtual Func<JSONObject, bool> Query { get; set; } public virtual void Start() { Query = (geo) => true; } public override void Create(Tile tile) { base.Create(tile); if (MergeMeshes) { if (!tile.Data.HasField(XmlTag)) return; var b = CreateLayer(tile.TileCenter, tile.Data[XmlTag]["features"].list); if (b) //getting a weird error without this, no idea really b.transform.SetParent(tile.transform, false); } else { if (!(tile.Data.HasField(XmlTag) && tile.Data[XmlTag].HasField("features"))) return; foreach (var entity in tile.Data[XmlTag]["features"].list.Where(x => Query(x)).SelectMany(geo => Create(tile.TileCenter, geo))) { if (entity != null) { entity.transform.SetParent(tile.transform, false); } } } } protected virtual IEnumerable<MonoBehaviour> Create(Vector2d tileMercPos, JSONObject geo) { return null; } protected virtual GameObject CreateLayer(Vector2d tileMercPos, List<JSONObject> toList) { return null; } } }
using System; using System.Collections.Generic; using System.Linq; using Assets.MapzenGo.Models.Plugins; using UnityEngine; namespace MapzenGo.Models.Factories { public class Factory : Plugin { public bool MergeMeshes; public float Order = 1; public virtual string XmlTag {get { return ""; } } public virtual Func<JSONObject, bool> Query { get; set; } public virtual void Start() { Query = (geo) => true; } public override void Create(Tile tile) { base.Create(tile); if (MergeMeshes) { if (!tile.Data.HasField(XmlTag)) return; var b = CreateLayer(tile.TileCenter, tile.Data[XmlTag]["features"].list); if (b) //getting a weird error without this, no idea really b.transform.SetParent(tile.transform, false); } else { foreach (var entity in tile.Data[XmlTag]["features"].list.Where(x => Query(x)).SelectMany(geo => Create(tile.TileCenter, geo))) { if (entity != null) { entity.transform.SetParent(tile.transform, false); } } } } protected virtual IEnumerable<MonoBehaviour> Create(Vector2d tileMercPos, JSONObject geo) { return null; } protected virtual GameObject CreateLayer(Vector2d tileMercPos, List<JSONObject> toList) { return null; } } }
mit
C#
564a24951d05a611dd435be26ed2b8a2126094b0
Remove expiration date of DesignScript
DynamoDS/designscript-archive,samuto/designscript,DynamoDS/designscript-archive,DynamoDS/designscript-archive,DynamoDS/designscript-archive,samuto/designscript,DynamoDS/designscript-archive,samuto/designscript,samuto/designscript,samuto/designscript,samuto/designscript
Core/ProtoCore/Utils/Validity.cs
Core/ProtoCore/Utils/Validity.cs
using System; namespace ProtoCore.Utils { public class Validity { public static void Assert(bool cond) { if (!cond) throw new Exceptions.CompilerInternalException(""); } public static void Assert(bool cond, string message) { if (!cond) throw new Exceptions.CompilerInternalException(message); } private static DateTime? mAppStartupTime = null; public static void AssertExpiry() { //Expires on 30th September 2013 /* DateTime expires = new DateTime(2013, 9, 30); if(!mAppStartupTime.HasValue) mAppStartupTime = DateTime.Now; if (mAppStartupTime.Value >= expires) throw new ProductExpiredException("DesignScript Technology Preview has expired. Visit http://labs.autodesk.com for more information.", expires); */ } } public class ProductExpiredException : Exception { public ProductExpiredException(string message, DateTime expirydate) : base(message) { ExpiryDate = expirydate; } public DateTime ExpiryDate { get; private set; } } }
using System; namespace ProtoCore.Utils { public class Validity { public static void Assert(bool cond) { if (!cond) throw new Exceptions.CompilerInternalException(""); } public static void Assert(bool cond, string message) { if (!cond) throw new Exceptions.CompilerInternalException(message); } private static DateTime? mAppStartupTime = null; public static void AssertExpiry() { //Expires on 30th September 2013 DateTime expires = new DateTime(2013, 9, 30); if(!mAppStartupTime.HasValue) mAppStartupTime = DateTime.Now; if (mAppStartupTime.Value >= expires) throw new ProductExpiredException("DesignScript Technology Preview has expired. Visit http://labs.autodesk.com for more information.", expires); } } public class ProductExpiredException : Exception { public ProductExpiredException(string message, DateTime expirydate) : base(message) { ExpiryDate = expirydate; } public DateTime ExpiryDate { get; private set; } } }
apache-2.0
C#
f7b98393a9efc955813eca4f81940949e261d3ee
Add HttpCode convenience property to exception
rackerlabs/RackspaceCloudOfficeApiClient
Rackspace.CloudOffice/ApiException.cs
Rackspace.CloudOffice/ApiException.cs
using System; using System.Dynamic; using System.IO; using System.Net; using Newtonsoft.Json; namespace Rackspace.CloudOffice { public class ApiException : Exception { public dynamic Response { get; private set; } public HttpStatusCode? HttpCode { get; private set; } public ApiException(WebException ex) : base(GetErrorMessage(ex), ex) { Response = ParseResponse(ex.Response); var webResponse = ex.Response as HttpWebResponse; if (webResponse != null) HttpCode = webResponse.StatusCode; } static object ParseResponse(WebResponse response) { if (response == null) return null; using (var stream = response.GetResponseStream()) using (var reader = new StreamReader(stream)) { var raw = reader.ReadToEnd(); try { return JsonConvert.DeserializeObject<ExpandoObject>(raw); } catch { return raw; } } } static string GetErrorMessage(WebException ex) { var r = ex.Response as HttpWebResponse; return r == null ? ex.Message : $"{r.StatusCode:d} - {r.Headers["x-error-message"]}"; } } }
using System; using System.Dynamic; using System.IO; using System.Net; using Newtonsoft.Json; namespace Rackspace.CloudOffice { public class ApiException : Exception { public dynamic Response { get; private set; } public ApiException(WebException ex) : base(GetErrorMessage(ex), ex) { Response = ParseResponse(ex.Response); } static object ParseResponse(WebResponse response) { if (response == null) return null; using (var stream = response.GetResponseStream()) using (var reader = new StreamReader(stream)) { var raw = reader.ReadToEnd(); try { return JsonConvert.DeserializeObject<ExpandoObject>(raw); } catch { return raw; } } } static string GetErrorMessage(WebException ex) { var r = ex.Response as HttpWebResponse; return r == null ? ex.Message : $"{r.StatusCode:d} - {r.Headers["x-error-message"]}"; } } }
mit
C#
b639a71f8e954bb39cec5ebd529205210c03687a
use options in all calls of serializer and set dateformat to ISO8601 (a better default IMO)
YoloDev/elephanet,jmkelly/elephanet,jmkelly/elephanet,YoloDev/elephanet
Elephanet/Serialization/JilJsonConverter.cs
Elephanet/Serialization/JilJsonConverter.cs
using Jil; namespace Elephanet.Serialization { public class JilJsonConverter : IJsonConverter { private readonly Options _options; public JilJsonConverter() { _options = new Options(includeInherited: true, dateFormat:DateTimeFormat.ISO8601); } public string Serialize<T>(T entity) { return JSON.Serialize<T>(entity,_options); } public T Deserialize<T>(string json) { return JSON.Deserialize<T>(json,_options); } public object Deserialize(string json) { return JSON.DeserializeDynamic(json, _options); } public object Deserialize(string json, System.Type type) { return JSON.Deserialize(json, type,_options); } } }
using Jil; namespace Elephanet.Serialization { public class JilJsonConverter : IJsonConverter { private readonly Options _options; public JilJsonConverter() { _options = new Options(includeInherited: true); } public string Serialize<T>(T entity) { return JSON.Serialize<T>(entity,_options); } public T Deserialize<T>(string json) { return JSON.Deserialize<T>(json); } public object Deserialize(string json) { return JSON.DeserializeDynamic(json); } public object Deserialize(string json, System.Type type) { return JSON.Deserialize(json, type); } } }
mit
C#
7f940693521c299c46812a16909418c2238a9587
Modify the MeidoHook interface to allow communicating to the plugins they need to stop. That way they can release whatever resources they're holding or stop threads/timers to have running seperate from the main thread. This will make it possible to have MeidoBot stop the entire program from top-down.
IvionSauce/MeidoBot
MeidoCommon/MeidoCommon.cs
MeidoCommon/MeidoCommon.cs
using System; using System.Collections.Generic; namespace MeidoCommon { public interface IMeidoHook { // Things the plugin provides us with. string Name { get; } string Version { get; } Dictionary<string, string> Help { get; } // Things we provide to the plugin. string Prefix { set; } // Method to signal to the plugins they need to stop whatever seperate threads they have running. // As well as to save/deserialize whatever it needs to. void Stop(); } public interface IIrcMessage { string Message { get; } string[] MessageArray { get; } string Channel { get; } string Nick { get; } string Ident { get; } string Host { get; } } public interface IMeidoComm { string ConfDir { get; } } public interface IIrcComm { void AddChannelMessageHandler(Action<IIrcMessage> handler); void AddQueryMessageHandler(Action<IIrcMessage> handler); void SendMessage(string target, string message); void DoAction(string target, string action); void SendNotice(string target, string message); string[] GetChannels(); bool IsMe(string nick); } }
using System; using System.Collections.Generic; namespace MeidoCommon { public interface IMeidoHook { string Name { get; } string Version { get; } Dictionary<string, string> Help { get; } string Prefix { set; } } public interface IIrcMessage { string Message { get; } string[] MessageArray { get; } string Channel { get; } string Nick { get; } string Ident { get; } string Host { get; } } public interface IMeidoComm { string ConfDir { get; } } public interface IIrcComm { void AddChannelMessageHandler(Action<IIrcMessage> handler); void AddQueryMessageHandler(Action<IIrcMessage> handler); void SendMessage(string target, string message); void DoAction(string target, string action); void SendNotice(string target, string message); string[] GetChannels(); bool IsMe(string nick); } }
bsd-2-clause
C#
18aeef8e6fae5897dcff5b3ad43d3afdb0e81485
Make method virtual so clients can decorate behavior.
themotleyfool/AspNet.WebApi.HtmlMicrodataFormatter
source/AspNet.WebApi.HtmlMicrodataFormatter/DocumentationController.cs
source/AspNet.WebApi.HtmlMicrodataFormatter/DocumentationController.cs
using System; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; namespace AspNet.WebApi.HtmlMicrodataFormatter { public class DocumentationController : ApiController { public IDocumentationProviderEx DocumentationProvider { get; set; } protected override void Initialize(HttpControllerContext controllerContext) { base.Initialize(controllerContext); if (DocumentationProvider != null) return; DocumentationProvider = Configuration.Services.GetService(typeof (IDocumentationProvider)) as IDocumentationProviderEx; if (DocumentationProvider == null) { var msg = string.Format("{0} can only be used when {1} is registered as {2} service provider.", typeof(DocumentationController), typeof(WebApiHtmlDocumentationProvider), typeof(IDocumentationProvider)); throw new InvalidOperationException(msg); } } public virtual SimpleApiDocumentation GetDocumentation() { var apiExplorer = Configuration.Services.GetApiExplorer(); var documentation = new SimpleApiDocumentation(); foreach (var api in apiExplorer.ApiDescriptions) { var controllerDescriptor = api.ActionDescriptor.ControllerDescriptor; documentation.Add(controllerDescriptor.ControllerName, api.Simplify(Configuration)); documentation[controllerDescriptor.ControllerName].Documentation = DocumentationProvider.GetDocumentation(controllerDescriptor.ControllerType); } return documentation; } } }
using System; using System.Linq; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; namespace AspNet.WebApi.HtmlMicrodataFormatter { public class DocumentationController : ApiController { public IDocumentationProviderEx DocumentationProvider { get; set; } protected override void Initialize(HttpControllerContext controllerContext) { base.Initialize(controllerContext); if (DocumentationProvider != null) return; DocumentationProvider = Configuration.Services.GetService(typeof (IDocumentationProvider)) as IDocumentationProviderEx; if (DocumentationProvider == null) { var msg = string.Format("{0} can only be used when {1} is registered as {2} service provider.", typeof(DocumentationController), typeof(WebApiHtmlDocumentationProvider), typeof(IDocumentationProvider)); throw new InvalidOperationException(msg); } } public SimpleApiDocumentation GetDocumentation() { var apiExplorer = Configuration.Services.GetApiExplorer(); var documentation = new SimpleApiDocumentation(); foreach (var api in apiExplorer.ApiDescriptions) { var controllerDescriptor = api.ActionDescriptor.ControllerDescriptor; documentation.Add(controllerDescriptor.ControllerName, api.Simplify(Configuration)); documentation[controllerDescriptor.ControllerName].Documentation = DocumentationProvider.GetDocumentation(controllerDescriptor.ControllerType); } return documentation; } } }
apache-2.0
C#
9691f78cbf0d1e4fa9abaf3213592ec59302c0bd
Test directory creation access by creating a directory (not a file)
arkivverket/arkade5,arkivverket/arkade5,arkivverket/arkade5
src/Arkivverket.Arkade.GUI/Util/ArkadeProcessingAreaLocationSetting.cs
src/Arkivverket.Arkade.GUI/Util/ArkadeProcessingAreaLocationSetting.cs
using System.IO; using Arkivverket.Arkade.Core.Base; using Arkivverket.Arkade.GUI.Properties; namespace Arkivverket.Arkade.GUI.Util { public static class ArkadeProcessingAreaLocationSetting { public static string Get() { Settings.Default.Reload(); return Settings.Default.ArkadeProcessingAreaLocation; } public static void Set(string locationSetting) { Settings.Default.ArkadeProcessingAreaLocation = locationSetting; Settings.Default.Save(); } public static bool IsValid() { try { string definedLocation = Get(); return DirectoryIsWritable(definedLocation); } catch { return false; // Invalid path string in settings } } public static bool IsApplied() { string appliedLocation = ArkadeProcessingArea.Location?.FullName ?? string.Empty; string definedLocation = Get(); return appliedLocation.Equals(definedLocation); } private static bool DirectoryIsWritable(string directory) { if (string.IsNullOrWhiteSpace(directory)) return false; string tmpDirectory = Path.Combine(directory, "arkade-writeaccess-test"); try { Directory.CreateDirectory(tmpDirectory); return true; } catch { return false; } finally { if (Directory.Exists(tmpDirectory)) Directory.Delete(tmpDirectory); } } } }
using System.IO; using Arkivverket.Arkade.Core.Base; using Arkivverket.Arkade.GUI.Properties; namespace Arkivverket.Arkade.GUI.Util { public static class ArkadeProcessingAreaLocationSetting { public static string Get() { Settings.Default.Reload(); return Settings.Default.ArkadeProcessingAreaLocation; } public static void Set(string locationSetting) { Settings.Default.ArkadeProcessingAreaLocation = locationSetting; Settings.Default.Save(); } public static bool IsValid() { try { string definedLocation = Get(); return DirectoryIsWritable(definedLocation); } catch { return false; // Invalid path string in settings } } public static bool IsApplied() { string appliedLocation = ArkadeProcessingArea.Location?.FullName ?? string.Empty; string definedLocation = Get(); return appliedLocation.Equals(definedLocation); } private static bool DirectoryIsWritable(string directory) { if (string.IsNullOrWhiteSpace(directory)) return false; string tmpFile = Path.Combine(directory, Path.GetRandomFileName()); try { using (File.Create(tmpFile, 1, FileOptions.DeleteOnClose)) { // Attempt to write temporary file to the directory } return true; } catch { return false; } } } }
agpl-3.0
C#
9fb7b8febd2b8bf5fd2f2a1f3cfe2acfd09a08ca
Update ModuleAModule.cs
HansKrJensrud/Prism-Samples-Wpf
HelloWorld/Modules/ModuleA/ModuleAModule.cs
HelloWorld/Modules/ModuleA/ModuleAModule.cs
using ModuleA.Views; using Prism.Modularity; using Prism.Regions; namespace ModuleA { public class ModuleAModule : IModule { IRegionManager _regionManager; public ModuleAModule(IRegionManager regionManager) { _regionManager = regionManager; } public void Initialize() { _regionManager.RegisterViewWithRegion("TopRegion", typeof(ViewA)); } } }
using ModuleA.Views; using Prism.Modularity; using Prism.Regions; namespace ModuleA { public class ModuleAModule : IModule { IRegionManager _regionManager; public ModuleAModule(IRegionManager regionManager) { _regionManager = regionManager; } public void Initialize() { _regionManager.RegisterViewWithRegion("MainRegion", typeof(ViewA)); } } }
mit
C#
56d867d48ea75d11beaa735a8f8d6e40e935277f
Add OS-differing paths
Mako88/dxx-tracker
RebirthTracker/RebirthTracker/Configuration.cs
RebirthTracker/RebirthTracker/Configuration.cs
using System.Runtime.InteropServices; namespace RebirthTracker { /// <summary> /// Class to keep track of OS-specific configuration settings /// </summary> public static class Configuration { /// <summary> /// Get the folder where files should be stored /// </summary> public static string GetDataDir() { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { return "..\\..\\..\\..\\..\\"; } return "../../../../../../"; } } }
namespace RebirthTracker { /// <summary> /// Class to keep track of OS-specific configuration settings /// </summary> public static class Configuration { /// <summary> /// Get the folder where files should be stored /// </summary> public static string GetDataDir() { return "..{Path.DirectorySeparatorChar}..{Path.DirectorySeparatorChar}..{Path.DirectorySeparatorChar}..{Path.DirectorySeparatorChar}..{Path.DirectorySeparatorChar}"; } } }
mit
C#
078f6bb112800048f596abea3dc1d6e7f9c82f19
Add new GetSchemaOverload to mock
Laoujin/SolrNet,Laoujin/SolrNet,18098924759/SolrNet,erandr/SolrNet,doss78/SolrNet,mausch/SolrNet,tombeany/SolrNet,vladen/SolrNet,vmanral/SolrNet,tombeany/SolrNet,drakeh/SolrNet,chang892886597/SolrNet,vladen/SolrNet,chang892886597/SolrNet,erandr/SolrNet,erandr/SolrNet,chang892886597/SolrNet,18098924759/SolrNet,SolrNet/SolrNet,vmanral/SolrNet,erandr/SolrNet,yonglehou/SolrNet,drakeh/SolrNet,vyzvam/SolrNet,vladen/SolrNet,vyzvam/SolrNet,drakeh/SolrNet,18098924759/SolrNet,mausch/SolrNet,vladen/SolrNet,mausch/SolrNet,MetSystem/SolrNet,MetSystem/SolrNet,yonglehou/SolrNet,Laoujin/SolrNet,doss78/SolrNet,tombeany/SolrNet,MetSystem/SolrNet,vmanral/SolrNet,SolrNet/SolrNet,vyzvam/SolrNet,doss78/SolrNet,yonglehou/SolrNet
SampleSolrApp.Tests/MSolrReadOnlyOperations.cs
SampleSolrApp.Tests/MSolrReadOnlyOperations.cs
using System; using System.Collections.Generic; using Moroco; using SolrNet; using SolrNet.Commands.Parameters; using SolrNet.Impl; using SolrNet.Schema; namespace SampleSolrApp.Tests { public class MSolrReadOnlyOperations<T> : ISolrReadOnlyOperations<T> { public MFunc<ISolrQuery, QueryOptions, SolrQueryResults<T>> query; public SolrQueryResults<T> Query(ISolrQuery q, QueryOptions options) { return query.Invoke(q, options); } public SolrMoreLikeThisHandlerResults<T> MoreLikeThis(SolrMLTQuery query, MoreLikeThisHandlerQueryOptions options) { throw new NotImplementedException(); } public ResponseHeader Ping() { throw new NotImplementedException(); } public SolrSchema GetSchema(string filename) { throw new NotImplementedException(); } public SolrSchema GetSchema() { throw new NotImplementedException(); } public SolrDIHStatus GetDIHStatus(KeyValuePair<string, string> options) { throw new NotImplementedException(); } public SolrQueryResults<T> Query(string q) { throw new NotImplementedException(); } public SolrQueryResults<T> Query(string q, ICollection<SortOrder> orders) { throw new NotImplementedException(); } public SolrQueryResults<T> Query(string q, QueryOptions options) { throw new NotImplementedException(); } public SolrQueryResults<T> Query(ISolrQuery q) { throw new NotImplementedException(); } public SolrQueryResults<T> Query(ISolrQuery query, ICollection<SortOrder> orders) { throw new NotImplementedException(); } public ICollection<KeyValuePair<string, int>> FacetFieldQuery(SolrFacetFieldQuery facets) { throw new NotImplementedException(); } } }
using System; using System.Collections.Generic; using Moroco; using SolrNet; using SolrNet.Commands.Parameters; using SolrNet.Impl; using SolrNet.Schema; namespace SampleSolrApp.Tests { public class MSolrReadOnlyOperations<T> : ISolrReadOnlyOperations<T> { public MFunc<ISolrQuery, QueryOptions, SolrQueryResults<T>> query; public SolrQueryResults<T> Query(ISolrQuery q, QueryOptions options) { return query.Invoke(q, options); } public SolrMoreLikeThisHandlerResults<T> MoreLikeThis(SolrMLTQuery query, MoreLikeThisHandlerQueryOptions options) { throw new NotImplementedException(); } public ResponseHeader Ping() { throw new NotImplementedException(); } public SolrSchema GetSchema() { throw new NotImplementedException(); } public SolrDIHStatus GetDIHStatus(KeyValuePair<string, string> options) { throw new NotImplementedException(); } public SolrQueryResults<T> Query(string q) { throw new NotImplementedException(); } public SolrQueryResults<T> Query(string q, ICollection<SortOrder> orders) { throw new NotImplementedException(); } public SolrQueryResults<T> Query(string q, QueryOptions options) { throw new NotImplementedException(); } public SolrQueryResults<T> Query(ISolrQuery q) { throw new NotImplementedException(); } public SolrQueryResults<T> Query(ISolrQuery query, ICollection<SortOrder> orders) { throw new NotImplementedException(); } public ICollection<KeyValuePair<string, int>> FacetFieldQuery(SolrFacetFieldQuery facets) { throw new NotImplementedException(); } } }
apache-2.0
C#
7ec4b3f289f32e444ea9d89caa59a2361528f6d2
Use FindObject, not Instance property!
Tarocco/roaring-fangs-unity
Source/RoaringFangs/Utility/SingletonHelper.cs
Source/RoaringFangs/Utility/SingletonHelper.cs
/* The MIT License (MIT) Copyright (c) 2016 Roaring Fangs Entertainment 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 UnityEngine; using System.Collections; using System.Linq; namespace RoaringFangs.Utility { public class SingletonHelper : MonoBehaviour { [SerializeField] private GameObject _Prefab; private GameObject _Instance; [SerializeField] private bool _DontDestroy = true; public bool DontDestroy { get { return _DontDestroy; } set { _DontDestroy = value; } } [SerializeField] void Awake() { SingletonHelper[] helpers = FindObjectsOfType<SingletonHelper>(); if (helpers.All(s => s == this || s.name != name)) { _Instance = (GameObject)GameObject.Instantiate(_Prefab); if(_DontDestroy) DontDestroyOnLoad(_Instance); } } } }
/* The MIT License (MIT) Copyright (c) 2016 Roaring Fangs Entertainment 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 UnityEngine; using System.Collections; using System.Linq; namespace RoaringFangs.Utility { public class SingletonHelper : MonoBehaviour { [SerializeField] private GameObject _Prefab; [SerializeField] private GameObject _Instance; public GameObject Instance { get { return _Instance; } private set { _Instance = value; } } [SerializeField] private bool _DontDestroy = true; public bool DontDestroy { get { return _DontDestroy; } set { _DontDestroy = value; } } [SerializeField] void Awake() { SingletonHelper[] helpers = FindObjectsOfType<SingletonHelper>(); if (helpers.All(s => s == this || s.name != name)) { Instance = (GameObject)GameObject.Instantiate(_Prefab); if(_DontDestroy) DontDestroyOnLoad(Instance); } } } }
mit
C#
184b3059ce7f104458b6514bdde38058bbdce1df
Check for parent controller on same object too, not just parents
PearMed/Pear-Interaction-Engine
Assets/Pear.InteractionEngine/Scripts/Controllers/Editor/ControllerBehaviorEditor.cs
Assets/Pear.InteractionEngine/Scripts/Controllers/Editor/ControllerBehaviorEditor.cs
using Pear.InteractionEngine.Utils; using System; using UnityEditor; using UnityEngine; namespace Pear.InteractionEngine.Controllers { [CustomEditor(typeof(ControllerBehaviorBase), true)] [CanEditMultipleObjects] public class ControllerBehaviorEditor : Editor { // The controller property SerializedProperty _controller; void OnEnable() { _controller = serializedObject.FindProperty("_controller"); } /// <summary> /// Attempt to set the controller if it is not set /// </summary> public override void OnInspectorGUI() { serializedObject.Update(); // If a reference to the controller is not set // try to find it on the game object if (_controller.objectReferenceValue == null) { // Get the type of controller by examing the templated argument // pased to the controller behavior Type typeOfController = ReflectionHelpers.GetGenericArgumentTypes(target.GetType(), typeof(IControllerBehavior<>))[0]; // Check to see if this component has a controller on the same gameobject or one of its parents. Transform objTpCheck = ((Component)target).transform; while(_controller.objectReferenceValue == null && objTpCheck != null) { _controller.objectReferenceValue = objTpCheck.GetComponent(typeOfController); if (_controller.objectReferenceValue == null) objTpCheck = objTpCheck.parent; } } serializedObject.ApplyModifiedProperties(); DrawDefaultInspector(); } } }
using Pear.InteractionEngine.Utils; using System; using UnityEditor; using UnityEngine; namespace Pear.InteractionEngine.Controllers { [CustomEditor(typeof(ControllerBehaviorBase), true)] [CanEditMultipleObjects] public class ControllerBehaviorEditor : Editor { // The controller property SerializedProperty _controller; void OnEnable() { _controller = serializedObject.FindProperty("_controller"); } /// <summary> /// Attempt to set the controller if it is not set /// </summary> public override void OnInspectorGUI() { serializedObject.Update(); // If a reference to the controller is not set // try to find it on the game object if (_controller.objectReferenceValue == null) { // Get the type of controller by examing the templated argument // pased to the controller behavior Type typeOfController = ReflectionHelpers.GetGenericArgumentTypes(target.GetType(), typeof(IControllerBehavior<>))[0]; // Check to see if this component has a parent controller. Transform parent = ((Component)target).transform.parent; while(_controller.objectReferenceValue == null && parent != null) { _controller.objectReferenceValue = parent.GetComponent(typeOfController); if (_controller.objectReferenceValue == null) parent = parent.parent; } } serializedObject.ApplyModifiedProperties(); DrawDefaultInspector(); } } }
mit
C#
4ecefc64709c4b2966bd9817e556cd7052a16e9f
Add fade-in feature to FadingMusic
plrusek/NitoriWare,Barleytree/NitoriWare,NitorInc/NitoriWare,Barleytree/NitoriWare,NitorInc/NitoriWare
Assets/Scripts/Audio/FadingMusic.cs
Assets/Scripts/Audio/FadingMusic.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class FadingMusic : MonoBehaviour { #pragma warning disable 0649 [SerializeField] private bool fadeInFirst; [SerializeField] private float fadeSpeed; #pragma warning restore 0649 private AudioSource _audioSource; private bool started; void Awake() { started = false; _audioSource = GetComponent<AudioSource>(); } void Update() { if (started) updateFade(); } void updateFade() { float diff = fadeSpeed * Time.deltaTime; if (fadeInFirst) { if (_audioSource.volume >= diff) { _audioSource.volume = 1f; fadeInFirst = started = false; } else _audioSource.volume += diff; } else { if (_audioSource.volume <= diff) { _audioSource.volume = 0f; _audioSource.Stop(); } else _audioSource.volume -= diff; } } public void startFade() { if (started && fadeInFirst) fadeInFirst = false; started = true; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class FadingMusic : MonoBehaviour { #pragma warning disable 0649 [SerializeField] private float fadeSpeed; #pragma warning restore 0649 private AudioSource _audioSource; private bool started; void Awake() { started = false; _audioSource = GetComponent<AudioSource>(); } void Update() { if (started) updateFade(); } void updateFade() { float diff = fadeSpeed * Time.deltaTime; if (_audioSource.volume <= diff) { _audioSource.volume = 0f; _audioSource.Stop(); } else _audioSource.volume -= diff; } public void startFade() { started = true; } }
mit
C#
7fd82d5b4e3e91715be39a66cc2c578a435d02d3
Mark fields explicitly private
Perspektyva/EconomySim
World/Range.cs
World/Range.cs
namespace World { public struct IntRange { private int lowerInclusive; private int upperInclusive; private IntRange(int lowerInclusive, int upperInclusive) { this.lowerInclusive = lowerInclusive; this.upperInclusive = upperInclusive; } public static IntRange Inclusive(int lower, int upper) => new IntRange(lower, upper); public bool Contains(int value) => value >= this.lowerInclusive && value <= this.upperInclusive; } }
namespace World { public struct IntRange { int lowerInclusive; int upperInclusive; private IntRange(int lowerInclusive, int upperInclusive) { this.lowerInclusive = lowerInclusive; this.upperInclusive = upperInclusive; } public static IntRange Inclusive(int lower, int upper) => new IntRange(lower, upper); public bool Contains(int value) => value >= this.lowerInclusive && value <= this.upperInclusive; } }
mit
C#
327c8f5ca6a954fbb271a4f05362e084f56350f3
Bump version
transistor1/SQLFormatterPlugin
Properties/AssemblyInfo.cs
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("SQLFormatterPlugin")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SQLFormatterPlugin")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("22247641-9910-4c24-9a9d-dd295a749d41")] // 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.10001.0")] [assembly: AssemblyFileVersion("1.0.10001.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("SQLFormatterPlugin")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SQLFormatterPlugin")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("22247641-9910-4c24-9a9d-dd295a749d41")] // 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.10000.0")] [assembly: AssemblyFileVersion("1.0.10000.0")]
bsd-3-clause
C#
e36c91f13be59b369ccee465425f3c523fc11f5c
Test available only where the drive support multi-queries
nhibernate/nhibernate-core,ManufacturingIntelligence/nhibernate-core,hazzik/nhibernate-core,alobakov/nhibernate-core,lnu/nhibernate-core,ManufacturingIntelligence/nhibernate-core,fredericDelaporte/nhibernate-core,livioc/nhibernate-core,hazzik/nhibernate-core,nkreipke/nhibernate-core,ngbrown/nhibernate-core,gliljas/nhibernate-core,alobakov/nhibernate-core,ngbrown/nhibernate-core,fredericDelaporte/nhibernate-core,gliljas/nhibernate-core,gliljas/nhibernate-core,nhibernate/nhibernate-core,livioc/nhibernate-core,RogerKratz/nhibernate-core,lnu/nhibernate-core,RogerKratz/nhibernate-core,livioc/nhibernate-core,nkreipke/nhibernate-core,lnu/nhibernate-core,hazzik/nhibernate-core,ManufacturingIntelligence/nhibernate-core,ngbrown/nhibernate-core,hazzik/nhibernate-core,gliljas/nhibernate-core,fredericDelaporte/nhibernate-core,alobakov/nhibernate-core,RogerKratz/nhibernate-core,nkreipke/nhibernate-core,RogerKratz/nhibernate-core,fredericDelaporte/nhibernate-core,nhibernate/nhibernate-core,nhibernate/nhibernate-core
src/NHibernate.Test/NHSpecificTest/NH1508/Fixture.cs
src/NHibernate.Test/NHSpecificTest/NH1508/Fixture.cs
using System; using NHibernate.Driver; using NUnit.Framework; namespace NHibernate.Test.NHSpecificTest.NH1508 { [TestFixture] public class Fixture : BugTestCase { [TestFixtureSetUp] public void CheckMultiQuerySupport() { TestFixtureSetUp(); IDriver driver = sessions.ConnectionProvider.Driver; if (!driver.SupportsMultipleQueries) { Assert.Ignore("Driver {0} does not support multi-queries", driver.GetType().FullName); } } protected override void OnSetUp() { Person john = new Person(); john.Name = "John"; Document doc1 = new Document(); doc1.Person = john; doc1.Title = "John's Doc"; Document doc2 = new Document(); doc2.Title = "Spec"; using (ISession session = OpenSession()) using (ITransaction tx = session.BeginTransaction()) { session.Save(john); session.Save(doc1); session.Save(doc2); tx.Commit(); } } protected override void OnTearDown() { using (ISession session = OpenSession()) using (ITransaction tx = session.BeginTransaction()) { session.Delete("from Person"); session.Delete("from Document"); tx.Commit(); } } [Test] public void DoesntThrowExceptionWhenHqlQueryIsGiven() { using (ISession session = OpenSession()) using (ITransaction tx = session.BeginTransaction()) { IQuery sqlQuery = session.CreateQuery("from Document"); IMultiQuery q = session .CreateMultiQuery() .Add(sqlQuery); q.List(); } } [Test] [ExpectedException(typeof(NotSupportedException))] public void ThrowsExceptionWhenSqlQueryIsGiven() { using (ISession session = OpenSession()) using (ITransaction tx = session.BeginTransaction()) { ISQLQuery sqlQuery = session.CreateSQLQuery("select * from Document"); IMultiQuery q = session .CreateMultiQuery() .Add(sqlQuery); q.List(); } } [Test] [ExpectedException(typeof(NotSupportedException))] public void ThrowsExceptionWhenNamedSqlQueryIsGiven() { using (ISession session = OpenSession()) using (ITransaction tx = session.BeginTransaction()) { IMultiQuery q = session .CreateMultiQuery() .AddNamedQuery("SampleSqlQuery"); q.List(); } } } }
using System; using System.Collections; using System.Collections.Generic; using NHibernate.Criterion; using NUnit.Framework; namespace NHibernate.Test.NHSpecificTest.NH1508 { [TestFixture] public class Fixture : BugTestCase { protected override void OnSetUp() { Person john = new Person(); john.Name = "John"; Document doc1 = new Document(); doc1.Person = john; doc1.Title = "John's Doc"; Document doc2 = new Document(); doc2.Title = "Spec"; using (ISession session = OpenSession()) using (ITransaction tx = session.BeginTransaction()) { session.Save(john); session.Save(doc1); session.Save(doc2); tx.Commit(); } } protected override void OnTearDown() { using (ISession session = OpenSession()) using (ITransaction tx = session.BeginTransaction()) { session.Delete("from Person"); session.Delete("from Document"); tx.Commit(); } } [Test] public void DoesntThrowExceptionWhenHqlQueryIsGiven() { using (ISession session = OpenSession()) using (ITransaction tx = session.BeginTransaction()) { IQuery sqlQuery = session.CreateQuery("from Document"); IMultiQuery q = session .CreateMultiQuery() .Add(sqlQuery); q.List(); } } [Test] [ExpectedException(typeof(NotSupportedException))] public void ThrowsExceptionWhenSqlQueryIsGiven() { using (ISession session = OpenSession()) using (ITransaction tx = session.BeginTransaction()) { ISQLQuery sqlQuery = session.CreateSQLQuery("select * from Document"); IMultiQuery q = session .CreateMultiQuery() .Add(sqlQuery); q.List(); } } [Test] [ExpectedException(typeof(NotSupportedException))] public void ThrowsExceptionWhenNamedSqlQueryIsGiven() { using (ISession session = OpenSession()) using (ITransaction tx = session.BeginTransaction()) { IMultiQuery q = session .CreateMultiQuery() .AddNamedQuery("SampleSqlQuery"); q.List(); } } } }
lgpl-2.1
C#
1fb3a9f794a9792789c2d2bd4a06fc590713f1f6
Update pruebaLINQ.cs
Beelzenef/GestionMenu
LINQ/pruebaLINQ.cs
LINQ/pruebaLINQ.cs
using System; using System.Linq; namespace ConLINQ { class pruebaLINQ { // Usando WHERE string _LastName = "Prescott"; IQueryable<Employee> emps = from e in Employees where e.LastName == _LastName select e; // Usando una Clase para capturar los datos private class FullName { public string Forename { get; set; } public string Surname { get; set; } } private void FilteringDataByColumn() { IQueryable<FullName> names = from e in Employees select new FullName { Forename = e.FirstName, Surname = e.LastName }; } // Accediendo a los datos recogidos foreach (var emp in emps) Console.WriteLine("{0} {1}", emp.FirstName, emp.LastName); // Agrupando var emps = from e in Employees group e by e.JobTitle into eGroup select new { Job = eGroup.Key, CountOfEmployees = eGroup.Count() }; // Notacion de punto para acceder a los miembros de los datos recogidos var emps = from e in Employees select new { FirstName = e.FirstName, LastName = e.LastName, Job = e.JobTitle1.Job }; } }
using System; using System.Linq; namespace ConLINQ { class pruebaLINQ { // Usando WHERE string _LastName = "Prescott"; IQueryable<Employee> emps = from e in Employees where e.LastName == _LastName select e; // Usando una Clase para capturar los datos private class FullName { public string Forename { get; set; } public string Surname { get; set; } } private void FilteringDataByColumn() { IQueryable<FullName> names = from e in Employees select new FullName { Forename = e.FirstName, Surname = e.LastName }; } // Accediendo a los datos recogidos foreach (var emp in emps) { Console.WriteLine("{0} {1}", emp.FirstName, emp.LastName); } // Agrupando var emps = from e in Employees group e by e.JobTitle into eGroup select new { Job = eGroup.Key, CountOfEmployees = eGroup.Count() }; Navegando por los datos // Notacion de punto para acceder a los miembros de los datos recogidos var emps = from e in Employees select new { FirstName = e.FirstName, LastName = e.LastName, Job = e.JobTitle1.Job }; }
mit
C#
1e7d4d88f2c3d4e6dacb5c58ad7fed721d506654
Fix netfx test failure
ericstj/corefx,mmitche/corefx,mmitche/corefx,ericstj/corefx,ptoonen/corefx,shimingsg/corefx,mmitche/corefx,wtgodbe/corefx,wtgodbe/corefx,ViktorHofer/corefx,Jiayili1/corefx,Jiayili1/corefx,ericstj/corefx,BrennanConroy/corefx,ericstj/corefx,Jiayili1/corefx,shimingsg/corefx,ViktorHofer/corefx,wtgodbe/corefx,ericstj/corefx,BrennanConroy/corefx,ptoonen/corefx,mmitche/corefx,ViktorHofer/corefx,ericstj/corefx,BrennanConroy/corefx,wtgodbe/corefx,ViktorHofer/corefx,Jiayili1/corefx,mmitche/corefx,Jiayili1/corefx,shimingsg/corefx,shimingsg/corefx,ptoonen/corefx,shimingsg/corefx,wtgodbe/corefx,mmitche/corefx,Jiayili1/corefx,ptoonen/corefx,Jiayili1/corefx,ViktorHofer/corefx,ViktorHofer/corefx,shimingsg/corefx,ptoonen/corefx,ptoonen/corefx,ericstj/corefx,shimingsg/corefx,wtgodbe/corefx,ptoonen/corefx,mmitche/corefx,wtgodbe/corefx,ViktorHofer/corefx
src/System.Runtime.InteropServices/tests/System/Runtime/InteropServices/Marshal/PrelinkTests.cs
src/System.Runtime.InteropServices/tests/System/Runtime/InteropServices/Marshal/PrelinkTests.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.Collections.Generic; using System.Globalization; using System.Reflection; using Xunit; namespace System.Runtime.InteropServices.Tests { public class PrelinkTests { [Fact] public void Prelink_ValidMethod_Success() { MethodInfo method = typeof(PrelinkTests).GetMethod(nameof(Prelink_ValidMethod_Success)); Marshal.Prelink(method); Marshal.Prelink(method); } [Fact] public void Prelink_RuntimeSuppliedMethod_Success() { MethodInfo method = typeof(Math).GetMethod(nameof(Math.Abs), new Type[] { typeof(double) }); Marshal.Prelink(method); Marshal.Prelink(method); } [Fact] public void Prelink_NullMethod_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("m", () => Marshal.Prelink(null)); } [Fact] public void Prelink_NonRuntimeMethod_ThrowsArgumentException() { AssertExtensions.Throws<ArgumentException>("m", null, () => Marshal.Prelink(new NonRuntimeMethodInfo())); } public class NonRuntimeMethodInfo : MethodInfo { public override ICustomAttributeProvider ReturnTypeCustomAttributes => throw new NotImplementedException(); public override RuntimeMethodHandle MethodHandle => throw new NotImplementedException(); public override MethodAttributes Attributes => throw new NotImplementedException(); public override string Name => throw new NotImplementedException(); public override Type DeclaringType => throw new NotImplementedException(); public override Type ReflectedType => throw new NotImplementedException(); public override MethodInfo GetBaseDefinition() => throw new NotImplementedException(); public override object[] GetCustomAttributes(bool inherit) => throw new NotImplementedException(); public override object[] GetCustomAttributes(Type attributeType, bool inherit) => throw new NotImplementedException(); public override MethodImplAttributes GetMethodImplementationFlags() => throw new NotImplementedException(); public override ParameterInfo[] GetParameters() => throw new NotImplementedException(); public override object Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture) => throw new NotImplementedException(); public override bool IsDefined(Type attributeType, bool inherit) => throw new NotImplementedException(); } } }
// 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.Collections.Generic; using System.Globalization; using System.Reflection; using Xunit; namespace System.Runtime.InteropServices.Tests { public class PrelinkTests { [Fact] public void Prelink_ValidMethod_Success() { MethodInfo method = typeof(PrelinkTests).GetMethod(nameof(Prelink_ValidMethod_Success)); Marshal.Prelink(method); Marshal.Prelink(method); } [Fact] public void Prelink_RuntimeSuppliedMethod_Success() { MethodInfo method = typeof(Math).GetMethod(nameof(Math.Abs), new Type[] { typeof(double) }); Marshal.Prelink(method); Marshal.Prelink(method); } [Fact] public void Prelink_NullMethod_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("m", () => Marshal.Prelink(null)); } [Fact] public void Prelink_NonRuntimeMethod_ThrowsArgumentException() { AssertExtensions.Throws<ArgumentException>("m", () => Marshal.Prelink(new NonRuntimeMethodInfo())); } public class NonRuntimeMethodInfo : MethodInfo { public override ICustomAttributeProvider ReturnTypeCustomAttributes => throw new NotImplementedException(); public override RuntimeMethodHandle MethodHandle => throw new NotImplementedException(); public override MethodAttributes Attributes => throw new NotImplementedException(); public override string Name => throw new NotImplementedException(); public override Type DeclaringType => throw new NotImplementedException(); public override Type ReflectedType => throw new NotImplementedException(); public override MethodInfo GetBaseDefinition() => throw new NotImplementedException(); public override object[] GetCustomAttributes(bool inherit) => throw new NotImplementedException(); public override object[] GetCustomAttributes(Type attributeType, bool inherit) => throw new NotImplementedException(); public override MethodImplAttributes GetMethodImplementationFlags() => throw new NotImplementedException(); public override ParameterInfo[] GetParameters() => throw new NotImplementedException(); public override object Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture) => throw new NotImplementedException(); public override bool IsDefined(Type attributeType, bool inherit) => throw new NotImplementedException(); } } }
mit
C#
5054fe4af9d79ce0c274302924147368a52cf69a
Add Format methods.
joshyy/LogPile
LogPile/LogPile.cs
LogPile/LogPile.cs
/* * This is free and unencumbered software released into the public domain. * * Anyone is free to copy, modify, publish, use, compile, sell, or * distribute this software, either in source code form or as a compiled * binary, for any purpose, commercial or non-commercial, and by any * means. * * In jurisdictions that recognize copyright laws, the author or authors * of this software dedicate any and all copyright interest in the * software to the public domain. We make this dedication for the benefit * of the public at large and to the detriment of our heirs and * successors. We intend this dedication to be an overt act of * relinquishment in perpetuity of all present and future rights to this * software under copyright law. * * 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 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. * * For more information, please refer to <http://unlicense.org> */ using System; using System.IO; using System.Reflection; public class LogPile { //defaults - use config file to customize static string dateFormatFileNm = "yyyy-MM-dd"; //easily control file name rollover by using H, m or s in dateFormatFileNm. Default is daily. static string dateFormatLog = "yyyy-MM-dd HH:mm:ss:fff"; static string dir = Environment.CurrentDirectory; static string fileNm = System.Diagnostics.Process.GetCurrentProcess().ProcessName; static string fileExt = ".logpile"; internal static void WriteLine(string level, string message) { DateTime date = DateTime.Now; string logFile = Path.Combine(dir, fileNm + "_" + date.ToString(dateFormatFileNm) + fileExt); string className = "ClassNameHere"; // todo: using (StreamWriter w = new StreamWriter(logFile, true)) { w.WriteLine(string.Format("{0}|{1}|{2}|{3}", date.ToString(dateFormatLog), level, className, message)); } } public static void Info(string message) { WriteLine("INFO", message); } public static void InfoFormat(string message, params object[] args) { WriteLine("INFO", string.Format(message, args)); } public static void Debug(string message) { WriteLine("DEBUG", message); } public static void DebugFormat(string message, params object[] args) { WriteLine("DEBUG", string.Format(message, args)); } public static void Warn(string message) { WriteLine("WARN", message); } public static void WarnFormat(string message, params object[] args) { WriteLine("WARN", string.Format(message, args)); } public static void Fatal(string message) { WriteLine("FATAL", message); } public static void FatalFormat(string message, params object[] args) { WriteLine("FATAL", string.Format(message, args)); } public static void Error(string message) { WriteLine("ERROR", message); } public static void ErrorFormat(string message, params object[] args) { WriteLine("ERROR", string.Format(message, args)); } public static void Custom(string level, string message) { WriteLine(level, message); } public static void CustomFormat(string level, string message, params object[] args) { WriteLine(level, string.Format(message, args)); } }
/* * This is free and unencumbered software released into the public domain. * * Anyone is free to copy, modify, publish, use, compile, sell, or * distribute this software, either in source code form or as a compiled * binary, for any purpose, commercial or non-commercial, and by any * means. * * In jurisdictions that recognize copyright laws, the author or authors * of this software dedicate any and all copyright interest in the * software to the public domain. We make this dedication for the benefit * of the public at large and to the detriment of our heirs and * successors. We intend this dedication to be an overt act of * relinquishment in perpetuity of all present and future rights to this * software under copyright law. * * 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 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. * * For more information, please refer to <http://unlicense.org> */ using System; using System.IO; using System.Reflection; public class LogPile { //defaults - use config file to customize static string dateFormatFileNm = "yyyy-MM-dd"; //easily control file name rollover by using H, m or s in dateFormatFileNm. Default is daily. static string dateFormatLog = "yyyy-MM-dd HH:mm:ss:fff"; static string dir = Environment.CurrentDirectory; static string fileNm = System.Diagnostics.Process.GetCurrentProcess().ProcessName; static string fileExt = ".logpile"; internal static void WriteLine(string level, string message) { DateTime date = DateTime.Now; string logFile = Path.Combine(dir, fileNm + "_" + date.ToString(dateFormatFileNm) + fileExt); string className = "ClassNameHere"; // todo: using (StreamWriter w = new StreamWriter(logFile, true)) { w.WriteLine(string.Format("{0}|{1}|{2}|{3}", date.ToString(dateFormatLog), level, className, message)); } } public static void Info(string message) { WriteLine("INFO", message); } public static void Debug(string message) { WriteLine("DEBUG", message); } public static void Warn(string message) { WriteLine("WARN", message); } public static void Fatal(string message) { WriteLine("FATAL", message); } public static void Error(string message) { WriteLine("ERROR", message); } public static void Custom(string level, string message) { WriteLine(level, message); } }
unlicense
C#
64bb0d486c4f076e45aeffd66f8de83aa4700253
Enable move sequence override
NitorInc/NitoriWare,Barleytree/NitoriWare,Barleytree/NitoriWare,NitorInc/NitoriWare
Assets/Resources/Microgames/DollDance/Scripts/Sequence/DollDanceSequence.cs
Assets/Resources/Microgames/DollDance/Scripts/Sequence/DollDanceSequence.cs
using System; using System.Collections.Generic; using System.Linq; using UnityEngine; [Serializable] public class DollDanceSequence : MonoBehaviour { public enum Move { Idle, Up, Down, Left, Right } [Header("Debug fields")] [SerializeField] bool enableOverrideMoves; [SerializeField] Move[] overrideMoves; [Header("Number of sequential dance moves")] [SerializeField] int moveCount; List<Move> validMoves; Stack<Move> sequence; void Awake() { this.sequence = new Stack<Move>(); this.validMoves = Enum.GetValues(typeof(Move)).Cast<Move>().ToList(); this.validMoves.Remove(Move.Idle); if (enableOverrideMoves) this.moveCount = overrideMoves.Length; ResetSlots(this.moveCount); } void ResetSlots(int moveCount) { // Clear slots this.moveCount = moveCount; sequence.Clear(); // Fill all of the sequence slots randomly System.Random random = new System.Random(); Move previousMove = Move.Idle; for (int i = 0; i < this.moveCount; i++) { List<Move> available = new List<Move>(this.validMoves); available.Remove(previousMove); Move newMove; if (enableOverrideMoves) newMove = overrideMoves[this.moveCount - 1 - i]; else newMove = available[random.Next(available.Count)]; sequence.Push(newMove); previousMove = newMove; } } public List<Move> CopySequence() { return new List<Move>(this.sequence); } public Move Process(Move move) { if (move == sequence.Peek()) return sequence.Pop(); else return Move.Idle; } public bool IsComplete() { return sequence.Count == 0; } }
using System; using System.Collections.Generic; using System.Linq; using UnityEngine; [Serializable] public class DollDanceSequence : MonoBehaviour { public enum Move { Idle, Up, Down, Left, Right } [Header("Debug fields")] [SerializeField] bool pointAllDirections; [Header("Number of sequential dance moves")] [SerializeField] int moveCount; List<Move> validMoves; Stack<Move> sequence; void Awake() { this.sequence = new Stack<Move>(); this.validMoves = Enum.GetValues(typeof(Move)).Cast<Move>().ToList(); this.validMoves.Remove(Move.Idle); if (pointAllDirections) moveCount = 4; ResetSlots(this.moveCount); } void ResetSlots(int moveCount) { // Clear slots this.moveCount = moveCount; sequence.Clear(); // Fill all of the sequence slots randomly System.Random random = new System.Random(); Move previousMove = Move.Idle; for (int i = 0; i < this.moveCount; i++) { List<Move> available = new List<Move>(this.validMoves); available.Remove(previousMove); Move newMove; if (pointAllDirections) newMove = validMoves[i]; else newMove = available[random.Next(available.Count)]; sequence.Push(newMove); previousMove = newMove; } } public List<Move> CopySequence() { return new List<Move>(this.sequence); } public Move Process(Move move) { if (move == sequence.Peek()) return sequence.Pop(); else return Move.Idle; } public bool IsComplete() { return sequence.Count == 0; } }
mit
C#
4d526237d012bbfea42fe9e4e9d75db92d8dabc9
Split ClassWithLengthConstrainedConstructorArgument test class
sergeyshushlyapin/AutoFixture,AutoFixture/AutoFixture,sean-gilliam/AutoFixture,zvirja/AutoFixture,adamchester/AutoFixture,sergeyshushlyapin/AutoFixture,Pvlerick/AutoFixture,adamchester/AutoFixture
Src/AutoFixtureUnitTest/DataAnnotations/StringLengthArgumentSupportTests.cs
Src/AutoFixtureUnitTest/DataAnnotations/StringLengthArgumentSupportTests.cs
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using Ploeh.AutoFixture; using Xunit; namespace Ploeh.AutoFixtureUnitTest.DataAnnotations { public class StringLengthArgumentSupportTests { [Fact] public void FixtureCorrectlyCreatesShortText() { // Fixture setup var fixture = new Fixture(); // Exercise system var actual = fixture.Create<ClassWithShortStringLengthConstrainedConstructorArgument>(); // Verify outcome Assert.True( actual.ShortText.Length <= ClassWithShortStringLengthConstrainedConstructorArgument.ShortTextMaximumLength, "AutoFixture should respect [StringLength] attribute on constructor arguments."); // Teardown } [Fact] public void FixtureCorrectlyCreatesLongText() { // Fixture setup var fixture = new Fixture(); // Exercise system var actual = fixture.Create<ClassWithLongStringLengthConstrainedConstructorArgument>(); // Verify outcome Assert.Equal( ClassWithLongStringLengthConstrainedConstructorArgument.LongTextLength, actual.LongText.Length); // Teardown } private class ClassWithShortStringLengthConstrainedConstructorArgument { public const int ShortTextMaximumLength = 3; public readonly string ShortText; public ClassWithShortStringLengthConstrainedConstructorArgument( [StringLength(ShortTextMaximumLength)]string shortText) { this.ShortText = shortText; } } private class ClassWithLongStringLengthConstrainedConstructorArgument { public const int LongTextLength = 50; public readonly string LongText; public ClassWithLongStringLengthConstrainedConstructorArgument( [StringLength(LongTextLength, MinimumLength = LongTextLength)]string longText) { this.LongText = longText; } } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using Ploeh.AutoFixture; using Xunit; namespace Ploeh.AutoFixtureUnitTest.DataAnnotations { public class StringLengthArgumentSupportTests { [Fact] public void FixtureCorrectlyCreatesShortText() { // Fixture setup var fixture = new Fixture(); // Exercise system var actual = fixture.Create<ClassWithLengthConstrainedConstructorArgument>(); // Verify outcome Assert.True( actual.ShortText.Length <= ClassWithLengthConstrainedConstructorArgument.ShortTextMaximumLength, "AutoFixture should respect [StringLength] attribute on constructor arguments."); // Teardown } [Fact] public void FixtureCorrectlyCreatesLongText() { // Fixture setup var fixture = new Fixture(); // Exercise system var actual = fixture.Create<ClassWithLengthConstrainedConstructorArgument>(); // Verify outcome Assert.Equal( ClassWithLengthConstrainedConstructorArgument.LongTextLength, actual.LongText.Length); // Teardown } private class ClassWithLengthConstrainedConstructorArgument { public const int ShortTextMaximumLength = 3; public const int LongTextLength = 50; public readonly string ShortText; public readonly string LongText; public ClassWithLengthConstrainedConstructorArgument( [StringLength(ShortTextMaximumLength)]string shortText, [StringLength(LongTextLength, MinimumLength = LongTextLength)]string longText) { this.ShortText = shortText; this.LongText = longText; } } } }
mit
C#
baca60021daee1dfe21629269bda4594b4f16175
Revise base parameter naming to resolve Roslyn indicator
larsbrubaker/MatterControl,unlimitedbacon/MatterControl,unlimitedbacon/MatterControl,larsbrubaker/MatterControl,jlewin/MatterControl,unlimitedbacon/MatterControl,mmoening/MatterControl,jlewin/MatterControl,mmoening/MatterControl,jlewin/MatterControl,mmoening/MatterControl,larsbrubaker/MatterControl,jlewin/MatterControl,unlimitedbacon/MatterControl,larsbrubaker/MatterControl
PartPreviewWindow/View3D/IObject3DEditor.cs
PartPreviewWindow/View3D/IObject3DEditor.cs
/* Copyright (c) 2016, Lars Brubaker, John Lewin All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. */ //#define DoBooleanTest using MatterHackers.Agg.UI; using MatterHackers.DataConverters3D; using System; using System.Collections.Generic; namespace MatterHackers.MatterControl.PartPreviewWindow { public interface IObject3DEditor { bool Unlocked { get; } string Name { get; } IEnumerable<Type> SupportedTypes(); GuiWidget Create(IObject3D item, View3DWidget view3DWidget, ThemeConfig theme); } }
/* Copyright (c) 2016, Lars Brubaker, John Lewin All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. */ //#define DoBooleanTest using MatterHackers.Agg.UI; using MatterHackers.DataConverters3D; using System; using System.Collections.Generic; namespace MatterHackers.MatterControl.PartPreviewWindow { public interface IObject3DEditor { bool Unlocked { get; } string Name { get; } IEnumerable<Type> SupportedTypes(); GuiWidget Create(IObject3D item, View3DWidget parentView3D, ThemeConfig theme); } }
bsd-2-clause
C#
b483785319ac22cdcb81aa9abe7ee21b2bc88371
Add cancellationToken
CatPhat/Fabrik.SimpleBus
src/Fabrik.SimpleBus.Demo/Program.cs
src/Fabrik.SimpleBus.Demo/Program.cs
using System; using System.Threading; using System.Threading.Tasks; namespace Fabrik.SimpleBus.Demo { class Program { static void Main(string[] args) { new Program().Run(); } private void Run() { var bus = new InProcessBus(); // Delegate Handler bus.Subscribe<string>(message => Console.WriteLine("Delegate Handler Received: {0}", message)); bus.Subscribe<string>(async (message, token) => await WriteMessageAsync(message, token)); // Strongly typed handler bus.Subscribe<Message>(() => new MessageHandler()); // Strongly typed async handler bus.Subscribe<Message>(() => new AsyncMessageHandler()); // will automatically be passed a cancellation token Console.WriteLine("Enter a message\n"); string input; while ((input = Console.ReadLine()) != "q") { var t2 = bus.SendAsync(input); var t1 = bus.SendAsync(new Message { Body = input }); Task.WaitAll(t1, t2); Console.WriteLine("\nEnter another message\n"); } } private Task WriteMessageAsync(string message, CancellationToken cancellationToken) { return Task.Delay(2000).ContinueWith(task => Console.WriteLine("Delegate Async Handler Received: {0}", message), cancellationToken); } } public class Message { public string Body { get; set; } } public class MessageHandler : IHandle<Message> { public void Handle(Message message) { Console.WriteLine("{0} Received message type: {1}", this.GetType().Name, typeof(Message).Name); } } public class AsyncMessageHandler : IHandleAsync<Message> { public async Task HandleAsync(Message message, CancellationToken cancellationToken) { await Task.Delay(1000); Console.WriteLine("{0} Received message type: {1}", this.GetType().Name, typeof(Message).Name); } } }
using System; using System.Threading; using System.Threading.Tasks; namespace Fabrik.SimpleBus.Demo { class Program { static void Main(string[] args) { new Program().Run(); } private void Run() { var bus = new InProcessBus(); // Delegate Handler bus.Subscribe<string>(message => Console.WriteLine("Delegate Handler Received: {0}", message)); bus.Subscribe<string>(async (message, token) => await WriteMessageAsync(message, token)); // Strongly typed handler bus.Subscribe<Message>(() => new MessageHandler()); // Strongly typed async handler bus.Subscribe<Message>(() => new AsyncMessageHandler()); // will automatically be passed a cancellation token Console.WriteLine("Enter a message\n"); string input; while ((input = Console.ReadLine()) != "q") { var t2 = bus.SendAsync(input); var t1 = bus.SendAsync(new Message { Body = input }); Task.WaitAll(t1, t2); Console.WriteLine("\nEnter another message\n"); } } private Task WriteMessageAsync(string message, CancellationToken cancellationToken) { return Task.Delay(2000).ContinueWith(task => Console.WriteLine("Delegate Async Handler Received: {0}", message)); } } public class Message { public string Body { get; set; } } public class MessageHandler : IHandle<Message> { public void Handle(Message message) { Console.WriteLine("{0} Received message type: {1}", this.GetType().Name, typeof(Message).Name); } } public class AsyncMessageHandler : IHandleAsync<Message> { public async Task HandleAsync(Message message, CancellationToken cancellationToken) { await Task.Delay(1000); Console.WriteLine("{0} Received message type: {1}", this.GetType().Name, typeof(Message).Name); } } }
mit
C#
03d0d050abd55938e6d75085153d70b4ee738498
fix RazorWebSite example to work on .NET Core 3
andrewlock/NetEscapades.AspNetCore.SecurityHeaders,andrewlock/NetEscapades.AspNetCore.SecurityHeaders,andrewlock/NetEscapades.AspNetCore.SecurityHeaders,andrewlock/NetEscapades.AspNetCore.SecurityHeaders
test/RazorWebSite/Startup.cs
test/RazorWebSite/Startup.cs
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.DependencyInjection; namespace RazorWebSite { public class Startup { // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { var policyCollection = new HeaderPolicyCollection() .AddXssProtectionBlock() .AddContentTypeOptionsNoSniff() .AddExpectCTNoEnforceOrReport(0) .AddStrictTransportSecurityMaxAgeIncludeSubDomains(maxAgeInSeconds: 60 * 60 * 24 * 365) // maxage = one year in seconds .AddReferrerPolicyStrictOriginWhenCrossOrigin() .AddContentSecurityPolicy(builder => { builder.AddUpgradeInsecureRequests(); builder.AddDefaultSrc().Self(); builder.AddConnectSrc().From("*"); builder.AddFontSrc().From("*"); builder.AddFrameAncestors().From("*"); builder.AddFrameSource().From("*"); builder.AddWorkerSrc().From("*"); builder.AddMediaSrc().From("*"); builder.AddImgSrc().From("*").Data(); builder.AddObjectSrc().From("*"); builder.AddScriptSrc().From("*").UnsafeInline().UnsafeEval(); builder.AddStyleSrc().From("*").UnsafeEval().UnsafeInline(); }) .RemoveServerHeader(); app.UseSecurityHeaders(policyCollection); app.UseStaticFiles(); #if NETCOREAPP3_0 app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); }); #else app.UseMvc(); #endif } } }
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.DependencyInjection; namespace RazorWebSite { public class Startup { // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { var policyCollection = new HeaderPolicyCollection() .AddXssProtectionBlock() .AddContentTypeOptionsNoSniff() .AddStrictTransportSecurityMaxAgeIncludeSubDomains(maxAgeInSeconds: 60 * 60 * 24 * 365) // maxage = one year in seconds .AddReferrerPolicyStrictOriginWhenCrossOrigin() .AddContentSecurityPolicy(builder => { builder.AddUpgradeInsecureRequests(); builder.AddDefaultSrc().Self(); builder.AddConnectSrc().From("*"); builder.AddFontSrc().From("*"); builder.AddFrameAncestors().From("*"); builder.AddFrameSource().From("*"); builder.AddWorkerSrc().From("*"); builder.AddMediaSrc().From("*"); builder.AddImgSrc().From("*").Data(); builder.AddObjectSrc().From("*"); builder.AddScriptSrc().From("*").UnsafeInline().UnsafeEval(); builder.AddStyleSrc().From("*").UnsafeEval().UnsafeInline(); }) .RemoveServerHeader(); app.UseSecurityHeaders(policyCollection); app.UseStaticFiles(); app.UseMvc(); } } }
mit
C#
77de01c1baa94dbc0af9bee81658164b9ab068be
add localhost 127.0.0.1 for ipv4
IvanZheng/IFramework,IvanZheng/IFramework,IvanZheng/IFramework
Src/iFramework.Plugins/IFramework.WebApi/IPRestriction/IPRestrictFilterAttribute.cs
Src/iFramework.Plugins/IFramework.WebApi/IPRestriction/IPRestrictFilterAttribute.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Web.Http.Controllers; using System.Web.Http.Filters; using IFramework.Infrastructure; using System.Web.Http; using System.Net.Http; using System.Net; namespace IFramework.AspNet { public class IPFilterAttribute : ActionFilterAttribute { List<string> WhiteList = null; /// <summary> /// restrict client request by ip /// </summary> /// <param name="entry">entry as key in config to find while list or black list. /// if entry is empty, use global config. /// </param> public IPFilterAttribute(string entry = null) { if (string.IsNullOrEmpty(entry)) { WhiteList = IPRestrictExtension.IPRestrictConfig?.GlobalWhiteList; } else { WhiteList = IPRestrictExtension.IPRestrictConfig .EntryWhiteListDictionary .TryGetValue(entry, null); } WhiteList = WhiteList ?? new List<string>(); } public override void OnActionExecuting(HttpActionContext actionContext) { base.OnActionExecuting(actionContext); var clientIP = actionContext.Request.GetClientIp(); if (clientIP != "::1" && clientIP != "127.0.0.1" && !WhiteList.Contains(clientIP)) { throw new HttpResponseException(actionContext.Request .CreateErrorResponse(HttpStatusCode.Forbidden, "Client IP is not allowed!")); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Web.Http.Controllers; using System.Web.Http.Filters; using IFramework.Infrastructure; using System.Web.Http; using System.Net.Http; using System.Net; namespace IFramework.AspNet { public class IPFilterAttribute : ActionFilterAttribute { List<string> WhiteList = null; /// <summary> /// restrict client request by ip /// </summary> /// <param name="entry">entry as key in config to find while list or black list. /// if entry is empty, use global config. /// </param> public IPFilterAttribute(string entry = null) { if (string.IsNullOrEmpty(entry)) { WhiteList = IPRestrictExtension.IPRestrictConfig?.GlobalWhiteList; } else { WhiteList = IPRestrictExtension.IPRestrictConfig .EntryWhiteListDictionary .TryGetValue(entry, null); } WhiteList = WhiteList ?? new List<string>(); } public override void OnActionExecuting(HttpActionContext actionContext) { base.OnActionExecuting(actionContext); var clientIP = actionContext.Request.GetClientIp(); if (clientIP != "::1" && !WhiteList.Contains(clientIP)) { throw new HttpResponseException(actionContext.Request .CreateErrorResponse(HttpStatusCode.Forbidden, "Client IP is not allowed!")); } } } }
mit
C#
854e2effc2443a96e850c04f20e7e40d793d5a64
添加MemberInfo.GetAttributes
zkweb-framework/ZKWeb,zkweb-framework/ZKWeb,zkweb-framework/ZKWeb,303248153/ZKWeb,zkweb-framework/ZKWeb,zkweb-framework/ZKWeb,zkweb-framework/ZKWeb
ZKWeb.Utils/Extensions/MemberInfoExtensions.cs
ZKWeb.Utils/Extensions/MemberInfoExtensions.cs
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using ZKWeb.Utils.Functions; namespace ZKWeb.Utils.Extensions { /// <summary> /// 成员信息的扩展函数 /// </summary> public static class MemberInfoExtensions { /// <summary> /// 获取指定类型的属性,没有时返回null /// </summary> /// <typeparam name="TAttribute">属性类型</typeparam> /// <param name="info">成员信息</param> /// <returns></returns> public static TAttribute GetAttribute<TAttribute>(this MemberInfo info) where TAttribute : Attribute { return info.GetCustomAttributes( typeof(TAttribute), true).FirstOrDefault() as TAttribute; } /// <summary> /// 获取指定类型的属性列表 /// </summary> /// <typeparam name="TAttribute">属性类型</typeparam> /// <param name="info">成员信息</param> /// <returns></returns> public static IEnumerable<TAttribute> GetAttributes<TAttribute>(this MemberInfo info) where TAttribute : Attribute { return info.GetCustomAttributes(typeof(TAttribute), true).OfType<TAttribute>(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using ZKWeb.Utils.Functions; namespace ZKWeb.Utils.Extensions { /// <summary> /// 成员信息的扩展函数 /// </summary> public static class MemberInfoExtensions { /// <summary> /// 获取指定类型的属性,没有时返回null /// </summary> /// <typeparam name="TAttribute">属性类型</typeparam> /// <param name="info">成员信息</param> /// <returns></returns> public static TAttribute GetAttribute<TAttribute>(this MemberInfo info) where TAttribute : Attribute { return info.GetCustomAttributes( typeof(TAttribute), true).FirstOrDefault() as TAttribute; } } }
mit
C#
a55b77f7f8ac8035da6b4181237f02326cc91f24
Remove correct page on back button press
rotorgames/Rg.Plugins.Popup,rotorgames/Rg.Plugins.Popup
Rg.Plugins.Popup/Platforms/Android/Popup.cs
Rg.Plugins.Popup/Platforms/Android/Popup.cs
using System; using System.Linq; using Android.Content; using Android.OS; using Rg.Plugins.Popup.Droid.Impl; using Rg.Plugins.Popup.Droid.Renderers; using Rg.Plugins.Popup.Services; using Xamarin.Forms; namespace Rg.Plugins.Popup { public static class Popup { internal static event EventHandler OnInitialized; internal static bool IsInitialized { get; private set; } internal static Context Context { get; private set; } public static void Init(Context context, Bundle bundle) { LinkAssemblies(); Context = context; IsInitialized = true; OnInitialized?.Invoke(null, EventArgs.Empty); } public static bool SendBackPressed(Action backPressedHandler = null) { var popupNavigationInstance = PopupNavigation.Instance; if (popupNavigationInstance.PopupStack.Count > 0) { var lastPage = popupNavigationInstance.PopupStack.Last(); var isPreventClose = lastPage.DisappearingTransactionTask != null || lastPage.SendBackButtonPressed(); if (!isPreventClose) { Device.BeginInvokeOnMainThread(async () => { await popupNavigationInstance.RemovePageAsync(lastPage); }); } return true; } backPressedHandler?.Invoke(); return false; } private static void LinkAssemblies() { if (false.Equals(true)) { var i = new PopupPlatformDroid(); var r = new PopupPageRenderer(null); } } } }
using System; using System.Linq; using Android.Content; using Android.OS; using Rg.Plugins.Popup.Droid.Impl; using Rg.Plugins.Popup.Droid.Renderers; using Rg.Plugins.Popup.Services; using Xamarin.Forms; namespace Rg.Plugins.Popup { public static class Popup { internal static event EventHandler OnInitialized; internal static bool IsInitialized { get; private set; } internal static Context Context { get; private set; } public static void Init(Context context, Bundle bundle) { LinkAssemblies(); Context = context; IsInitialized = true; OnInitialized?.Invoke(null, EventArgs.Empty); } public static bool SendBackPressed(Action backPressedHandler = null) { var popupNavigationInstance = PopupNavigation.Instance; if (popupNavigationInstance.PopupStack.Count > 0) { var lastPage = popupNavigationInstance.PopupStack.Last(); var isPreventClose = lastPage.DisappearingTransactionTask != null || lastPage.SendBackButtonPressed(); if (!isPreventClose) { Device.BeginInvokeOnMainThread(async () => { await popupNavigationInstance.PopAsync(); }); } return true; } backPressedHandler?.Invoke(); return false; } private static void LinkAssemblies() { if (false.Equals(true)) { var i = new PopupPlatformDroid(); var r = new PopupPageRenderer(null); } } } }
mit
C#
5be22916bb80ca652099369e6a69b2cee955fca5
Add test coverage against frequency ramp increasing between fail animation and fail screen
smoogipoo/osu,NeoAdonis/osu,smoogipoo/osu,ppy/osu,peppy/osu,peppy/osu,smoogipooo/osu,NeoAdonis/osu,peppy/osu,NeoAdonis/osu,ppy/osu,ppy/osu,smoogipoo/osu
osu.Game.Tests/Visual/Gameplay/TestSceneFailAnimation.cs
osu.Game.Tests/Visual/Gameplay/TestSceneFailAnimation.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; using NUnit.Framework; using osu.Framework.Graphics.Containers; using osu.Game.Configuration; using osu.Game.Rulesets; using osu.Game.Rulesets.Mods; using osu.Game.Screens.Play; namespace osu.Game.Tests.Visual.Gameplay { public class TestSceneFailAnimation : TestSceneAllRulesetPlayers { protected override Player CreatePlayer(Ruleset ruleset) { SelectedMods.Value = Array.Empty<Mod>(); return new FailPlayer(); } [Test] public void TestOsuWithoutRedTint() { AddStep("Disable red tint", () => Config.SetValue(OsuSetting.FadePlayfieldWhenHealthLow, false)); TestOsu(); AddStep("Enable red tint", () => Config.SetValue(OsuSetting.FadePlayfieldWhenHealthLow, true)); } protected override void AddCheckSteps() { AddUntilStep("wait for fail", () => Player.HasFailed); AddUntilStep("wait for fail overlay", () => ((FailPlayer)Player).FailOverlay.State.Value == Visibility.Visible); // The pause screen and fail animation both ramp frequency. // This tests to ensure that it doesn't reset during that handoff. AddAssert("frequency only ever decreased", () => !((FailPlayer)Player).FrequencyIncreased); } private class FailPlayer : TestPlayer { public new FailOverlay FailOverlay => base.FailOverlay; public bool FrequencyIncreased { get; private set; } public FailPlayer() : base(false, false) { } protected override void LoadComplete() { base.LoadComplete(); HealthProcessor.FailConditions += (_, __) => true; } private double lastFrequency = double.MaxValue; protected override void Update() { base.Update(); double freq = Beatmap.Value.Track.AggregateFrequency.Value; FrequencyIncreased |= freq > lastFrequency; lastFrequency = freq; } } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using NUnit.Framework; using osu.Framework.Graphics.Containers; using osu.Game.Configuration; using osu.Game.Rulesets; using osu.Game.Rulesets.Mods; using osu.Game.Screens.Play; namespace osu.Game.Tests.Visual.Gameplay { public class TestSceneFailAnimation : TestSceneAllRulesetPlayers { protected override Player CreatePlayer(Ruleset ruleset) { SelectedMods.Value = Array.Empty<Mod>(); return new FailPlayer(); } [Test] public void TestOsuWithoutRedTint() { AddStep("Disable red tint", () => Config.SetValue(OsuSetting.FadePlayfieldWhenHealthLow, false)); TestOsu(); AddStep("Enable red tint", () => Config.SetValue(OsuSetting.FadePlayfieldWhenHealthLow, true)); } protected override void AddCheckSteps() { AddUntilStep("wait for fail", () => Player.HasFailed); AddUntilStep("wait for fail overlay", () => ((FailPlayer)Player).FailOverlay.State.Value == Visibility.Visible); } private class FailPlayer : TestPlayer { public new FailOverlay FailOverlay => base.FailOverlay; public FailPlayer() : base(false, false) { } protected override void LoadComplete() { base.LoadComplete(); HealthProcessor.FailConditions += (_, __) => true; } } } }
mit
C#
9475d3bb08b05b5e69708d37f2c603ddc66c8635
Add support for `Mandate` in `ChargePaymentMethodDetailsAcssDebit`
stripe/stripe-dotnet
src/Stripe.net/Entities/Charges/ChargePaymentMethodDetails/ChargePaymentMethodDetailsAcssDebit.cs
src/Stripe.net/Entities/Charges/ChargePaymentMethodDetails/ChargePaymentMethodDetailsAcssDebit.cs
namespace Stripe { using Newtonsoft.Json; using Stripe.Infrastructure; public class ChargePaymentMethodDetailsAcssDebit : StripeEntity<ChargePaymentMethodDetailsAcssDebit> { /// <summary> /// Uniquely identifies this particular bank account. You can use this attribute to check /// whether two bank accounts are the same. /// </summary> [JsonProperty("fingerprint")] public string Fingerprint { get; set; } /// <summary> /// Institution number of the bank account. /// </summary> [JsonProperty("institution_number")] public string InstitutionNumber { get; set; } /// <summary> /// Last four digits of the bank account number. /// </summary> [JsonProperty("last4")] public string Last4 { get; set; } /// <summary> /// ID of the mandate used to make this payment. /// </summary> [JsonProperty("mandate")] public string Mandate { get; set; } /// <summary> /// Transit number of the bank account. /// </summary> [JsonProperty("transit_number")] public string TransitNumber { get; set; } } }
namespace Stripe { using Newtonsoft.Json; using Stripe.Infrastructure; public class ChargePaymentMethodDetailsAcssDebit : StripeEntity<ChargePaymentMethodDetailsAcssDebit> { /// <summary> /// Uniquely identifies this particular bank account. You can use this attribute to check /// whether two bank accounts are the same. /// </summary> [JsonProperty("fingerprint")] public string Fingerprint { get; set; } /// <summary> /// Institution number of the bank account. /// </summary> [JsonProperty("institution_number")] public string InstitutionNumber { get; set; } /// <summary> /// Last four digits of the bank account number. /// </summary> [JsonProperty("last4")] public string Last4 { get; set; } /// <summary> /// Transit number of the bank account. /// </summary> [JsonProperty("transit_number")] public string TransitNumber { get; set; } } }
apache-2.0
C#
22d9a39a1e0c197d923f507fccac8fa91678b1a9
Remove unnecessary using
MahApps/MahApps.Metro,ye4241/MahApps.Metro,Evangelink/MahApps.Metro,batzen/MahApps.Metro,xxMUROxx/MahApps.Metro
src/MahApps.Metro/MahApps.Metro.Shared/Controls/Dialogs/MetroDialogAutomationPeer.cs
src/MahApps.Metro/MahApps.Metro.Shared/Controls/Dialogs/MetroDialogAutomationPeer.cs
using System.Windows.Automation.Peers; namespace MahApps.Metro.Controls.Dialogs { public class MetroDialogAutomationPeer : FrameworkElementAutomationPeer { public MetroDialogAutomationPeer(BaseMetroDialog owner) : base(owner) { } protected override string GetClassNameCore() { return this.Owner.GetType().Name; } protected override AutomationControlType GetAutomationControlTypeCore() { return AutomationControlType.Custom; } protected override string GetNameCore() { string ownerTitle = ((BaseMetroDialog)this.Owner).Title; string nameCore = base.GetNameCore(); if (!string.IsNullOrEmpty(ownerTitle)) { nameCore = $"{nameCore} {ownerTitle}"; } return nameCore; } } }
using System; using System.Windows.Automation.Peers; namespace MahApps.Metro.Controls.Dialogs { public class MetroDialogAutomationPeer : FrameworkElementAutomationPeer { public MetroDialogAutomationPeer(BaseMetroDialog owner) : base(owner) { } protected override string GetClassNameCore() { return this.Owner.GetType().Name; } protected override AutomationControlType GetAutomationControlTypeCore() { return AutomationControlType.Custom; } protected override string GetNameCore() { string ownerTitle = ((BaseMetroDialog)this.Owner).Title; string nameCore = base.GetNameCore(); if (!string.IsNullOrEmpty(ownerTitle)) { nameCore = $"{nameCore} {ownerTitle}"; } return nameCore; } } }
mit
C#