commit
stringlengths
40
40
subject
stringlengths
4
1.73k
repos
stringlengths
5
127k
old_file
stringlengths
2
751
new_file
stringlengths
2
751
new_contents
stringlengths
1
8.98k
old_contents
stringlengths
0
6.59k
license
stringclasses
13 values
lang
stringclasses
23 values
fad730441ab107d60c39495205b7e984ac54f0df
Fix Assembly Info
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
src/Microsoft.AspNetCore.Rewrite/Properties/AssemblyInfo.cs
src/Microsoft.AspNetCore.Rewrite/Properties/AssemblyInfo.cs
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Reflection; using System.Resources; [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: NeutralResourcesLanguage("en-us")] [assembly: AssemblyCompany("Microsoft Corporation.")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyProduct("Microsoft ASP.NET Core")]
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: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Microsoft.AspNetCore.Rewrite")] [assembly: AssemblyTrademark("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("0e7ca1a7-1dc3-4ce6-b9c7-1688fe1410f1")]
apache-2.0
C#
06255967d261bfbc0fb1f6e122561317a01538aa
Store the inner exception. Fixes #575
mysql-net/MySqlConnector,mysql-net/MySqlConnector
src/MySqlConnector/MySql.Data.MySqlClient/MySqlException.cs
src/MySqlConnector/MySql.Data.MySqlClient/MySqlException.cs
using System; using System.Data.Common; namespace MySql.Data.MySqlClient { public sealed class MySqlException : DbException { public int Number { get; } public string SqlState { get; } internal MySqlException(string message) : this(message, null) { } internal MySqlException(string message, Exception innerException) : this(0, null, message, innerException) { } internal MySqlException(int errorNumber, string sqlState, string message) : this(errorNumber, sqlState, message, null) { } internal MySqlException(int errorNumber, string sqlState, string message, Exception innerException) : base(message, innerException) { Number = errorNumber; SqlState = sqlState; } internal static MySqlException CreateForTimeout() => CreateForTimeout(null); internal static MySqlException CreateForTimeout(Exception innerException) => new MySqlException((int) MySqlErrorCode.CommandTimeoutExpired, null, "The Command Timeout expired before the operation completed.", innerException); } }
using System; using System.Data.Common; namespace MySql.Data.MySqlClient { public sealed class MySqlException : DbException { public int Number { get; } public string SqlState { get; } internal MySqlException(string message) : this(message, null) { } internal MySqlException(string message, Exception innerException) : this(0, null, message, innerException) { } internal MySqlException(int errorNumber, string sqlState, string message) : this(errorNumber, sqlState, message, null) { } internal MySqlException(int errorNumber, string sqlState, string message, Exception innerException) : base(message, innerException) { Number = errorNumber; SqlState = sqlState; } internal static MySqlException CreateForTimeout() => CreateForTimeout(null); internal static MySqlException CreateForTimeout(Exception innerException) => new MySqlException((int) MySqlErrorCode.CommandTimeoutExpired, null, "The Command Timeout expired before the operation completed."); } }
mit
C#
3366eabebd7ae8eb146709778b35f1b6d697275d
Update ResourceController
openiddict/openiddict-core,PinpointTownes/core,openiddict/openiddict-core,joshcomley/openiddict-core,openiddict/openiddict-core,PinpointTownes/core,openiddict/openiddict-core,vyfster/openiddict-core,joshcomley/openiddict-core,PinpointTownes/openiddict-core,openiddict/core,PinpointTownes/openiddict-core,vyfster/openiddict-core,openiddict/openiddict-core,openiddict/core
samples/Mvc.Server/Controllers/ResourceController.cs
samples/Mvc.Server/Controllers/ResourceController.cs
using System.Threading.Tasks; using AspNet.Security.OAuth.Validation; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Mvc.Server.Models; namespace Mvc.Server.Controllers { [Route("api")] public class ResourceController : Controller { private readonly UserManager<ApplicationUser> _userManager; public ResourceController(UserManager<ApplicationUser> userManager) { _userManager = userManager; } [Authorize(ActiveAuthenticationSchemes = OAuthValidationDefaults.AuthenticationScheme)] [HttpGet("message")] public async Task<IActionResult> GetMessage() { var user = await _userManager.GetUserAsync(User); if (user == null) { return BadRequest(); } return Content($"{user.UserName} has been successfully authenticated."); } } }
using System.Security.Claims; using AspNet.Security.OAuth.Validation; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; namespace Mvc.Server.Controllers { [Route("api")] public class ResourceController : Controller { [Authorize(ActiveAuthenticationSchemes = OAuthValidationDefaults.AuthenticationScheme)] [HttpGet("message")] public IActionResult GetMessage() { var identity = User.Identity as ClaimsIdentity; if (identity == null) { return BadRequest(); } return Content($"{identity.Name} has been successfully authenticated."); } } }
apache-2.0
C#
0990c9f98a54f2b219254aa7faf862f202859873
Fix broken test
appharbor/appharbor-cli
src/AppHarbor.Tests/Commands/CreateAppCommandTest.cs
src/AppHarbor.Tests/Commands/CreateAppCommandTest.cs
using System.IO; using System.Linq; using AppHarbor.Commands; using AppHarbor.Model; using Moq; using Ploeh.AutoFixture.Xunit; using Xunit; using Xunit.Extensions; namespace AppHarbor.Tests.Commands { public class CreateAppCommandTest { [Theory, AutoCommandData] public void ShouldThrowWhenNoArguments(CreateAppCommand command) { var exception = Assert.Throws<CommandException>(() => command.Execute(new string[0])); Assert.Equal("An application name must be provided to create an application", exception.Message); } [Theory, AutoCommandData] public void ShouldCreateApplicationWithOnlyName([Frozen]Mock<IAppHarborClient> client, CreateAppCommand command) { var arguments = new string[] { "foo" }; VerifyArguments(client, command, arguments); } [Theory, AutoCommandData] public void ShouldCreateApplicationWithRegion([Frozen]Mock<IAppHarborClient> client, CreateAppCommand command, string[] arguments) { VerifyArguments(client, command, arguments); } private static void VerifyArguments(Mock<IAppHarborClient> client, CreateAppCommand command, string[] arguments) { command.Execute(arguments); client.Verify(x => x.CreateApplication(arguments.First(), arguments.Skip(1).FirstOrDefault()), Times.Once()); } [Theory, AutoCommandData] public void ShouldSetupApplicationLocallyAfterCreationIfNotConfigured([Frozen]Mock<IApplicationConfiguration> applicationConfiguration, [Frozen]Mock<IAppHarborClient> client, CreateAppCommand command, CreateResult result, User user, string[] arguments) { client.Setup(x => x.CreateApplication(It.IsAny<string>(), It.IsAny<string>())).Returns(result); client.Setup(x => x.GetUser()).Returns(user); applicationConfiguration.Setup(x => x.GetApplicationId()).Throws<ApplicationConfigurationException>(); command.Execute(arguments); applicationConfiguration.Verify(x => x.SetupApplication(result.Id, user), Times.Once()); } [Theory, AutoCommandData] public void ShouldNotSetupApplicationIfAlreadyConfigured([Frozen]Mock<IApplicationConfiguration> applicationConfiguration, [Frozen]Mock<TextWriter> writer, CreateAppCommand command, string[] arguments, string applicationName) { applicationConfiguration.Setup(x => x.GetApplicationId()).Returns(applicationName); command.Execute(arguments); writer.Verify(x => x.WriteLine("This directory is already configured to track application \"{0}\".", applicationName), Times.Once()); } [Theory, AutoCommandData] public void ShouldPrintSuccessMessageAfterCreatingApplication([Frozen]Mock<IAppHarborClient> client, [Frozen]Mock<TextWriter> writer, Mock<CreateAppCommand> command, string applicationName, string applicationSlug) { client.Setup(x => x.CreateApplication(applicationName, null)).Returns(new CreateResult { Id = applicationSlug }); command.Object.Execute(new string[] { applicationName }); writer.Verify(x => x.WriteLine("Created application \"{0}\" | URL: https://{0}.apphb.com", applicationSlug), Times.Once()); } } }
using System.IO; using System.Linq; using AppHarbor.Commands; using AppHarbor.Model; using Moq; using Ploeh.AutoFixture.Xunit; using Xunit; using Xunit.Extensions; namespace AppHarbor.Tests.Commands { public class CreateAppCommandTest { [Theory, AutoCommandData] public void ShouldThrowWhenNoArguments(CreateAppCommand command) { var exception = Assert.Throws<CommandException>(() => command.Execute(new string[0])); Assert.Equal("An application name must be provided to create an application", exception.Message); } [Theory, AutoCommandData] public void ShouldCreateApplicationWithOnlyName([Frozen]Mock<IAppHarborClient> client, CreateAppCommand command) { var arguments = new string[] { "foo" }; VerifyArguments(client, command, arguments); } [Theory, AutoCommandData] public void ShouldCreateApplicationWithRegion([Frozen]Mock<IAppHarborClient> client, CreateAppCommand command, string[] arguments) { VerifyArguments(client, command, arguments); } private static void VerifyArguments(Mock<IAppHarborClient> client, CreateAppCommand command, string[] arguments) { command.Execute(arguments); client.Verify(x => x.CreateApplication(arguments.First(), arguments.Skip(1).FirstOrDefault()), Times.Once()); } [Theory, AutoCommandData] public void ShouldSetupApplicationLocallyAfterCreationIfNotConfigured([Frozen]Mock<IApplicationConfiguration> applicationConfiguration, [Frozen]Mock<IAppHarborClient> client, CreateAppCommand command, CreateResult result, User user, string[] arguments) { client.Setup(x => x.CreateApplication(It.IsAny<string>(), It.IsAny<string>())).Returns(result); client.Setup(x => x.GetUser()).Returns(user); applicationConfiguration.Setup(x => x.GetApplicationId()).Throws<ApplicationConfigurationException>(); command.Execute(arguments); applicationConfiguration.Verify(x => x.SetupApplication(result.Id, user), Times.Once()); } [Theory, AutoCommandData] public void ShouldNotSetupApplicationIfAlreadyConfigured([Frozen]Mock<IApplicationConfiguration> applicationConfiguration, [Frozen]Mock<TextWriter> writer, CreateAppCommand command, string[] arguments, string applicationName) { applicationConfiguration.Setup(x => x.GetApplicationId()).Returns(applicationName); command.Execute(arguments); writer.Verify(x => x.WriteLine("This directory is already configured to track application \"{0}\".", applicationName), Times.Once()); } [Theory, AutoCommandData] public void ShouldPrintSuccessMessageAfterCreatingApplication([Frozen]Mock<IAppHarborClient> client, [Frozen]Mock<TextWriter> writer, Mock<CreateAppCommand> command, string[] arguments, string applicationSlug) { client.Setup(x => x.CreateApplication(arguments[0], arguments[1])).Returns(new CreateResult { Id = applicationSlug }); command.Object.Execute(arguments); writer.Verify(x => x.WriteLine("Created application \"{0}\" | URL: https://{0}.apphb.com", applicationSlug), Times.Once()); } } }
mit
C#
2d2d58cb230aadf922224450b615ed50a340b38c
Make ConsoleHost/AssemblyInfo portable
JamesWTruher/PowerShell-1,JamesWTruher/PowerShell-1,bmanikm/PowerShell,TravisEz13/PowerShell,kmosher/PowerShell,bmanikm/PowerShell,kmosher/PowerShell,bingbing8/PowerShell,PaulHigin/PowerShell,jsoref/PowerShell,bingbing8/PowerShell,bmanikm/PowerShell,daxian-dbw/PowerShell,KarolKaczmarek/PowerShell,bmanikm/PowerShell,JamesWTruher/PowerShell-1,bingbing8/PowerShell,KarolKaczmarek/PowerShell,PaulHigin/PowerShell,jsoref/PowerShell,KarolKaczmarek/PowerShell,JamesWTruher/PowerShell-1,bingbing8/PowerShell,TravisEz13/PowerShell,daxian-dbw/PowerShell,daxian-dbw/PowerShell,KarolKaczmarek/PowerShell,bmanikm/PowerShell,jsoref/PowerShell,bingbing8/PowerShell,KarolKaczmarek/PowerShell,kmosher/PowerShell,TravisEz13/PowerShell,jsoref/PowerShell,kmosher/PowerShell,daxian-dbw/PowerShell,jsoref/PowerShell,PaulHigin/PowerShell,PaulHigin/PowerShell,TravisEz13/PowerShell,kmosher/PowerShell
src/Microsoft.PowerShell.ConsoleHost/AssemblyInfo.cs
src/Microsoft.PowerShell.ConsoleHost/AssemblyInfo.cs
using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; #if !CORECLR using System.Runtime.ConstrainedExecution; using System.Security.Permissions; #endif [assembly:AssemblyCulture("")] [assembly:NeutralResourcesLanguage("en-US")] #if !CORECLR [assembly:AssemblyConfiguration("")] [assembly:AssemblyInformationalVersionAttribute (@"10.0.10011.16384")] [assembly:ReliabilityContractAttribute(Consistency.MayCorruptAppDomain, Cer.MayFail)] [assembly:AssemblyTitle("Microsoft.PowerShell.ConsoleHost")] [assembly:AssemblyDescription("Microsoft Windows PowerShell Console Host")] [assembly:System.Runtime.Versioning.TargetFrameworkAttribute(".NETFramework,Version=v4.5")] [assembly:System.Reflection.AssemblyFileVersion("10.0.10011.16384")] [assembly:AssemblyKeyFileAttribute(@"..\signing\visualstudiopublic.snk")] [assembly:System.Reflection.AssemblyDelaySign(true)] #endif [assembly:System.Runtime.InteropServices.ComVisible(false)] [assembly:System.Reflection.AssemblyVersion("3.0.0.0")] [assembly:System.Reflection.AssemblyProduct("Microsoft (R) Windows (R) Operating System")] [assembly:System.Reflection.AssemblyCopyright("Copyright (c) Microsoft Corporation. All rights reserved.")] [assembly:System.Reflection.AssemblyCompany("Microsoft Corporation")] internal static class AssemblyStrings { internal const string AssemblyVersion = @"3.0.0.0"; internal const string AssemblyCopyright = "Copyright (C) 2006 Microsoft Corporation. All rights reserved."; }
using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Security.Permissions; [assembly:AssemblyCulture("")] [assembly:NeutralResourcesLanguage("en-US")] [assembly:AssemblyConfiguration("")] [assembly:AssemblyInformationalVersionAttribute (@"10.0.10011.16384")] [assembly:ReliabilityContractAttribute(Consistency.MayCorruptAppDomain, Cer.MayFail)] [assembly:AssemblyTitle("Microsoft.PowerShell.ConsoleHost")] [assembly:AssemblyDescription("Microsoft Windows PowerShell Console Host")] [assembly:System.Runtime.Versioning.TargetFrameworkAttribute(".NETFramework,Version=v4.5")] [assembly:System.Runtime.InteropServices.ComVisible(false)] [assembly:System.Reflection.AssemblyVersion("3.0.0.0")] [assembly:System.Reflection.AssemblyProduct("Microsoft (R) Windows (R) Operating System")] [assembly:System.Reflection.AssemblyCopyright("Copyright (c) Microsoft Corporation. All rights reserved.")] [assembly:System.Reflection.AssemblyCompany("Microsoft Corporation")] [assembly:System.Reflection.AssemblyFileVersion("10.0.10011.16384")] [assembly:AssemblyKeyFileAttribute(@"..\signing\visualstudiopublic.snk")] [assembly:System.Reflection.AssemblyDelaySign(true)] internal static class AssemblyStrings { internal const string AssemblyVersion = @"3.0.0.0"; internal const string AssemblyCopyright = "Copyright (C) 2006 Microsoft Corporation. All rights reserved."; }
mit
C#
db92441330f6338e3e8a715be1b7ce479f3f11c9
make copy work as method
WeihanLi/WeihanLi.Common,WeihanLi/WeihanLi.Common,WeihanLi/WeihanLi.Common
src/WeihanLi.Common/Logging/LogHelperLoggingEvent.cs
src/WeihanLi.Common/Logging/LogHelperLoggingEvent.cs
using System; using System.Collections.Generic; namespace WeihanLi.Common.Logging { public class LogHelperLoggingEvent : ICloneable { public string CategoryName { get; set; } public DateTimeOffset DateTime { get; set; } public string MessageTemplate { get; set; } public string Message { get; set; } public Exception Exception { get; set; } public LogHelperLogLevel LogLevel { get; set; } public Dictionary<string, object> Properties { get; set; } public LogHelperLoggingEvent Copy() => (LogHelperLoggingEvent)Clone(); public object Clone() { var newEvent = (LogHelperLoggingEvent)MemberwiseClone(); if (Properties != null) { newEvent.Properties = new Dictionary<string, object>(); foreach (var property in Properties) { newEvent.Properties[property.Key] = property.Value; } } return newEvent; } } }
using System; using System.Collections.Generic; namespace WeihanLi.Common.Logging { public class LogHelperLoggingEvent : ICloneable { public string CategoryName { get; set; } public DateTimeOffset DateTime { get; set; } public string MessageTemplate { get; set; } public string Message { get; set; } public Exception Exception { get; set; } public LogHelperLogLevel LogLevel { get; set; } public Dictionary<string, object> Properties { get; set; } public LogHelperLoggingEvent Copy => (LogHelperLoggingEvent)Clone(); public object Clone() { var newEvent = (LogHelperLoggingEvent)MemberwiseClone(); if (Properties != null) { newEvent.Properties = new Dictionary<string, object>(); foreach (var property in Properties) { newEvent.Properties[property.Key] = property.Value; } } return newEvent; } } }
mit
C#
5567d2b15132ccc90553178565c3bede894a0f0d
use generic collections wherever possible
hmah/boo,KingJiangNet/boo,rmartinho/boo,KidFashion/boo,boo-lang/boo,rmboggs/boo,wbardzinski/boo,KingJiangNet/boo,scottstephens/boo,hmah/boo,bamboo/boo,KingJiangNet/boo,KidFashion/boo,scottstephens/boo,scottstephens/boo,wbardzinski/boo,KidFashion/boo,rmboggs/boo,rmboggs/boo,BITechnologies/boo,Unity-Technologies/boo,scottstephens/boo,scottstephens/boo,wbardzinski/boo,BillHally/boo,boo-lang/boo,scottstephens/boo,BITechnologies/boo,KingJiangNet/boo,BitPuffin/boo,KidFashion/boo,KingJiangNet/boo,BitPuffin/boo,BITechnologies/boo,BitPuffin/boo,boo-lang/boo,rmartinho/boo,drslump/boo,hmah/boo,bamboo/boo,KingJiangNet/boo,rmboggs/boo,rmartinho/boo,BillHally/boo,KidFashion/boo,wbardzinski/boo,BillHally/boo,Unity-Technologies/boo,scottstephens/boo,KingJiangNet/boo,rmboggs/boo,rmboggs/boo,drslump/boo,rmartinho/boo,drslump/boo,drslump/boo,hmah/boo,bamboo/boo,bamboo/boo,BillHally/boo,BitPuffin/boo,hmah/boo,Unity-Technologies/boo,BillHally/boo,wbardzinski/boo,BitPuffin/boo,BitPuffin/boo,BillHally/boo,Unity-Technologies/boo,hmah/boo,bamboo/boo,rmartinho/boo,Unity-Technologies/boo,KidFashion/boo,rmartinho/boo,KidFashion/boo,BITechnologies/boo,BillHally/boo,boo-lang/boo,rmboggs/boo,Unity-Technologies/boo,wbardzinski/boo,rmartinho/boo,drslump/boo,drslump/boo,rmartinho/boo,drslump/boo,hmah/boo,BITechnologies/boo,BITechnologies/boo,boo-lang/boo,Unity-Technologies/boo,boo-lang/boo,KingJiangNet/boo,hmah/boo,BITechnologies/boo,scottstephens/boo,Unity-Technologies/boo,hmah/boo,BITechnologies/boo,BitPuffin/boo,boo-lang/boo,BitPuffin/boo,bamboo/boo,rmboggs/boo,bamboo/boo,boo-lang/boo,wbardzinski/boo,wbardzinski/boo
src/Boo.Lang.Compiler/TypeSystem/Services/MemberCollector.cs
src/Boo.Lang.Compiler/TypeSystem/Services/MemberCollector.cs
using System.Collections.Generic; using System.Linq; namespace Boo.Lang.Compiler.TypeSystem.Services { public static class MemberCollector { public static IEntity[] CollectAllMembers(INamespace entity) { var members = new List<IEntity>(); CollectAllMembers(members, entity); return members.ToArray(); } private static void CollectAllMembers(List<IEntity> members, INamespace entity) { var type = entity as IType; if (null != type) { members.ExtendUnique(type.GetMembers()); CollectBaseTypeMembers(members, type.BaseType); } else { members.Extend(entity.GetMembers()); } } private static void CollectBaseTypeMembers(List<IEntity> members, IType baseType) { if (null == baseType) return; members.Extend(baseType.GetMembers().Where(m => !(m is IConstructor) && !IsHiddenBy(m, members))); CollectBaseTypeMembers(members, baseType.BaseType); } private static bool IsHiddenBy(IEntity entity, IEnumerable<IEntity> members) { var m = entity as IMethod; if (m != null) return members.OfType<IMethod>().Any(existing => SameNameAndSignature(m, existing)); return members.OfType<IEntity>().Any(existing => existing.Name == entity.Name); } private static bool SameNameAndSignature(IMethod method, IMethod existing) { if (method.Name != existing.Name) return false; return method.CallableType == existing.CallableType; } } }
using System.Linq; namespace Boo.Lang.Compiler.TypeSystem.Services { public static class MemberCollector { public static IEntity[] CollectAllMembers(INamespace entity) { List members = new List(); CollectAllMembers(members, entity); return (IEntity[])members.ToArray(new IEntity[members.Count]); } private static void CollectAllMembers(List members, INamespace entity) { IType type = entity as IType; if (null != type) { members.ExtendUnique(type.GetMembers()); CollectBaseTypeMembers(members, type.BaseType); } else { members.Extend(entity.GetMembers()); } } private static void CollectBaseTypeMembers(List members, IType baseType) { if (null == baseType) return; members.Extend(baseType.GetMembers().Where(m => !(m is IConstructor) && !IsHiddenBy(m, members))); CollectBaseTypeMembers(members, baseType.BaseType); } private static bool IsHiddenBy(IEntity entity, List members) { var m = entity as IMethod; if (m != null) return members.OfType<IMethod>().Any(existing => SameNameAndSignature(m, existing)); return members.OfType<IEntity>().Any(existing => existing.Name == entity.Name); } private static bool SameNameAndSignature(IMethod method, IMethod existing) { if (method.Name != existing.Name) return false; return method.CallableType == existing.CallableType; } } }
bsd-3-clause
C#
b68e6bea1a90519099cce16f9f424be23dfeb46a
remove comma
AnthonyDGreen/roslyn,jcouv/roslyn,tannergooding/roslyn,AlekseyTs/roslyn,abock/roslyn,amcasey/roslyn,AmadeusW/roslyn,zooba/roslyn,davkean/roslyn,CaptainHayashi/roslyn,VSadov/roslyn,amcasey/roslyn,VSadov/roslyn,agocke/roslyn,heejaechang/roslyn,srivatsn/roslyn,sharwell/roslyn,tmeschter/roslyn,KirillOsenkov/roslyn,robinsedlaczek/roslyn,ErikSchierboom/roslyn,mavasani/roslyn,sharwell/roslyn,tvand7093/roslyn,dpoeschl/roslyn,tannergooding/roslyn,Hosch250/roslyn,dpoeschl/roslyn,nguerrera/roslyn,diryboy/roslyn,dpoeschl/roslyn,paulvanbrenk/roslyn,MattWindsor91/roslyn,mmitche/roslyn,Giftednewt/roslyn,Hosch250/roslyn,mattscheffer/roslyn,Giftednewt/roslyn,bkoelman/roslyn,KirillOsenkov/roslyn,eriawan/roslyn,mavasani/roslyn,zooba/roslyn,eriawan/roslyn,bkoelman/roslyn,srivatsn/roslyn,KevinRansom/roslyn,gafter/roslyn,khyperia/roslyn,aelij/roslyn,akrisiun/roslyn,davkean/roslyn,weltkante/roslyn,bartdesmet/roslyn,Giftednewt/roslyn,pdelvo/roslyn,jmarolf/roslyn,dotnet/roslyn,heejaechang/roslyn,panopticoncentral/roslyn,MichalStrehovsky/roslyn,sharwell/roslyn,shyamnamboodiripad/roslyn,bartdesmet/roslyn,brettfo/roslyn,mattscheffer/roslyn,bartdesmet/roslyn,mattwar/roslyn,kelltrick/roslyn,agocke/roslyn,jamesqo/roslyn,yeaicc/roslyn,MattWindsor91/roslyn,jamesqo/roslyn,mattwar/roslyn,aelij/roslyn,abock/roslyn,cston/roslyn,DustinCampbell/roslyn,AmadeusW/roslyn,dotnet/roslyn,reaction1989/roslyn,genlu/roslyn,swaroop-sridhar/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,stephentoub/roslyn,weltkante/roslyn,dotnet/roslyn,brettfo/roslyn,orthoxerox/roslyn,MichalStrehovsky/roslyn,AnthonyDGreen/roslyn,VSadov/roslyn,ErikSchierboom/roslyn,wvdd007/roslyn,jkotas/roslyn,jeffanders/roslyn,OmarTawfik/roslyn,mattwar/roslyn,davkean/roslyn,xasx/roslyn,mgoertz-msft/roslyn,mgoertz-msft/roslyn,jmarolf/roslyn,OmarTawfik/roslyn,jasonmalinowski/roslyn,CyrusNajmabadi/roslyn,physhi/roslyn,jasonmalinowski/roslyn,gafter/roslyn,TyOverby/roslyn,paulvanbrenk/roslyn,AlekseyTs/roslyn,abock/roslyn,AlekseyTs/roslyn,AmadeusW/roslyn,yeaicc/roslyn,MattWindsor91/roslyn,lorcanmooney/roslyn,kelltrick/roslyn,jkotas/roslyn,cston/roslyn,tmat/roslyn,yeaicc/roslyn,physhi/roslyn,diryboy/roslyn,zooba/roslyn,wvdd007/roslyn,jcouv/roslyn,amcasey/roslyn,khyperia/roslyn,Hosch250/roslyn,drognanar/roslyn,gafter/roslyn,kelltrick/roslyn,physhi/roslyn,jasonmalinowski/roslyn,shyamnamboodiripad/roslyn,AnthonyDGreen/roslyn,jeffanders/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,akrisiun/roslyn,nguerrera/roslyn,lorcanmooney/roslyn,wvdd007/roslyn,drognanar/roslyn,tvand7093/roslyn,genlu/roslyn,pdelvo/roslyn,reaction1989/roslyn,aelij/roslyn,lorcanmooney/roslyn,orthoxerox/roslyn,genlu/roslyn,mavasani/roslyn,reaction1989/roslyn,jeffanders/roslyn,TyOverby/roslyn,swaroop-sridhar/roslyn,CyrusNajmabadi/roslyn,diryboy/roslyn,robinsedlaczek/roslyn,jamesqo/roslyn,mgoertz-msft/roslyn,paulvanbrenk/roslyn,jmarolf/roslyn,heejaechang/roslyn,brettfo/roslyn,tvand7093/roslyn,jcouv/roslyn,akrisiun/roslyn,eriawan/roslyn,drognanar/roslyn,stephentoub/roslyn,CyrusNajmabadi/roslyn,KirillOsenkov/roslyn,DustinCampbell/roslyn,MattWindsor91/roslyn,srivatsn/roslyn,panopticoncentral/roslyn,robinsedlaczek/roslyn,orthoxerox/roslyn,xasx/roslyn,mmitche/roslyn,CaptainHayashi/roslyn,swaroop-sridhar/roslyn,CaptainHayashi/roslyn,tmat/roslyn,shyamnamboodiripad/roslyn,tmat/roslyn,tmeschter/roslyn,tannergooding/roslyn,khyperia/roslyn,panopticoncentral/roslyn,nguerrera/roslyn,MichalStrehovsky/roslyn,KevinRansom/roslyn,TyOverby/roslyn,KevinRansom/roslyn,OmarTawfik/roslyn,stephentoub/roslyn,ErikSchierboom/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,mmitche/roslyn,xasx/roslyn,agocke/roslyn,mattscheffer/roslyn,weltkante/roslyn,cston/roslyn,pdelvo/roslyn,DustinCampbell/roslyn,jkotas/roslyn,bkoelman/roslyn,tmeschter/roslyn
src/Workspaces/Core/Portable/Editing/DeclarationKind.cs
src/Workspaces/Core/Portable/Editing/DeclarationKind.cs
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. namespace Microsoft.CodeAnalysis.Editing { public enum DeclarationKind { None, CompilationUnit, Class, Struct, Interface, Enum, Delegate, Method, Operator, ConversionOperator, Constructor, Destructor, Field, Property, Indexer, EnumMember, Event, CustomEvent, Namespace, NamespaceImport, Parameter, Variable, Attribute, LambdaExpression, GetAccessor, SetAccessor, AddAccessor, RemoveAccessor, RaiseAccessor } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. namespace Microsoft.CodeAnalysis.Editing { public enum DeclarationKind { None, CompilationUnit, Class, Struct, Interface, Enum, Delegate, Method, Operator, ConversionOperator, Constructor, Destructor, Field, Property, Indexer, EnumMember, Event, CustomEvent, Namespace, NamespaceImport, Parameter, Variable, Attribute, LambdaExpression, GetAccessor, SetAccessor, AddAccessor, RemoveAccessor, RaiseAccessor, } }
apache-2.0
C#
e7c86dc7c535e2e99d313e104a24eee64151c2d4
Use SetUp for tests, add test for clearing children
ppy/osu-framework,peppy/osu-framework,peppy/osu-framework,ppy/osu-framework,peppy/osu-framework,ppy/osu-framework
osu.Framework.Tests/Visual/Containers/TestSceneEnumerator.cs
osu.Framework.Tests/Visual/Containers/TestSceneEnumerator.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable disable using System; using NUnit.Framework; using osu.Framework.Graphics.Containers; namespace osu.Framework.Tests.Visual.Containers { public class TestSceneEnumerator : FrameworkTestScene { private Container parent; [SetUp] public void SetUp() { Child = parent = new Container { Child = new Container { } }; } [Test] public void TestEnumeratingNormally() { AddStep("iterate through parent doing nothing", () => Assert.DoesNotThrow(() => { foreach (var child in parent) { } })); } [Test] public void TestAddChildDuringEnumerationFails() { AddStep("adding child during enumeration fails", () => Assert.Throws<InvalidOperationException>(() => { foreach (var child in parent) { parent.Add(new Container()); } })); } [Test] public void TestRemoveChildDuringEnumerationFails() { AddStep("removing child during enumeration fails", () => Assert.Throws<InvalidOperationException>(() => { foreach (var child in parent) { parent.Remove(child, true); } })); } [Test] public void TestClearDuringEnumerationFails() { AddStep("clearing children during enumeration fails", () => Assert.Throws<InvalidOperationException>(() => { foreach (var child in parent) { parent.Clear(); } })); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable disable using System; using NUnit.Framework; using osu.Framework.Graphics.Containers; namespace osu.Framework.Tests.Visual.Containers { public class TestSceneEnumerator : FrameworkTestScene { private Container parent; [Test] public void TestAddChildDuringEnumerationFails() { AddStep("create hierarchy", () => Child = parent = new Container { Child = new Container { } }); AddStep("iterate through parent doing nothing", () => Assert.DoesNotThrow(() => { foreach (var child in parent) { } })); AddStep("adding child during enumeration fails", () => Assert.Throws<InvalidOperationException>(() => { foreach (var child in parent) { parent.Add(new Container()); } })); } [Test] public void TestRemoveChildDuringEnumerationFails() { AddStep("create hierarchy", () => Child = parent = new Container { Child = new Container { } }); AddStep("iterate through parent doing nothing", () => Assert.DoesNotThrow(() => { foreach (var child in parent) { } })); AddStep("removing child during enumeration fails", () => Assert.Throws<InvalidOperationException>(() => { foreach (var child in parent) { parent.Remove(child, true); } })); } } }
mit
C#
dced6a2e682a9902f43e1901e2ae1912bb637016
Add extended test coverage for desired input handling
peppy/osu,ppy/osu,smoogipoo/osu,smoogipoo/osu,peppy/osu,ppy/osu,smoogipooo/osu,peppy/osu,NeoAdonis/osu,NeoAdonis/osu,ppy/osu,smoogipoo/osu,NeoAdonis/osu
osu.Game.Tests/Visual/Settings/TestSceneSettingsNumberBox.cs
osu.Game.Tests/Visual/Settings/TestSceneSettingsNumberBox.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Linq; using NUnit.Framework; using osu.Framework.Testing; using osu.Game.Graphics.UserInterface; using osu.Game.Overlays.Settings; namespace osu.Game.Tests.Visual.Settings { public class TestSceneSettingsNumberBox : OsuTestScene { private SettingsNumberBox numberBox; private OsuTextBox textBox; [SetUpSteps] public void SetUpSteps() { AddStep("create number box", () => Child = numberBox = new SettingsNumberBox()); AddStep("get inner text box", () => textBox = numberBox.ChildrenOfType<OsuTextBox>().Single()); } [Test] public void TestLargeInteger() { AddStep("set current to 1,000,000,000", () => numberBox.Current.Value = 1_000_000_000); AddAssert("text box text is correct", () => textBox.Text == "1000000000"); } [Test] public void TestUserInput() { inputText("42"); currentValueIs(42); currentTextIs("42"); inputText(string.Empty); currentValueIs(null); currentTextIs(string.Empty); inputText("555"); currentValueIs(555); currentTextIs("555"); inputText("-4444"); // attempting to input the minus will raise an input error, the rest will pass through fine. currentValueIs(4444); currentTextIs("4444"); // checking the upper bound. inputText(int.MaxValue.ToString()); currentValueIs(int.MaxValue); currentTextIs(int.MaxValue.ToString()); inputText((long)int.MaxValue + 1.ToString()); currentValueIs(int.MaxValue); currentTextIs(int.MaxValue.ToString()); inputText("0"); currentValueIs(0); currentTextIs("0"); // checking that leading zeroes are stripped. inputText("00"); currentValueIs(0); currentTextIs("0"); inputText("01"); currentValueIs(1); currentTextIs("1"); } private void inputText(string text) => AddStep($"set textbox text to {text}", () => textBox.Text = text); private void currentValueIs(int? value) => AddAssert($"current value is {value?.ToString() ?? "null"}", () => numberBox.Current.Value == value); private void currentTextIs(string value) => AddAssert($"current text is {value}", () => textBox.Text == value); } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Linq; using NUnit.Framework; using osu.Framework.Testing; using osu.Game.Graphics.UserInterface; using osu.Game.Overlays.Settings; namespace osu.Game.Tests.Visual.Settings { public class TestSceneSettingsNumberBox : OsuTestScene { [Test] public void TestLargeInteger() { SettingsNumberBox numberBox = null; AddStep("create number box", () => Child = numberBox = new SettingsNumberBox()); AddStep("set value to 1,000,000,000", () => numberBox.Current.Value = 1_000_000_000); AddAssert("text box text is correct", () => numberBox.ChildrenOfType<OsuTextBox>().Single().Current.Value == "1000000000"); } } }
mit
C#
eb26f6f4273c638fac4be82a7a8535bcdf42a820
Add failing test case
smoogipoo/osu,peppy/osu,UselessToucan/osu,UselessToucan/osu,NeoAdonis/osu,ppy/osu,NeoAdonis/osu,smoogipooo/osu,UselessToucan/osu,peppy/osu,ppy/osu,peppy/osu-new,ppy/osu,peppy/osu,smoogipoo/osu,NeoAdonis/osu,smoogipoo/osu
osu.Game.Tournament.Tests/Screens/TestSceneGameplayScreen.cs
osu.Game.Tournament.Tests/Screens/TestSceneGameplayScreen.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Linq; using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Testing; using osu.Game.Tournament.Components; using osu.Game.Tournament.Screens.Gameplay; using osu.Game.Tournament.Screens.Gameplay.Components; namespace osu.Game.Tournament.Tests.Screens { public class TestSceneGameplayScreen : TournamentTestScene { [Cached] private TournamentMatchChatDisplay chat = new TournamentMatchChatDisplay { Width = 0.5f }; [BackgroundDependencyLoader] private void load() { Add(new GameplayScreen()); Add(chat); } [Test] public void TestWarmup() { checkScoreVisibility(false); toggleWarmup(); checkScoreVisibility(true); toggleWarmup(); checkScoreVisibility(false); } private void checkScoreVisibility(bool visible) => AddUntilStep($"scores {(visible ? "shown" : "hidden")}", () => this.ChildrenOfType<TeamScore>().All(score => score.Alpha == (visible ? 1 : 0))); private void toggleWarmup() => AddStep("toggle warmup", () => this.ChildrenOfType<TourneyButton>().First().Click()); } }
// 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.Game.Tournament.Components; using osu.Game.Tournament.Screens.Gameplay; namespace osu.Game.Tournament.Tests.Screens { public class TestSceneGameplayScreen : TournamentTestScene { [Cached] private TournamentMatchChatDisplay chat = new TournamentMatchChatDisplay { Width = 0.5f }; [BackgroundDependencyLoader] private void load() { Add(new GameplayScreen()); Add(chat); } } }
mit
C#
977b4049a4b9704227dbd410696f66a189ead0bf
Handle Keyboard events rather than polling
smoogipooo/osu-framework,naoey/osu-framework,DrabWeb/osu-framework,ppy/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,paparony03/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,Tom94/osu-framework,peppy/osu-framework,naoey/osu-framework,Nabile-Rahmani/osu-framework,Nabile-Rahmani/osu-framework,EVAST9919/osu-framework,Tom94/osu-framework,ZLima12/osu-framework,ppy/osu-framework,default0/osu-framework,paparony03/osu-framework,DrabWeb/osu-framework,default0/osu-framework,ZLima12/osu-framework,ppy/osu-framework,DrabWeb/osu-framework
osu.Framework.Desktop/Input/Handlers/Keyboard/OpenTKKeyboardHandler.cs
osu.Framework.Desktop/Input/Handlers/Keyboard/OpenTKKeyboardHandler.cs
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System; using System.Collections.Generic; using System.Linq; using osu.Framework.Input; using osu.Framework.Input.Handlers; using osu.Framework.Platform; using OpenTK.Input; using KeyboardState = osu.Framework.Input.KeyboardState; using osu.Framework.Statistics; namespace osu.Framework.Desktop.Input.Handlers.Keyboard { internal class OpenTKKeyboardHandler : InputHandler { public override bool IsActive => true; public override int Priority => 0; private OpenTK.Input.KeyboardState lastState; public override bool Initialize(GameHost host) { host.Window.KeyDown += handleState; host.Window.KeyUp += handleState; return true; } private void handleState(object sender, KeyboardKeyEventArgs e) { var state = e.Keyboard; if (state.Equals(lastState)) return; lastState = state; PendingStates.Enqueue(new InputState { Keyboard = new TkKeyboardState(state) }); FrameStatistics.Increment(StatisticsCounterType.KeyEvents); } private class TkKeyboardState : KeyboardState { private static readonly IEnumerable<Key> all_keys = Enum.GetValues(typeof(Key)).Cast<Key>(); public TkKeyboardState(OpenTK.Input.KeyboardState tkState) { if (tkState.IsAnyKeyDown) Keys = all_keys.Where(tkState.IsKeyDown); } } } }
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System; using System.Collections.Generic; using System.Linq; using osu.Framework.Input; using osu.Framework.Input.Handlers; using osu.Framework.Platform; using osu.Framework.Threading; using OpenTK.Input; using KeyboardState = osu.Framework.Input.KeyboardState; using osu.Framework.Statistics; namespace osu.Framework.Desktop.Input.Handlers.Keyboard { internal class OpenTKKeyboardHandler : InputHandler { private ScheduledDelegate scheduled; public override bool IsActive => true; public override int Priority => 0; private OpenTK.Input.KeyboardState lastState; public override bool Initialize(GameHost host) { host.InputThread.Scheduler.Add(scheduled = new ScheduledDelegate(delegate { var state = host.IsActive ? OpenTK.Input.Keyboard.GetState() : new OpenTK.Input.KeyboardState(); if (state.Equals(lastState)) return; lastState = state; PendingStates.Enqueue(new InputState { Keyboard = new TkKeyboardState(state) }); FrameStatistics.Increment(StatisticsCounterType.KeyEvents); }, 0, 0)); return true; } protected override void Dispose(bool disposing) { base.Dispose(disposing); scheduled.Cancel(); } private class TkKeyboardState : KeyboardState { private static readonly IEnumerable<Key> all_keys = Enum.GetValues(typeof(Key)).Cast<Key>(); public TkKeyboardState(OpenTK.Input.KeyboardState tkState) { if (tkState.IsAnyKeyDown) Keys = all_keys.Where(tkState.IsKeyDown); } } } }
mit
C#
1f21b41eb6e893f5a594f525144523d55903f3a9
move try/catch down
danielgerlag/workflow-core
src/WorkflowCore/Services/LifeCycleEventPublisher.cs
src/WorkflowCore/Services/LifeCycleEventPublisher.cs
using Microsoft.Extensions.Logging; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using WorkflowCore.Interface; using WorkflowCore.Models.LifeCycleEvents; namespace WorkflowCore.Services { public class LifeCycleEventPublisher : ILifeCycleEventPublisher, IDisposable { private readonly ILifeCycleEventHub _eventHub; private readonly ILogger _logger; private readonly BlockingCollection<LifeCycleEvent> _outbox; private Task _dispatchTask; public LifeCycleEventPublisher(ILifeCycleEventHub eventHub, ILoggerFactory loggerFactory) { _eventHub = eventHub; _outbox = new BlockingCollection<LifeCycleEvent>(); _logger = loggerFactory.CreateLogger(GetType()); } public void PublishNotification(LifeCycleEvent evt) { if (_outbox.IsAddingCompleted) return; _outbox.Add(evt); } public void Start() { if (_dispatchTask != null) { throw new InvalidOperationException(); } _dispatchTask = new Task(Execute); _dispatchTask.Start(); } public void Stop() { _outbox.CompleteAdding(); _dispatchTask.Wait(); _dispatchTask = null; } public void Dispose() { _outbox.Dispose(); } private async void Execute() { foreach (var evt in _outbox.GetConsumingEnumerable()) { try { await _eventHub.PublishNotification(evt); } catch (Exception ex) { _logger.LogError(default(EventId), ex, ex.Message); } } } } }
using Microsoft.Extensions.Logging; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using WorkflowCore.Interface; using WorkflowCore.Models.LifeCycleEvents; namespace WorkflowCore.Services { public class LifeCycleEventPublisher : ILifeCycleEventPublisher, IDisposable { private readonly ILifeCycleEventHub _eventHub; private readonly ILogger _logger; private readonly BlockingCollection<LifeCycleEvent> _outbox; protected Task DispatchTask; public LifeCycleEventPublisher(ILifeCycleEventHub eventHub, ILoggerFactory loggerFactory) { _eventHub = eventHub; _outbox = new BlockingCollection<LifeCycleEvent>(); _logger = loggerFactory.CreateLogger(GetType()); } public void PublishNotification(LifeCycleEvent evt) { if (_outbox.IsAddingCompleted) return; _outbox.Add(evt); } public void Start() { if (DispatchTask != null) { throw new InvalidOperationException(); } DispatchTask = new Task(Execute); DispatchTask.Start(); } public void Stop() { _outbox.CompleteAdding(); DispatchTask.Wait(); DispatchTask = null; } public void Dispose() { _outbox.Dispose(); } private async void Execute() { try { foreach (var evt in _outbox.GetConsumingEnumerable()) { await _eventHub.PublishNotification(evt); } } catch (Exception ex) { _logger.LogError(default(EventId), ex, ex.Message); } } } }
mit
C#
a2722dd4035ef2e8305d82061cb3fca63af4cdfe
Fix Unity 5.2 errors
redbluegames/unity-bulk-rename,redbluegames/unity-mulligan-renamer
Assets/RedBlueGames/MulliganRenamer/Editor/ObjectNameDelta.cs
Assets/RedBlueGames/MulliganRenamer/Editor/ObjectNameDelta.cs
/* MIT License Copyright (c) 2016 Edward Rowe, RedBlueGames 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 RedBlueGames.MulliganRenamer { using System.Collections; using System.Collections.Generic; using UnityEngine; /// <summary> /// Object name delta tracks name changes to an Object. /// </summary> public class ObjectNameDelta { /// <summary> /// Initializes a new instance of the <see cref="ObjectNameDelta"/> class. /// </summary> /// <param name="obj">Object associated with these names.</param> /// <param name="newName">New name for the object</param> public ObjectNameDelta(UnityEngine.Object obj, string newName) { this.NamedObject = obj; this.OldName = obj.name; this.NewName = newName; } /// <summary> /// Gets the named object. /// </summary> /// <value>The named object.</value> public UnityEngine.Object NamedObject { get; private set;} /// <summary> /// Gets the old name of the object. /// </summary> /// <value>The old name.</value> public string OldName { get; private set;} /// <summary> /// Gets the new name of the object. /// </summary> /// <value>The new name.</value> public string NewName { get; private set;} } }
/* MIT License Copyright (c) 2016 Edward Rowe, RedBlueGames 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 RedBlueGames.MulliganRenamer { using System.Collections; using System.Collections.Generic; using UnityEngine; /// <summary> /// Object name delta tracks name changes to an Object. /// </summary> public class ObjectNameDelta { /// <summary> /// Initializes a new instance of the <see cref="ObjectNameDelta"/> class. /// </summary> /// <param name="obj">Object associated with these names.</param> /// <param name="newName">New name for the object</param> public ObjectNameDelta(UnityEngine.Object obj, string newName) { this.NamedObject = obj; this.OldName = obj.name; this.NewName = newName; } /// <summary> /// Gets the named object. /// </summary> /// <value>The named object.</value> public UnityEngine.Object NamedObject { get; } /// <summary> /// Gets the old name of the object. /// </summary> /// <value>The old name.</value> public string OldName { get; } /// <summary> /// Gets the new name of the object. /// </summary> /// <value>The new name.</value> public string NewName { get; } } }
mit
C#
f2aee98a14453e51d673007153611eaac525c29c
Change some comments on IWithdrawal (#3556)
Neurosploit/StratisBitcoinFullNode,quantumagi/StratisBitcoinFullNode,quantumagi/StratisBitcoinFullNode,fassadlr/StratisBitcoinFullNode,fassadlr/StratisBitcoinFullNode,Neurosploit/StratisBitcoinFullNode,stratisproject/StratisBitcoinFullNode,stratisproject/StratisBitcoinFullNode,Neurosploit/StratisBitcoinFullNode
src/Stratis.Features.FederatedPeg/Interfaces/IWithdrawal.cs
src/Stratis.Features.FederatedPeg/Interfaces/IWithdrawal.cs
using NBitcoin; using Newtonsoft.Json; using Stratis.Bitcoin.Utilities.JsonConverters; namespace Stratis.Features.FederatedPeg.Interfaces { /// <summary> /// Represents a withdrawal made from a source chain to a target chain. /// </summary> public interface IWithdrawal { /// <summary> /// The hash of the deposit transaction from the source chain. /// </summary> [JsonConverter(typeof(UInt256JsonConverter))] uint256 DepositId { get; } /// <summary> /// The hash of the withdrawal transaction to the target chain. /// This can be null until the trx is fully signed. /// </summary> [JsonConverter(typeof(UInt256JsonConverter))] uint256 Id { get; } /// <summary> /// The amount of fund transferred (in target currency). /// </summary> [JsonConverter(typeof(MoneyJsonConverter))] Money Amount { get; } /// <summary> /// The target address, on the target chain, for the fund deposited on the multi-sig. /// </summary> string TargetAddress { get; } /// <summary> /// The block number on the target chain where the withdrawal has been deposited. /// </summary> int BlockNumber { get; } /// <summary> /// The block hash on the target chain where the withdrawal has been deposited. /// </summary> [JsonConverter(typeof(UInt256JsonConverter))] uint256 BlockHash { get; } /// <summary> /// Abbreviated information about the withdrawal. /// </summary> string GetInfo(); } }
using NBitcoin; using Newtonsoft.Json; using Stratis.Bitcoin.Utilities.JsonConverters; namespace Stratis.Features.FederatedPeg.Interfaces { /// <summary> /// Represents a withdrawals made from a sidechain mutlisig, with the aim of realising /// a cross chain transfer. /// </summary> public interface IWithdrawal { /// <summary> /// The Id (or hash) of the source transaction that originates the fund transfer. /// </summary> [JsonConverter(typeof(UInt256JsonConverter))] uint256 DepositId { get; } /// <summary> /// The Id (or hash) of the source transaction that originated the fund /// transfer causing this withdrawal. /// </summary> [JsonConverter(typeof(UInt256JsonConverter))] uint256 Id { get; } /// <summary> /// The amount of fund transferred (in target currency). /// </summary> [JsonConverter(typeof(MoneyJsonConverter))] Money Amount { get; } /// <summary> /// The target address, on the target chain, for the fund deposited on the multisig. /// </summary> string TargetAddress { get; } /// <summary> /// The block number where the target deposit has been persisted. /// </summary> int BlockNumber { get; } /// <summary> /// The hash of the block where the target deposit has been persisted. /// </summary> [JsonConverter(typeof(UInt256JsonConverter))] uint256 BlockHash { get; } /// <summary> /// Abbreviated information about the withdrawal. /// </summary> string GetInfo(); } }
mit
C#
e4a2c027431c66d4815c33fef08147ae868bf2eb
Update Lombiq.HelpfulExtensions.Tests.UI/Constants/XPathSelectors.cs
Lombiq/Helpful-Extensions,Lombiq/Helpful-Extensions
Lombiq.HelpfulExtensions.Tests.UI/Constants/XPathSelectors.cs
Lombiq.HelpfulExtensions.Tests.UI/Constants/XPathSelectors.cs
namespace Lombiq.HelpfulExtensions.Tests.UI.Constants; public static class XPathSelectors { public const string AddWidgetButtonGroup = "//div[contains(@class, 'btn-widget-add-below-wrapper')]" + "/div/div[@class='btn-group']"; public const string AddWidgetButton = $"{AddWidgetButtonGroup}/button[@title='Add Widget']"; public const string WidgetList = $"{AddWidgetButtonGroup}/div[@class='dropdown-menu']"; public const string WidgetEditorHeader = "//div[contains(@class, 'widget-template')]" + "/div[contains(@class, 'widget-editor')]" + "/div[contains(@class, 'widget-editor-header')]"; public const string WidgetEditorHeaderText = $"{WidgetEditorHeader}/span[contains(@class, 'widget-editor-header-text')]"; public const string FlowSettingsButtonGroup = $"{WidgetEditorHeader}/div[contains(@class, 'btn-widget-metadata')]" + "/div[@class='btn-group']/div[@class='btn-group']"; public const string FlowSettingsButton = $"{FlowSettingsButtonGroup}/button[@title='Settings']"; public const string FlowSettingsDropdown = $"{FlowSettingsButtonGroup}/div[contains(@class, 'dropdown-menu')]"; public const string CustomClassesInput = "id('FlowPart-0_ContentItem_CustomClasses')"; }
namespace Lombiq.HelpfulExtensions.Tests.UI.Constants; public static class XPathSelectors { public const string AddWidgetButtonGroup = "//div[contains(@class, 'btn-widget-add-below-wrapper')]" + "/div/div[@class='btn-group']"; public const string AddWidgetButton = $"{AddWidgetButtonGroup}/button[@title='Add Widget']"; public const string WidgetList = $"{AddWidgetButtonGroup}/div[@class='dropdown-menu']"; public const string WidgetEditorHeader = "//div[contains(@class, 'widget-template')]" + "/div[contains(@class, 'widget-editor')]" + "/div[contains(@class, 'widget-editor-header')]"; public const string WidgetEditorHeaderText = $"{WidgetEditorHeader}/span[contains(@class, 'widget-editor-header-text')]"; public const string FlowSettingsButtonGroup = $"{WidgetEditorHeader}/div[contains(@class, 'btn-widget-metadata')]" + "/div[@class='btn-group']/div[@class='btn-group']"; public const string FlowSettingsButton = $"{FlowSettingsButtonGroup}/button[@title='Settings']"; public const string FlowSettingsDropdown = $"{FlowSettingsButtonGroup}/div[contains(@class, 'dropdown-menu')]"; public const string CustomClassesInput = $"{FlowSettingsDropdown}/div[@class='form-group']" + "/input[@id='FlowPart-0_ContentItem_CustomClasses']"; }
bsd-3-clause
C#
58c2736361674eb4752394b3694cee344ac1e6df
Enable pattern helper as equivalent of component helper
namics/NitroNet,namics/NitroNet
NitroNet.ViewEngine.TemplateHandler/ComponentHelperHandler.cs
NitroNet.ViewEngine.TemplateHandler/ComponentHelperHandler.cs
using System; using System.Collections.Generic; using System.Linq; using Veil; using Veil.Helper; namespace NitroNet.ViewEngine.TemplateHandler { internal class ComponentHelperHandler : IHelperHandler { private readonly INitroTemplateHandler _handler; public ComponentHelperHandler(INitroTemplateHandler handler) { _handler = handler; } public bool IsSupported(string name) { return name.StartsWith("component", StringComparison.OrdinalIgnoreCase) || name.StartsWith("pattern", StringComparison.OrdinalIgnoreCase); } public void Evaluate(object model, RenderingContext context, IDictionary<string, string> parameters) { RenderingParameter template; var firstParameter = parameters.FirstOrDefault(); if (string.IsNullOrEmpty(firstParameter.Value)) { template = new RenderingParameter("name") { Value = firstParameter.Key.Trim('"', '\'') }; } else { template = CreateRenderingParameter("name", parameters); } var skin = CreateRenderingParameter("template", parameters); var dataVariation = CreateRenderingParameter("data", parameters); _handler.RenderComponent(template, skin, dataVariation, model, context); } private RenderingParameter CreateRenderingParameter(string name, IDictionary<string, string> parameters) { var renderingParameter = new RenderingParameter(name); if (parameters.ContainsKey(renderingParameter.Name)) { var value = parameters[renderingParameter.Name]; if (!value.StartsWith("\"") && !value.StartsWith("'")) { renderingParameter.IsDynamic = true; } renderingParameter.Value = value.Trim('"', '\''); } return renderingParameter; } } }
using System; using System.Collections.Generic; using System.Linq; using Veil; using Veil.Helper; namespace NitroNet.ViewEngine.TemplateHandler { internal class ComponentHelperHandler : IHelperHandler { private readonly INitroTemplateHandler _handler; public ComponentHelperHandler(INitroTemplateHandler handler) { _handler = handler; } public bool IsSupported(string name) { return name.StartsWith("component", StringComparison.OrdinalIgnoreCase); } public void Evaluate(object model, RenderingContext context, IDictionary<string, string> parameters) { RenderingParameter template; var firstParameter = parameters.FirstOrDefault(); if (string.IsNullOrEmpty(firstParameter.Value)) { template = new RenderingParameter("name") { Value = firstParameter.Key.Trim('"', '\'') }; } else { template = CreateRenderingParameter("name", parameters); } var skin = CreateRenderingParameter("template", parameters); var dataVariation = CreateRenderingParameter("data", parameters); _handler.RenderComponent(template, skin, dataVariation, model, context); } private RenderingParameter CreateRenderingParameter(string name, IDictionary<string, string> parameters) { var renderingParameter = new RenderingParameter(name); if (parameters.ContainsKey(renderingParameter.Name)) { var value = parameters[renderingParameter.Name]; if (!value.StartsWith("\"") && !value.StartsWith("'")) { renderingParameter.IsDynamic = true; } renderingParameter.Value = value.Trim('"', '\''); } return renderingParameter; } } }
mit
C#
3a56c2344c9cf213f8736805c0888fe76892b1f4
Update SiteController.cs
gnalvesteffer/StoreManagement,gnalvesteffer/StoreManagement
StoreManagement/StoreManagement/Controllers/SiteController.cs
StoreManagement/StoreManagement/Controllers/SiteController.cs
using StoreManagement.Models.Services; using System.Web.Mvc; namespace StoreManagement.Controllers { public class SiteController : Controller { private readonly StoreService _storeService = new StoreService(); public ActionResult Index() { return View(); } [Route("stores")] public ActionResult StoreList() { return View(_storeService.GetStores()); } [Route("store/{storeNumber}")] public ActionResult StoreDetail(int storeNumber) { return View(_storeService.GetStore(storeNumber)); } [Route("store/new")] public ActionResult AddStore() { return View(); } } }
using StoreManagement.Models.Services; using System.Web.Mvc; namespace StoreManagement.Controllers { public class SiteController : Controller { private readonly StoreService _storeService = new StoreService(); // GET: Home public ActionResult Index() { return View(); } [Route("stores")] public ActionResult StoreList() { return View(_storeService.GetStores()); } [Route("store/{storeNumber}")] public ActionResult StoreDetail(int storeNumber) { return View(_storeService.GetStore(storeNumber)); } [Route("store/new")] public ActionResult AddStore() { return View(); } } }
mit
C#
867f383028514af3dfa928e70fad14cc1b92f6c9
Fix refcount issue disposing sampler state pins
id144/dx11-vvvv,id144/dx11-vvvv,id144/dx11-vvvv
Core/VVVV.DX11.Lib/Effects/Pins/Resources/SamplerShaderPin.cs
Core/VVVV.DX11.Lib/Effects/Pins/Resources/SamplerShaderPin.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using VVVV.DX11.Internals.Effects.Pins; using VVVV.PluginInterfaces.V2; using SlimDX.Direct3D11; using VVVV.PluginInterfaces.V1; using VVVV.Hosting.Pins; using VVVV.DX11.Lib.Effects.Pins; using FeralTic.DX11; namespace VVVV.DX11.Internals.Effects.Pins { public class SamplerShaderPin : AbstractShaderV2Pin<SamplerDescription> { private SamplerState state; protected override void ProcessAttribute(InputAttribute attr, EffectVariable var) { attr.IsSingle = true; attr.CheckIfChanged = true; } protected override bool RecreatePin(EffectVariable var) { return false; } public override void SetVariable(DX11ShaderInstance shaderinstance, int slice) { if (this.pin.PluginIO.IsConnected) { if (this.pin.IsChanged) { if (this.state != null) { this.state.Dispose(); this.state = null; } } if (this.state == null || this.state.Disposed) { this.state = SamplerState.FromDescription(shaderinstance.RenderContext.Device, this.pin[0]); } shaderinstance.SetByName(this.Name, this.state); } else { if (this.state != null) { this.state.Dispose(); this.state = null; shaderinstance.SetByName(this.Name, this.state); } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using VVVV.DX11.Internals.Effects.Pins; using VVVV.PluginInterfaces.V2; using SlimDX.Direct3D11; using VVVV.PluginInterfaces.V1; using VVVV.Hosting.Pins; using VVVV.DX11.Lib.Effects.Pins; using FeralTic.DX11; namespace VVVV.DX11.Internals.Effects.Pins { public class SamplerShaderPin : AbstractShaderV2Pin<SamplerDescription> { private SamplerState state; protected override void ProcessAttribute(InputAttribute attr, EffectVariable var) { attr.IsSingle = true; attr.CheckIfChanged = true; } protected override bool RecreatePin(EffectVariable var) { return false; } public override void SetVariable(DX11ShaderInstance shaderinstance, int slice) { if (this.pin.PluginIO.IsConnected) { if (this.pin.IsChanged) { if (this.state != null) { this.state.Dispose(); this.state = null; } } if (this.state == null) { this.state = SamplerState.FromDescription(shaderinstance.RenderContext.Device, this.pin[0]); } shaderinstance.SetByName(this.Name, this.state); } else { if (this.state != null) { this.state.Dispose(); this.state = null; shaderinstance.SetByName(this.Name, this.state); } } } } }
bsd-3-clause
C#
6429574fff991a9e6bdd9efc578aa41e29f580da
Fix verbosity tests
dasMulli/cli,svick/cli,harshjain2/cli,livarcocc/cli-1,harshjain2/cli,Faizan2304/cli,Faizan2304/cli,blackdwarf/cli,EdwardBlair/cli,Faizan2304/cli,johnbeisner/cli,blackdwarf/cli,livarcocc/cli-1,ravimeda/cli,svick/cli,ravimeda/cli,EdwardBlair/cli,EdwardBlair/cli,johnbeisner/cli,harshjain2/cli,blackdwarf/cli,svick/cli,blackdwarf/cli,livarcocc/cli-1,ravimeda/cli,johnbeisner/cli,dasMulli/cli,dasMulli/cli
test/dotnet-msbuild.Tests/GivenDotnetCleanInvocation.cs
test/dotnet-msbuild.Tests/GivenDotnetCleanInvocation.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 Microsoft.DotNet.Tools.Clean; using FluentAssertions; using Xunit; using System; namespace Microsoft.DotNet.Cli.MSBuild.Tests { public class GivenDotnetCleanInvocation { const string ExpectedPrefix = "exec <msbuildpath> /m /v:m /t:Clean"; [Fact] public void ItAddsProjectToMsbuildInvocation() { var msbuildPath = "<msbuildpath>"; CleanCommand.FromArgs(new string[] { "<project>" }, msbuildPath) .GetProcessStartInfo().Arguments.Should().Be("exec <msbuildpath> /m /v:m <project> /t:Clean"); } [Theory] [InlineData(new string[] { }, "")] [InlineData(new string[] { "-o", "<output>" }, "/p:OutputPath=<output>")] [InlineData(new string[] { "--output", "<output>" }, "/p:OutputPath=<output>")] [InlineData(new string[] { "-f", "<framework>" }, "/p:TargetFramework=<framework>")] [InlineData(new string[] { "--framework", "<framework>" }, "/p:TargetFramework=<framework>")] [InlineData(new string[] { "-c", "<configuration>" }, "/p:Configuration=<configuration>")] [InlineData(new string[] { "--configuration", "<configuration>" }, "/p:Configuration=<configuration>")] [InlineData(new string[] { "-v", "diag" }, "/verbosity:diag")] [InlineData(new string[] { "--verbosity", "diag" }, "/verbosity:diag")] public void MsbuildInvocationIsCorrect(string[] args, string expectedAdditionalArgs) { expectedAdditionalArgs = (string.IsNullOrEmpty(expectedAdditionalArgs) ? "" : $" {expectedAdditionalArgs}"); var msbuildPath = "<msbuildpath>"; CleanCommand.FromArgs(args, msbuildPath) .GetProcessStartInfo().Arguments.Should().Be($"{ExpectedPrefix}{expectedAdditionalArgs}"); } } }
// 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 Microsoft.DotNet.Tools.Clean; using FluentAssertions; using Xunit; using System; namespace Microsoft.DotNet.Cli.MSBuild.Tests { public class GivenDotnetCleanInvocation { const string ExpectedPrefix = "exec <msbuildpath> /m /v:m /t:Clean"; [Fact] public void ItAddsProjectToMsbuildInvocation() { var msbuildPath = "<msbuildpath>"; CleanCommand.FromArgs(new string[] { "<project>" }, msbuildPath) .GetProcessStartInfo().Arguments.Should().Be("exec <msbuildpath> /m /v:m <project> /t:Clean"); } [Theory] [InlineData(new string[] { }, "")] [InlineData(new string[] { "-o", "<output>" }, "/p:OutputPath=<output>")] [InlineData(new string[] { "--output", "<output>" }, "/p:OutputPath=<output>")] [InlineData(new string[] { "-f", "<framework>" }, "/p:TargetFramework=<framework>")] [InlineData(new string[] { "--framework", "<framework>" }, "/p:TargetFramework=<framework>")] [InlineData(new string[] { "-c", "<configuration>" }, "/p:Configuration=<configuration>")] [InlineData(new string[] { "--configuration", "<configuration>" }, "/p:Configuration=<configuration>")] [InlineData(new string[] { "-v", "<verbosity>" }, "/verbosity:<verbosity>")] [InlineData(new string[] { "--verbosity", "<verbosity>" }, "/verbosity:<verbosity>")] public void MsbuildInvocationIsCorrect(string[] args, string expectedAdditionalArgs) { expectedAdditionalArgs = (string.IsNullOrEmpty(expectedAdditionalArgs) ? "" : $" {expectedAdditionalArgs}"); var msbuildPath = "<msbuildpath>"; CleanCommand.FromArgs(args, msbuildPath) .GetProcessStartInfo().Arguments.Should().Be($"{ExpectedPrefix}{expectedAdditionalArgs}"); } } }
mit
C#
441feb43225cdf9a813f283657cce7ad4a21d3b7
add application version to EnvironmentApi
reinterpretcat/utymap,reinterpretcat/utymap,reinterpretcat/utymap
unity/demo/Assets/Scripts/Environment/EnvironmentApi.cs
unity/demo/Assets/Scripts/Environment/EnvironmentApi.cs
namespace Assets.Scripts.Environment { internal static class EnvironmentApi { /// <summary> Returns application version. </summary> public static string Version { get { return "0.1"; } } /// <summary> Returns directory where UtyMap stores files. </summary> /// <remarks> Read/write access is required. </remarks> public static string ExternalDataPath { get { #if UNITY_EDITOR return @"Assets/StreamingAssets/"; #else return UnityEngine.Application.persistentDataPath; #endif } } } }
namespace Assets.Scripts.Environment { internal static class EnvironmentApi { /// <summary> Returns directory where UtyMap stores files. </summary> /// <remarks> Read/write access is required. </remarks> public static string ExternalDataPath { get { #if UNITY_EDITOR return @"Assets/StreamingAssets/"; #else return UnityEngine.Application.persistentDataPath; #endif } } } }
apache-2.0
C#
b80beffad4960c498f73ecaf4057ab81e6855ad5
Rename Type parameters
inputfalken/Sharpy
GeneratorAPI/Generation.cs
GeneratorAPI/Generation.cs
using System; using System.Collections.Generic; using System.Linq; namespace GeneratorAPI { public class Generation<T> { private readonly IEnumerable<T> _infiniteEnumerable; public Generation(IEnumerable<T> infiniteEnumerable) => _infiniteEnumerable = infiniteEnumerable; public Generation<TResult> Select<TResult>(Func<T, TResult> fn) => new Generation<TResult>(_infiniteEnumerable .Select(fn)); public T Take() => _infiniteEnumerable.First(); public IEnumerable<T> Take(int count) => _infiniteEnumerable.Take(count); public Generation<TResult> SelectMany<TResult>(Func<T, Generation<TResult>> fn) { return new Generation<TResult>( _infiniteEnumerable.SelectMany(result => fn(result)._infiniteEnumerable)); } //BUG Runs forever since _infiniteEnumerable never ends. public Generation<TCompose> SelectMany<TResult, TCompose>(Func<T, Generation<TResult>> fn, Func<T, TResult, TCompose> composer) { return new Generation<TCompose>( _infiniteEnumerable.SelectMany(result => fn(result)._infiniteEnumerable, composer)); } public Generation<T> Where(Func<T, bool> predicate) => new Generation<T>( _infiniteEnumerable.Where(predicate)); } }
using System; using System.Collections.Generic; using System.Linq; namespace GeneratorAPI { public class Generation<TResult> { private readonly IEnumerable<TResult> _infiniteEnumerable; public Generation(IEnumerable<TResult> infiniteEnumerable) => _infiniteEnumerable = infiniteEnumerable; public Generation<T> Select<T>(Func<TResult, T> fn) => new Generation<T>(_infiniteEnumerable.Select(fn)); public TResult Take() => _infiniteEnumerable.First(); public IEnumerable<TResult> Take(int count) => _infiniteEnumerable.Take(count); public Generation<T> SelectMany<T>(Func<TResult, Generation<T>> fn) { return new Generation<T>( _infiniteEnumerable.SelectMany(result => fn(result)._infiniteEnumerable)); } //BUG Runs forever since _infiniteEnumerable never ends. public Generation<TCompose> SelectMany<T, TCompose>(Func<TResult, Generation<T>> fn, Func<TResult, T, TCompose> composer) { return new Generation<TCompose>( _infiniteEnumerable.SelectMany(result => fn(result)._infiniteEnumerable, composer)); } public Generation<TResult> Where(Func<TResult, bool> predicate) => new Generation<TResult>( _infiniteEnumerable.Where(predicate)); } }
mit
C#
0b95e36675b2131ae7eb0ca5185678f8d432a627
Fix RelativeChildSize error temporarily
DrabWeb/osu,johnneijzen/osu,peppy/osu,UselessToucan/osu,smoogipoo/osu,NeoAdonis/osu,ppy/osu,peppy/osu,johnneijzen/osu,ppy/osu,naoey/osu,DrabWeb/osu,peppy/osu,peppy/osu-new,EVAST9919/osu,Nabile-Rahmani/osu,2yangk23/osu,NeoAdonis/osu,naoey/osu,NeoAdonis/osu,2yangk23/osu,smoogipoo/osu,DrabWeb/osu,EVAST9919/osu,smoogipooo/osu,ppy/osu,smoogipoo/osu,UselessToucan/osu,Frontear/osuKyzer,ZLima12/osu,UselessToucan/osu,naoey/osu,ZLima12/osu
osu.Game/Screens/Edit/Components/Timelines/Summary/Parts/TimelinePart.cs
osu.Game/Screens/Edit/Components/Timelines/Summary/Parts/TimelinePart.cs
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using OpenTK; using osu.Framework.Configuration; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Beatmaps; namespace osu.Game.Screens.Edit.Components.Timelines.Summary.Parts { /// <summary> /// Represents a part of the summary timeline.. /// </summary> public abstract class TimelinePart : CompositeDrawable { public Bindable<WorkingBeatmap> Beatmap = new Bindable<WorkingBeatmap>(); private readonly Container timeline; protected TimelinePart() { AddInternal(timeline = new Container { RelativeSizeAxes = Axes.Both }); Beatmap.ValueChanged += b => { updateRelativeChildSize(); LoadBeatmap(b); }; } private void updateRelativeChildSize() { // the track may not be loaded completely (only has a length once it is). if (!Beatmap.Value.Track.IsLoaded) { timeline.RelativeChildSize = Vector2.One; Schedule(updateRelativeChildSize); return; } timeline.RelativeChildSize = Beatmap.Value.Track.Length == double.PositiveInfinity ? Vector2.One : new Vector2((float)Math.Max(1, Beatmap.Value.Track.Length), 1); } protected void Add(Drawable visualisation) => timeline.Add(visualisation); protected virtual void LoadBeatmap(WorkingBeatmap beatmap) { timeline.Clear(); } } }
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using OpenTK; using osu.Framework.Configuration; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Beatmaps; namespace osu.Game.Screens.Edit.Components.Timelines.Summary.Parts { /// <summary> /// Represents a part of the summary timeline.. /// </summary> public abstract class TimelinePart : CompositeDrawable { public Bindable<WorkingBeatmap> Beatmap = new Bindable<WorkingBeatmap>(); private readonly Container timeline; protected TimelinePart() { AddInternal(timeline = new Container { RelativeSizeAxes = Axes.Both }); Beatmap.ValueChanged += b => { updateRelativeChildSize(); LoadBeatmap(b); }; } private void updateRelativeChildSize() { // the track may not be loaded completely (only has a length once it is). if (!Beatmap.Value.Track.IsLoaded) { timeline.RelativeChildSize = Vector2.One; Schedule(updateRelativeChildSize); return; } timeline.RelativeChildSize = new Vector2((float)Math.Max(1, Beatmap.Value.Track.Length), 1); } protected void Add(Drawable visualisation) => timeline.Add(visualisation); protected virtual void LoadBeatmap(WorkingBeatmap beatmap) { timeline.Clear(); } } }
mit
C#
a6bbbd510c51d31f758fcce746eab08b998e940e
revert change made in error
luiseduardohdbackup/SevenDigital.Api.Wrapper,minkaotic/SevenDigital.Api.Wrapper,AnthonySteele/SevenDigital.Api.Wrapper,emashliles/SevenDigital.Api.Wrapper,bnathyuw/SevenDigital.Api.Wrapper,bettiolo/SevenDigital.Api.Wrapper,danhaller/SevenDigital.Api.Wrapper,gregsochanik/SevenDigital.Api.Wrapper,danbadge/SevenDigital.Api.Wrapper
src/SevenDigital.Api.Wrapper.Integration.Tests/AppSettingsCredentials.cs
src/SevenDigital.Api.Wrapper.Integration.Tests/AppSettingsCredentials.cs
using System.Configuration; namespace SevenDigital.Api.Wrapper.Integration.Tests { public class AppSettingsCredentials : IOAuthCredentials { public AppSettingsCredentials() { ConsumerKey = ValueFromEnvOrConfig("WRAPPER_INTEGRATION_TEST_CONSUMER_KEY", "Wrapper.ConsumerKey"); ConsumerSecret = ValueFromEnvOrConfig("WRAPPER_INTEGRATION_TEST_CONSUMER_SECRET", "Wrapper.ConsumerSecret"); } public string ConsumerKey { get; private set; } public string ConsumerSecret { get; private set; } private static string ValueFromEnvOrConfig(string envName, string configName) { return System.Environment.GetEnvironmentVariable(envName) ?? ConfigurationManager.AppSettings[configName]; } } }
using System.Configuration; namespace SevenDigital.Api.Wrapper.Integration.Tests { public class AppSettingsCredentials : IOAuthCredentials { public AppSettingsCredentials() { ConsumerKey = ValueFromEnvOrConfig("WRAPPER_INTEGRATION_TEST_CONSUMER_KEY", "Wrapper.ConsumerKey"); ConsumerSecret = ValueFromEnvOrConfig("WRAPPER_INTEGRATION_TEST_CONSUMER_SECRET", "Wrapper.ConsumerSecret"); } public string ConsumerKey { get; private set; } public string ConsumerSecret { get; private set; } private static string ValueFromEnvOrConfig(string envName, string configName) { //return System.Environment.GetEnvironmentVariable(envName) ?? ConfigurationManager.AppSettings[configName]; return ConfigurationManager.AppSettings[configName]; } } }
mit
C#
e53f897b9b59b5e05d08c071f8ab8ec18dd8330b
Make the CackeKeyPrefix protected instead of Public
shaynevanasperen/NHibernate.Sessions.Operations
NHibernate.Sessions.Operations/AbstractCachedDatabaseQuery.cs
NHibernate.Sessions.Operations/AbstractCachedDatabaseQuery.cs
using System; namespace NHibernate.Sessions.Operations { public abstract class AbstractCachedDatabaseQuery<T> : DatabaseOperation { protected abstract void ConfigureCache(CacheConfig cacheConfig); protected abstract T QueryDatabase(ISessionManager sessionManager); protected virtual string CacheKeyPrefix { get { return GetType().FullName; } } protected T GetDatabaseResult(ISessionManager sessionManager, IDatabaseQueryCache databaseQueryCache = null) { var cacheConfig = CacheConfig.None; ConfigureCache(cacheConfig); if (databaseQueryCache == null || cacheConfig.AbsoluteDuration == TimeSpan.Zero) return QueryDatabase(sessionManager); return databaseQueryCache.Get(() => QueryDatabase(sessionManager), cacheConfig.BuildCacheKey(CacheKeyPrefix), cacheConfig.AbsoluteDuration, cacheConfig.CacheNulls); } } }
using System; namespace NHibernate.Sessions.Operations { public abstract class AbstractCachedDatabaseQuery<T> : DatabaseOperation { protected abstract void ConfigureCache(CacheConfig cacheConfig); protected abstract T QueryDatabase(ISessionManager sessionManager); public virtual string CacheKeyPrefix { get { return GetType().FullName; } } protected T GetDatabaseResult(ISessionManager sessionManager, IDatabaseQueryCache databaseQueryCache = null) { var cacheConfig = CacheConfig.None; ConfigureCache(cacheConfig); if (databaseQueryCache == null || cacheConfig.AbsoluteDuration == TimeSpan.Zero) return QueryDatabase(sessionManager); return databaseQueryCache.Get(() => QueryDatabase(sessionManager), cacheConfig.BuildCacheKey(CacheKeyPrefix), cacheConfig.AbsoluteDuration, cacheConfig.CacheNulls); } } }
mit
C#
2b6c613bc4435061bc68355f2963be076cbe994c
Fix outdated code comment.
nbevans/EventStreams,nbevans/EventStreams
EventStreams.Core/Core/Domain/ConventionEventHandler.cs
EventStreams.Core/Core/Domain/ConventionEventHandler.cs
using System; namespace EventStreams.Core.Domain { public class ConventionEventHandler<TModel> : EventHandler<TModel> where TModel : class, new() { // Note: Because this is a generic type, each ConventionEventHandler per TModel type will have its own static state. // Therefore, the HandleMethodInvocationCache will be a different instance per TModel type. Handy. // Originally, the HandleMethodInvocationCache was based on an outer and inner cache. // But leaning on the CLR behaviour of static and generics in this way will yield better performance. private static readonly HandleMethodInvocationCache<TModel> _methodCache = new HandleMethodInvocationCache<TModel>(); public ConventionEventHandler(TModel owner) : base(owner, EventHandlerBehavior.Lossless) { } public ConventionEventHandler(TModel owner, EventHandlerBehavior behavior) : base(owner, behavior) { } public override void OnNext(EventArgs value) { base.OnNext(value); Action<TModel, EventArgs> method; if (_methodCache.TryGetMethod(value, out method)) method.Invoke(Owner, value); else HandleEventHandlerNotFound(value); } } }
using System; namespace EventStreams.Core.Domain { public class ConventionEventHandler<TModel> : EventHandler<TModel> where TModel : class, new() { // Note: Because this is a generic type, each ConventionEventHandler per TEventSourced type will have its own static state. // Therefore, the HandleMethodInvocationCache will be a different instance per TModel type. Handy. // Originally, the HandleMethodInvocationCache was based on an outer and inner cache. // But leaning on the CLR behaviour of static and generics in this way will yield better performance. private static readonly HandleMethodInvocationCache<TModel> _methodCache = new HandleMethodInvocationCache<TModel>(); public ConventionEventHandler(TModel owner) : base(owner, EventHandlerBehavior.Lossless) { } public ConventionEventHandler(TModel owner, EventHandlerBehavior behavior) : base(owner, behavior) { } public override void OnNext(EventArgs value) { base.OnNext(value); Action<TModel, EventArgs> method; if (_methodCache.TryGetMethod(value, out method)) method.Invoke(Owner, value); else HandleEventHandlerNotFound(value); } } }
mit
C#
04169bd8c3b38bd3f8a018c67fd231d5bb723de7
Rename fields, set background to white, add subviews rotation
nelzomal/monotouch-samples,nelzomal/monotouch-samples,haithemaraissia/monotouch-samples,hongnguyenpro/monotouch-samples,sakthivelnagarajan/monotouch-samples,andypaul/monotouch-samples,labdogg1003/monotouch-samples,a9upam/monotouch-samples,davidrynn/monotouch-samples,kingyond/monotouch-samples,haithemaraissia/monotouch-samples,peteryule/monotouch-samples,iFreedive/monotouch-samples,robinlaide/monotouch-samples,xamarin/monotouch-samples,nervevau2/monotouch-samples,hongnguyenpro/monotouch-samples,nelzomal/monotouch-samples,haithemaraissia/monotouch-samples,YOTOV-LIMITED/monotouch-samples,W3SS/monotouch-samples,hongnguyenpro/monotouch-samples,xamarin/monotouch-samples,albertoms/monotouch-samples,labdogg1003/monotouch-samples,sakthivelnagarajan/monotouch-samples,xamarin/monotouch-samples,nervevau2/monotouch-samples,sakthivelnagarajan/monotouch-samples,nervevau2/monotouch-samples,andypaul/monotouch-samples,a9upam/monotouch-samples,albertoms/monotouch-samples,markradacz/monotouch-samples,nelzomal/monotouch-samples,YOTOV-LIMITED/monotouch-samples,haithemaraissia/monotouch-samples,robinlaide/monotouch-samples,markradacz/monotouch-samples,YOTOV-LIMITED/monotouch-samples,davidrynn/monotouch-samples,hongnguyenpro/monotouch-samples,W3SS/monotouch-samples,labdogg1003/monotouch-samples,W3SS/monotouch-samples,peteryule/monotouch-samples,kingyond/monotouch-samples,labdogg1003/monotouch-samples,davidrynn/monotouch-samples,andypaul/monotouch-samples,albertoms/monotouch-samples,peteryule/monotouch-samples,robinlaide/monotouch-samples,YOTOV-LIMITED/monotouch-samples,iFreedive/monotouch-samples,nervevau2/monotouch-samples,iFreedive/monotouch-samples,a9upam/monotouch-samples,peteryule/monotouch-samples,markradacz/monotouch-samples,andypaul/monotouch-samples,a9upam/monotouch-samples,sakthivelnagarajan/monotouch-samples,davidrynn/monotouch-samples,kingyond/monotouch-samples,robinlaide/monotouch-samples
CoreAnimation/Screens/iPad/ViewTransitions/Controller.cs
CoreAnimation/Screens/iPad/ViewTransitions/Controller.cs
using System; using System.Drawing; using MonoTouch.CoreFoundation; using MonoTouch.UIKit; namespace Example_CoreAnimation.Screens.iPad.ViewTransitions { public class Controller : UIViewController, IDetailView { public event EventHandler ContentsButtonClicked; private TransitionViewController transitionViewController; private BackTransitionViewController backViewController; public override void ViewDidLoad () { base.ViewDidLoad (); View.BackgroundColor = UIColor.White; var mainFrame = new RectangleF (0f, 44f, View.Frame.Width, View.Frame.Height - 44f); transitionViewController = new TransitionViewController (); transitionViewController.View.Frame = mainFrame; backViewController = new BackTransitionViewController (); backViewController.View.Frame = mainFrame; View.AddSubview (transitionViewController.View); transitionViewController.TransitionClicked += (s, e) => { UIView.Animate (1, 0, transitionViewController.SelectedTransition, () => { transitionViewController.View.RemoveFromSuperview (); View.AddSubview (backViewController.View); }, null); UIView.BeginAnimations ("ViewChange"); }; transitionViewController.ContentsClicked += () => { if (ContentsButtonClicked != null) { ContentsButtonClicked (null, null); } }; backViewController.BackClicked += (s, e) => { UIView.Animate (.75, 0, transitionViewController.SelectedTransition, () => { backViewController.View.RemoveFromSuperview (); View.AddSubview (transitionViewController.View); }, null); }; } public override void WillRotate (UIInterfaceOrientation toInterfaceOrientation, double duration) { transitionViewController.WillRotate (toInterfaceOrientation, duration); backViewController.WillRotate (toInterfaceOrientation, duration); base.WillRotate (toInterfaceOrientation, duration); } } }
using System; using MonoTouch.CoreFoundation; using MonoTouch.UIKit; using System.Drawing; namespace Example_CoreAnimation.Screens.iPad.ViewTransitions { public class Controller : UIViewController, IDetailView { protected UIToolbar toolbar; protected TransitionViewController controller1; protected BackTransitionViewController controller2; public Controller () { } public override void ViewDidLoad () { base.ViewDidLoad (); toolbar = new UIToolbar (new RectangleF (0, 0, this.View.Frame.Width, 44)); this.View.Add (toolbar); RectangleF mainFrame = new RectangleF (0, toolbar.Frame.Height, this.View.Frame.Width, this.View.Frame.Height - toolbar.Frame.Height); controller1 = new TransitionViewController (); controller1.View.Frame = mainFrame; controller2 = new BackTransitionViewController (); controller2.View.Frame = mainFrame; View.AddSubview (controller1.View); // controller2.View.Hidden = true; controller1.TransitionClicked += (s, e) => { UIView.Animate (1, 0, controller1.SelectedTransition, () => { controller1.View.RemoveFromSuperview (); View.AddSubview (controller2.View); // controller1.View.Hidden = false; // controller2.View.Hidden = true; }, null); UIView.BeginAnimations("ViewChange"); // UIView.SetAnimationTransition(UIViewAnimationTransition.FlipFromLeft, this.View, true); // { // controller1.View.RemoveFromSuperview(); // this.View.AddSubview( controller2.View); // } // UIView.CommitAnimations(); }; controller2.BackClicked += (s, e) => { UIView.Animate(.75, 0, controller1.SelectedTransition, () => { controller2.View.RemoveFromSuperview (); View.AddSubview (controller1.View); }, null); }; } public void AddContentsButton (UIBarButtonItem button) { button.Title = "Contents"; toolbar.SetItems(new UIBarButtonItem[] { button }, false ); } public void RemoveContentsButton () { toolbar.SetItems(new UIBarButtonItem[0], false); } } }
mit
C#
79ac504e5cdab9fcb7e49f0321a9bacebbc47397
Revert "added email variable to model"
GridProtectionAlliance/openXDA,GridProtectionAlliance/openXDA,GridProtectionAlliance/openXDA,GridProtectionAlliance/openXDA
Source/Libraries/openXDA.Model/Links/UserAccountAssetGroup.cs
Source/Libraries/openXDA.Model/Links/UserAccountAssetGroup.cs
//****************************************************************************************************** // UserAccountAssetGroup.cs - Gbtc // // Copyright © 2017, Grid Protection Alliance. All Rights Reserved. // // Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See // the NOTICE file distributed with this work for additional information regarding copyright ownership. // The GPA licenses this file to you under the MIT License (MIT), the "License"; you may // not use this file except in compliance with the License. You may obtain a copy of the License at: // // http://opensource.org/licenses/MIT // // Unless agreed to in writing, the subject software distributed under the License is distributed on an // "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the // License for the specific language governing permissions and limitations. // // Code Modification History: // ---------------------------------------------------------------------------------------------------- // 08/29/2017 - Billy Ernest // Generated original version of source code. // //****************************************************************************************************** using System; using System.ComponentModel; using GSF.ComponentModel.DataAnnotations; using GSF.Data.Model; namespace openXDA.Model { public class UserAccountAssetGroup { [PrimaryKey(true)] public int ID { get; set; } public Guid UserAccountID { get; set; } public int AssetGroupID { get; set; } [DefaultValue(true)] public bool Dashboard { get; set; } } [PrimaryLabel("Username")] public class UserAccountAssetGroupView : UserAccountAssetGroup { [Searchable] public string Username { get; set; } [Searchable] public string GroupName { get; set; } } }
//****************************************************************************************************** // UserAccountAssetGroup.cs - Gbtc // // Copyright © 2017, Grid Protection Alliance. All Rights Reserved. // // Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See // the NOTICE file distributed with this work for additional information regarding copyright ownership. // The GPA licenses this file to you under the MIT License (MIT), the "License"; you may // not use this file except in compliance with the License. You may obtain a copy of the License at: // // http://opensource.org/licenses/MIT // // Unless agreed to in writing, the subject software distributed under the License is distributed on an // "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the // License for the specific language governing permissions and limitations. // // Code Modification History: // ---------------------------------------------------------------------------------------------------- // 08/29/2017 - Billy Ernest // Generated original version of source code. // //****************************************************************************************************** using System; using System.ComponentModel; using GSF.ComponentModel.DataAnnotations; using GSF.Data.Model; namespace openXDA.Model { public class UserAccountAssetGroup { [PrimaryKey(true)] public int ID { get; set; } public Guid UserAccountID { get; set; } public int AssetGroupID { get; set; } [DefaultValue(true)] public bool Dashboard { get; set; } [DefaultValue(false)] public bool Email { get; set; } } [PrimaryLabel("Username")] public class UserAccountAssetGroupView : UserAccountAssetGroup { [Searchable] public string Username { get; set; } [Searchable] public string GroupName { get; set; } } }
mit
C#
23b702ca948c92159c136b4717e9264c5ee8654a
Set version number to 0.9.3
cshung/clrmd,stjeong/clrmd,tomasr/clrmd,Microsoft/clrmd,JeffCyr/clrmd,cshung/clrmd,Microsoft/clrmd,jazzdelightsme/clrmd,stefangossner/clrmd
src/Microsoft.Diagnostics.Runtime/Properties/AssemblyInfo.cs
src/Microsoft.Diagnostics.Runtime/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("Microsoft.Diagnostics.Runtime")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Microsoft.Diagnostics.Runtime")] [assembly: AssemblyCopyright("Copyright \u00A9 Microsoft")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("94432a8e-3e06-4776-b9b2-3684a62bb96a")] [assembly: AssemblyVersion("0.9.3.0")] [assembly: AssemblyFileVersion("0.9.3.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("Microsoft.Diagnostics.Runtime")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Microsoft.Diagnostics.Runtime")] [assembly: AssemblyCopyright("Copyright \u00A9 Microsoft")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("94432a8e-3e06-4776-b9b2-3684a62bb96a")] [assembly: AssemblyVersion("0.9.2.1")] [assembly: AssemblyFileVersion("0.9.2.1")]
mit
C#
40bc07da5de6a4da12bff22e8a725b1a7b1d0a32
Fix merge conflict issue
ethanmoffat/EndlessClient
EOLib/Net/Translators/AccountLoginPacketTranslator.cs
EOLib/Net/Translators/AccountLoginPacketTranslator.cs
using System.Collections.Generic; using AutomaticTypeMapper; using EOLib.Domain.Character; using EOLib.Domain.Login; using EOLib.IO.Repositories; using EOLib.Domain.Protocol; namespace EOLib.Net.Translators { [AutoMappedType] public class AccountLoginPacketTranslator : CharacterDisplayPacketTranslator<IAccountLoginData> { public AccountLoginPacketTranslator(IEIFFileProvider eifFileProvider) : base(eifFileProvider) { } public override IAccountLoginData TranslatePacket(IPacket packet) { LoginReply reply; var characters = new List<ICharacter>(); if (packet.Family == PacketFamily.Login && packet.Action == PacketAction.Reply) { reply = (LoginReply)packet.ReadShort(); if (reply == LoginReply.Ok) characters.AddRange(GetCharacters(packet)); } else if (packet.Family == PacketFamily.Init && packet.Action == PacketAction.Init) { var initReply = (InitReply)packet.ReadByte(); var banType = (BanType)packet.ReadByte(); if (initReply != InitReply.BannedFromServer && banType != BanType.PermanentBan) reply = LoginReply.THIS_IS_WRONG; else reply = LoginReply.AccountBanned; } else { reply = LoginReply.THIS_IS_WRONG; } return new AccountLoginData(reply, characters); } } }
using System.Collections.Generic; using AutomaticTypeMapper; using EOLib.Domain.Character; using EOLib.Domain.Login; <<<<<<< HEAD using EOLib.IO.Repositories; ======= using EOLib.Domain.Protocol; >>>>>>> master namespace EOLib.Net.Translators { [AutoMappedType] public class AccountLoginPacketTranslator : CharacterDisplayPacketTranslator<IAccountLoginData> { public AccountLoginPacketTranslator(IEIFFileProvider eifFileProvider) : base(eifFileProvider) { } public override IAccountLoginData TranslatePacket(IPacket packet) { LoginReply reply; var characters = new List<ICharacter>(); if (packet.Family == PacketFamily.Login && packet.Action == PacketAction.Reply) { reply = (LoginReply)packet.ReadShort(); if (reply == LoginReply.Ok) characters.AddRange(GetCharacters(packet)); } else if (packet.Family == PacketFamily.Init && packet.Action == PacketAction.Init) { var initReply = (InitReply)packet.ReadByte(); var banType = (BanType)packet.ReadByte(); if (initReply != InitReply.BannedFromServer && banType != BanType.PermanentBan) reply = LoginReply.THIS_IS_WRONG; else reply = LoginReply.AccountBanned; } else { reply = LoginReply.THIS_IS_WRONG; } return new AccountLoginData(reply, characters); } } }
mit
C#
202af1325078bb6acf8e2c9de9921bff8922ed15
Add missing using
Gibe/Gibe.DittoProcessors
Gibe.DittoProcessors/Processors/BreadcrumbsAttribute.cs
Gibe.DittoProcessors/Processors/BreadcrumbsAttribute.cs
using System; using System.Collections.Generic; using System.Linq; using Gibe.DittoServices.ModelConverters; using Gibe.UmbracoWrappers; using Umbraco.Core.Models; using Umbraco.Web; namespace Gibe.DittoProcessors.Processors { public class BreadcrumbsAttribute : InjectableProcessorAttribute { public Func<IUmbracoWrapper> UmbracoWrapper { get; set; } = Inject<IUmbracoWrapper>(); public Func<IModelConverter> ModelConverter { get; set; } = Inject<IModelConverter>(); public override object ProcessValue() { var content = Context.Content; var breadcrumbs = CurrentPage(content) .Concat(AncestorsPages(content)) .Concat(HomePage()) .Reverse(); return breadcrumbs; } public IEnumerable<BreadcrumbItemModel> CurrentPage(IPublishedContent content) { var breadcrumbs = new List<BreadcrumbItemModel> { new BreadcrumbItemModel(content.Name, content.Url, true) }; return breadcrumbs; } public IEnumerable<BreadcrumbItemModel> AncestorsPages(IPublishedContent content) { foreach (var item in UmbracoWrapper() .Ancestors(content) .Where(i => i.IsVisible() && i.DocumentTypeAlias != "") .Select(i => ModelConverter().ToModel<BreadcrumbItem>(i))) { if (item.Level <= 1) break; yield return new BreadcrumbItemModel(item.Name, item.Url, false); } } public IEnumerable<BreadcrumbItemModel> HomePage() { yield return new BreadcrumbItemModel("Home", "/", false); } } public class BreadcrumbItem { public bool Visible { get; set; } public string DocumentTypeAlias { get; set; } public int Level { get; set; } public string Name { get; set; } public string Url { get; set; } } public class BreadcrumbItemModel { public BreadcrumbItemModel(string title, string url, bool isActive) { Title = title; Url = url; IsActive = isActive; } public string Title { get; } public string Url { get; } public bool IsActive { get; } } }
using System; using System.Collections.Generic; using System.Linq; using Gibe.DittoServices.ModelConverters; using Gibe.UmbracoWrappers; using Umbraco.Core.Models; namespace Gibe.DittoProcessors.Processors { public class BreadcrumbsAttribute : InjectableProcessorAttribute { public Func<IUmbracoWrapper> UmbracoWrapper { get; set; } = Inject<IUmbracoWrapper>(); public Func<IModelConverter> ModelConverter { get; set; } = Inject<IModelConverter>(); public override object ProcessValue() { var content = Context.Content; var breadcrumbs = CurrentPage(content) .Concat(AncestorsPages(content)) .Concat(HomePage()) .Reverse(); return breadcrumbs; } public IEnumerable<BreadcrumbItemModel> CurrentPage(IPublishedContent content) { var breadcrumbs = new List<BreadcrumbItemModel> { new BreadcrumbItemModel(content.Name, content.Url, true) }; return breadcrumbs; } public IEnumerable<BreadcrumbItemModel> AncestorsPages(IPublishedContent content) { foreach (var item in UmbracoWrapper().Ancestors(content).Where(i => i.IsVisible() && i.DocumentTypeAlias != "").Select(i => ModelConverter().ToModel<BreadcrumbItem>(i))) //foreach (var item in content.Ancestors().Where("Visible && DocumentTypeAlias !=\"\"")) { if (item.Level <= 1) break; yield return new BreadcrumbItemModel(item.Name, item.Url, false); } } public IEnumerable<BreadcrumbItemModel> HomePage() { yield return new BreadcrumbItemModel("Home", "/", false); } } public class BreadcrumbItem { public bool Visible { get; set; } public string DocumentTypeAlias { get; set; } public int Level { get; set; } public string Name { get; set; } public string Url { get; set; } } public class BreadcrumbItemModel { public BreadcrumbItemModel(string title, string url, bool isActive) { Title = title; Url = url; IsActive = isActive; } public string Title { get; } public string Url { get; } public bool IsActive { get; } } }
mit
C#
3f03eab8f10da86c36aa48dcf8e064743f459f73
Fix return value in Subroutines.NoParamsOutput test
TheBerkin/Rant
Rant.Tests/Subroutines.cs
Rant.Tests/Subroutines.cs
using NUnit.Framework; namespace Rant.Tests { [TestFixture] public class Subroutines { [Test] public void NoParamsOutput() { Assert.AreEqual("1 2 3 4 5 6 7 8 9 10", new RantEngine().Do(@"[$[test]:[r:10][s:\s]{[rn]}][$test]").MainValue); } [Test] [ExpectedException(typeof(RantRuntimeException))] public void OutOfScope() { new RantEngine().Do(@"{[$[test]:\16,c]}[$test]"); } [Test] public void InnerScope() { new RantEngine().Do(@"[$[test]:\16,c]{[$test]}"); } [Test] [ExpectedException(typeof(RantRuntimeException))] public void MissingSubroutine() { new RantEngine().Do(@"[$missing]"); } } }
using NUnit.Framework; namespace Rant.Tests { [TestFixture] public class Subroutines { [Test] public void NoParamsOutput() { Assert.AreEqual("1 2 3 4 5 6 7 8 9 10", new RantEngine().Do(@"[$[test]:[r:10][s:\s]{[rn]}][$test]")); } [Test] [ExpectedException(typeof(RantRuntimeException))] public void OutOfScope() { new RantEngine().Do(@"{[$[test]:\16,c]}[$test]"); } [Test] public void InnerScope() { new RantEngine().Do(@"[$[test]:\16,c]{[$test]}"); } [Test] [ExpectedException(typeof(RantRuntimeException))] public void MissingSubroutine() { new RantEngine().Do(@"[$missing]"); } } }
mit
C#
dfa9432f2178622e8160aa853e27c1addce2a1a4
Remove unused code
MelHarbour/HeadRaceTiming-Site,MelHarbour/HeadRaceTiming-Site,MelHarbour/HeadRaceTiming-Site
HeadRaceTiming-Site/Controllers/CompetitionController.cs
HeadRaceTiming-Site/Controllers/CompetitionController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using HeadRaceTimingSite.Models; using Microsoft.EntityFrameworkCore; using System.Globalization; using HeadRaceTimingSite.Helpers; using AutoMapper; using HeadRaceTimingSite.ViewModels; namespace HeadRaceTimingSite.Controllers { public class CompetitionController : BaseController { private readonly IMapper _mapper; public CompetitionController(IMapper mapper, TimingSiteContext context) : base(context) { _mapper = mapper; } public async Task<IActionResult> Index() { return View(await _context.Competitions.Where(x => x.IsVisible).ToListAsync()); } public async Task<IActionResult> Details(string id) { int competitionId; Competition competition; if (Int32.TryParse(id, out competitionId)) { competition = await _context.Competitions.Include(x => x.TimingPoints).Include(x => x.Awards) .SingleOrDefaultAsync(c => c.CompetitionId == competitionId); } else { competition = await _context.Competitions.Include(x => x.TimingPoints).Include(x => x.Awards) .SingleOrDefaultAsync(c => c.FriendlyName == id); } CompetitionDetailsViewModel viewModel = _mapper.Map<CompetitionDetailsViewModel>(competition); viewModel.AwardFilterName = "Overall"; return View(viewModel); } [HttpGet] [Produces("text/csv")] public async Task<IActionResult> DetailsAsCsv(int? id) { IEnumerable<Crew> crews = await _context.Crews.Where(c => c.CompetitionId == id) .Include(x => x.Competition.TimingPoints).Include(x => x.Results) .Include("Athletes.Athlete") .Include(x => x.Penalties).ToListAsync(); return Ok(ResultsHelper.BuildCrewsList(_mapper, crews)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using HeadRaceTimingSite.Models; using Microsoft.EntityFrameworkCore; using System.Globalization; using HeadRaceTimingSite.Helpers; using AutoMapper; using HeadRaceTimingSite.ViewModels; namespace HeadRaceTimingSite.Controllers { public class CompetitionController : BaseController { private readonly IMapper _mapper; public CompetitionController(IMapper mapper, TimingSiteContext context) : base(context) { _mapper = mapper; } public async Task<IActionResult> Index() { return View(await _context.Competitions.Where(x => x.IsVisible).ToListAsync()); } public async Task<IActionResult> Details(string id) { int competitionId; Competition competition; if (Int32.TryParse(id, out competitionId)) { competition = await _context.Competitions.Include(x => x.TimingPoints).Include(x => x.Awards) .SingleOrDefaultAsync(c => c.CompetitionId == competitionId); } else { competition = await _context.Competitions.Include(x => x.TimingPoints).Include(x => x.Awards) .SingleOrDefaultAsync(c => c.FriendlyName == id); } CompetitionDetailsViewModel viewModel = _mapper.Map<CompetitionDetailsViewModel>(competition); viewModel.AwardFilterName = "Overall"; return View(viewModel); } [HttpGet] [Produces("text/csv")] public async Task<IActionResult> DetailsAsCsv(int? id) { IEnumerable<Crew> crews = await _context.Crews.Where(c => c.CompetitionId == id) .Include(x => x.Competition.TimingPoints).Include(x => x.Results) .Include("Athletes.Athlete") .Include(x => x.Penalties).ToListAsync(); return Ok(ResultsHelper.BuildCrewsList(_mapper, crews)); } public IActionResult Error() { return View(); } } }
mit
C#
75d094359ae272c538b44bedcafb962d58db3953
Fix WinBehavior bug.
john29917958/Korat-Framework
Korat-Framework/Behaviors/Os/Windows/WindowsBehaviors.cs
Korat-Framework/Behaviors/Os/Windows/WindowsBehaviors.cs
using System.Collections.Generic; using System.Windows.Forms; using Ncu.Oolab.Korat.Library; namespace KoratFramework.Behaviors.Os.Windows { public class WindowsBehaviors : OsBehaviors { public override string Version => "7"; public WindowsBehaviors(Korat korat) : base(korat) { } public override void OpenApp(string appName) { Korat.SendCompositeKeys(new HashSet<Keys> { Keys.Control, Keys.R }); Korat.SendString(appName); Korat.SendKey(Keys.Enter); } public override void OpenTerminal() { OpenApp("cmd.exe"); } public override string Copy() { Korat.SendCompositeKeys(new HashSet<Keys> { Keys.Control, Keys.C }); return Clipboard.GetText(); } } }
using System.Collections.Generic; using System.Windows.Forms; using Ncu.Oolab.Korat.Library; namespace KoratFramework.Behaviors.Os.Windows { public class WindowsBehaviors : OsBehaviors { public override string Version => "7"; public WindowsBehaviors(Korat korat) : base(korat) { } public override void OpenApp(string appName) { Korat.SendCompositeKeys(new HashSet<Keys> { Keys.Control, Keys.R }); Korat.SendString(appName); } public override void OpenTerminal() { OpenApp("cmd.exe"); } public override string Copy() { Korat.SendCompositeKeys(new HashSet<Keys> { Keys.Control, Keys.C }); return Clipboard.GetText(); } } }
mit
C#
faec10d1322ecbf0253af20621ecb3a406882fc8
Comment failing assertion
browserstack/browserstack-local-csharp
BrowserStackLocal/BrowserStackLocalIntegrationTests/IntegrationTests.cs
BrowserStackLocal/BrowserStackLocalIntegrationTests/IntegrationTests.cs
using NUnit.Framework; using System; using System.Diagnostics; using System.Collections.Generic; using OpenQA.Selenium; using OpenQA.Selenium.Remote; using OpenQA.Selenium.Edge; using BrowserStack; namespace BrowserStackLocalIntegrationTests { public class IntegrationTests { private static string username = Environment.GetEnvironmentVariable("BROWSERSTACK_USERNAME"); private static string accesskey = Environment.GetEnvironmentVariable("BROWSERSTACK_ACCESS_KEY"); private List<KeyValuePair<string, string>> options = new List<KeyValuePair<string, string>>() { new KeyValuePair<string, string>("key", accesskey), new KeyValuePair<string, string>("verbose", "true"), new KeyValuePair<string, string>("forcelocal", "true"), new KeyValuePair<string, string>("binarypath", "C:\\Users\\Admin\\Desktop\\BrowserStackLocal.exe"), new KeyValuePair<string, string>("logfile", "C:\\Users\\Admin\\Desktop\\local.log"), }; [Test] public void TestStartsAndStopsLocalSession() { Local local = new Local(); void startWithOptions() { local.start(options); } Assert.DoesNotThrow(new TestDelegate(startWithOptions)); Process[] binaryInstances = Process.GetProcessesByName("BrowserStackLocal"); Assert.AreNotEqual(binaryInstances.Length, 0); IWebDriver driver; EdgeOptions capability = new EdgeOptions(); capability.AddAdditionalCapability("browserstack.user", username); capability.AddAdditionalCapability("browserstack.key", accesskey); capability.AddAdditionalCapability("browserstack.local", true); capability.AddAdditionalCapability("build", "C Sharp binding Integration Test"); driver = new RemoteWebDriver( new Uri("http://hub.browserstack.com/wd/hub/"), capability ); driver.Navigate().GoToUrl("http://bs-local.com:45691/check"); String status = driver.FindElement(By.TagName("body")).Text; Assert.AreEqual(status, "Up and running"); driver.Quit(); local.stop(); binaryInstances = Process.GetProcessesByName("BrowserStackLocal"); Assert.AreEqual(binaryInstances.Length, 0); } [Test] public void TestBinaryState() { Local local = new Local(); Assert.AreEqual(local.isRunning(), false); local.start(options); // TODO: Fix bug with method `isRunning` and make assertion pass // Assert.AreEqual(local.isRunning(), true); local.stop(); Assert.AreEqual(local.isRunning(), false); } [TearDown] public void TestCleanup() { foreach(Process p in Process.GetProcessesByName("BrowserStackLocal")) { p.Kill(); } } } }
using NUnit.Framework; using System; using System.Diagnostics; using System.Collections.Generic; using OpenQA.Selenium; using OpenQA.Selenium.Remote; using OpenQA.Selenium.Edge; using BrowserStack; namespace BrowserStackLocalIntegrationTests { public class IntegrationTests { private static string username = Environment.GetEnvironmentVariable("BROWSERSTACK_USERNAME"); private static string accesskey = Environment.GetEnvironmentVariable("BROWSERSTACK_ACCESS_KEY"); private List<KeyValuePair<string, string>> options = new List<KeyValuePair<string, string>>() { new KeyValuePair<string, string>("key", accesskey), new KeyValuePair<string, string>("verbose", "true"), new KeyValuePair<string, string>("forcelocal", "true"), new KeyValuePair<string, string>("binarypath", "C:\\Users\\Admin\\Desktop\\BrowserStackLocal.exe"), new KeyValuePair<string, string>("logfile", "C:\\Users\\Admin\\Desktop\\local.log"), }; [Test] public void TestStartsAndStopsLocalSession() { Local local = new Local(); void startWithOptions() { local.start(options); } Assert.DoesNotThrow(new TestDelegate(startWithOptions)); Process[] binaryInstances = Process.GetProcessesByName("BrowserStackLocal"); Assert.AreNotEqual(binaryInstances.Length, 0); IWebDriver driver; EdgeOptions capability = new EdgeOptions(); capability.AddAdditionalCapability("browserstack.user", username); capability.AddAdditionalCapability("browserstack.key", accesskey); capability.AddAdditionalCapability("browserstack.local", true); capability.AddAdditionalCapability("build", "C Sharp binding Integration Test"); driver = new RemoteWebDriver( new Uri("http://hub.browserstack.com/wd/hub/"), capability ); driver.Navigate().GoToUrl("http://bs-local.com:45691/check"); String status = driver.FindElement(By.TagName("body")).Text; Assert.AreEqual(status, "Up and running"); driver.Quit(); local.stop(); binaryInstances = Process.GetProcessesByName("BrowserStackLocal"); Assert.AreEqual(binaryInstances.Length, 0); } [Test] public void TestBinaryState() { Local local = new Local(); Assert.AreEqual(local.isRunning(), false); local.start(options); Assert.AreEqual(local.isRunning(), true); local.stop(); Assert.AreEqual(local.isRunning(), false); } [TearDown] public void TestCleanup() { foreach(Process p in Process.GetProcessesByName("BrowserStackLocal")) { p.Kill(); } } } }
mit
C#
1e81b211c8020d722c48cf2f95635b30e17f81ed
Add person support
aloisdg/edx-csharp
edX/Module3/Program.cs
edX/Module3/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace Module3 { public class Program { public static void Main() { try { HandlePeople(); // ToDo // course //string courseName = null; } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { Console.WriteLine("We are going to exit the program."); Console.WriteLine("See you next time."); Console.ReadLine(); } } private static void HandlePeople() { const string studentStatus = "student"; const string teacherStatus = "teacher"; HandlePerson(studentStatus); HandlePerson(teacherStatus); } private static void HandlePerson(string status) { string firstName = null; string lastName = null; ushort? age = null; SetPersonDetails(status, ref firstName, ref lastName, ref age); PrintPersonDetails(status, firstName, lastName, age); Console.WriteLine(); } private static void PrintPersonDetails(string status, string firstName, string lastName, ushort? age) { Console.WriteLine("{1}'s detail{0}" + "{1}'s first name :\t{2}{0}" + "{1}'s last name :\t{3}{0}" + "{1}'s age :\t\t{4}", Environment.NewLine, status, firstName, lastName, age); } private static void SetPersonDetails(string status, ref string firstName, ref string lastName, ref ushort? age) { const string output = "the {0}'s {1} "; const ushort ageMax = 200; ushort num; firstName = HandleInputOutput(String.Format(output, status, "first name")); lastName = HandleInputOutput(String.Format(output, status, "last name")); if (!UInt16.TryParse(HandleInputOutput(String.Format(output, status, "age")).Trim(), out num) || num > ageMax) throw new Exception("Age invalid!"); age = num; } private static string HandleInputOutput(string output) { Console.WriteLine("Enter {0}: ", output); return ReadInput(); } private static string ReadInput() { string input; if (IsNotNullNorWhiteSpace(Console.ReadLine(), out input)) return input; throw new Exception("Input is null, empty or consists exclusively of white-space characters."); } public static bool IsNotNullNorWhiteSpace(string value, out string result) { result = String.Empty; if (String.IsNullOrWhiteSpace(value)) return false; result = value; return true; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Module3 { class Program { static void Main(string[] args) { } } }
mit
C#
ce0de92e27e789b984ca2c4349b6c93ce4fab715
change genetic restriction
plantain-00/csharp-demo,plantain-00/csharp-demo,plantain-00/csharp-demo
Ridge/Ridge/Nodes/Node.cs
Ridge/Ridge/Nodes/Node.cs
using System; using System.Collections.Generic; using System.Linq; namespace Ridge.Nodes { public abstract class Node { public List<Node> Children { get; set; } internal int Depth { get; set; } public Node this[int index] { get { return Children[index]; } } public Node this[string tagName, int index] { get { var nodes = Children.Where(c => c is Tag && (c as Tag).Name.Equals(tagName, StringComparison.CurrentCultureIgnoreCase)); return nodes.ElementAt(index); } } public Node this[string tagName] { get { return this[tagName, 0]; } } public T As<T>() where T : Node { return this as T; } internal virtual Node GetElementById(string id) { if (Children == null) { return null; } foreach (var child in Children) { var node = child.GetElementById(id); if (node != null) { return node; } } return null; } public abstract string ToString(Formatting formatting, int spaceNumber = 4); } }
using System; using System.Collections.Generic; using System.Linq; namespace Ridge.Nodes { public abstract class Node { public List<Node> Children { get; set; } internal int Depth { get; set; } public Node this[int index] { get { return Children[index]; } } public Node this[string tagName, int index] { get { var nodes = Children.Where(c => c is Tag && (c as Tag).Name.Equals(tagName, StringComparison.CurrentCultureIgnoreCase)); return nodes.ElementAt(index); } } public Node this[string tagName] { get { return this[tagName, 0]; } } public T As<T>() where T : class { return this as T; } internal virtual Node GetElementById(string id) { if (Children == null) { return null; } foreach (var child in Children) { var node = child.GetElementById(id); if (node != null) { return node; } } return null; } public abstract string ToString(Formatting formatting, int spaceNumber = 4); } }
mit
C#
1051e29cb7fd5023cbb0e0121536908d2e96e91b
Fix incorrect namespace. (#1433)
dg2k/Template10,teamneusta/Template10,MichaelPetrinolis/Template10,callummoffat/Template10,Windows-XAML/Template10,liptonbeer/Template10,teamneusta/Template10,MichaelPetrinolis/Template10,liptonbeer/Template10,mvermef/Template10,callummoffat/Template10
Template10.Core/Template10.Core.Behaviors/Behaviors/ChangeCursorAction.cs
Template10.Core/Template10.Core.Behaviors/Behaviors/ChangeCursorAction.cs
using Microsoft.Xaml.Interactivity; using Windows.UI.Core; using Windows.UI.Xaml; namespace Template10.Behaviors { public class CursorBehavior : DependencyObject, IAction { public CoreCursorType Cursor { get; set; } = CoreCursorType.Arrow; public object Execute(object sender, object parameter) { Window.Current.CoreWindow.PointerCursor = new CoreCursor(Cursor, 0); return null; } } }
using Microsoft.Xaml.Interactivity; using Windows.UI.Core; using Windows.UI.Xaml; namespace Template10.Behaviors.Behaviors { public class CursorBehavior : DependencyObject, IAction { public CoreCursorType Cursor { get; set; } = CoreCursorType.Arrow; public object Execute(object sender, object parameter) { Window.Current.CoreWindow.PointerCursor = new CoreCursor(Cursor, 0); return null; } } }
apache-2.0
C#
be8166348ff1e090929956899cb172e285f465dc
Add [Serializable] attribute
dnm240/NSubstitute,dnm240/NSubstitute,dnm240/NSubstitute,dnm240/NSubstitute,dnm240/NSubstitute
Source/NSubstitute/Exceptions/CouldNotRaiseEventException.cs
Source/NSubstitute/Exceptions/CouldNotRaiseEventException.cs
using System.Runtime.Serialization; namespace NSubstitute.Exceptions { [Serializable] public class CouldNotRaiseEventException : SubstituteException { protected const string WhatProbablyWentWrong = "Make sure you are using Raise.Event() as part of an event subscription on a substitute.\n" + "For example:\n" + "\tmySub.Clicked += Raise.Event();\n" + "\n" + "If you substituted for a class rather than an interface, check that the event on your substitute is virtual/abstract.\n" + "Events on classes cannot be raised if they are not declared virtual or abstract.\n" + "\n" + "Note that the source of the problem may be prior to where this exception was thrown (possibly in a previous test!).\n" + "For example:\n" + "\tvar notASub = new Button();\n" + "\tnotASub.Clicked += Raise.Event(); // <-- Problem here. This is not a substitute.\n" + "\tvar sub = Substitute.For<IController>();\n" + "\tsub.Load(); // <-- Exception thrown here. NSubstitute thinks the earlier Raise.Event() was meant for this call."; public CouldNotRaiseEventException() : base(WhatProbablyWentWrong) { } protected CouldNotRaiseEventException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
using System.Runtime.Serialization; namespace NSubstitute.Exceptions { public class CouldNotRaiseEventException : SubstituteException { protected const string WhatProbablyWentWrong = "Make sure you are using Raise.Event() as part of an event subscription on a substitute.\n" + "For example:\n" + "\tmySub.Clicked += Raise.Event();\n" + "\n" + "If you substituted for a class rather than an interface, check that the event on your substitute is virtual/abstract.\n" + "Events on classes cannot be raised if they are not declared virtual or abstract.\n" + "\n" + "Note that the source of the problem may be prior to where this exception was thrown (possibly in a previous test!).\n" + "For example:\n" + "\tvar notASub = new Button();\n" + "\tnotASub.Clicked += Raise.Event(); // <-- Problem here. This is not a substitute.\n" + "\tvar sub = Substitute.For<IController>();\n" + "\tsub.Load(); // <-- Exception thrown here. NSubstitute thinks the earlier Raise.Event() was meant for this call."; public CouldNotRaiseEventException() : base(WhatProbablyWentWrong) { } protected CouldNotRaiseEventException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
bsd-3-clause
C#
b964908442c1395e4b33fcba65445ccbab9f7476
Rename variable
weltkante/roslyn,swaroop-sridhar/roslyn,tmat/roslyn,aelij/roslyn,eriawan/roslyn,swaroop-sridhar/roslyn,KevinRansom/roslyn,wvdd007/roslyn,sharwell/roslyn,jasonmalinowski/roslyn,agocke/roslyn,mavasani/roslyn,stephentoub/roslyn,davkean/roslyn,eriawan/roslyn,mgoertz-msft/roslyn,nguerrera/roslyn,AlekseyTs/roslyn,wvdd007/roslyn,jmarolf/roslyn,MichalStrehovsky/roslyn,heejaechang/roslyn,brettfo/roslyn,MichalStrehovsky/roslyn,KirillOsenkov/roslyn,KevinRansom/roslyn,nguerrera/roslyn,ErikSchierboom/roslyn,diryboy/roslyn,aelij/roslyn,shyamnamboodiripad/roslyn,stephentoub/roslyn,gafter/roslyn,panopticoncentral/roslyn,agocke/roslyn,tannergooding/roslyn,bartdesmet/roslyn,heejaechang/roslyn,dotnet/roslyn,mavasani/roslyn,mgoertz-msft/roslyn,KevinRansom/roslyn,jasonmalinowski/roslyn,tannergooding/roslyn,tmat/roslyn,bartdesmet/roslyn,sharwell/roslyn,physhi/roslyn,gafter/roslyn,diryboy/roslyn,physhi/roslyn,diryboy/roslyn,ErikSchierboom/roslyn,dotnet/roslyn,reaction1989/roslyn,AlekseyTs/roslyn,reaction1989/roslyn,brettfo/roslyn,weltkante/roslyn,davkean/roslyn,genlu/roslyn,dotnet/roslyn,aelij/roslyn,tannergooding/roslyn,weltkante/roslyn,abock/roslyn,nguerrera/roslyn,wvdd007/roslyn,MichalStrehovsky/roslyn,eriawan/roslyn,CyrusNajmabadi/roslyn,abock/roslyn,heejaechang/roslyn,KirillOsenkov/roslyn,shyamnamboodiripad/roslyn,sharwell/roslyn,davkean/roslyn,brettfo/roslyn,tmat/roslyn,CyrusNajmabadi/roslyn,genlu/roslyn,agocke/roslyn,mgoertz-msft/roslyn,gafter/roslyn,KirillOsenkov/roslyn,swaroop-sridhar/roslyn,abock/roslyn,jmarolf/roslyn,reaction1989/roslyn,AmadeusW/roslyn,genlu/roslyn,CyrusNajmabadi/roslyn,mavasani/roslyn,physhi/roslyn,ErikSchierboom/roslyn,AmadeusW/roslyn,bartdesmet/roslyn,panopticoncentral/roslyn,shyamnamboodiripad/roslyn,AmadeusW/roslyn,panopticoncentral/roslyn,jmarolf/roslyn,stephentoub/roslyn,AlekseyTs/roslyn,jasonmalinowski/roslyn
src/Features/CSharp/Portable/Completion/KeywordRecommenders/AssemblyKeywordRecommender.cs
src/Features/CSharp/Portable/Completion/KeywordRecommenders/AssemblyKeywordRecommender.cs
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class AssemblyKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public AssemblyKeywordRecommender() : base(SyntaxKind.AssemblyKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { var token = context.TargetToken; if (token.Kind() != SyntaxKind.OpenBracketToken) { return false; } if (token.Parent.Kind() == SyntaxKind.AttributeList) { var attributeList = token.Parent; var compilationUnitSyntax = attributeList.Parent; return compilationUnitSyntax is CompilationUnitSyntax || compilationUnitSyntax.Parent is CompilationUnitSyntax; } var skippedTokensTriviaSyntax = token.Parent; return skippedTokensTriviaSyntax is SkippedTokensTriviaSyntax; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class AssemblyKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public AssemblyKeywordRecommender() : base(SyntaxKind.AssemblyKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { var token = context.TargetToken; if (token.Kind() != SyntaxKind.OpenBracketToken) { return false; } if (token.Parent.Kind() == SyntaxKind.AttributeList) { var attributeList = token.Parent; var previousSyntax = attributeList.Parent; return previousSyntax is CompilationUnitSyntax || previousSyntax.Parent is CompilationUnitSyntax; } var parentSyntax = token.Parent; return parentSyntax is SkippedTokensTriviaSyntax; } } }
mit
C#
4f809767a5f9cf762244843021a6f33ac99c94af
Disable button while update check is in progress
peppy/osu-new,ppy/osu,smoogipoo/osu,peppy/osu,ppy/osu,ppy/osu,NeoAdonis/osu,peppy/osu,NeoAdonis/osu,NeoAdonis/osu,smoogipoo/osu,peppy/osu,UselessToucan/osu,smoogipoo/osu,smoogipooo/osu,UselessToucan/osu,UselessToucan/osu
osu.Game/Overlays/Settings/Sections/General/UpdateSettings.cs
osu.Game/Overlays/Settings/Sections/General/UpdateSettings.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Threading.Tasks; using osu.Framework; using osu.Framework.Allocation; using osu.Framework.Platform; using osu.Framework.Screens; using osu.Game.Configuration; using osu.Game.Overlays.Settings.Sections.Maintenance; using osu.Game.Updater; namespace osu.Game.Overlays.Settings.Sections.General { public class UpdateSettings : SettingsSubsection { [Resolved(CanBeNull = true)] private UpdateManager updateManager { get; set; } protected override string Header => "Updates"; private SettingsButton checkForUpdatesButton; [BackgroundDependencyLoader(true)] private void load(Storage storage, OsuConfigManager config, OsuGame game) { Add(new SettingsEnumDropdown<ReleaseStream> { LabelText = "Release stream", Bindable = config.GetBindable<ReleaseStream>(OsuSetting.ReleaseStream), }); // We should only display the button for UpdateManagers that do check for updates Add(checkForUpdatesButton = new SettingsButton { Text = "Check for updates", Action = () => { checkForUpdatesButton.Enabled.Value = false; Task.Run(updateManager.CheckForUpdateAsync).ContinueWith(t => Schedule(() => checkForUpdatesButton.Enabled.Value = true)); } }); if (RuntimeInfo.IsDesktop) { Add(new SettingsButton { Text = "Open osu! folder", Action = storage.OpenInNativeExplorer, }); Add(new SettingsButton { Text = "Change folder location...", Action = () => game?.PerformFromScreen(menu => menu.Push(new MigrationSelectScreen())) }); } } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Threading.Tasks; using osu.Framework; using osu.Framework.Allocation; using osu.Framework.Platform; using osu.Framework.Screens; using osu.Game.Configuration; using osu.Game.Overlays.Settings.Sections.Maintenance; using osu.Game.Updater; namespace osu.Game.Overlays.Settings.Sections.General { public class UpdateSettings : SettingsSubsection { [Resolved(CanBeNull = true)] private UpdateManager updateManager { get; set; } protected override string Header => "Updates"; [BackgroundDependencyLoader(true)] private void load(Storage storage, OsuConfigManager config, OsuGame game) { Add(new SettingsEnumDropdown<ReleaseStream> { LabelText = "Release stream", Bindable = config.GetBindable<ReleaseStream>(OsuSetting.ReleaseStream), }); // We should only display the button for UpdateManagers that do check for updates Add(new SettingsButton { Text = "Check for updates", Action = () => Schedule(() => Task.Run(updateManager.CheckForUpdateAsync)), Enabled = { Value = updateManager.CanCheckForUpdate } }); if (RuntimeInfo.IsDesktop) { Add(new SettingsButton { Text = "Open osu! folder", Action = storage.OpenInNativeExplorer, }); Add(new SettingsButton { Text = "Change folder location...", Action = () => game?.PerformFromScreen(menu => menu.Push(new MigrationSelectScreen())) }); } } } }
mit
C#
39dac5b49f6ce5a2c96a2b17c7dea081017aa8f6
Add xml documentation to InvalidConfigurationException.
RockFramework/Rock.Core,peteraritchie/Rock.Core,bfriesen/Rock.Core
Rock.Core/Configuration/InvalidConfigurationException.cs
Rock.Core/Configuration/InvalidConfigurationException.cs
using System; using System.Configuration; using System.Runtime.Serialization; using System.Xml; namespace Rock.Configuration { /// <summary> /// The exception that is thrown when an invalid configuration is encountered. /// </summary> [Serializable] public class InvalidConfigurationException : ConfigurationException { /// <summary> /// Initializes a new instance of the <see cref="InvalidConfigurationException"/> class. /// </summary> /// <param name="message">A message describing why this <see cref="InvalidConfigurationException"/> exception was thrown.</param> /// <param name="node">The <see cref="T:System.Xml.XmlNode"/> that caused this <see cref="InvalidConfigurationException"/> to be thrown.</param> public InvalidConfigurationException(string message, XmlNode node) : base(message, node) { } /// <summary> /// Initializes a new instance of the <see cref="InvalidConfigurationException"/> class. /// </summary> /// <param name="info">The object that holds the information to deserialize.</param> /// <param name="context">Contextual information about the source or destination.</param> protected InvalidConfigurationException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
using System; using System.Configuration; using System.Runtime.Serialization; using System.Xml; namespace Rock.Configuration { [Serializable] public class InvalidConfigurationException : ConfigurationException { public InvalidConfigurationException(string message, XmlNode node) : base(message, node) { } protected InvalidConfigurationException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
mit
C#
0e53cc5e03b3b538191228c856025949b0a7a484
Change namespace
dhawalharsora/connectedcare-sdk,SnapMD/connectedcare-sdk
SnapMD.ConnectedCare.ApiModels/ResponseObservableItem.cs
SnapMD.ConnectedCare.ApiModels/ResponseObservableItem.cs
#region Copyright // Copyright 2015 SnapMD, Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion namespace SnapMD.ConnectedCare.ApiModels { /// <summary> /// Simple object for IDs and text. /// </summary> public class ResponseObservableItem { public int Id { get; set; } public string Description { get; set; } public string ShortName { get; set; } } }
#region Copyright // Copyright 2015 SnapMD, Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion namespace SnapMD.ConnectedCare.Sdk.Models { /// <summary> /// Simple object for IDs and text. /// </summary> public class ResponseObservableItem { public int Id { get; set; } public string Description { get; set; } public string ShortName { get; set; } } }
apache-2.0
C#
90eedcf5f41c65dc9f79b8003f9c25a92de4f966
Add methods for adding/removing vertices.
DasAllFolks/SharpGraphs
Graph/IGraph.cs
Graph/IGraph.cs
using System; namespace Graph { /// <summary> /// Represents a labeled graph. /// </summary> /// <typeparam name="V">The vertex type.</typeparam> /// <typeparam name="E">The edge type.</typeparam> public interface IGraph<V, E> : IEquatable<IGraph<V, E>> where E: IEdge<V> { /// <summary> /// Attempts to add a vertex to the graph. /// </summary> /// <param name="vertex">The vertex.</param> /// <returns> /// True if the vertex was successfully added, false if it already /// existed. /// </returns> bool TryAddVertex(V vertex); /// <summary> /// Attempts to remove a vertex from the graph. /// </summary> /// <param name="vertex">The vertex.</param> /// <returns> /// True if the vertex was successfully removed, false if no such /// vertex was found in the graph. /// </returns> bool TryRemoveVertex(V vertex); /// <summary> /// Attempts to add an edge to the graph. /// </summary> /// <param name="edge"> /// The edge. /// </param> /// <param name="allowNewVertices"> /// Iff true, add vertices in the edge which aren't yet in the graph /// to the graph's vertex set. /// </param> /// <returns> /// True if the edge was successfully added (the definition of /// "success" may vary from implementation to implementation). /// </returns> /// <exception cref="InvalidOperationException"> /// Thrown if the edge contains at least one edge not in the graph, /// and allowNewVertices is set to false. /// </exception> bool TryAddEdge(E edge, bool allowNewVertices = false); /// <summary> /// Attempts to remove an edge from the graph. /// </summary> /// <param name="edge">The edge.</param> /// <returns> /// True if the edge was successfully removed, false otherwise. /// </returns> bool TryRemoveEdge(E edge); } }
using System; using System.Collections.Generic; namespace Graph { /// <summary> /// Represents a graph. /// </summary> /// <typeparam name="V">The vertex type.</typeparam> /// <typeparam name="E">The edge type.</typeparam> public interface IGraph<V, E> : IEquatable<IGraph<V, E>> where E: IEdge<V> { /// <summary> /// Attempts to add an edge to the graph. /// </summary> /// <param name="edge"> /// The edge. /// </param> /// <param name="allowNewVertices"> /// Iff true, add vertices in the edge which aren't yet in the graph /// to the graph's vertex set. /// </param> /// <returns> /// True if the edge was successfully added (the definition of /// "success" may vary from implementation to implementation). /// </returns> /// <exception cref="InvalidOperationException"> /// Thrown if the edge contains at least one edge not in the graph, /// and allowNewVertices is set to false. /// </exception> bool TryAddEdge(E edge, bool allowNewVertices = false); /// <summary> /// Attempts to remove an edge from the graph. /// </summary> /// <param name="edge">The edge.</param> /// <returns> /// True if the edge was successfully removed, false otherwise. /// </returns> bool TryRemoveEdge(E edge); } }
apache-2.0
C#
55ab8d0de3373062da8092e8270171d6cd52d8d7
add Timer in PomodoroService
zindlsn/RosaroterTiger
RosaroterPanterWPF/RosaroterPanterWPF/PomodoroService.cs
RosaroterPanterWPF/RosaroterPanterWPF/PomodoroService.cs
using System; using System.Collections.Generic; using System.Text; using System.Timers; namespace RosaroterPanterWPF { public class PomodoroService { private Timer _Timer = new Timer(); //private EventArgs public int Seconds { get; set; } private int _CurrentSeconds { get; set; } public PomodoroService() { } public void SetTimerPerRound(int seconds) { this.Seconds = seconds; this._CurrentSeconds = seconds; } public void StartTask(Task task) { _Timer.Interval = 1000; _Timer.Elapsed += Timer_Elapsed; } private void Timer_Elapsed(object sender, ElapsedEventArgs e) { if (this._CurrentSeconds > 0) { this._CurrentSeconds--; } else { this._CurrentSeconds = this.Seconds; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Timers; namespace RosaroterPanterWPF { public class PomodoroService { private Timer Timer; public PomodoroService() { } public void StartTask(DataService.Task task) { } } }
mit
C#
f08cfcba1410c56aecdae697e140d1de5fa6141e
refactor delegates
louthy/language-ext,StanJav/language-ext,StefanBertels/language-ext
Samples/Contoso/Contoso.Web/Extensions/HostExtensions.cs
Samples/Contoso/Contoso.Web/Extensions/HostExtensions.cs
using System; using Contoso.Infrastructure.Data; using LanguageExt; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using static LanguageExt.Prelude; namespace Contoso.Web.Extensions { public static class HostExtensions { public static IHost SeedDatabase(this IHost host) { var test = use(() => host.Services.CreateScope(), Seed); return host; } static Func<IServiceScope, Unit> Seed = (scope) => { var services = scope.ServiceProvider; Try(GetDbContext(services)).Bind(ctx => Try(InitializeDb(ctx))) .Match( Succ: a => { }, Fail: ex => LogException(ex, services)); return Unit.Default; }; static Func<IServiceProvider, ContosoDbContext> GetDbContext = (provider) => provider.GetRequiredService<ContosoDbContext>(); static Func<ContosoDbContext, Unit> InitializeDb = (context) => DbInitializer.Initialize(context); private static void LogException(Exception ex, IServiceProvider provider) => provider.GetRequiredService<ILogger<Program>>() .LogError(ex, "Error occurred while seeding database"); } }
using System; using Contoso.Infrastructure.Data; using LanguageExt; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using static LanguageExt.Prelude; namespace Contoso.Web.Extensions { public static class HostExtensions { public static IHost SeedDatabase(this IHost host) { use(host.Services.CreateScope(), Seed); return host; } static readonly Func<IServiceScope, Unit> Seed = (scope) => { var services = scope.ServiceProvider; TryGetDbContext(services).Bind(ctx => TryInitializeDb(ctx)) .Match( Succ: a => { }, Fail: ex => LogException(ex, services)); return Unit.Default; }; private static Try<ContosoDbContext> TryGetDbContext(IServiceProvider provider) => () => provider.GetRequiredService<ContosoDbContext>(); private static Try<Unit> TryInitializeDb(ContosoDbContext context) => () => DbInitializer.Initialize(context); private static void LogException(Exception ex, IServiceProvider provider) => provider.GetRequiredService<ILogger<Program>>() .LogError(ex, "Error occurred while seeding database"); } }
mit
C#
79726ff857e9b1f9092e934f80f5a4496859cb61
Fix CS
Lc5/CurrencyRates,Lc5/CurrencyRates,Lc5/CurrencyRates
CurrencyRates.NbpCurrencyRates/Service/FileFetcher.cs
CurrencyRates.NbpCurrencyRates/Service/FileFetcher.cs
namespace CurrencyRates.NbpCurrencyRates.Service { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using CurrencyRates.NbpCurrencyRates.Net; using CurrencyRates.NbpCurrencyRates.Service.Entity; public class FileFetcher : IFileFetcher { private const string FileListPath = "dir.txt"; private const string Url = "http://www.nbp.pl/kursy/xml/"; private readonly IWebClient webClient; public FileFetcher(IWebClient webClient) { this.webClient = webClient; } public IEnumerable<File> FetchAllFilesExcept(IEnumerable<string> existingFilenames) { var filenames = this.FetchFilenames().Except(existingFilenames); var files = new Collection<File>(); foreach (var filename in filenames) { files.Add(this.FetchFile(filename)); } return files; } private File FetchFile(string filename) { var content = this.webClient.DownloadString(Url + filename); return new File { Name = filename, Content = content }; } private IEnumerable<string> FetchFilenames() { var filenames = this.webClient .DownloadString(Url + FileListPath) .Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries) .Where(s => s.StartsWith("a") || s.StartsWith("b")) .Select(f => f + ".xml"); return filenames; } } }
namespace CurrencyRates.NbpCurrencyRates.Service { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using CurrencyRates.NbpCurrencyRates.Net; using CurrencyRates.NbpCurrencyRates.Service.Entity; public class FileFetcher : IFileFetcher { private const string FileListPath = "dir.txt"; private const string Url = "http://www.nbp.pl/kursy/xml/"; private readonly IWebClient webClient; public FileFetcher(IWebClient webClient) { this.webClient = webClient; } public IEnumerable<File> FetchAllFilesExcept(IEnumerable<string> existingFilenames) { var filenames = this.FetchFilenames().Except(existingFilenames); var files = new Collection<File>(); foreach (var filename in filenames) { files.Add(this.FetchFile(filename)); } return files; } private File FetchFile(string filename) { var content = this.webClient.DownloadString(Url + filename); return new File { Name = filename, Content = content }; } private IEnumerable<string> FetchFilenames() { var filenames = this.webClient.DownloadString(Url + FileListPath) .Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries) .Where(s => s.StartsWith("a") || s.StartsWith("b")) .Select(f => f + ".xml"); return filenames; } } }
mit
C#
7e370a83f13c01359fac9a88c2f84c5b68d77e01
fix lint.
GoogleCloudPlatform/dotnet-docs-samples,GoogleCloudPlatform/dotnet-docs-samples,GoogleCloudPlatform/dotnet-docs-samples,GoogleCloudPlatform/dotnet-docs-samples
asset/quickstart/ExportAssetsTest/ExportAssetsTest.cs
asset/quickstart/ExportAssetsTest/ExportAssetsTest.cs
/* * Copyright (c) 2018 Google LLC. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * 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 Google.Apis.Storage.v1.Data; using Google.Cloud.Storage.V1; using System; using Xunit; using Xunit.Abstractions; namespace GoogleCloudSamples { public class ExportAssetsTest : IClassFixture<RandomBucketFixture>, System.IDisposable { static readonly CommandLineRunner s_runner = new CommandLineRunner { Command = "ExportAssets", VoidMain = ExportAssets.Main, }; private readonly ITestOutputHelper _testOutput; private readonly StorageClient _storageClient = StorageClient.Create(); private readonly string _bucketName; readonly BucketCollector _bucketCollector; public ExportAssetsTest(ITestOutputHelper output, RandomBucketFixture bucketFixture) { _testOutput = output; _bucketName = bucketFixture.BucketName; _bucketCollector = new BucketCollector(_bucketName); } [Fact] public void TestExportAsests() { string projectId = Environment.GetEnvironmentVariable("GOOGLE_PROJECT_ID"); Environment.SetEnvironmentVariable("AssetBucketName", _bucketName); var output = s_runner.Run(); _testOutput.WriteLine(output.Stdout); string expectedOutput = String.Format("\"outputConfig\": {{ \"gcsDestination\": {{ \"uri\": \"gs://{0}/my-assets.txt\" }} }}", _bucketName); Assert.Contains(expectedOutput, output.Stdout); } public void Dispose() { ((IDisposable)_bucketCollector).Dispose(); } } }
/* * Copyright (c) 2018 Google LLC. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * 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 Google.Apis.Storage.v1.Data; using Google.Cloud.Storage.V1; using System; using Xunit; using Xunit.Abstractions; namespace GoogleCloudSamples { public class ExportAssetsTest : IClassFixture<RandomBucketFixture>, System.IDisposable { static readonly CommandLineRunner s_runner = new CommandLineRunner { Command = "ExportAssets", VoidMain = ExportAssets.Main, }; private readonly ITestOutputHelper _testOutput; private readonly StorageClient _storageClient = StorageClient.Create(); private readonly string _bucketName; readonly BucketCollector _bucketCollector; public ExportAssetsTest(ITestOutputHelper output, RandomBucketFixture bucketFixture) { _testOutput = output; _bucketName = bucketFixture.BucketName; _bucketCollector = new BucketCollector(_bucketName); } [Fact] public void TestExportAsests() { string projectId = Environment.GetEnvironmentVariable("GOOGLE_PROJECT_ID"); Environment.SetEnvironmentVariable("AssetBucketName", _bucketName); var output = s_runner.Run(); _testOutput.WriteLine(output.Stdout); string expectedOutput = String.Format("\"outputConfig\": {{ \"gcsDestination\": {{ \"uri\": \"gs://{0}/my-assets.txt\" }} }}", _bucketName); Assert.Contains(expectedOutput, output.Stdout); } public void Dispose() { ((IDisposable)_bucketCollector).Dispose(); } } }
apache-2.0
C#
a5611da9485b474c4ea5552b34fe26bc86e7423c
Create generic invoke method for RPC
faint32/snowflake-1,RonnChyran/snowflake,RonnChyran/snowflake,faint32/snowflake-1,SnowflakePowered/snowflake,SnowflakePowered/snowflake,RonnChyran/snowflake,faint32/snowflake-1,SnowflakePowered/snowflake
Snowflake.API/Core/EventDelegate/JsonRPCEventDelegate.cs
Snowflake.API/Core/EventDelegate/JsonRPCEventDelegate.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Collections.Specialized; using Newtonsoft.Json; using System.IO; namespace Snowflake.Core.EventDelegate { public class JsonRPCEventDelegate { private string RPCUrl; public JsonRPCEventDelegate(int port) { this.RPCUrl = "http://localhost:" + port.ToString() + @"/"; } public WebResponse InvokeMethod(string method, string methodParams, string id) { WebRequest request = WebRequest.Create(this.RPCUrl); request.ContentType = "application/json-rpc"; request.Method = "POST"; var values = new Dictionary<string, dynamic>(){ {"method", method}, {"params", methodParams}, {"id", id} }; var data = JsonConvert.SerializeObject(values); byte[] byteArray = Encoding.UTF8.GetBytes(data); request.ContentLength = byteArray.Length; Stream dataStream = request.GetRequestStream(); dataStream.Write(byteArray, 0, byteArray.Length); dataStream.Flush(); dataStream.Close(); return request.GetResponse(); } public void Notify(string eventName, dynamic eventData) { var response = this.InvokeMethod( "notify", JsonConvert.SerializeObject( new Dictionary<string, dynamic>(){ {"eventData", eventData}, {"eventName", eventName} }), "null" ); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Collections.Specialized; using Newtonsoft.Json; using System.IO; namespace Snowflake.Core.EventDelegate { public class JsonRPCEventDelegate { private string RPCUrl; public JsonRPCEventDelegate(int port) { this.RPCUrl = "http://localhost:" + port.ToString() + @"/"; } public void Notify(string eventName, dynamic eventData) { WebRequest request = WebRequest.Create (this.RPCUrl); request.ContentType = "application/json-rpc"; request.Method = "POST"; var values = new Dictionary<string, dynamic>(){ {"method", "notify"}, {"params", JsonConvert.SerializeObject(eventData)}, {"id", "null"} }; var data = JsonConvert.SerializeObject(values); byte[] byteArray = Encoding.UTF8.GetBytes(data); request.ContentLength = byteArray.Length; Stream dataStream = request.GetRequestStream(); dataStream.Write(byteArray, 0, byteArray.Length); dataStream.Flush(); dataStream.Close(); WebResponse response = request.GetResponse(); } } }
mpl-2.0
C#
d14711290d7a6f32dc40332b888502717bacda40
Fix uri mapper return invalid uri
jonstodle/Postolego
Postolego/PostolegoMapper.cs
Postolego/PostolegoMapper.cs
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using System.Windows.Navigation; namespace Postolego { public class PostolegoMapper : UriMapperBase { public override Uri MapUri(Uri uri) { var tempUri = HttpUtility.UrlDecode(uri.ToString()); if(tempUri.Contains("postolego:")) { if(tempUri.Contains("authorize")) { return new Uri("/Pages/SignInPage.xaml", UriKind.Relative); } } if((App.Current.Resources["PostolegoData"] as PostolegoData).PocketSession == null || !(App.Current.Resources["PostolegoData"] as PostolegoData).PocketSession.IsAuthenticated) { return new Uri("/Pages/SignInPage.xaml", UriKind.Relative); } else { return uri; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using System.Windows.Navigation; namespace Postolego { public class PostolegoMapper : UriMapperBase { public override Uri MapUri(Uri uri) { var tempUri = HttpUtility.UrlDecode(uri.ToString()); if(tempUri.Contains("postolego:")) { if(tempUri.Contains("authorize")) { return new Uri("/Pages/SignInPage.xaml", UriKind.Relative); } else { return uri; } } else { if((App.Current.Resources["PostolegoData"] as PostolegoData).PocketSession == null || !(App.Current.Resources["PostolegoData"] as PostolegoData).PocketSession.IsAuthenticated) { return new Uri("/Pages/SignInPage.xaml", UriKind.Relative); } else { return uri; } } } } }
mit
C#
1aa4c425f50cf2cad90bffc048e5576e6d707c81
Fix output encoding
dsuess/vernacular,StephaneDelcroix/vernacular,benoitjadinon/vernacular,benoitjadinon/vernacular,gabornemeth/vernacular,gabornemeth/vernacular,StephaneDelcroix/vernacular,mightea/vernacular,rdio/vernacular,mightea/vernacular,dsuess/vernacular,rdio/vernacular
Vernacular.Tool/Vernacular.Generators/StreamGenerator.cs
Vernacular.Tool/Vernacular.Generators/StreamGenerator.cs
// // ResxGenerator.cs // // Author: // Aaron Bockover <abock@rd.io> // // Copyright 2012 Rdio, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace Vernacular.Generators { public abstract class StreamGenerator : Generator { protected TextWriter Writer { get; private set; } protected virtual Encoding Encoding { get { return Encoding.UTF8; } } public override void Generate (string path) { if (String.IsNullOrEmpty (path) || path == "-") { Writer = Console.Out; } else { Writer = new GeneratorWriter (File.Create (path), Encoding); } try { Generate (); } finally { Writer.Close (); Writer = null; } } protected sealed class GeneratorWriter : StreamWriter { public GeneratorWriter (Stream stream, Encoding encoding) : base (stream, encoding) { NewLine = "\n"; } } } }
// // ResxGenerator.cs // // Author: // Aaron Bockover <abock@rd.io> // // Copyright 2012 Rdio, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace Vernacular.Generators { public abstract class StreamGenerator : Generator { protected TextWriter Writer { get; private set; } protected virtual Encoding Encoding { get { return Encoding.UTF8; } } public override void Generate (string path) { if (String.IsNullOrEmpty (path) || path == "-") { Writer = Console.Out; } else { Writer = new GeneratorWriter (File.Create (path), Encoding); } try { Generate (); } finally { Writer.Close (); Writer = null; } } protected sealed class GeneratorWriter : StreamWriter { private Encoding encoding; public override Encoding Encoding { get { return encoding; } } public GeneratorWriter (Stream stream, Encoding encoding) : base (stream) { this.encoding = encoding; NewLine = "\n"; } } } }
mit
C#
b3136d592cd5b107e9fc479b0e0a5b1df2a24f7d
fix Message definition
acple/ParsecSharp
ParsecSharp/Core/Result/Implementations/Failure.ParseError.cs
ParsecSharp/Core/Result/Implementations/Failure.ParseError.cs
namespace ParsecSharp.Internal.Results { internal sealed class ParseError<TToken, TState, T> : Failure<TToken, T> where TState : IParsecState<TToken, TState> { private readonly TState _state; public sealed override IParsecState<TToken> State => this._state.GetState(); public sealed override string Message => $"Unexpected '{this._state.ToString()}'"; public ParseError(TState state) { this._state = state; } public sealed override SuspendedResult<TToken, T> Suspend() => SuspendedResult<TToken, T>.Create(this, this._state); public sealed override Failure<TToken, TNext> Convert<TNext>() => new ParseError<TToken, TState, TNext>(this._state); } }
namespace ParsecSharp.Internal.Results { internal sealed class ParseError<TToken, TState, T> : Failure<TToken, T> where TState : IParsecState<TToken, TState> { private readonly TState _state; public sealed override IParsecState<TToken> State => this._state.GetState(); public sealed override string Message => $"Unexpected '{this.State.ToString()}'"; public ParseError(TState state) { this._state = state; } public sealed override SuspendedResult<TToken, T> Suspend() => SuspendedResult<TToken, T>.Create(this, this._state); public sealed override Failure<TToken, TNext> Convert<TNext>() => new ParseError<TToken, TState, TNext>(this._state); } }
mit
C#
197f22f3597b077b4f92379691c6fdf1aaddd852
Bump version.
FacilityApi/Facility
SolutionInfo.cs
SolutionInfo.cs
using System.Reflection; [assembly: AssemblyVersion("0.4.1.0")] [assembly: AssemblyCompany("")] [assembly: AssemblyCopyright("Copyright 2016-2017 Ed Ball")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")]
using System.Reflection; [assembly: AssemblyVersion("0.4.0.0")] [assembly: AssemblyCompany("")] [assembly: AssemblyCopyright("Copyright 2016-2017 Ed Ball")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")]
mit
C#
b5bbafe2569e7893f4a6d477f69130b97e29bbde
bump ver
AntonyCorbett/OnlyT,AntonyCorbett/OnlyT
SolutionInfo.cs
SolutionInfo.cs
using System.Reflection; [assembly: AssemblyCompany("SoundBox")] [assembly: AssemblyProduct("OnlyT")] [assembly: AssemblyCopyright("Copyright © 2019 Antony Corbett")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("1.2.0.14")]
using System.Reflection; [assembly: AssemblyCompany("SoundBox")] [assembly: AssemblyProduct("OnlyT")] [assembly: AssemblyCopyright("Copyright © 2019 Antony Corbett")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("1.2.0.13")]
mit
C#
5ecca629fe56c4ad9321f2967527f4ca0e229979
Fix issue #185. Add NeutralResourcesLanguage assembly attribute required by Win8 Metro certification
sharpdx/Toolkit,tomba/Toolkit,sharpdx/Toolkit
Source/SharedAssemblyInfo.cs
Source/SharedAssemblyInfo.cs
// Copyright (c) 2010-2012 SharpDX - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly:AssemblyCompany("Alexandre Mutel")] [assembly:AssemblyCopyright("Copyright © 2010-2011 Alexandre Mutel")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly:AssemblyVersion("2.1.0")] [assembly:AssemblyFileVersion("2.1.0")] [assembly: NeutralResourcesLanguage("en")] #if DEBUG [assembly:AssemblyConfiguration("Debug")] #else [assembly:AssemblyConfiguration("Release")] #endif [assembly:ComVisible(false)]
// Copyright (c) 2010-2012 SharpDX - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System.Reflection; using System.Runtime.InteropServices; [assembly:AssemblyCompany("Alexandre Mutel")] [assembly:AssemblyCopyright("Copyright © 2010-2011 Alexandre Mutel")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly:AssemblyVersion("2.1.0")] [assembly:AssemblyFileVersion("2.1.0")] #if DEBUG [assembly:AssemblyConfiguration("Debug")] #else [assembly:AssemblyConfiguration("Release")] #endif [assembly:ComVisible(false)]
mit
C#
5ca176753544778f16530e642c7988ca6e51f477
Update AssemblyInfo.cs
kevinledinh/azure-iot-sdks,dominicbetts/azure-iot-sdks,kevinledinh/azure-iot-sdks,oriolpinol/azure-iot-sdks,emirotin/resin-azure-iot-sample,andrew-buckley/azure-iot-sdks,Eclo/azure-iot-sdks,emirotin/resin-azure-iot-sample,dominicbetts/azure-iot-sdks,avranju/azure-iot-sdks,Eclo/azure-iot-sdks,Eclo/azure-iot-sdks,emirotin/resin-azure-iot-sample,oriolpinol/azure-iot-sdks,damonbarry/azure-iot-sdks-1,emirotin/resin-azure-iot-sample,andrew-buckley/azure-iot-sdks,damonbarry/azure-iot-sdks-1,andrew-buckley/azure-iot-sdks,damonbarry/azure-iot-sdks-1,oriolpinol/azure-iot-sdks,Eclo/azure-iot-sdks,avranju/azure-iot-sdks,kevinledinh/azure-iot-sdks,kevinledinh/azure-iot-sdks,andrew-buckley/azure-iot-sdks,dominicbetts/azure-iot-sdks,Eclo/azure-iot-sdks,oriolpinol/azure-iot-sdks,dominicbetts/azure-iot-sdks,Eclo/azure-iot-sdks,avranju/azure-iot-sdks,damonbarry/azure-iot-sdks-1,oriolpinol/azure-iot-sdks,avranju/azure-iot-sdks,damonbarry/azure-iot-sdks-1,damonbarry/azure-iot-sdks-1,andrew-buckley/azure-iot-sdks,kevinledinh/azure-iot-sdks,avranju/azure-iot-sdks,emirotin/resin-azure-iot-sample,dominicbetts/azure-iot-sdks,emirotin/resin-azure-iot-sample,dominicbetts/azure-iot-sdks,damonbarry/azure-iot-sdks-1,oriolpinol/azure-iot-sdks,Eclo/azure-iot-sdks,andrew-buckley/azure-iot-sdks,oriolpinol/azure-iot-sdks,damonbarry/azure-iot-sdks-1,kevinledinh/azure-iot-sdks,dominicbetts/azure-iot-sdks,andrew-buckley/azure-iot-sdks,Eclo/azure-iot-sdks,Eclo/azure-iot-sdks,oriolpinol/azure-iot-sdks,dominicbetts/azure-iot-sdks,kevinledinh/azure-iot-sdks,avranju/azure-iot-sdks,kevinledinh/azure-iot-sdks,emirotin/resin-azure-iot-sample,kevinledinh/azure-iot-sdks,avranju/azure-iot-sdks
csharp/device/Microsoft.Azure.Devices.Client.NetMF/HttpClient_43/Properties/AssemblyInfo.cs
csharp/device/Microsoft.Azure.Devices.Client.NetMF/HttpClient_43/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Microsoft.Azure.Devices.Client.Http.NetMF_43")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Microsoft.Azure.Devices.Client.Http.NetMF_43")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Microsoft.Azure.Devices.Client.Http.NetMF_44")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Microsoft.Azure.Devices.Client.Http.NetMF_44")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#
6a5482403a7025925a73cc434784c560c02577aa
Remove missing namespaces from ContentManagerController
Endlessages/EndlessAges.LauncherService
src/EndlessAges.LauncherService/Controllers/ContentManagerController.cs
src/EndlessAges.LauncherService/Controllers/ContentManagerController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; namespace EndlessAges.LauncherService.Controllers { /// <summary> /// Emulated controller ContentManager.aspx from the Endless Ages backend. /// </summary> [Route("ContentManager.aspx")] public class ContentManagerController : Controller { //ContentManager.aspx?installer_patcher=ENDLESS [HttpGet] public IActionResult GetPatchingInfo([FromQuery]string installer_patcher) { //If no valid parameter was provided in the query then return an error code //This should only happen if someone is spoofing //422 (Unprocessable Entity) if (string.IsNullOrWhiteSpace(installer_patcher)) return StatusCode(422); //TODO: What exactly should the backend return? EACentral returns a broken url return Content($"{@"http://game1.endlessagesonline./ENDLESSINSTALL.cab"}\n{@"ENDLESSINSTALL.cab"}"); } //ContentManager.aspx?gameapp=1 [HttpGet] public IActionResult GetGameApplicationUrl([FromQuery]int gameapp) { //If no valid parameter was provided in the query then return an error code //This should only happen if someone is spoofing //422 (Unprocessable Entity) if (gameapp < 0) return StatusCode(422); //TODO: Server is down at the moment can't check the returned content return Content($"GameApp: {gameapp.ToString()}"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading.Tasks; using System.Web.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.WebApiCompatShim; namespace EndlessAges.LauncherService.Controllers { /// <summary> /// Emulated controller ContentManager.aspx from the Endless Ages backend. /// </summary> [Route("ContentManager.aspx")] public class ContentManagerController : Controller { //ContentManager.aspx?installer_patcher=ENDLESS [HttpGet] public IActionResult GetPatchingInfo([FromQuery]string installer_patcher) { //If no valid parameter was provided in the query then return an error code //This should only happen if someone is spoofing //422 (Unprocessable Entity) if (string.IsNullOrWhiteSpace(installer_patcher)) return StatusCode(422); //TODO: What exactly should the backend return? EACentral returns a broken url return Content($"{@"http://game1.endlessagesonline./ENDLESSINSTALL.cab"}\n{@"ENDLESSINSTALL.cab"}"); } //ContentManager.aspx?gameapp=1 [HttpGet] public IActionResult GetGameApplicationUrl([FromQuery]int gameapp) { //If no valid parameter was provided in the query then return an error code //This should only happen if someone is spoofing //422 (Unprocessable Entity) if (gameapp < 0) return StatusCode(422); //TODO: Server is down at the moment can't check the returned content return Content($"GameApp: {gameapp.ToString()}"); } } }
mit
C#
93ba19f30e2935c74ef32d7c4d4267c68fa93a7a
Update Global.asax.cs
pedroreys/docs.particular.net,WojcikMike/docs.particular.net,eclaus/docs.particular.net,yuxuac/docs.particular.net
samples/web/asp-mvc-injecting-bus/Version_5/WebApplication/Global.asax.cs
samples/web/asp-mvc-injecting-bus/Version_5/WebApplication/Global.asax.cs
using System.Web; using System.Web.Mvc; using System.Web.Routing; using Autofac; using Autofac.Integration.Mvc; using NServiceBus; namespace WebApplication { public class MvcApplication : HttpApplication { ISendOnlyBus bus; protected void Application_Start() { #region ApplicationStart ContainerBuilder builder = new ContainerBuilder(); // Register your MVC controllers. builder.RegisterControllers(typeof(MvcApplication).Assembly); // Set the dependency resolver to be Autofac. IContainer container = builder.Build(); BusConfiguration busConfiguration = new BusConfiguration(); busConfiguration.EndpointName("Samples.MvcInjection.WebApplication"); // ExistingLifetimeScope() ensures that IBus is added to the container as well, // allowing you to resolve IBus from your own components. busConfiguration.UseContainer<AutofacBuilder>(c => c.ExistingLifetimeScope(container)); busConfiguration.UseSerialization<JsonSerializer>(); busConfiguration.UsePersistence<InMemoryPersistence>(); busConfiguration.EnableInstallers(); bus = Bus.CreateSendOnly(busConfiguration); DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); AreaRegistration.RegisterAllAreas(); RouteConfig.RegisterRoutes(RouteTable.Routes); #endregion } public override void Dispose() { if (bus != null) { bus.Dispose(); } base.Dispose(); } } }
using System.Web; using System.Web.Mvc; using System.Web.Routing; using Autofac; using Autofac.Integration.Mvc; using NServiceBus; namespace WebApplication { public class MvcApplication : HttpApplication { ISendOnlyBus bus; protected void Application_Start() { #region ApplicationStart ContainerBuilder builder = new ContainerBuilder(); // Register your MVC controllers. builder.RegisterControllers(typeof(MvcApplication).Assembly); // Set the dependency resolver to be Autofac. IContainer container = builder.Build(); BusConfiguration busConfiguration = new BusConfiguration(); busConfiguration.EndpointName("Samples.MvcInjection.WebApplication"); // ExistingLifetimeScope() ensures that IBus is added to the container as well, // allowing you to resolve IBus from your MVC controllers. busConfiguration.UseContainer<AutofacBuilder>(c => c.ExistingLifetimeScope(container)); busConfiguration.UseSerialization<JsonSerializer>(); busConfiguration.UsePersistence<InMemoryPersistence>(); busConfiguration.EnableInstallers(); bus = Bus.CreateSendOnly(busConfiguration); DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); AreaRegistration.RegisterAllAreas(); RouteConfig.RegisterRoutes(RouteTable.Routes); #endregion } public override void Dispose() { if (bus != null) { bus.Dispose(); } base.Dispose(); } } }
apache-2.0
C#
e5b7cdc33b2c14580009022c2bd564e52f5a4676
use WithUnitOfWork extension method in NotificationSubscriptionSynchronizer
luchaoshuai/aspnetboilerplate,ryancyq/aspnetboilerplate,ryancyq/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,luchaoshuai/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,ryancyq/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,ryancyq/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate
src/Abp.Zero.Common/Notifications/NotificationSubscriptionSynchronizer.cs
src/Abp.Zero.Common/Notifications/NotificationSubscriptionSynchronizer.cs
using System; using Abp.Authorization.Users; using Abp.Dependency; using Abp.Domain.Repositories; using Abp.Domain.Uow; using Abp.Events.Bus.Entities; using Abp.Events.Bus.Handlers; namespace Abp.Notifications { public class NotificationSubscriptionSynchronizer : IEventHandler<EntityDeletedEventData<AbpUserBase>>, ITransientDependency { private readonly IRepository<NotificationSubscriptionInfo, Guid> _notificationSubscriptionRepository; private readonly IUnitOfWorkManager _unitOfWorkManager; public NotificationSubscriptionSynchronizer( IRepository<NotificationSubscriptionInfo, Guid> notificationSubscriptionRepository, IUnitOfWorkManager unitOfWorkManager ) { _notificationSubscriptionRepository = notificationSubscriptionRepository; _unitOfWorkManager = unitOfWorkManager; } public virtual void HandleEvent(EntityDeletedEventData<AbpUserBase> eventData) { _unitOfWorkManager.WithUnitOfWork(() => { using (_unitOfWorkManager.Current.SetTenantId(eventData.Entity.TenantId)) { _notificationSubscriptionRepository.Delete(x => x.UserId == eventData.Entity.Id); } }); } } }
using System; using Abp.Authorization.Users; using Abp.Dependency; using Abp.Domain.Repositories; using Abp.Domain.Uow; using Abp.Events.Bus.Entities; using Abp.Events.Bus.Handlers; namespace Abp.Notifications { public class NotificationSubscriptionSynchronizer : IEventHandler<EntityDeletedEventData<AbpUserBase>>, ITransientDependency { private readonly IRepository<NotificationSubscriptionInfo, Guid> _notificationSubscriptionRepository; private readonly IUnitOfWorkManager _unitOfWorkManager; public NotificationSubscriptionSynchronizer( IRepository<NotificationSubscriptionInfo, Guid> notificationSubscriptionRepository, IUnitOfWorkManager unitOfWorkManager ) { _notificationSubscriptionRepository = notificationSubscriptionRepository; _unitOfWorkManager = unitOfWorkManager; } public virtual void HandleEvent(EntityDeletedEventData<AbpUserBase> eventData) { using (var uow = _unitOfWorkManager.Begin()) { using (_unitOfWorkManager.Current.SetTenantId(eventData.Entity.TenantId)) { _notificationSubscriptionRepository.Delete(x => x.UserId == eventData.Entity.Id); } uow.Complete(); } } } }
mit
C#
451a6055313bda54702d65cd530c680d528378b9
Add Inherited in IInterceptor
AspectCore/Abstractions,AspectCore/AspectCore-Framework,AspectCore/AspectCore-Framework,AspectCore/Lite
src/Abstractions/src/AspectCore.Abstractions/Interceptors/IInterceptor.cs
src/Abstractions/src/AspectCore.Abstractions/Interceptors/IInterceptor.cs
using System.Threading.Tasks; namespace AspectCore.Abstractions { [NonAspect] public interface IInterceptor { bool AllowMultiple { get; } bool Inherited { get; set; } int Order { get; set; } Task Invoke(AspectContext context, AspectDelegate next); } }
using System.Threading.Tasks; namespace AspectCore.Abstractions { [NonAspect] public interface IInterceptor { bool AllowMultiple { get; } int Order { get; set; } Task Invoke(AspectContext context, AspectDelegate next); } }
mit
C#
8d817c2c0fdc112d004ed196c748922c6d37fe32
Add AttributeUsage.Class to QualifierAttribute
yonglehou/spring-net,zi1jing/spring-net,yonglehou/spring-net,yonglehou/spring-net,spring-projects/spring-net,likesea/spring-net,zi1jing/spring-net,djechelon/spring-net,kvr000/spring-net,likesea/spring-net,likesea/spring-net,spring-projects/spring-net,dreamofei/spring-net,djechelon/spring-net,spring-projects/spring-net,dreamofei/spring-net,kvr000/spring-net,kvr000/spring-net
src/Spring/Spring.Core/Objects/Factory/Attributes/QualifierAttribute.cs
src/Spring/Spring.Core/Objects/Factory/Attributes/QualifierAttribute.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Spring.Objects.Factory.Attributes { /// <summary> /// This annotation may be used on a field or parameter as a qualifier for /// candidate beans when autowiring. It may also be used to annotate other /// custom annotations that can then in turn be used as qualifiers. /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter)] public class QualifierAttribute : Attribute { private readonly string _value; /// <summary> /// Instantiate a new qualifier with an empty name /// </summary> public QualifierAttribute() { _value = ""; } /// <summary> /// Instantiate a new qualifier with a givin name /// </summary> /// <param name="value">name to use as qualifier</param> public QualifierAttribute(string value) { _value = value; } /// <summary> /// Gets the name associated with this qualifier /// </summary> public string Value { get { return _value; } } /// <summary> /// Checks weather the attribute is the same /// </summary> /// <param name="obj"></param> /// <returns></returns> public override bool Equals(object obj) { if (obj == null || GetType() != obj.GetType()) { return false; } var o1 = obj as QualifierAttribute; if (_value != o1._value) return false; return true; } public override int GetHashCode() { return _value != null ? _value.GetHashCode() : 0; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Spring.Objects.Factory.Attributes { /// <summary> /// This annotation may be used on a field or parameter as a qualifier for /// candidate beans when autowiring. It may also be used to annotate other /// custom annotations that can then in turn be used as qualifiers. /// </summary> [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter)] public class QualifierAttribute : Attribute { private readonly string _value; /// <summary> /// Instantiate a new qualifier with an empty name /// </summary> public QualifierAttribute() { _value = ""; } /// <summary> /// Instantiate a new qualifier with a givin name /// </summary> /// <param name="value">name to use as qualifier</param> public QualifierAttribute(string value) { _value = value; } /// <summary> /// Gets the name associated with this qualifier /// </summary> public string Value { get { return _value; } } /// <summary> /// Checks weather the attribute is the same /// </summary> /// <param name="obj"></param> /// <returns></returns> public override bool Equals(object obj) { if (obj == null || GetType() != obj.GetType()) { return false; } var o1 = obj as QualifierAttribute; if (_value != o1._value) return false; return true; } public override int GetHashCode() { return _value != null ? _value.GetHashCode() : 0; } } }
apache-2.0
C#
5d890c069693fde7527458880d95fe70afb612c5
Change Scope for WorkflowPurger
danielgerlag/workflow-core
src/providers/WorkflowCore.Providers.Azure/ServiceCollectionExtensions.cs
src/providers/WorkflowCore.Providers.Azure/ServiceCollectionExtensions.cs
using Microsoft.Extensions.Logging; using WorkflowCore.Interface; using WorkflowCore.Models; using WorkflowCore.Providers.Azure.Interface; using WorkflowCore.Providers.Azure.Services; namespace Microsoft.Extensions.DependencyInjection { public static class ServiceCollectionExtensions { public static WorkflowOptions UseAzureSynchronization(this WorkflowOptions options, string connectionString) { options.UseQueueProvider(sp => new AzureStorageQueueProvider(connectionString, sp.GetService<ILoggerFactory>())); options.UseDistributedLockManager(sp => new AzureLockManager(connectionString, sp.GetService<ILoggerFactory>())); return options; } public static WorkflowOptions UseAzureServiceBusEventHub( this WorkflowOptions options, string connectionString, string topicName, string subscriptionName) { options.UseEventHub(sp => new ServiceBusLifeCycleEventHub( connectionString, topicName, subscriptionName, sp.GetService<ILoggerFactory>())); return options; } public static WorkflowOptions UseCosmosDbPersistence( this WorkflowOptions options, string connectionString, string databaseId, CosmosDbStorageOptions cosmosDbStorageOptions = null) { if (cosmosDbStorageOptions == null) { cosmosDbStorageOptions = new CosmosDbStorageOptions(); } options.Services.AddSingleton<ICosmosClientFactory>(sp => new CosmosClientFactory(connectionString)); options.Services.AddTransient<ICosmosDbProvisioner>(sp => new CosmosDbProvisioner(sp.GetService<ICosmosClientFactory>(), cosmosDbStorageOptions)); options.Services.AddSingleton<IWorkflowPurger>(sp => new WorkflowPurger(sp.GetService<ICosmosClientFactory>(), databaseId, cosmosDbStorageOptions)); options.UsePersistence(sp => new CosmosDbPersistenceProvider(sp.GetService<ICosmosClientFactory>(), databaseId, sp.GetService<ICosmosDbProvisioner>(), cosmosDbStorageOptions)); return options; } } }
using Microsoft.Extensions.Logging; using WorkflowCore.Interface; using WorkflowCore.Models; using WorkflowCore.Providers.Azure.Interface; using WorkflowCore.Providers.Azure.Services; namespace Microsoft.Extensions.DependencyInjection { public static class ServiceCollectionExtensions { public static WorkflowOptions UseAzureSynchronization(this WorkflowOptions options, string connectionString) { options.UseQueueProvider(sp => new AzureStorageQueueProvider(connectionString, sp.GetService<ILoggerFactory>())); options.UseDistributedLockManager(sp => new AzureLockManager(connectionString, sp.GetService<ILoggerFactory>())); return options; } public static WorkflowOptions UseAzureServiceBusEventHub( this WorkflowOptions options, string connectionString, string topicName, string subscriptionName) { options.UseEventHub(sp => new ServiceBusLifeCycleEventHub( connectionString, topicName, subscriptionName, sp.GetService<ILoggerFactory>())); return options; } public static WorkflowOptions UseCosmosDbPersistence( this WorkflowOptions options, string connectionString, string databaseId, CosmosDbStorageOptions cosmosDbStorageOptions = null) { if (cosmosDbStorageOptions == null) { cosmosDbStorageOptions = new CosmosDbStorageOptions(); } options.Services.AddSingleton<ICosmosClientFactory>(sp => new CosmosClientFactory(connectionString)); options.Services.AddTransient<ICosmosDbProvisioner>(sp => new CosmosDbProvisioner(sp.GetService<ICosmosClientFactory>(), cosmosDbStorageOptions)); options.Services.AddTransient<IWorkflowPurger>(sp => new WorkflowPurger(sp.GetService<ICosmosClientFactory>(), databaseId, cosmosDbStorageOptions)); options.UsePersistence(sp => new CosmosDbPersistenceProvider(sp.GetService<ICosmosClientFactory>(), databaseId, sp.GetService<ICosmosDbProvisioner>(), cosmosDbStorageOptions)); return options; } } }
mit
C#
64b7f6ba3c5fe153bf90dcbc747fd99f1109fc11
Make sure date processing is accurate
jquintus/spikes,jquintus/spikes,jquintus/spikes,jquintus/spikes
ConsoleApps/Repack/Repack/Program.cs
ConsoleApps/Repack/Repack/Program.cs
using System; using Humanizer; namespace Repack { internal class Program { public static void Main(string[] args) { Console.WriteLine("Usage: repack [date]"); Console.WriteLine("Prints how long it is until your birthday."); Console.WriteLine("If you don't supply your birthday, it uses mine."); DateTime birthDay = GetBirthday(args); Console.WriteLine(); var span = GetSpan(birthDay); Console.WriteLine("{0} until your birthday", span.Humanize()); } private static TimeSpan GetSpan(DateTime birthDay) { var span = birthDay.Date - DateTime.Now.Date; if (span.Days < 0) { // If the supplied birthday has already happened, then find the next one that will occur. int years = span.Days / -365; if (span.Days % 365 != 0) years++; span = span.Add(TimeSpan.FromDays(years * 365)); } return span; } private static DateTime GetBirthday(string[] args) { string day = null; if (args != null && args.Length > 0) { day = args[0]; } return GetBirthday(day); } private static DateTime GetBirthday(string day) { DateTime parsed; if (DateTime.TryParse(day, out parsed)) { return parsed; } else { return new DateTime(DateTime.Now.Year, 8, 20); } } } }
using System; using Humanizer; namespace Repack { internal class Program { public static void Main(string[] args) { Console.WriteLine("Usage: repack [date]"); Console.WriteLine("Prints how long it is until your birthday."); Console.WriteLine("If you don't supply your birthday, it uses mine."); DateTime birthDay = GetBirthday(args); Console.WriteLine(); var span = GetSpan(birthDay); Console.WriteLine("{0} until your birthday", span.Humanize()); } private static TimeSpan GetSpan(DateTime birthDay) { var span = birthDay - DateTime.Now; if (span.Days < 0) { // If the supplied birthday has already happened, then find the next one that will occur. int years = span.Days / -365; span = span.Add(TimeSpan.FromDays((years + 1) * 365)); } return span; } private static DateTime GetBirthday(string[] args) { string day = null; if (args != null && args.Length > 0) { day = args[0]; } return GetBirthday(day); } private static DateTime GetBirthday(string day) { DateTime parsed; if (DateTime.TryParse(day, out parsed)) { return parsed; } else { return new DateTime(DateTime.Now.Year, 8, 20); } } } }
mit
C#
b1fa3901279b330b9699eb29402cca32d2b8c84d
Remove ununsed code
cityindex-attic/CIAPI.CS.AspNet,cityindex-attic/CIAPI.CS.AspNet
src/CIAPI.AspNet.Controls/Core/ControlInjectorCssRegistrar.cs
src/CIAPI.AspNet.Controls/Core/ControlInjectorCssRegistrar.cs
using System; using System.Linq; using System.Web.UI; using System.Web.UI.WebControls; namespace CIAPI.AspNet.Controls.Core { public class ControlInjectorCssRegistrar : ICssRegistrar { private readonly Control _injectionTarget; public ControlInjectorCssRegistrar(Control injectionTarget) { _injectionTarget = injectionTarget; } public void RegisterFromResource(WebControl control, Type resourceAssembly, string resourceNamePrefix, string resourceName) { var cssUrl = control.Page.ClientScript.GetWebResourceUrl(resourceAssembly, resourceNamePrefix + "." + resourceName); var cssControl = new Literal {Text = @"<link href=""" + cssUrl + @""" type=""text/css"" rel=""stylesheet"" />"}; _injectionTarget.Controls.Add(cssControl); } } }
using System; using System.Linq; using System.Web.UI; using System.Web.UI.WebControls; namespace CIAPI.AspNet.Controls.Core { public class ControlInjectorCssRegistrar : ICssRegistrar { private readonly Control _injectionTarget; public ControlInjectorCssRegistrar(Control injectionTarget) { _injectionTarget = injectionTarget; } public void RegisterFromResource(WebControl control, Type resourceAssembly, string resourceNamePrefix, string resourceName) { // var scriptManager = GetPageScriptManager(control); // if (ResourceAddedAlready(scriptManager, resourceName)) return; var cssUrl = control.Page.ClientScript.GetWebResourceUrl(resourceAssembly, resourceNamePrefix + "." + resourceName); var cssControl = new Literal {Text = @"<link href=""" + cssUrl + @""" type=""text/css"" rel=""stylesheet"" />"}; _injectionTarget.Controls.Add(cssControl); // ScriptManager.RegisterClientScriptBlock(control.Page, control.GetType(), resourceName, css, false); } private static ScriptManager GetPageScriptManager(Control control) { var scriptManager = ScriptManager.GetCurrent(control.Page); if (scriptManager==null) { throw new ArgumentNullException("control", string.Format("The {0} control must be on a page that has a ScriptManager on it", control.GetType().FullName)); } return scriptManager; } private static bool ResourceAddedAlready(ScriptManager scriptManager, string resourceName) { return scriptManager.Scripts.Where(s => s.Name.EndsWith(resourceName)).Count() > 0; } } }
apache-2.0
C#
87345fbd4891045397708d550b26ffaac7efd0c5
Add PrintSchema Framework names
kei10in/KipSharp
Kip/PrintSchemaFramework.cs
Kip/PrintSchemaFramework.cs
using System.Xml.Linq; namespace Kip { public static class PrintSchemaFramework { public static readonly XNamespace Url = "http://schemas.microsoft.com/windows/2003/08/printing/printschemaframework"; public static readonly XName PrintCapabilities = Url + "PrintCapabilities"; public static readonly XName PrintTicket = Url + "PrintTicket"; public static readonly XName Feature = Url + "Feature"; public static readonly XName Option = Url + "Option"; public static readonly XName ParameterDef = Url + "ParameterDef"; public static readonly XName ParameterInit = Url + "ParameterInit"; public static readonly XName ParameterRef = Url + "ParameterRef"; public static readonly XName Property = Url + "Property"; public static readonly XName ScoredProperty = Url + "ScoredProperty"; public static readonly XName Value = Url + "Value"; public static readonly XName SelectionType = Url + "SelectionType"; public static readonly XName IdentityOption = Url + "IdentityOpiton"; public static readonly XName DataType = Url + "DataType"; public static readonly XName DefaultValue = Url + "DefaultValue"; public static readonly XName MaxLength = Url + "MaxLength"; public static readonly XName MinLength = Url + "MinLength"; public static readonly XName MaxValue = Url + "MaxValue"; public static readonly XName MinValue = Url + "MinValue"; public static readonly XName Mandatory = Url + "Mandatory"; public static readonly XName UnitType = Url + "UnitType"; } }
using System.Xml.Linq; namespace Kip { public static class PrintSchemaFramework { public static readonly XNamespace Url = "http://schemas.microsoft.com/windows/2003/08/printing/printschemaframework"; public static readonly XName PrintCapabilities = Url + "PrintCapabilities"; public static readonly XName PrintTicket = Url + "PrintTicket"; public static readonly XName Feature = Url + "Feature"; public static readonly XName Option = Url + "Option"; public static readonly XName ParameterDef = Url + "ParameterDef"; public static readonly XName ParameterInit = Url + "ParameterInit"; public static readonly XName ParameterRef = Url + "ParameterRef"; public static readonly XName Property = Url + "Property"; public static readonly XName ScoredProperty = Url + "ScoredProperty"; public static readonly XName Value = Url + "Value"; public static readonly XName SelectionType = Url + "SelectionType"; public static readonly XName IdentityOption = Url + "IdentityOpiton"; } }
mit
C#
6bb27dbbfb70ae983abf8e626ffb96b2a52a73ed
Add missing code to VisualStudio virConnectSetErrorFunc example
libvirt/libvirt-csharp,Anthilla/libvirt-csharp
examples/VisualStudio/virConnectSetErrorFunc/Form1.cs
examples/VisualStudio/virConnectSetErrorFunc/Form1.cs
/* * Copyright (C) * Arnaud Champion <arnaud.champion@devatom.fr> * Jaromír Červenka <cervajz@cervajz.com> * * See COPYING.LIB for the License of this software * * Sample code for : * Functions : * Connect.OpenAuth * Domain.GetInfo * Domain.LookupByName * Errors.GetLastError * Errors.SetErrorFunc * * Types : * DomainInfo * Error * */ using System; using System.Windows.Forms; using Libvirt; namespace virConnectSetErrorFunc { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btnConnect_Click(object sender, EventArgs e) { IntPtr conn = Connect.Open(tbURI.Text); if (conn != IntPtr.Zero) { Errors.SetErrorFunc(IntPtr.Zero, ErrorCallback); IntPtr domain = Domain.LookupByName(conn, tbDomainName.Text); DomainInfo di = new DomainInfo(); Domain.GetInfo(domain, di); textBox1.Text = di.State.ToString(); textBox2.Text = di.maxMem.ToString(); textBox3.Text = di.memory.ToString(); textBox4.Text = di.nrVirtCpu.ToString(); textBox5.Text = di.cpuTime.ToString(); } else { Error error = Errors.GetLastError(); ShowError(error); } } private void ErrorCallback(IntPtr userData, Error error) { ShowError(error); } private void ShowError(Error libvirtError) { string ErrorBoxMessage = string.Format("Error number : {0}. Error message : {1}", libvirtError.code, libvirtError.Message); MessageBox.Show(ErrorBoxMessage, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } }
/* * Copyright (C) * Arnaud Champion <arnaud.champion@devatom.fr> * Jaromír Červenka <cervajz@cervajz.com> * * See COPYING.LIB for the License of this software * * Sample code for : * Functions : * Connect.OpenAuth * Domain.GetInfo * Domain.LookupByName * Errors.GetLastError * Errors.SetErrorFunc * * Types : * DomainInfo * Error * */ using System; using System.Windows.Forms; using Libvirt; namespace virConnectSetErrorFunc { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btnConnect_Click(object sender, EventArgs e) { IntPtr conn = Connect.Open(tbURI.Text); if (conn != IntPtr.Zero) { Errors.SetErrorFunc(IntPtr.Zero, ErrorCallback); IntPtr domain = Domain.LookupByName(conn, tbDomainName.Text); DomainInfo di = new DomainInfo(); Domain.GetInfo(domain, di); textBox1.Text = di.State.ToString(); textBox2.Text = di.maxMem.ToString(); textBox3.Text = di.memory.ToString(); textBox4.Text = di.nrVirtCpu.ToString(); textBox5.Text = di.cpuTime.ToString(); }
lgpl-2.1
C#
acfd89ba9f11afd29a17d34c4ab8a5768c9c5b05
disable blocked FilterListsDesignTimeDbContextFactory
collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists
src/FilterLists.Data/FilterListsDesignTimeDbContextFactory.cs
src/FilterLists.Data/FilterListsDesignTimeDbContextFactory.cs
using System; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Design; namespace FilterLists.Data { //TODO: [BLOCKED] pass connection string https://github.com/aspnet/EntityFrameworkCore/issues/8332 //[UsedImplicitly] //public class FilterListsDesignTimeDbContextFactory : IDesignTimeDbContextFactory<FilterListsDbContext> //{ // private readonly int commandTimeoutSecs = (int)TimeSpan.FromMinutes(30).TotalSeconds; // /// <summary> // /// increases command timeout for design time migrations // /// </summary> // public FilterListsDbContext CreateDbContext(string[] args) // { // var optionsBuilder = new DbContextOptionsBuilder<FilterListsDbContext>(); // optionsBuilder.UseMySql( // @"", // o => // { // o.MigrationsAssembly("FilterLists.Api"); // o.CommandTimeout(commandTimeoutSecs); // } // ); // return new FilterListsDbContext(optionsBuilder.Options); // } //} }
using System; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Design; namespace FilterLists.Data { [UsedImplicitly] public class FilterListsDesignTimeDbContextFactory : IDesignTimeDbContextFactory<FilterListsDbContext> { private readonly int commandTimeoutSecs = (int)TimeSpan.FromMinutes(30).TotalSeconds; /// <summary> /// increases command timeout for design time migrations /// </summary> public FilterListsDbContext CreateDbContext(string[] args) { var optionsBuilder = new DbContextOptionsBuilder<FilterListsDbContext>(); optionsBuilder.UseMySql( @"", //BLOCKED: pass connection string https://github.com/aspnet/EntityFrameworkCore/issues/8332 o => { o.MigrationsAssembly("FilterLists.Api"); o.CommandTimeout(commandTimeoutSecs); } ); return new FilterListsDbContext(optionsBuilder.Options); } } }
mit
C#
aab810f233c6211b4106f8bc06c018a31827cff8
Use at least a password that has char that needs to be encoded so that that is tested.
danielwertheim/mycouch,danielwertheim/mycouch
src/Tests/MyCouch.IntegrationTests/TestClientFactory.cs
src/Tests/MyCouch.IntegrationTests/TestClientFactory.cs
using System; namespace MyCouch.IntegrationTests { internal static class TestClientFactory { internal static IClient CreateDefault() { return new Client("http://mycouchtester:" + Uri.EscapeDataString("p@ssword") + "@localhost:5984/" + TestConstants.TestDbName); } } }
namespace MyCouch.IntegrationTests { internal static class TestClientFactory { internal static IClient CreateDefault() { return new Client("http://mycouchtester:1q2w3e4r@localhost:5984/" + TestConstants.TestDbName); } } }
mit
C#
f169fb33d332e9cde27bfed9792ea2fafbd4fc09
undo class1
gusev-p/simple-1c
Tests/Class1.cs
Tests/Class1.cs
using NUnit.Framework; using Simple1C.Tests.Helpers; namespace Simple1C.Tests { internal class Class1 : TestBase { [Test] [Ignore("")] public void Test1() { } } }
using System; using System.IO; using System.Linq; using System.Text; using NUnit.Framework; using Simple1C.Impl.Sql.SchemaMapping; using Simple1C.Impl.Sql.SqlAccess; using Simple1C.Impl.Sql.Translation; using Simple1C.Tests.Helpers; namespace Simple1C.Tests { internal class Class1 : TestBase { [Test] public void Test1() { var inputs = new[] { "C:\\Users\\mskr\\Desktop\\badQuery.1c"} .Select(c=>File.ReadAllText(c, Encoding.UTF8)) .ToArray(); var translator = new QueryToSqlTranslator( new PostgreeSqlSchemaStore( new PostgreeSqlDatabase("host=localhost;port=5432;Database=mskr;Username=mskr;Password=developer")), new int[0]); foreach (var input in inputs) { Console.WriteLine(translator.Translate(input)); } } } }
mit
C#
60a1fbaf175e88090b6d30a7f0a1cac9d31bc0c6
Increase project version to 0.15.0
atata-framework/atata-sample-app-tests
src/CommonAssemblyInfo.cs
src/CommonAssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Yevgeniy Shunevych")] [assembly: AssemblyProduct("Atata Framework")] [assembly: AssemblyCopyright("Copyright © Yevgeniy Shunevych 2017")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("0.15.0")] [assembly: AssemblyFileVersion("0.15.0")]
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Yevgeniy Shunevych")] [assembly: AssemblyProduct("Atata Framework")] [assembly: AssemblyCopyright("Copyright © Yevgeniy Shunevych 2017")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("0.14.0")] [assembly: AssemblyFileVersion("0.14.0")]
apache-2.0
C#
1e0be9a25eab735883b52d424875bb976bd2ef8d
Set id when adding new cinema
jenspettersson/Argentum
Sample/SilverScreen/Domain/Cinema.cs
Sample/SilverScreen/Domain/Cinema.cs
using System; using System.Collections.Generic; using Argentum.Core; namespace SilverScreen.Domain { public class Cinema : AggregateBase<CinemaState> { public Cinema(CinemaState state) : base(state) { } private Cinema(Guid id, string name) { Apply(new CinemaAdded(id, name)); } public static Cinema Add(string name) { return new Cinema(Guid.NewGuid(), name); } } public class CinemaState : State { public string Name { get; set; } public List<Screen> Screens { get; set; } public void When(CinemaAdded evt) { Id = evt.Id; Name = evt.Name; } } public class CinemaAdded : IEvent { public Guid Id { get; private set; } public string Name { get; private set; } public CinemaAdded(Guid id, string name) { Id = id; Name = name; } } }
using System.Collections.Generic; using Argentum.Core; namespace SilverScreen.Domain { public class Cinema : AggregateBase<CinemaState> { public Cinema(CinemaState state) : base(state) { } private Cinema(string name) { Apply(new CinemaAdded(name)); } public static Cinema Add(string name) { return new Cinema(name); } } public class CinemaState : State { public string Name { get; set; } public List<Screen> Screens { get; set; } public void When(CinemaAdded evt) { Name = evt.Name; } } public class CinemaAdded : IEvent { public string Name { get; private set; } public CinemaAdded(string name) { Name = name; } } }
mit
C#
4d52e5a4064356d2d5f5d626017c79e88219f196
Change HttpContext variable to aspnet.HttpContext.
shiftkey/SignalR,shiftkey/SignalR
SignalR.AspNet/AspNetHost.cs
SignalR.AspNet/AspNetHost.cs
using System; using System.Linq; using System.Threading.Tasks; using System.Web; using SignalR.Abstractions; namespace SignalR.AspNet { public class AspNetHost : HttpTaskAsyncHandler { private readonly PersistentConnection _connection; private static readonly Lazy<bool> _hasAcceptWebSocketRequest = new Lazy<bool>(() => { return typeof(HttpContextBase).GetMethods().Any(m => m.Name.Equals("AcceptWebSocketRequest", StringComparison.OrdinalIgnoreCase)); }); public AspNetHost(PersistentConnection connection) { _connection = connection; } public override Task ProcessRequestAsync(HttpContextBase context) { var request = new AspNetRequest(context.Request); var response = new AspNetResponse(context.Request, context.Response); var hostContext = new HostContext(request, response, context.User); // Determine if the client should bother to try a websocket request hostContext.Items["supportsWebSockets"] = _hasAcceptWebSocketRequest.Value; // Set the debugging flag hostContext.Items["debugMode"] = context.IsDebuggingEnabled; // Stick the context in here so transports or other asp.net specific logic can // grab at it. hostContext.Items["aspnet.HttpContext"] = context; return _connection.ProcessRequestAsync(hostContext); } } }
using System; using System.Linq; using System.Threading.Tasks; using System.Web; using SignalR.Abstractions; namespace SignalR.AspNet { public class AspNetHost : HttpTaskAsyncHandler { private readonly PersistentConnection _connection; private static readonly Lazy<bool> _hasAcceptWebSocketRequest = new Lazy<bool>(() => { return typeof(HttpContextBase).GetMethods().Any(m => m.Name.Equals("AcceptWebSocketRequest", StringComparison.OrdinalIgnoreCase)); }); public AspNetHost(PersistentConnection connection) { _connection = connection; } public override Task ProcessRequestAsync(HttpContextBase context) { var request = new AspNetRequest(context.Request); var response = new AspNetResponse(context.Request, context.Response); var hostContext = new HostContext(request, response, context.User); // Determine if the client should bother to try a websocket request hostContext.Items["supportsWebSockets"] = _hasAcceptWebSocketRequest.Value; // Set the debugging flag hostContext.Items["debugMode"] = context.IsDebuggingEnabled; // Stick the context in here so transports or other asp.net specific logic can // grab at it. hostContext.Items["aspnet.context"] = context; return _connection.ProcessRequestAsync(hostContext); } } }
mit
C#
13be5e3681e13d9d30c39e3c8ca6f3bf3201e4f9
Update Cop.cs
ScrappyOrc/copsnrobbers,ScrappyOrc/copsnrobbers
Assets/Scripts/Characters/Cop.cs
Assets/Scripts/Characters/Cop.cs
using UnityEngine; using System.Collections; public class Cop : Character { // Use this for initialization override protected void Start () { base.Start (); } // Update is called once per frame override protected void Update () { } public void MakeDecision() { DecisionTree.Node node = dTree.Root; bool inTree = true; while(inTree) { bool result = true; switch (node.Data) { case "HasCall": result = HasCall(); break; case "RobberNearby": result = RobberNearby(); break; case "ManyPoliceOnCall": result = ManyPoliceOnCall(); break; case "StopRobber": result = StopRobber(); break; case "BiggerCrime": result = BiggerCrime(); break; case "HeadToCall": result = HeadToCall(); break; case "PanicNearby": result = PanicNearby(); break; case "LookForCause": result = LookForCause(); break; case "Patrol": result = Patrol(); break; } } } private bool HasCall() { // TODO check if I have a call or not return false; } private bool RobberNearby() { // TODO Spherical raycast or similar to check return false; } private bool ManyPoliceOnCall() { // TODO implement count of active police return false; } private bool StopRobber() { // TODO Seek target robber and "stop" him return false; } private bool BiggerCrime() { // TODO check if this is the current biggest crime return false; } private bool HeadToCall() { // TODO seek location provided by call return false; } private bool PanicNearby() { // TODO detect if a hubbub has started nearby return false; } private bool LookForCause() { // TODO if hubbub, seek towards it return false; } private bool Patrol() { // TODO wander within beat QueueAction(new Wander(4)); return true; } }
using UnityEngine; using System.Collections; public class Cop : Character { // Use this for initialization override protected void Start () { base.Start (); } // Update is called once per frame override protected void Update () { } }
mit
C#
7616e8fbdedebaf2af329c053a0f2926dde0deed
Update assembly
amweiss/vigilant-cupcake
VigilantCupcake/Properties/AssemblyInfo.cs
VigilantCupcake/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Resources; // 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("VigilantCupcake")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("VigilantCupcake")] [assembly: AssemblyProduct("VigilantCupcake")] [assembly: AssemblyCopyright("Copyright © VigilantCupcake 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("354605ff-ffd4-4825-81e6-a9781e1a0368")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.1.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: NeutralResourcesLanguageAttribute("en-US")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Resources; // 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("VigilantCupcake")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("VigilantCupcake")] [assembly: AssemblyProduct("VigilantCupcake")] [assembly: AssemblyCopyright("Copyright © VigilantCupcake 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("354605ff-ffd4-4825-81e6-a9781e1a0368")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.0.1.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: NeutralResourcesLanguageAttribute("en-US")]
mit
C#
e474ebf6bbfed8d0fbc6665b2653d093ee4b3ea3
Update the link to product site in ProductInfoForm.
rubyu/CreviceApp,rubyu/CreviceApp
CreviceApp/UI.ProductInfoForm.cs
CreviceApp/UI.ProductInfoForm.cs
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Drawing; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Web; using System.Windows.Forms; namespace Crevice.UI { using Crevice.Config; public partial class ProductInfoForm : Form { private CLIOption.Result cliOption; public ProductInfoForm(CLIOption.Result cliOption) { this.cliOption = cliOption; this.Icon = Properties.Resources.CreviceIcon; InitializeComponent(); } private const string url = "https://github.com/creviceapp/creviceapp"; protected string GetInfoMessage() { return string.Format(Properties.Resources.ProductInfo, "Crevice", Application.ProductVersion, ((AssemblyCopyrightAttribute)Attribute.GetCustomAttribute(Assembly.GetExecutingAssembly(), typeof(AssemblyCopyrightAttribute), false)).Copyright, url, cliOption.helpMessageHtml); } protected override void OnShown(EventArgs e) { base.OnShown(e); webBrowser1.DocumentText = GetInfoMessage(); } private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e) { if (e.Url.Scheme.StartsWith("http")) { e.Cancel = true; Process.Start(e.Url.ToString()); } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Drawing; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Web; using System.Windows.Forms; namespace Crevice.UI { using Crevice.Config; public partial class ProductInfoForm : Form { private CLIOption.Result cliOption; public ProductInfoForm(CLIOption.Result cliOption) { this.cliOption = cliOption; this.Icon = Properties.Resources.CreviceIcon; InitializeComponent(); } private const string url = "https://github.com/rubyu/CreviceApp"; protected string GetInfoMessage() { return string.Format(Properties.Resources.ProductInfo, "Crevice", Application.ProductVersion, ((AssemblyCopyrightAttribute)Attribute.GetCustomAttribute(Assembly.GetExecutingAssembly(), typeof(AssemblyCopyrightAttribute), false)).Copyright, url, cliOption.helpMessageHtml); } protected override void OnShown(EventArgs e) { base.OnShown(e); webBrowser1.DocumentText = GetInfoMessage(); } private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e) { if (e.Url.Scheme.StartsWith("http")) { e.Cancel = true; Process.Start(e.Url.ToString()); } } } }
mit
C#
73ddac6a31107c0229f4722e9cd3c3d6071f9dd6
Fix menu highlighting bug
stvnhrlnd/SH,stvnhrlnd/SH,stvnhrlnd/SH
SH.Site/Views/Master.cshtml
SH.Site/Views/Master.cshtml
@inherits UmbracoViewPage<IMaster> @{ var website = Model.Ancestor<Website>(); var menuItems = website.Children<IMaster>(); } <!doctype html> <html lang="en"> <head> <meta charset="utf-8" /> <title>@Model.SeoMetadata.Title</title> <meta name="description" content="@Model.SeoMetadata.Description" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.6.1/css/font-awesome.min.css" /> <link rel="stylesheet" href="//yui.yahooapis.com/pure/0.6.0/pure-min.css" /> <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.3.0/styles/default.min.css" /> <link rel="stylesheet" href="~/css/base.css" /> <link rel="stylesheet" href="~/css/layout/main.css" /> <link rel="stylesheet" href="~/css/layout/menu.css" /> <link rel="stylesheet" href="~/css/components/header.css" /> <link rel="stylesheet" href="~/css/components/post.css" /> </head> <body> <a href="#menu" id="menu-link"> <i class="fa fa-bars" aria-hidden="true"></i> <i class="fa fa-times" aria-hidden="true"></i> </a> <div id="menu"> <div class="pure-menu"> <span class="pure-menu-heading">@website.SiteName</span> <ul class="pure-menu-list"> @foreach (var item in menuItems) { var selected = Model.Path.Split(',').Select(int.Parse).Contains(item.Id); <li class="pure-menu-item @(selected ? "pure-menu-selected": "")"> <a href="@item.Url" class="pure-menu-link"> @item.Name </a> </li> } </ul> </div> </div> <div id="main"> @RenderBody() </div> <script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.3.0/highlight.min.js"></script> <script src="~/scripts/highlighting.js"></script> <script src="~/scripts/menu.js"></script> </body> </html>
@inherits UmbracoViewPage<IMaster> @{ var website = Model.Ancestor<Website>(); var menuItems = website.Children<IMaster>(); } <!doctype html> <html lang="en"> <head> <meta charset="utf-8" /> <title>@Model.SeoMetadata.Title</title> <meta name="description" content="@Model.SeoMetadata.Description" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.6.1/css/font-awesome.min.css" /> <link rel="stylesheet" href="//yui.yahooapis.com/pure/0.6.0/pure-min.css" /> <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.3.0/styles/default.min.css" /> <link rel="stylesheet" href="~/css/base.css" /> <link rel="stylesheet" href="~/css/layout/main.css" /> <link rel="stylesheet" href="~/css/layout/menu.css" /> <link rel="stylesheet" href="~/css/components/header.css" /> <link rel="stylesheet" href="~/css/components/post.css" /> </head> <body> <a href="#menu" id="menu-link"> <i class="fa fa-bars" aria-hidden="true"></i> <i class="fa fa-times" aria-hidden="true"></i> </a> <div id="menu"> <div class="pure-menu"> <span class="pure-menu-heading">@website.SiteName</span> <ul class="pure-menu-list"> @foreach (var item in menuItems) { var selected = Model.Id == item.Id; <li class="pure-menu-item @(selected ? "pure-menu-selected": "")"> <a href="@item.Url" class="pure-menu-link"> @item.Name </a> </li> } </ul> </div> </div> <div id="main"> @RenderBody() </div> <script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.3.0/highlight.min.js"></script> <script src="~/scripts/highlighting.js"></script> <script src="~/scripts/menu.js"></script> </body> </html>
mit
C#
888e4fbda7388ebf083c823c4562977ea166a09a
make NonCopyable public
ufcpp/MixinGenerator
MixinGenerator/MixinGenerator.Mixins/Annotations/NonCopyableAttribute.cs
MixinGenerator/MixinGenerator.Mixins/Annotations/NonCopyableAttribute.cs
using System; namespace MixinGenerator.Annotations { [AttributeUsage(AttributeTargets.Struct)] public class NonCopyableAttribute : Attribute { } }
using System; namespace MixinGenerator.Annotations { [AttributeUsage(AttributeTargets.Struct)] internal class NonCopyableAttribute : Attribute { } }
mit
C#
88066a77b55c678d391d12debe68b7eee0456659
Remove getter of Value of BindingVisibleRegionBehavior.
nuitsjp/Xamarin.Forms.GoogleMaps.Bindings
Soruce/Xamarin.Forms.GoogleMaps.Bindings/BindingVisibleRegionBehavior.cs
Soruce/Xamarin.Forms.GoogleMaps.Bindings/BindingVisibleRegionBehavior.cs
using System.ComponentModel; namespace Xamarin.Forms.GoogleMaps.Bindings { [Preserve(AllMembers = true)] public class BindingVisibleRegionBehavior : BehaviorBase<Map> { public static readonly BindableProperty ValueProperty = BindableProperty.Create("Value", typeof(MapSpan), typeof(BindingVisibleRegionBehavior), default(MapSpan), BindingMode.OneWayToSource); public MapSpan Value { set { SetValue(ValueProperty, value); } } protected override void OnAttachedTo(Map bindable) { base.OnAttachedTo(bindable); bindable.PropertyChanged += BindableOnPropertyChanged; } protected override void OnDetachingFrom(Map bindable) { bindable.PropertyChanged -= BindableOnPropertyChanged; base.OnDetachingFrom(bindable); } private void BindableOnPropertyChanged(object sender, PropertyChangedEventArgs args) { if (args.PropertyName == "VisibleRegion") { Value = AssociatedObject.VisibleRegion; } } } }
using System.ComponentModel; namespace Xamarin.Forms.GoogleMaps.Bindings { [Preserve(AllMembers = true)] public class BindingVisibleRegionBehavior : BehaviorBase<Map> { public static readonly BindableProperty ValueProperty = BindableProperty.Create("Value", typeof(MapSpan), typeof(BindingVisibleRegionBehavior), default(MapSpan), BindingMode.OneWayToSource); public MapSpan Value { get { return (MapSpan)GetValue(ValueProperty); } set { SetValue(ValueProperty, value); } } protected override void OnAttachedTo(Map bindable) { base.OnAttachedTo(bindable); bindable.PropertyChanged += BindableOnPropertyChanged; } protected override void OnDetachingFrom(Map bindable) { bindable.PropertyChanged -= BindableOnPropertyChanged; base.OnDetachingFrom(bindable); } private void BindableOnPropertyChanged(object sender, PropertyChangedEventArgs args) { if (args.PropertyName == "VisibleRegion") { Value = AssociatedObject.VisibleRegion; } } } }
mit
C#
5d34cbf39459925809050e43196c49e4c222ad5d
Improve Network.GamePacketReader by using properties and adding ReadBool()
IceYGO/ygosharp,Zayelion/ygosharp
YGOSharp.Network/GamePacketReader.cs
YGOSharp.Network/GamePacketReader.cs
using System.IO; using YGOSharp.Network.Enums; using YGOSharp.Network.Utils; namespace YGOSharp.Network { public class GamePacketReader { public byte[] Content { get; private set; } private BinaryReader _reader; public GamePacketReader(byte[] content) { Content = content; _reader = new BinaryReader(new MemoryStream(Content)); } public long Position { get { return _reader.BaseStream.Position; } set { _reader.BaseStream.Position = value; } } public long Length { get { return _reader.BaseStream.Length; } } public CtosMessage ReadCtos() { return (CtosMessage)_reader.ReadByte(); } public StocMessage ReadStoc() { return (StocMessage)_reader.ReadByte(); } public byte ReadByte() { return _reader.ReadByte(); } public byte[] ReadBytes(int count) { return _reader.ReadBytes(count); } public byte[] ReadToEnd() { return _reader.ReadBytes((int)(Length - Position)); } public sbyte ReadSByte() { return _reader.ReadSByte(); } public bool ReadBool() { return _reader.ReadByte() != 0; } public short ReadInt16() { return _reader.ReadInt16(); } public int ReadInt32() { return _reader.ReadInt32(); } public string ReadUnicode(int len) { return _reader.ReadUnicode(len); } } }
using System.IO; using YGOSharp.Network.Enums; using YGOSharp.Network.Utils; namespace YGOSharp.Network { public class GamePacketReader { public byte[] Content { get; private set; } private BinaryReader _reader; public GamePacketReader(byte[] content) { Content = content; _reader = new BinaryReader(new MemoryStream(Content)); } public CtosMessage ReadCtos() { return (CtosMessage)_reader.ReadByte(); } public StocMessage ReadStoc() { return (StocMessage)_reader.ReadByte(); } public byte ReadByte() { return _reader.ReadByte(); } public byte[] ReadToEnd() { return _reader.ReadBytes((int)_reader.BaseStream.Length - (int)_reader.BaseStream.Position); } public sbyte ReadSByte() { return _reader.ReadSByte(); } public short ReadInt16() { return _reader.ReadInt16(); } public int ReadInt32() { return _reader.ReadInt32(); } public string ReadUnicode(int len) { return _reader.ReadUnicode(len); } public long GetPosition() { return _reader.BaseStream.Position; } public void SetPosition(long pos) { _reader.BaseStream.Position = pos; } } }
mit
C#
5fdb6a74841ed1cdf5b287d5722fe8776c07d558
Index public events
Elders/Cronus,Elders/Cronus
src/Elders.Cronus/EventStore/Index/EventToAggregateRootId.cs
src/Elders.Cronus/EventStore/Index/EventToAggregateRootId.cs
using Elders.Cronus.Projections.Cassandra.EventSourcing; using Microsoft.Extensions.Logging; using System.Collections.Generic; using System.Runtime.Serialization; using System.Text; namespace Elders.Cronus.EventStore.Index { [DataContract(Name = "55f9e248-7bb3-4288-8db8-ba9620c67228")] public class EventToAggregateRootId : IEventStoreIndex { private static readonly ILogger logger = CronusLogger.CreateLogger(typeof(EventToAggregateRootId)); private readonly IIndexStore indexStore; public EventToAggregateRootId(IIndexStore indexStore) { this.indexStore = indexStore; } public void Index(AggregateCommit aggregateCommit) { List<IndexRecord> indexRecordsBatch = new List<IndexRecord>(); foreach (var @event in aggregateCommit.Events) { string eventTypeId = @event.Unwrap().GetType().GetContractId(); var record = new IndexRecord(eventTypeId, aggregateCommit.AggregateRootId); indexRecordsBatch.Add(record); } foreach (var publicEvent in aggregateCommit.PublicEvents) { string eventTypeId = publicEvent.GetType().GetContractId(); var record = new IndexRecord(eventTypeId, aggregateCommit.AggregateRootId); indexRecordsBatch.Add(record); } indexStore.Apend(indexRecordsBatch); } public void Index(CronusMessage message) { var @event = message.Payload as IEvent; string eventTypeId = @event.Unwrap().GetType().GetContractId(); var indexRecord = new List<IndexRecord>(); indexRecord.Add(new IndexRecord(eventTypeId, Encoding.UTF8.GetBytes(message.GetRootId()))); indexStore.Apend(indexRecord); } public IEnumerable<IndexRecord> EnumerateRecords(string dataId) { // TODO: index exists? return indexStore.Get(dataId); } public LoadIndexRecordsResult EnumerateRecords(string dataId, string paginationToken, int pageSize = 5000) { // TODO: index exists? return indexStore.Get(dataId, paginationToken, pageSize); } } }
using Elders.Cronus.Projections.Cassandra.EventSourcing; using Microsoft.Extensions.Logging; using System.Collections.Generic; using System.Runtime.Serialization; using System.Text; namespace Elders.Cronus.EventStore.Index { [DataContract(Name = "55f9e248-7bb3-4288-8db8-ba9620c67228")] public class EventToAggregateRootId : IEventStoreIndex { private static readonly ILogger logger = CronusLogger.CreateLogger(typeof(EventToAggregateRootId)); private readonly IIndexStore indexStore; public EventToAggregateRootId(IIndexStore indexStore) { this.indexStore = indexStore; } public void Index(AggregateCommit aggregateCommit) { List<IndexRecord> indexRecordsBatch = new List<IndexRecord>(); foreach (var @event in aggregateCommit.Events) { string eventTypeId = @event.Unwrap().GetType().GetContractId(); var record = new IndexRecord(eventTypeId, aggregateCommit.AggregateRootId); indexRecordsBatch.Add(record); } indexStore.Apend(indexRecordsBatch); } public void Index(CronusMessage message) { var @event = message.Payload as IEvent; string eventTypeId = @event.Unwrap().GetType().GetContractId(); var indexRecord = new List<IndexRecord>(); indexRecord.Add(new IndexRecord(eventTypeId, Encoding.UTF8.GetBytes(message.GetRootId()))); indexStore.Apend(indexRecord); } public IEnumerable<IndexRecord> EnumerateRecords(string dataId) { // TODO: index exists? return indexStore.Get(dataId); } public LoadIndexRecordsResult EnumerateRecords(string dataId, string paginationToken, int pageSize = 5000) { // TODO: index exists? return indexStore.Get(dataId, paginationToken, pageSize); } } }
apache-2.0
C#
b281ce07764c42d4c9f99bdae98f2389b5b7174f
Allow PR details to be opened more than once.
github/VisualStudio,github/VisualStudio,github/VisualStudio
src/GitHub.VisualStudio/UI/Views/PullRequestListView.xaml.cs
src/GitHub.VisualStudio/UI/Views/PullRequestListView.xaml.cs
using System; using GitHub.Exports; using GitHub.Extensions; using GitHub.UI; using GitHub.ViewModels; using ReactiveUI; using System.ComponentModel.Composition; using System.Reactive.Subjects; using System.Windows.Input; using GitHub.Services; using GitHub.Primitives; namespace GitHub.VisualStudio.UI.Views { public class GenericPullRequestListView : SimpleViewUserControl<IPullRequestListViewModel, PullRequestListView> { } [ExportView(ViewType = UIViewType.PRList)] [PartCreationPolicy(CreationPolicy.NonShared)] public partial class PullRequestListView : GenericPullRequestListView, IHasDetailView, IHasCreationView { readonly Subject<ViewWithData> open = new Subject<ViewWithData>(); readonly Subject<ViewWithData> create = new Subject<ViewWithData>(); public PullRequestListView() { InitializeComponent(); OpenPR = new RelayCommand(x => { NotifyOpen(new ViewWithData { Data = x }); }); CreatePR = new RelayCommand(x => NotifyCreate()); this.WhenActivated(d => { }); } public IObservable<ViewWithData> Open { get { return open; } } public IObservable<ViewWithData> Create { get { return create; } } public ICommand OpenPR { get; set; } public ICommand CreatePR { get; set; } protected void NotifyOpen(ViewWithData id) { open.OnNext(id); } protected void NotifyCreate() { create.OnNext(null); } bool disposed; protected override void Dispose(bool disposing) { base.Dispose(disposing); if (disposing) { if (disposed) return; open.Dispose(); create.Dispose(); disposed = true; } } } }
using System; using GitHub.Exports; using GitHub.Extensions; using GitHub.UI; using GitHub.ViewModels; using ReactiveUI; using System.ComponentModel.Composition; using System.Reactive.Subjects; using System.Windows.Input; using GitHub.Services; using GitHub.Primitives; namespace GitHub.VisualStudio.UI.Views { public class GenericPullRequestListView : SimpleViewUserControl<IPullRequestListViewModel, PullRequestListView> { } [ExportView(ViewType = UIViewType.PRList)] [PartCreationPolicy(CreationPolicy.NonShared)] public partial class PullRequestListView : GenericPullRequestListView, IHasDetailView, IHasCreationView { readonly Subject<ViewWithData> open = new Subject<ViewWithData>(); readonly Subject<ViewWithData> create = new Subject<ViewWithData>(); public PullRequestListView() { InitializeComponent(); OpenPR = new RelayCommand(x => { NotifyOpen(new ViewWithData { Data = x }); }); CreatePR = new RelayCommand(x => NotifyCreate()); this.WhenActivated(d => { }); } public IObservable<ViewWithData> Open { get { return open; } } public IObservable<ViewWithData> Create { get { return create; } } public ICommand OpenPR { get; set; } public ICommand CreatePR { get; set; } protected void NotifyOpen(ViewWithData id) { open.OnNext(id); open.OnCompleted(); } protected void NotifyCreate() { create.OnNext(null); } bool disposed; protected override void Dispose(bool disposing) { base.Dispose(disposing); if (disposing) { if (disposed) return; open.Dispose(); create.Dispose(); disposed = true; } } } }
mit
C#
8ee5c2ebbfdb058d3d665abc06a920e5cbabbff4
Remove unnecessary code
gigya/microdot
Gigya.Microdot.Hosting/Validators/ConfigObjectTypeValidator.cs
Gigya.Microdot.Hosting/Validators/ConfigObjectTypeValidator.cs
#region Copyright // Copyright 2017 Gigya Inc. 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 // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Gigya.Common.Contracts.Exceptions; using Gigya.Microdot.Interfaces; using Gigya.Microdot.Interfaces.Configuration; namespace Gigya.Microdot.Hosting.Validators { public class ConfigObjectTypeValidator : IValidator { private IAssemblyProvider _assemblyProvider; public ConfigObjectTypeValidator(IAssemblyProvider assemblyProvider) { _assemblyProvider = assemblyProvider; } public void Validate() { List<Type> configValueTypes = _assemblyProvider.GetAllTypes().Where(t => t.GetTypeInfo().ImplementedInterfaces.Any(i => i == typeof(IConfigObject) && t.GetTypeInfo().IsValueType)).ToList(); if (configValueTypes.Count == 0) { return; } throw new ProgrammaticException( $"The type/s {string.Join(", ", configValueTypes.Select(t => t.Name))} are value types and cannot implement IConfigObject interfaces"); } } }
#region Copyright // Copyright 2017 Gigya Inc. 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 // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Gigya.Common.Contracts.Exceptions; using Gigya.Microdot.Interfaces; using Gigya.Microdot.Interfaces.Configuration; namespace Gigya.Microdot.Hosting.Validators { public class ConfigObjectTypeValidator : IValidator { private IAssemblyProvider _assemblyProvider; public ConfigObjectTypeValidator(IAssemblyProvider assemblyProvider) { _assemblyProvider = assemblyProvider; } public void Validate() { List<Type> configValueTypes = _assemblyProvider.GetAllTypes().Where(t => t.GetTypeInfo().ImplementedInterfaces.Any(i => i == typeof(IConfigObject) && t.GetTypeInfo().IsValueType)).ToList(); if (configValueTypes.Count == 0) { return; } IEnumerable<Type> valueTypes = configValueTypes.Where(t => t.GetTypeInfo().IsValueType); if (valueTypes.Any()) { throw new ProgrammaticException( $"The type/s {string.Join(", ", valueTypes.Select(t => t.Name))} are value types and cannot implement IConfigObject interfaces"); } } } }
apache-2.0
C#
adb0bb63783513ea644a87df40494819bb21808c
Add finished version
ahockersten/ScrollsKeepChatOpen
KeepChatOpen.mod/KeepChatOpen.cs
KeepChatOpen.mod/KeepChatOpen.cs
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using ScrollsModLoader.Interfaces; using UnityEngine; using Mono.Cecil; // FIXME check existence of methods, private variables etc and fail gracefully! namespace KeepChatOpen.mod { public class KeepChatOpen : BaseMod { private bool debug = false; public KeepChatOpen() { } public static string GetName() { return "KeepChatOpen"; } public static int GetVersion() { return 1; } public static MethodDefinition[] GetHooks(TypeDefinitionCollection scrollsTypes, int version) { try { return new MethodDefinition[] { scrollsTypes["ChatUI"].Methods.GetMethod("Show", new Type[]{typeof(bool)}) }; } catch { Console.WriteLine("KeepChatOpen failed to connect to methods used."); return new MethodDefinition[] { }; } } public override bool BeforeInvoke(InvocationInfo info, out object returnValue) { returnValue = null; if (info.target is ChatUI && info.targetMethod.Equals("Show")) { foreach (StackFrame frame in info.stackTrace.GetFrames()) { // Disallow all except for: // ChatUI.OnGUI() - this gets called when the user clicks the open/close button // Lobby.Start() - this gets called when the user moves to the "arena" tab if ((frame.GetMethod().ReflectedType.Equals(typeof(ChatUI)) && frame.GetMethod().Name.Contains("OnGUI")) || (frame.GetMethod().ReflectedType.Equals(typeof(Lobby)) && frame.GetMethod().Name.Contains("Start"))) { return false; } } return true; } return false; } public override void AfterInvoke(InvocationInfo info, ref object returnValue) { return; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using System.Text.RegularExpressions; using ScrollsModLoader.Interfaces; using UnityEngine; using Mono.Cecil; // FIXME check existence of methods, private variables etc and fail gracefully! namespace KeepChatOpen.mod { public class KeepChatOpen : BaseMod { private bool debug = false; public KeepChatOpen() { } public static string GetName() { return "KeepChatOpen"; } public static int GetVersion() { return 1; } public static MethodDefinition[] GetHooks(TypeDefinitionCollection scrollsTypes, int version) { return new MethodDefinition[] { }; } public override bool BeforeInvoke(InvocationInfo info, out object returnValue) { returnValue = null; return false; } public override void AfterInvoke(InvocationInfo info, ref object returnValue) { return; } } }
bsd-2-clause
C#
e39da830a059d134082ea2cf6736cb1061b1c830
Fix VirtualTree.GetDescendants method
jasonmcboyd/Treenumerable
Source/Treenumerable/VirtualTree/VirtualTree.GetDescendants.cs
Source/Treenumerable/VirtualTree/VirtualTree.GetDescendants.cs
using System; using System.Collections.Generic; namespace Treenumerable { public partial struct VirtualTree<T> { public VirtualTreeEnumerable<T> GetDescendants(Func<T, bool> predicate) { return this .TreeWalker .GetDescendants(this.Root, predicate) .ToVirtualTrees(this) .AsVirtualTreeEnumerable(); } public VirtualTreeEnumerable<T> GetDescendants(Func<T, int, bool> predicate) { return this .TreeWalker .GetDescendants(this.Root, predicate) .ToVirtualTrees(this) .AsVirtualTreeEnumerable(); } public VirtualTreeEnumerable<T> GetDescendants(T key) { return this .TreeWalker .GetDescendants(this.Root, key, this.Comparer) .ToVirtualTrees(this) .AsVirtualTreeEnumerable(); } public VirtualTreeEnumerable<T> GetDescendants(T key, IEqualityComparer<T> comparer) { return this .TreeWalker .GetDescendants(this.Root, key, comparer) .ToVirtualTrees(this) .AsVirtualTreeEnumerable(); } } }
using System; using System.Collections.Generic; namespace Treenumerable { public partial struct VirtualTree<T> { public VirtualTreeEnumerable<T> GetDescendants(Func<T, bool> predicate) { return this .TreeWalker .GetDescendants(this.Root, predicate) .ToVirtualTrees(this) .AsVirtualTreeEnumerable(); } public VirtualTreeEnumerable<T> GetDescendants(Func<T, int, bool> predicate) { return this .TreeWalker .GetDescendants(this.Root, predicate) .ToVirtualTrees(this) .AsVirtualTreeEnumerable(); } public VirtualTreeEnumerable<T> GetDescendants(T key) { return this .TreeWalker .GetDescendants(this.Root, key) .ToVirtualTrees(this) .AsVirtualTreeEnumerable(); } public VirtualTreeEnumerable<T> GetDescendants(T key, IEqualityComparer<T> comparer) { return this .TreeWalker .GetDescendants(this.Root, key, comparer) .ToVirtualTrees(this) .AsVirtualTreeEnumerable(); } } }
mit
C#
6012b8fe8c41e4511d8c23c7d95b6449b640f324
Swap build and revision numbers in PackageReader
mtrinder/Xamarin.Plugins
Version/Version/Version.Plugin.WindowsPhone81/PackageReader.cs
Version/Version/Version.Plugin.WindowsPhone81/PackageReader.cs
using System; using Windows.ApplicationModel; namespace Version.Plugin { internal class PackageReader { public static string GetAppVersion() { try { var pv = Package.Current.Id.Version; return string.Format("{0}.{1}.{2}.{3}", pv.Major, pv.Minor, pv.Build, pv.Revision); } catch { return string.Empty; } } } }
using System; using Windows.ApplicationModel; namespace Version.Plugin { internal class PackageReader { public static string GetAppVersion() { try { var pv = Package.Current.Id.Version; return string.Format("{0}.{1}.{2}.{3}", pv.Major, pv.Minor, pv.Revision, pv.Build); } catch { return string.Empty; } } } }
mit
C#
a66a51ac195581a2982c1caab11e9880ba1d6b36
fix build warning
Code-Inside/Sloader
tests/Sloader.Tests/MasterCrawlerConfigTests/TwitterTimelineConfigTests.cs
tests/Sloader.Tests/MasterCrawlerConfigTests/TwitterTimelineConfigTests.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Sloader.Shared; using Xunit; using YamlDotNet.Serialization; namespace Sloader.Tests.MasterCrawlerConfigTests { public class TwitterTimelineConfigTests { [Fact] public void Handle_Is_Identifier() { StringBuilder fakeYaml = new StringBuilder(); fakeYaml.AppendLine("TwitterTimelinesToCrawl:"); fakeYaml.AppendLine("- Handle: codeinsideblog"); var deserializer = new Deserializer(); var result = deserializer.Deserialize<MasterCrawlerConfig>(new StringReader(fakeYaml.ToString())); var configValue = result.TwitterTimelinesToCrawl.First(); Assert.Equal("codeinsideblog", configValue.ResultIdentifier); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Sloader.Shared; using Xunit; using YamlDotNet.Serialization; namespace Sloader.Tests.MasterCrawlerConfigTests { public class TwitterTimelineConfigTests { [Fact] public async Task Handle_Is_Identifier() { StringBuilder fakeYaml = new StringBuilder(); fakeYaml.AppendLine("TwitterTimelinesToCrawl:"); fakeYaml.AppendLine("- Handle: codeinsideblog"); var deserializer = new Deserializer(); var result = deserializer.Deserialize<MasterCrawlerConfig>(new StringReader(fakeYaml.ToString())); var configValue = result.TwitterTimelinesToCrawl.First(); Assert.Equal("codeinsideblog", configValue.ResultIdentifier); } } }
mit
C#
8c08114df49335fd00582745da190db32770cf21
Add overload for parsing event from byte[]
huysentruitw/win-beacon,ghkim69/win-beacon
src/WinBeacon/Stack/Hci/Event.cs
src/WinBeacon/Stack/Hci/Event.cs
/* * Copyright 2015 Huysentruit Wouter * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System.Collections.Generic; using WinBeacon.Stack.Hci.Events; namespace WinBeacon.Stack.Hci { /// <summary> /// Base class for Bluetooth events. /// </summary> public class Event { /// <summary> /// The event code. /// </summary> public EventCode Code { get; protected set; } /// <summary> /// Creates an event object. /// </summary> protected Event() { } /// <summary> /// Creates an event object with event code. /// </summary> protected Event(EventCode code) { Code = code; } internal static Event Parse(byte[] data) { return Parse(new Queue<byte>(data)); } internal static Event Parse(Queue<byte> data) { if (data.Count < 2) return null; EventCode code = (EventCode)data.Dequeue(); int payloadSize = data.Dequeue(); switch (code) { case EventCode.CommandComplete: return CommandCompleteEvent.Parse(code, data); case EventCode.LeMeta: return LeMetaEvent.Parse(code, data); default: return new Event(code); } } } }
/* * Copyright 2015 Huysentruit Wouter * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System.Collections.Generic; using WinBeacon.Stack.Hci.Events; namespace WinBeacon.Stack.Hci { /// <summary> /// Base class for Bluetooth events. /// </summary> public class Event { /// <summary> /// The event code. /// </summary> public EventCode Code { get; protected set; } /// <summary> /// Creates an event object. /// </summary> protected Event() { } /// <summary> /// Creates an event object with event code. /// </summary> protected Event(EventCode code) { Code = code; } internal static Event Parse(Queue<byte> data) { if (data.Count < 2) return null; EventCode code = (EventCode)data.Dequeue(); int payloadSize = data.Dequeue(); switch (code) { case EventCode.CommandComplete: return CommandCompleteEvent.Parse(code, data); case EventCode.LeMeta: return LeMetaEvent.Parse(code, data); default: return new Event(code); } } } }
mit
C#
3775ae350a5e11ca39f176c8bf19d760112f9408
Fix account lookup.
ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab
Anlab.Core/Models/AccountModel.cs
Anlab.Core/Models/AccountModel.cs
using System; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; namespace Anlab.Jobs.MoneyMovement { public class AccountModel { public AccountModel(string rawAccount) { var regx = Regex.Match(rawAccount, @"^(\w)-(\w{7})\/?(\w{5})?$"); Chart = regx.Groups[1].Value; Account = regx.Groups[2].Value; SubAccount = regx.Groups[3].Value; } public string Chart { get; set; } public string Account { get; set; } public string SubAccount { get; set; } } }
using System; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; namespace Anlab.Jobs.MoneyMovement { public class AccountModel { public AccountModel(string rawAccount) { var regx = Regex.Match(rawAccount, @"(\w)-(\w{7})\/?(\w{5})?"); Chart = regx.Groups[1].Value; Account = regx.Groups[2].Value; SubAccount = regx.Groups[3].Value; } public string Chart { get; set; } public string Account { get; set; } public string SubAccount { get; set; } } }
mit
C#
550bf9bd8e7f2681e415322b74ed8fb04c18b095
Update Vengeance.cs (#46)
BosslandGmbH/BuddyWing.DefaultCombat
trunk/DefaultCombat/Routines/Advanced/Juggernaut/Vengeance.cs
trunk/DefaultCombat/Routines/Advanced/Juggernaut/Vengeance.cs
// Copyright (C) 2011-2016 Bossland GmbH // See the file LICENSE for the source code's detailed license using Buddy.BehaviorTree; using DefaultCombat.Core; using DefaultCombat.Helpers; namespace DefaultCombat.Routines { internal class Vengeance : RotationBase { public override string Name { get { return "Juggernaut Vengeance"; } } public override Composite Buffs { get { return new PrioritySelector( Spell.Buff("Unnatural Might") ); } } public override Composite Cooldowns { get { return new PrioritySelector( Spell.Buff("Unleash", ret => Me.IsStunned), Spell.Buff("Enraged Defense", ret => Me.HealthPercent <= 70), Spell.Buff("Saber Reflect", ret => Me.HealthPercent <= 60), Spell.Buff("Saber Ward", ret => Me.HealthPercent <= 50), Spell.Buff("Endure Pain", ret => Me.HealthPercent <= 30), Spell.Buff("Enrage", ret => Me.ActionPoints <= 6) ); } } public override Composite SingleTarget { get { return new PrioritySelector( Spell.Cast("Saber Throw", ret => !DefaultCombat.MovementDisabled && Me.CurrentTarget.Distance >= 0.5f && Me.CurrentTarget.Distance <= 3f), Spell.Cast("Force Charge", ret => !DefaultCombat.MovementDisabled && Me.CurrentTarget.Distance >= 1f && Me.CurrentTarget.Distance <= 3f), //Movement CombatMovement.CloseDistance(Distance.Melee), //Rotation Spell.Cast("Disruption", ret => Me.CurrentTarget.IsCasting && !DefaultCombat.MovementDisabled), Spell.Cast("Force Scream", ret => Me.BuffCount("Savagery") == 2), Spell.Cast("Hew", ret => Me.HasBuff("Destroyer") || Me.CurrentTarget.HealthPercent <= 30), Spell.Cast("Shatter"), Spell.Cast("Impale"), Spell.Cast("Sundering Assault", ret => Me.ActionPoints <= 7), Spell.Cast("Ravage"), Spell.Cast("Vicious Slash", ret => Me.ActionPoints >= 11), Spell.Cast("Assault"), Spell.Cast("Retaliation") ); } } public override Composite AreaOfEffect { get { return new Decorator(ret => Targeting.ShouldPbaoe, new PrioritySelector( Spell.Cast("Vengeful Slam"), Spell.Cast("Smash"), Spell.Cast("Sweeping Slash") )); } } } }
// Copyright (C) 2011-2016 Bossland GmbH // See the file LICENSE for the source code's detailed license using Buddy.BehaviorTree; using DefaultCombat.Core; using DefaultCombat.Helpers; namespace DefaultCombat.Routines { internal class Vengeance : RotationBase { public override string Name { get { return "Juggernaut Vengeance"; } } public override Composite Buffs { get { return new PrioritySelector( Spell.Buff("Shien Form"), Spell.Buff("Unnatural Might") ); } } public override Composite Cooldowns { get { return new PrioritySelector( Spell.Buff("Unleash", ret => Me.IsStunned), Spell.Buff("Enraged Defense", ret => Me.HealthPercent <= 70), Spell.Buff("Saber Reflect", ret => Me.HealthPercent <= 60), Spell.Buff("Saber Ward", ret => Me.HealthPercent <= 50), Spell.Buff("Endure Pain", ret => Me.HealthPercent <= 30), Spell.Buff("Enrage", ret => Me.ActionPoints <= 6) ); } } public override Composite SingleTarget { get { return new PrioritySelector( Spell.Cast("Saber Throw", ret => !DefaultCombat.MovementDisabled && Me.CurrentTarget.Distance >= 0.5f && Me.CurrentTarget.Distance <= 3f), Spell.Cast("Force Charge", ret => !DefaultCombat.MovementDisabled && Me.CurrentTarget.Distance >= 1f && Me.CurrentTarget.Distance <= 3f), //Movement CombatMovement.CloseDistance(Distance.Melee), //Rotation Spell.Cast("Disruption", ret => Me.CurrentTarget.IsCasting && !DefaultCombat.MovementDisabled), Spell.Cast("Force Scream", ret => Me.BuffCount("Savagery") == 2), Spell.Cast("Vicious Throw", ret => Me.HasBuff("Destroyer") || Me.CurrentTarget.HealthPercent <= 30), Spell.Cast("Shatter"), Spell.Cast("Impale"), Spell.Cast("Sundering Assault", ret => Me.ActionPoints <= 7), Spell.Cast("Ravage"), Spell.Cast("Vicious Slash", ret => Me.ActionPoints >= 11), Spell.Cast("Assault"), Spell.Cast("Retaliation") ); } } public override Composite AreaOfEffect { get { return new Decorator(ret => Targeting.ShouldPbaoe, new PrioritySelector( Spell.Cast("Vengeful Slam"), Spell.Cast("Smash"), Spell.Cast("Sweeping Slash") )); } } } }
apache-2.0
C#
80cce7c3cb1d5c840ec6bbb599a3bcdf3baf1e17
Add failing test case
NeoAdonis/osu,peppy/osu,ppy/osu,ppy/osu,ppy/osu,NeoAdonis/osu,peppy/osu,peppy/osu,NeoAdonis/osu
osu.Game.Tests/Visual/Editing/TestSceneComposeScreen.cs
osu.Game.Tests/Visual/Editing/TestSceneComposeScreen.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Linq; using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Extensions.ObjectExtensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Testing; using osu.Game.Rulesets.Edit; using osu.Game.Rulesets.Osu; using osu.Game.Rulesets.Osu.Beatmaps; using osu.Game.Screens.Edit; using osu.Game.Screens.Edit.Compose; using osu.Game.Skinning; namespace osu.Game.Tests.Visual.Editing { [TestFixture] public class TestSceneComposeScreen : EditorClockTestScene { private EditorBeatmap editorBeatmap; [Cached] private EditorClipboard clipboard = new EditorClipboard(); [SetUpSteps] public void SetUpSteps() { AddStep("setup compose screen", () => { var beatmap = new OsuBeatmap { BeatmapInfo = { Ruleset = new OsuRuleset().RulesetInfo } }; editorBeatmap = new EditorBeatmap(beatmap, new LegacyBeatmapSkin(beatmap.BeatmapInfo, null)); Beatmap.Value = CreateWorkingBeatmap(editorBeatmap.PlayableBeatmap); Child = new DependencyProvidingContainer { RelativeSizeAxes = Axes.Both, CachedDependencies = new (Type, object)[] { (typeof(EditorBeatmap), editorBeatmap), (typeof(IBeatSnapProvider), editorBeatmap), }, Child = new ComposeScreen { State = { Value = Visibility.Visible } }, }; }); AddUntilStep("wait for composer", () => this.ChildrenOfType<HitObjectComposer>().SingleOrDefault()?.IsLoaded == true); } /// <summary> /// Ensures that the skin of the edited beatmap is properly wrapped in a <see cref="LegacySkinTransformer"/>. /// </summary> [Test] public void TestLegacyBeatmapSkinHasTransformer() { AddAssert("legacy beatmap skin has transformer", () => { var sources = this.ChildrenOfType<BeatmapSkinProvidingContainer>().First().AllSources; return sources.OfType<LegacySkinTransformer>().Count(t => t.Skin == editorBeatmap.BeatmapSkin.AsNonNull().Skin) == 1; }); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Graphics.Containers; using osu.Game.Rulesets.Edit; using osu.Game.Rulesets.Osu; using osu.Game.Rulesets.Osu.Beatmaps; using osu.Game.Screens.Edit; using osu.Game.Screens.Edit.Compose; namespace osu.Game.Tests.Visual.Editing { [TestFixture] public class TestSceneComposeScreen : EditorClockTestScene { [Cached(typeof(EditorBeatmap))] [Cached(typeof(IBeatSnapProvider))] private readonly EditorBeatmap editorBeatmap = new EditorBeatmap(new OsuBeatmap { BeatmapInfo = { Ruleset = new OsuRuleset().RulesetInfo } }); [Cached] private EditorClipboard clipboard = new EditorClipboard(); protected override void LoadComplete() { base.LoadComplete(); Beatmap.Value = CreateWorkingBeatmap(editorBeatmap.PlayableBeatmap); Child = new ComposeScreen { State = { Value = Visibility.Visible }, }; } } }
mit
C#
e193f8214df514f770d3bcad9ef41ce053255ed8
Remove unnecessary room id from leave room request
smoogipooo/osu,smoogipoo/osu,peppy/osu,smoogipoo/osu,UselessToucan/osu,NeoAdonis/osu,NeoAdonis/osu,peppy/osu-new,ppy/osu,UselessToucan/osu,ppy/osu,ppy/osu,NeoAdonis/osu,peppy/osu,smoogipoo/osu,UselessToucan/osu,peppy/osu
osu.Game/Online/RealtimeMultiplayer/ISpectatorServer.cs
osu.Game/Online/RealtimeMultiplayer/ISpectatorServer.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Threading.Tasks; namespace osu.Game.Online.RealtimeMultiplayer { /// <summary> /// An interface defining the spectator server instance. /// </summary> public interface IMultiplayerServer { /// <summary> /// Request to join a multiplayer room. /// </summary> /// <param name="roomId">The databased room ID.</param> /// <returns>Whether the room could be joined.</returns> Task<bool> JoinRoom(long roomId); /// <summary> /// Request to leave the currently joined room. /// </summary> Task LeaveRoom(); } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Threading.Tasks; namespace osu.Game.Online.RealtimeMultiplayer { /// <summary> /// An interface defining the spectator server instance. /// </summary> public interface IMultiplayerServer { /// <summary> /// Request to join a multiplayer room. /// </summary> /// <param name="roomId">The databased room ID.</param> /// <returns>Whether the room could be joined.</returns> Task<bool> JoinRoom(long roomId); /// <summary> /// Request to leave the currently joined room. /// </summary> /// <param name="roomId">The databased room ID.</param> Task LeaveRoom(long roomId); } }
mit
C#
91c071c7a2232d61573e8606235b078be5422976
fix AssemblyInfo
YSRKEN/Shioi,YSRKEN/Shioi,YSRKEN/Shioi
Shioi/Properties/AssemblyInfo.cs
Shioi/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // アセンブリに関する一般情報は以下の属性セットをとおして制御されます。 // アセンブリに関連付けられている情報を変更するには、 // これらの属性値を変更してください。 [assembly: AssemblyTitle("Renju player and solver by C++ and C#")] [assembly: AssemblyDescription("Renju player and solver by C++ and C#")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Shioi")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから // 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、 // その型の ComVisible 属性を true に設定してください。 [assembly: ComVisible(false)] // このプロジェクトが COM に公開される場合、次の GUID が typelib の ID になります [assembly: Guid("1ba7c4a7-2884-4824-9336-1994d222af32")] // アセンブリのバージョン情報は次の 4 つの値で構成されています: // // メジャー バージョン // マイナー バージョン // ビルド番号 // Revision // // すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を // 既定値にすることができます: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.2.0")] [assembly: AssemblyFileVersion("0.2.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // アセンブリに関する一般情報は以下の属性セットをとおして制御されます。 // アセンブリに関連付けられている情報を変更するには、 // これらの属性値を変更してください。 [assembly: AssemblyTitle("Renju player and solver by C++ and C#")] [assembly: AssemblyDescription("Renju player and solver by C++ and C#")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Shioi")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから // 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、 // その型の ComVisible 属性を true に設定してください。 [assembly: ComVisible(false)] // このプロジェクトが COM に公開される場合、次の GUID が typelib の ID になります [assembly: Guid("1ba7c4a7-2884-4824-9336-1994d222af32")] // アセンブリのバージョン情報は次の 4 つの値で構成されています: // // メジャー バージョン // マイナー バージョン // ビルド番号 // Revision // // すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を // 既定値にすることができます: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.1.0")] [assembly: AssemblyFileVersion("0.1.0")]
mit
C#
25001e7e22d8a0ecdc9f27e6c2a0434f2ed47f64
implement DefineShape4Tag writing
Alexx999/SwfSharp
SwfSharp/Tags/DefineShape4Tag.cs
SwfSharp/Tags/DefineShape4Tag.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using SwfSharp.Structs; using SwfSharp.Utils; namespace SwfSharp.Tags { public class DefineShape4Tag : DefineShape3Tag { public RectStruct EdgeBounds { get; set; } public bool UsesFillWindingRule { get; set; } public bool UsesNonScalingStrokes { get; set; } public bool UsesScalingStrokes { get; set; } public DefineShape4Tag(int size) : base(TagType.DefineShape4, size) { } internal override void FromStream(BitReader reader, byte swfVersion) { ShapeId = reader.ReadUI16(); ShapeBounds = RectStruct.CreateFromStream(reader); EdgeBounds = RectStruct.CreateFromStream(reader); reader.ReadBits(5); UsesFillWindingRule = reader.ReadBoolBit(); UsesNonScalingStrokes = reader.ReadBoolBit(); UsesScalingStrokes = reader.ReadBoolBit(); Shapes = ShapeWithStyleStruct.CreateFromStream(reader, TagType); } internal override void ToStream(BitWriter writer, byte swfVersion) { writer.WriteUI16(ShapeId); ShapeBounds.ToStream(writer); EdgeBounds.ToStream(writer); writer.WriteBits(5, 0); writer.WriteBoolBit(UsesFillWindingRule); writer.WriteBoolBit(UsesNonScalingStrokes); writer.WriteBoolBit(UsesScalingStrokes); Shapes.ToStream(writer, TagType); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using SwfSharp.Structs; using SwfSharp.Utils; namespace SwfSharp.Tags { public class DefineShape4Tag : DefineShape3Tag { public RectStruct EdgeBounds { get; set; } public bool UsesFillWindingRule { get; set; } public bool UsesNonScalingStrokes { get; set; } public bool UsesScalingStrokes { get; set; } public DefineShape4Tag(int size) : base(TagType.DefineShape4, size) { } internal override void FromStream(BitReader reader, byte swfVersion) { ShapeId = reader.ReadUI16(); ShapeBounds = RectStruct.CreateFromStream(reader); EdgeBounds = RectStruct.CreateFromStream(reader); reader.ReadBits(5); UsesFillWindingRule = reader.ReadBoolBit(); UsesNonScalingStrokes = reader.ReadBoolBit(); UsesScalingStrokes = reader.ReadBoolBit(); Shapes = ShapeWithStyleStruct.CreateFromStream(reader, TagType); } } }
mit
C#
280a8cfedeaa19e26e7b57a72a1295ad9ca90b5b
Fix integration test by using correct traversal source TINKREPOP-1836
apache/tinkerpop,krlohnes/tinkerpop,pluradj/incubator-tinkerpop,robertdale/tinkerpop,apache/incubator-tinkerpop,apache/tinkerpop,apache/incubator-tinkerpop,apache/incubator-tinkerpop,robertdale/tinkerpop,krlohnes/tinkerpop,apache/tinkerpop,krlohnes/tinkerpop,apache/tinkerpop,krlohnes/tinkerpop,apache/tinkerpop,apache/tinkerpop,pluradj/incubator-tinkerpop,krlohnes/tinkerpop,robertdale/tinkerpop,apache/tinkerpop,pluradj/incubator-tinkerpop,robertdale/tinkerpop,robertdale/tinkerpop
gremlin-dotnet/test/Gremlin.Net.Template.IntegrationTest/ServiceTests.cs
gremlin-dotnet/test/Gremlin.Net.Template.IntegrationTest/ServiceTests.cs
#region License /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 using System.Collections.Generic; using Gremlin.Net.Driver; using Gremlin.Net.Driver.Remote; using Gremlin.Net.Structure; using Xunit; namespace Gremlin.Net.Template.IntegrationTest { public class ServiceTests { private const string TestHost = "localhost"; private const int TestPort = 45940; private const string TestTraversalSource = "gmodern"; [Fact] public void ShouldReturnExpectedCreators() { using (var client = CreateClient()) { var g = new Graph().Traversal().WithRemote(new DriverRemoteConnection(client, TestTraversalSource)); var service = new Service(g); var creators = service.FindCreatorsOfSoftware("lop"); Assert.Equal(new List<string> {"marko", "josh", "peter"}, creators); } } private static IGremlinClient CreateClient() { return new GremlinClient(new GremlinServer(TestHost, TestPort)); } } }
#region License /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 using System.Collections.Generic; using Gremlin.Net.Driver; using Gremlin.Net.Driver.Remote; using Gremlin.Net.Structure; using Xunit; namespace Gremlin.Net.Template.IntegrationTest { public class ServiceTests { private const string TestHost = "localhost"; private const int TestPort = 45940; [Fact] public void ShouldReturnExpectedCreators() { using (var client = CreateClient()) { var g = new Graph().Traversal().WithRemote(new DriverRemoteConnection(client)); var service = new Service(g); var creators = service.FindCreatorsOfSoftware("lop"); Assert.Equal(new List<string> {"marko", "josh", "peter"}, creators); } } private static IGremlinClient CreateClient() { return new GremlinClient(new GremlinServer(TestHost, TestPort)); } } }
apache-2.0
C#
a601abdaafc7382f87a5942740353ca32c1b4f86
Set version to 1.2.2-master
PerfectXL/XLParser,PerfectXL/XLParser,PerfectXL/XLParser
src/XLParser/Properties/AssemblyInfo.cs
src/XLParser/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("XLParser")] [assembly: AssemblyDescription("A parser for Excel formulas")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("TU Delft Spreadsheet Lab, Infotron")] [assembly: AssemblyProduct("XLParser")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("6d8981be-e2fd-424c-85ac-c7adbbf96604")] // 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.*")] // Free form tag, use the version tag from git [assembly: AssemblyInformationalVersion("1.2.2-master")] // This is what other developers reference. As such this should change at breaking changes, but not otherwise // so use major.minor.0.0, but only bump minor if there's a breaking change (and at that point you should consider bumping major) [assembly: AssemblyVersion("1.2.0.0")] // This isn't used by .NET but requires the 4-number format, use major.minor.patch.0 [assembly: AssemblyFileVersion("1.2.2.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("XLParser")] [assembly: AssemblyDescription("A parser for Excel formulas")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("TU Delft Spreadsheet Lab, Infotron")] [assembly: AssemblyProduct("XLParser")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("6d8981be-e2fd-424c-85ac-c7adbbf96604")] // 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.*")] // Free form tag, use the version tag from git [assembly: AssemblyInformationalVersion("1.2.1")] // This is what other developers reference. As such this should change at breaking changes, but not otherwise // so use major.minor.0.0 [assembly: AssemblyVersion("1.2.0.0")] // This isn't used by .NET but requires the 4-number format, use major.minor.patch.0 [assembly: AssemblyFileVersion("1.2.0.0")]
mpl-2.0
C#
9602a5fa52e66bfdd2daa9c53d2cc6fc00ce96ef
Add auth handling
mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander
Battery-Commander.Web/Models/Reports/Green3_SensitiveItems.cs
Battery-Commander.Web/Models/Reports/Green3_SensitiveItems.cs
using System; using System.Linq; namespace BatteryCommander.Web.Models.Reports { public class Green3_SensitiveItems : Report { public Green3_SensitiveItems(Unit unit) : base(unit) { // Nothing to do here } // HACK: Make this configurable for a specific user public String Authentication => Unit.ReportSettings.SingleOrDefault(settings => settings.Type == Type)?.From.Name; // You damn well better have a Green status public String Status => "GREEN"; public override ReportType Type => ReportType.Sensitive_Items; } }
using System; namespace BatteryCommander.Web.Models.Reports { public class Green3_SensitiveItems : Report { public Green3_SensitiveItems(Unit unit) : base(unit) { // Nothing to do here } // HACK: Make this configurable for a specific user public String Authentication => "1LT MW"; // You damn well better have a Green status public String Status => "GREEN"; public override ReportType Type => ReportType.Sensitive_Items; } }
mit
C#
02188fe727e632855e1804960c65995076e01366
Add some missing headers to generated .vcproj file.
lewissbaker/cppcoro,lewissbaker/cppcoro,lewissbaker/cppcoro,lewissbaker/cppcoro
lib/build.cake
lib/build.cake
############################################################################### # Copyright Lewis Baker # Licenced under MIT license. See LICENSE.txt for details. ############################################################################### import cake.path from cake.tools import compiler, script, env, project includes = cake.path.join(env.expand('${CPPCORO}'), 'include', 'cppcoro', [ 'async_mutex.hpp', 'broken_promise.hpp', 'lazy_task.hpp', 'single_consumer_event.hpp', 'task.hpp', ]) sources = script.cwd([ 'async_mutex.cpp', ]) extras = script.cwd([ 'build.cake', 'use.cake', ]) buildDir = env.expand('${CPPCORO_BUILD}') compiler.addIncludePath(env.expand('${CPPCORO}/include')) objects = compiler.objects( targetDir=env.expand('${CPPCORO_BUILD}/obj'), sources=sources, ) lib = compiler.library( target=env.expand('${CPPCORO_LIB}/cppcoro'), sources=objects, ) vcproj = project.project( target=env.expand('${CPPCORO_PROJECT}/cppcoro'), items={ 'Include': includes, 'Source': sources, '': extras }, output=lib, ) script.setResult( project=vcproj, library=lib, )
############################################################################### # Copyright Lewis Baker # Licenced under MIT license. See LICENSE.txt for details. ############################################################################### import cake.path from cake.tools import compiler, script, env, project includes = cake.path.join(env.expand('${CPPCORO}'), 'include', 'cppcoro', [ 'broken_promise.hpp', 'task.hpp', 'single_consumer_event.hpp', ]) sources = script.cwd([ 'async_mutex.cpp', ]) extras = script.cwd([ 'build.cake', 'use.cake', ]) buildDir = env.expand('${CPPCORO_BUILD}') compiler.addIncludePath(env.expand('${CPPCORO}/include')) objects = compiler.objects( targetDir=env.expand('${CPPCORO_BUILD}/obj'), sources=sources, ) lib = compiler.library( target=env.expand('${CPPCORO_LIB}/cppcoro'), sources=objects, ) vcproj = project.project( target=env.expand('${CPPCORO_PROJECT}/cppcoro'), items={ 'Include': includes, 'Source': sources, '': extras }, output=lib, ) script.setResult( project=vcproj, library=lib, )
mit
C#
ad5bd1f0c00ae10c0c857759e38b1f588d2f4b45
Update in line with other/unspecified switch
peppy/osu,UselessToucan/osu,UselessToucan/osu,smoogipoo/osu,peppy/osu-new,smoogipoo/osu,ppy/osu,NeoAdonis/osu,UselessToucan/osu,NeoAdonis/osu,smoogipooo/osu,NeoAdonis/osu,peppy/osu,ppy/osu,ppy/osu,peppy/osu,smoogipoo/osu
osu.Game/Overlays/BeatmapListing/SearchLanguage.cs
osu.Game/Overlays/BeatmapListing/SearchLanguage.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Game.Utils; namespace osu.Game.Overlays.BeatmapListing { [HasOrderedElements] public enum SearchLanguage { [Order(0)] Any, [Order(14)] Unspecified, [Order(1)] English, [Order(6)] Japanese, [Order(2)] Chinese, [Order(12)] Instrumental, [Order(7)] Korean, [Order(3)] French, [Order(4)] German, [Order(9)] Swedish, [Order(8)] Spanish, [Order(5)] Italian, [Order(10)] Russian, [Order(11)] Polish, [Order(13)] Other } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Game.Utils; namespace osu.Game.Overlays.BeatmapListing { [HasOrderedElements] public enum SearchLanguage { [Order(0)] Any, [Order(13)] Other, [Order(1)] English, [Order(6)] Japanese, [Order(2)] Chinese, [Order(12)] Instrumental, [Order(7)] Korean, [Order(3)] French, [Order(4)] German, [Order(9)] Swedish, [Order(8)] Spanish, [Order(5)] Italian, [Order(10)] Russian, [Order(11)] Polish, [Order(14)] Unspecified } }
mit
C#
265a89e5cc778e5c7054f566bdcaba16d61bf3a6
Fix `LegacySkinPlayerTestScene` overriden by default beatmap skin
ppy/osu,peppy/osu,smoogipoo/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu-new,smoogipoo/osu,smoogipooo/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu,NeoAdonis/osu,UselessToucan/osu,ppy/osu,peppy/osu,smoogipoo/osu,ppy/osu
osu.Game/Tests/Visual/LegacySkinPlayerTestScene.cs
osu.Game/Tests/Visual/LegacySkinPlayerTestScene.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Linq; using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Audio; using osu.Framework.IO.Stores; using osu.Framework.Testing; using osu.Framework.Timing; using osu.Game.Beatmaps; using osu.Game.Rulesets; using osu.Game.Skinning; using osu.Game.Storyboards; namespace osu.Game.Tests.Visual { [TestFixture] public abstract class LegacySkinPlayerTestScene : PlayerTestScene { private ISkinSource legacySkinSource; protected override TestPlayer CreatePlayer(Ruleset ruleset) => new SkinProvidingPlayer(legacySkinSource); protected override WorkingBeatmap CreateWorkingBeatmap(IBeatmap beatmap, Storyboard storyboard = null) => new LegacySkinWorkingBeatmap(beatmap, storyboard, Clock, Audio); [BackgroundDependencyLoader] private void load(OsuGameBase game, SkinManager skins) { var legacySkin = new DefaultLegacySkin(new NamespacedResourceStore<byte[]>(game.Resources, "Skins/Legacy"), skins); legacySkinSource = new SkinProvidingContainer(legacySkin); } public override void SetUpSteps() { base.SetUpSteps(); // check presence of a random legacy HUD component to ensure this is using legacy skin. AddAssert("using legacy skin", () => this.ChildrenOfType<LegacyScoreCounter>().Any()); } public class SkinProvidingPlayer : TestPlayer { [Cached(typeof(ISkinSource))] private readonly ISkinSource skinSource; public SkinProvidingPlayer(ISkinSource skinSource) { this.skinSource = skinSource; } } private class LegacySkinWorkingBeatmap : ClockBackedTestWorkingBeatmap { public LegacySkinWorkingBeatmap(IBeatmap beatmap, Storyboard storyboard, IFrameBasedClock frameBasedClock, AudioManager audio) : base(beatmap, storyboard, frameBasedClock, audio) { } protected override ISkin GetSkin() => new LegacyBeatmapSkin(BeatmapInfo, null, null); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.IO.Stores; using osu.Game.Rulesets; using osu.Game.Skinning; namespace osu.Game.Tests.Visual { [TestFixture] public abstract class LegacySkinPlayerTestScene : PlayerTestScene { private ISkinSource legacySkinSource; protected override TestPlayer CreatePlayer(Ruleset ruleset) => new SkinProvidingPlayer(legacySkinSource); [BackgroundDependencyLoader] private void load(OsuGameBase game, SkinManager skins) { var legacySkin = new DefaultLegacySkin(new NamespacedResourceStore<byte[]>(game.Resources, "Skins/Legacy"), skins); legacySkinSource = new SkinProvidingContainer(legacySkin); } public class SkinProvidingPlayer : TestPlayer { [Cached(typeof(ISkinSource))] private readonly ISkinSource skinSource; public SkinProvidingPlayer(ISkinSource skinSource) { this.skinSource = skinSource; } } } }
mit
C#
1017cce748ce840052f786e598165ec1e3a575cb
Remove duplicated license header
ppy/osu-framework,peppy/osu-framework,ppy/osu-framework,ppy/osu-framework,ZLima12/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,peppy/osu-framework,smoogipooo/osu-framework
osu.Framework/Bindables/BindableNumberWithCurrent.cs
osu.Framework/Bindables/BindableNumberWithCurrent.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Graphics.UserInterface; namespace osu.Framework.Bindables { /// <summary> /// A bindable which holds a reference to a bound target, allowing switching between targets and handling unbind/rebind. /// </summary> /// <typeparam name="T">The type of our stored <see cref="Bindable{T}.Value"/>.</typeparam> public class BindableNumberWithCurrent<T> : BindableNumber<T>, IHasCurrentValue<T> where T : struct, IComparable<T>, IConvertible, IEquatable<T> { private BindableNumber<T> currentBound; public Bindable<T> Current { get => this; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (currentBound != null) UnbindFrom(currentBound); BindTo(currentBound = (BindableNumber<T>)value); } } } }
// 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. // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Graphics.UserInterface; namespace osu.Framework.Bindables { /// <summary> /// A bindable which holds a reference to a bound target, allowing switching between targets and handling unbind/rebind. /// </summary> /// <typeparam name="T">The type of our stored <see cref="Bindable{T}.Value"/>.</typeparam> public class BindableNumberWithCurrent<T> : BindableNumber<T>, IHasCurrentValue<T> where T : struct, IComparable<T>, IConvertible, IEquatable<T> { private BindableNumber<T> currentBound; public Bindable<T> Current { get => this; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (currentBound != null) UnbindFrom(currentBound); BindTo(currentBound = (BindableNumber<T>)value); } } } }
mit
C#