commit
stringlengths
40
40
old_file
stringlengths
4
237
new_file
stringlengths
4
237
old_contents
stringlengths
1
4.24k
new_contents
stringlengths
1
4.87k
subject
stringlengths
15
778
message
stringlengths
15
8.75k
lang
stringclasses
266 values
license
stringclasses
13 values
repos
stringlengths
5
127k
eaf5cbf0563e6b85531938e669ed8649e70103e3
test/Microsoft.NET.TestFramework/Commands/MSBuildTest.cs
test/Microsoft.NET.TestFramework/Commands/MSBuildTest.cs
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using System.Linq; using Microsoft.DotNet.Cli.Utils; namespace Microsoft.NET.TestFramework.Commands { public class MSBuildTest { public static readonly MSBuildTest Stage0MSBuild = new MSBuildTest(RepoInfo.DotNetHostPath); private string DotNetHostPath { get; } public MSBuildTest(string dotNetHostPath) { DotNetHostPath = dotNetHostPath; } public ICommand CreateCommandForTarget(string target, params string[] args) { var newArgs = args.ToList(); newArgs.Insert(0, $"/t:{target}"); return CreateCommand(newArgs.ToArray()); } private ICommand CreateCommand(params string[] args) { var newArgs = args.ToList(); newArgs.Insert(0, $"msbuild"); ICommand command = Command.Create(DotNetHostPath, newArgs); // Set NUGET_PACKAGES environment variable to match value from build.ps1 command = command.EnvironmentVariable("NUGET_PACKAGES", RepoInfo.PackagesPath); return command; } } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using System.Linq; using Microsoft.DotNet.Cli.Utils; namespace Microsoft.NET.TestFramework.Commands { public class MSBuildTest { public static readonly MSBuildTest Stage0MSBuild = new MSBuildTest(RepoInfo.DotNetHostPath); private string DotNetHostPath { get; } public MSBuildTest(string dotNetHostPath) { DotNetHostPath = dotNetHostPath; } public ICommand CreateCommandForTarget(string target, params string[] args) { var newArgs = args.ToList(); newArgs.Insert(0, $"/t:{target}"); return CreateCommand(newArgs.ToArray()); } private ICommand CreateCommand(params string[] args) { var newArgs = args.ToList(); newArgs.Insert(0, $"msbuild"); ICommand command = Command.Create(DotNetHostPath, newArgs); // Set NUGET_PACKAGES environment variable to match value from build.ps1 command = command.EnvironmentVariable("NUGET_PACKAGES", Path.Combine(RepoInfo.RepoRoot, "packages")); return command; } } }
Fix NUGET_PACKAGES folder when running tests.
Fix NUGET_PACKAGES folder when running tests. RepoInfo.PackagesPath is actually the output path for the .nupkg, and is configuration-specific. NUGET_PACKAGES should just be the packages folder under the repo root.
C#
mit
nkolev92/sdk,nkolev92/sdk
e81bd9a1be512dde46a1684a9dd31985a127b314
src/GitHub.Api/Git/Tasks/GitCommitTask.cs
src/GitHub.Api/Git/Tasks/GitCommitTask.cs
using System; using System.Threading; namespace GitHub.Unity { class GitCommitTask : ProcessTask<string> { private const string TaskName = "git commit"; private readonly string arguments; public GitCommitTask(string message, string body, CancellationToken token, IOutputProcessor<string> processor = null) : base(token, processor ?? new SimpleOutputProcessor()) { Guard.ArgumentNotNullOrWhiteSpace(message, "message"); Name = TaskName; arguments = "commit "; arguments += String.Format(" -m \"{0}", message); if (!String.IsNullOrEmpty(body)) arguments += String.Format("{0}{1}", Environment.NewLine, body); arguments += "\""; } public override string ProcessArguments { get { return arguments; } } public override TaskAffinity Affinity { get { return TaskAffinity.Exclusive; } } } }
using System; using System.Threading; namespace GitHub.Unity { class GitCommitTask : ProcessTask<string> { private const string TaskName = "git commit"; private readonly string arguments; public GitCommitTask(string message, string body, CancellationToken token, IOutputProcessor<string> processor = null) : base(token, processor ?? new SimpleOutputProcessor()) { Guard.ArgumentNotNullOrWhiteSpace(message, "message"); Name = TaskName; arguments = "commit "; arguments += String.Format(" -m \"{0}\"", message); if (!String.IsNullOrEmpty(body)) arguments += String.Format(" -m \"{0}\"", body); } public override string ProcessArguments { get { return arguments; } } public override TaskAffinity Affinity { get { return TaskAffinity.Exclusive; } } } }
Split the commit message into the subject line and the body
Split the commit message into the subject line and the body
C#
mit
github-for-unity/Unity,mpOzelot/Unity,github-for-unity/Unity,github-for-unity/Unity,mpOzelot/Unity
402c227028ca320293b594ab6ee8eae56cb00bad
row.cs
row.cs
using System; using System.Collections.Generic; namespace Hangman { public class Row { public Cell[] Cells; public Row(Cell[] cells) { Cells = cells; } public string Draw(int width) { // return new String(' ', width - Text.Length) + Text; return String.Join("\n", Lines()); } private string[] Lines() { var lines = new List<string>(); for (var i = 0; i < MaxCellDepth(); i++) { var line = LineAtIndex(i); lines.Add(String.Join("", line)); } return lines.ToArray(); } private string LineAtIndex(int index) { var line = new List<string>(); int usedSpace = 0; foreach (var cell in Cells) { var part = cell.LineAtIndex(index); line.Add(part); usedSpace += part.Length; } return String.Join("", line); } private int MaxCellDepth() { int max = 0; foreach (var cell in Cells) { max = Math.Max(max, cell.Depth()); } return max; } } }
using System; using System.Collections.Generic; namespace Hangman { public class Row { public Cell[] Cells; private int Width; public Row(Cell[] cells) { Cells = cells; } public string Draw(int width) { // return new String(' ', width - Text.Length) + Text; Width = width; return String.Join("\n", Lines()); } private string[] Lines() { var lines = new List<string>(); for (var i = 0; i < MaxCellDepth(); i++) { var line = LineAtIndex(i); lines.Add(String.Join("", line)); } return lines.ToArray(); } private string LineAtIndex(int index) { var line = new List<string>(); int usedSpace = 0; foreach (var cell in Cells) { var part = cell.LineAtIndex(index); var spacing = SpacingFor(cell); line.Add(spacing + part); usedSpace += part.Length; } return String.Join("", line); } private string SpacingFor(Cell cell) { return new String(' ', 4); } private int MaxCellDepth() { int max = 0; foreach (var cell in Cells) { max = Math.Max(max, cell.Depth()); } return max; } } }
Add dynamic left margin for line parts
Add dynamic left margin for line parts
C#
unlicense
12joan/hangman
3b6485d312dbe1ea431b13fac617841ed667be9e
ExchangeRate/Providers/GoogleProvider.cs
ExchangeRate/Providers/GoogleProvider.cs
// Copyright ©2017 Simonray (http://github.com/simonray). All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using ExchangeRate.Model; using System.Net; using System.Text.RegularExpressions; namespace ExchangeRate.Providers { /// <exclude /> public class GoogleProvider : BaseProvider { /// <exclude /> const string URL = "http://www.google.com/finance/converter?a=1&from={0}&to={1}"; /// <exclude /> public override string Name { get { return "Google"; } } /// <exclude /> public override Rate Fetch(Pair pair) { string url = pair.Construct(URL); var data = new GZipWebClient().DownloadString(url); var result = Regex.Matches(data, "<span class=\"?bld\"?>([^<]+)</span>")[0].Groups[1].Value; if (result == null) ThrowFormatChanged(); var value = Regex.Match(result, @"[0-9]*(?:\.[0-9]+)?"); if (value == null) ThrowFormatChanged(); return new Rate(double.Parse(value.Value)); } } }
// Copyright ©2017 Simonray (http://github.com/simonray). All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using ExchangeRate.Model; using System.Net; using System.Text.RegularExpressions; namespace ExchangeRate.Providers { /// <exclude /> public class GoogleProvider : BaseProvider { /// <exclude /> const string URL = "http://finance.google.com/finance/converter?a=1&from={0}&to={1}"; /// <exclude /> public override string Name { get { return "Google"; } } /// <exclude /> public override Rate Fetch(Pair pair) { string url = pair.Construct(URL); var data = new GZipWebClient().DownloadString(url); var result = Regex.Matches(data, "<span class=\"?bld\"?>([^<]+)</span>")[0].Groups[1].Value; if (result == null) ThrowFormatChanged(); var value = Regex.Match(result, @"[0-9]*(?:\.[0-9]+)?"); if (value == null) ThrowFormatChanged(); return new Rate(double.Parse(value.Value)); } } }
Update changes to Google finance url
Update changes to Google finance url
C#
mit
simonray/exchange-rate
d82cf72379a5e7fabe149058f2f292d716cb7cfc
src/Scrutor/ServiceDescriptorAttribute.cs
src/Scrutor/ServiceDescriptorAttribute.cs
using System; using System.Collections.Generic; using System.Reflection; using Microsoft.Extensions.DependencyInjection; namespace Scrutor { [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public class ServiceDescriptorAttribute : Attribute { public ServiceDescriptorAttribute() : this(null) { } public ServiceDescriptorAttribute(Type serviceType) : this(serviceType, ServiceLifetime.Transient) { } public ServiceDescriptorAttribute(Type serviceType, ServiceLifetime lifetime) { ServiceType = serviceType; Lifetime = lifetime; } public Type ServiceType { get; } public ServiceLifetime Lifetime { get; } public IEnumerable<Type> GetServiceTypes(Type fallbackType) { if (ServiceType == null) { yield return fallbackType; var fallbackTypes = fallbackType.GetBaseTypes(); foreach (var type in fallbackTypes) { if (type == typeof(object)) { continue; } yield return type; } yield break; } var fallbackTypeInfo = fallbackType.GetTypeInfo(); var serviceTypeInfo = ServiceType.GetTypeInfo(); if (!serviceTypeInfo.IsAssignableFrom(fallbackTypeInfo)) { throw new InvalidOperationException($@"Type ""{fallbackTypeInfo.FullName}"" is not assignable to ""${serviceTypeInfo.FullName}""."); } yield return ServiceType; } } }
using System; using System.Collections.Generic; using Microsoft.Extensions.DependencyInjection; namespace Scrutor { [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public class ServiceDescriptorAttribute : Attribute { public ServiceDescriptorAttribute() : this(null) { } public ServiceDescriptorAttribute(Type serviceType) : this(serviceType, ServiceLifetime.Transient) { } public ServiceDescriptorAttribute(Type serviceType, ServiceLifetime lifetime) { ServiceType = serviceType; Lifetime = lifetime; } public Type ServiceType { get; } public ServiceLifetime Lifetime { get; } public IEnumerable<Type> GetServiceTypes(Type fallbackType) { if (ServiceType == null) { yield return fallbackType; var fallbackTypes = fallbackType.GetBaseTypes(); foreach (var type in fallbackTypes) { if (type == typeof(object)) { continue; } yield return type; } yield break; } if (!fallbackType.IsAssignableTo(ServiceType)) { throw new InvalidOperationException($@"Type ""{fallbackType.FullName}"" is not assignable to ""${ServiceType.FullName}""."); } yield return ServiceType; } } }
Use IsAssignableTo instead of IsAssignableFrom
Use IsAssignableTo instead of IsAssignableFrom
C#
mit
khellang/Scrutor
71cdc74c5bbff09a84078f56ed1be30ffa6a54fa
src/ConsoleApp/Program.cs
src/ConsoleApp/Program.cs
using System; using System.Collections.Generic; using System.Linq; using static System.Console; namespace ConsoleApp { public class Table { public void OutputMigrationCode(string tableName, IEnumerable<Column> columns) { var writer = Out; writer.Write(@"namespace Cucu { [Migration("); writer.Write(DateTime.Now.ToString("yyyyMMddHHmmss")); writer.Write(@")] public class Vaca : Migration { public override void Up() { Create.Table("""); writer.Write(tableName); writer.Write(@""")"); columns.ToList().ForEach(c => { writer.WriteLine(); writer.Write(c.FluentMigratorCode()); }); writer.WriteLine(@"; } public override void Down() { // nothing here yet } } }"); } } class Program { private static void Main() { var columnsProvider = new ColumnsProvider(@"Server=.\SQLEXPRESS;Database=LearnORM;Trusted_Connection=True;"); var tableName = "Book"; var columns = columnsProvider.GetColumnsAsync("dbo", tableName).GetAwaiter().GetResult(); new Table().OutputMigrationCode(tableName, columns); } } }
using System; using System.Collections.Generic; using System.Linq; using static System.Console; namespace ConsoleApp { public class Table { private readonly string tableName; private readonly IEnumerable<Column> columns; public Table(string tableName, IEnumerable<Column> columns) { this.tableName = tableName; this.columns = columns; } public void OutputMigrationCode() { var writer = Out; writer.Write(@"namespace Cucu { [Migration("); writer.Write(DateTime.Now.ToString("yyyyMMddHHmmss")); writer.Write(@")] public class Vaca : Migration { public override void Up() { Create.Table("""); writer.Write(tableName); writer.Write(@""")"); columns.ToList().ForEach(c => { writer.WriteLine(); writer.Write(c.FluentMigratorCode()); }); writer.WriteLine(@"; } public override void Down() { // nothing here yet } } }"); } } class Program { private static void Main() { var columnsProvider = new ColumnsProvider(@"Server=.\SQLEXPRESS;Database=LearnORM;Trusted_Connection=True;"); var tableName = "Book"; var columns = columnsProvider.GetColumnsAsync("dbo", tableName).GetAwaiter().GetResult(); new Table(tableName, columns).OutputMigrationCode(); } } }
Move parameters from method to constructor
Move parameters from method to constructor
C#
mit
TeamnetGroup/schema2fm
9b05cbe24438574befe2dd0090b5a0ba173a916d
src/ResourceManager/Profile/Commands.Profile/Context/GetAzureRMContext.cs
src/ResourceManager/Profile/Commands.Profile/Context/GetAzureRMContext.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 Microsoft.Azure.Commands.Profile.Models; using Microsoft.Azure.Commands.ResourceManager.Common; using Microsoft.WindowsAzure.Commands.Common; using System.Management.Automation; namespace Microsoft.Azure.Commands.Profile { /// <summary> /// Cmdlet to get current context. /// </summary> [Cmdlet(VerbsCommon.Get, "AzureRmContext")] [OutputType(typeof(PSAzureContext))] public class GetAzureRMContextCommand : AzureRMCmdlet { public override void ExecuteCmdlet() { WriteObject((PSAzureContext)AzureRmProfileProvider.Instance.Profile.Context); } } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using Microsoft.Azure.Commands.Common.Authentication.Models; using Microsoft.Azure.Commands.Profile.Models; using Microsoft.Azure.Commands.ResourceManager.Common; using Microsoft.WindowsAzure.Commands.Common; using System.Management.Automation; namespace Microsoft.Azure.Commands.Profile { /// <summary> /// Cmdlet to get current context. /// </summary> [Cmdlet(VerbsCommon.Get, "AzureRmContext")] [OutputType(typeof(PSAzureContext))] public class GetAzureRMContextCommand : AzureRMCmdlet { /// <summary> /// Gets the current default context. /// </summary> protected override AzureContext DefaultContext { get { if (DefaultProfile == null || DefaultProfile.Context == null) { WriteError(new ErrorRecord( new PSInvalidOperationException("Run Login-AzureRmAccount to login."), string.Empty, ErrorCategory.AuthenticationError, null)); } return DefaultProfile.Context; } } public override void ExecuteCmdlet() { WriteObject((PSAzureContext)AzureRmProfileProvider.Instance.Profile.Context); } } }
Fix issue where Get-AzureRmContext does not allow user to silently continue
Fix issue where Get-AzureRmContext does not allow user to silently continue
C#
apache-2.0
AzureAutomationTeam/azure-powershell,naveedaz/azure-powershell,ClogenyTechnologies/azure-powershell,hungmai-msft/azure-powershell,naveedaz/azure-powershell,ClogenyTechnologies/azure-powershell,krkhan/azure-powershell,atpham256/azure-powershell,devigned/azure-powershell,naveedaz/azure-powershell,atpham256/azure-powershell,atpham256/azure-powershell,hungmai-msft/azure-powershell,devigned/azure-powershell,AzureAutomationTeam/azure-powershell,ClogenyTechnologies/azure-powershell,devigned/azure-powershell,atpham256/azure-powershell,AzureAutomationTeam/azure-powershell,hungmai-msft/azure-powershell,AzureAutomationTeam/azure-powershell,AzureAutomationTeam/azure-powershell,krkhan/azure-powershell,AzureAutomationTeam/azure-powershell,hungmai-msft/azure-powershell,ClogenyTechnologies/azure-powershell,krkhan/azure-powershell,krkhan/azure-powershell,devigned/azure-powershell,krkhan/azure-powershell,krkhan/azure-powershell,devigned/azure-powershell,hungmai-msft/azure-powershell,ClogenyTechnologies/azure-powershell,naveedaz/azure-powershell,atpham256/azure-powershell,atpham256/azure-powershell,devigned/azure-powershell,naveedaz/azure-powershell,hungmai-msft/azure-powershell,naveedaz/azure-powershell
696d0b8fb986959caac13535f6e475c8affec6c6
Agiil.Bootstrap/Data/NHibernateModule.cs
Agiil.Bootstrap/Data/NHibernateModule.cs
using System; using Agiil.Data; using Agiil.Domain; using Autofac; using NHibernate; using NHibernate.Cfg; namespace Agiil.Bootstrap.Data { public class NHibernateModule : Module { protected override void Load(ContainerBuilder builder) { // Configuration builder .Register((ctx, parameters) => { var factory = ctx.Resolve<ISessionFactoryFactory>(); return factory.GetConfiguration(); }) .SingleInstance(); // ISessionFactory builder .Register((ctx, parameters) => { var config = ctx.Resolve<Configuration>(); return config.BuildSessionFactory(); }) .SingleInstance(); // ISession builder .Register((ctx, parameters) => { var factory = ctx.Resolve<ISessionFactory>(); return factory.OpenSession(); }) .InstancePerMatchingLifetimeScope(ComponentScope.ApplicationConnection); } } }
using System; using Agiil.Data; using Agiil.Domain; using Autofac; using NHibernate; using NHibernate.Cfg; namespace Agiil.Bootstrap.Data { public class NHibernateModule : Module { protected override void Load(ContainerBuilder builder) { builder .Register(BuildNHibernateConfiguration) .SingleInstance(); builder .Register(BuildSessionFactory) .SingleInstance(); builder .Register(BuildSession) .InstancePerMatchingLifetimeScope(ComponentScope.ApplicationConnection); } Configuration BuildNHibernateConfiguration(IComponentContext ctx) { var factory = ctx.Resolve<ISessionFactoryFactory>(); return factory.GetConfiguration(); } ISessionFactory BuildSessionFactory(IComponentContext ctx) { var config = ctx.Resolve<Configuration>(); return config.BuildSessionFactory(); } ISession BuildSession(IComponentContext ctx) { var factory = ctx.Resolve<ISessionFactory>(); return factory.OpenSession(); } } }
Refactor NHibernate module for clarity
Refactor NHibernate module for clarity
C#
mit
csf-dev/agiil,csf-dev/agiil,csf-dev/agiil,csf-dev/agiil
513798f7e50053c0a8aff6b91c02cfa70f399410
src/Core/Vipr/Properties/AssemblyInfo.cs
src/Core/Vipr/Properties/AssemblyInfo.cs
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.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("Vipr")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Vipr")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: InternalsVisibleTo("ViprCliUnitTests")] [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] [assembly: AssemblyCompanyAttribute("Microsoft")] [assembly: AssemblyVersionAttribute("1.0.0.0")] [assembly: AssemblyFileVersionAttribute("1.0.*")]
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. 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("Vipr")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Vipr")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: InternalsVisibleTo("ViprCliUnitTests")] [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] [assembly: AssemblyCompanyAttribute("Microsoft")] [assembly: AssemblyVersionAttribute("1.0.*")] [assembly: AssemblyFileVersionAttribute("1.0.*")] [assembly: InternalsVisibleTo("T4TemplateWriterTests")]
Add InternalsVisibleTo for T4 Tests
Add InternalsVisibleTo for T4 Tests
C#
mit
MSOpenTech/Vipr,v-am/Vipr,Microsoft/Vipr
c3fc1168d1cee9a5487ce625b749272600402bf1
src/DeploymentCockpit.Data/UnitOfWork.cs
src/DeploymentCockpit.Data/UnitOfWork.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using DeploymentCockpit.Data.Repositories; using DeploymentCockpit.Interfaces; using DeploymentCockpit.Models; namespace DeploymentCockpit.Data { public class UnitOfWork : IUnitOfWork { private readonly Dictionary<Type, object> _repositories = new Dictionary<Type, object>(); public UnitOfWork(DeploymentCockpitEntities db) { if (db == null) throw new ArgumentNullException("db"); _db = db; } private readonly DeploymentCockpitEntities _db; public void Commit() { _db.SaveChanges(); } public void Dispose() { _db.Dispose(); } public IRepository<T> Repository<T>() where T : class { var key = typeof(T); if (!_repositories.ContainsKey(key)) _repositories.Add(key, new Repository<T>(_db)); return _repositories[key] as Repository<T>; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using DeploymentCockpit.Data.Repositories; using DeploymentCockpit.Interfaces; using DeploymentCockpit.Models; namespace DeploymentCockpit.Data { public class UnitOfWork : IUnitOfWork { private readonly DeploymentCockpitEntities _db; private readonly Dictionary<Type, object> _repositories = new Dictionary<Type, object>(); public UnitOfWork(DeploymentCockpitEntities db) { if (db == null) throw new ArgumentNullException("db"); _db = db; } public void Commit() { _db.SaveChanges(); } public void Dispose() { _db.Dispose(); } public IRepository<T> Repository<T>() where T : class { var key = typeof(T); if (!_repositories.ContainsKey(key)) _repositories.Add(key, new Repository<T>(_db)); return _repositories[key] as Repository<T>; } } }
Put declaration in right place
Put declaration in right place
C#
apache-2.0
anilmujagic/DeploymentCockpit,anilmujagic/DeploymentCockpit,anilmujagic/DeploymentCockpit
1f25bfe14e10286d3022c3de1ff851036f0c20da
src/Cassette.Views/HtmlString.cs
src/Cassette.Views/HtmlString.cs
namespace Cassette.Views { #if NET35 public interface IHtmlString { string ToHtmlString(); } public class HtmlString : IHtmlString { string _htmlString; public HtmlString(string htmlString) { this._htmlString = htmlString; } public string ToHtmlString() { return _htmlString; } public override string ToString() { return this._htmlString; } } #endif }
#if NET35 namespace Cassette.Views { public interface IHtmlString { string ToHtmlString(); } public class HtmlString : IHtmlString { string _htmlString; public HtmlString(string htmlString) { this._htmlString = htmlString; } public string ToHtmlString() { return _htmlString; } public override string ToString() { return this._htmlString; } } } #endif
Move conditional compilation around namespace.
Move conditional compilation around namespace.
C#
mit
damiensawyer/cassette,andrewdavey/cassette,honestegg/cassette,andrewdavey/cassette,honestegg/cassette,andrewdavey/cassette,damiensawyer/cassette,damiensawyer/cassette,honestegg/cassette,BluewireTechnologies/cassette,BluewireTechnologies/cassette
aabdbdaeb6c53179f0c0549f60cfdec4080007ab
osu.Framework.Tests/Localisation/CultureInfoHelperTest.cs
osu.Framework.Tests/Localisation/CultureInfoHelperTest.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.Globalization; using NUnit.Framework; using osu.Framework.Localisation; namespace osu.Framework.Tests.Localisation { [TestFixture] public class CultureInfoHelperTest { private const string invariant_culture = "invariant"; private const string current_culture = ""; [TestCase("en-US", true, "en-US")] [TestCase("invalid name", false, invariant_culture)] [TestCase(current_culture, true, current_culture)] [TestCase("ko_KR", false, invariant_culture)] public void TestTryGetCultureInfo(string name, bool expectedReturnValue, string expectedCultureName) { CultureInfo expectedCulture; switch (expectedCultureName) { case invariant_culture: expectedCulture = CultureInfo.InvariantCulture; break; case current_culture: expectedCulture = CultureInfo.CurrentCulture; break; default: expectedCulture = CultureInfo.GetCultureInfo(expectedCultureName); break; } bool retVal = CultureInfoHelper.TryGetCultureInfo(name, out var culture); Assert.That(retVal, Is.EqualTo(expectedReturnValue)); Assert.That(culture, Is.EqualTo(expectedCulture)); } } }
// 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.Globalization; using NUnit.Framework; using osu.Framework.Localisation; namespace osu.Framework.Tests.Localisation { [TestFixture] public class CultureInfoHelperTest { private const string invariant_culture = ""; [TestCase("en-US", true, "en-US")] [TestCase("invalid name", false, invariant_culture)] [TestCase(invariant_culture, true, invariant_culture)] [TestCase("ko_KR", false, invariant_culture)] public void TestTryGetCultureInfo(string name, bool expectedReturnValue, string expectedCultureName) { CultureInfo expectedCulture; switch (expectedCultureName) { case invariant_culture: expectedCulture = CultureInfo.InvariantCulture; break; default: expectedCulture = CultureInfo.GetCultureInfo(expectedCultureName); break; } bool retVal = CultureInfoHelper.TryGetCultureInfo(name, out var culture); Assert.That(retVal, Is.EqualTo(expectedReturnValue)); Assert.That(culture, Is.EqualTo(expectedCulture)); } } }
Update tests with new behaviour
Update tests with new behaviour
C#
mit
peppy/osu-framework,ppy/osu-framework,peppy/osu-framework,ppy/osu-framework,peppy/osu-framework,ppy/osu-framework
a99f98bf1657ec43ef5ff244d8ef2998ee3cba00
src/Media.Plugin.Abstractions/MediaPermissionException.cs
src/Media.Plugin.Abstractions/MediaPermissionException.cs
using System; using System.Collections.Generic; using System.Text; using Plugin.Permissions.Abstractions; namespace Plugin.Media.Abstractions { /// <summary> /// Permission exception. /// </summary> public class MediaPermissionException : Exception { /// <summary> /// Permission required that is missing /// </summary> public Permission[] Permissions { get; } /// <summary> /// Creates a media permission exception /// </summary> /// <param name="permissions"></param> public MediaPermissionException(params Permission[] permissions) : base($"{permissions} permission(s) are required.") { Permissions = permissions; } } }
using System; using System.Collections.Generic; using System.Text; using Plugin.Permissions.Abstractions; namespace Plugin.Media.Abstractions { /// <summary> /// Permission exception. /// </summary> public class MediaPermissionException : Exception { /// <summary> /// Permission required that is missing /// </summary> public Permission[] Permissions { get; } /// <summary> /// Creates a media permission exception /// </summary> /// <param name="permissions"></param> public MediaPermissionException(params Permission[] permissions) : base() { Permissions = permissions; } /// <summary> /// Gets a message that describes current exception /// </summary> /// <value>The message.</value> public override string Message { get { string missingPermissions = string.Join(", ", Permissions); return $"{missingPermissions} permission(s) are required."; } } } }
Update the exception to be more developer friendly
Update the exception to be more developer friendly Before: Plugin.Permissions.Abstractions.Permission[] permission(s) are required. After: Camera, Microphone, Photos permission(s) are required.
C#
mit
jamesmontemagno/MediaPlugin,jamesmontemagno/MediaPlugin
4eec1afd07eebedab12c19d2b4f038e1739d0923
zipkin4net-aspnetcore/Criteo.Profiling.Tracing.Middleware/TracingHandler.cs
zipkin4net-aspnetcore/Criteo.Profiling.Tracing.Middleware/TracingHandler.cs
using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; using Criteo.Profiling.Tracing.Transport; namespace Criteo.Profiling.Tracing.Middleware { public class TracingHandler : DelegatingHandler { private readonly ITraceInjector<HttpHeaders> _injector; private readonly string _serviceName; public TracingHandler(ITraceInjector<HttpHeaders> injector, string serviceName) { _injector = injector; _serviceName = serviceName; } protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { var trace = Trace.Current; if (trace != null) { trace = trace.Child(); _injector.Inject(trace, request.Headers); } trace.Record(Annotations.ClientSend()); trace.Record(Annotations.ServiceName(_serviceName)); trace.Record(Annotations.Rpc(request.Method.ToString())); return base.SendAsync(request, cancellationToken) .ContinueWith(t => { trace.Record(Annotations.ClientRecv()); return t.Result; }); } } }
using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; using Criteo.Profiling.Tracing.Transport; namespace Criteo.Profiling.Tracing.Middleware { public class TracingHandler : DelegatingHandler { private readonly ZipkinHttpTraceInjector _injector; private readonly string _serviceName; public TracingHandler(string serviceName) : this(new ZipkinHttpTraceInjector(), serviceName) {} internal TracingHandler(ZipkinHttpTraceInjector injector, string serviceName) { _injector = injector; _serviceName = serviceName; } protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { var trace = Trace.Current; if (trace != null) { trace = trace.Child(); _injector.Inject(trace, request.Headers); } trace.Record(Annotations.ClientSend()); trace.Record(Annotations.ServiceName(_serviceName)); trace.Record(Annotations.Rpc(request.Method.ToString())); return base.SendAsync(request, cancellationToken) .ContinueWith(t => { trace.Record(Annotations.ClientRecv()); return t.Result; }); } } }
Modify trace injector to http injector
Modify trace injector to http injector
C#
apache-2.0
criteo/zipkin4net,criteo/zipkin4net
ade5805b083bf693bd6ea63a06ff0a94cdc62ede
LmpUpdater/Appveyor/AppveyorUpdateChecker.cs
LmpUpdater/Appveyor/AppveyorUpdateChecker.cs
using LmpGlobal; using LmpUpdater.Appveyor.Contracts; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Net; namespace LmpUpdater.Appveyor { public class AppveyorUpdateChecker { public static RootObject LatestBuild { get { try { using (var wc = new WebClient()) { wc.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)"); var json = wc.DownloadString(RepoConstants.ApiLatestGithubReleaseUrl); return JsonConvert.DeserializeObject<RootObject>(JObject.Parse(json).ToString()); } } catch (Exception) { //Ignore as either we don't have internet connection or something like that... } return null; } } public static Version GetLatestVersion() { var versionComponents = LatestBuild?.build.version.Split('.'); return versionComponents != null && versionComponents.Length >= 3 ? new Version(int.Parse(versionComponents[0]), int.Parse(versionComponents[1]), int.Parse(versionComponents[2])) : new Version("0.0.0"); } } }
using LmpGlobal; using LmpUpdater.Appveyor.Contracts; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Net; namespace LmpUpdater.Appveyor { public class AppveyorUpdateChecker { public static RootObject LatestBuild { get { try { using (var wc = new WebClient()) { wc.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)"); var json = wc.DownloadString(RepoConstants.AppveyorUrl); return JsonConvert.DeserializeObject<RootObject>(JObject.Parse(json).ToString()); } } catch (Exception) { //Ignore as either we don't have internet connection or something like that... } return null; } } public static Version GetLatestVersion() { var versionComponents = LatestBuild?.build.version.Split('.'); return versionComponents != null && versionComponents.Length >= 3 ? new Version(int.Parse(versionComponents[0]), int.Parse(versionComponents[1]), int.Parse(versionComponents[2])) : new Version("0.0.0"); } } }
Fix master server auto-update with /nightly flag
Fix master server auto-update with /nightly flag
C#
mit
gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer,DaggerES/LunaMultiPlayer,gavazquez/LunaMultiPlayer
fd3a26c25df88d1efc6c22172c6e12c03fd6557a
D3DMeshConverter/Form1.cs
D3DMeshConverter/Form1.cs
using System; using System.IO; using System.Windows.Forms; namespace JPMeshConverter { public partial class Form1 : Form { private ModelFileDialog fileDialog; public Form1() { InitializeComponent(); fileDialog = new ModelFileDialog(System.AppDomain.CurrentDomain.BaseDirectory); } private void OnConvert(object sender, EventArgs e) { // Show the user a file dialog if (!fileDialog.Open()) { return; } // Parse the model data D3DReader reader = new D3DReader(fileDialog.FileName); // If the model couldn't be parsed correctly, error and return Mesh mesh = reader.MeshData; if (reader.MeshData == null) { MessageBox.Show("ERROR: Model could not be parsed.","Export failed!"); return; } // Output the mesh data to a Wavefront OBJ String outputName = fileDialog.FileName.Replace(".d3dmesh", ".obj"); File.WriteAllText(outputName, mesh.ToString()); // Show the user it worked MessageBox.Show(outputName+"\n\nProcessed "+mesh.Chunks.Count+" chunks.\n"+mesh.Vertices.Count + " vertices exported.", "Export successful!"); } } }
using System; using System.IO; using System.Windows.Forms; namespace JPMeshConverter { public partial class Form1 : Form { private ModelFileDialog fileDialog; public Form1() { InitializeComponent(); fileDialog = new ModelFileDialog(System.AppDomain.CurrentDomain.BaseDirectory); } private void OnConvert(object sender, EventArgs e) { // Show the user a file dialog if (!fileDialog.Open()) { return; } // Parse the model data D3DReader reader = new D3DReader(fileDialog.FileName); // If the model couldn't be parsed correctly, error and return Mesh mesh = reader.MeshData; if (reader.MeshData == null) { MessageBox.Show("ERROR: Model could not be parsed.","Export failed!"); return; } // Output the mesh data to a Wavefront OBJ String meshOutputName = fileDialog.FileName.Replace(".d3dmesh", ".obj"); String mtlOutputName = meshOutputName.Replace(".obj",".mtl"); String mtlName = mtlOutputName.Substring(mtlOutputName.LastIndexOf("\\")+1); File.WriteAllText(meshOutputName, mesh.GetObjData(mtlName)); File.WriteAllText(mtlOutputName,mesh.GetMtlData()); // Show the user it worked MessageBox.Show(meshOutputName+"\n\nProcessed "+mesh.Chunks.Count+" chunks.\n"+mesh.Vertices.Count + " vertices exported.", "Export successful!"); } } }
Write data to OBJ and MTL
Write data to OBJ and MTL
C#
mit
Stefander/JPMeshConverter
2e168ca512aae82446dee8db211b325bf8a8b56a
CSharp/MetadataWebApi/MetadataWebApi.Tests/IntegrationTests.cs
CSharp/MetadataWebApi/MetadataWebApi.Tests/IntegrationTests.cs
//----------------------------------------------------------------------- // <copyright file="IntegrationTests.cs" company="Experian Data Quality"> // Copyright (c) Experian. All rights reserved. // </copyright> //----------------------------------------------------------------------- using System; using System.Globalization; using System.IO; using Xunit; using Xunit.Abstractions; namespace Experian.Qas.Updates.Metadata.WebApi.V1 { public class IntegrationTests { private readonly ITestOutputHelper _output; public IntegrationTests(ITestOutputHelper output) { _output = output; } [Fact(Skip = "Requires access to a dedicated test account.")] public void Program_Downloads_Data_Files() { // Arrange Environment.SetEnvironmentVariable("QAS:ElectronicUpdates:UserName", string.Empty); Environment.SetEnvironmentVariable("QAS:ElectronicUpdates:Password", string.Empty); using (TextWriter writer = new StringWriter(CultureInfo.InvariantCulture)) { Console.SetOut(writer); try { // Act Program.MainInternal(); // Assert Assert.True(Directory.Exists("QASData")); Assert.NotEmpty(Directory.GetFiles("QASData", "*", SearchOption.AllDirectories)); } finally { _output.WriteLine(writer.ToString()); } } } } }
//----------------------------------------------------------------------- // <copyright file="IntegrationTests.cs" company="Experian Data Quality"> // Copyright (c) Experian. All rights reserved. // </copyright> //----------------------------------------------------------------------- using System; using System.Globalization; using System.IO; using Xunit; using Xunit.Abstractions; namespace Experian.Qas.Updates.Metadata.WebApi.V1 { public class IntegrationTests { private readonly ITestOutputHelper _output; public IntegrationTests(ITestOutputHelper output) { _output = output; } [RequiresServiceCredentialsFact] public void Program_Downloads_Data_Files() { // Arrange using (TextWriter writer = new StringWriter(CultureInfo.InvariantCulture)) { Console.SetOut(writer); try { // Act Program.MainInternal(); // Assert Assert.True(Directory.Exists("QASData")); Assert.NotEmpty(Directory.GetFiles("QASData", "*", SearchOption.AllDirectories)); } finally { _output.WriteLine(writer.ToString()); } } } private sealed class RequiresServiceCredentialsFact : FactAttribute { public RequiresServiceCredentialsFact() : base() { if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("QAS:ElectronicUpdates:UserName")) || string.IsNullOrEmpty(Environment.GetEnvironmentVariable("QAS:ElectronicUpdates:Password"))) { this.Skip = "No service credentials are configured."; } } } } }
Refactor Program_Downloads_Data_Files() to determine dynamically whether it should be skipped.
Refactor Program_Downloads_Data_Files() to determine dynamically whether it should be skipped.
C#
apache-2.0
martincostello/electronicupdates,experiandataquality/electronicupdates,experiandataquality/electronicupdates,martincostello/electronicupdates,martincostello/electronicupdates,martincostello/electronicupdates,experiandataquality/electronicupdates,martincostello/electronicupdates,experiandataquality/electronicupdates,experiandataquality/electronicupdates
10080a492aaafb5a3636fc8235eb6fc21a626e2b
src/Cash-Flow-Projection/Models/Balance.cs
src/Cash-Flow-Projection/Models/Balance.cs
using System; using System.Collections.Generic; using System.Linq; namespace Cash_Flow_Projection.Models { public static class Balance { public static Decimal CurrentBalance(this IEnumerable<Entry> entries, Account account = Account.Cash) { return GetLastBalanceEntry(entries, account)?.Amount ?? Decimal.Zero; } public static IEnumerable<Entry> SinceBalance(this IEnumerable<Entry> entries, DateTime end) { // Includes the last balance entry var last_balance = GetLastBalanceEntry(entries)?.Date; return entries .Where(entry => entry.Date >= last_balance) .Where(entry => entry.Date < end) .OrderBy(entry => entry.Date); } public static Entry GetLastBalanceEntry(this IEnumerable<Entry> entries, Account account = Account.Cash) { return entries .Where(entry => entry.Account == account) .Where(entry => entry.IsBalance) .OrderByDescending(entry => entry.Date) .FirstOrDefault(); } public static Decimal GetBalanceOn(this IEnumerable<Entry> entries, DateTime asOf, Account account = Account.Cash) { var last_balance = GetLastBalanceEntry(entries, account).Date; var delta_since_last_balance = entries .Where(entry => entry.Account == account) .Where(entry => !entry.IsBalance) .Where(entry => entry.Date >= last_balance) .Where(entry => entry.Date <= asOf) .Sum(entry => entry.Amount); return CurrentBalance(entries, account) + delta_since_last_balance; } } }
using System; using System.Collections.Generic; using System.Linq; namespace Cash_Flow_Projection.Models { public static class Balance { public static Decimal CurrentBalance(this IEnumerable<Entry> entries, Account account = Account.Cash) { return GetLastBalanceEntry(entries, account)?.Amount ?? Decimal.Zero; } public static IEnumerable<Entry> SinceBalance(this IEnumerable<Entry> entries, DateTime end) { // Includes the last balance entry var last_balance = GetLastBalanceEntry(entries)?.Date; return entries .Where(entry => entry.Date >= last_balance) .Where(entry => entry.Date < end) .OrderBy(entry => entry.Date); } public static Entry GetLastBalanceEntry(this IEnumerable<Entry> entries, Account account = Account.Cash) { return entries .Where(entry => entry.Account == account) .Where(entry => entry.IsBalance) .OrderByDescending(entry => entry.Date) .FirstOrDefault(); } public static Decimal GetBalanceOn(this IEnumerable<Entry> entries, DateTime asOf, Account account = Account.Cash) { var last_balance = GetLastBalanceEntry(entries, account)?.Date; var delta_since_last_balance = entries .Where(entry => entry.Account == account) .Where(entry => !entry.IsBalance) .Where(entry => entry.Date >= last_balance) .Where(entry => entry.Date <= asOf) .Sum(entry => entry.Amount); return CurrentBalance(entries, account) + delta_since_last_balance; } } }
Fix for balance null ref
Fix for balance null ref
C#
mit
mattgwagner/Cash-Flow-Projection,mattgwagner/Cash-Flow-Projection,mattgwagner/Cash-Flow-Projection,mattgwagner/Cash-Flow-Projection
eef0eaa1901c51c638e98865a15ccdfd62f53731
Client/Systems/VesselPartModuleSyncSys/VesselPartModuleSyncMessageHandler.cs
Client/Systems/VesselPartModuleSyncSys/VesselPartModuleSyncMessageHandler.cs
using LunaClient.Base; using LunaClient.Base.Interface; using LunaClient.VesselUtilities; using LunaCommon.Message.Data.Vessel; using LunaCommon.Message.Interface; using System.Collections.Concurrent; namespace LunaClient.Systems.VesselPartModuleSyncSys { public class VesselPartModuleSyncMessageHandler : SubSystem<VesselPartModuleSyncSystem>, IMessageHandler { public ConcurrentQueue<IServerMessageBase> IncomingMessages { get; set; } = new ConcurrentQueue<IServerMessageBase>(); public void HandleMessage(IServerMessageBase msg) { if (!(msg.Data is VesselPartSyncMsgData msgData) || !System.PartSyncSystemReady) return; //We received a msg for our own controlled/updated vessel so ignore it if (!VesselCommon.DoVesselChecks(msgData.VesselId)) return; if (!System.VesselPartsSyncs.ContainsKey(msgData.VesselId)) { System.VesselPartsSyncs.TryAdd(msgData.VesselId, new VesselPartSyncQueue()); } if (System.VesselPartsSyncs.TryGetValue(msgData.VesselId, out var queue)) { if (queue.TryPeek(out var resource) && resource.GameTime > msgData.GameTime) { //A user reverted, so clear his message queue and start from scratch queue.Clear(); } queue.Enqueue(msgData); } } } }
using LunaClient.Base; using LunaClient.Base.Interface; using LunaClient.VesselUtilities; using LunaCommon.Message.Data.Vessel; using LunaCommon.Message.Interface; using System.Collections.Concurrent; namespace LunaClient.Systems.VesselPartModuleSyncSys { public class VesselPartModuleSyncMessageHandler : SubSystem<VesselPartModuleSyncSystem>, IMessageHandler { public ConcurrentQueue<IServerMessageBase> IncomingMessages { get; set; } = new ConcurrentQueue<IServerMessageBase>(); public void HandleMessage(IServerMessageBase msg) { if (!(msg.Data is VesselPartSyncMsgData msgData)) return; //We received a msg for our own controlled/updated vessel so ignore it if (!VesselCommon.DoVesselChecks(msgData.VesselId)) return; if (!System.VesselPartsSyncs.ContainsKey(msgData.VesselId)) { System.VesselPartsSyncs.TryAdd(msgData.VesselId, new VesselPartSyncQueue()); } if (System.VesselPartsSyncs.TryGetValue(msgData.VesselId, out var queue)) { if (queue.TryPeek(out var resource) && resource.GameTime > msgData.GameTime) { //A user reverted, so clear his message queue and start from scratch queue.Clear(); } queue.Enqueue(msgData); } } } }
Fix unity call in another thread
Fix unity call in another thread
C#
mit
gavazquez/LunaMultiPlayer,DaggerES/LunaMultiPlayer,gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer
8495409d8d9637293d82dca6c46e3f8e7660882c
EDDiscovery/Controls/StatusStripCustom.cs
EDDiscovery/Controls/StatusStripCustom.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Drawing; using System.Windows.Forms; namespace ExtendedControls { public class StatusStripCustom : StatusStrip { public const int WM_NCHITTEST = 0x84; public const int WM_NCLBUTTONDOWN = 0xA1; public const int WM_NCLBUTTONUP = 0xA2; public const int HT_CLIENT = 0x1; public const int HT_BOTTOMRIGHT = 0x11; public const int HT_TRANSPARENT = -1; protected override void WndProc(ref Message m) { base.WndProc(ref m); if (m.Msg == WM_NCHITTEST && (int)m.Result == HT_BOTTOMRIGHT) { // Tell the system to test the parent m.Result = (IntPtr)HT_TRANSPARENT; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Drawing; using System.Windows.Forms; namespace ExtendedControls { public class StatusStripCustom : StatusStrip { public const int WM_NCHITTEST = 0x84; public const int WM_NCLBUTTONDOWN = 0xA1; public const int WM_NCLBUTTONUP = 0xA2; public const int HT_CLIENT = 0x1; public const int HT_BOTTOMRIGHT = 0x11; public const int HT_TRANSPARENT = -1; protected override void WndProc(ref Message m) { base.WndProc(ref m); if (m.Msg == WM_NCHITTEST) { if ((int)m.Result == HT_BOTTOMRIGHT) { // Tell the system to test the parent m.Result = (IntPtr)HT_TRANSPARENT; } else if ((int)m.Result == HT_CLIENT) { // Work around the implementation returning HT_CLIENT instead of HT_BOTTOMRIGHT int x = unchecked((short)((uint)m.LParam & 0xFFFF)); int y = unchecked((short)((uint)m.LParam >> 16)); Point p = PointToClient(new Point(x, y)); if (p.X >= this.ClientSize.Width - this.ClientSize.Height) { // Tell the system to test the parent m.Result = (IntPtr)HT_TRANSPARENT; } } } } } }
Work around faulty StatusStrip implementations
Work around faulty StatusStrip implementations Some StatusStrip implementations apparently return HT_CLIENT for the sizing grip where they should return HT_BOTTOMRIGHT.
C#
apache-2.0
jeoffman/EDDiscovery,jthorpe4/EDDiscovery,mwerle/EDDiscovery,jgoode/EDDiscovery,jeoffman/EDDiscovery,vendolis/EDDiscovery,jgoode/EDDiscovery,mwerle/EDDiscovery,vendolis/EDDiscovery
04acbdc2dc980d18dae94aa214a521a3657f1f2a
src/FileCurator/Formats/RSS/Data/Utils.cs
src/FileCurator/Formats/RSS/Data/Utils.cs
/* Copyright 2017 James Craig 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 FileCurator.Formats.RSS.Data { /// <summary> /// Utility class used by RSS classes. /// </summary> public static class Utils { /// <summary> /// Strips illegal characters from RSS items /// </summary> /// <param name="original">Original text</param> /// <returns>string stripped of certain characters.</returns> public static string StripIllegalCharacters(string original) { return original.Replace("&nbsp;", " ") .Replace("&#160;", string.Empty) .Trim() .Replace("&", "and"); } } }
/* Copyright 2017 James Craig 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 FileCurator.Formats.RSS.Data { /// <summary> /// Utility class used by RSS classes. /// </summary> public static class Utils { /// <summary> /// Strips illegal characters from RSS items /// </summary> /// <param name="original">Original text</param> /// <returns>string stripped of certain characters.</returns> public static string StripIllegalCharacters(string original) { return original?.Replace("&nbsp;", " ") .Replace("&#160;", string.Empty) .Trim() .Replace("&", "and") ?? ""; } } }
Fix for null values when stripping characters in feeds.
Fix for null values when stripping characters in feeds.
C#
apache-2.0
JaCraig/FileCurator,JaCraig/FileCurator
11395c40b7e4586c7c3c1030bc7e36d9e51ac5d3
osu.Game/Overlays/Settings/Sections/GeneralSection.cs
osu.Game/Overlays/Settings/Sections/GeneralSection.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Graphics; using osu.Framework.Graphics.Sprites; using osu.Framework.Localisation; using osu.Game.Localisation; using osu.Game.Overlays.Settings.Sections.General; namespace osu.Game.Overlays.Settings.Sections { public class GeneralSection : SettingsSection { public override LocalisableString Header => GeneralSettingsStrings.GeneralSectionHeader; public override Drawable CreateIcon() => new SpriteIcon { Icon = FontAwesome.Solid.Cog }; public GeneralSection() { Children = new Drawable[] { new LanguageSettings(), new UpdateSettings(), }; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Sprites; using osu.Framework.Localisation; using osu.Game.Localisation; using osu.Game.Overlays.Settings.Sections.General; namespace osu.Game.Overlays.Settings.Sections { public class GeneralSection : SettingsSection { [Resolved(CanBeNull = true)] private FirstRunSetupOverlay firstRunSetupOverlay { get; set; } public override LocalisableString Header => GeneralSettingsStrings.GeneralSectionHeader; public override Drawable CreateIcon() => new SpriteIcon { Icon = FontAwesome.Solid.Cog }; public GeneralSection() { Children = new Drawable[] { new SettingsButton { Text = "Run setup wizard", Action = () => firstRunSetupOverlay?.Show(), }, new LanguageSettings(), new UpdateSettings(), }; } } }
Add button to access first run setup on demand
Add button to access first run setup on demand
C#
mit
peppy/osu,peppy/osu,NeoAdonis/osu,NeoAdonis/osu,ppy/osu,ppy/osu,NeoAdonis/osu,ppy/osu,peppy/osu
83350b13049b51aeb235259dffb214e287af7612
CertiPay.Payroll.Common/CalculationType.cs
CertiPay.Payroll.Common/CalculationType.cs
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace CertiPay.Payroll.Common { /// <summary> /// Identifies the method to calculate the result /// </summary> public enum CalculationType : byte { /// <summary> /// Deduction is taken as a percentage of the gross pay /// </summary> [Display(Name = "Percent of Gross Pay")] PercentOfGrossPay = 1, /// <summary> /// Deduction is taken as a percentage of the net pay /// </summary> [Display(Name = "Percent of Net Pay")] PercentOfNetPay = 2, /// <summary> /// Deduction is taken as a flat, fixed amount /// </summary> [Display(Name = "Fixed Amount")] FixedAmount = 3, /// <summary> /// Deduction is taken as a fixed amount per hour of work /// </summary> [Display(Name = "Fixed Hourly Amount")] FixedHourlyAmount = 4 } public static class CalculationTypes { public static IEnumerable<CalculationType> Values() { yield return CalculationType.PercentOfGrossPay; yield return CalculationType.PercentOfNetPay; yield return CalculationType.FixedAmount; yield return CalculationType.FixedHourlyAmount; } } }
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace CertiPay.Payroll.Common { /// <summary> /// Identifies the method to calculate the result /// </summary> public enum CalculationType : byte { /// <summary> /// Deduction is taken as a percentage of the gross pay /// </summary> [Display(Name = "Percent of Gross Pay")] PercentOfGrossPay = 1, /// <summary> /// Deduction is taken as a percentage of the net pay /// </summary> [Display(Name = "Percent of Net Pay")] PercentOfNetPay = 2, /// <summary> /// Deduction is taken as a flat, fixed amount /// </summary> [Display(Name = "Fixed Amount")] FixedAmount = 3, /// <summary> /// Deduction is taken as a fixed amount per hour of work /// </summary> [Display(Name = "Fixed Hourly Amount")] FixedHourlyAmount = 4, /// <summary> /// Deduction is taken as a percentage of the disposible income (gross pay - payroll taxes) /// </summary> PercentOfDisposibleIncome } public static class CalculationTypes { public static IEnumerable<CalculationType> Values() { yield return CalculationType.PercentOfGrossPay; yield return CalculationType.PercentOfNetPay; yield return CalculationType.FixedAmount; yield return CalculationType.FixedHourlyAmount; yield return CalculationType.PercentOfDisposibleIncome; } } }
Add calc method for disposible income
Add calc method for disposible income
C#
mit
mattgwagner/CertiPay.Payroll.Common
93a1aeb3f8f155921dc8aa3514b7e8065fdfd797
DrawShip.Viewer/Program.cs
DrawShip.Viewer/Program.cs
using System; using System.Windows.Forms; namespace DrawShip.Viewer { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { var applicationContext = new ApplicationContext(); var runMode = applicationContext.GetRunMode(); runMode.Run(applicationContext); } } }
using System; using System.Net; using System.Windows.Forms; namespace DrawShip.Viewer { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; var applicationContext = new ApplicationContext(); var runMode = applicationContext.GetRunMode(); runMode.Run(applicationContext); } } }
Support invalid certificates (e.g. if Fiddler is in use) and more security protocols (adds Tls1.1 and Tls1.2)
Support invalid certificates (e.g. if Fiddler is in use) and more security protocols (adds Tls1.1 and Tls1.2)
C#
apache-2.0
laingsimon/draw-ship,laingsimon/draw-ship
d7ab964824edd4681dc5fddfdaf78fae592e8053
Nodejs/Product/Npm/PackageComparer.cs
Nodejs/Product/Npm/PackageComparer.cs
//*********************************************************// // Copyright (c) Microsoft. All rights reserved. // // Apache 2.0 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.Collections.Generic; namespace Microsoft.NodejsTools.Npm { public class PackageComparer : IComparer<IPackage> { public int Compare(IPackage x, IPackage y) { if (x == y) { return 0; } else if (null == x) { return -1; } else if (null == y) { return 1; } // TODO: should take into account versions! return x.Name.CompareTo(y.Name); } } }
//*********************************************************// // Copyright (c) Microsoft. All rights reserved. // // Apache 2.0 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.Collections.Generic; namespace Microsoft.NodejsTools.Npm { public class PackageComparer : IComparer<IPackage> { public int Compare(IPackage x, IPackage y) { if (x == y) { return 0; } else if (null == x) { return -1; } else if (null == y) { return 1; } // TODO: should take into account versions! return x.Name.CompareTo(y.Name); } } public class PackageEqualityComparer : EqualityComparer<IPackage> { public override bool Equals(IPackage p1, IPackage p2) { return p1.Name == p2.Name && p1.Version == p2.Version && p1.IsBundledDependency == p2.IsBundledDependency && p1.IsDevDependency == p2.IsDevDependency && p1.IsListedInParentPackageJson == p2.IsListedInParentPackageJson && p1.IsMissing == p2.IsMissing && p1.IsOptionalDependency == p2.IsOptionalDependency; } public override int GetHashCode(IPackage obj) { if (obj.Name == null || obj.Version == null) return obj.GetHashCode(); return obj.Name.GetHashCode() ^ obj.Version.GetHashCode(); } } }
Split out package equality comparer
Split out package equality comparer
C#
apache-2.0
lukedgr/nodejstools,AustinHull/nodejstools,paulvanbrenk/nodejstools,lukedgr/nodejstools,paladique/nodejstools,Microsoft/nodejstools,lukedgr/nodejstools,Microsoft/nodejstools,kant2002/nodejstools,paulvanbrenk/nodejstools,munyirik/nodejstools,avitalb/nodejstools,mousetraps/nodejstools,Microsoft/nodejstools,AustinHull/nodejstools,kant2002/nodejstools,avitalb/nodejstools,paulvanbrenk/nodejstools,paladique/nodejstools,munyirik/nodejstools,paladique/nodejstools,kant2002/nodejstools,kant2002/nodejstools,paladique/nodejstools,Microsoft/nodejstools,avitalb/nodejstools,munyirik/nodejstools,lukedgr/nodejstools,kant2002/nodejstools,avitalb/nodejstools,mjbvz/nodejstools,AustinHull/nodejstools,munyirik/nodejstools,mousetraps/nodejstools,paulvanbrenk/nodejstools,mjbvz/nodejstools,mjbvz/nodejstools,lukedgr/nodejstools,mjbvz/nodejstools,mousetraps/nodejstools,paulvanbrenk/nodejstools,mousetraps/nodejstools,mousetraps/nodejstools,munyirik/nodejstools,AustinHull/nodejstools,AustinHull/nodejstools,avitalb/nodejstools,Microsoft/nodejstools,mjbvz/nodejstools,paladique/nodejstools
ec5e571533fd466c3ea865c7d50fc182e19bd46b
Sketchball/GameComponents/SoundManager.cs
Sketchball/GameComponents/SoundManager.cs
using System; using System.Collections.Generic; using System.Linq; using System.Media; using System.Text; using System.Threading.Tasks; namespace Sketchball.GameComponents { public class SoundManager { private SoundPlayer currentPlayer; private DateTime lastPlay = new DateTime(); /// <summary> /// The minimum interval between to equivalent sounds. /// </summary> private const int MIN_INTERVAL = 400; public void Play(SoundPlayer player) { DateTime now = DateTime.Now; if (currentPlayer != player || (now - lastPlay).TotalMilliseconds > MIN_INTERVAL) { if (currentPlayer != null) currentPlayer.Stop(); currentPlayer = player; currentPlayer.Play(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Media; using System.Text; using System.Threading.Tasks; namespace Sketchball.GameComponents { public class SoundManager { private SoundPlayer currentPlayer; private DateTime lastPlay = new DateTime(); /// <summary> /// The minimum interval between to equivalent sounds. /// </summary> private const int MIN_INTERVAL = 200; public void Play(SoundPlayer player) { DateTime now = DateTime.Now; if (currentPlayer != player || (now - lastPlay).TotalMilliseconds > MIN_INTERVAL) { if (currentPlayer != null) currentPlayer.Stop(); currentPlayer = player; currentPlayer.Play(); lastPlay = now; } } } }
Fix soundmanager (forgot to record time)
Fix soundmanager (forgot to record time)
C#
mit
EusthEnoptEron/Sketchball
2c1a47552b7a69bd366d32f586a5a68393692623
Rusty/Core/Common/Misc.cs
Rusty/Core/Common/Misc.cs
using System; using System.Diagnostics; namespace IronAHK.Rusty { partial class Core { #region Disk static string[] Glob(string pattern) { return new string[] { }; } #endregion #region Process static Process FindProcess(string name) { int id; if (int.TryParse(name, out id)) return System.Diagnostics.Process.GetProcessById(id); var prc = System.Diagnostics.Process.GetProcessesByName(name); return prc.Length > 0 ? prc[0] : null; } #endregion #region Text static string NormaliseEol(string text, string eol = null) { const string CR = "\r", LF = "\n", CRLF = "\r\n"; eol = eol ?? Environment.NewLine; switch (eol) { case CR: return text.Replace(CRLF, CR).Replace(LF, CR); case LF: return text.Replace(CRLF, LF).Replace(CR, LF); case CRLF: return text.Replace(CR, string.Empty).Replace(LF, CRLF); } return text; } #endregion } }
using System; using System.Diagnostics; namespace IronAHK.Rusty { partial class Core { #region Disk static string[] Glob(string pattern) { return new string[] { }; } #endregion #region Process static Process FindProcess(string name) { int id; if (int.TryParse(name, out id)) return System.Diagnostics.Process.GetProcessById(id); const string exe = ".exe"; if (name.EndsWith(exe, StringComparison.OrdinalIgnoreCase)) name = name.Substring(0, name.Length - exe.Length); var prc = System.Diagnostics.Process.GetProcessesByName(name); return prc.Length > 0 ? prc[0] : null; } #endregion #region Text static string NormaliseEol(string text, string eol = null) { const string CR = "\r", LF = "\n", CRLF = "\r\n"; eol = eol ?? Environment.NewLine; switch (eol) { case CR: return text.Replace(CRLF, CR).Replace(LF, CR); case LF: return text.Replace(CRLF, LF).Replace(CR, LF); case CRLF: return text.Replace(CR, string.Empty).Replace(LF, CRLF); } return text; } #endregion } }
Remove trailing .exe in process name.
Remove trailing .exe in process name.
C#
bsd-2-clause
michaltakac/IronAHK,yatsek/IronAHK,polyethene/IronAHK,michaltakac/IronAHK,michaltakac/IronAHK,michaltakac/IronAHK,polyethene/IronAHK,yatsek/IronAHK,polyethene/IronAHK,polyethene/IronAHK,michaltakac/IronAHK,yatsek/IronAHK,yatsek/IronAHK,yatsek/IronAHK
15e8317021fdbbe6278847c1c35b87622c47e979
CORS/Controllers/ValuesController.cs
CORS/Controllers/ValuesController.cs
using System.Collections.Generic; using System.Web.Http; using System.Web.Http.Cors; namespace CORS.Controllers { public class ValuesController : ApiController { // GET api/values public IEnumerable<string> Get() { return new string[] { "This is a CORS request.", "That works from any origin." }; } // GET api/values/another [HttpGet] [EnableCors(origins:"http://www.bigfont.ca", headers:"*", methods: "*")] public IEnumerable<string> Another() { return new string[] { "This is a CORS request.", "It works only from www.bigfont.ca." }; } } }
using System.Collections.Generic; using System.Web.Http; using System.Web.Http.Cors; namespace CORS.Controllers { public class ValuesController : ApiController { // GET api/values public IEnumerable<string> Get() { return new string[] { "This is a CORS response.", "It works from any origin." }; } // GET api/values/another [HttpGet] [EnableCors(origins:"http://www.bigfont.ca", headers:"*", methods: "*")] public IEnumerable<string> Another() { return new string[] { "This is a CORS response.", "It works only from www.bigfont.ca AND from the same origin." }; } } }
Use the term response instead of request.
Use the term response instead of request.
C#
mit
bigfont/webapi-cors
c0d9e1891ab392cc80da5e794fdd8fe36d20f12d
src/WebPackAngular2TypeScript/Routing/DeepLinkingMiddleware.cs
src/WebPackAngular2TypeScript/Routing/DeepLinkingMiddleware.cs
using Microsoft.AspNet.Builder; using Microsoft.AspNet.Hosting; using Microsoft.AspNet.Http; using Microsoft.AspNet.StaticFiles; using Microsoft.Extensions.Logging; using System.Threading.Tasks; namespace WebPackAngular2TypeScript.Routing { public class DeepLinkingMiddleware { public DeepLinkingMiddleware(RequestDelegate next, IHostingEnvironment hostingEnv, ILoggerFactory loggerFactory, DeepLinkingOptions options) { this.next = next; this.options = options; staticFileMiddleware = new StaticFileMiddleware(next, hostingEnv, options.FileServerOptions.StaticFileOptions, loggerFactory); } public async Task Invoke(HttpContext context) { // try to resolve the request with default static file middleware await staticFileMiddleware.Invoke(context); if (context.Response.StatusCode == 404) { var redirectUrlPath = FindRedirection(context); if (redirectUrlPath != unresolvedPath) { context.Request.Path = redirectUrlPath; await staticFileMiddleware.Invoke(context); } } } protected virtual PathString FindRedirection(HttpContext context) { // route to root path when request was not resolved return options.RedirectUrlPath; } protected readonly DeepLinkingOptions options; protected readonly RequestDelegate next; protected readonly StaticFileMiddleware staticFileMiddleware; protected readonly PathString unresolvedPath = null; } }
using Microsoft.AspNet.Builder; using Microsoft.AspNet.Hosting; using Microsoft.AspNet.Http; using Microsoft.AspNet.StaticFiles; using Microsoft.Extensions.Logging; using System.Threading.Tasks; namespace WebPackAngular2TypeScript.Routing { public class DeepLinkingMiddleware { public DeepLinkingMiddleware(RequestDelegate next, IHostingEnvironment hostingEnv, ILoggerFactory loggerFactory, DeepLinkingOptions options) { this.next = next; this.options = options; staticFileMiddleware = new StaticFileMiddleware(next, hostingEnv, options.FileServerOptions.StaticFileOptions, loggerFactory); } public async Task Invoke(HttpContext context) { // try to resolve the request with default static file middleware await staticFileMiddleware.Invoke(context); if (context.Response.StatusCode == StatusCodes.Status404NotFound) { var redirectUrlPath = FindRedirection(context); if (redirectUrlPath != unresolvedPath) { // if resolved, reset response as successful context.Response.StatusCode = StatusCodes.Status200OK; context.Request.Path = redirectUrlPath; await staticFileMiddleware.Invoke(context); } } } protected virtual PathString FindRedirection(HttpContext context) { // route to root path when request was not resolved return options.RedirectUrlPath; } protected readonly DeepLinkingOptions options; protected readonly RequestDelegate next; protected readonly StaticFileMiddleware staticFileMiddleware; protected readonly PathString unresolvedPath = null; } }
Fix spurious 404 response when deep linking to a client route
Fix spurious 404 response when deep linking to a client route
C#
mit
BrainCrumbz/AWATTS,BrainCrumbz/AWATTS,BrainCrumbz/AWATTS,BrainCrumbz/AWATTS
69bf905ab7fd223a356a9f80a3280dcb7657bf25
src/Dashboard/Views/BadConfig/Index.cshtml
src/Dashboard/Views/BadConfig/Index.cshtml
@using Dashboard @using Microsoft.WindowsAzure.Jobs @{ ViewBag.Title = "Configuration Error"; } <h2>Bad Config</h2> <p> The configuration is not properly set for the Windows Azure Web Jobs SDK Dashboard. In your configuration (such as web.config), you must set a connection string named <i>@JobHost.LoggingConnectionStringName</i> that points to the account connection string where the sb logs are being stored. EG, under "connectionStrings" in Web.config, add a value like: </p> <pre> &lt;add name="@JobHost.LoggingConnectionStringName" value="DefaultEndpointsProtocol=https;AccountName=<b>NAME</b>;AccountKey=<b>KEY</b>" /&gt; </pre> <p> This is the storage account that your user functions will bind against. This is also where logging will be stored. </p> <p class="alert alert-danger">@SimpleBatchStuff.BadInitErrorMessage</p>
@using Dashboard @using Microsoft.WindowsAzure.Jobs @{ ViewBag.Title = "Configuration Error"; } <h2>Bad Config</h2> <p> The configuration is not properly set for the Windows Azure Web Jobs SDK Dashboard. In your configuration (such as web.config), you must set a connection string named <i>@JobHost.LoggingConnectionStringName</i> that points to the account connection string where the sb logs are being stored. EG, under "connectionStrings" in Web.config, add a value like: </p> <pre> &lt;add name="@JobHost.LoggingConnectionStringName" connectionString="DefaultEndpointsProtocol=https;AccountName=<b>NAME</b>;AccountKey=<b>KEY</b>" /&gt; </pre> <p> This is the storage account that your user functions will bind against. This is also where logging will be stored. </p> <p class="alert alert-danger">@SimpleBatchStuff.BadInitErrorMessage</p>
Fix connectionStrings section attribute in BadConfig doc page
Fix connectionStrings section attribute in BadConfig doc page
C#
mit
vasanthangel4/azure-webjobs-sdk,Azure/azure-webjobs-sdk,shrishrirang/azure-webjobs-sdk,Azure/azure-webjobs-sdk,gibwar/azure-webjobs-sdk,vasanthangel4/azure-webjobs-sdk,brendankowitz/azure-webjobs-sdk,oliver-feng/azure-webjobs-sdk,shrishrirang/azure-webjobs-sdk,brendankowitz/azure-webjobs-sdk,shrishrirang/azure-webjobs-sdk,vasanthangel4/azure-webjobs-sdk,brendankowitz/azure-webjobs-sdk,oaastest/azure-webjobs-sdk,oliver-feng/azure-webjobs-sdk,gibwar/azure-webjobs-sdk,oliver-feng/azure-webjobs-sdk,oaastest/azure-webjobs-sdk,gibwar/azure-webjobs-sdk,oaastest/azure-webjobs-sdk
a9dfe2065a6fd456e3ffe306b046a3a08890231f
RepoZ.UI.Mac.Story/StringCommandHandler.cs
RepoZ.UI.Mac.Story/StringCommandHandler.cs
using System; using System.Text; using System.Collections.Generic; using System.Linq; namespace RepoZ.UI.Mac.Story { public class StringCommandHandler { private Dictionary<string, Action> _commands = new Dictionary<string, Action>(); private StringBuilder _helpBuilder = new StringBuilder(); internal bool IsCommand(string value) { return value?.StartsWith(":") == true; } internal bool Handle(string command) { if (_commands.TryGetValue(CleanCommand(command), out Action commandAction)) { commandAction.Invoke(); return true; } return false; } internal void Define(string[] commands, Action commandAction, string helpText) { foreach (var command in commands) _commands[CleanCommand(command)] = commandAction; if (_helpBuilder.Length > 0) _helpBuilder.AppendLine(""); _helpBuilder.AppendLine(string.Join(", ", commands.OrderBy(c => c))); _helpBuilder.AppendLine("\t"+ helpText); } private string CleanCommand(string command) { command = command?.Trim().ToLower() ?? ""; return command.StartsWith(":", StringComparison.OrdinalIgnoreCase) ? command.Substring(1) : command; } internal string GetHelpText() => _helpBuilder.ToString(); } }
using System; using System.Text; using System.Collections.Generic; using System.Linq; namespace RepoZ.UI.Mac.Story { public class StringCommandHandler { private Dictionary<string, Action> _commands = new Dictionary<string, Action>(); private StringBuilder _helpBuilder = new StringBuilder(); internal bool IsCommand(string value) { return value?.StartsWith(":") == true; } internal bool Handle(string command) { if (_commands.TryGetValue(CleanCommand(command), out Action commandAction)) { commandAction.Invoke(); return true; } return false; } internal void Define(string[] commands, Action commandAction, string helpText) { foreach (var command in commands) _commands[CleanCommand(command)] = commandAction; if (_helpBuilder.Length == 0) { _helpBuilder.AppendLine("To execute a command instead of filtering the list of repositories, simply begin with a colon (:)."); _helpBuilder.AppendLine(""); _helpBuilder.AppendLine("Command reference:"); } _helpBuilder.AppendLine(""); _helpBuilder.AppendLine("\t:" + string.Join(" or :", commands.OrderBy(c => c))); _helpBuilder.AppendLine("\t\t"+ helpText); } private string CleanCommand(string command) { command = command?.Trim().ToLower() ?? ""; return command.StartsWith(":", StringComparison.OrdinalIgnoreCase) ? command.Substring(1) : command; } internal string GetHelpText() => _helpBuilder.ToString(); } }
Enhance the Mac command reference text a bit
Enhance the Mac command reference text a bit
C#
mit
awaescher/RepoZ,awaescher/RepoZ
356e0f42d34cd5ff11767f8f584ead235aa8bc0e
Source/Controllers/MailController.cs
Source/Controllers/MailController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using ActionMailer.Net.Mvc; using RationalVote.Models; using System.Configuration; namespace RationalVote.Controllers { public class MailController : MailerBase { public static string GetFromEmail( string purpose ) { return String.Format( "\"{0} {1}\" <{2}>", ConfigurationManager.AppSettings.Get("siteTitle"), purpose, ConfigurationManager.AppSettings.Get("emailFrom") ); } public EmailResult VerificationEmail( User model, EmailVerificationToken token ) { To.Add( model.Email ); From = GetFromEmail( "Verification" ); Subject = "Please verify your account"; ViewBag.Token = token.Token; return Email( "VerificationEmail" ); } public EmailResult ExceptionEmail( HttpException e, string message ) { To.Add( ConfigurationManager.AppSettings.Get( "ServerAdmin" ) ); From = GetFromEmail( "Exception" ); Subject = "Site exception - " + message; ViewBag.Exception = e.ToString(); return Email( "ExceptionEmail" ); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using ActionMailer.Net.Mvc; using RationalVote.Models; using System.Configuration; namespace RationalVote.Controllers { public class MailController : MailerBase { public static string GetFromEmail( string purpose ) { return String.Format( "\"{0} {1}\" <{2}>", ConfigurationManager.AppSettings.Get("siteTitle"), purpose, ConfigurationManager.AppSettings.Get("emailFrom") ); } public EmailResult VerificationEmail( User model, EmailVerificationToken token ) { To.Add( model.Email ); From = GetFromEmail( "Verification" ); Subject = "Please verify your account"; ViewBag.Token = token.Token; return Email( "VerificationEmail" ); } public EmailResult ExceptionEmail( HttpException e, string message ) { To.Add( ConfigurationManager.AppSettings.Get( "ServerAdmin" ) ); From = GetFromEmail( "Exception" ); Subject = ConfigurationManager.AppSettings.Get("siteTitle") + " exception - " + message; ViewBag.Exception = e.ToString(); return Email( "ExceptionEmail" ); } } }
Use site title in email subject for exception handler.
Use site title in email subject for exception handler.
C#
mit
IanNorris/RationalVote,IanNorris/RationalVote
50e741ea0b59cc94d6e43d4939676906576718a2
test/InfoCarrier.Core.EFCore.FunctionalTests/BuiltInDataTypesInfoCarrierTest.cs
test/InfoCarrier.Core.EFCore.FunctionalTests/BuiltInDataTypesInfoCarrierTest.cs
namespace InfoCarrier.Core.EFCore.FunctionalTests { using Microsoft.EntityFrameworkCore.Specification.Tests; using Xunit; public class BuiltInDataTypesInfoCarrierTest : BuiltInDataTypesTestBase<BuiltInDataTypesInfoCarrierFixture> { public BuiltInDataTypesInfoCarrierTest(BuiltInDataTypesInfoCarrierFixture fixture) : base(fixture) { } [Fact] public virtual void Can_perform_query_with_ansi_strings() { this.Can_perform_query_with_ansi_strings(supportsAnsi: false); } } }
namespace InfoCarrier.Core.EFCore.FunctionalTests { using System.Linq; using Microsoft.EntityFrameworkCore.Specification.Tests; using Xunit; public class BuiltInDataTypesInfoCarrierTest : BuiltInDataTypesTestBase<BuiltInDataTypesInfoCarrierFixture> { public BuiltInDataTypesInfoCarrierTest(BuiltInDataTypesInfoCarrierFixture fixture) : base(fixture) { } [Fact] public virtual void Can_perform_query_with_ansi_strings() { this.Can_perform_query_with_ansi_strings(supportsAnsi: false); } [Fact] public override void Can_perform_query_with_max_length() { // UGLY: this is a complete copy-n-paste of // https://github.com/aspnet/EntityFramework/blob/rel/1.1.0/src/Microsoft.EntityFrameworkCore.Specification.Tests/BuiltInDataTypesTestBase.cs#L25 // We only use SequenceEqual instead of operator== for comparison of arrays. var shortString = "Sky"; var shortBinary = new byte[] { 8, 8, 7, 8, 7 }; var longString = new string('X', 9000); var longBinary = new byte[9000]; for (var i = 0; i < longBinary.Length; i++) { longBinary[i] = (byte)i; } using (var context = this.CreateContext()) { context.Set<MaxLengthDataTypes>().Add( new MaxLengthDataTypes { Id = 799, String3 = shortString, ByteArray5 = shortBinary, String9000 = longString, ByteArray9000 = longBinary }); Assert.Equal(1, context.SaveChanges()); } using (var context = this.CreateContext()) { Assert.NotNull(context.Set<MaxLengthDataTypes>().SingleOrDefault(e => e.Id == 799 && e.String3 == shortString)); Assert.NotNull(context.Set<MaxLengthDataTypes>().SingleOrDefault(e => e.Id == 799 && e.ByteArray5.SequenceEqual(shortBinary))); Assert.NotNull(context.Set<MaxLengthDataTypes>().SingleOrDefault(e => e.Id == 799 && e.String9000 == longString)); Assert.NotNull(context.Set<MaxLengthDataTypes>().SingleOrDefault(e => e.Id == 799 && e.ByteArray9000.SequenceEqual(longBinary))); } } } }
Use SequenceEqual instead of operator== for comparison of arrays in 'Can_perform_query_with_max_length' test
Use SequenceEqual instead of operator== for comparison of arrays in 'Can_perform_query_with_max_length' test
C#
mit
azabluda/InfoCarrier.Core
d5b8ccf222f8bfeb7c9d54a85c4e4f82f949421e
auth0/04-Calling-API/server/src/WebAPIApplication/Controllers/ValuesController.cs
auth0/04-Calling-API/server/src/WebAPIApplication/Controllers/ValuesController.cs
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; namespace WebAPIApplication.Controllers { [Route("api/[controller]")] public class ValuesController : Controller { [HttpGet] [Route("ping")] public string Ping() { return "All good. You don't need to be authenticated to call this."; } [Authorize] [HttpGet] [Route("secured/ping")] public string PingSecured() { return "All good. You only get this message if you are authenticated."; } } }
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; namespace WebAPIApplication.Controllers { [Route("api/[controller]")] public class ValuesController : Controller { [HttpGet] [Route("ping")] public dynamic Ping() { return new { message = "All good. You don't need to be authenticated to call this." }; } [Authorize] [HttpGet] [Route("secured/ping")] public object PingSecured() { return new { message = "All good. You only get this message if you are authenticated." }; } } }
Return JSON object from Values controller
Return JSON object from Values controller
C#
unlicense
peterblazejewicz/ng-templates,peterblazejewicz/ng-templates,peterblazejewicz/ng-templates,peterblazejewicz/ng-templates
234224e8d93a6c9ebc7e4532206d79677db2de6c
src/Scriban/Syntax/ScriptCaptureStatement.cs
src/Scriban/Syntax/ScriptCaptureStatement.cs
// Copyright (c) Alexandre Mutel. All rights reserved. // Licensed under the BSD-Clause 2 license. // See license.txt file in the project root for full license information. using Scriban.Runtime; namespace Scriban.Syntax { [ScriptSyntax("capture statement", "capture <variable> ... end")] public class ScriptCaptureStatement : ScriptStatement { public ScriptExpression Target { get; set; } public ScriptBlockStatement Body { get; set; } public override object Evaluate(TemplateContext context) { // unit test: 230-capture-statement.txt context.PushOutput(); { context.Evaluate(Body); } var result = context.PopOutput(); context.SetValue(Target, result); return null; } } }
// Copyright (c) Alexandre Mutel. All rights reserved. // Licensed under the BSD-Clause 2 license. // See license.txt file in the project root for full license information. using Scriban.Runtime; namespace Scriban.Syntax { [ScriptSyntax("capture statement", "capture <variable> ... end")] public class ScriptCaptureStatement : ScriptStatement { public ScriptExpression Target { get; set; } public ScriptBlockStatement Body { get; set; } public override object Evaluate(TemplateContext context) { // unit test: 230-capture-statement.txt context.PushOutput(); try { context.Evaluate(Body); } finally { var result = context.PopOutput(); context.SetValue(Target, result); } return null; } } }
Make sure a capture will not leave the TemplateContext in an unbalanced state if an exception occurs
Make sure a capture will not leave the TemplateContext in an unbalanced state if an exception occurs
C#
bsd-2-clause
lunet-io/scriban,textamina/scriban
7a9fe3554d13c42c5e48b320c7c04cc7228c3d92
Properties/AssemblyInfo.cs
Properties/AssemblyInfo.cs
using System.Reflection; [assembly: AssemblyTitle("Autofac.Tests.Configuration")] [assembly: AssemblyDescription("")]
using System.Reflection; [assembly: AssemblyTitle("Autofac.Tests.Configuration")]
Build script now writes the package name and version into the AssemblyDescription attibute. This allows the package information to be seen in Visual Studio avoiding confusion with the assembly version that remains at the major.
Build script now writes the package name and version into the AssemblyDescription attibute. This allows the package information to be seen in Visual Studio avoiding confusion with the assembly version that remains at the major.
C#
mit
jango2015/Autofac.Configuration,autofac/Autofac.Configuration
3c19009759bc19fb90dc0af5b8a981d845537c33
Properties/AssemblyInfo.cs
Properties/AssemblyInfo.cs
using System.Reflection; [assembly: AssemblyTitle("Autofac.Tests.Integration.Mvc")] [assembly: AssemblyDescription("")]
using System.Reflection; [assembly: AssemblyTitle("Autofac.Tests.Integration.Mvc")]
Build script now writes the package name and version into the AssemblyDescription attibute. This allows the package information to be seen in Visual Studio avoiding confusion with the assembly version that remains at the major.
Build script now writes the package name and version into the AssemblyDescription attibute. This allows the package information to be seen in Visual Studio avoiding confusion with the assembly version that remains at the major.
C#
mit
dparra0007/Autofac.Mvc,autofac/Autofac.Mvc,jango2015/Autofac.Mvc
932d6658a47d4d0926a9219353b090dcbb2a1ff0
src/SFA.DAS.EmployerFinance.Api/Startup.cs
src/SFA.DAS.EmployerFinance.Api/Startup.cs
using System.Configuration; using Microsoft.Owin; using Microsoft.Owin.Security.ActiveDirectory; using Owin; using SFA.DAS.EmployerFinance.Api; [assembly: OwinStartup(typeof(Startup))] namespace SFA.DAS.EmployerFinance.Api { public class Startup { public void Configuration(IAppBuilder app) { _ = app.UseWindowsAzureActiveDirectoryBearerAuthentication(new WindowsAzureActiveDirectoryBearerAuthenticationOptions { Tenant = ConfigurationManager.AppSettings["idaTenant"], TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters { RoleClaimType = "http://schemas.microsoft.com/ws/2008/06/identity/claims/role", ValidAudiences = ConfigurationManager.AppSettings["FinanceApiIdentifierUri"].ToString().Split(',') } }); } } }
using System.Configuration; using Microsoft.Owin; using Microsoft.Owin.Security.ActiveDirectory; using Owin; using SFA.DAS.EmployerFinance.Api; [assembly: OwinStartup(typeof(Startup))] namespace SFA.DAS.EmployerFinance.Api { public class Startup { public void Configuration(IAppBuilder app) { _ = app.UseWindowsAzureActiveDirectoryBearerAuthentication(new WindowsAzureActiveDirectoryBearerAuthenticationOptions { Tenant = ConfigurationManager.AppSettings["idaTenant"], TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters { RoleClaimType = "http://schemas.microsoft.com/ws/2008/06/identity/claims/role", ValidAudiences = ConfigurationManager.AppSettings["FinanceApiIdaAudience"].ToString().Split(',') } }); } } }
Rename app setting for finance api audiences
Rename app setting for finance api audiences
C#
mit
SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice
71c703ad6c1058edf6146a1af5f9f5c655eb7b57
source/CroquetAustraliaWebsite.Application/app/Infrastructure/PublicNavigationBar.cs
source/CroquetAustraliaWebsite.Application/app/Infrastructure/PublicNavigationBar.cs
using System.Collections.Generic; namespace CroquetAustraliaWebsite.Application.App.Infrastructure { public static class PublicNavigationBar { public static IEnumerable<NavigationItem> GetNavigationItems() { return new[] { new NavigationItem("Contact Us", new NavigationItem("Office & Board", "~/governance/contact-us"), new NavigationItem("Committees", "~/governance/contact-us#committees"), new NavigationItem("Appointed Officers", "~/governance/contact-us#appointed-officers"), new NavigationItem("State Associations", "~/governance/state-associations")), new NavigationItem("Governance", new NavigationItem("Background", "~/governance/background"), new NavigationItem("Constitution, Regulations & Policies", "~/governance/constitution-regulations-and-policies"), new NavigationItem("Members", "~/governance/members")), new NavigationItem("Tournaments", "~/tournaments"), new NavigationItem("Disciplines", new NavigationItem("Association Croquet", new NavigationItem("Coaching", "~/disciplines/association-croquet/coaching"), new NavigationItem("Refereeing", "~/disciplines/association-croquet/refereeing")), new NavigationItem("Golf Croquet", new NavigationItem("Coaching", "~/disciplines/golf-croquet/coaching"), new NavigationItem("Refereeing", "~/disciplines/golf-croquet/refereeing"), new NavigationItem("Resources", "~/disciplines/golf-croquet/resources"))) }; } } }
using System.Collections.Generic; namespace CroquetAustraliaWebsite.Application.App.Infrastructure { public static class PublicNavigationBar { public static IEnumerable<NavigationItem> GetNavigationItems() { return new[] { new NavigationItem("Contact Us", new NavigationItem("Office & Board", "~/governance/contact-us"), new NavigationItem("Committees", "~/governance/contact-us#committees"), new NavigationItem("Appointed Officers", "~/governance/contact-us#appointed-officers"), new NavigationItem("State Associations", "~/governance/state-associations")), new NavigationItem("Governance", new NavigationItem("Background", "~/governance/background"), new NavigationItem("Constitution, Regulations & Policies", "~/governance/constitution-regulations-and-policies"), new NavigationItem("Members", "~/governance/members"), new NavigationItem("Board Meeting Minutes", "~/governance/minutes/board-meeting-minutes")), new NavigationItem("Tournaments", "~/tournaments"), new NavigationItem("Disciplines", new NavigationItem("Association Croquet", new NavigationItem("Coaching", "~/disciplines/association-croquet/coaching"), new NavigationItem("Refereeing", "~/disciplines/association-croquet/refereeing")), new NavigationItem("Golf Croquet", new NavigationItem("Coaching", "~/disciplines/golf-croquet/coaching"), new NavigationItem("Refereeing", "~/disciplines/golf-croquet/refereeing"), new NavigationItem("Resources", "~/disciplines/golf-croquet/resources"))) }; } } }
Add 'Board Meeting Minutes' to navigation bar
Add 'Board Meeting Minutes' to navigation bar
C#
mit
croquet-australia/croquet-australia.com.au,croquet-australia/croquet-australia.com.au,croquet-australia/croquet-australia-website,croquet-australia/croquet-australia.com.au,croquet-australia/website-application,croquet-australia/website-application,croquet-australia/croquet-australia-website,croquet-australia/website-application,croquet-australia/croquet-australia-website,croquet-australia/croquet-australia-website,croquet-australia/croquet-australia.com.au,croquet-australia/website-application
5d964a0fb8abd58aa30759fc69c391febaf502b2
Abc.NCrafts.Quizz/Performance/Questions/028/Answer1.cs
Abc.NCrafts.Quizz/Performance/Questions/028/Answer1.cs
using System; using System.Linq; namespace Abc.NCrafts.Quizz.Performance.Questions._028 { [CorrectAnswer(Difficulty = Difficulty.Medium)] public class Answer1 { public static void Run() { // begin var primes = Enumerable.Range(0, 10 * 1000) .Where(IsPrime) .ToList(); // end Logger.Log("Primes: {0}", primes.Count); } private static bool IsPrime(int number) { if (number == 0 || number == 1) return false; if (number == 2) return true; for (var divisor = 2; divisor < (int)Math.Sqrt(number); divisor++) { if (number % divisor == 0) return false; } return true; } } }
using System; using System.Linq; namespace Abc.NCrafts.Quizz.Performance.Questions._028 { [CorrectAnswer(Difficulty = Difficulty.Medium)] public class Answer1 { public static void Run() { // begin var primes = Enumerable.Range(0, 10 * 1000) .Where(IsPrime) .ToList(); // end Logger.Log("Primes: {0}", primes.Count); } private static bool IsPrime(int number) { if (number == 0 || number == 1) return false; if (number == 2) return true; for (var divisor = 2; divisor <= (int)Math.Sqrt(number); divisor++) { if (number % divisor == 0) return false; } return true; } } }
Fix answer 28 to include square roots in prime test
Fix answer 28 to include square roots in prime test
C#
mit
Abc-Arbitrage/Abc.NCrafts.AllocationQuiz
558f8172e487d62acceca5b87da241bfceb11ea2
tests/SocksSharp.Tests/ProxyClientTests.cs
tests/SocksSharp.Tests/ProxyClientTests.cs
using System; using System.Diagnostics; using Microsoft.Extensions.Configuration; using Xunit; using SocksSharp; using SocksSharp.Proxy; namespace SocksSharp.Tests { public class ProxyClientTests { private ProxySettings proxySettings; private void GatherTestConfiguration() { var appConfigMsgWarning = "{0} not configured in proxysettings.json! Some tests may fail."; var builder = new ConfigurationBuilder() .AddJsonFile("proxysettings.json") .Build(); proxySettings = new ProxySettings(); var host = builder["host"]; if (String.IsNullOrEmpty(host)) { Debug.WriteLine(String.Format(appConfigMsgWarning, nameof(host))); } else { proxySettings.Host = host; } var port = builder["port"]; if (String.IsNullOrEmpty(port)) { Debug.WriteLine(String.Format(appConfigMsgWarning, nameof(port))); } else { proxySettings.Port = Int32.Parse(port); } //TODO: Setup manualy var username = builder["username"]; var password = builder["password"]; } private ProxyClientHandler<Socks5> CreateNewSocks5Client() { if(proxySettings.Host == null || proxySettings.Port == 0) { throw new Exception("Please add your proxy settings to proxysettings.json!"); } return new ProxyClientHandler<Socks5>(proxySettings); } [Fact] public void Test1() { } } }
using System; using System.Diagnostics; using Microsoft.Extensions.Configuration; using Xunit; using SocksSharp; using SocksSharp.Proxy; namespace SocksSharp.Tests { public class ProxyClientTests { private Uri baseUri = new Uri("http://httpbin.org/"); private ProxySettings proxySettings; private void GatherTestConfiguration() { var appConfigMsgWarning = "{0} not configured in proxysettings.json! Some tests may fail."; var builder = new ConfigurationBuilder() .AddJsonFile("proxysettings.json") .Build(); proxySettings = new ProxySettings(); var host = builder["host"]; if (String.IsNullOrEmpty(host)) { Debug.WriteLine(String.Format(appConfigMsgWarning, nameof(host))); } else { proxySettings.Host = host; } var port = builder["port"]; if (String.IsNullOrEmpty(port)) { Debug.WriteLine(String.Format(appConfigMsgWarning, nameof(port))); } else { proxySettings.Port = Int32.Parse(port); } //TODO: Setup manualy var username = builder["username"]; var password = builder["password"]; } private ProxyClientHandler<Socks5> CreateNewSocks5Client() { if(proxySettings.Host == null || proxySettings.Port == 0) { throw new Exception("Please add your proxy settings to proxysettings.json!"); } return new ProxyClientHandler<Socks5>(proxySettings); } [Fact] public void Test1() { } } }
Add base uri to tests
Add base uri to tests
C#
mit
extremecodetv/SocksSharp
cab75b4de0a28a59043ee989b6e0f6ebbde50d44
Cogito.Composition/ExportOrderAttribute.cs
Cogito.Composition/ExportOrderAttribute.cs
using System; using System.ComponentModel.Composition; namespace Cogito.Composition { /// <summary> /// Attaches an Order metadata property to the export. /// </summary> [MetadataAttribute] public class ExportOrderAttribute : Attribute { readonly int order; /// <summary> /// Initializes a new instance. /// </summary> /// <param name="order"></param> /// <returns></returns> public ExportOrderAttribute(int order) { Priority = order; } public int Priority { get; set; } } }
using System; using System.ComponentModel.Composition; namespace Cogito.Composition { /// <summary> /// Attaches an Order metadata property to the export. /// </summary> [MetadataAttribute] public class ExportOrderAttribute : Attribute, IOrderedExportMetadata { /// <summary> /// Initializes a new instance. /// </summary> /// <param name="order"></param> /// <returns></returns> public ExportOrderAttribute(int order) { Order = order; } public int Order { get; set; } } }
Check Azure configuration more carefully. Add contracts for some base classes. Fix ExportOrder.
Check Azure configuration more carefully. Add contracts for some base classes. Fix ExportOrder.
C#
mit
wasabii/Cogito,wasabii/Cogito
988a11fa8cbe4998f678f957af6516ee93faef6d
test/UnitTests/LongExtensionsUnitTests.cs
test/UnitTests/LongExtensionsUnitTests.cs
namespace DarkSky.UnitTests.Extensions { using System; using NodaTime; using Xunit; using static DarkSky.Extensions.LongExtensions; public class LongExtensionsUnitTests { public static System.Collections.Generic.IEnumerable<object[]> GetDateTimeOffsets() { yield return new object[] { DateTimeOffset.MinValue, "UTC" }; yield return new object[] { DateTimeOffset.MaxValue, "UTC" }; yield return new object[] { new DateTimeOffset(2017, 1, 1, 1, 0, 0, new TimeSpan(0)), "UTC" }; yield return new object[] { new ZonedDateTime(Instant.FromUnixTimeSeconds(1499435235), DateTimeZoneProviders.Tzdb["America/New_York"]).ToDateTimeOffset(), "America/New_York" }; } [Theory] [MemberData(nameof(GetDateTimeOffsets))] public void CorrectConversionTest(DateTimeOffset date, string timezone) { // Truncate milliseconds since we don't use them for the UNIX timestamps. var dateTimeOffset = date.AddTicks(-(date.Ticks % TimeSpan.TicksPerSecond)); var convertedDate = dateTimeOffset.ToUnixTimeSeconds().ToDateTimeOffsetFromUnixTimestamp(timezone); Assert.Equal(dateTimeOffset, convertedDate); } } }
namespace DarkSky.UnitTests.Extensions { using System; using NodaTime; using Xunit; using static DarkSky.Extensions.LongExtensions; public class LongExtensionsUnitTests { public static System.Collections.Generic.IEnumerable<object[]> GetDateTimeOffsets() { yield return new object[] { DateTimeOffset.MinValue, "UTC" }; yield return new object[] { DateTimeOffset.MaxValue, "UTC" }; yield return new object[] { new DateTimeOffset(2017, 1, 1, 1, 0, 0, new TimeSpan(0)), "UTC" }; yield return new object[] { new ZonedDateTime(Instant.FromUnixTimeSeconds(1499435235), DateTimeZoneProviders.Tzdb["America/New_York"]).ToDateTimeOffset(), "America/New_York" }; yield return new object[] { new ZonedDateTime(Instant.FromUnixTimeSeconds(1499435235), DateTimeZoneProviders.Tzdb["America/New_York"]).ToDateTimeOffset(), string.Empty }; yield return new object[] { new ZonedDateTime(Instant.FromUnixTimeSeconds(1499435235), DateTimeZoneProviders.Tzdb["America/New_York"]).ToDateTimeOffset(), null }; } [Theory] [MemberData(nameof(GetDateTimeOffsets))] public void CorrectConversionTest(DateTimeOffset date, string timezone) { // Truncate milliseconds since we don't use them for the UNIX timestamps. var dateTimeOffset = date.AddTicks(-(date.Ticks % TimeSpan.TicksPerSecond)); var convertedDate = dateTimeOffset.ToUnixTimeSeconds().ToDateTimeOffsetFromUnixTimestamp(timezone); Assert.Equal(dateTimeOffset, convertedDate); } } }
Add unit test for empty timezone
chore(test): Add unit test for empty timezone
C#
mit
amweiss/dark-sky-core
f43f8cf6b95bebf5c18683acdb0e96a6ff731fb3
osu.Game/Screens/Edit/Setup/SetupScreen.cs
osu.Game/Screens/Edit/Setup/SetupScreen.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. namespace osu.Game.Screens.Edit.Setup { public class SetupScreen : EditorScreen { public SetupScreen() { Child = new ScreenWhiteBox.UnderConstructionMessage("Setup mode"); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Game.Beatmaps.Drawables; using osu.Game.Graphics; using osu.Game.Graphics.Containers; using osu.Game.Graphics.Sprites; using osu.Game.Graphics.UserInterfaceV2; using osuTK; namespace osu.Game.Screens.Edit.Setup { public class SetupScreen : EditorScreen { [BackgroundDependencyLoader] private void load(OsuColour colours) { Children = new Drawable[] { new Box { Colour = colours.Gray0, RelativeSizeAxes = Axes.Both, }, new OsuScrollContainer { RelativeSizeAxes = Axes.Both, Padding = new MarginPadding(50), Child = new FillFlowContainer { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Spacing = new Vector2(20), Direction = FillDirection.Vertical, Children = new Drawable[] { new Container { RelativeSizeAxes = Axes.X, Height = 250, Masking = true, CornerRadius = 50, Child = new BeatmapBackgroundSprite(Beatmap.Value) { RelativeSizeAxes = Axes.Both, FillMode = FillMode.Fill, }, }, new OsuSpriteText { Text = "Beatmap metadata" }, new LabelledTextBox { Label = "Artist", Current = { Value = Beatmap.Value.Metadata.Artist } }, new LabelledTextBox { Label = "Title", Current = { Value = Beatmap.Value.Metadata.Title } }, new LabelledTextBox { Label = "Creator", Current = { Value = Beatmap.Value.Metadata.AuthorString } }, new LabelledTextBox { Label = "Difficulty Name", Current = { Value = Beatmap.Value.BeatmapInfo.Version } }, } }, }, }; } } }
Add basic setup for song select screen
Add basic setup for song select screen
C#
mit
smoogipoo/osu,UselessToucan/osu,peppy/osu,UselessToucan/osu,smoogipooo/osu,NeoAdonis/osu,peppy/osu-new,NeoAdonis/osu,ppy/osu,peppy/osu,smoogipoo/osu,peppy/osu,ppy/osu,ppy/osu,NeoAdonis/osu,UselessToucan/osu,smoogipoo/osu
1319e8a998eabee85285c44d62858c41512f412c
EOLib.IO/Repositories/PubFileRepository.cs
EOLib.IO/Repositories/PubFileRepository.cs
// Original Work Copyright (c) Ethan Moffat 2014-2016 // This file is subject to the GPL v2 License // For additional details, see the LICENSE file using AutomaticTypeMapper; using EOLib.IO.Pub; namespace EOLib.IO.Repositories { [MappedType(BaseType = typeof(IPubFileRepository), IsSingleton = true)] [MappedType(BaseType = typeof(IEIFFileRepository), IsSingleton = true)] [MappedType(BaseType = typeof(IEIFFileProvider), IsSingleton = true)] [MappedType(BaseType = typeof(IENFFileRepository), IsSingleton = true)] [MappedType(BaseType = typeof(IENFFileProvider), IsSingleton = true)] [MappedType(BaseType = typeof(IESFFileRepository), IsSingleton = true)] [MappedType(BaseType = typeof(IESFFileProvider), IsSingleton = true)] [MappedType(BaseType = typeof(IECFFileRepository), IsSingleton = true)] [MappedType(BaseType = typeof(IECFFileProvider), IsSingleton = true)] public class PubFileRepository : IPubFileRepository, IPubFileProvider { public IPubFile<EIFRecord> EIFFile { get; set; } public IPubFile<ENFRecord> ENFFile { get; set; } public IPubFile<ESFRecord> ESFFile { get; set; } public IPubFile<ECFRecord> ECFFile { get; set; } } }
// Original Work Copyright (c) Ethan Moffat 2014-2016 // This file is subject to the GPL v2 License // For additional details, see the LICENSE file using AutomaticTypeMapper; using EOLib.IO.Pub; namespace EOLib.IO.Repositories { [MappedType(BaseType = typeof(IPubFileRepository), IsSingleton = true)] [MappedType(BaseType = typeof(IPubFileProvider), IsSingleton = true)] [MappedType(BaseType = typeof(IEIFFileRepository), IsSingleton = true)] [MappedType(BaseType = typeof(IEIFFileProvider), IsSingleton = true)] [MappedType(BaseType = typeof(IENFFileRepository), IsSingleton = true)] [MappedType(BaseType = typeof(IENFFileProvider), IsSingleton = true)] [MappedType(BaseType = typeof(IESFFileRepository), IsSingleton = true)] [MappedType(BaseType = typeof(IESFFileProvider), IsSingleton = true)] [MappedType(BaseType = typeof(IECFFileRepository), IsSingleton = true)] [MappedType(BaseType = typeof(IECFFileProvider), IsSingleton = true)] public class PubFileRepository : IPubFileRepository, IPubFileProvider { public IPubFile<EIFRecord> EIFFile { get; set; } public IPubFile<ENFRecord> ENFFile { get; set; } public IPubFile<ESFRecord> ESFFile { get; set; } public IPubFile<ECFRecord> ECFFile { get; set; } } }
Fix type mapping for IPubFileProvider
Fix type mapping for IPubFileProvider
C#
mit
ethanmoffat/EndlessClient
1c015e31f1f919e7b8221fab45a7e39e961a7c6f
Plugins/Wox.Plugin.BrowserBookmark/Main.cs
Plugins/Wox.Plugin.BrowserBookmark/Main.cs
using System.Collections.Generic; using System.Linq; using Wox.Plugin.BrowserBookmark.Commands; using Wox.Plugin.SharedCommands; namespace Wox.Plugin.BrowserBookmark { public class Main : IPlugin { private PluginInitContext context; private List<Bookmark> cachedBookmarks = new List<Bookmark>(); public void Init(PluginInitContext context) { this.context = context; cachedBookmarks = Bookmarks.LoadAllBookmarks(); } public List<Result> Query(Query query) { string param = query.GetAllRemainingParameter().TrimStart(); // Should top results be returned? (true if no search parameters have been passed) var topResults = string.IsNullOrEmpty(param); var returnList = cachedBookmarks; if (!topResults) { // Since we mixed chrome and firefox bookmarks, we should order them again returnList = cachedBookmarks.Where(o => Bookmarks.MatchProgram(o, param)).ToList(); returnList = returnList.OrderByDescending(o => o.Score).ToList(); } return returnList.Select(c => new Result() { Title = c.Name, SubTitle = "Bookmark: " + c.Url, IcoPath = @"Images\bookmark.png", Score = 5, Action = (e) => { context.API.HideApp(); c.Url.NewBrowserWindow(""); return true; } }).ToList(); } } }
using System.Collections.Generic; using System.Linq; using Wox.Plugin.BrowserBookmark.Commands; using Wox.Plugin.SharedCommands; namespace Wox.Plugin.BrowserBookmark { public class Main : IPlugin, IReloadable { private PluginInitContext context; private List<Bookmark> cachedBookmarks = new List<Bookmark>(); public void Init(PluginInitContext context) { this.context = context; cachedBookmarks = Bookmarks.LoadAllBookmarks(); } public List<Result> Query(Query query) { string param = query.GetAllRemainingParameter().TrimStart(); // Should top results be returned? (true if no search parameters have been passed) var topResults = string.IsNullOrEmpty(param); var returnList = cachedBookmarks; if (!topResults) { // Since we mixed chrome and firefox bookmarks, we should order them again returnList = cachedBookmarks.Where(o => Bookmarks.MatchProgram(o, param)).ToList(); returnList = returnList.OrderByDescending(o => o.Score).ToList(); } return returnList.Select(c => new Result() { Title = c.Name, SubTitle = "Bookmark: " + c.Url, IcoPath = @"Images\bookmark.png", Score = 5, Action = (e) => { context.API.HideApp(); c.Url.NewBrowserWindow(""); return true; } }).ToList(); } public void ReloadData() { cachedBookmarks.Clear(); cachedBookmarks = Bookmarks.LoadAllBookmarks(); } } }
Add IReloadable interface and method
Add IReloadable interface and method
C#
mit
Wox-launcher/Wox,qianlifeng/Wox,qianlifeng/Wox,qianlifeng/Wox,Wox-launcher/Wox
e1fa3e868a769ab6064ab707c3d9fb3af9fadc27
Properties/AssemblyInfo.cs
Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Skylight")] [assembly: AssemblyDescription("An API by TakoMan02 for Everybody Edits")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("TakoMan02")] [assembly: AssemblyProduct("Skylight")] [assembly: AssemblyCopyright("Copyright © TakoMan02 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: InternalsVisibleTo("Skylight")] [assembly: ComVisible(false)] [assembly: Guid("a460c245-2753-4861-ae17-751db86fbae2")] // // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyFileVersion("0.0.5.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Skylight")] [assembly: AssemblyDescription("An API by TakoMan02 for Everybody Edits")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("TakoMan02")] [assembly: AssemblyProduct("Skylight")] [assembly: AssemblyCopyright("Copyright © TakoMan02 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: InternalsVisibleTo("Skylight")] [assembly: ComVisible(false)] [assembly: Guid("a460c245-2753-4861-ae17-751db86fbae2")] // // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyFileVersion("0.5.1.0")]
Change version number to v0.5.1.0
Change version number to v0.5.1.0
C#
mit
Seist/Skylight
4533449ba6131a36c4263bc9529c5e0c21471ba9
src/SQLite.Net/BlobSerializerDelegate.cs
src/SQLite.Net/BlobSerializerDelegate.cs
using System; namespace SQLite.Net { public class BlobSerializerDelegate : IBlobSerializer { public delegate byte[] SerializeDelegate(object obj); public delegate bool CanSerializeDelegate(Type type); public delegate object DeserializeDelegate(byte[] data, Type type); private readonly SerializeDelegate serializeDelegate; private readonly DeserializeDelegate deserializeDelegate; private readonly CanSerializeDelegate canDeserializeDelegate; public BlobSerializerDelegate (SerializeDelegate serializeDelegate, DeserializeDelegate deserializeDelegate, CanSerializeDelegate canDeserializeDelegate) { this.serializeDelegate = serializeDelegate; this.deserializeDelegate = deserializeDelegate; this.canDeserializeDelegate = canDeserializeDelegate; } #region IBlobSerializer implementation public byte[] Serialize<T>(T obj) { return this.serializeDelegate (obj); } public object Deserialize(byte[] data, Type type) { return this.deserializeDelegate (data, type); } public bool CanDeserialize(Type type) { return this.canDeserializeDelegate (type); } #endregion } }
using System; namespace SQLite.Net { public class BlobSerializerDelegate : IBlobSerializer { public delegate byte[] SerializeDelegate(object obj); public delegate bool CanSerializeDelegate(Type type); public delegate object DeserializeDelegate(byte[] data, Type type); private readonly SerializeDelegate _serializeDelegate; private readonly DeserializeDelegate _deserializeDelegate; private readonly CanSerializeDelegate _canDeserializeDelegate; public BlobSerializerDelegate(SerializeDelegate serializeDelegate, DeserializeDelegate deserializeDelegate, CanSerializeDelegate canDeserializeDelegate) { _serializeDelegate = serializeDelegate; _deserializeDelegate = deserializeDelegate; _canDeserializeDelegate = canDeserializeDelegate; } #region IBlobSerializer implementation public byte[] Serialize<T>(T obj) { return _serializeDelegate(obj); } public object Deserialize(byte[] data, Type type) { return _deserializeDelegate(data, type); } public bool CanDeserialize(Type type) { return _canDeserializeDelegate(type); } #endregion } }
Rename fields name pattern to match rest of code
core/BlobSerializer: Rename fields name pattern to match rest of code
C#
mit
TiendaNube/SQLite.Net-PCL,igrali/SQLite.Net-PCL,caseydedore/SQLite.Net-PCL,mattleibow/SQLite.Net-PCL,fernandovm/SQLite.Net-PCL,igrali/SQLite.Net-PCL,kreuzhofer/SQLite.Net-PCL,molinch/SQLite.Net-PCL,oysteinkrog/SQLite.Net-PCL
e0a3df8344a1e51d18afc6a6844491d561d3198b
src/Ensconce.Cake/EnsconceFileUpdateExtensions.cs
src/Ensconce.Cake/EnsconceFileUpdateExtensions.cs
using Cake.Core.IO; using Ensconce.Update; using System.IO; namespace Ensconce.Cake { public static class EnsconceFileUpdateExtensions { public static void TextSubstitute(this IFile file, FilePath fixedStructureFile) { var tagDictionary = fixedStructureFile == null ? TagDictionaryBuilder.Build(string.Empty) : TagDictionaryBuilder.Build(fixedStructureFile.FullPath); Update.ProcessFiles.UpdateFile(new FileInfo(file.Path.FullPath), tagDictionary); } public static void TextSubstitute(this IDirectory directory, FilePath fixedStructureFile) { directory.TextSubstitute("*.*", fixedStructureFile); } public static void TextSubstitute(this IDirectory directory, string filter, FilePath fixedStructureFile) { var tagDictionary = fixedStructureFile == null ? TagDictionaryBuilder.Build(string.Empty) : TagDictionaryBuilder.Build(fixedStructureFile.FullPath); Update.ProcessFiles.UpdateFiles(directory.Path.FullPath, filter, tagDictionary); } } }
using Cake.Core.IO; using Ensconce.Update; using System.IO; namespace Ensconce.Cake { public static class EnsconceFileUpdateExtensions { public static void TextSubstitute(this IFile file, FilePath fixedStructureFile) { file.Path.TextSubstitute(fixedStructureFile); } public static void TextSubstitute(this IDirectory directory, FilePath fixedStructureFile) { directory.Path.TextSubstitute(fixedStructureFile); } public static void TextSubstitute(this IDirectory directory, string filter, FilePath fixedStructureFile) { directory.Path.TextSubstitute(filter, fixedStructureFile); } public static void TextSubstitute(this FilePath file, FilePath fixedStructureFile) { var tagDictionary = fixedStructureFile == null ? TagDictionaryBuilder.Build(string.Empty) : TagDictionaryBuilder.Build(fixedStructureFile.FullPath); Update.ProcessFiles.UpdateFile(new FileInfo(file.FullPath), tagDictionary); } public static void TextSubstitute(this DirectoryPath directory, FilePath fixedStructureFile) { directory.TextSubstitute("*.*", fixedStructureFile); } public static void TextSubstitute(this DirectoryPath directory, string filter, FilePath fixedStructureFile) { var tagDictionary = fixedStructureFile == null ? TagDictionaryBuilder.Build(string.Empty) : TagDictionaryBuilder.Build(fixedStructureFile.FullPath); Update.ProcessFiles.UpdateFiles(directory.FullPath, filter, tagDictionary); } } }
Handle update based on a path object as well as the directory/file
Handle update based on a path object as well as the directory/file
C#
mit
15below/Ensconce,BlythMeister/Ensconce,BlythMeister/Ensconce,15below/Ensconce
0ca87c03d6b9c621e2044ac3878a8453af904549
BForms.Docs/Global.asax.cs
BForms.Docs/Global.asax.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using BForms.Models; using BForms.Mvc; namespace BForms.Docs { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); //register BForms validation provider ModelValidatorProviders.Providers.Add(new BsModelValidatorProvider()); BForms.Utilities.BsResourceManager.Register(Resources.Resource.ResourceManager); //BForms.Utilities.BsUIManager.Theme(BsTheme.Black); System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US"); System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-US"); #if !DEBUG BForms.Utilities.BsConfigurationManager.Release(true); #endif } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using BForms.Models; using BForms.Mvc; namespace BForms.Docs { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); //register BForms validation provider ModelValidatorProviders.Providers.Add(new BsModelValidatorProvider()); BForms.Utilities.BsResourceManager.Register(Resources.Resource.ResourceManager); //BForms.Utilities.BsUIManager.Theme(BsTheme.Black); #if !DEBUG BForms.Utilities.BsConfigurationManager.Release(true); #endif } } }
Revert "fixed mandatory field error message"
Revert "fixed mandatory field error message" This reverts commit fe294ec07e8cf85ecea8f317b7aa2ee169bd2120.
C#
mit
vtfuture/BForms,vtfuture/BForms,vtfuture/BForms
9c3e74131f01a804661539b3f00f4010a4946390
src/ServiceStack.Common/Web/HttpHeaders.cs
src/ServiceStack.Common/Web/HttpHeaders.cs
namespace ServiceStack.Common.Web { public static class HttpHeaders { public const string XParamOverridePrefix = "X-Param-Override-"; public const string XHttpMethodOverride = "X-Http-Method-Override"; public const string XUserAuthId = "X-UAId"; public const string XForwardedFor = "X-Forwarded-For"; public const string XRealIp = "X-Real-IP"; public const string Referer = "Referer"; public const string CacheControl = "Cache-Control"; public const string IfModifiedSince = "If-Modified-Since"; public const string LastModified = "Last-Modified"; public const string Accept = "Accept"; public const string AcceptEncoding = "Accept-Encoding"; public const string ContentType = "Content-Type"; public const string ContentEncoding = "Content-Encoding"; public const string ContentLength = "Content-Length"; public const string ContentDisposition = "Content-Disposition"; public const string Location = "Location"; public const string SetCookie = "Set-Cookie"; public const string ETag = "ETag"; public const string Authorization = "Authorization"; public const string WwwAuthenticate = "WWW-Authenticate"; public const string AllowOrigin = "Access-Control-Allow-Origin"; public const string AllowMethods = "Access-Control-Allow-Methods"; public const string AllowHeaders = "Access-Control-Allow-Headers"; public const string AllowCredentials = "Access-Control-Allow-Credentials"; } }
namespace ServiceStack.Common.Web { public static class HttpHeaders { public const string XParamOverridePrefix = "X-Param-Override-"; public const string XHttpMethodOverride = "X-Http-Method-Override"; public const string XUserAuthId = "X-UAId"; public const string XForwardedFor = "X-Forwarded-For"; public const string XRealIp = "X-Real-IP"; public const string Referer = "Referer"; public const string CacheControl = "Cache-Control"; public const string IfModifiedSince = "If-Modified-Since"; public const string IfNoneMatch = "If-None-Match"; public const string LastModified = "Last-Modified"; public const string Accept = "Accept"; public const string AcceptEncoding = "Accept-Encoding"; public const string ContentType = "Content-Type"; public const string ContentEncoding = "Content-Encoding"; public const string ContentLength = "Content-Length"; public const string ContentDisposition = "Content-Disposition"; public const string Location = "Location"; public const string SetCookie = "Set-Cookie"; public const string ETag = "ETag"; public const string Authorization = "Authorization"; public const string WwwAuthenticate = "WWW-Authenticate"; public const string AllowOrigin = "Access-Control-Allow-Origin"; public const string AllowMethods = "Access-Control-Allow-Methods"; public const string AllowHeaders = "Access-Control-Allow-Headers"; public const string AllowCredentials = "Access-Control-Allow-Credentials"; } }
Add a const string field for the If-None-Match HTTP header
Add a const string field for the If-None-Match HTTP header
C#
bsd-3-clause
ZocDoc/ServiceStack,NServiceKit/NServiceKit,MindTouch/NServiceKit,NServiceKit/NServiceKit,nataren/NServiceKit,ZocDoc/ServiceStack,NServiceKit/NServiceKit,NServiceKit/NServiceKit,ZocDoc/ServiceStack,timba/NServiceKit,timba/NServiceKit,MindTouch/NServiceKit,nataren/NServiceKit,timba/NServiceKit,nataren/NServiceKit,ZocDoc/ServiceStack,MindTouch/NServiceKit,nataren/NServiceKit,timba/NServiceKit,MindTouch/NServiceKit
c66c36b53727bbafedfe9fe6472c5a8db88dd6b4
WalletWasabi/Extensions/MemoryExtensions.cs
WalletWasabi/Extensions/MemoryExtensions.cs
using Nito.AsyncEx; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace Microsoft.Extensions.Caching.Memory { public static class MemoryExtensions { private static Dictionary<object, AsyncLock> AsyncLocks { get; } = new Dictionary<object, AsyncLock>(); private static object AsyncLocksLock { get; } = new object(); public static async Task<TItem> AtomicGetOrCreateAsync<TItem>(this IMemoryCache cache, object key, Func<ICacheEntry, Task<TItem>> factory) { if (cache.TryGetValue(key, out TItem value)) { return value; } AsyncLock asyncLock; lock (AsyncLocksLock) { if (!AsyncLocks.TryGetValue(key, out asyncLock)) { asyncLock = new AsyncLock(); AsyncLocks.Add(key, asyncLock); } } using (await asyncLock.LockAsync().ConfigureAwait(false)) { if (!cache.TryGetValue(key, out value)) { value = await cache.GetOrCreateAsync(key, factory).ConfigureAwait(false); } return value; } } } }
using Nito.AsyncEx; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Microsoft.Extensions.Caching.Memory { public static class MemoryExtensions { private static Dictionary<object, AsyncLock> AsyncLocks { get; } = new Dictionary<object, AsyncLock>(); private static object AsyncLocksLock { get; } = new object(); public static async Task<TItem> AtomicGetOrCreateAsync<TItem>(this IMemoryCache cache, object key, Func<ICacheEntry, Task<TItem>> factory) { if (cache.TryGetValue(key, out TItem value)) { return value; } AsyncLock asyncLock; lock (AsyncLocksLock) { // Cleanup the evicted asynclocks first. foreach (var toRemove in AsyncLocks.Keys.Where(x => !cache.TryGetValue(x, out _)).ToList()) { AsyncLocks.Remove(toRemove); } if (!AsyncLocks.TryGetValue(key, out asyncLock)) { asyncLock = new AsyncLock(); AsyncLocks.Add(key, asyncLock); } } using (await asyncLock.LockAsync().ConfigureAwait(false)) { if (!cache.TryGetValue(key, out value)) { value = await cache.GetOrCreateAsync(key, factory).ConfigureAwait(false); } return value; } } } }
Make sure to clean my dic.
Make sure to clean my dic.
C#
mit
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
4ddddfcb6eaf000c5790913d888016de5e010598
Properties/AssemblyInfo.cs
Properties/AssemblyInfo.cs
using System.Reflection; [assembly: AssemblyTitle("Autofac.Tests.Integration.Web")] [assembly: AssemblyDescription("")]
using System.Reflection; [assembly: AssemblyTitle("Autofac.Tests.Integration.Web")]
Build script now writes the package name and version into the AssemblyDescription attibute. This allows the package information to be seen in Visual Studio avoiding confusion with the assembly version that remains at the major.
Build script now writes the package name and version into the AssemblyDescription attibute. This allows the package information to be seen in Visual Studio avoiding confusion with the assembly version that remains at the major.
C#
mit
autofac/Autofac.Web
4751601973861024ca9e46b0c8dbc16b2dd37a70
source/XeroApi/Model/Journal.cs
source/XeroApi/Model/Journal.cs
using System; namespace XeroApi.Model { public class Journal : EndpointModelBase { [ItemId] public Guid JournalID { get; set; } public DateTime JournalDate { get; set; } public long JournalNumber { get; set; } [ItemUpdatedDate] public DateTime CreatedDateUTC { get; set; } public string Reference { get; set; } public JournalLines JournalLines { get; set; } public override string ToString() { return string.Format("Journal:{0}", JournalNumber); } } public class Journals : ModelList<Journal> { } }
using System; namespace XeroApi.Model { public class Journal : EndpointModelBase { [ItemId] public Guid JournalID { get; set; } public DateTime JournalDate { get; set; } public long JournalNumber { get; set; } [ItemUpdatedDate] public DateTime CreatedDateUTC { get; set; } public string Reference { get; set; } public JournalLines JournalLines { get; set; } public Guid SourceID { get; set; } public string SourceType { get; set; } public override string ToString() { return string.Format("Journal:{0}", JournalNumber); } } public class Journals : ModelList<Journal> { } }
Add SourceID and SourceType to journal
Add SourceID and SourceType to journal
C#
mit
MatthewSteeples/XeroAPI.Net
a0460b8216eedbf6dd02bde2f89ebb4ddf568447
plugins/TrackableData.MySql.Tests/Database.cs
plugins/TrackableData.MySql.Tests/Database.cs
using System; using System.Configuration; using System.Data.SqlClient; using MySql.Data.MySqlClient; namespace TrackableData.MySql.Tests { public class Database : IDisposable { public Database() { var cstr = ConfigurationManager.ConnectionStrings["TestDb"].ConnectionString; // create TestDb if not exist var cstrForMaster = ""; { var connectionBuilder = new SqlConnectionStringBuilder(cstr); connectionBuilder.InitialCatalog = "sys"; cstrForMaster = connectionBuilder.ToString(); } using (var conn = new MySqlConnection(cstrForMaster)) { conn.Open(); using (var cmd = new MySqlCommand()) { cmd.CommandText = string.Format(@" DROP DATABASE IF EXISTS {0}; CREATE DATABASE {0}; ", new SqlConnectionStringBuilder(cstr).InitialCatalog); cmd.Connection = conn; var result = cmd.ExecuteScalar(); } } } public MySqlConnection Connection { get { var cstr = ConfigurationManager.ConnectionStrings["TestDb"].ConnectionString; var connection = new MySqlConnection(cstr); connection.Open(); return connection; } } public void Dispose() { } } }
using System; using System.Configuration; using System.Data.SqlClient; using MySql.Data.MySqlClient; namespace TrackableData.MySql.Tests { public class Database : IDisposable { public Database() { var cstr = ConfigurationManager.ConnectionStrings["TestDb"].ConnectionString; // create TestDb if not exist var cstrForMaster = ""; { var connectionBuilder = new SqlConnectionStringBuilder(cstr); connectionBuilder.InitialCatalog = ""; cstrForMaster = connectionBuilder.ToString(); } using (var conn = new MySqlConnection(cstrForMaster)) { conn.Open(); using (var cmd = new MySqlCommand()) { cmd.CommandText = string.Format(@" DROP DATABASE IF EXISTS {0}; CREATE DATABASE {0}; ", new SqlConnectionStringBuilder(cstr).InitialCatalog); cmd.Connection = conn; var result = cmd.ExecuteScalar(); } } } public MySqlConnection Connection { get { var cstr = ConfigurationManager.ConnectionStrings["TestDb"].ConnectionString; var connection = new MySqlConnection(cstr); connection.Open(); return connection; } } public void Dispose() { } } }
Fix bug to find non-existent sys db in mysql
Fix bug to find non-existent sys db in mysql
C#
mit
SaladLab/TrackableData,SaladbowlCreative/TrackableData,SaladbowlCreative/TrackableData,SaladLab/TrackableData
b306a7b0a8ce6c837b20ea0a25d6f9bb2adc2fa4
src/Certify.Models/Config/ActionResult.cs
src/Certify.Models/Config/ActionResult.cs
namespace Certify.Models.Config { public class ActionResult { public ActionResult() { } public ActionResult(string msg, bool isSuccess) { Message = msg; IsSuccess = isSuccess; } public bool IsSuccess { get; set; } public string Message { get; set; } /// <summary> /// Optional field to hold related information such as required info or error details /// </summary> public object Result { get; set; } } public class ActionResult<T> : ActionResult { public new T Result; public ActionResult() { } public ActionResult(string msg, bool isSuccess) { Message = msg; IsSuccess = isSuccess; } public ActionResult(string msg, bool isSuccess, T result) { Message = msg; IsSuccess = isSuccess; Result = result; } } }
namespace Certify.Models.Config { public class ActionResult { public ActionResult() { } public ActionResult(string msg, bool isSuccess) { Message = msg; IsSuccess = isSuccess; } public bool IsSuccess { get; set; } public bool IsWarning { get; set; } public string Message { get; set; } /// <summary> /// Optional field to hold related information such as required info or error details /// </summary> public object Result { get; set; } } public class ActionResult<T> : ActionResult { public new T Result; public ActionResult() { } public ActionResult(string msg, bool isSuccess) { Message = msg; IsSuccess = isSuccess; } public ActionResult(string msg, bool isSuccess, T result) { Message = msg; IsSuccess = isSuccess; Result = result; } } }
Add IsWarning to action result
Add IsWarning to action result
C#
mit
webprofusion/Certify
2a8b84bd3deb0d7d6a8e8f0701e0d5521ee26206
src/Cake.Frosting.Template/templates/cakefrosting/build/Program.cs
src/Cake.Frosting.Template/templates/cakefrosting/build/Program.cs
using System.Threading.Tasks; using Cake.Core; using Cake.Core.Diagnostics; using Cake.Frosting; public static class Program { public static int Main(string[] args) { return new CakeHost() .UseContext<BuildContext>() .UseWorkingDirectory("..") .Run(args); } } public class BuildContext : FrostingContext { public bool Delay { get; set; } public BuildContext(ICakeContext context) : base(context) { Delay = context.Arguments.HasArgument("delay"); } } [TaskName("Hello")] public sealed class HelloTask : FrostingTask<BuildContext> { public override void Run(BuildContext context) { context.Log.Information("Hello"); } } [TaskName("World")] [IsDependentOn(typeof(HelloTask))] public sealed class WorldTask : AsyncFrostingTask<BuildContext> { // Tasks can be asynchronous public override async Task RunAsync(BuildContext context) { if (context.Delay) { context.Log.Information("Waiting..."); await Task.Delay(1500); } context.Log.Information("World"); } } [TaskName("Default")] [IsDependentOn(typeof(WorldTask))] public class DefaultTask : FrostingTask { }
using System.Threading.Tasks; using Cake.Core; using Cake.Core.Diagnostics; using Cake.Frosting; public static class Program { public static int Main(string[] args) { return new CakeHost() .UseContext<BuildContext>() .Run(args); } } public class BuildContext : FrostingContext { public bool Delay { get; set; } public BuildContext(ICakeContext context) : base(context) { Delay = context.Arguments.HasArgument("delay"); } } [TaskName("Hello")] public sealed class HelloTask : FrostingTask<BuildContext> { public override void Run(BuildContext context) { context.Log.Information("Hello"); } } [TaskName("World")] [IsDependentOn(typeof(HelloTask))] public sealed class WorldTask : AsyncFrostingTask<BuildContext> { // Tasks can be asynchronous public override async Task RunAsync(BuildContext context) { if (context.Delay) { context.Log.Information("Waiting..."); await Task.Delay(1500); } context.Log.Information("World"); } } [TaskName("Default")] [IsDependentOn(typeof(WorldTask))] public class DefaultTask : FrostingTask { }
Remove use of UseWorkingDirectory in default template
Remove use of UseWorkingDirectory in default template
C#
mit
cake-build/cake,gep13/cake,patriksvensson/cake,devlead/cake,patriksvensson/cake,devlead/cake,gep13/cake,cake-build/cake
bae1e37f3a917c61033cacb12f3a02526961bfd6
bees-in-the-trap/Assets/Scripts/Upgrade.cs
bees-in-the-trap/Assets/Scripts/Upgrade.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public enum Upgrade { NONE, ROBOT, NIGHTVISION, UNICORN, ZOMBIE, REDHAT, BEEARD }
using System.Collections; using System.Collections.Generic; using UnityEngine; public enum Upgrade { NONE, ROBOT, NIGHTVISION, UNICORN, ZOMBIE, REDHAT, BEEARD, BEEBALL, SCHOOLBUZZ, BUZZFEED, BEACH, GUM, VISOR }
Add other upgrades to enum
Add other upgrades to enum
C#
mit
makerslocal/LudumDare38
7616c7a6ab30877993a00bbaa53ac185d67a7aa8
Swashbuckle.Core/Swagger/JsonPropertyExtensions.cs
Swashbuckle.Core/Swagger/JsonPropertyExtensions.cs
using System; using System.ComponentModel.DataAnnotations; using System.Reflection; using Newtonsoft.Json.Serialization; namespace Swashbuckle.Swagger { public static class JsonPropertyExtensions { public static bool IsRequired(this JsonProperty jsonProperty) { return jsonProperty.HasAttribute<RequiredAttribute>(); } public static bool IsObsolete(this JsonProperty jsonProperty) { return jsonProperty.HasAttribute<ObsoleteAttribute>(); } public static bool HasAttribute<T>(this JsonProperty jsonProperty) { var propInfo = jsonProperty.PropertyInfo(); return propInfo != null && Attribute.IsDefined(propInfo, typeof (T)); } public static PropertyInfo PropertyInfo(this JsonProperty jsonProperty) { if(jsonProperty.UnderlyingName == null) return null; return jsonProperty.DeclaringType.GetProperty(jsonProperty.UnderlyingName, jsonProperty.PropertyType); } } }
using System; using System.ComponentModel.DataAnnotations; using System.Reflection; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; namespace Swashbuckle.Swagger { public static class JsonPropertyExtensions { public static bool IsRequired(this JsonProperty jsonProperty) { return jsonProperty.HasAttribute<RequiredAttribute>() || jsonProperty.Required == Required.Always; } public static bool IsObsolete(this JsonProperty jsonProperty) { return jsonProperty.HasAttribute<ObsoleteAttribute>(); } public static bool HasAttribute<T>(this JsonProperty jsonProperty) { var propInfo = jsonProperty.PropertyInfo(); return propInfo != null && Attribute.IsDefined(propInfo, typeof (T)); } public static PropertyInfo PropertyInfo(this JsonProperty jsonProperty) { if(jsonProperty.UnderlyingName == null) return null; return jsonProperty.DeclaringType.GetProperty(jsonProperty.UnderlyingName, jsonProperty.PropertyType); } } }
Fix to also check the Required property of the JsonProperty when determining if a model property is required or optional.
Fix to also check the Required property of the JsonProperty when determining if a model property is required or optional.
C#
bsd-3-clause
domaindrivendev/Swashbuckle,domaindrivendev/Swashbuckle,domaindrivendev/Swashbuckle
ab598eafe1d92e5564b31432e45b86843bdf80ae
RedditSharpTests/AuthenticatedTestsFixture.cs
RedditSharpTests/AuthenticatedTestsFixture.cs
using Microsoft.Extensions.Configuration; using Xunit; namespace RedditSharpTests { public class AuthenticatedTestsFixture { public IConfigurationRoot Config { get; private set; } public string AccessToken { get; private set; } public RedditSharp.BotWebAgent WebAgent { get; set; } public string TestUserName { get; private set; } public AuthenticatedTestsFixture() { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.AddJsonFile("private.config") .AddEnvironmentVariables(); Config = builder.Build(); WebAgent = new RedditSharp.BotWebAgent(Config["TestUserName"], Config["TestUserPassword"], Config["RedditClientID"], Config["RedditClientSecret"], Config["RedditRedirectURI"]); AccessToken = WebAgent.AccessToken; TestUserName = Config["TestUserName"]; } } [CollectionDefinition("AuthenticatedTests")] public class AuthenticatedTestsCollection : ICollectionFixture<AuthenticatedTestsFixture> { // This class has no code, and is never created. Its purpose is simply // to be the place to apply [CollectionDefinition] and all the // ICollectionFixture<> interfaces. } }
using Microsoft.Extensions.Configuration; using Xunit; namespace RedditSharpTests { public class AuthenticatedTestsFixture { public IConfigurationRoot Config { get; private set; } public string AccessToken { get; private set; } public RedditSharp.BotWebAgent WebAgent { get; set; } public string TestUserName { get; private set; } public AuthenticatedTestsFixture() { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.AddJsonFile("private.config",true) .AddEnvironmentVariables(); Config = builder.Build(); WebAgent = new RedditSharp.BotWebAgent(Config["TestUserName"], Config["TestUserPassword"], Config["RedditClientID"], Config["RedditClientSecret"], Config["RedditRedirectURI"]); AccessToken = WebAgent.AccessToken; TestUserName = Config["TestUserName"]; } } [CollectionDefinition("AuthenticatedTests")] public class AuthenticatedTestsCollection : ICollectionFixture<AuthenticatedTestsFixture> { // This class has no code, and is never created. Its purpose is simply // to be the place to apply [CollectionDefinition] and all the // ICollectionFixture<> interfaces. } }
Set private.config to optional to fix unit tests on build server
Set private.config to optional to fix unit tests on build server
C#
mit
CrustyJew/RedditSharp
3b1fd660928db28de677b08ed168613b98aee6f4
Scripts/GameApi/Messages/ServerTimeMessage.cs
Scripts/GameApi/Messages/ServerTimeMessage.cs
using System.Collections; using System.Collections.Generic; using LiteNetLib.Utils; namespace LiteNetLibManager { public struct ServerTimeMessage : INetSerializable { public int serverUnixTime; public float serverTime; public void Deserialize(NetDataReader reader) { serverUnixTime = reader.GetInt(); serverTime = reader.GetFloat(); } public void Serialize(NetDataWriter writer) { writer.Put(serverUnixTime); writer.Put(serverTime); } } }
using System.Collections; using System.Collections.Generic; using LiteNetLib.Utils; namespace LiteNetLibManager { public struct ServerTimeMessage : INetSerializable { public int serverUnixTime; public void Deserialize(NetDataReader reader) { serverUnixTime = reader.GetPackedInt(); } public void Serialize(NetDataWriter writer) { writer.PutPackedInt(serverUnixTime); } } }
Reduce packet size, remove bloated time codes
Reduce packet size, remove bloated time codes
C#
mit
insthync/LiteNetLibManager,insthync/LiteNetLibManager
a0f703f1334c0b25af0f524f85a61e2ab18afec6
Core/Theraot/Threading/GCMonitor.internal.cs
Core/Theraot/Threading/GCMonitor.internal.cs
// Needed for Workaround using System; using System.Threading; using Theraot.Collections.ThreadSafe; namespace Theraot.Threading { public static partial class GCMonitor { private static class Internal { private static readonly WeakDelegateCollection _collectedEventHandlers; private static readonly WaitCallback work; static Internal() { work = _ => RaiseCollected(); _collectedEventHandlers = new WeakDelegateCollection(false, false, INT_MaxProbingHint); } public static WeakDelegateCollection CollectedEventHandlers { get { return _collectedEventHandlers; } } public static void Invoke() { ThreadPool.QueueUserWorkItem(work); } private static void RaiseCollected() { var check = Thread.VolatileRead(ref _status); if (check == INT_StatusReady) { try { _collectedEventHandlers.RemoveDeadItems(); _collectedEventHandlers.Invoke(null, new EventArgs()); } catch (Exception exception) { // Pokemon GC.KeepAlive(exception); } Thread.VolatileWrite(ref _status, INT_StatusReady); } } } } }
// Needed for Workaround using System; using System.Threading; using Theraot.Collections.ThreadSafe; namespace Theraot.Threading { public static partial class GCMonitor { private static class Internal { private static readonly WeakDelegateCollection _collectedEventHandlers; private static readonly WaitCallback _work; static Internal() { _work = _ => RaiseCollected(); _collectedEventHandlers = new WeakDelegateCollection(false, false, INT_MaxProbingHint); } public static WeakDelegateCollection CollectedEventHandlers { get { return _collectedEventHandlers; } } public static void Invoke() { ThreadPool.QueueUserWorkItem(_work); } private static void RaiseCollected() { var check = Thread.VolatileRead(ref _status); if (check == INT_StatusReady) { try { _collectedEventHandlers.RemoveDeadItems(); _collectedEventHandlers.Invoke(null, new EventArgs()); } catch (Exception exception) { // Pokemon GC.KeepAlive(exception); } Thread.VolatileWrite(ref _status, INT_StatusReady); } } } } }
Rename refactor;: GCMonitor.work -> GCMonitor._work
Rename refactor;: GCMonitor.work -> GCMonitor._work
C#
mit
theraot/Theraot
7a6b4aefb7d0750d590fd7fe16b4afdb78415a64
CardboardControl/Scripts/ParsedTouchData.cs
CardboardControl/Scripts/ParsedTouchData.cs
using UnityEngine; using System.Collections; /** * Dealing with raw touch input from a Cardboard device */ public class ParsedTouchData { private bool wasTouched = false; public ParsedTouchData() {} public void Update() { wasTouched |= this.IsDown(); } public bool IsDown() { return Input.touchCount > 0; } public bool IsUp() { if (!this.IsDown() && wasTouched) { wasTouched = false; return true; } return false; } }
using UnityEngine; using System.Collections; /** * Dealing with raw touch input from a Cardboard device */ public class ParsedTouchData { private bool wasTouched = false; public ParsedTouchData() { Cardboard cardboard = CardboardGameObject().GetComponent<Cardboard>(); cardboard.TapIsTrigger = false; } private GameObject CardboardGameObject() { GameObject gameObject = Camera.main.gameObject; return gameObject.transform.parent.parent.gameObject; } public void Update() { wasTouched |= IsDown(); } public bool IsDown() { return Input.touchCount > 0; } public bool IsUp() { if (!IsDown() && wasTouched) { wasTouched = false; return true; } return false; } }
Update for new version of Cardboard SDK
Update for new version of Cardboard SDK
C#
mit
JScott/cardboard-controls
bbce4451aa7693ee634b55081c705b4672ae93a2
BTCPayServer.Abstractions/Security/AuthorizationFilterHandle.cs
BTCPayServer.Abstractions/Security/AuthorizationFilterHandle.cs
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; namespace BTCPayServer.Security; public class AuthorizationFilterHandle { public AuthorizationHandlerContext Context { get; } public PolicyRequirement Requirement { get; } public HttpContext HttpContext { get; } public bool Success { get; } public AuthorizationFilterHandle( AuthorizationHandlerContext context, PolicyRequirement requirement, HttpContext httpContext) { Context = context; Requirement = requirement; HttpContext = httpContext; } }
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; namespace BTCPayServer.Security; public class AuthorizationFilterHandle { public AuthorizationHandlerContext Context { get; } public PolicyRequirement Requirement { get; } public HttpContext HttpContext { get; } public bool Success { get; private set; } public AuthorizationFilterHandle( AuthorizationHandlerContext context, PolicyRequirement requirement, HttpContext httpContext) { Context = context; Requirement = requirement; HttpContext = httpContext; } public void MarkSuccessful() { Success = true; } }
Add ability to mark auth handle as successful
Add ability to mark auth handle as successful Without this, there is no way to let the handle finish with a successful state. I somehow missed to add this in #3977.
C#
mit
btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver
1905772d88235d4627f1520ae5243f512a57fe3c
src/platform/ICCSAXDelegator.cs
src/platform/ICCSAXDelegator.cs
/**************************************************************************** Copyright (c) 2010-2012 cocos2d-x.org Copyright (c) 2008-2009 Jason Booth Copyright (c) 2011-2012 openxlive.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ namespace CocosSharp { public interface ICCSAXDelegator { void StartElement(object ctx, string name, string[] atts); void EndElement(object ctx, string name); void TextHandler(object ctx, byte[] ch, int len); } }
/**************************************************************************** Copyright (c) 2010-2012 cocos2d-x.org Copyright (c) 2008-2009 Jason Booth Copyright (c) 2011-2012 openxlive.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ namespace CocosSharp { internal interface ICCSAXDelegator { void StartElement(object ctx, string name, string[] atts); void EndElement(object ctx, string name); void TextHandler(object ctx, byte[] ch, int len); } }
Mark ICCSaxDelegator class as internal.
Mark ICCSaxDelegator class as internal.
C#
mit
haithemaraissia/CocosSharp,netonjm/CocosSharp,netonjm/CocosSharp,mono/CocosSharp,MSylvia/CocosSharp,hig-ag/CocosSharp,haithemaraissia/CocosSharp,MSylvia/CocosSharp,mono/CocosSharp,hig-ag/CocosSharp,TukekeSoft/CocosSharp,zmaruo/CocosSharp,TukekeSoft/CocosSharp,zmaruo/CocosSharp
23c9cac1e27a1836c40c54ccca36fba0b645e4ec
BoardGamesApi/Controllers/TempController.cs
BoardGamesApi/Controllers/TempController.cs
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; namespace BoardGamesApi.Controllers { [ApiExplorerSettings(IgnoreApi = true)] public class TempController : Controller { private readonly IConfiguration _configuration; public TempController(IConfiguration configuration) { _configuration = configuration; } [AllowAnonymous] [Route("/get-token")] public IActionResult GenerateToken(string name = "mscommunity") { var jwt = JwtTokenGenerator .Generate(name, true, _configuration["Token:Issuer"], _configuration["Token:Key"]); return Ok(jwt); } } }
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; namespace BoardGamesApi.Controllers { [ApiExplorerSettings(IgnoreApi = true)] public class TempController : Controller { private readonly IConfiguration _configuration; public TempController(IConfiguration configuration) { _configuration = configuration; } [AllowAnonymous] [Route("/get-token")] public IActionResult GenerateToken(string name = "mscommunity") { var jwt = JwtTokenGenerator .Generate(name, true, _configuration["Tokens:Issuer"], _configuration["Tokens:Key"]); return Ok(jwt); } } }
Fix the issue with settings name
Fix the issue with settings name
C#
mit
miroslavpopovic/production-ready-apis-sample
08358c24e29d513f6e29a9db93d2647976777565
Source/Eto.Mac/Forms/Controls/MacButton.cs
Source/Eto.Mac/Forms/Controls/MacButton.cs
using Eto.Forms; using MonoMac.AppKit; using Eto.Drawing; namespace Eto.Mac.Forms.Controls { public abstract class MacButton<TControl, TWidget, TCallback> : MacControl<TControl, TWidget, TCallback>, TextControl.IHandler where TControl: NSButton where TWidget: Control where TCallback: Control.ICallback { public virtual string Text { get { return Control.Title; } set { var oldSize = GetPreferredSize(Size.MaxValue); Control.SetTitleWithMnemonic(value); LayoutIfNeeded(oldSize); } } } }
using Eto.Forms; using MonoMac.AppKit; using Eto.Drawing; namespace Eto.Mac.Forms.Controls { public abstract class MacButton<TControl, TWidget, TCallback> : MacControl<TControl, TWidget, TCallback>, TextControl.IHandler where TControl: NSButton where TWidget: Control where TCallback: Control.ICallback { public virtual string Text { get { return Control.Title; } set { var oldSize = GetPreferredSize(Size.MaxValue); Control.SetTitleWithMnemonic(value ?? string.Empty); LayoutIfNeeded(oldSize); } } } }
Allow Button.Text to be set to null
Mac: Allow Button.Text to be set to null
C#
bsd-3-clause
l8s/Eto,l8s/Eto,bbqchickenrobot/Eto-1,PowerOfCode/Eto,l8s/Eto,bbqchickenrobot/Eto-1,PowerOfCode/Eto,PowerOfCode/Eto,bbqchickenrobot/Eto-1
1c74e56bab1679e7d42a52b7cc84126e66a10dad
osu.Game.Rulesets.Mania/ManiaInputManager.cs
osu.Game.Rulesets.Mania/ManiaInputManager.cs
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System.ComponentModel; using osu.Framework.Input.Bindings; using osu.Game.Rulesets.UI; namespace osu.Game.Rulesets.Mania { public class ManiaInputManager : RulesetInputManager<ManiaAction> { public ManiaInputManager(RulesetInfo ruleset, int variant) : base(ruleset, variant, SimultaneousBindingMode.Unique) { } } public enum ManiaAction { [Description("Special")] Special, [Description("Special")] Specia2, [Description("Key 1")] Key1 = 10, [Description("Key 2")] Key2, [Description("Key 3")] Key3, [Description("Key 4")] Key4, [Description("Key 5")] Key5, [Description("Key 6")] Key6, [Description("Key 7")] Key7, [Description("Key 8")] Key8, [Description("Key 9")] Key9 } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System.ComponentModel; using osu.Framework.Input.Bindings; using osu.Game.Rulesets.UI; namespace osu.Game.Rulesets.Mania { public class ManiaInputManager : RulesetInputManager<ManiaAction> { public ManiaInputManager(RulesetInfo ruleset, int variant) : base(ruleset, variant, SimultaneousBindingMode.Unique) { } } public enum ManiaAction { [Description("Special")] Special, [Description("Special")] Specia2, [Description("Key 1")] Key1 = 1000, [Description("Key 2")] Key2, [Description("Key 3")] Key3, [Description("Key 4")] Key4, [Description("Key 5")] Key5, [Description("Key 6")] Key6, [Description("Key 7")] Key7, [Description("Key 8")] Key8, [Description("Key 9")] Key9 } }
Increase the point at which normal keys start in ManiaAction
Increase the point at which normal keys start in ManiaAction
C#
mit
ppy/osu,UselessToucan/osu,EVAST9919/osu,DrabWeb/osu,peppy/osu-new,smoogipoo/osu,DrabWeb/osu,NeoAdonis/osu,ppy/osu,Frontear/osuKyzer,2yangk23/osu,smoogipoo/osu,peppy/osu,johnneijzen/osu,EVAST9919/osu,Nabile-Rahmani/osu,DrabWeb/osu,naoey/osu,ZLima12/osu,ppy/osu,peppy/osu,UselessToucan/osu,2yangk23/osu,NeoAdonis/osu,johnneijzen/osu,NeoAdonis/osu,ZLima12/osu,UselessToucan/osu,peppy/osu,naoey/osu,smoogipoo/osu,naoey/osu,smoogipooo/osu
2fd2d0a852232c55602fa3dc2f2556546ffba97a
src/UnityExtension/Assets/Editor/GitHub.Unity/UI/LoadingView.cs
src/UnityExtension/Assets/Editor/GitHub.Unity/UI/LoadingView.cs
using System; using System.Linq; using System.Threading.Tasks; using Octokit; using Rackspace.Threading; using UnityEditor; using UnityEngine; namespace GitHub.Unity { class LoadingView : Subview { private static readonly Vector2 viewSize = new Vector2(300, 250); private bool isBusy; private const string WindowTitle = "Loading..."; private const string Header = ""; public override void InitializeView(IView parent) { base.InitializeView(parent); Title = WindowTitle; Size = viewSize; } public override void OnGUI() {} public override bool IsBusy { get { return false; } } } }
using System; using System.Linq; using System.Threading.Tasks; using Octokit; using Rackspace.Threading; using UnityEditor; using UnityEngine; namespace GitHub.Unity { class LoadingView : Subview { private static readonly Vector2 viewSize = new Vector2(300, 250); private const string WindowTitle = "Loading..."; private const string Header = ""; public override void InitializeView(IView parent) { base.InitializeView(parent); Title = WindowTitle; Size = viewSize; } public override void OnGUI() {} public override bool IsBusy { get { return false; } } } }
Remove unused field, for now
Remove unused field, for now
C#
mit
github-for-unity/Unity,github-for-unity/Unity,mpOzelot/Unity,github-for-unity/Unity,mpOzelot/Unity
ca4c9ff43084f90f715f0ca4eb44c7d397fb39ea
src/Xamarin.Forms.OAuth/OAuthTestApp/OAuthTestApp/ResultPage.cs
src/Xamarin.Forms.OAuth/OAuthTestApp/OAuthTestApp/ResultPage.cs
using System; using Xamarin.Forms; using Xamarin.Forms.OAuth; namespace OAuthTestApp { public class ResultPage : ContentPage { public ResultPage(AuthenticatonResult result, Action returnCallback) { var stack = new StackLayout { VerticalOptions = LayoutOptions.Center, HorizontalOptions = LayoutOptions.Center }; if (result) { stack.Children.Add(new Label { Text = $"Provider: {result.Account.Provider}" }); stack.Children.Add(new Label { Text = $"Id: {result.Account.Id}" }); stack.Children.Add(new Label { Text = $"Name: {result.Account.DisplayName}" }); stack.Children.Add(new Label { Text = $"Access Token: {result.Account.AccessToken}" }); } else { stack.Children.Add(new Label { Text = "Authentication failed!" }); stack.Children.Add(new Label { Text = $"Reason: {result.ErrorMessage}" }); } stack.Children.Add(new Button { Text = "Back", Command = new Command(returnCallback) }); Content = stack; } } }
using System; using Xamarin.Forms; using Xamarin.Forms.OAuth; using Xamarin.Forms.OAuth.Views; namespace OAuthTestApp { public class ResultPage : ContentPage, IBackHandlingView { private readonly Action _returnCallback; public ResultPage(AuthenticatonResult result, Action returnCallback) { _returnCallback = returnCallback; var stack = new StackLayout { VerticalOptions = LayoutOptions.Center, HorizontalOptions = LayoutOptions.Center }; if (result) { stack.Children.Add(new Label { Text = $"Provider: {result.Account.Provider}" }); stack.Children.Add(new Label { Text = $"Id: {result.Account.Id}" }); stack.Children.Add(new Label { Text = $"Name: {result.Account.DisplayName}" }); stack.Children.Add(new Label { Text = $"Access Token: {result.Account.AccessToken}" }); } else { stack.Children.Add(new Label { Text = "Authentication failed!" }); stack.Children.Add(new Label { Text = $"Reason: {result.ErrorMessage}" }); } stack.Children.Add(new Button { Text = "Back", Command = new Command(returnCallback) }); Content = stack; } public void HandleBack() { _returnCallback?.Invoke(); } } }
Handle physical back button in result view
Handle physical back button in result view
C#
mit
Bigsby/Xamarin.Forms.OAuth
75f88f087620ac0609f5dd852a85b1094b602c8a
Sync/Program.cs
Sync/Program.cs
using Sync.Command; using Sync.MessageFilter; using Sync.Plugins; using Sync.Source; using Sync.Tools; using System; using System.Diagnostics; using static Sync.Tools.IO; namespace Sync { public static class Program { //public static I18n i18n; static void Main(string[] args) { /* 程序工作流程: * 1.程序枚举所有插件,保存所有IPlugin到List中 * 2.程序整理出所有的List<ISourceBase> * 3.初始化Sync类,Sync类检测配置文件,用正确的类初始化SyncInstance * 4.程序IO Manager开始工作,等待用户输入 */ I18n.Instance.ApplyLanguage(new DefaultI18n()); while(true) { SyncHost.Instance = new SyncHost(); SyncHost.Instance.Load(); CurrentIO.WriteWelcome(); string cmd = CurrentIO.ReadCommand(); while (true) { SyncHost.Instance.Commands.invokeCmdString(cmd); cmd = CurrentIO.ReadCommand(); } } } } }
using Sync.Command; using Sync.MessageFilter; using Sync.Plugins; using Sync.Source; using Sync.Tools; using System; using System.Diagnostics; using static Sync.Tools.IO; namespace Sync { public static class Program { //public static I18n i18n; static void Main(string[] args) { /* 程序工作流程: * 1.程序枚举所有插件,保存所有IPlugin到List中 * 2.程序整理出所有的List<ISourceBase> * 3.初始化Sync类,Sync类检测配置文件,用正确的类初始化SyncInstance * 4.程序IO Manager开始工作,等待用户输入 */ I18n.Instance.ApplyLanguage(new DefaultI18n()); while(true) { SyncHost.Instance = new SyncHost(); SyncHost.Instance.Load(); CurrentIO.WriteWelcome(); string cmd = ""; while (true) { SyncHost.Instance.Commands.invokeCmdString(cmd); cmd = CurrentIO.ReadCommand(); } } } } }
Move input block for thread safe
Move input block for thread safe
C#
mit
Deliay/osuSync,Deliay/Sync
045a611730a253c43330e932eb661f7fe262a2ad
AzureIoTHubConnectedServiceLibrary/Handler.VisualC.WAC.cs
AzureIoTHubConnectedServiceLibrary/Handler.VisualC.WAC.cs
using Microsoft.VisualStudio.ConnectedServices; namespace AzureIoTHubConnectedService { [ConnectedServiceHandlerExport("Microsoft.AzureIoTHubService", AppliesTo = "VisualC+WindowsAppContainer")] internal class CppHandlerWAC : GenericAzureIoTHubServiceHandler { protected override HandlerManifest BuildHandlerManifest(ConnectedServiceHandlerContext context) { HandlerManifest manifest = new HandlerManifest(); manifest.PackageReferences.Add(new NuGetReference("Newtonsoft.Json", "6.0.8")); manifest.PackageReferences.Add(new NuGetReference("Microsoft.Azure.Devices.Client", "1.0.1")); manifest.Files.Add(new FileToAdd("CPP/WAC/azure_iot_hub.cpp")); manifest.Files.Add(new FileToAdd("CPP/WAC/azure_iot_hub.h")); return manifest; } protected override AddServiceInstanceResult CreateAddServiceInstanceResult(ConnectedServiceHandlerContext context) { return new AddServiceInstanceResult( "", null ); } protected override ConnectedServiceHandlerHelper GetConnectedServiceHandlerHelper(ConnectedServiceHandlerContext context) { return new AzureIoTHubConnectedServiceHandlerHelper(context); } } }
using Microsoft.VisualStudio.ConnectedServices; namespace AzureIoTHubConnectedService { #if false // Disabled to a bug: https://github.com/Azure/azure-iot-sdks/issues/289 [ConnectedServiceHandlerExport("Microsoft.AzureIoTHubService", AppliesTo = "VisualC+WindowsAppContainer")] #endif internal class CppHandlerWAC : GenericAzureIoTHubServiceHandler { protected override HandlerManifest BuildHandlerManifest(ConnectedServiceHandlerContext context) { HandlerManifest manifest = new HandlerManifest(); manifest.PackageReferences.Add(new NuGetReference("Newtonsoft.Json", "6.0.8")); manifest.PackageReferences.Add(new NuGetReference("Microsoft.Azure.Devices.Client", "1.0.1")); manifest.Files.Add(new FileToAdd("CPP/WAC/azure_iot_hub.cpp")); manifest.Files.Add(new FileToAdd("CPP/WAC/azure_iot_hub.h")); return manifest; } protected override AddServiceInstanceResult CreateAddServiceInstanceResult(ConnectedServiceHandlerContext context) { return new AddServiceInstanceResult( "", null ); } protected override ConnectedServiceHandlerHelper GetConnectedServiceHandlerHelper(ConnectedServiceHandlerContext context) { return new AzureIoTHubConnectedServiceHandlerHelper(context); } } }
Disable UWP C++ (for now)
Disable UWP C++ (for now)
C#
mit
Azure/azure-iot-hub-vs-cs,Azure/azure-iot-hub-vs-cs,Azure/azure-iot-hub-vs-cs
334fb7d4753386c6d534efe27e80e421a3b8a94f
osu.Game/Online/Multiplayer/IndexPlaylistScoresRequest.cs
osu.Game/Online/Multiplayer/IndexPlaylistScoresRequest.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using Newtonsoft.Json; using osu.Game.Online.API; namespace osu.Game.Online.Multiplayer { public class IndexPlaylistScoresRequest : APIRequest<RoomPlaylistScores> { private readonly int roomId; private readonly int playlistItemId; public IndexPlaylistScoresRequest(int roomId, int playlistItemId) { this.roomId = roomId; this.playlistItemId = playlistItemId; } protected override string Target => $@"rooms/{roomId}/playlist/{playlistItemId}/scores"; } public class RoomPlaylistScores { [JsonProperty("scores")] public List<MultiplayerScore> Scores { get; set; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using Newtonsoft.Json; using osu.Framework.IO.Network; using osu.Game.Extensions; using osu.Game.Online.API; using osu.Game.Online.API.Requests; namespace osu.Game.Online.Multiplayer { /// <summary> /// Returns a list of scores for the specified playlist item. /// </summary> public class IndexPlaylistScoresRequest : APIRequest<RoomPlaylistScores> { private readonly int roomId; private readonly int playlistItemId; private readonly Cursor cursor; private readonly MultiplayerScoresSort? sort; public IndexPlaylistScoresRequest(int roomId, int playlistItemId, Cursor cursor = null, MultiplayerScoresSort? sort = null) { this.roomId = roomId; this.playlistItemId = playlistItemId; this.cursor = cursor; this.sort = sort; } protected override WebRequest CreateWebRequest() { var req = base.CreateWebRequest(); req.AddCursor(cursor); switch (sort) { case MultiplayerScoresSort.Ascending: req.AddParameter("sort", "scores_asc"); break; case MultiplayerScoresSort.Descending: req.AddParameter("sort", "scores_desc"); break; } return req; } protected override string Target => $@"rooms/{roomId}/playlist/{playlistItemId}/scores"; } public class RoomPlaylistScores { [JsonProperty("scores")] public List<MultiplayerScore> Scores { get; set; } } }
Add additional params to index request
Add additional params to index request
C#
mit
UselessToucan/osu,peppy/osu-new,peppy/osu,smoogipoo/osu,peppy/osu,ppy/osu,UselessToucan/osu,UselessToucan/osu,NeoAdonis/osu,smoogipoo/osu,NeoAdonis/osu,ppy/osu,smoogipoo/osu,peppy/osu,smoogipooo/osu,ppy/osu,NeoAdonis/osu
168a7a588b62b3f087e1d6e9785b7e8eeb2f9959
osu.Game/Rulesets/Difficulty/TimedDifficultyAttributes.cs
osu.Game/Rulesets/Difficulty/TimedDifficultyAttributes.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; namespace osu.Game.Rulesets.Difficulty { /// <summary> /// Wraps a <see cref="DifficultyAttributes"/> object and adds a time value for which the attribute is valid. /// Output by <see cref="DifficultyCalculator.CalculateTimed"/>. /// </summary> public class TimedDifficultyAttributes : IComparable<TimedDifficultyAttributes> { /// <summary> /// The non-clock-adjusted time value at which the attributes take effect. /// </summary> public readonly double Time; /// <summary> /// The attributes. /// </summary> public readonly DifficultyAttributes Attributes; public TimedDifficultyAttributes(double time, DifficultyAttributes attributes) { Time = time; Attributes = attributes; } public int CompareTo(TimedDifficultyAttributes other) => Time.CompareTo(other.Time); } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; namespace osu.Game.Rulesets.Difficulty { /// <summary> /// Wraps a <see cref="DifficultyAttributes"/> object and adds a time value for which the attribute is valid. /// Output by <see cref="DifficultyCalculator.CalculateTimed"/>. /// </summary> public class TimedDifficultyAttributes : IComparable<TimedDifficultyAttributes> { /// <summary> /// The non-clock-adjusted time value at which the attributes take effect. /// </summary> public readonly double Time; /// <summary> /// The attributes. /// </summary> public readonly DifficultyAttributes Attributes; /// <summary> /// Creates new <see cref="TimedDifficultyAttributes"/>. /// </summary> /// <param name="time">The non-clock-adjusted time value at which the attributes take effect.</param> /// <param name="attributes">The attributes.</param> public TimedDifficultyAttributes(double time, DifficultyAttributes attributes) { Time = time; Attributes = attributes; } public int CompareTo(TimedDifficultyAttributes other) => Time.CompareTo(other.Time); } }
Add xmldoc to ctor also
Add xmldoc to ctor also
C#
mit
peppy/osu,NeoAdonis/osu,smoogipooo/osu,NeoAdonis/osu,ppy/osu,ppy/osu,smoogipoo/osu,peppy/osu,smoogipoo/osu,smoogipoo/osu,peppy/osu,ppy/osu,NeoAdonis/osu
82cb85bba1c0ba0e2ac8343f9f6716a6afbf9f82
src/Orchard/Caching/Cache.cs
src/Orchard/Caching/Cache.cs
using System; using System.Collections.Generic; using System.Linq; namespace Orchard.Caching { public class Cache<TKey, TResult> : ICache<TKey, TResult> { private readonly Dictionary<TKey, CacheEntry> _entries; public Cache() { _entries = new Dictionary<TKey, CacheEntry>(); } public TResult Get(TKey key, Func<AcquireContext<TKey>, TResult> acquire) { CacheEntry entry; if (!_entries.TryGetValue(key, out entry) || entry.Tokens.Any(t => !t.IsCurrent)) { entry = new CacheEntry { Tokens = new List<IVolatileToken>() }; var context = new AcquireContext<TKey>(key, volatileItem => entry.Tokens.Add(volatileItem)); entry.Result = acquire(context); _entries[key] = entry; } return entry.Result; } private class CacheEntry { public TResult Result { get; set; } public IList<IVolatileToken> Tokens { get; set; } } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; namespace Orchard.Caching { public class Cache<TKey, TResult> : ICache<TKey, TResult> { private readonly ConcurrentDictionary<TKey, CacheEntry> _entries; public Cache() { _entries = new ConcurrentDictionary<TKey, CacheEntry>(); } public TResult Get(TKey key, Func<AcquireContext<TKey>, TResult> acquire) { var entry = _entries.AddOrUpdate(key, // "Add" lambda k => CreateEntry(k, acquire), // "Update" lamdba (k, currentEntry) => (currentEntry.Tokens.All(t => t.IsCurrent) ? currentEntry : CreateEntry(k, acquire))); return entry.Result; } private static CacheEntry CreateEntry(TKey k, Func<AcquireContext<TKey>, TResult> acquire) { var entry = new CacheEntry { Tokens = new List<IVolatileToken>() }; var context = new AcquireContext<TKey>(k, volatileItem => entry.Tokens.Add(volatileItem)); entry.Result = acquire(context); return entry; } private class CacheEntry { public TResult Result { get; set; } public IList<IVolatileToken> Tokens { get; set; } } } }
Fix concurrency issue accessing Dictionary instance
Fix concurrency issue accessing Dictionary instance --HG-- branch : dev
C#
bsd-3-clause
li0803/Orchard,xiaobudian/Orchard,austinsc/Orchard,smartnet-developers/Orchard,hbulzy/Orchard,harmony7/Orchard,m2cms/Orchard,Ermesx/Orchard,bigfont/orchard-continuous-integration-demo,qt1/Orchard,kouweizhong/Orchard,armanforghani/Orchard,OrchardCMS/Orchard,omidnasri/Orchard,MetSystem/Orchard,tobydodds/folklife,mgrowan/Orchard,Serlead/Orchard,AdvantageCS/Orchard,Codinlab/Orchard,marcoaoteixeira/Orchard,hhland/Orchard,TalaveraTechnologySolutions/Orchard,jtkech/Orchard,AEdmunds/beautiful-springtime,alejandroaldana/Orchard,huoxudong125/Orchard,arminkarimi/Orchard,harmony7/Orchard,bedegaming-aleksej/Orchard,omidnasri/Orchard,andyshao/Orchard,aaronamm/Orchard,geertdoornbos/Orchard,vard0/orchard.tan,AdvantageCS/Orchard,luchaoshuai/Orchard,AndreVolksdorf/Orchard,OrchardCMS/Orchard,mgrowan/Orchard,Praggie/Orchard,Morgma/valleyviewknolls,oxwanawxo/Orchard,Serlead/Orchard,Morgma/valleyviewknolls,abhishekluv/Orchard,Codinlab/Orchard,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,ericschultz/outercurve-orchard,xiaobudian/Orchard,SeyDutch/Airbrush,huoxudong125/Orchard,omidnasri/Orchard,huoxudong125/Orchard,rtpHarry/Orchard,rtpHarry/Orchard,TaiAivaras/Orchard,TalaveraTechnologySolutions/Orchard,emretiryaki/Orchard,brownjordaninternational/OrchardCMS,cooclsee/Orchard,ehe888/Orchard,abhishekluv/Orchard,Serlead/Orchard,austinsc/Orchard,Praggie/Orchard,luchaoshuai/Orchard,caoxk/orchard,mgrowan/Orchard,Cphusion/Orchard,hhland/Orchard,Fogolan/OrchardForWork,arminkarimi/Orchard,li0803/Orchard,xkproject/Orchard,aaronamm/Orchard,LaserSrl/Orchard,Dolphinsimon/Orchard,jagraz/Orchard,austinsc/Orchard,Lombiq/Orchard,omidnasri/Orchard,andyshao/Orchard,mgrowan/Orchard,geertdoornbos/Orchard,brownjordaninternational/OrchardCMS,kgacova/Orchard,SeyDutch/Airbrush,princeppy/JPYSites-Orchard-Azure-Live-SourceCode,angelapper/Orchard,jerryshi2007/Orchard,DonnotRain/Orchard,TalaveraTechnologySolutions/Orchard,vard0/orchard.tan,Dolphinsimon/Orchard,AndreVolksdorf/Orchard,xiaobudian/Orchard,KeithRaven/Orchard,NIKASoftwareDevs/Orchard,AndreVolksdorf/Orchard,jimasp/Orchard,salarvand/Portal,JRKelso/Orchard,SouleDesigns/SouleDesigns.Orchard,johnnyqian/Orchard,asabbott/chicagodevnet-website,enspiral-dev-academy/Orchard,stormleoxia/Orchard,SeyDutch/Airbrush,TalaveraTechnologySolutions/Orchard,KeithRaven/Orchard,LaserSrl/Orchard,OrchardCMS/Orchard-Harvest-Website,grapto/Orchard.CloudBust,Ermesx/Orchard,OrchardCMS/Orchard,openbizgit/Orchard,mgrowan/Orchard,phillipsj/Orchard,fassetar/Orchard,Serlead/Orchard,Sylapse/Orchard.HttpAuthSample,stormleoxia/Orchard,SzymonSel/Orchard,harmony7/Orchard,dozoft/Orchard,dburriss/Orchard,TalaveraTechnologySolutions/Orchard,jagraz/Orchard,qt1/Orchard,fortunearterial/Orchard,ehe888/Orchard,dcinzona/Orchard-Harvest-Website,xiaobudian/Orchard,salarvand/orchard,hbulzy/Orchard,xkproject/Orchard,emretiryaki/Orchard,MetSystem/Orchard,jchenga/Orchard,jaraco/orchard,xkproject/Orchard,smartnet-developers/Orchard,phillipsj/Orchard,dcinzona/Orchard,xiaobudian/Orchard,planetClaire/Orchard-LETS,jimasp/Orchard,fortunearterial/Orchard,openbizgit/Orchard,kgacova/Orchard,JRKelso/Orchard,SeyDutch/Airbrush,jersiovic/Orchard,yersans/Orchard,Inner89/Orchard,bigfont/orchard-cms-modules-and-themes,salarvand/orchard,austinsc/Orchard,AEdmunds/beautiful-springtime,omidnasri/Orchard,sebastienros/msc,salarvand/orchard,abhishekluv/Orchard,asabbott/chicagodevnet-website,fortunearterial/Orchard,salarvand/orchard,SouleDesigns/SouleDesigns.Orchard,jerryshi2007/Orchard,dozoft/Orchard,xkproject/Orchard,dburriss/Orchard,jtkech/Orchard,m2cms/Orchard,enspiral-dev-academy/Orchard,SzymonSel/Orchard,Morgma/valleyviewknolls,emretiryaki/Orchard,johnnyqian/Orchard,geertdoornbos/Orchard,Lombiq/Orchard,brownjordaninternational/OrchardCMS,hannan-azam/Orchard,RoyalVeterinaryCollege/Orchard,dmitry-urenev/extended-orchard-cms-v10.1,jimasp/Orchard,infofromca/Orchard,Codinlab/Orchard,SzymonSel/Orchard,Cphusion/Orchard,tobydodds/folklife,jaraco/orchard,JRKelso/Orchard,MpDzik/Orchard,sfmskywalker/Orchard,jagraz/Orchard,tobydodds/folklife,Praggie/Orchard,spraiin/Orchard,jagraz/Orchard,jersiovic/Orchard,harmony7/Orchard,cooclsee/Orchard,dburriss/Orchard,neTp9c/Orchard,dcinzona/Orchard,Praggie/Orchard,planetClaire/Orchard-LETS,angelapper/Orchard,OrchardCMS/Orchard-Harvest-Website,emretiryaki/Orchard,grapto/Orchard.CloudBust,TalaveraTechnologySolutions/Orchard,cryogen/orchard,LaserSrl/Orchard,princeppy/JPYSites-Orchard-Azure-Live-SourceCode,vard0/orchard.tan,jerryshi2007/Orchard,dmitry-urenev/extended-orchard-cms-v10.1,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,RoyalVeterinaryCollege/Orchard,TalaveraTechnologySolutions/Orchard,dozoft/Orchard,patricmutwiri/Orchard,aaronamm/Orchard,planetClaire/Orchard-LETS,Lombiq/Orchard,OrchardCMS/Orchard-Harvest-Website,bigfont/orchard-cms-modules-and-themes,geertdoornbos/Orchard,Fogolan/OrchardForWork,abhishekluv/Orchard,stormleoxia/Orchard,Sylapse/Orchard.HttpAuthSample,Dolphinsimon/Orchard,yersans/Orchard,huoxudong125/Orchard,neTp9c/Orchard,JRKelso/Orchard,m2cms/Orchard,omidnasri/Orchard,Inner89/Orchard,Morgma/valleyviewknolls,spraiin/Orchard,DonnotRain/Orchard,oxwanawxo/Orchard,yersans/Orchard,Sylapse/Orchard.HttpAuthSample,DonnotRain/Orchard,phillipsj/Orchard,yersans/Orchard,bedegaming-aleksej/Orchard,abhishekluv/Orchard,grapto/Orchard.CloudBust,dcinzona/Orchard,armanforghani/Orchard,DonnotRain/Orchard,neTp9c/Orchard,AndreVolksdorf/Orchard,andyshao/Orchard,bigfont/orchard-cms-modules-and-themes,qt1/orchard4ibn,jerryshi2007/Orchard,jchenga/Orchard,jimasp/Orchard,TaiAivaras/Orchard,bigfont/orchard-cms-modules-and-themes,dcinzona/Orchard,Anton-Am/Orchard,Inner89/Orchard,dcinzona/Orchard-Harvest-Website,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,infofromca/Orchard,gcsuk/Orchard,kouweizhong/Orchard,arminkarimi/Orchard,ericschultz/outercurve-orchard,sfmskywalker/Orchard,MetSystem/Orchard,infofromca/Orchard,luchaoshuai/Orchard,li0803/Orchard,mvarblow/Orchard,dcinzona/Orchard,KeithRaven/Orchard,NIKASoftwareDevs/Orchard,escofieldnaxos/Orchard,hhland/Orchard,oxwanawxo/Orchard,vard0/orchard.tan,brownjordaninternational/OrchardCMS,patricmutwiri/Orchard,kgacova/Orchard,JRKelso/Orchard,bedegaming-aleksej/Orchard,hbulzy/Orchard,MpDzik/Orchard,grapto/Orchard.CloudBust,vard0/orchard.tan,openbizgit/Orchard,TaiAivaras/Orchard,yonglehou/Orchard,gcsuk/Orchard,sebastienros/msc,TaiAivaras/Orchard,caoxk/orchard,princeppy/JPYSites-Orchard-Azure-Live-SourceCode,kouweizhong/Orchard,johnnyqian/Orchard,patricmutwiri/Orchard,grapto/Orchard.CloudBust,openbizgit/Orchard,fortunearterial/Orchard,bigfont/orchard-continuous-integration-demo,kouweizhong/Orchard,AdvantageCS/Orchard,sfmskywalker/Orchard,Sylapse/Orchard.HttpAuthSample,hannan-azam/Orchard,smartnet-developers/Orchard,Codinlab/Orchard,Morgma/valleyviewknolls,li0803/Orchard,hhland/Orchard,SzymonSel/Orchard,Cphusion/Orchard,mvarblow/Orchard,OrchardCMS/Orchard,SouleDesigns/SouleDesigns.Orchard,Sylapse/Orchard.HttpAuthSample,Serlead/Orchard,RoyalVeterinaryCollege/Orchard,DonnotRain/Orchard,spraiin/Orchard,vairam-svs/Orchard,jersiovic/Orchard,sebastienros/msc,Dolphinsimon/Orchard,Anton-Am/Orchard,SouleDesigns/SouleDesigns.Orchard,brownjordaninternational/OrchardCMS,NIKASoftwareDevs/Orchard,armanforghani/Orchard,omidnasri/Orchard,dcinzona/Orchard-Harvest-Website,MpDzik/Orchard,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,armanforghani/Orchard,cooclsee/Orchard,AdvantageCS/Orchard,escofieldnaxos/Orchard,jchenga/Orchard,m2cms/Orchard,smartnet-developers/Orchard,neTp9c/Orchard,oxwanawxo/Orchard,OrchardCMS/Orchard-Harvest-Website,yonglehou/Orchard,Anton-Am/Orchard,salarvand/Portal,AndreVolksdorf/Orchard,enspiral-dev-academy/Orchard,hbulzy/Orchard,qt1/orchard4ibn,infofromca/Orchard,jaraco/orchard,ehe888/Orchard,dmitry-urenev/extended-orchard-cms-v10.1,AdvantageCS/Orchard,planetClaire/Orchard-LETS,Ermesx/Orchard,asabbott/chicagodevnet-website,OrchardCMS/Orchard-Harvest-Website,NIKASoftwareDevs/Orchard,geertdoornbos/Orchard,enspiral-dev-academy/Orchard,planetClaire/Orchard-LETS,alejandroaldana/Orchard,austinsc/Orchard,MetSystem/Orchard,dburriss/Orchard,aaronamm/Orchard,jtkech/Orchard,vairam-svs/Orchard,qt1/Orchard,SouleDesigns/SouleDesigns.Orchard,qt1/Orchard,Dolphinsimon/Orchard,mvarblow/Orchard,OrchardCMS/Orchard,smartnet-developers/Orchard,MetSystem/Orchard,alejandroaldana/Orchard,jtkech/Orchard,Cphusion/Orchard,vard0/orchard.tan,salarvand/Portal,andyshao/Orchard,fortunearterial/Orchard,marcoaoteixeira/Orchard,infofromca/Orchard,vairam-svs/Orchard,Cphusion/Orchard,Ermesx/Orchard,harmony7/Orchard,xkproject/Orchard,omidnasri/Orchard,caoxk/orchard,LaserSrl/Orchard,jerryshi2007/Orchard,escofieldnaxos/Orchard,gcsuk/Orchard,dcinzona/Orchard-Harvest-Website,abhishekluv/Orchard,IDeliverable/Orchard,emretiryaki/Orchard,m2cms/Orchard,rtpHarry/Orchard,dozoft/Orchard,qt1/orchard4ibn,jimasp/Orchard,salarvand/orchard,cooclsee/Orchard,kgacova/Orchard,sebastienros/msc,Fogolan/OrchardForWork,angelapper/Orchard,kgacova/Orchard,KeithRaven/Orchard,qt1/orchard4ibn,escofieldnaxos/Orchard,sfmskywalker/Orchard,yonglehou/Orchard,OrchardCMS/Orchard-Harvest-Website,dmitry-urenev/extended-orchard-cms-v10.1,IDeliverable/Orchard,Lombiq/Orchard,AEdmunds/beautiful-springtime,TaiAivaras/Orchard,kouweizhong/Orchard,Anton-Am/Orchard,jtkech/Orchard,enspiral-dev-academy/Orchard,johnnyqian/Orchard,TalaveraTechnologySolutions/Orchard,qt1/Orchard,Inner89/Orchard,SeyDutch/Airbrush,vairam-svs/Orchard,jchenga/Orchard,caoxk/orchard,princeppy/JPYSites-Orchard-Azure-Live-SourceCode,cryogen/orchard,qt1/orchard4ibn,fassetar/Orchard,Codinlab/Orchard,andyshao/Orchard,bigfont/orchard-cms-modules-and-themes,oxwanawxo/Orchard,vairam-svs/Orchard,rtpHarry/Orchard,stormleoxia/Orchard,arminkarimi/Orchard,aaronamm/Orchard,dmitry-urenev/extended-orchard-cms-v10.1,SzymonSel/Orchard,angelapper/Orchard,angelapper/Orchard,bigfont/orchard-continuous-integration-demo,ehe888/Orchard,bedegaming-aleksej/Orchard,patricmutwiri/Orchard,ericschultz/outercurve-orchard,IDeliverable/Orchard,IDeliverable/Orchard,hannan-azam/Orchard,alejandroaldana/Orchard,jersiovic/Orchard,tobydodds/folklife,IDeliverable/Orchard,MpDzik/Orchard,RoyalVeterinaryCollege/Orchard,Ermesx/Orchard,Lombiq/Orchard,RoyalVeterinaryCollege/Orchard,MpDzik/Orchard,fassetar/Orchard,luchaoshuai/Orchard,dcinzona/Orchard-Harvest-Website,MpDzik/Orchard,NIKASoftwareDevs/Orchard,Inner89/Orchard,asabbott/chicagodevnet-website,sfmskywalker/Orchard,spraiin/Orchard,dcinzona/Orchard-Harvest-Website,marcoaoteixeira/Orchard,mvarblow/Orchard,marcoaoteixeira/Orchard,marcoaoteixeira/Orchard,escofieldnaxos/Orchard,Anton-Am/Orchard,li0803/Orchard,jersiovic/Orchard,jagraz/Orchard,Fogolan/OrchardForWork,patricmutwiri/Orchard,hannan-azam/Orchard,bedegaming-aleksej/Orchard,bigfont/orchard-continuous-integration-demo,salarvand/Portal,Praggie/Orchard,gcsuk/Orchard,salarvand/Portal,sebastienros/msc,arminkarimi/Orchard,AEdmunds/beautiful-springtime,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,phillipsj/Orchard,fassetar/Orchard,sfmskywalker/Orchard,jaraco/orchard,ericschultz/outercurve-orchard,phillipsj/Orchard,cryogen/orchard,yonglehou/Orchard,yersans/Orchard,stormleoxia/Orchard,omidnasri/Orchard,dburriss/Orchard,jchenga/Orchard,cryogen/orchard,sfmskywalker/Orchard,tobydodds/folklife,hannan-azam/Orchard,rtpHarry/Orchard,Fogolan/OrchardForWork,hbulzy/Orchard,sfmskywalker/Orchard,spraiin/Orchard,princeppy/JPYSites-Orchard-Azure-Live-SourceCode,qt1/orchard4ibn,yonglehou/Orchard,huoxudong125/Orchard,fassetar/Orchard,KeithRaven/Orchard,dozoft/Orchard,cooclsee/Orchard,luchaoshuai/Orchard,gcsuk/Orchard,LaserSrl/Orchard,alejandroaldana/Orchard,johnnyqian/Orchard,neTp9c/Orchard,armanforghani/Orchard,grapto/Orchard.CloudBust,mvarblow/Orchard,tobydodds/folklife,openbizgit/Orchard,hhland/Orchard,ehe888/Orchard
d9521343fb8dcf5d1aea7958463ff186ec7abbf5
FootballLeague/Services/UsersADSearcher.cs
FootballLeague/Services/UsersADSearcher.cs
using FootballLeague.Models; using System.DirectoryServices; namespace FootballLeague.Services { public class UsersADSearcher : IUsersADSearcher { public User LoadUserDetails(string userName) { var entry = new DirectoryEntry(); var searcher = new DirectorySearcher(entry); searcher.Filter = "(&(objectClass=user)(sAMAccountName=" + userName + "))"; searcher.PropertiesToLoad.Add("givenName"); searcher.PropertiesToLoad.Add("sn"); searcher.PropertiesToLoad.Add("mail"); var userProps = searcher.FindOne().Properties; var mail = userProps["mail"][0].ToString(); var first = userProps["givenName"][0].ToString(); var last = userProps["sn"][0].ToString(); return new User { Name = userName, Mail = mail, FirstName = first, LastName = last }; } } }
using System.Linq; using System.Web; using FootballLeague.Models; using System.DirectoryServices; namespace FootballLeague.Services { public class UsersADSearcher : IUsersADSearcher { public User LoadUserDetails(string userName) { var entry = new DirectoryEntry(); var searcher = new DirectorySearcher(entry); searcher.Filter = "(&(objectClass=user)(sAMAccountName=" + userName + "))"; searcher.PropertiesToLoad.Add("givenName"); searcher.PropertiesToLoad.Add("sn"); searcher.PropertiesToLoad.Add("mail"); try { var userProps = searcher.FindOne().Properties; var mail = userProps["mail"][0].ToString(); var first = userProps["givenName"][0].ToString(); var last = userProps["sn"][0].ToString(); return new User { Name = userName, Mail = mail, FirstName = first, LastName = last }; } catch { return new User { Name = HttpContext.Current.User.Identity.Name.Split('\\').Last(), Mail = "local@user.sk", FirstName = "Local", LastName = "User" }; } } } }
Use local user when not in domain
Use local user when not in domain
C#
mit
pecosk/football,pecosk/football
377039400fa0456f15382a024020d43d061fc9ae
Assets/Teak/Editor/TeakPreProcessDefiner.cs
Assets/Teak/Editor/TeakPreProcessDefiner.cs
using UnityEditor; using UnityEditor.Build; #if UNITY_2018_1_OR_NEWER using UnityEditor.Build.Reporting; #endif using UnityEngine; class TeakPreProcessDefiner : #if UNITY_2018_1_OR_NEWER IPreprocessBuildWithReport #else IPreprocessBuild #endif { public int callbackOrder { get { return 0; } } public static readonly string[] TeakDefines = new string[] { "TEAK_2_0_OR_NEWER" }; #if UNITY_2018_1_OR_NEWER public void OnPreprocessBuild(BuildReport report) { SetTeakPreprocesorDefines(report.summary.platformGroup); } #else public void OnPreprocessBuild(BuildTarget target, string path) { SetTeakPreprocesorDefines(BuildPipeline.GetBuildTargetGroup(target)); } #endif private void SetTeakPreprocesorDefines(BuildTargetGroup targetGroup) { string defines = PlayerSettings.GetScriptingDefineSymbolsForGroup(targetGroup); if (!defines.EndsWith(";")) defines += ";"; defines += string.Join(";", TeakDefines); PlayerSettings.SetScriptingDefineSymbolsForGroup(targetGroup, defines); } }
using UnityEditor; using UnityEditor.Build; #if UNITY_2018_1_OR_NEWER using UnityEditor.Build.Reporting; #endif using UnityEngine; using System.Collections.Generic; class TeakPreProcessDefiner : #if UNITY_2018_1_OR_NEWER IPreprocessBuildWithReport #else IPreprocessBuild #endif { public int callbackOrder { get { return 0; } } public static readonly string[] TeakDefines = new string[] { "TEAK_2_0_OR_NEWER" }; #if UNITY_2018_1_OR_NEWER public void OnPreprocessBuild(BuildReport report) { SetTeakPreprocesorDefines(report.summary.platformGroup); } #else public void OnPreprocessBuild(BuildTarget target, string path) { SetTeakPreprocesorDefines(BuildPipeline.GetBuildTargetGroup(target)); } #endif private void SetTeakPreprocesorDefines(BuildTargetGroup targetGroup) { string[] existingDefines = PlayerSettings.GetScriptingDefineSymbolsForGroup(targetGroup).Split(";"); HashSet<string> defines = new HashSet<string>(existingDefines); defines.UnionWith(TeakDefines); PlayerSettings.SetScriptingDefineSymbolsForGroup(targetGroup, string.Join(";", defines.ToArray())); } }
Use a set of defines, and some generics
Use a set of defines, and some generics
C#
apache-2.0
GoCarrot/teak-unity,GoCarrot/teak-unity,GoCarrot/teak-unity,GoCarrot/teak-unity,GoCarrot/teak-unity
8783c703d8cbdf19d9b98b58b0d51f53512b0df4
src/Stripe.Tests.XUnit/coupons/_fixture.cs
src/Stripe.Tests.XUnit/coupons/_fixture.cs
using System; using System.Collections.Generic; namespace Stripe.Tests.Xunit { public class coupons_fixture : IDisposable { public StripeCouponCreateOptions CouponCreateOptions { get; set; } public StripeCouponUpdateOptions CouponUpdateOptions { get; set; } public StripeCoupon Coupon { get; set; } public StripeCoupon CouponRetrieved { get; set; } public StripeCoupon CouponUpdated { get; set; } public StripeDeleted CouponDeleted { get; set; } public StripeList<StripeCoupon> CouponsList { get; } public coupons_fixture() { CouponCreateOptions = new StripeCouponCreateOptions() { Id = "test-coupon-" + Guid.NewGuid().ToString() + " ", PercentOff = 25, Duration = "repeating", DurationInMonths = 3, }; CouponUpdateOptions = new StripeCouponUpdateOptions { Metadata = new Dictionary<string, string>{{"key_1", "value_1"}} }; var service = new StripeCouponService(Cache.ApiKey); Coupon = service.Create(CouponCreateOptions); CouponRetrieved = service.Get(Coupon.Id); CouponUpdated = service.Update(Coupon.Id, CouponUpdateOptions); CouponsList = service.List(); CouponDeleted = service.Delete(Coupon.Id); } public void Dispose() { } } }
using System; using System.Collections.Generic; namespace Stripe.Tests.Xunit { public class coupons_fixture : IDisposable { public StripeCouponCreateOptions CouponCreateOptions { get; set; } public StripeCouponUpdateOptions CouponUpdateOptions { get; set; } public StripeCoupon Coupon { get; set; } public StripeCoupon CouponRetrieved { get; set; } public StripeCoupon CouponUpdated { get; set; } public StripeDeleted CouponDeleted { get; set; } public StripeList<StripeCoupon> CouponsList { get; } public coupons_fixture() { CouponCreateOptions = new StripeCouponCreateOptions() { // Add a space at the end to ensure the ID is properly URL encoded // when passed in the URL for other methods Id = "test-coupon-" + Guid.NewGuid().ToString() + " ", PercentOff = 25, Duration = "repeating", DurationInMonths = 3, }; CouponUpdateOptions = new StripeCouponUpdateOptions { Metadata = new Dictionary<string, string>{{"key_1", "value_1"}} }; var service = new StripeCouponService(Cache.ApiKey); Coupon = service.Create(CouponCreateOptions); CouponRetrieved = service.Get(Coupon.Id); CouponUpdated = service.Update(Coupon.Id, CouponUpdateOptions); CouponsList = service.List(); CouponDeleted = service.Delete(Coupon.Id); } public void Dispose() { } } }
Add a detailed comment to explain why we test this
Add a detailed comment to explain why we test this
C#
apache-2.0
richardlawley/stripe.net,stripe/stripe-dotnet
c62779b03739388c3ada79a6a030531cb36486f5
src/NesZord.Core/Properties/AssemblyInfo.cs
src/NesZord.Core/Properties/AssemblyInfo.cs
using System.Resources; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("NesZord.Core")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("NesZord.Core")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
using System.Resources; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("NesZord.Core")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("NesZord.Core")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: InternalsVisibleTo("NesZord.Tests")]
Enable NesZord.Tests to se internal members of NesZord.Core
Enable NesZord.Tests to se internal members of NesZord.Core
C#
apache-2.0
rmterra/NesZord
f1117eb95074884465d7964acb6115797dded84e
src/RazorLight/Extensions/TypeExtensions.cs
src/RazorLight/Extensions/TypeExtensions.cs
using System; using System.Collections.Generic; using System.Dynamic; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; namespace RazorLight.Extensions { public static class TypeExtensions { public static ExpandoObject ToExpando(this object anonymousObject) { if (anonymousObject is ExpandoObject exp) { return exp; } IDictionary<string, object> expando = new ExpandoObject(); foreach (var propertyDescriptor in anonymousObject.GetType().GetTypeInfo().GetProperties()) { var obj = propertyDescriptor.GetValue(anonymousObject); expando.Add(propertyDescriptor.Name, obj); } return (ExpandoObject)expando; } public static bool IsAnonymousType(this Type type) { bool hasCompilerGeneratedAttribute = type.GetTypeInfo() .GetCustomAttributes(typeof(CompilerGeneratedAttribute), false) .Any(); bool nameContainsAnonymousType = type.FullName.Contains("AnonymousType"); bool isAnonymousType = hasCompilerGeneratedAttribute && nameContainsAnonymousType; return isAnonymousType; } } }
using System; using System.Collections.Generic; using System.Dynamic; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; namespace RazorLight.Extensions { public static class TypeExtensions { public static ExpandoObject ToExpando(this object anonymousObject) { if (anonymousObject is ExpandoObject exp) { return exp; } IDictionary<string, object> expando = new ExpandoObject(); foreach (var propertyDescriptor in anonymousObject.GetType().GetTypeInfo().GetProperties()) { var obj = propertyDescriptor.GetValue(anonymousObject); if (obj != null && obj.GetType().IsAnonymousType()) { obj = obj.ToExpando(); } expando.Add(propertyDescriptor.Name, obj); } return (ExpandoObject)expando; } public static bool IsAnonymousType(this Type type) { bool hasCompilerGeneratedAttribute = type.GetTypeInfo() .GetCustomAttributes(typeof(CompilerGeneratedAttribute), false) .Any(); bool nameContainsAnonymousType = type.FullName.Contains("AnonymousType"); bool isAnonymousType = hasCompilerGeneratedAttribute && nameContainsAnonymousType; return isAnonymousType; } } }
Add support for nested anonymous models
Add support for nested anonymous models
C#
apache-2.0
toddams/RazorLight,toddams/RazorLight
74d724bb076a82e39b423f4d29ec3457ebf63c77
src/Core/Extensions/FilterBooleanExtensions.cs
src/Core/Extensions/FilterBooleanExtensions.cs
using UnityEngine; namespace PrepareLanding.Core.Extensions { public static class FilterBooleanExtensions { public static string ToStringHuman(this FilterBoolean filterBool) { switch (filterBool) { case FilterBoolean.AndFiltering: return "AND"; case FilterBoolean.OrFiltering: return "OR"; default: return "UNK"; } } public static FilterBoolean Next(this FilterBoolean filterBoolean) { return (FilterBoolean)(((int)filterBoolean + 1) % (int)FilterBoolean.Undefined); } public static Color Color(this FilterBoolean filterBoolean) { switch (filterBoolean) { case FilterBoolean.AndFiltering: return Verse.ColorLibrary.BurntOrange; case FilterBoolean.OrFiltering: return Verse.ColorLibrary.BrightBlue; default: return UnityEngine.Color.black; } } } }
using UnityEngine; using Verse; namespace PrepareLanding.Core.Extensions { public static class FilterBooleanExtensions { public static string ToStringHuman(this FilterBoolean filterBool) { switch (filterBool) { case FilterBoolean.AndFiltering: return "PLMWTT_FilterBooleanOr".Translate(); case FilterBoolean.OrFiltering: return "PLMWTT_FilterBooleanAnd".Translate(); default: return "UNK"; } } public static FilterBoolean Next(this FilterBoolean filterBoolean) { return (FilterBoolean)(((int)filterBoolean + 1) % (int)FilterBoolean.Undefined); } public static Color Color(this FilterBoolean filterBoolean) { switch (filterBoolean) { case FilterBoolean.AndFiltering: return Verse.ColorLibrary.BurntOrange; case FilterBoolean.OrFiltering: return Verse.ColorLibrary.BrightBlue; default: return UnityEngine.Color.black; } } } }
Allow translation of boolean filtering text.
Allow translation of boolean filtering text.
C#
mit
neitsa/PrepareLanding,neitsa/PrepareLanding
d8b3ffa06e72f5ae415e8e402ace4a6839aa0ae3
src/OpenSage.Game/Utilities/PlatformUtility.cs
src/OpenSage.Game/Utilities/PlatformUtility.cs
using System; using System.Runtime.InteropServices; namespace OpenSage.Utilities { public static class PlatformUtility { /// <summary> /// Check if current platform is windows /// </summary> /// <returns></returns> public static bool IsWindowsPlatform() { switch (Environment.OSVersion.Platform) { case PlatformID.Win32Windows: case PlatformID.Win32NT: case PlatformID.WinCE: case PlatformID.Win32S: return true; default: return false; } } public static float GetDefaultDpi() { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { return 96.0f; } else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { return 72.0f; } else { return 1.0f; // TODO: What happens on Linux? } } } }
using System; using System.Runtime.InteropServices; namespace OpenSage.Utilities { public static class PlatformUtility { /// <summary> /// Check if current platform is windows /// </summary> /// <returns></returns> public static bool IsWindowsPlatform() { switch (Environment.OSVersion.Platform) { case PlatformID.Win32Windows: case PlatformID.Win32NT: case PlatformID.WinCE: case PlatformID.Win32S: return true; default: return false; } } public static float GetDefaultDpi() { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { return 96.0f; } else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { return 72.0f; } else { return 96.0f; // TODO: For GNOME3 the default DPI is 96 } } } }
Use correct Gnome3 default DPI
Use correct Gnome3 default DPI
C#
mit
feliwir/openSage,feliwir/openSage
91d572235eaf43a2ca9eb1ad562849322cd43468
Plugins/PluginScriptGenerator.cs
Plugins/PluginScriptGenerator.cs
using System.Text; using TweetDuck.Plugins.Enums; namespace TweetDuck.Plugins{ static class PluginScriptGenerator{ public static string GenerateConfig(PluginConfig config){ return config.AnyDisabled ? "window.TD_PLUGINS.disabled = [\""+string.Join("\",\"", config.DisabledPlugins)+"\"];" : string.Empty; } public static string GeneratePlugin(string pluginIdentifier, string pluginContents, int pluginToken, PluginEnvironment environment){ StringBuilder build = new StringBuilder(2*pluginIdentifier.Length+pluginContents.Length+165); build.Append("(function(").Append(environment.GetScriptVariables()).Append("){"); build.Append("let tmp={"); build.Append("id:\"").Append(pluginIdentifier).Append("\","); build.Append("obj:new class extends PluginBase{").Append(pluginContents).Append("}"); build.Append("};"); build.Append("tmp.obj.$id=\"").Append(pluginIdentifier).Append("\";"); build.Append("tmp.obj.$token=").Append(pluginToken).Append(";"); build.Append("window.TD_PLUGINS.install(tmp);"); build.Append("})(").Append(environment.GetScriptVariables()).Append(");"); return build.ToString(); } } }
using System.Globalization; using TweetDuck.Plugins.Enums; namespace TweetDuck.Plugins{ static class PluginScriptGenerator{ public static string GenerateConfig(PluginConfig config){ return config.AnyDisabled ? "window.TD_PLUGINS.disabled = [\""+string.Join("\",\"", config.DisabledPlugins)+"\"];" : string.Empty; } public static string GeneratePlugin(string pluginIdentifier, string pluginContents, int pluginToken, PluginEnvironment environment){ return PluginGen .Replace("%params", environment.GetScriptVariables()) .Replace("%id", pluginIdentifier) .Replace("%token", pluginToken.ToString(CultureInfo.InvariantCulture)) .Replace("%contents", pluginContents); } private const string PluginGen = "(function(%params,$d){let tmp={id:'%id',obj:new class extends PluginBase{%contents}};$d(tmp.obj,'$id',{value:'%id'});$d(tmp.obj,'$token',{value:%token});window.TD_PLUGINS.install(tmp);})(%params,Object.defineProperty);"; /* PluginGen (function(%params, $i, $d){ let tmp = { id: '%id', obj: new class extends PluginBase{%contents} }; $d(tmp.obj, '$id', { value: '%id' }); $d(tmp.obj, '$token', { value: %token }); window.TD_PLUGINS.install(tmp); })(%params, Object.defineProperty); */ } }
Make $id and $token properties in plugin objects unmodifiable
Make $id and $token properties in plugin objects unmodifiable
C#
mit
chylex/TweetDuck,chylex/TweetDuck,chylex/TweetDuck,chylex/TweetDuck
634a77748ab4fc326e4d227ec84d7404d21f0b7d
src/OmniSharp.Abstractions/Models/Request.cs
src/OmniSharp.Abstractions/Models/Request.cs
using System.Collections.Generic; using Newtonsoft.Json; namespace OmniSharp.Models { public class Request : SimpleFileRequest { [JsonConverter(typeof(ZeroBasedIndexConverter))] public int Line { get; set; } [JsonConverter(typeof(ZeroBasedIndexConverter))] public int Column { get; set; } public string Buffer { get; set; } public IEnumerable<LinePositionSpanTextChange> Changes { get; set; } public bool ApplyChangesTogether { get; set; } } }
using System.Collections.Generic; using Newtonsoft.Json; namespace OmniSharp.Models { public class Request : SimpleFileRequest { [JsonConverter(typeof(ZeroBasedIndexConverter))] public int Line { get; set; } [JsonConverter(typeof(ZeroBasedIndexConverter))] public int Column { get; set; } public string Buffer { get; set; } public IEnumerable<LinePositionSpanTextChange> Changes { get; set; } [JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate)] public bool ApplyChangesTogether { get; set; } } }
Make ApplyChangesTogether automatically filled to false if not present.
Make ApplyChangesTogether automatically filled to false if not present.
C#
mit
OmniSharp/omnisharp-roslyn,OmniSharp/omnisharp-roslyn
426498a203d65c664829f8a255c5589ea9234782
src/LibYear.Lib/FileTypes/ProjectJsonFile.cs
src/LibYear.Lib/FileTypes/ProjectJsonFile.cs
using System.Collections.Generic; using System.IO; using System.Linq; using Newtonsoft.Json.Linq; namespace LibYear.Lib.FileTypes { public class ProjectJsonFile : IProjectFile { private string _fileContents; public string FileName { get; } public IDictionary<string, PackageVersion> Packages { get; } public ProjectJsonFile(string filename) { FileName = filename; _fileContents = File.ReadAllText(FileName); Packages = GetDependencies().ToDictionary(p => ((JProperty)p).Name.ToString(), p => PackageVersion.Parse(((JProperty)p).Value.ToString())); } private IEnumerable<JToken> GetDependencies() { return JObject.Parse(_fileContents).Descendants() .Where(d => d.Type == JTokenType.Property && d.Path.Contains("dependencies") && (!d.Path.Contains("[") || d.Path.EndsWith("]")) && ((JProperty)d).Value.Type == JTokenType.String); } public void Update(IEnumerable<Result> results) { lock (_fileContents) { foreach (var result in results) _fileContents = _fileContents.Replace($"\"{result.Name}\": \"{result.Installed.Version}\"", $"\"{result.Name}\": \"{result.Latest.Version}\""); File.WriteAllText(FileName, _fileContents); } } } }
using System.Collections.Generic; using System.IO; using System.Linq; using Newtonsoft.Json.Linq; namespace LibYear.Lib.FileTypes { public class ProjectJsonFile : IProjectFile { private string _fileContents; public string FileName { get; } public IDictionary<string, PackageVersion> Packages { get; } private readonly object _lock = new object(); public ProjectJsonFile(string filename) { FileName = filename; _fileContents = File.ReadAllText(FileName); Packages = GetDependencies().ToDictionary(p => ((JProperty)p).Name.ToString(), p => PackageVersion.Parse(((JProperty)p).Value.ToString())); } private IEnumerable<JToken> GetDependencies() { return JObject.Parse(_fileContents).Descendants() .Where(d => d.Type == JTokenType.Property && d.Path.Contains("dependencies") && (!d.Path.Contains("[") || d.Path.EndsWith("]")) && ((JProperty)d).Value.Type == JTokenType.String); } public void Update(IEnumerable<Result> results) { lock (_lock) { foreach (var result in results) { _fileContents = _fileContents.Replace($"\"{result.Name}\": \"{result.Installed.Version}\"", $"\"{result.Name}\": \"{result.Latest.Version}\""); } File.WriteAllText(FileName, _fileContents); } } } }
Fix JSON file locking issue
Fix JSON file locking issue
C#
mit
stevedesmond-ca/dotnet-libyear
f0558a7b59d2a5904176a69f57834ca639d4850b
LearnosityDemo/Pages/ItemsAPIDemo.cshtml.cs
LearnosityDemo/Pages/ItemsAPIDemo.cshtml.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using LearnositySDK.Request; using LearnositySDK.Utils; // static LearnositySDK.Credentials; namespace LearnosityDemo.Pages { public class ItemsAPIDemoModel : PageModel { public void OnGet() { // prepare all the params string service = "items"; JsonObject security = new JsonObject(); security.set("consumer_key", LearnositySDK.Credentials.ConsumerKey); security.set("domain", LearnositySDK.Credentials.Domain); security.set("user_id", Uuid.generate()); string secret = LearnositySDK.Credentials.ConsumerSecret; //JsonObject config = new JsonObject(); JsonObject request = new JsonObject(); request.set("user_id", Uuid.generate()); request.set("activity_template_id", "quickstart_examples_activity_template_001"); request.set("session_id", Uuid.generate()); request.set("activity_id", "quickstart_examples_activity_001"); request.set("rendering_type", "assess"); request.set("type", "submit_practice"); request.set("name", "Items API Quickstart"); //request.set("config", config); // Instantiate Init class Init init = new Init(service, security, secret, request); // Call the generate() method to retrieve a JavaScript object ViewData["InitJSON"] = init.generate(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using LearnositySDK.Request; using LearnositySDK.Utils; // static LearnositySDK.Credentials; namespace LearnosityDemo.Pages { public class ItemsAPIDemoModel : PageModel { public void OnGet() { // prepare all the params string service = "items"; JsonObject security = new JsonObject(); security.set("consumer_key", LearnositySDK.Credentials.ConsumerKey); security.set("domain", LearnositySDK.Credentials.Domain); security.set("user_id", Uuid.generate()); string secret = LearnositySDK.Credentials.ConsumerSecret; JsonObject request = new JsonObject(); request.set("user_id", Uuid.generate()); request.set("activity_template_id", "quickstart_examples_activity_template_001"); request.set("session_id", Uuid.generate()); request.set("activity_id", "quickstart_examples_activity_001"); request.set("rendering_type", "assess"); request.set("type", "submit_practice"); request.set("name", "Items API Quickstart"); request.set("state", "initial"); // Instantiate Init class Init init = new Init(service, security, secret, request); // Call the generate() method to retrieve a JavaScript object ViewData["InitJSON"] = init.generate(); } } }
Add example for state init option to quick-start guide example project.
[DOC] Add example for state init option to quick-start guide example project.
C#
apache-2.0
Learnosity/learnosity-sdk-asp.net,Learnosity/learnosity-sdk-asp.net,Learnosity/learnosity-sdk-asp.net
a6a67cf03159bc1085b2f9c1887f09ccaf59bba0
DesktopWidgets/Widgets/RSSFeed/Metadata.cs
DesktopWidgets/Widgets/RSSFeed/Metadata.cs
namespace DesktopWidgets.Widgets.RSSFeed { public static class Metadata { public const string FriendlyName = "RSS Headlines"; } }
namespace DesktopWidgets.Widgets.RSSFeed { public static class Metadata { public const string FriendlyName = "RSS Feed"; } }
Change "RSS Headlines" widget name
Change "RSS Headlines" widget name
C#
apache-2.0
danielchalmers/DesktopWidgets
93edc93c0cb26f3f6933b071b9f78b3614dcc58d
src/live.asp.net/Views/Shared/_AnalyticsHead.cshtml
src/live.asp.net/Views/Shared/_AnalyticsHead.cshtml
@using Microsoft.ApplicationInsights.Extensibility @inject TelemetryConfiguration TelemetryConfiguration <environment names="Production"> <script type="text/javascript"> (function (i, s, o, g, r, a, m) { i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () { (i[r].q = i[r].q || []).push(arguments) }, i[r].l = 1 * new Date(); a = s.createElement(o), m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m) })(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga'); ga('create', 'UA-61337531-1', 'auto', { 'name': 'mscTracker' }); ga('mscTracker.send', 'pageview'); </script> @Html.ApplicationInsightsJavaScript(TelemetryConfiguration) </environment>
@using Microsoft.ApplicationInsights.Extensibility @inject TelemetryConfiguration TelemetryConfiguration <environment names="Production"> <script type="text/javascript"> (function (i, s, o, g, r, a, m) { i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () { (i[r].q = i[r].q || []).push(arguments) }, i[r].l = 1 * new Date(); a = s.createElement(o), m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m) })(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga'); ga('create', 'UA-61337531-1', 'auto', { 'name': 'mscTracker' }); ga('create', 'UA-61337531-4', 'auto', { 'name': 'liveaspnetTracker' }); ga('mscTracker.send', 'pageview'); ga('liveaspnetTracker.send', 'pageview'); </script> @Html.ApplicationInsightsJavaScript(TelemetryConfiguration) </environment>
Add new Google Analytics tracking ID
Add new Google Analytics tracking ID
C#
mit
aspnet/live.asp.net,reactiveui/website,reactiveui/website,sejka/live.asp.net,pakrym/kudutest,aspnet/live.asp.net,pakrym/kudutest,reactiveui/website,aspnet/live.asp.net,reactiveui/website,sejka/live.asp.net
4ee99a3fe2802f7263bc787c212ecf2b89d3002b
WordPressRestApi/Properties/AssemblyInfo.cs
WordPressRestApi/Properties/AssemblyInfo.cs
using System.Resources; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("WordPressRestApi")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("DevFoundries")] [assembly: AssemblyProduct("WordPressRestApi")] [assembly: AssemblyCopyright("Copyright © 2017 Wm. Barrett Simms")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.3.0.0")] [assembly: AssemblyFileVersion("1.3.0.0")]
using System.Resources; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("WordPressRestApi")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("DevFoundries")] [assembly: AssemblyProduct("WordPressRestApi")] [assembly: AssemblyCopyright("Copyright © 2017 Wm. Barrett Simms")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.4.0.0")] [assembly: AssemblyFileVersion("1.4.0.0")]
Package rename and add support for Media
Package rename and add support for Media
C#
apache-2.0
wbsimms/WordPressRestApi
8cb2b512376e63c21e352b7326c98b8c1af37c66
Common/Data/Custom/Intrinio/IntrinioConfig.cs
Common/Data/Custom/Intrinio/IntrinioConfig.cs
using System; using QuantConnect.Parameters; using QuantConnect.Util; namespace QuantConnect.Data.Custom.Intrinio { /// <summary> /// Auxiliary class to access all Intrinio API data. /// </summary> public static class IntrinioConfig { /// <summary> /// </summary> public static RateGate RateGate = new RateGate(1, TimeSpan.FromMilliseconds(5000)); /// <summary> /// Check if Intrinio API user and password are not empty or null. /// </summary> public static bool IsInitialized => !string.IsNullOrWhiteSpace(User) && !string.IsNullOrWhiteSpace(Password); /// <summary> /// Intrinio API password /// </summary> public static string Password = string.Empty; /// <summary> /// Intrinio API user /// </summary> public static string User = string.Empty; /// <summary> /// Set the Intrinio API user and password. /// </summary> public static void SetUserAndPassword(string user, string password) { User = user; Password = password; if (!IsInitialized) { throw new InvalidOperationException("Please set a valid Intrinio user and password."); } } } }
using System; using QuantConnect.Parameters; using QuantConnect.Util; namespace QuantConnect.Data.Custom.Intrinio { /// <summary> /// Auxiliary class to access all Intrinio API data. /// </summary> public static class IntrinioConfig { /// <summary> /// </summary> public static RateGate RateGate = new RateGate(1, TimeSpan.FromMinutes(1)); /// <summary> /// Check if Intrinio API user and password are not empty or null. /// </summary> public static bool IsInitialized => !string.IsNullOrWhiteSpace(User) && !string.IsNullOrWhiteSpace(Password); /// <summary> /// Intrinio API password /// </summary> public static string Password = string.Empty; /// <summary> /// Intrinio API user /// </summary> public static string User = string.Empty; /// <summary> /// Set the Intrinio API user and password. /// </summary> public static void SetUserAndPassword(string user, string password) { User = user; Password = password; if (!IsInitialized) { throw new InvalidOperationException("Please set a valid Intrinio user and password."); } } } }
Increment Intrinio time between calls to 1 minute
Increment Intrinio time between calls to 1 minute The actual implementation uses the Intrinio `historical_data` end point and ask for CSV format. At the moment of development, the key they provided and the one used in the test has a limit of 1 call per second for the historical_data` end point`, now the key only free access 1 call per minute. This commit is the fastest fix for the test failing but is impractical for any user with a free account. Maybe a better solution is to implement `historical_data` end point and but asking for the JSON (default) format. This implies implementing reading the data from JSON and implement paging in the `BaseData.Read` method.
C#
apache-2.0
StefanoRaggi/Lean,JKarathiya/Lean,AlexCatarino/Lean,jameschch/Lean,Jay-Jay-D/LeanSTP,kaffeebrauer/Lean,StefanoRaggi/Lean,StefanoRaggi/Lean,AlexCatarino/Lean,kaffeebrauer/Lean,jameschch/Lean,jameschch/Lean,JKarathiya/Lean,QuantConnect/Lean,kaffeebrauer/Lean,jameschch/Lean,JKarathiya/Lean,Jay-Jay-D/LeanSTP,kaffeebrauer/Lean,jameschch/Lean,Jay-Jay-D/LeanSTP,JKarathiya/Lean,QuantConnect/Lean,AlexCatarino/Lean,Jay-Jay-D/LeanSTP,AlexCatarino/Lean,Jay-Jay-D/LeanSTP,StefanoRaggi/Lean,StefanoRaggi/Lean,kaffeebrauer/Lean,QuantConnect/Lean,QuantConnect/Lean
6fcd5b195bd07c05ddb19cfd5689f7cdba5525eb
src/conekta/conekta/Models/PaymentSource.cs
src/conekta/conekta/Models/PaymentSource.cs
using System.Text.RegularExpressions; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace conekta { public class PaymentSource : Resource { public string id { get; set; } public string type { get; set; } /* In case card token */ public string token_id { get; set; } /* In case card object*/ public string name { get; set; } public string number { get; set; } public string exp_month { get; set; } public string exp_year { get; set; } public string cvc { get; set; } public Address address { get; set; } public string parent_id { get; set; } public PaymentSource update(string data) { PaymentSource payment_source = this.toClass(this.toObject(this.update("/customers/" + this.parent_id + "/payment_sources/" + this.id, data)).ToString()); return payment_source; } public PaymentSource destroy() { this.delete("/customers/" + this.parent_id + "/payment_sources/" + this.id); return this; } public PaymentSource toClass(string json) { PaymentSource payment_source = JsonConvert.DeserializeObject<PaymentSource>(json, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); return payment_source; } } }
using System.Text.RegularExpressions; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace conekta { public class PaymentSource : Resource { public string id { get; set; } public string type { get; set; } /* In case card token */ public string token_id { get; set; } /* In case card object*/ public string name { get; set; } public string number { get; set; } public string exp_month { get; set; } public string exp_year { get; set; } public string cvc { get; set; } public string last4 { get; set; } public string bin { get; set; } public string brand { get; set; } public Address address { get; set; } public string parent_id { get; set; } public PaymentSource update(string data) { PaymentSource payment_source = this.toClass(this.toObject(this.update("/customers/" + this.parent_id + "/payment_sources/" + this.id, data)).ToString()); return payment_source; } public PaymentSource destroy() { this.delete("/customers/" + this.parent_id + "/payment_sources/" + this.id); return this; } public PaymentSource toClass(string json) { PaymentSource payment_source = JsonConvert.DeserializeObject<PaymentSource>(json, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); return payment_source; } } }
Add missing attributes to paymentSource
Add missing attributes to paymentSource
C#
mit
conekta/conekta-.net
135df8c9cdb8287a2ca408492ca7306a9db1e1a2
dist/Vidyano.Web2/Web2ControllerFactory.cs
dist/Vidyano.Web2/Web2ControllerFactory.cs
using System.Web.Http; using System.Web.Routing; namespace Vidyano.Web2 { public static class Web2ControllerFactory { public static void MapVidyanoWeb2Route(this RouteCollection routes, string routeTemplate = "web2/") { routes.MapHttpRoute("VidyanoWeb2 Vulcanize", routeTemplate + "vulcanize/{*id}", new { controller = "Web2", action = "Vulcanize", id = RouteParameter.Optional }); routes.MapHttpRoute("VidyanoWeb2", routeTemplate + "{*id}", new { controller = "Web2", action = "Get", id = RouteParameter.Optional }); } } }
using System.Web.Http; using System.Web.Routing; namespace Vidyano.Web2 { public static class Web2ControllerFactory { public static void MapVidyanoWeb2Route(this RouteCollection routes, string routeTemplate = "web2/") { routes.MapHttpRoute("VidyanoWeb2 Vulcanize", routeTemplate + "vulcanize/{*id}", new { controller = "Web2", action = "Vulcanize", id = RouteParameter.Optional }); routes.MapHttpRoute("VidyanoWeb2", routeTemplate + "{*id}", new { controller = "Web2", action = "Get", id = RouteParameter.Optional }); } public static void MapVidyanoWeb2Route(this HttpRouteCollection routes, string routeTemplate = "web2/") { routes.MapHttpRoute("VidyanoWeb2 Vulcanize", routeTemplate + "vulcanize/{*id}", new { controller = "Web2", action = "Vulcanize", id = RouteParameter.Optional }); routes.MapHttpRoute("VidyanoWeb2", routeTemplate + "{*id}", new { controller = "Web2", action = "Get", id = RouteParameter.Optional }); } } }
Handle MapVidyanoWeb2Route for HttpRouteCollection as well
Handle MapVidyanoWeb2Route for HttpRouteCollection as well
C#
mit
2sky/Vidyano,jmptrader/Vidyano,jmptrader/Vidyano,2sky/Vidyano,2sky/Vidyano,2sky/Vidyano,2sky/Vidyano,jmptrader/Vidyano
3358ab9f8abde79becfd4bca2a56361170aef2e1
osu.Game.Rulesets.Osu.Tests/OsuDifficultyCalculatorTest.cs
osu.Game.Rulesets.Osu.Tests/OsuDifficultyCalculatorTest.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.Game.Beatmaps; using osu.Game.Rulesets.Difficulty; using osu.Game.Rulesets.Osu.Difficulty; using osu.Game.Tests.Beatmaps; namespace osu.Game.Rulesets.Osu.Tests { [TestFixture] public class OsuDifficultyCalculatorTest : DifficultyCalculatorTest { protected override string ResourceAssembly => "osu.Game.Rulesets.Osu"; [TestCase(6.931145117263422, "diffcalc-test")] [TestCase(1.0736587013228804d, "zero-length-sliders")] public void Test(double expected, string name) => base.Test(expected, name); protected override DifficultyCalculator CreateDifficultyCalculator(WorkingBeatmap beatmap) => new OsuDifficultyCalculator(new OsuRuleset(), beatmap); protected override Ruleset CreateRuleset() => new OsuRuleset(); } }
// 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.Game.Beatmaps; using osu.Game.Rulesets.Difficulty; using osu.Game.Rulesets.Osu.Difficulty; using osu.Game.Tests.Beatmaps; namespace osu.Game.Rulesets.Osu.Tests { [TestFixture] public class OsuDifficultyCalculatorTest : DifficultyCalculatorTest { protected override string ResourceAssembly => "osu.Game.Rulesets.Osu"; [TestCase(6.9311451172608853d, "diffcalc-test")] [TestCase(1.0736587013228804d, "zero-length-sliders")] public void Test(double expected, string name) => base.Test(expected, name); protected override DifficultyCalculator CreateDifficultyCalculator(WorkingBeatmap beatmap) => new OsuDifficultyCalculator(new OsuRuleset(), beatmap); protected override Ruleset CreateRuleset() => new OsuRuleset(); } }
Adjust diffcalc test expected value
Adjust diffcalc test expected value The difference is caused by the reworked calculateLength() of SliderPath. This comes as a result of the increased accuracy of path lengthenings due to calculating the final position relative to the second-to-last point, rather than relative to the last point.
C#
mit
2yangk23/osu,EVAST9919/osu,ppy/osu,UselessToucan/osu,ppy/osu,smoogipoo/osu,smoogipoo/osu,NeoAdonis/osu,UselessToucan/osu,smoogipooo/osu,peppy/osu,johnneijzen/osu,smoogipoo/osu,NeoAdonis/osu,peppy/osu,ppy/osu,NeoAdonis/osu,peppy/osu-new,2yangk23/osu,peppy/osu,EVAST9919/osu,UselessToucan/osu,johnneijzen/osu
3fee889036a322d67dec019e533e893cbf06d752
Shippo/Track.cs
Shippo/Track.cs
using System; using System.Collections; using System.Collections.Generic; using Newtonsoft.Json; namespace Shippo { [JsonObject (MemberSerialization.OptIn)] public class Track : ShippoId { [JsonProperty (PropertyName = "carrier")] public string Carrier { get; set; } [JsonProperty (PropertyName = "tracking_number")] public string TrackingNumber { get; set; } [JsonProperty (PropertyName = "address_from")] public ShortAddress AddressFrom { get; set; } [JsonProperty (PropertyName = "address_to")] public ShortAddress AddressTo { get; set; } [JsonProperty (PropertyName = "eta")] public DateTime? Eta { get; set; } [JsonProperty (PropertyName = "servicelevel")] public Servicelevel Servicelevel { get; set; } [JsonProperty (PropertyName = "tracking_status")] public TrackingStatus TrackingStatus { get; set; } [JsonProperty (PropertyName = "tracking_history")] public List<TrackingHistory> TrackingHistory { get; set; } [JsonProperty (PropertyName = "metadata")] public string Metadata { get; set; } public override string ToString () { return string.Format ("[Track: Carrier={0}, TrackingNumber={1}, AddressFrom={2}, AddressTo={3}, Eta={4}," + "Servicelevel={5}, TrackingStatus={6}, TrackingHistory={7}, Metadata={8}]",Carrier, TrackingNumber, AddressFrom, AddressTo, Eta, Servicelevel, TrackingStatus, TrackingHistory, Metadata); } } }
using System; using System.Collections; using System.Collections.Generic; using Newtonsoft.Json; namespace Shippo { [JsonObject (MemberSerialization.OptIn)] public class Track : ShippoId { [JsonProperty (PropertyName = "carrier")] private string Carrier; [JsonProperty (PropertyName = "tracking_number")] public string TrackingNumber; [JsonProperty (PropertyName = "address_from")] public ShortAddress AddressFrom; [JsonProperty (PropertyName = "address_to")] public ShortAddress AddressTo; [JsonProperty (PropertyName = "eta")] public DateTime? Eta; [JsonProperty (PropertyName = "servicelevel")] public Servicelevel Servicelevel; [JsonProperty (PropertyName = "tracking_status")] public TrackingStatus TrackingStatus; [JsonProperty (PropertyName = "tracking_history")] public List<TrackingHistory> TrackingHistory; [JsonProperty (PropertyName = "metadata")] public string Metadata; public override string ToString () { return string.Format ("[Track: Carrier={0}, TrackingNumber={1}, AddressFrom={2}, AddressTo={3}, Eta={4}," + "Servicelevel={5}, TrackingStatus={6}, TrackingHistory={7}, Metadata={8}]",Carrier, TrackingNumber, AddressFrom, AddressTo, Eta, Servicelevel, TrackingStatus, TrackingHistory, Metadata); } } }
Remove redundant getters and setters
Remove redundant getters and setters
C#
apache-2.0
goshippo/shippo-csharp-client
d71b25589e6e404036a4522762b98847dac17c81
OctoAwesome/OctoAwesome/PhysicalProperties.cs
OctoAwesome/OctoAwesome/PhysicalProperties.cs
namespace OctoAwesome { /// <summary> /// Repräsentiert die physikalischen Eigenschaften eines Blocks/Items/... /// </summary> public class PhysicalProperties { /// <summary> /// Härte /// </summary> public float Hardness { get; set; } /// <summary> /// Dichte in kg/dm^3 /// </summary> public float Density { get; set; } /// <summary> /// Granularität /// </summary> public float Granularity { get; set; } /// <summary> /// Bruchzähigkeit /// </summary> public float FractureToughness { get; set; } } }
namespace OctoAwesome { /// <summary> /// Repräsentiert die physikalischen Eigenschaften eines Blocks/Items/... /// </summary> public class PhysicalProperties { /// <summary> /// Härte, welche Materialien können abgebaut werden /// </summary> public float Hardness { get; set; } /// <summary> /// Dichte in kg/dm^3, Wie viel benötigt (Volumen berechnung) für Crafting bzw. hit result etc.... /// </summary> public float Density { get; set; } /// <summary> /// Granularität, Effiktivität von "Materialien" Schaufel für hohe Werte, Pickaxe für niedrige /// </summary> public float Granularity { get; set; } /// <summary> /// Bruchzähigkeit, Wie schnell geht etwas zu bruch? Haltbarkeit. /// </summary> public float FractureToughness { get; set; } } }
Add comments to physical props
Add comments to physical props * Add comments to the physical props so we know in future what we find out today 😀 Co-authored-by: susch19 <bae0fb0a2bea97e664e26778477eb5557a713d80@ist-einmalig.de>
C#
mit
OctoAwesome/octoawesome,OctoAwesome/octoawesome
6ed95029837b3051682c1f2d75a796293a65230e
osu.Framework/Bindables/ILeasedBindable.cs
osu.Framework/Bindables/ILeasedBindable.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. namespace osu.Framework.Bindables { /// <summary> /// An interface that represents a read-only leased bindable. /// </summary> public interface ILeasedBindable : IBindable { /// <summary> /// End the lease on the source <see cref="Bindable{T}"/>. /// </summary> void Return(); } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. namespace osu.Framework.Bindables { /// <summary> /// An interface that represents a read-only leased bindable. /// </summary> public interface ILeasedBindable : IBindable { /// <summary> /// End the lease on the source <see cref="Bindable{T}"/>. /// </summary> void Return(); } /// <summary> /// An interface that representes a read-only leased bindable. /// </summary> /// <typeparam name="T">The value type of the bindable.</typeparam> public interface ILeasedBindable<T> : ILeasedBindable, IBindable<T> { } }
Add generic version of interface
Add generic version of interface
C#
mit
peppy/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,ZLima12/osu-framework,ZLima12/osu-framework,ppy/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,peppy/osu-framework
7522fd495560e0ada2f59be5cb45de6d69fa3fca
MoreLinq/MoreEnumerable.cs
MoreLinq/MoreEnumerable.cs
#region License and Terms // MoreLINQ - Extensions to LINQ to Objects // Copyright (c) 2008 Jonathan Skeet. All rights reserved. // // 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. #endregion namespace MoreLinq { using System; using System.Collections.Generic; /// <summary> /// Provides a set of static methods for querying objects that /// implement <see cref="IEnumerable{T}" />. The actual methods /// are implemented in files reflecting the method name. /// </summary> public static partial class MoreEnumerable { static int? TryGetCollectionCount<T>(this IEnumerable<T> source) { if (source == null) throw new ArgumentNullException(nameof(source)); return source is ICollection<T> collection ? collection.Count : source is IReadOnlyCollection<T> readOnlyCollection ? readOnlyCollection.Count : (int?)null; } } }
#region License and Terms // MoreLINQ - Extensions to LINQ to Objects // Copyright (c) 2008 Jonathan Skeet. All rights reserved. // // 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. #endregion namespace MoreLinq { using System; using System.Collections.Generic; /// <summary> /// Provides a set of static methods for querying objects that /// implement <see cref="IEnumerable{T}" />. /// </summary> public static partial class MoreEnumerable { static int? TryGetCollectionCount<T>(this IEnumerable<T> source) { if (source == null) throw new ArgumentNullException(nameof(source)); return source is ICollection<T> collection ? collection.Count : source is IReadOnlyCollection<T> readOnlyCollection ? readOnlyCollection.Count : (int?)null; } } }
Remove file structure comment from doc summary
Remove file structure comment from doc summary
C#
apache-2.0
ddpruitt/morelinq,ddpruitt/morelinq,morelinq/MoreLINQ,morelinq/MoreLINQ,fsateler/MoreLINQ,fsateler/MoreLINQ
15fad097aa95bfdbf1f681685bfafbf1d05b4aa6
Runner.cs
Runner.cs
using System; using System.Linq; using System.Reflection; namespace TDDUnit { class Runner { public Runner(Type exceptType) { Suite suite = new Suite(); m_result = new Result(); foreach (Type t in Assembly.GetEntryAssembly().GetTypes()) { if (t.Name.StartsWith("Test") && t.Name != exceptType.Name) suite.Add(t); } foreach (string test in suite.FailedTests(m_result)) { Console.WriteLine("Failed: " + test); } Console.WriteLine(m_result.Summary); } public string Summary { get { return m_result.Summary; } } private Result m_result; } }
using System; using System.Linq; using System.Reflection; namespace TDDUnit { class Runner { public Runner(Type callingType) { Suite suite = new Suite(); m_result = new Result(); Type[] forbiddenTypes = new Type[] { callingType , typeof (TDDUnit.WasRunObj) , typeof (TDDUnit.WasRunSetUpFailed) }; foreach (Type t in Assembly.GetEntryAssembly().GetTypes()) { if (t.IsSubclassOf(typeof (TDDUnit.Case)) && !forbiddenTypes.Contains(t)) suite.Add(t); } foreach (string test in suite.FailedTests(m_result)) { Console.WriteLine("Failed: " + test); } Console.WriteLine(m_result.Summary); } public string Summary { get { return m_result.Summary; } } private Result m_result; } }
Add test cases based on inheritance from Case
Add test cases based on inheritance from Case Make the Runner object add test cases based on their inheritance from the base Case class. With this method, we have to forbid the object from adding the tests of its calling type (since they're already being run), and of a couple of helper types that we use to test the TDDUnit library itself.
C#
apache-2.0
yawaramin/TDDUnit
fea782a2b3d7c2564798a54f52473dc3bc4c07be
src/Stripe.net/Entities/StripeCoupon.cs
src/Stripe.net/Entities/StripeCoupon.cs
namespace Stripe { using System; using System.Collections.Generic; using Newtonsoft.Json; using Stripe.Infrastructure; public class StripeCoupon : StripeEntityWithId, ISupportMetadata { [JsonProperty("object")] public string Object { get; set; } [JsonProperty("amount_off")] public int? AmountOff { get; set; } [JsonProperty("created")] [JsonConverter(typeof(StripeDateTimeConverter))] public DateTime Created { get; set; } [JsonProperty("currency")] public string Currency { get; set; } [JsonProperty("duration")] public string Duration { get; set; } [JsonProperty("duration_in_months")] public int? DurationInMonths { get; set; } [JsonProperty("livemode")] public bool LiveMode { get; set; } [JsonProperty("max_redemptions")] public int? MaxRedemptions { get; set; } [JsonProperty("metadata")] public Dictionary<string, string> Metadata { get; set; } [JsonProperty("name")] public string Name { get; set; } [JsonProperty("percent_off")] public int? PercentOff { get; set; } [JsonProperty("redeem_by")] [JsonConverter(typeof(StripeDateTimeConverter))] public DateTime? RedeemBy { get; set; } [JsonProperty("times_redeemed")] public int TimesRedeemed { get; private set; } [JsonProperty("valid")] public bool Valid { get; set; } } }
namespace Stripe { using System; using System.Collections.Generic; using Newtonsoft.Json; using Stripe.Infrastructure; public class StripeCoupon : StripeEntityWithId, ISupportMetadata { [JsonProperty("object")] public string Object { get; set; } [JsonProperty("amount_off")] public int? AmountOff { get; set; } [JsonProperty("created")] [JsonConverter(typeof(StripeDateTimeConverter))] public DateTime Created { get; set; } [JsonProperty("currency")] public string Currency { get; set; } [JsonProperty("duration")] public string Duration { get; set; } [JsonProperty("duration_in_months")] public int? DurationInMonths { get; set; } [JsonProperty("livemode")] public bool LiveMode { get; set; } [JsonProperty("max_redemptions")] public int? MaxRedemptions { get; set; } [JsonProperty("metadata")] public Dictionary<string, string> Metadata { get; set; } [JsonProperty("name")] public string Name { get; set; } [JsonProperty("percent_off")] public decimal? PercentOff { get; set; } [JsonProperty("redeem_by")] [JsonConverter(typeof(StripeDateTimeConverter))] public DateTime? RedeemBy { get; set; } [JsonProperty("times_redeemed")] public int TimesRedeemed { get; private set; } [JsonProperty("valid")] public bool Valid { get; set; } } }
Fix the Coupon resource as percent_off is now a decimal
Fix the Coupon resource as percent_off is now a decimal
C#
apache-2.0
stripe/stripe-dotnet,richardlawley/stripe.net
4395d77667afd7a9106a7a37d08531bcc14d3a5b
MitternachtWeb/Startup.cs
MitternachtWeb/Startup.cs
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace MitternachtWeb { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if(env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); } } }
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Hosting; using System.Linq; namespace MitternachtWeb { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); services.Add(ServiceDescriptor.Singleton(Program.MitternachtBot)); services.Add(Program.MitternachtBot.Services.Services.Select(s => ServiceDescriptor.Singleton(s.Key, s.Value))); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if(env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); } } }
Add the MitternachtBot instance and its services to the ASP.NET services.
Add the MitternachtBot instance and its services to the ASP.NET services.
C#
mit
Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW