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
17f078abde14fa6c767544927dd613ff22f63bf6
fix a problem with the formatting of the json
marinoscar/TrackingApp
Code/TrackingApp.Droid/Event.cs
Code/TrackingApp.Droid/Event.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; namespace TrackingApp.Droid { public class Event : EntityBase { public Event(string action) { PartitionKey = action; } public override string ToOData() { var template = @" ""PartitionKey"":""{0}"", ""RowKey"":""{1}"", ""Type"":""{2}"", ""Currency"":""{3}"", ""Category"":""{4}"", ""LocalTimestamp@odata.type"":""Edm.DateTime"", ""LocalTimestamp"":""{5}"", ""Value"":{6} "; return "{" + string.Format(template, PartitionKey, RowKey, Type, Currency, Category, LocalTimestamp.ToJson(), Value) + "}"; } public string Type { get; set; } public string Currency { get; set; } public string Category { get; set; } public DateTime LocalTimestamp { get; set; } public double Value { get; set; } public static Event FromTextResult(TextParseResult result) { var item = new Event(result.Action) { Category = result.Category, Currency = result.Curency, LocalTimestamp = DateTime.Now, Type = result.Type, Value = result.Value }; return item; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; namespace TrackingApp.Droid { public class Event : EntityBase { public Event(string action) { PartitionKey = action; } public override string ToOData() { var template = @" { ""PartitionKey"":""{0}"", ""RowKey"":""{1}"", ""Type"":""{2}"", ""Currency"":""{3}"", ""Category"":""{4}"", ""LocalTmestamp@odata.type"":""Edm.DateTime"", ""LocalTmestamp"":""{5}"", ""Value"":{6} } "; return string.Format(template, PartitionKey, RowKey, Type, Currency, Category, LocalTmestamp.ToJson(), Value); } public string Type { get; set; } public string Currency { get; set; } public string Category { get; set; } public DateTime LocalTmestamp { get; set; } public double Value { get; set; } public static Event FromTextResult(TextParseResult result) { var item = new Event(result.Action) { Category = result.Category, Currency = result.Curency, LocalTmestamp = DateTime.Now, Type = result.Type, Value = result.Value }; return item; } } }
mit
C#
b7b4e0b26a15f5f5ecf23936f956e0818daf2fad
Update tests to run in serial for #59.
Haacked/Scientist.net
test/Scientist.Test/Properties/AssemblyInfo.cs
test/Scientist.Test/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Xunit; // 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("UnitTests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("UnitTests")] [assembly: AssemblyCopyright("Copyright © 2016")] [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("2d25879a-6768-4d96-9299-63bca675b822")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: CollectionBehavior(DisableTestParallelization = true)]
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("UnitTests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("UnitTests")] [assembly: AssemblyCopyright("Copyright © 2016")] [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("2d25879a-6768-4d96-9299-63bca675b822")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#
5df0180305eda67b1d694500f928879fff61b40b
Update RoleAuthorizeAttribute.cs
SkillsFundingAgency/das-providerapprenticeshipsservice,SkillsFundingAgency/das-providerapprenticeshipsservice,SkillsFundingAgency/das-providerapprenticeshipsservice
src/SFA.DAS.ProviderApprenticeshipsService.Web/Attributes/RoleAuthorizeAttribute.cs
src/SFA.DAS.ProviderApprenticeshipsService.Web/Attributes/RoleAuthorizeAttribute.cs
using System.Linq; using System.Web; using System.Web.Mvc; using SFA.DAS.ProviderApprenticeshipsService.Web.Extensions; namespace SFA.DAS.ProviderApprenticeshipsService.Web.Attributes { public class AllowAllRolesAttribute : ActionFilterAttribute { } public class RoleAuthorizeAttribute : AuthorizeAttribute { public override void OnAuthorization(AuthorizationContext filterContext) { filterContext.HttpContext.Items["ActionDescriptor"] = filterContext.ActionDescriptor; base.OnAuthorization(filterContext); } protected override bool AuthorizeCore(HttpContextBase httpContext) { if (httpContext.Items["ActionDescriptor"] is ActionDescriptor actionDescriptor) { if ((actionDescriptor.GetCustomAttributes(typeof(AllowAllRolesAttribute), true).Any() || actionDescriptor.ControllerDescriptor.GetCustomAttributes(typeof(AllowAllRolesAttribute), true).Any()) && httpContext.User.Identity.HasServiceClaim()) { return true; } } return base.AuthorizeCore(httpContext); } protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { if (filterContext.HttpContext.Request.IsAuthenticated) { filterContext.HttpContext.Response.Redirect("/Error/Forbidden"); } base.HandleUnauthorizedRequest(filterContext); } } }
using System.Linq; using System.Web; using System.Web.Mvc; using SFA.DAS.ProviderApprenticeshipsService.Web.Extensions; namespace SFA.DAS.ProviderApprenticeshipsService.Web.Attributes { public class AllowAllRolesAttribute : ActionFilterAttribute { } public class RoleAuthorizeAttribute : AuthorizeAttribute { public override void OnAuthorization(AuthorizationContext filterContext) { filterContext.HttpContext.Items["ActionDescriptor"] = filterContext.ActionDescriptor; base.OnAuthorization(filterContext); } protected override bool AuthorizeCore(HttpContextBase httpContext) { if (httpContext.Items["ActionDescriptor"] is ActionDescriptor actionDescriptor) { if ((actionDescriptor.GetCustomAttributes(typeof(AllowAllRolesAttribute), true).Any() || actionDescriptor.ControllerDescriptor.GetCustomAttributes(typeof(AllowAllRolesAttribute), true).Any()) && httpContext.User.Identity.HasServiceClaim()) { return true; } } return base.AuthorizeCore(httpContext); } protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { if (filterContext.HttpContext.Request.IsAuthenticated) { filterContext.HttpContext.Response.Redirect("Error/Forbidden"); } base.HandleUnauthorizedRequest(filterContext); } } }
mit
C#
195e8e1609b987a32597e48e86453093247ccfd2
fix compilation
JetBrains/resharper-unity,JetBrains/resharper-unity,JetBrains/resharper-unity
resharper/resharper-unity/src/Rider/ShaderLabHighlighterPropertiesProvider.cs
resharper/resharper-unity/src/Rider/ShaderLabHighlighterPropertiesProvider.cs
using JetBrains.Application; using JetBrains.RdBackend.Common.Features.Daemon; using JetBrains.RdBackend.Common.Features.Daemon.Registration; using JetBrains.ReSharper.Plugins.Unity.ShaderLab.Daemon.Stages; using JetBrains.Rider.Model.HighlighterRegistration; namespace JetBrains.ReSharper.Plugins.Unity.Rider { [ShellComponent] public class ShaderLabHighlighterPropertiesProvider : IRiderHighlighterPropertiesProvider { public bool Applicable(RiderHighlighterDescription description) { return description.AttributeId == ShaderLabHighlightingAttributeIds.INJECTED_LANGUAGE_FRAGMENT; } public HighlighterProperties GetProperties(RiderHighlighterDescription description) { return new HighlighterProperties(description.AttributeId, description.HighlighterID, !description.NotRecyclable,false, false, false); } public int Priority => 0; } }
using JetBrains.Application; using JetBrains.RdBackend.Common.Features.Daemon; using JetBrains.RdBackend.Common.Features.Daemon.Registration; using JetBrains.ReSharper.Plugins.Unity.ShaderLab.Daemon.Stages; using JetBrains.Rider.Model.HighlighterRegistration; namespace JetBrains.ReSharper.Plugins.Unity.Rider { [ShellComponent] public class ShaderLabHighlighterPropertiesProvider : IRiderHighlighterPropertiesProvider { public bool Applicable(RiderHighlighterDescription description) { return description.AttributeId == ShaderLabHighlightingAttributeIds.INJECTED_LANGUAGE_FRAGMENT; } public HighlighterProperties GetProperties(RiderHighlighterDescription description) { return new HighlighterProperties( description.Kind.ToModel(), !description.NotRecyclable, GreedySide.NONE, false, false, false); } public int Priority => 0; } }
apache-2.0
C#
9e485021c1dea5e3c1583cdb26fdbb83858e74e8
Fix flaky unit test caused by concurrency issue
paiden/Nett
Source/Nett/UserTypeMetaData.cs
Source/Nett/UserTypeMetaData.cs
namespace Nett { using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Reflection; using Util; internal static class UserTypeMetaData { private static readonly ConcurrentDictionary<Type, MetaDataInfo> MetaData = new ConcurrentDictionary<Type, MetaDataInfo>(); public static bool IsPropertyIgnored(Type ownerType, PropertyInfo pi) { if (ownerType == null) { throw new ArgumentNullException(nameof(ownerType)); } if (pi == null) { throw new ArgumentNullException(nameof(pi)); } EnsureMetaDataInitialized(ownerType); return MetaData[ownerType].IgnoredProperties.Contains(pi.Name); } private static void EnsureMetaDataInitialized(Type t) => Extensions.DictionaryExtensions.AddIfNeeded(MetaData, t, () => ProcessType(t)); private static MetaDataInfo ProcessType(Type t) { var ignored = ProcessIgnoredProperties(t); return new MetaDataInfo(ignored); } private static IEnumerable<string> ProcessIgnoredProperties(Type t) { var attributes = ReflectionUtil.GetPropertiesWithAttribute<TomlIgnoreAttribute>(t); return attributes.Select(pi => pi.Name); } private sealed class MetaDataInfo { public MetaDataInfo(IEnumerable<string> ignoredProperties) { this.IgnoredProperties = new HashSet<string>(ignoredProperties); } public HashSet<string> IgnoredProperties { get; } } } }
namespace Nett { using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Util; internal static class UserTypeMetaData { private static readonly Dictionary<Type, MetaDataInfo> MetaData = new Dictionary<Type, MetaDataInfo>(); public static bool IsPropertyIgnored(Type ownerType, PropertyInfo pi) { if (ownerType == null) { throw new ArgumentNullException(nameof(ownerType)); } if (pi == null) { throw new ArgumentNullException(nameof(pi)); } EnsureMetaDataInitialized(ownerType); return MetaData[ownerType].IgnoredProperties.Contains(pi.Name); } private static void EnsureMetaDataInitialized(Type t) => Extensions.DictionaryExtensions.AddIfNeeded(MetaData, t, () => ProcessType(t)); private static MetaDataInfo ProcessType(Type t) { var ignored = ProcessIgnoredProperties(t); return new MetaDataInfo(ignored); } private static IEnumerable<string> ProcessIgnoredProperties(Type t) { var attributes = ReflectionUtil.GetPropertiesWithAttribute<TomlIgnoreAttribute>(t); return attributes.Select(pi => pi.Name); } private sealed class MetaDataInfo { public MetaDataInfo(IEnumerable<string> ignoredProperties) { this.IgnoredProperties = new HashSet<string>(ignoredProperties); } public HashSet<string> IgnoredProperties { get; } } } }
mit
C#
801a7c76527a571c77dad8d3bd247e7039f73173
Add copyright header to TransportSocketOptions.cs.
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
src/Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets/SocketTransportOptions.cs
src/Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets/SocketTransportOptions.cs
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Text; namespace Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets { // TODO: Come up with some options public class SocketTransportOptions { } }
using System; using System.Collections.Generic; using System.Text; namespace Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets { // TODO: Come up with some options public class SocketTransportOptions { } }
apache-2.0
C#
5eb76deb755f0596cad5b83d17fefb8cc68e7ce0
handle auth proxy url with jupyter job
h2020-westlife-eu/west-life-wp6,h2020-westlife-eu/west-life-wp6,h2020-westlife-eu/west-life-wp6,h2020-westlife-eu/west-life-wp6,h2020-westlife-eu/west-life-wp6,h2020-westlife-eu/west-life-wp6,h2020-westlife-eu/west-life-wp6
wp6-virtualfolder/src/WP6Service2/WP6Service2/Services/PerUserProcess/JupyterJob.cs
wp6-virtualfolder/src/WP6Service2/WP6Service2/Services/PerUserProcess/JupyterJob.cs
using System; using System.CodeDom; using System.Data; using System.Linq; using Dropbox.Api.Properties; using ServiceStack.OrmLite; using ServiceStack.ServiceHost; namespace WP6Service2.Services.PerUserProcess { /** specific implementation for jupyter notebook - first arg is userid, second arg is portnumber */ public class JupyterJob : DefaultJob { private long port =0; private string suffix; private string proxyurl; private string outputlog; public JupyterJob(string jobname, IHttpRequest request, IDbConnection db, int pid) : base(jobname, request, db, pid) { var portnumber = getAvailablePort(); proxyurl = "/vfnotebook" + "/"+request.Items["authproxy"].ToString().Trim('/'); //proxyurl= proxyurl.TrimEnd('/'); outputlog = "/home/vagrant/logs/"+jobname + DateTime.Now.Ticks + ".log"; suffix = request.Items["userid"] + " " +portnumber + " " + proxyurl;//l+" "+getUrl(); } //startJupyter.sh add|remove [username] [port] [proxyurlpart] public override string getArgs() { return suffix + " " + outputlog; } //returns 8901 + max id of already existing jobs. private long getAvailablePort() { var b = db.Select<UserJob>().Select(x => x.Id); port = 8950 + (b.Any() ? b.Max()+1 : 0) ; return port ; } public override string getUrl() { if (port==0) throw new ArgumentNullException("port","port not set."); return proxyurl; } } }
using System; using System.CodeDom; using System.Data; using System.Linq; using Dropbox.Api.Properties; using ServiceStack.OrmLite; using ServiceStack.ServiceHost; namespace WP6Service2.Services.PerUserProcess { /** specific implementation for jupyter notebook - first arg is userid, second arg is portnumber */ public class JupyterJob : DefaultJob { private long port =0; private string suffix; private string proxyurl; private string outputlog; public JupyterJob(string jobname, IHttpRequest request, IDbConnection db, int pid) : base(jobname, request, db, pid) { var portnumber = getAvailablePort(); proxyurl = "/vfnotebook" + request.Items["authproxy"]; proxyurl= proxyurl.TrimEnd('/'); outputlog = "/home/vagrant/logs/"+jobname + DateTime.Now.Ticks + ".log"; suffix = request.Items["userid"] + " " +portnumber + " " + proxyurl;//l+" "+getUrl(); } //startJupyter.sh add|remove [username] [port] [proxyurlpart] public override string getArgs() { return suffix + " " + outputlog; } //returns 8901 + max id of already existing jobs. private long getAvailablePort() { var b = db.Select<UserJob>().Select(x => x.Id); port = 8950 + (b.Any() ? b.Max()+1 : 0) ; return port ; } public override string getUrl() { if (port==0) throw new ArgumentNullException("port","port not set."); return proxyurl; } } }
mit
C#
0ee173e56c026abdc7324c26f4a33b92bdd4dcb5
fix bug in mapzen map data provider
reinterpretcat/utymap,reinterpretcat/utymap,reinterpretcat/utymap
unity/library/UtyMap.Unity/Data/Providers/Geo/MapzenMapDataProvider.cs
unity/library/UtyMap.Unity/Data/Providers/Geo/MapzenMapDataProvider.cs
using System; using System.IO; using UtyDepend; using UtyDepend.Config; using UtyMap.Unity.Infrastructure.Diagnostic; using UtyMap.Unity.Infrastructure.IO; namespace UtyMap.Unity.Data.Providers.Geo { /// <summary> Downloads map data from mapzen servers. </summary> internal class MapzenMapDataProvider : RemoteMapDataProvider { private string _cachePath; private string _mapDataServerUri; private string _mapDataFormatExtension; private string _mapDataLayers; private string _mapDataApiKey; [Dependency] public MapzenMapDataProvider(IFileSystemService fileSystemService, INetworkService networkService, ITrace trace) : base(fileSystemService, networkService, trace) { } /// <inheritdoc /> public override void Configure(IConfigSection configSection) { _mapDataServerUri = configSection.GetString(@"data/mapzen/server", null); _mapDataFormatExtension = "." + configSection.GetString(@"data/mapzen/format", "json"); _mapDataApiKey = configSection.GetString(@"data/mapzen/apikey", null); _mapDataLayers = configSection.GetString(@"data/mapzen/layers", null); _cachePath = configSection.GetString(@"data/cache", null); } /// <inheritdoc /> protected override string GetUri(QuadKey quadKey) { return String.Format(_mapDataServerUri, _mapDataLayers, quadKey.LevelOfDetail, quadKey.TileX, quadKey.TileY, _mapDataApiKey); } /// <inheritdoc /> protected override string GetFilePath(QuadKey quadKey) { return Path.Combine(_cachePath, quadKey + _mapDataFormatExtension); } } }
using System; using System.IO; using UtyDepend; using UtyDepend.Config; using UtyMap.Unity.Infrastructure.Diagnostic; using UtyMap.Unity.Infrastructure.IO; namespace UtyMap.Unity.Data.Providers.Geo { /// <summary> Downloads map data from mapzen servers. </summary> internal class MapzenMapDataProvider : RemoteMapDataProvider { private string _cachePath; private string _mapDataServerUri; private string _mapDataFormatExtension; private string _mapDataLayers; private string _mapDataApiKey; [Dependency] public MapzenMapDataProvider(IFileSystemService fileSystemService, INetworkService networkService, ITrace trace) : base(fileSystemService, networkService, trace) { } /// <inheritdoc /> public override void Configure(IConfigSection configSection) { _mapDataServerUri = configSection.GetString(@"data/mapzen/server", null); _mapDataFormatExtension = "." + configSection.GetString(@"data/mapzen/format", "json"); _mapDataApiKey = configSection.GetString(@"data/mapzen/apikey", null); _mapDataLayers = configSection.GetString(@"data/mapzen/layers", null); _cachePath = configSection.GetString(@"data/cache", null); } /// <inheritdoc /> protected override string GetUri(QuadKey quadKey) { return Path.Combine(_cachePath, quadKey + _mapDataFormatExtension); } /// <inheritdoc /> protected override string GetFilePath(QuadKey quadKey) { return String.Format(_mapDataServerUri, _mapDataLayers, quadKey.LevelOfDetail, quadKey.TileX, quadKey.TileY, _mapDataApiKey); } } }
apache-2.0
C#
8f8392b8995e5e4bb62c08a30088a2d0287a7e16
rename object to context
bkoelman/roslyn-analyzers,dotnet/roslyn-analyzers,dotnet/roslyn-analyzers,srivatsn/roslyn-analyzers,pakdev/roslyn-analyzers,VitalyTVA/roslyn-analyzers,tmeschter/roslyn-analyzers-1,heejaechang/roslyn-analyzers,mattwar/roslyn-analyzers,SpotLabsNET/roslyn-analyzers,jepetty/roslyn-analyzers,genlu/roslyn-analyzers,jinujoseph/roslyn-analyzers,mavasani/roslyn-analyzers,Anniepoh/roslyn-analyzers,qinxgit/roslyn-analyzers,jasonmalinowski/roslyn-analyzers,jaredpar/roslyn-analyzers,mavasani/roslyn-analyzers,modulexcite/roslyn-analyzers,pakdev/roslyn-analyzers,natidea/roslyn-analyzers
SyntaxNodeAnalyzer/SyntaxNodeAnalyzer/SyntaxNodeAnalyzer/DiagnosticAnalyzer.cs
SyntaxNodeAnalyzer/SyntaxNodeAnalyzer/SyntaxNodeAnalyzer/DiagnosticAnalyzer.cs
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Text; namespace SyntaxNodeAnalyzer { [DiagnosticAnalyzer(LanguageNames.CSharp)] public class SyntaxNodeAnalyzerAnalyzer : DiagnosticAnalyzer { public const string spacingRuleId = "IfSpacing"; internal static DiagnosticDescriptor Rule = new DiagnosticDescriptor( id: spacingRuleId, //make the id specific title: "If statement must have a space between 'if' and the boolean expression", //allow any title messageFormat: "If statements must contain a space between the 'if' keyword and the boolean expression", //allow any message category: "Syntax", //make the category specific defaultSeverity: DiagnosticSeverity.Warning, //possible options isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Rule); } } public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction(AnalyzeIfStatement, SyntaxKind.IfStatement); } private void AnalyzeIfStatement(SyntaxNodeAnalysisContext context) { var ifStatement = (IfStatementSyntax)context.Node; var ifKeyword = ifStatement.IfKeyword; var openParen = ifStatement.OpenParenToken; var diagnosticLocation = Location.Create(ifStatement.SyntaxTree, TextSpan.FromBounds(ifKeyword.Span.Start, openParen.Span.Start)); if (ifKeyword.HasTrailingTrivia) { var trailingTrivia = ifKeyword.TrailingTrivia.Last(); if (trailingTrivia.Kind() == SyntaxKind.WhitespaceTrivia) { if (trailingTrivia.ToString() == " ") { return; } } } var diagnostic = Diagnostic.Create(Rule, diagnosticLocation, Rule.MessageFormat); context.ReportDiagnostic(diagnostic); } } }
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Text; namespace SyntaxNodeAnalyzer { [DiagnosticAnalyzer(LanguageNames.CSharp)] public class SyntaxNodeAnalyzerAnalyzer : DiagnosticAnalyzer { public const string spacingRuleId = "IfSpacing"; internal static DiagnosticDescriptor Rule = new DiagnosticDescriptor( id: spacingRuleId, //make the id specific title: "If statement must have a space between 'if' and the boolean expression", //allow any title messageFormat: "If statements must contain a space between the 'if' keyword and the boolean expression", //allow any message category: "Syntax", //make the category specific defaultSeverity: DiagnosticSeverity.Warning, //possible options isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Rule); } } public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction(AnalyzeIfStatement, SyntaxKind.IfStatement); } private void AnalyzeIfStatement(SyntaxNodeAnalysisContext context) { var ifStatement = (IfStatementSyntax)context.Node; var ifKeyword = ifStatement.IfKeyword; var openParen = ifStatement.OpenParenToken; var diagnosticLocation = Location.Create(ifStatement.SyntaxTree, TextSpan.FromBounds(ifKeyword.Span.Start, openParen.Span.Start)); if (ifKeyword.HasTrailingTrivia) { var trailingTrivia = ifKeyword.TrailingTrivia.Last(); if (trailingTrivia.Kind() == SyntaxKind.WhitespaceTrivia) { if (trailingTrivia.ToString() == " ") { return; } } } var diagnostic = Diagnostic.Create(Rule, diagnosticLocation, Rule.MessageFormat); obj.ReportDiagnostic(diagnostic); } } }
mit
C#
00197c364032ed09666df5b7f2052d891e6f1158
Add MVC dependency resolver
rocky0904/mozu-dotnet,Mozu/mozu-dotnet,sanjaymandadi/mozu-dotnet,ezekielthao/mozu-dotnet
Libraries/Mozu.Api.WebToolKit/Mozu.Api.WebToolKit/AbstractWebApiBootstrapper.cs
Libraries/Mozu.Api.WebToolKit/Mozu.Api.WebToolKit/AbstractWebApiBootstrapper.cs
using System; using System.Collections.Generic; using System.Web.Http; using System.Web.Mvc; using Autofac; using Autofac.Integration.Mvc; using Autofac.Integration.WebApi; using Mozu.Api.Logging; using Mozu.Api.ToolKit; using Mozu.Api.WebToolKit.Events; using Mozu.Api.WebToolKit.Logging; using Mozu.Api.WebToolKit.Controllers; namespace Mozu.Api.WebToolKit { public abstract class AbstractWebApiBootstrapper : AbstractBootstrapper { private HttpConfiguration _httpConfiguration; public AbstractWebApiBootstrapper Bootstrap(HttpConfiguration httpConfiguration) { Bootstrap(); return this; } public override void InitializeContainer(ContainerBuilder containerBuilder) { base.InitializeContainer(containerBuilder); _containerBuilder.RegisterType<EventRouteHandler>().AsSelf(); _containerBuilder.RegisterType<ApiLogger>().AsSelf().InstancePerRequest(); _containerBuilder.RegisterType<MvcLoggingFilter>().AsSelf().InstancePerRequest(); _containerBuilder.RegisterType<VersionController>().InstancePerRequest(); } public override void PostInitialize() { base.PostInitialize(); _httpConfiguration.DependencyResolver = new AutofacWebApiDependencyResolver(Container); DependencyResolver.SetResolver(new AutofacDependencyResolver(Container)); _httpConfiguration.MessageHandlers.Add(DependencyResolver.Current.GetService<ApiLogger>()); } } }
using System; using System.Collections.Generic; using System.Web.Http; using System.Web.Mvc; using Autofac; using Autofac.Integration.WebApi; using Mozu.Api.Logging; using Mozu.Api.ToolKit; using Mozu.Api.WebToolKit.Events; using Mozu.Api.WebToolKit.Logging; using Mozu.Api.WebToolKit.Controllers; namespace Mozu.Api.WebToolKit { public abstract class AbstractWebApiBootstrapper : AbstractBootstrapper { private HttpConfiguration _httpConfiguration; public AbstractWebApiBootstrapper Bootstrap(HttpConfiguration httpConfiguration) { Bootstrap(); return this; } public override void InitializeContainer(ContainerBuilder containerBuilder) { base.InitializeContainer(containerBuilder); _containerBuilder.RegisterType<EventRouteHandler>().AsSelf(); _containerBuilder.RegisterType<ApiLogger>().AsSelf().InstancePerRequest(); _containerBuilder.RegisterType<MvcLoggingFilter>().AsSelf().InstancePerRequest(); _containerBuilder.RegisterType<VersionController>().InstancePerRequest(); } public override void PostInitialize() { base.PostInitialize(); _httpConfiguration.DependencyResolver = new AutofacWebApiDependencyResolver(Container); _httpConfiguration.MessageHandlers.Add(DependencyResolver.Current.GetService<ApiLogger>()); } } }
mit
C#
0a94976666ab9d42a108f212e2ad411e774299f2
Fix borken test
DimitarDKirov/RealEstateSystem,DimitarDKirov/RealEstateSystem,DimitarDKirov/RealEstateSystem
RealEstateWebApi/Tests/Teleimot.Web.Api.Tests/IntegrationTests/CommentsTests.cs
RealEstateWebApi/Tests/Teleimot.Web.Api.Tests/IntegrationTests/CommentsTests.cs
namespace Teleimot.Web.Api.Tests.IntegrationTests { using System.Net; using System.Net.Http; using Microsoft.VisualStudio.TestTools.UnitTesting; using MyTested.WebApi; [TestClass] public class CommentsTests { private static IServerBuilder server; [ClassInitialize] public static void Init(TestContext testContext) { server = MyWebApi.Server().Starts<Startup>(); } [TestMethod] public void CommentsShouldReturnUnauthorizedWithNoAuthenticatedUser() { //server // .WithHttpRequestMessage(req => req // .WithMethod(HttpMethod.Get) // .WithRequestUri("api/Comments/ByUser/TestUser")) // .ShouldReturnHttpResponseMessage() // .WithStatusCode(HttpStatusCode.Unauthorized); } [ClassCleanup] public static void Clean() { MyWebApi.Server().Stops(); } } }
namespace Teleimot.Web.Api.Tests.IntegrationTests { using System.Net; using System.Net.Http; using Microsoft.VisualStudio.TestTools.UnitTesting; using MyTested.WebApi; [TestClass] public class CommentsTests { private static IServerBuilder server; [ClassInitialize] public static void Init(TestContext testContext) { server = MyWebApi.Server().Starts<Startup>(); } [TestMethod] public void CommentsShouldReturnUnauthorizedWithNoAuthenticatedUser() { server .WithHttpRequestMessage(req => req .WithMethod(HttpMethod.Get) .WithRequestUri("api/Comments/ByUser/TestUser")) .ShouldReturnHttpResponseMessage() .WithStatusCode(HttpStatusCode.Unauthorized); } [ClassCleanup] public static void Clean() { MyWebApi.Server().Stops(); } } }
mit
C#
4c564581739a13e1de73ef75054bd7c825dca384
Change button location to the right side of dropdown
NeoAdonis/osu,ppy/osu,ppy/osu,peppy/osu,peppy/osu,ppy/osu,peppy/osu,NeoAdonis/osu,NeoAdonis/osu
osu.Game.Tournament/Screens/Setup/TournamentSwitcher.cs
osu.Game.Tournament/Screens/Setup/TournamentSwitcher.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Game.Graphics.UserInterface; using osu.Game.Tournament.IO; namespace osu.Game.Tournament.Screens.Setup { internal class TournamentSwitcher : ActionableInfo { private OsuDropdown<string> dropdown; private OsuButton folderButton; [Resolved] private TournamentGameBase game { get; set; } [BackgroundDependencyLoader] private void load(TournamentStorage storage) { string startupTournament = storage.CurrentTournament.Value; dropdown.Current = storage.CurrentTournament; dropdown.Items = storage.ListTournaments(); dropdown.Current.BindValueChanged(v => Button.Enabled.Value = v.NewValue != startupTournament, true); Action = () => game.GracefullyExit(); folderButton.Action = storage.PresentExternally; ButtonText = "Close osu!"; } protected override Drawable CreateComponent() { var drawable = base.CreateComponent(); FlowContainer.Insert(-1, folderButton = new TriangleButton { Text = "Open folder", Width = 100 }); FlowContainer.Insert(-2, dropdown = new OsuDropdown<string> { Width = 510 }); return drawable; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Game.Graphics.UserInterface; using osu.Game.Tournament.IO; namespace osu.Game.Tournament.Screens.Setup { internal class TournamentSwitcher : ActionableInfo { private OsuDropdown<string> dropdown; private OsuButton folderButton; [Resolved] private TournamentGameBase game { get; set; } [BackgroundDependencyLoader] private void load(TournamentStorage storage) { string startupTournament = storage.CurrentTournament.Value; dropdown.Current = storage.CurrentTournament; dropdown.Items = storage.ListTournaments(); dropdown.Current.BindValueChanged(v => Button.Enabled.Value = v.NewValue != startupTournament, true); Action = () => game.GracefullyExit(); folderButton.Action = storage.PresentExternally; ButtonText = "Close osu!"; } protected override Drawable CreateComponent() { var drawable = base.CreateComponent(); FlowContainer.Insert(-1, dropdown = new OsuDropdown<string> { Width = 510 }); FlowContainer.Insert(-2, folderButton = new TriangleButton { Text = "Open folder", Width = 100 }); return drawable; } } }
mit
C#
f8b5f74ef4d415914a2476f71956db4391ff66a7
Fix TeamCityOutputSink to not handle trace and information messages
nuke-build/nuke,nuke-build/nuke,nuke-build/nuke,nuke-build/nuke
source/Nuke.Common/OutputSinks/TeamCityOutputSink.cs
source/Nuke.Common/OutputSinks/TeamCityOutputSink.cs
// Copyright Matthias Koch, Sebastian Karasek 2018. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.Diagnostics.CodeAnalysis; using System.Linq; using JetBrains.Annotations; using Nuke.Common.BuildServers; using Nuke.Common.Utilities; namespace Nuke.Common.OutputSinks { [UsedImplicitly] [ExcludeFromCodeCoverage] internal class TeamCityOutputSink : ConsoleOutputSink { private readonly TeamCity _teamCity; internal TeamCityOutputSink(TeamCity teamCity) { _teamCity = teamCity; } public override void Write(string text) { _teamCity.WriteMessage(text); } public override IDisposable WriteBlock(string text) { return DelegateDisposable.CreateBracket( () => _teamCity.OpenBlock(text), () => _teamCity.CloseBlock(text)); } public override void Warn(string text, string details = null) { _teamCity.WriteWarning(text); if (details != null) _teamCity.WriteWarning(details); } public override void Error(string text, string details = null) { _teamCity.WriteError(text, details); _teamCity.AddBuildProblem(text); } public override void Success(string text) { _teamCity.WriteMessage(text); } } }
// Copyright Matthias Koch, Sebastian Karasek 2018. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.Diagnostics.CodeAnalysis; using System.Linq; using JetBrains.Annotations; using Nuke.Common.BuildServers; using Nuke.Common.Utilities; namespace Nuke.Common.OutputSinks { [UsedImplicitly] [ExcludeFromCodeCoverage] internal class TeamCityOutputSink : ConsoleOutputSink { private readonly TeamCity _teamCity; internal TeamCityOutputSink(TeamCity teamCity) { _teamCity = teamCity; } public override void Write(string text) { _teamCity.WriteMessage(text); } public override IDisposable WriteBlock(string text) { return DelegateDisposable.CreateBracket( () => _teamCity.OpenBlock(text), () => _teamCity.CloseBlock(text)); } public override void Trace(string text) { _teamCity.WriteMessage(text); } public override void Info(string text) { _teamCity.WriteMessage(text); } public override void Warn(string text, string details = null) { _teamCity.WriteWarning(text); if (details != null) _teamCity.WriteWarning(details); } public override void Error(string text, string details = null) { _teamCity.WriteError(text, details); _teamCity.AddBuildProblem(text); } public override void Success(string text) { _teamCity.WriteMessage(text); } } }
mit
C#
f14e8418f1de24b04e8fcd37ce13ecdc832aa102
Update AutomationActionFrequency.cs
smartsheet-platform/smartsheet-csharp-sdk,smartsheet-platform/smartsheet-csharp-sdk
main/Smartsheet/Api/Models/AutomationActionFrequency.cs
main/Smartsheet/Api/Models/AutomationActionFrequency.cs
// #[license] // SmartsheetClient SDK for C# // %% // Copyright (C) 2018 SmartsheetClient // %% // 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. // %[license] using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Smartsheet.Api.Models { public enum AutomationActionFrequency { IMMEDIATELY, HOURLY, DAILY, WEEKLY } }
// #[license] // SmartsheetClient SDK for C# // %% // Copyright (C) 2018 SmartsheetClient // %% // 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. // %[license] using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Smartsheet.Api.Models { public enum AutomationActionFrequency { IMMEDIATELY, HOURLY, DAILY, WEEKLY } }
apache-2.0
C#
9b7770c2a425c74b92e183d1cc4de45cc8a6aca3
Implement IHtmlTableDataCellElement
zedr0n/AngleSharp.Local,Livven/AngleSharp,FlorianRappl/AngleSharp,FlorianRappl/AngleSharp,zedr0n/AngleSharp.Local,AngleSharp/AngleSharp,AngleSharp/AngleSharp,AngleSharp/AngleSharp,FlorianRappl/AngleSharp,AngleSharp/AngleSharp,Livven/AngleSharp,zedr0n/AngleSharp.Local,AngleSharp/AngleSharp,Livven/AngleSharp,FlorianRappl/AngleSharp
AngleSharp/Dom/Html/HtmlTableDataCellElement.cs
AngleSharp/Dom/Html/HtmlTableDataCellElement.cs
namespace AngleSharp.Dom.Html { using AngleSharp.Html; /// <summary> /// Represents the object for HTML td elements. /// </summary> sealed class HtmlTableDataCellElement : HtmlTableCellElement, IHtmlTableDataCellElement { #region ctor public HtmlTableDataCellElement(Document owner) : base(owner, Tags.Td) { } #endregion } }
namespace AngleSharp.Dom.Html { using AngleSharp.Html; /// <summary> /// Represents the object for HTML td elements. /// </summary> sealed class HtmlTableDataCellElement : HtmlTableCellElement, IHtmlTableCellElement { #region ctor public HtmlTableDataCellElement(Document owner) : base(owner, Tags.Td) { } #endregion } }
mit
C#
f4f0a4fe37a0f90c3513898a6fff017380be2f1a
Update templates path
projectkudu/AzureFunctions,projectkudu/AzureFunctions,projectkudu/AzureFunctions,projectkudu/WebJobsPortal,agruning/azure-functions-ux,chunye/azure-functions-ux,agruning/azure-functions-ux,projectkudu/WebJobsPortal,projectkudu/AzureFunctions,chunye/azure-functions-ux,agruning/azure-functions-ux,chunye/azure-functions-ux,chunye/azure-functions-ux,chunye/azure-functions-ux,projectkudu/WebJobsPortal,projectkudu/WebJobsPortal,agruning/azure-functions-ux,agruning/azure-functions-ux
AzureFunctions/Code/Settings.cs
AzureFunctions/Code/Settings.cs
using AzureFunctions.Contracts; using System.Configuration; using System.IO; using System.Runtime.CompilerServices; using System.Threading.Tasks; using System.Web.Hosting; namespace AzureFunctions.Code { public class Settings : ISettings { private static string config(string @default = null, [CallerMemberName] string key = null) { var value = System.Environment.GetEnvironmentVariable(key) ?? ConfigurationManager.AppSettings[key]; return string.IsNullOrEmpty(value) ? @default : value; } public async Task<string> GetCurrentSiteExtensionVersion() { try { using (var stream = new StreamReader(Path.Combine(AppDataPath, "version.txt"))) { return await stream.ReadToEndAsync(); } } catch { } return string.Empty; } public string AppDataPath => Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "App_Data"); public string TemplatesPath => Path.Combine(AppDataPath, "Templates\\Templates"); public string LoggingSqlServerConnectionString => config(); public bool LogToSql => bool.Parse(config(false.ToString())); public bool LogToFile => bool.Parse(config(true.ToString())); } }
using AzureFunctions.Contracts; using System.Configuration; using System.IO; using System.Runtime.CompilerServices; using System.Threading.Tasks; using System.Web.Hosting; namespace AzureFunctions.Code { public class Settings : ISettings { private static string config(string @default = null, [CallerMemberName] string key = null) { var value = System.Environment.GetEnvironmentVariable(key) ?? ConfigurationManager.AppSettings[key]; return string.IsNullOrEmpty(value) ? @default : value; } public async Task<string> GetCurrentSiteExtensionVersion() { try { using (var stream = new StreamReader(Path.Combine(AppDataPath, "version.txt"))) { return await stream.ReadToEndAsync(); } } catch { } return string.Empty; } public string AppDataPath => Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "App_Data"); public string TemplatesPath => Path.Combine(AppDataPath, "Templates"); public string LoggingSqlServerConnectionString => config(); public bool LogToSql => bool.Parse(config(false.ToString())); public bool LogToFile => bool.Parse(config(true.ToString())); } }
apache-2.0
C#
84ab4cff36c5628999fee9c330a8b929b8f5a498
Implement InMemoryFileSystem methods
appharbor/appharbor-cli
src/AppHarbor.Tests/InMemoryFileSystem.cs
src/AppHarbor.Tests/InMemoryFileSystem.cs
using System; using System.Collections.Generic; using System.IO; namespace AppHarbor.Tests { public class InMemoryFileSystem : IFileSystem { private readonly IDictionary<string, byte[]> _files; public InMemoryFileSystem() { _files = new Dictionary<string, byte[]>(); } public void Delete(string path) { _files.Remove(path); } public Stream OpenRead(string path) { byte[] bytes; if (!_files.TryGetValue(path, out bytes)) { throw new FileNotFoundException(); } return new MemoryStream(bytes); } public Stream OpenWrite(string path) { return new DelegateOutputStream(x => { var bytes = x.ToArray(); _files.Add(path, bytes); }); } public IDictionary<string, byte[]> Files { get { return _files; } } private class DelegateOutputStream : MemoryStream { private readonly Action<MemoryStream> _beforeDispose; private bool _hasDisposed; public DelegateOutputStream(Action<MemoryStream> beforeDispose) { _beforeDispose = beforeDispose; } protected override void Dispose(bool disposing) { if (disposing && !_hasDisposed) { _hasDisposed = true; _beforeDispose(this); } base.Dispose(disposing); } } } }
using System; using System.IO; namespace AppHarbor.Tests { public class InMemoryFileSystem : IFileSystem { public void Delete(string path) { throw new NotImplementedException(); } public Stream OpenRead(string path) { throw new NotImplementedException(); } public Stream OpenWrite(string path) { throw new NotImplementedException(); } } }
mit
C#
4a0b7494ada5a509e287b2e72c30da8914d8ccca
Update start message
matteocontrini/locuspocusbot
LocusPocusBot/Handlers/StartHandler.cs
LocusPocusBot/Handlers/StartHandler.cs
using System.Text; using System.Threading.Tasks; using Telegram.Bot.Types.Enums; namespace LocusPocusBot.Handlers { public class StartHandler : HandlerBase { private readonly IBotService bot; public StartHandler(IBotService botService) { this.bot = botService; } public override async Task Run() { StringBuilder msg = new StringBuilder(); msg.AppendLine("Ciao! 🤓"); msg.AppendLine(); msg.AppendLine("Sono *LocusPocus* e ti posso aiutare a trovare le aule libere presso i poli dell'Università di Trento 🎓"); msg.AppendLine(); msg.AppendLine("Scrivimi /povo, /mesiano o /psicologia per ottenere la lista delle aule libere."); msg.AppendLine(); msg.AppendLine("Altre info in /aiuto"); await this.bot.Client.SendTextMessageAsync( chatId: this.Chat.Id, text: msg.ToString(), parseMode: ParseMode.Markdown ); } } }
using System.Text; using System.Threading.Tasks; using Telegram.Bot.Types.Enums; namespace LocusPocusBot.Handlers { public class StartHandler : HandlerBase { private readonly IBotService bot; public StartHandler(IBotService botService) { this.bot = botService; } public override async Task Run() { StringBuilder msg = new StringBuilder(); msg.AppendLine("Ciao! 🤓"); msg.AppendLine(); msg.AppendLine("Sono *LocusPocus* e ti posso aiutare a trovare le aule libere presso i poli di Povo e Mesiano dell'Università di Trento 🎓"); msg.AppendLine(); msg.AppendLine("Scrivimi /povo o /mesiano per ottenere la lista delle aule libere."); msg.AppendLine(); msg.AppendLine("Altre info in /aiuto"); await this.bot.Client.SendTextMessageAsync( chatId: this.Chat.Id, text: msg.ToString(), parseMode: ParseMode.Markdown ); } } }
mit
C#
0e9d0f91337e34f60ae2617e00ec3fd6c1f7666f
Implement sender
sakapon/Samples-2017
Network/UdpSample/UdpSender/Program.cs
Network/UdpSample/UdpSender/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Net.Sockets; using System.Text; using System.Threading; namespace UdpSender { class Program { const string ReceiverAddress = "127.0.0.1"; const int ReceiverPort = 8100; static void Main(string[] args) { var client = new UdpClient(ReceiverAddress, ReceiverPort); var timer = new Timer(o => { var text = $"{DateTime.Now:HH:mm:ss.fff}"; var data = Encoding.UTF8.GetBytes(text); client.Send(data, data.Length); Console.WriteLine(text); }, null, 1000, 1000); Console.WriteLine("Press [Enter] key to exit."); Console.ReadLine(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace UdpSender { class Program { static void Main(string[] args) { } } }
mit
C#
9324b4d5b185d2ff3254a0cbd29597dcb7aa537a
Add test to make sure normal collection works.
AxeDotNet/AxePractice.CSharpViaTest
src/CSharpViaTest.Collections/20_YieldPractices/TakeUntilCatchingAnException.cs
src/CSharpViaTest.Collections/20_YieldPractices/TakeUntilCatchingAnException.cs
using System; using System.Collections.Generic; using System.Linq; using CSharpViaTest.Collections.Annotations; using Xunit; namespace CSharpViaTest.Collections._20_YieldPractices { [Medium] public class TakeUntilCatchingAnException { readonly int indexThatWillThrow = new Random().Next(2, 10); IEnumerable<int> GetSequenceOfData() { for (int i = 0;; ++i) { if (i == indexThatWillThrow) { throw new Exception("An exception is thrown"); } yield return i; } } #region Please modifies the code to pass the test static IEnumerable<int> TakeUntilError(IEnumerable<int> sequence) { throw new NotImplementedException(); } #endregion [Fact] public void should_get_sequence_until_an_exception_is_thrown() { IEnumerable<int> sequence = TakeUntilError(GetSequenceOfData()); Assert.Equal(Enumerable.Range(0, indexThatWillThrow + 1), sequence); } [Fact] public void should_get_sequence_given_normal_collection() { var sequence = new[] { 1, 2, 3 }; IEnumerable<int> result = TakeUntilError(sequence); Assert.Equal(sequence, result); } } }
using System; using System.Collections.Generic; using System.Linq; using CSharpViaTest.Collections.Annotations; using Xunit; namespace CSharpViaTest.Collections._20_YieldPractices { [Medium] public class TakeUntilCatchingAnException { readonly int indexThatWillThrow = new Random().Next(2, 10); IEnumerable<int> GetSequenceOfData() { for (int i = 0;; ++i) { if (i == indexThatWillThrow) { throw new Exception("An exception is thrown"); } yield return i; } } #region Please modifies the code to pass the test static IEnumerable<int> TakeUntilError(IEnumerable<int> sequence) { throw new NotImplementedException(); } #endregion [Fact] public void should_get_sequence_until_an_exception_is_thrown() { IEnumerable<int> sequence = TakeUntilError(GetSequenceOfData()); Assert.Equal(Enumerable.Range(0, indexThatWillThrow + 1), sequence); } } }
mit
C#
c58bcf9ec349f6dcf8ea6b897b6a8a1fb06e9816
add data annotations to baseDataModel
olebg/car-mods-heaven,olebg/car-mods-heaven
CarModsHeaven/CarModsHeaven/CarModsHeaven.Data.Models/Abstracts/BaseDataModel.cs
CarModsHeaven/CarModsHeaven/CarModsHeaven.Data.Models/Abstracts/BaseDataModel.cs
using CarModsHeaven.Data.Models.Contracts; using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace CarModsHeaven.Data.Models.Abstracts { public abstract class BaseDataModel : IDeletable, IAuditable { public Guid Id { get; set; } [Index] public bool IsDeleted { get; set; } [DataType(DataType.DateTime)] public DateTime CreatedOn { get; set; } [DataType(DataType.DateTime)] public DateTime? ModifiedOn { get; set; } [DataType(DataType.DateTime)] public DateTime? DeletedOn { get; set; } } }
using CarModsHeaven.Data.Models.Contracts; using System; namespace CarModsHeaven.Data.Models.Abstracts { public abstract class BaseDataModel : IDeletable, IAuditable { public bool IsDeleted { get; set; } public DateTime? DeletedOn { get; set; } public DateTime CreatedOn { get; set; } public DateTime? ModifiedOn { get; set; } } }
mit
C#
353f65ae28232b7dee9a3c91249faa586de875a1
fix typo
maxwellb/csharp-driver,datastax/csharp-driver,maxwellb/csharp-driver,datastax/csharp-driver
src/Cassandra/GraphProtocol.cs
src/Cassandra/GraphProtocol.cs
// // Copyright (C) DataStax 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. // namespace Cassandra { /// <summary> /// Specifies the different graph protocol versions that are supported by the driver /// </summary> public enum GraphProtocol { /// <summary> /// GraphSON v1. /// </summary> GraphSON1 = 1, /// <summary> /// GraphSON v2. /// </summary> GraphSON2 = 2, /// <summary> /// GraphSON v3. /// </summary> GraphSON3 = 3 } }
// // Copyright (C) DataStax 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. // namespace Cassandra { /// <summary> /// Specifies the different graph protocol versions that are supported by the driver /// </summary> public enum GraphProtocol { /// <summary> /// GraphSON v1. /// </summary> GraphSON1 = 1, /// <summary> /// GraphSON v12. /// </summary> GraphSON2 = 2, /// <summary> /// GraphSON v3. /// </summary> GraphSON3 = 3 } }
apache-2.0
C#
9e28fbe2a54d23e7992cf13d0ae09178cb8577d2
Update HttpContextBaseExtensions.cs
gcsuk/Orchard,bedegaming-aleksej/Orchard,OrchardCMS/Orchard,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,bedegaming-aleksej/Orchard,omidnasri/Orchard,Lombiq/Orchard,jtkech/Orchard,Fogolan/OrchardForWork,Lombiq/Orchard,jagraz/Orchard,JRKelso/Orchard,phillipsj/Orchard,armanforghani/Orchard,sfmskywalker/Orchard,jersiovic/Orchard,SzymonSel/Orchard,jimasp/Orchard,geertdoornbos/Orchard,omidnasri/Orchard,ehe888/Orchard,geertdoornbos/Orchard,Serlead/Orchard,omidnasri/Orchard,jtkech/Orchard,aaronamm/Orchard,IDeliverable/Orchard,bedegaming-aleksej/Orchard,armanforghani/Orchard,sfmskywalker/Orchard,johnnyqian/Orchard,ehe888/Orchard,AdvantageCS/Orchard,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,IDeliverable/Orchard,SzymonSel/Orchard,OrchardCMS/Orchard,omidnasri/Orchard,Fogolan/OrchardForWork,jimasp/Orchard,gcsuk/Orchard,mvarblow/Orchard,Serlead/Orchard,LaserSrl/Orchard,mvarblow/Orchard,geertdoornbos/Orchard,omidnasri/Orchard,AdvantageCS/Orchard,fassetar/Orchard,JRKelso/Orchard,fassetar/Orchard,johnnyqian/Orchard,OrchardCMS/Orchard,jersiovic/Orchard,rtpHarry/Orchard,jagraz/Orchard,fassetar/Orchard,jtkech/Orchard,Praggie/Orchard,yersans/Orchard,hbulzy/Orchard,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,ehe888/Orchard,hannan-azam/Orchard,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,sfmskywalker/Orchard,gcsuk/Orchard,JRKelso/Orchard,johnnyqian/Orchard,omidnasri/Orchard,jagraz/Orchard,Lombiq/Orchard,mvarblow/Orchard,JRKelso/Orchard,armanforghani/Orchard,hbulzy/Orchard,yersans/Orchard,sfmskywalker/Orchard,LaserSrl/Orchard,jagraz/Orchard,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,gcsuk/Orchard,Lombiq/Orchard,sfmskywalker/Orchard,jersiovic/Orchard,geertdoornbos/Orchard,Praggie/Orchard,sfmskywalker/Orchard,AdvantageCS/Orchard,fassetar/Orchard,omidnasri/Orchard,omidnasri/Orchard,jtkech/Orchard,jersiovic/Orchard,phillipsj/Orchard,jimasp/Orchard,sfmskywalker/Orchard,omidnasri/Orchard,bedegaming-aleksej/Orchard,gcsuk/Orchard,Dolphinsimon/Orchard,rtpHarry/Orchard,mvarblow/Orchard,JRKelso/Orchard,Praggie/Orchard,bedegaming-aleksej/Orchard,jagraz/Orchard,SzymonSel/Orchard,IDeliverable/Orchard,armanforghani/Orchard,Fogolan/OrchardForWork,AdvantageCS/Orchard,aaronamm/Orchard,hannan-azam/Orchard,OrchardCMS/Orchard,johnnyqian/Orchard,hannan-azam/Orchard,aaronamm/Orchard,Praggie/Orchard,aaronamm/Orchard,phillipsj/Orchard,geertdoornbos/Orchard,hbulzy/Orchard,fassetar/Orchard,Lombiq/Orchard,jimasp/Orchard,LaserSrl/Orchard,phillipsj/Orchard,johnnyqian/Orchard,phillipsj/Orchard,SzymonSel/Orchard,Dolphinsimon/Orchard,ehe888/Orchard,hbulzy/Orchard,hbulzy/Orchard,Praggie/Orchard,Dolphinsimon/Orchard,LaserSrl/Orchard,rtpHarry/Orchard,mvarblow/Orchard,Fogolan/OrchardForWork,yersans/Orchard,Fogolan/OrchardForWork,Dolphinsimon/Orchard,rtpHarry/Orchard,Dolphinsimon/Orchard,aaronamm/Orchard,sfmskywalker/Orchard,IDeliverable/Orchard,jimasp/Orchard,AdvantageCS/Orchard,rtpHarry/Orchard,Serlead/Orchard,SzymonSel/Orchard,hannan-azam/Orchard,yersans/Orchard,jtkech/Orchard,yersans/Orchard,IDeliverable/Orchard,armanforghani/Orchard,Serlead/Orchard,Serlead/Orchard,hannan-azam/Orchard,LaserSrl/Orchard,jersiovic/Orchard,OrchardCMS/Orchard,ehe888/Orchard
src/Orchard/Mvc/Extensions/HttpContextBaseExtensions.cs
src/Orchard/Mvc/Extensions/HttpContextBaseExtensions.cs
using System.Web; namespace Orchard.Mvc.Extensions { public static class HttpContextBaseExtensions { public static bool IsBackgroundContext(this HttpContextBase httpContextBase) { return httpContextBase == null || httpContextBase is MvcModule.HttpContextPlaceholder; } } public static class HttpContextExtensions { public static bool IsBackgroundHttpContext(this HttpContext httpContext) { return HttpContextAccessor.IsBackgroundHttpContext(httpContext); } } }
using System.Web; namespace Orchard.Mvc.Extensions { public static class HttpContextBaseExtensions { public static bool IsBackgroundContext(this HttpContextBase httpContextBase) { return httpContextBase == null || httpContextBase is MvcModule.HttpContextPlaceholder; } } }
bsd-3-clause
C#
f74331817a34776ce6a95de9a954a598fa0e955f
Bump version
grcodemonkey/iron_sharp
src/SolutionInfo.cs
src/SolutionInfo.cs
using System.Reflection; [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("grcodemonkey")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("2014.06.01.*")] [assembly: AssemblyFileVersion("2014.05.01.0")]
using System.Reflection; [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("grcodemonkey")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("2014.05.23.*")] [assembly: AssemblyFileVersion("2014.05.23.0")]
mit
C#
242428f94c25df7635697f1904fa4200e2703bb8
bump version
ceee/PocketSharp
PocketSharp/Properties/AssemblyInfo.cs
PocketSharp/Properties/AssemblyInfo.cs
using System.Resources; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("PocketSharp")] [assembly: AssemblyDescription("PocketSharp is a .NET class library, that integrates the Pocket API v3")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("cee")] [assembly: AssemblyProduct("PocketSharp")] [assembly: AssemblyCopyright("Copyright © 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.2.1")] [assembly: AssemblyFileVersion("1.2.1")]
using System.Resources; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("PocketSharp")] [assembly: AssemblyDescription("PocketSharp is a .NET class library, that integrates the Pocket API v3")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("cee")] [assembly: AssemblyProduct("PocketSharp")] [assembly: AssemblyCopyright("Copyright © 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.2.0")] [assembly: AssemblyFileVersion("1.2.0")]
mit
C#
e531dc1cb01b034b065963e0f7f6624234b3087c
Update content for feature not enabled
SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice
src/SFA.DAS.EmployerApprenticeshipsService.Web/Views/Shared/FeatureNotEnabled.cshtml
src/SFA.DAS.EmployerApprenticeshipsService.Web/Views/Shared/FeatureNotEnabled.cshtml
 <div class="grid-row"> <div class="column-two-thirds"> <h1 class="heading-xlarge">Under development</h1> <p>This service is currently being developed and you don't yet have access.</p> </div> </div> @section breadcrumb { <div class="breadcrumbs"> <ol> <li><a href="@Url.Action("Index","Home")">Back to homepage</a></li> </ol> </div> }
 <div class="grid-row"> <div class="column-two-thirds"> <h1 class="heading-xlarge">Coming soon</h1> <p>This service isn't available yet.</p> </div> </div> @section breadcrumb { <div class="breadcrumbs"> <ol> <li><a href="@Url.Action("Index","Home")">Back to homepage</a></li> </ol> </div> }
mit
C#
41efbcad6326d3163cc53e0f85edf18bc094207a
Add a stub implementation of VisualStudioProjectTracker.GetProject
dotnet/roslyn,eriawan/roslyn,agocke/roslyn,MichalStrehovsky/roslyn,wvdd007/roslyn,AlekseyTs/roslyn,jcouv/roslyn,bartdesmet/roslyn,tannergooding/roslyn,agocke/roslyn,tmat/roslyn,bartdesmet/roslyn,swaroop-sridhar/roslyn,agocke/roslyn,jmarolf/roslyn,CyrusNajmabadi/roslyn,AmadeusW/roslyn,tmat/roslyn,mavasani/roslyn,nguerrera/roslyn,physhi/roslyn,AlekseyTs/roslyn,reaction1989/roslyn,tmat/roslyn,KirillOsenkov/roslyn,DustinCampbell/roslyn,sharwell/roslyn,heejaechang/roslyn,VSadov/roslyn,MichalStrehovsky/roslyn,abock/roslyn,KevinRansom/roslyn,jmarolf/roslyn,genlu/roslyn,diryboy/roslyn,weltkante/roslyn,ErikSchierboom/roslyn,CyrusNajmabadi/roslyn,mgoertz-msft/roslyn,physhi/roslyn,brettfo/roslyn,xasx/roslyn,panopticoncentral/roslyn,jasonmalinowski/roslyn,wvdd007/roslyn,weltkante/roslyn,genlu/roslyn,aelij/roslyn,AmadeusW/roslyn,eriawan/roslyn,stephentoub/roslyn,jasonmalinowski/roslyn,jcouv/roslyn,genlu/roslyn,DustinCampbell/roslyn,ErikSchierboom/roslyn,VSadov/roslyn,abock/roslyn,jcouv/roslyn,xasx/roslyn,wvdd007/roslyn,jmarolf/roslyn,shyamnamboodiripad/roslyn,KirillOsenkov/roslyn,eriawan/roslyn,brettfo/roslyn,CyrusNajmabadi/roslyn,davkean/roslyn,abock/roslyn,heejaechang/roslyn,mavasani/roslyn,brettfo/roslyn,davkean/roslyn,weltkante/roslyn,swaroop-sridhar/roslyn,KevinRansom/roslyn,diryboy/roslyn,KirillOsenkov/roslyn,mgoertz-msft/roslyn,panopticoncentral/roslyn,tannergooding/roslyn,AmadeusW/roslyn,diryboy/roslyn,MichalStrehovsky/roslyn,panopticoncentral/roslyn,aelij/roslyn,sharwell/roslyn,tannergooding/roslyn,jasonmalinowski/roslyn,aelij/roslyn,gafter/roslyn,stephentoub/roslyn,nguerrera/roslyn,gafter/roslyn,shyamnamboodiripad/roslyn,DustinCampbell/roslyn,AlekseyTs/roslyn,VSadov/roslyn,mgoertz-msft/roslyn,physhi/roslyn,nguerrera/roslyn,stephentoub/roslyn,KevinRansom/roslyn,swaroop-sridhar/roslyn,bartdesmet/roslyn,heejaechang/roslyn,reaction1989/roslyn,davkean/roslyn,sharwell/roslyn,dotnet/roslyn,mavasani/roslyn,ErikSchierboom/roslyn,xasx/roslyn,dotnet/roslyn,shyamnamboodiripad/roslyn,gafter/roslyn,reaction1989/roslyn
src/VisualStudio/Core/Def/Implementation/ProjectSystem/VisualStudioProjectTracker.cs
src/VisualStudio/Core/Def/Implementation/ProjectSystem/VisualStudioProjectTracker.cs
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { internal sealed partial class VisualStudioProjectTracker { private readonly Workspace _workspace; private readonly IThreadingContext _threadingContext; internal ImmutableArray<AbstractProject> ImmutableProjects => ImmutableArray<AbstractProject>.Empty; internal HostWorkspaceServices WorkspaceServices => _workspace.Services; public VisualStudioProjectTracker(Workspace workspace, IThreadingContext threadingContext) { _workspace = workspace; _threadingContext = threadingContext; } /* private void FinishLoad() { // Check that the set of analyzers is complete and consistent. GetAnalyzerDependencyCheckingService()?.ReanalyzeSolutionForConflicts(); } private AnalyzerDependencyCheckingService GetAnalyzerDependencyCheckingService() { var componentModel = (IComponentModel)_serviceProvider.GetService(typeof(SComponentModel)); return componentModel.GetService<AnalyzerDependencyCheckingService>(); } */ public ProjectId GetOrCreateProjectIdForPath(string filePath, string projectDisplayName) { // HACK: to keep F# working, we will ensure we return the ProjectId if there is a project that matches this path. Otherwise, we'll just return // a random ProjectId, which is sufficient for their needs. They'll simply observe there is no project with that ID, and then go and create a // new project. Then they call this function again, and fetch the real ID. return _workspace.CurrentSolution.Projects.FirstOrDefault(p => p.FilePath == filePath)?.Id ?? ProjectId.CreateNewId("ProjectNotFound"); } public AbstractProject GetProject(ProjectId projectId) { // HACK: to keep F# working, we will ensure that if there is a project with that ID, we will return a non-null value, otherwise we'll return null. // It doesn't actually matter *what* the project is, so we'll just return something silly var project = _workspace.CurrentSolution.GetProject(projectId); if (project != null) { return new StubProject(project, _threadingContext); } else { return null; } } private sealed class StubProject : AbstractProject { public StubProject(Project project, IThreadingContext threadingContext) : base(_ => null, project.Name + "_Stub", project.FilePath, null, project.Language, Guid.Empty, null, threadingContext, null) { } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.Shell.Interop; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { internal sealed partial class VisualStudioProjectTracker { private readonly Workspace _workspace; private readonly IThreadingContext _threadingContext; internal ImmutableArray<AbstractProject> ImmutableProjects => ImmutableArray<AbstractProject>.Empty; internal HostWorkspaceServices WorkspaceServices => _workspace.Services; public VisualStudioProjectTracker(Workspace workspace, IThreadingContext threadingContext) { _workspace = workspace; _threadingContext = threadingContext; } /* private void FinishLoad() { // Check that the set of analyzers is complete and consistent. GetAnalyzerDependencyCheckingService()?.ReanalyzeSolutionForConflicts(); } private AnalyzerDependencyCheckingService GetAnalyzerDependencyCheckingService() { var componentModel = (IComponentModel)_serviceProvider.GetService(typeof(SComponentModel)); return componentModel.GetService<AnalyzerDependencyCheckingService>(); } */ public ProjectId GetOrCreateProjectIdForPath(string filePath, string projectDisplayName) { // HACK: to keep F# working, we will ensure we return the ProjectId if there is a project that matches this path. Otherwise, we'll just return // a random ProjectId, which is sufficient for their needs. They'll simply observe there is no project with that ID, and then go and create a // new project. Then they call this function again, and fetch the real ID. return _workspace.CurrentSolution.Projects.FirstOrDefault(p => p.FilePath == filePath)?.Id ?? ProjectId.CreateNewId("ProjectNotFound"); } } }
mit
C#
77048118e7df6eed964c7d14012d9a7e1909d54c
fix test method name
Ky7m/DemoCode,Ky7m/DemoCode,Ky7m/DemoCode,Ky7m/DemoCode
PulumiDemo/AppInsightsResourceTests.cs
PulumiDemo/AppInsightsResourceTests.cs
using System.Linq; using System.Threading.Tasks; using FluentAssertions; using Pulumi; using Pulumi.Azure.AppInsights; using Pulumi.Azure.Core; using Pulumi.Testing; using Xunit; namespace PulumiDemo { public class AppInsightsResourceTests { [Fact] public async Task AppInsightsResourceExists() { var resources = await Deployment.TestAsync<AppInsightsResourceTestStack>(new Mocks(), new TestOptions {StackName = "dev"}); var resourceGroups = resources.OfType<ResourceGroup>().ToList(); resourceGroups.Count.Should().Be(1, "a single resource group is expected"); var appInsights = resources.OfType<Insights>().ToList(); appInsights.Count.Should().Be(1, "a single app insights instance is expected"); } private class AppInsightsResourceTestStack : Stack { public AppInsightsResourceTestStack() { var resourceGroup = new ResourceGroup("www-prod-rg"); var _ = new AppInsightsResource("appi", resourceGroup.Name); } } } }
using System.Linq; using System.Threading.Tasks; using FluentAssertions; using Pulumi; using Pulumi.Azure.AppInsights; using Pulumi.Azure.Core; using Pulumi.Testing; using Xunit; namespace PulumiDemo { public class AppInsightsResourceTests { [Fact] public async Task AppInsightsKeyExists() { var resources = await Deployment.TestAsync<AppInsightsResourceTestStack>(new Mocks(), new TestOptions {StackName = "dev"}); var resourceGroups = resources.OfType<ResourceGroup>().ToList(); resourceGroups.Count.Should().Be(1, "a single resource group is expected"); var appInsights = resources.OfType<Insights>().ToList(); appInsights.Count.Should().Be(1, "a single app insights instance is expected"); } private class AppInsightsResourceTestStack : Stack { public AppInsightsResourceTestStack() { var resourceGroup = new ResourceGroup("www-prod-rg"); var _ = new AppInsightsResource("appi", resourceGroup.Name); } } } }
mit
C#
9bc2f6e5f92222a33455b66bcaf59efba64615f5
disable twitter auth
DanielLarsenNZ/Radiostr,DanielLarsenNZ/Radiostr
Radiostr.Web/App_Start/Startup.Auth.cs
Radiostr.Web/App_Start/Startup.Auth.cs
using System; using System.Collections.Generic; using System.Linq; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using Microsoft.Owin; using Microsoft.Owin.Security.Cookies; using Microsoft.Owin.Security.Google; using Microsoft.Owin.Security.OAuth; using Owin; using Radiostr.Web.Configuration; using Radiostr.Web.Providers; namespace Radiostr.Web { public partial class Startup { static Startup() { PublicClientId = "self"; UserManagerFactory = () => new UserManager<IdentityUser>(new UserStore<IdentityUser>()); OAuthOptions = new OAuthAuthorizationServerOptions { TokenEndpointPath = new PathString("/Token"), Provider = new ApplicationOAuthProvider(PublicClientId, UserManagerFactory), AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"), AccessTokenExpireTimeSpan = TimeSpan.FromDays(14), AllowInsecureHttp = true }; } public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; } public static Func<UserManager<IdentityUser>> UserManagerFactory { get; set; } public static string PublicClientId { get; private set; } // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864 public void ConfigureAuth(IAppBuilder app) { // Enable the application to use a cookie to store information for the signed in user // and to use a cookie to temporarily store information about a user logging in with a third party login provider app.UseCookieAuthentication(new CookieAuthenticationOptions()); app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); // Enable the application to use bearer tokens to authenticate users app.UseOAuthBearerTokens(OAuthOptions); // Uncomment the following lines to enable logging in with third party login providers //app.UseMicrosoftAccountAuthentication( // clientId: "", // clientSecret: ""); //app.UseTwitterAuthentication(TwitterOAuthSettings.Settings.ApiKey, TwitterOAuthSettings.Settings.ApiSecret); //app.UseFacebookAuthentication( // appId: "", // appSecret: ""); app.UseGoogleAuthentication(); } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using Microsoft.Owin; using Microsoft.Owin.Security.Cookies; using Microsoft.Owin.Security.Google; using Microsoft.Owin.Security.OAuth; using Owin; using Radiostr.Web.Configuration; using Radiostr.Web.Providers; namespace Radiostr.Web { public partial class Startup { static Startup() { PublicClientId = "self"; UserManagerFactory = () => new UserManager<IdentityUser>(new UserStore<IdentityUser>()); OAuthOptions = new OAuthAuthorizationServerOptions { TokenEndpointPath = new PathString("/Token"), Provider = new ApplicationOAuthProvider(PublicClientId, UserManagerFactory), AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"), AccessTokenExpireTimeSpan = TimeSpan.FromDays(14), AllowInsecureHttp = true }; } public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; } public static Func<UserManager<IdentityUser>> UserManagerFactory { get; set; } public static string PublicClientId { get; private set; } // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864 public void ConfigureAuth(IAppBuilder app) { // Enable the application to use a cookie to store information for the signed in user // and to use a cookie to temporarily store information about a user logging in with a third party login provider app.UseCookieAuthentication(new CookieAuthenticationOptions()); app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); // Enable the application to use bearer tokens to authenticate users app.UseOAuthBearerTokens(OAuthOptions); // Uncomment the following lines to enable logging in with third party login providers //app.UseMicrosoftAccountAuthentication( // clientId: "", // clientSecret: ""); app.UseTwitterAuthentication(TwitterOAuthSettings.Settings.ApiKey, TwitterOAuthSettings.Settings.ApiSecret); //app.UseFacebookAuthentication( // appId: "", // appSecret: ""); app.UseGoogleAuthentication(); } } }
mit
C#
778562528da8bcde7f3d01a4b79dbd9f33288c5f
remove use of cache region
yuzukwok/IdentityServer3.AccessTokenValidation,liupengf12/IdentityServer3.AccessTokenValidation,faithword/IdentityServer3.AccessTokenValidation,IdentityServer/IdentityServer3.AccessTokenValidation
source/AccessTokenValidation/Cache.cs
source/AccessTokenValidation/Cache.cs
/* * Copyright 2014 Dominick Baier, Brock Allen * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Runtime.Caching; namespace Thinktecture.IdentityServer.v3.AccessTokenValidation { public class Cache : ICache { const string CacheName = "thinktecture.validationCache"; readonly MemoryCache _cache = new MemoryCache(CacheName); public bool Add(string key, object value, DateTimeOffset absoluteExpiration) { return _cache.Add(key, value, absoluteExpiration); } public object Get(string key) { return _cache.Get(key); } } }
/* * Copyright 2014 Dominick Baier, Brock Allen * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Runtime.Caching; namespace Thinktecture.IdentityServer.v3.AccessTokenValidation { public class Cache : ICache { const string CacheRegionName = "thinktecture.validationCache"; readonly MemoryCache _cache = new MemoryCache(CacheRegionName); public bool Add(string key, object value, DateTimeOffset absoluteExpiration) { return _cache.Add(key, value, absoluteExpiration, CacheRegionName); } public object Get(string key) { return _cache.Get(key, CacheRegionName); } } }
apache-2.0
C#
4c53a90e044aee18db8fc0cdd6158fc8a9fd376e
Fix error in JumpListService not adding resent folders
michael-reichenauer/GitMind
GitMind/RepositoryViews/Open/JumpListService.cs
GitMind/RepositoryViews/Open/JumpListService.cs
using System.IO; using System.Windows; using System.Windows.Shell; using GitMind.ApplicationHandling; namespace GitMind.RepositoryViews.Open { internal class JumpListService : IJumpListService { private static readonly int MaxTitleLength = 25; public void AddPath(string path) { if (string.IsNullOrEmpty(path) || !Directory.Exists(path)) { return; } JumpList jumpList = JumpList.GetJumpList(Application.Current) ?? new JumpList(); JumpTask jumpTask = new JumpTask { Title = GetTitle(path), ApplicationPath = ProgramInfo.GetInstallFilePath(), Arguments = GetOpenArguments(path), IconResourcePath = ProgramInfo.GetInstallFilePath(), Description = path }; jumpList.ShowRecentCategory = true; JumpList.AddToRecentCategory(jumpTask); JumpList.SetJumpList(Application.Current, jumpList); } private static string GetTitle(string path) { string name = Path.GetFileNameWithoutExtension(path) ?? path; return name.Length < MaxTitleLength ? name : name.Substring(0, MaxTitleLength) + "..."; } private static string GetOpenArguments(string path) => $"/d:\"{path}\""; } }
using System.IO; using System.Windows; using System.Windows.Shell; using GitMind.ApplicationHandling; using GitMind.ApplicationHandling.SettingsHandling; namespace GitMind.RepositoryViews.Open { internal class JumpListService : IJumpListService { private static readonly int MaxTitleLength = 25; public void AddPath(string path) { if (string.IsNullOrEmpty(path) || !File.Exists(path)) { return; } JumpList jumpList = JumpList.GetJumpList(Application.Current) ?? new JumpList(); JumpTask jumpTask = new JumpTask { Title = GetTitle(path), ApplicationPath = ProgramInfo.GetInstallFilePath(), Arguments = GetOpenArguments(path), IconResourcePath = ProgramInfo.GetInstallFilePath(), Description = path }; jumpList.ShowRecentCategory = true; JumpList.AddToRecentCategory(jumpTask); JumpList.SetJumpList(Application.Current, jumpList); } private static string GetTitle(string path) { string name = Path.GetFileNameWithoutExtension(path) ?? path; return name.Length < MaxTitleLength ? name : name.Substring(0, MaxTitleLength) + "..."; } private static string GetOpenArguments(string path) => $"/d:\"{path}\""; } }
mit
C#
ac9f9bb13039101a96420a53590efa3e344c876d
fix doc-comment file attribute
t-ashula/bl4n
bl4n/ISpace.cs
bl4n/ISpace.cs
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ISpace.cs"> // bl4n - Backlog.jp API Client library // this file is part of bl4n, license under MIT license. http://t-ashula.mit-license.org/2015 // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System; using System.Linq; using System.Runtime.Serialization; namespace BL4N.Data { /// <summary> スペース情報の公開インタフェース </summary> public interface ISpace { string SpaceKey { get; set; } string Name { get; set; } long OwnerId { get; set; } string Lang { get; set; } // XXX: use System.TimeZone? string Timezone { get; set; } string ReportSendTime { get; set; } string TextFormattingRule { get; set; } DateTime Created { get; set; } DateTime Updated { get; set; } } /// <summary> スペース情報の内部用データクラス API との serialize 用 </summary> [DataContract] internal class Space : ISpace { [DataMember(Name = "spaceKey")] public string SpaceKey { get; set; } [DataMember(Name = "name")] public string Name { get; set; } [DataMember(Name = "ownerId")] public long OwnerId { get; set; } [DataMember(Name = "lang")] public string Lang { get; set; } [DataMember(Name = "timezone")] public string Timezone { get; set; } [DataMember(Name = "reportSendTime")] public string ReportSendTime { get; set; } [DataMember(Name = "textFormattingRule")] public string TextFormattingRule { get; set; } [DataMember(Name = "created")] public DateTime Created { get; set; } [DataMember(Name = "updated")] public DateTime Updated { get; set; } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="BacklogTestsForRealServer.cs"> // bl4n - Backlog.jp API Client library // this file is part of bl4n, license under MIT license. http://t-ashula.mit-license.org/2015 // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System; using System.Linq; using System.Runtime.Serialization; namespace BL4N.Data { /// <summary> スペース情報の公開インタフェース </summary> public interface ISpace { string SpaceKey { get; set; } string Name { get; set; } long OwnerId { get; set; } string Lang { get; set; } // XXX: use System.TimeZone? string Timezone { get; set; } string ReportSendTime { get; set; } string TextFormattingRule { get; set; } DateTime Created { get; set; } DateTime Updated { get; set; } } /// <summary> スペース情報の内部用データクラス API との serialize 用 </summary> [DataContract] internal class Space : ISpace { [DataMember(Name = "spaceKey")] public string SpaceKey { get; set; } [DataMember(Name = "name")] public string Name { get; set; } [DataMember(Name = "ownerId")] public long OwnerId { get; set; } [DataMember(Name = "lang")] public string Lang { get; set; } [DataMember(Name = "timezone")] public string Timezone { get; set; } [DataMember(Name = "reportSendTime")] public string ReportSendTime { get; set; } [DataMember(Name = "textFormattingRule")] public string TextFormattingRule { get; set; } [DataMember(Name = "created")] public DateTime Created { get; set; } [DataMember(Name = "updated")] public DateTime Updated { get; set; } } }
mit
C#
264a4a35da37537136610f6766ec74617b85f284
Add rendering, no avail meanwhile
sheix/GameEngine,sheix/GameEngine,sheix/GameEngine
Infrastructure/SceneRenderer.cs
Infrastructure/SceneRenderer.cs
using System; using OpenTK; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL; using OpenTK.Input; using System.Drawing; namespace Infrastructure { public class SceneRenderer : GameWindow { public SceneRenderer () : base(800, 600, GraphicsMode.Default, "GameEngine v0.01", GameWindowFlags.Default, DisplayDevice.Default, 2, 1, GraphicsContextFlags.Default) { VSync = VSyncMode.On; } protected override void OnLoad(EventArgs e) { base.OnLoad(e); GL.ClearColor(Color.Black); GL.Enable(EnableCap.DepthTest); GL.Enable( EnableCap.Lighting ); GL.Enable( EnableCap.Light0 ); } protected override void OnUnload( EventArgs e ) { base.OnUnload( e ); // Object.Dispose(); } protected override void OnResize(EventArgs e) { base.OnResize(e); GL.Viewport(ClientRectangle); } protected override void OnUpdateFrame(FrameEventArgs e) { base.OnUpdateFrame(e); GL.PolygonMode(MaterialFace.FrontAndBack, PolygonMode.Line); GL.Begin(BeginMode.Quads); GL.Clear(ClearBufferMask.ColorBufferBit); GL.LoadIdentity (); //render scene GL.Color3(Color.White); GL.Vertex2(0.5, 0.5); GL.Vertex2(0.6, 0.5); GL.Vertex2(0.6, 0.6); GL.Vertex2(0.5, 0.6); GL.End (); if (Keyboard[Key.Escape]) Exit(); } } }
using System; using OpenTK; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL; using OpenTK.Input; namespace Infrastructure { public class SceneRenderer : GameWindow { public SceneRenderer () : base(800, 600, GraphicsMode.Default, "GameEngine v0.01", GameWindowFlags.Default, DisplayDevice.Default, 2, 1, GraphicsContextFlags.Default) { VSync = VSyncMode.On; } protected override void OnLoad(EventArgs e) { base.OnLoad(e); GL.ClearColor(System.Drawing.Color.Black); GL.Enable(EnableCap.DepthTest); GL.Enable( EnableCap.Lighting ); GL.Enable( EnableCap.Light0 ); } protected override void OnUnload( EventArgs e ) { base.OnUnload( e ); // Object.Dispose(); } protected override void OnResize(EventArgs e) { base.OnResize(e); GL.Viewport(ClientRectangle); } protected override void OnUpdateFrame(FrameEventArgs e) { base.OnUpdateFrame(e); //render scene if (Keyboard[Key.Escape]) Exit(); } } }
mit
C#
6a0498331d2b4c4f8db7f845b1f2a8f65f3ab499
Increase timeout for running in container
NimbusAPI/Nimbus,NimbusAPI/Nimbus
tests/Nimbus.UnitTests/MulticastRequestResponseTests/WhenTakingTwoResponses.cs
tests/Nimbus.UnitTests/MulticastRequestResponseTests/WhenTakingTwoResponses.cs
using System; using System.Linq; using NUnit.Framework; using Shouldly; namespace Nimbus.UnitTests.MulticastRequestResponseTests { [TestFixture] internal class WhenTakingTwoResponses : GivenAWrapperWithTwoResponses { private readonly TimeSpan _timeout = TimeSpan.FromSeconds(1.5); private string[] _result; protected override void When() { _result = Subject.ReturnResponsesOpportunistically(_timeout).Take(2).ToArray(); } [Test] public void TheElapsedTimeShouldBeLessThanTheTimeout() { ElapsedTime.ShouldBeLessThan(_timeout); } [Test] public void ThereShouldBeTwoResults() { _result.Count().ShouldBe(2); } } }
using System; using System.Linq; using NUnit.Framework; using Shouldly; namespace Nimbus.UnitTests.MulticastRequestResponseTests { [TestFixture] internal class WhenTakingTwoResponses : GivenAWrapperWithTwoResponses { private readonly TimeSpan _timeout = TimeSpan.FromSeconds(1); private string[] _result; protected override void When() { _result = Subject.ReturnResponsesOpportunistically(_timeout).Take(2).ToArray(); } [Test] public void TheElapsedTimeShouldBeLessThanTheTimeout() { ElapsedTime.ShouldBeLessThan(_timeout); } [Test] public void ThereShouldBeTwoResults() { _result.Count().ShouldBe(2); } } }
mit
C#
0bca71f3e9996b846cc425def0c071397fddc552
Change button padding
danielchalmers/SteamAccountSwitcher
SteamAccountSwitcher/AccountHandler.cs
SteamAccountSwitcher/AccountHandler.cs
#region using System.Collections.Generic; using System.Windows; using System.Windows.Controls; #endregion namespace SteamAccountSwitcher { internal class AccountHandler { private readonly List<Account> _accounts; private readonly StackPanel _stackPanel; private int SelectedIndex = -1; public AccountHandler(StackPanel stackPanel) { _accounts = new List<Account>(); _stackPanel = stackPanel; } public void LogOut() { Scripts.Run(Scripts.Close, new Account()); } public void LogIn(Account account) { Scripts.Run(Scripts.Open, account); } public void Add(Account account) { _accounts.Add(account); Refresh(); } public void Refresh() { // Remove all buttons. _stackPanel.Children.Clear(); // Add new buttons with saved shortcut data foreach (var account in _accounts) { var btn = new Button { Content = new TextBlock {Text = account.Username, TextWrapping = TextWrapping.Wrap}, Height = 32, HorizontalContentAlignment = HorizontalAlignment.Left, Margin = new Thickness(0, 0, 0, 8), Padding = new Thickness(4,0,0,0) }; btn.Click += Button_Click; btn.MouseEnter += delegate{SelectedIndex = _stackPanel.Children.IndexOf(btn);}; _stackPanel.Children.Add(btn); } } private void Button_Click(object sender, RoutedEventArgs e) { LogIn(_accounts[SelectedIndex]); } } }
#region using System.Collections.Generic; using System.Windows; using System.Windows.Controls; #endregion namespace SteamAccountSwitcher { internal class AccountHandler { private readonly List<Account> _accounts; private readonly StackPanel _stackPanel; private int SelectedIndex = -1; public AccountHandler(StackPanel stackPanel) { _accounts = new List<Account>(); _stackPanel = stackPanel; } public void LogOut() { Scripts.Run(Scripts.Close, new Account()); } public void LogIn(Account account) { Scripts.Run(Scripts.Open, account); } public void Add(Account account) { _accounts.Add(account); Refresh(); } public void Refresh() { // Remove all buttons. _stackPanel.Children.Clear(); // Add new buttons with saved shortcut data foreach (var account in _accounts) { var btn = new Button { Content = new TextBlock {Text = account.Username, TextWrapping = TextWrapping.Wrap}, Height = 32, HorizontalContentAlignment = HorizontalAlignment.Left, Margin = new Thickness(0, 0, 0, 8) }; btn.Click += Button_Click; btn.MouseEnter += delegate{SelectedIndex = _stackPanel.Children.IndexOf(btn);}; _stackPanel.Children.Add(btn); } } private void Button_Click(object sender, RoutedEventArgs e) { LogIn(_accounts[SelectedIndex]); } } }
mit
C#
4d52ea305974ecf4f7e571f1925238046b7df2aa
add ToList to SignumControllerFactory
avifatal/framework,AlejandroCano/framework,signumsoftware/framework,signumsoftware/framework,AlejandroCano/framework,avifatal/framework
Signum.React/Facades/SignumControllerFactory.cs
Signum.React/Facades/SignumControllerFactory.cs
using System; using System.Collections.Generic; using System.Linq; using Signum.Utilities; using System.Reflection; using Microsoft.AspNetCore.Mvc.ApplicationParts; using Microsoft.AspNetCore.Mvc.Controllers; namespace Signum.React { public class SignumControllerFactory : IApplicationFeatureProvider<ControllerFeature> { public Assembly MainAssembly { get; set; } public SignumControllerFactory(Assembly mainAssembly) : base() { this.MainAssembly = mainAssembly; } public static HashSet<Type> AllowedControllers { get; private set; } = new HashSet<Type>(); public static void RegisterController<T>() { AllowedControllers.Add(typeof(T)); } public static Dictionary<Assembly, HashSet<string>> AllowedAreas { get; private set; } = new Dictionary<Assembly, HashSet<string>>(); public static void RegisterArea(MethodBase? mb) => RegisterArea(mb!.DeclaringType!); public static void RegisterArea(Type type) { AllowedAreas.GetOrCreate(type.Assembly).Add(type.Namespace!); } public void PopulateFeature(IEnumerable<ApplicationPart> parts, ControllerFeature feature) { var allowed = feature.Controllers.Where(ti => ti.Assembly == MainAssembly || (AllowedAreas.TryGetC(ti.Assembly)?.Any(ns => ti.Namespace!.StartsWith(ns)) ?? false) || AllowedControllers.Contains(ti.AsType())); var toRemove = feature.Controllers.Where(ti => !allowed.Contains(ti)).ToList(); feature.Controllers.RemoveAll(ti => toRemove.Contains(ti)); } } }
using System; using System.Collections.Generic; using System.Linq; using Signum.Utilities; using System.Reflection; using Microsoft.AspNetCore.Mvc.ApplicationParts; using Microsoft.AspNetCore.Mvc.Controllers; namespace Signum.React { public class SignumControllerFactory : IApplicationFeatureProvider<ControllerFeature> { public Assembly MainAssembly { get; set; } public SignumControllerFactory(Assembly mainAssembly) : base() { this.MainAssembly = mainAssembly; } public static HashSet<Type> AllowedControllers { get; private set; } = new HashSet<Type>(); public static void RegisterController<T>() { AllowedControllers.Add(typeof(T)); } public static Dictionary<Assembly, HashSet<string>> AllowedAreas { get; private set; } = new Dictionary<Assembly, HashSet<string>>(); public static void RegisterArea(MethodBase? mb) => RegisterArea(mb!.DeclaringType!); public static void RegisterArea(Type type) { AllowedAreas.GetOrCreate(type.Assembly).Add(type.Namespace!); } public void PopulateFeature(IEnumerable<ApplicationPart> parts, ControllerFeature feature) { var allowed = feature.Controllers.Where(ti => ti.Assembly == MainAssembly || (AllowedAreas.TryGetC(ti.Assembly)?.Any(ns => ti.Namespace!.StartsWith(ns)) ?? false) || AllowedControllers.Contains(ti.AsType())); var toRemove = feature.Controllers.Where(ti => !allowed.Contains(ti)); feature.Controllers.RemoveAll(ti => toRemove.Contains(ti)); } } }
mit
C#
0729d9d36652e2a48fd08e5122c24d3b94176a9f
Fix bug not properly propagating route arguments
kswoll/WootzJs,kswoll/WootzJs,kswoll/WootzJs,x335/WootzJs,x335/WootzJs,x335/WootzJs
WootzJs.Mvc/ControllerActionInvoker.cs
WootzJs.Mvc/ControllerActionInvoker.cs
using System; using System.Linq; using System.Reflection; using System.Threading.Tasks; namespace WootzJs.Mvc { public class ControllerActionInvoker : IActionInvoker { public Task<ActionResult> InvokeAction(ControllerContext context, MethodInfo action) { var parameters = action.GetParameters(); var args = new object[parameters.Length]; for (var i = 0; i < parameters.Length; i++) { var value = context.Controller.RouteData[parameters[i].Name]; args[i] = value; } // If async if (action.ReturnType == typeof(Task<ActionResult>)) { return (Task<ActionResult>)action.Invoke(context.Controller, args); } // If synchronous else { var actionResult = (ActionResult)action.Invoke(context.Controller, args); return Task.FromResult(actionResult); } } } }
using System; using System.Linq; using System.Reflection; using System.Threading.Tasks; namespace WootzJs.Mvc { public class ControllerActionInvoker : IActionInvoker { public Task<ActionResult> InvokeAction(ControllerContext context, MethodInfo action) { var parameters = action.GetParameters(); var args = new object[parameters.Length]; // If async if (action.ReturnType == typeof(Task<ActionResult>)) { return (Task<ActionResult>)action.Invoke(context.Controller, args); } // If synchronous else { var actionResult = (ActionResult)action.Invoke(context.Controller, args); return Task.FromResult(actionResult); } } } }
mit
C#
e77eddc8355615b2e126c35ac80f4a2c18c30817
Support new PowerShell binary name
mrward/monodevelop-powershell-addin
src/MonoDevelop.PowerShell/MonoDevelop.PowerShell/PowerShellPathLocator.cs
src/MonoDevelop.PowerShell/MonoDevelop.PowerShell/PowerShellPathLocator.cs
// // PowerShellPathLocator.cs // // Author: // Matt Ward <matt.ward@xamarin.com> // // Copyright (c) 2016 Xamarin Inc. (http://xamarin.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.IO; using MonoDevelop.Core; namespace MonoDevelop.PowerShell { class PowerShellPathLocator { static readonly PowerShellPathLocator instance = new PowerShellPathLocator (); PowerShellPathLocator () { FindPowerShellPath (); } public static bool Exists { get { return instance.PowerShellPathExists; } } public static string PowerShellPath { get { return instance.PowerShellExePath; } } bool PowerShellPathExists { get; set; } string PowerShellExePath { get; set; } void FindPowerShellPath () { if (Platform.IsWindows) { PowerShellExePath = GetWindowsPowerShellExePath (); } else if (Platform.IsMac) { PowerShellExePath = "/usr/local/bin/pwsh"; if (!File.Exists (PowerShellExePath)) { PowerShellExePath = "/usr/local/bin/powershell"; } } else { PowerShellExePath = "/usr/bin/pwsh"; if (!File.Exists (PowerShellExePath)) { PowerShellExePath = "/usr/bin/powershell"; } } PowerShellPathExists = File.Exists (PowerShellExePath); if (!PowerShellPathExists) { PowerShellExePath = null; } } static string GetWindowsPowerShellExePath () { bool use32Bit = true; string windowsFolder = Environment.GetFolderPath (Environment.SpecialFolder.Windows); string processorArchitecture = Environment.GetEnvironmentVariable ("PROCESSOR_ARCHITEW6432"); if (use32Bit || string.IsNullOrEmpty (processorArchitecture)) { return Path.Combine (windowsFolder, @"System32\WindowsPowerShell\v1.0\powershell.exe"); } return Path.Combine (windowsFolder, @"Sysnative\WindowsPowerShell\v1.0\powershell.exe"); } } }
// // PowerShellPathLocator.cs // // Author: // Matt Ward <matt.ward@xamarin.com> // // Copyright (c) 2016 Xamarin Inc. (http://xamarin.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.IO; using MonoDevelop.Core; namespace MonoDevelop.PowerShell { class PowerShellPathLocator { static readonly PowerShellPathLocator instance = new PowerShellPathLocator (); PowerShellPathLocator () { FindPowerShellPath (); } public static bool Exists { get { return instance.PowerShellPathExists; } } public static string PowerShellPath { get { return instance.PowerShellExePath; } } bool PowerShellPathExists { get; set; } string PowerShellExePath { get; set; } void FindPowerShellPath () { if (Platform.IsWindows) { PowerShellExePath = GetWindowsPowerShellExePath (); } else if (Platform.IsMac) { PowerShellExePath = "/usr/local/bin/powershell"; } else { PowerShellExePath = "/usr/bin/powershell"; } PowerShellPathExists = File.Exists (PowerShellExePath); if (!PowerShellPathExists) { PowerShellExePath = null; } } static string GetWindowsPowerShellExePath () { bool use32Bit = true; string windowsFolder = Environment.GetFolderPath (Environment.SpecialFolder.Windows); string processorArchitecture = Environment.GetEnvironmentVariable ("PROCESSOR_ARCHITEW6432"); if (use32Bit || string.IsNullOrEmpty (processorArchitecture)) { return Path.Combine (windowsFolder, @"System32\WindowsPowerShell\v1.0\powershell.exe"); } return Path.Combine (windowsFolder, @"Sysnative\WindowsPowerShell\v1.0\powershell.exe"); } } }
mit
C#
1c40e109b3468e3056924db680b713eed05d144d
Update tests
CareerHub/.NET-CareerHub-API-Client,CareerHub/.NET-CareerHub-API-Client
Test/API/Authorization/AuthorizationApiFacts.cs
Test/API/Authorization/AuthorizationApiFacts.cs
using CareerHub.Client.API.Authorization; using System; using System.Collections.Generic; using System.Linq; using System.Text; using Xunit; namespace CareerHub.Client.Tests.API.Authorization { public class AuthorizationApiFacts { [Fact] public void Get_TokenInfo_Url() { string accessToken = "adsfasdfasdf"; string scope1 = "Test.Scope.1"; string scope2 = "Test.Scope.2"; string expected = String.Format("/tokeninfo?access_token={0}&scopes={1}&scopes={2}", accessToken, scope1, scope2); string actual = AuthorizationApi.GetTokenInfoUrl(accessToken, new string[] { scope1, scope2 }); Assert.Equal(expected, actual); } [Fact] public void Get_TokenInfo_Url_Throws_Null_Access_Token() { Assert.Throws<ArgumentNullException>(() => { AuthorizationApi.GetTokenInfoUrl(null, new string[] { }); }); } [Fact] public void Get_TokenInfo_Url_Throws_Null_Scopes() { Assert.Throws<ArgumentNullException>(() => { AuthorizationApi.GetTokenInfoUrl("test", null); }); } } }
using CareerHub.Client.API.Authorization; using System; using System.Collections.Generic; using System.Linq; using System.Text; using Xunit; namespace CareerHub.Client.Tests.API.Authorization { public class AuthorizationApiFacts { [Fact] public void Get_TokenInfo_Url() { string accessToken = "adsfasdfasdf"; string scope1 = "Test.Scope.1"; string scope2 = "Test.Scope.2"; string expected = String.Format("/oauth/tokeninfo?access_token={0}&scopes={1}&scopes={2}", accessToken, scope1, scope2); string actual = AuthorizationApi.GetTokenInfoUrl(accessToken, new string[] { scope1, scope2 }); Assert.Equal(expected, actual); } [Fact] public void Get_TokenInfo_Url_Throws_Null_Access_Token() { Assert.Throws<ArgumentNullException>(() => { AuthorizationApi.GetTokenInfoUrl(null, new string[] { }); }); } [Fact] public void Get_TokenInfo_Url_Throws_Null_Scopes() { Assert.Throws<ArgumentNullException>(() => { AuthorizationApi.GetTokenInfoUrl("test", null); }); } } }
mit
C#
418339dde3394a3e92d2c56fd286e4b85638a9d7
Increase this trial count and write out the absolute error.
airbreather/AirBreather.Common
Source/AirBreather.Common/AirBreather.Common.Tests/WeightedRandomPickerTests.cs
Source/AirBreather.Common/AirBreather.Common.Tests/WeightedRandomPickerTests.cs
using System; using System.Collections.Generic; using System.Linq; using Xunit; using Xunit.Abstractions; using AirBreather.Random; namespace AirBreather.Tests { public sealed class WeightedRandomPickerTests { private readonly ITestOutputHelper output; public WeightedRandomPickerTests(ITestOutputHelper output) => this.output = output; [Fact] public void TestWeightedRandomPicker() { var builder = new WeightedRandomPicker<string>.Builder(); var valsWithWeights = new Dictionary<string, int> { ["orly"] = 2, ["yarly"] = 1, ["nowai"] = 77, ["yaweh"] = 2 }; foreach (var (item, weight) in valsWithWeights) { builder = builder.AddWithWeight(item, weight); } var picker = builder.Build(); var dct = valsWithWeights.Keys.ToDictionary(x => x, x => 0); const int TrialCount = 500000; ulong[] span = new ulong[TrialCount]; CryptographicRandomGenerator.FillBuffer(span.AsSpan().AsBytes()); for (int i = 0; i < span.Length; ++i) { ++dct[picker.Pick(span[i] / (double)UInt64.MaxValue)]; } double scalar = TrialCount / (double)valsWithWeights.Values.Sum(); var expect = valsWithWeights.ToDictionary(kvp => kvp.Key, kvp => kvp.Value * scalar); foreach (var (item, actualCount) in dct) { this.output.WriteLine("{0} appeared {1} times (expected {2}) (absolute error: {3:P3})", item, actualCount, expect[item], Math.Abs(actualCount - expect[item]) / expect[item]); } } } }
using System; using System.Collections.Generic; using System.Linq; using Xunit; using Xunit.Abstractions; using AirBreather.Random; namespace AirBreather.Tests { public sealed class WeightedRandomPickerTests { private readonly ITestOutputHelper output; public WeightedRandomPickerTests(ITestOutputHelper output) => this.output = output; [Fact] public void TestWeightedRandomPicker() { var builder = new WeightedRandomPicker<string>.Builder(); var valsWithWeights = new Dictionary<string, int> { ["orly"] = 2, ["yarly"] = 1, ["nowai"] = 77, ["yaweh"] = 2 }; foreach (var (item, weight) in valsWithWeights) { builder = builder.AddWithWeight(item, weight); } var picker = builder.Build(); var dct = valsWithWeights.Keys.ToDictionary(x => x, x => 0); const int TrialCount = 10000; ulong[] span = new ulong[TrialCount]; CryptographicRandomGenerator.FillBuffer(span.AsSpan().AsBytes()); for (int i = 0; i < span.Length; ++i) { ++dct[picker.Pick(span[i] / (double)UInt64.MaxValue)]; } double scalar = TrialCount / (double)valsWithWeights.Values.Sum(); var expect = valsWithWeights.ToDictionary(kvp => kvp.Key, kvp => kvp.Value * scalar); foreach (var (item, actualCount) in dct) { this.output.WriteLine("{0} appeared {1} times (expected {2})", item, actualCount, expect[item]); } } } }
bsd-3-clause
C#
5d3056b1a6eebedf8770b42fdfd79e726c739f50
Make sure cipher text is not the same as clear text in tests
smoy/Xamarin.Droid.AesCrypto
AesCryptoSample/AesTest.cs
AesCryptoSample/AesTest.cs
using System; using Xunit; using Com.Tozny.Crypto.Android; using System.Text; using Android.Content; using Xamarin.Droid.AesCrypto.Util; using System.Linq; namespace AesCryptoSample { public class AesTest { public static Context context; public const string UnitTestAlias = "Unit Test"; public AesTest () { } [Fact] public void TestAesCbcWithIntegrityRoundTrip () { var privateKey = AesCbcWithIntegrity.GenerateKey (); var mySecretText = "This is my secret"; var mySecretBytes = Encoding.UTF8.GetBytes (mySecretText); var cipherText = AesCbcWithIntegrity.Encrypt (mySecretBytes, privateKey); Assert.False (AesCbcWithIntegrity.ConstantTimeEq (mySecretBytes, cipherText.GetCipherText ())); var decryptedBytes = AesCbcWithIntegrity.Decrypt (cipherText, privateKey); var decryptedText = Encoding.UTF8.GetString (decryptedBytes); Assert.True (mySecretText == decryptedText, string.Format("Expect {0} but got {1}", mySecretText, decryptedText)); } [Fact] public void TestSecretKeyWrapperRoundTrip () { var secretKeyWrapper = new SecretKeyWrapper (context, UnitTestAlias); var secretKeys = AesCbcWithIntegrity.GenerateKey (); var wrappedKey = secretKeyWrapper.Wrap (secretKeys.ConfidentialityKey); Assert.False (AesCbcWithIntegrity.ConstantTimeEq (secretKeys.ConfidentialityKey.GetEncoded (), wrappedKey)); var unwrappedKey = secretKeyWrapper.Unwrap (wrappedKey); Assert.True (AesCbcWithIntegrity.ConstantTimeEq (secretKeys.ConfidentialityKey.GetEncoded (), unwrappedKey.GetEncoded())); } [Fact] public void CompleteExample () { var mySecretText = "This is my secret"; const string completeExampleAlias = "CompleteExample"; var encryptedBundle = EncryptionUtil.Encrypt (context, completeExampleAlias, mySecretText); Assert.False (mySecretText == encryptedBundle.EncryptedText); var decryptedText = EncryptionUtil.Decrypt (context, completeExampleAlias, encryptedBundle); Assert.True (mySecretText == decryptedText, string.Format ("Expect {0} but got {1}", mySecretText, decryptedText)); } } }
using System; using Xunit; using Com.Tozny.Crypto.Android; using System.Text; using Android.Content; using Xamarin.Droid.AesCrypto.Util; using System.Linq; namespace AesCryptoSample { public class AesTest { public static Context context; public const string UnitTestAlias = "Unit Test"; public AesTest () { } [Fact] public void TestAesCbcWithIntegrityRoundTrip () { var privateKey = AesCbcWithIntegrity.GenerateKey (); var mySecretText = "This is my secret"; var mySecretBytes = Encoding.UTF8.GetBytes (mySecretText); var cipherText = AesCbcWithIntegrity.Encrypt (mySecretBytes, privateKey); var decryptedBytes = AesCbcWithIntegrity.Decrypt (cipherText, privateKey); var decryptedText = Encoding.UTF8.GetString (decryptedBytes); Assert.True (mySecretText == decryptedText, string.Format("Expect {0} but got {1}", mySecretText, decryptedText)); } [Fact] public void TestSecretKeyWrapperRoundTrip () { var secretKeyWrapper = new SecretKeyWrapper (context, UnitTestAlias); var secretKeys = AesCbcWithIntegrity.GenerateKey (); var wrappedKey = secretKeyWrapper.Wrap (secretKeys.ConfidentialityKey); var unwrappedKey = secretKeyWrapper.Unwrap (wrappedKey); Assert.True (AesCbcWithIntegrity.ConstantTimeEq (secretKeys.ConfidentialityKey.GetEncoded (), unwrappedKey.GetEncoded())); } [Fact] public void CompleteExample () { var mySecretText = "This is my secret"; const string completeExampleAlias = "CompleteExample"; var encryptedBundle = EncryptionUtil.Encrypt (context, completeExampleAlias, mySecretText); var decryptedText = EncryptionUtil.Decrypt (context, completeExampleAlias, encryptedBundle); Assert.True (mySecretText == decryptedText, string.Format ("Expect {0} but got {1}", mySecretText, decryptedText)); } } }
mit
C#
7cc4104cedd66406a9b1ddf725b62263c5147c0e
add utility to build required claims list from scopes
0xFireball/KQAnalytics3,0xFireball/KQAnalytics3,0xFireball/KQAnalytics3
KQAnalytics3/src/KQAnalytics3/Services/Authentication/ClientApiAccessValidator.cs
KQAnalytics3/src/KQAnalytics3/Services/Authentication/ClientApiAccessValidator.cs
using KQAnalytics3.Configuration.Access; using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; namespace KQAnalytics3.Services.Authentication { public static class ClientApiAccessValidator { public static string AuthTypeKey => "authType"; public static string AccessScopeKey => "accessScope"; public static IEnumerable<Claim> GetAuthClaims(ApiAccessKey accessKey) { var claimList = new List<Claim> { new Claim(AuthTypeKey, "stateless"), }; var accessScopeClaims = accessKey.AccessScopes.Select(accessScope => new Claim(AccessScopeKey, accessScope.ToString())); claimList.AddRange(accessScopeClaims); return claimList; } public static ApiAccessScope GetAccessScope(Claim accessScopeClaim) { return (ApiAccessScope)Enum.Parse(typeof(ApiAccessScope), accessScopeClaim.Value); } public static IEnumerable<Claim> GetAccessClaimListFromScopes(ApiAccessScope[] scopes) { return scopes.Select(x => new Claim(AccessScopeKey, x.ToString())); } } }
using KQAnalytics3.Configuration.Access; using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; namespace KQAnalytics3.Services.Authentication { public static class ClientApiAccessValidator { public static string AuthTypeKey => "authType"; public static string AccessScopeKey => "accessScope"; public static IEnumerable<Claim> GetAuthClaims(ApiAccessKey accessKey) { var claimList = new List<Claim> { new Claim(AuthTypeKey, "stateless"), }; var accessScopeClaims = accessKey.AccessScopes.Select(accessScope => new Claim(AccessScopeKey, accessScope.ToString())); claimList.AddRange(accessScopeClaims); return claimList; } public static ApiAccessScope GetAccessScope(Claim accessScopeClaim) { return (ApiAccessScope)Enum.Parse(typeof(ApiAccessScope), accessScopeClaim.Value); } } }
agpl-3.0
C#
0347c5afd7706b068b593d48fd8ce917383783b1
Fix serialization of the critical hit field. (#1000)
LtRipley36706/ACE,ACEmulator/ACE,ACEmulator/ACE,ACEmulator/ACE,LtRipley36706/ACE,LtRipley36706/ACE
Source/ACE.Server/Network/GameEvent/Events/GameEventAttackerNotification.cs
Source/ACE.Server/Network/GameEvent/Events/GameEventAttackerNotification.cs
using System; using ACE.Entity.Enum; using ACE.Server.Network.Enum; namespace ACE.Server.Network.GameEvent.Events { public class GameEventAttackerNotification : GameEventMessage { public GameEventAttackerNotification(Session session, string defenderName, DamageType damageType, float percent, uint damage, bool criticalHit, AttackConditions attackConditions) : base(GameEventType.AttackerNotification, GameMessageGroup.UIQueue, session) { Writer.WriteString16L(defenderName); Writer.Write((uint)damageType); Writer.Write((double)percent); Writer.Write(damage); Writer.Write(Convert.ToUInt32(criticalHit)); Writer.Write((UInt64)attackConditions); } } }
using System; using ACE.Entity.Enum; using ACE.Server.Network.Enum; namespace ACE.Server.Network.GameEvent.Events { public class GameEventAttackerNotification : GameEventMessage { public GameEventAttackerNotification(Session session, string defenderName, DamageType damageType, float percent, uint damage, bool criticalHit, AttackConditions attackConditions) : base(GameEventType.AttackerNotification, GameMessageGroup.UIQueue, session) { Writer.WriteString16L(defenderName); Writer.Write((uint)damageType); Writer.Write((double)percent); Writer.Write(damage); Writer.Write(Convert.ToUInt16(criticalHit)); Writer.Write((UInt64)attackConditions); } } }
agpl-3.0
C#
1c67ef7c9190ae8bdfe36cce0ed6d6e5576b040c
Make catchup clock support seeking
peppy/osu,smoogipooo/osu,peppy/osu,peppy/osu-new,smoogipoo/osu,UselessToucan/osu,ppy/osu,smoogipoo/osu,NeoAdonis/osu,NeoAdonis/osu,peppy/osu,ppy/osu,UselessToucan/osu,ppy/osu,NeoAdonis/osu,smoogipoo/osu,UselessToucan/osu
osu.Game/Screens/OnlinePlay/Multiplayer/Spectate/CatchUpSpectatorPlayerClock.cs
osu.Game/Screens/OnlinePlay/Multiplayer/Spectate/CatchUpSpectatorPlayerClock.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 enable using System; using osu.Framework.Bindables; using osu.Framework.Timing; namespace osu.Game.Screens.OnlinePlay.Multiplayer.Spectate { /// <summary> /// A <see cref="ISpectatorPlayerClock"/> which catches up using rate adjustment. /// </summary> public class CatchUpSpectatorPlayerClock : ISpectatorPlayerClock { /// <summary> /// The catch up rate. /// </summary> public const double CATCHUP_RATE = 2; /// <summary> /// The source clock. /// </summary> public IFrameBasedClock? Source { get; set; } public double CurrentTime { get; private set; } public bool IsRunning { get; private set; } public void Reset() => CurrentTime = 0; public void Start() => IsRunning = true; public void Stop() => IsRunning = false; public bool Seek(double position) { CurrentTime = position; return true; } public void ResetSpeedAdjustments() { } public double Rate => IsCatchingUp ? CATCHUP_RATE : 1; double IAdjustableClock.Rate { get => Rate; set => throw new NotSupportedException(); } double IClock.Rate => Rate; public void ProcessFrame() { ElapsedFrameTime = 0; FramesPerSecond = 0; if (Source == null) return; Source.ProcessFrame(); if (IsRunning) { double elapsedSource = Source.ElapsedFrameTime; double elapsed = elapsedSource * Rate; CurrentTime += elapsed; ElapsedFrameTime = elapsed; FramesPerSecond = Source.FramesPerSecond; } } public double ElapsedFrameTime { get; private set; } public double FramesPerSecond { get; private set; } public FrameTimeInfo TimeInfo => new FrameTimeInfo { Elapsed = ElapsedFrameTime, Current = CurrentTime }; public Bindable<bool> WaitingOnFrames { get; } = new Bindable<bool>(true); public bool IsCatchingUp { get; set; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable enable using System; using osu.Framework.Bindables; using osu.Framework.Timing; namespace osu.Game.Screens.OnlinePlay.Multiplayer.Spectate { /// <summary> /// A <see cref="ISpectatorPlayerClock"/> which catches up using rate adjustment. /// </summary> public class CatchUpSpectatorPlayerClock : ISpectatorPlayerClock { /// <summary> /// The catch up rate. /// </summary> public const double CATCHUP_RATE = 2; /// <summary> /// The source clock. /// </summary> public IFrameBasedClock? Source { get; set; } public double CurrentTime { get; private set; } public bool IsRunning { get; private set; } public void Reset() => CurrentTime = 0; public void Start() => IsRunning = true; public void Stop() => IsRunning = false; public bool Seek(double position) => true; public void ResetSpeedAdjustments() { } public double Rate => IsCatchingUp ? CATCHUP_RATE : 1; double IAdjustableClock.Rate { get => Rate; set => throw new NotSupportedException(); } double IClock.Rate => Rate; public void ProcessFrame() { ElapsedFrameTime = 0; FramesPerSecond = 0; if (Source == null) return; Source.ProcessFrame(); if (IsRunning) { double elapsedSource = Source.ElapsedFrameTime; double elapsed = elapsedSource * Rate; CurrentTime += elapsed; ElapsedFrameTime = elapsed; FramesPerSecond = Source.FramesPerSecond; } } public double ElapsedFrameTime { get; private set; } public double FramesPerSecond { get; private set; } public FrameTimeInfo TimeInfo => new FrameTimeInfo { Elapsed = ElapsedFrameTime, Current = CurrentTime }; public Bindable<bool> WaitingOnFrames { get; } = new Bindable<bool>(true); public bool IsCatchingUp { get; set; } } }
mit
C#
31431012359bb502be710ba05455e4ab40c8fb94
Update RuleUpdater.cs
win120a/ACClassRoomUtil,win120a/ACClassRoomUtil
ProcessBlockUtil/RuleUpdater.cs
ProcessBlockUtil/RuleUpdater.cs
/* Copyright (C) 2011-2014 AC Inc. (Andy Cheung) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.IO; using System.Diagnostics; using System.ServiceProcess; using System.Threading; using NetUtil; namespace ACProcessBlockUtil { class RuleUpdater { public static void Main(String[] a){ /* Version message. */ Console.WriteLine("AC PBU RuleUpdater V1.0.1"); Console.WriteLine("Copyright (C) 2011-2014 AC Inc. (Andy Cheung)"); Console.WriteLine(" "); Console.WriteLine("Process is starting, please make sure the program running."); /* Stop The Service. */ ServiceController pbuSC = new ServiceController("pbuService"); if(pbuSC.Status.Equals(ServiceControllerStatus.Running)) { Console.WriteLine("Stopping Service...."); pbuSC.Stop(); pbuSC.WaitForStatus(ServiceControllerStatus.Stopped); } /* Obtain some path. */ Console.WriteLine("Obtaining Paths..."); String userProfile = Environment.GetEnvironmentVariable("UserProfile"); String systemRoot = Environment.GetEnvironmentVariable("SystemRoot"); /* Delete and copy Exist file. */ Console.WriteLine("Deleting old file..."); if(File.Exists(userProfile + "\\ACRules.txt")){ File.Copy(userProfile + "\\ACRules.txt", userProfile + "\\ACRules_Backup.txt", true); File.Delete(userProfile + "\\ACRules.txt"); } /* Download File. */ Console.WriteLine("Downloading new rules..."); NetUtil.writeToFile("http://win120a.github.io/Api/PBURules.txt", userProfile + "\\ACRules.txt"); /* Restart the Service. */ Console.WriteLine("Restarting Service...."); pbuSC.Start(); pbuSC.WaitForStatus(ServiceControllerStatus.Running); /* Ending message. */ Console.WriteLine("Process Ended, you can close window."); Console.ReadLine(); } } }
/* Copyright (C) 2011-2014 AC Inc. (Andy Cheung) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.IO; using System.Diagnostics; using System.ServiceProcess; using System.Threading; using NetUtil; namespace ACProcessBlockUtil { class RuleUpdater { public static void Main(String[] a){ /* Version message. */ Console.WriteLine("AC PBU RuleUpdater V1.0.1"); Console.WriteLine("Copyright (C) 2011-2014 AC Inc. (Andy Cheung)"); Console.WriteLine(" "); Console.WriteLine("Process is starting, please make sure the program running."); /* Stop The Service. */ ServiceController pbuSC = new ServiceController("pbuService"); if(pbuSC.Status.Equals(ServiceControllerStatus.Running)) { Console.WriteLine("Stopping Service...."); pbuSC.Stop(); pbuSC.WaitForStatus(ServiceControllerStatus.Stopped); } /* Obtain some path. */ Console.WriteLine("Obtaining Paths..."); String userProfile = Environment.GetEnvironmentVariable("UserProfile"); String systemRoot = Environment.GetEnvironmentVariable("SystemRoot"); /* Delete and copy Exist file. */ Console.WriteLine("Deleting old file..."); if(File.Exists(userProfile + "\\ACRules.txt")){ File.Copy(userProfile + "\\ACRules.txt", userProfile + "\\ACRules_Backup.txt"); File.Delete(userProfile + "\\ACRules.txt"); } /* Download File. */ Console.WriteLine("Downloading new rules..."); NetUtil.writeToFile("http://win120a.github.io/Api/PBURules.txt", userProfile + "\\ACRules.txt"); /* Restart the Service. */ Console.WriteLine("Restarting Service...."); pbuSC.Start(); pbuSC.WaitForStatus(ServiceControllerStatus.Running); /* Ending message. */ Console.WriteLine("Process Ended, you can close window."); Console.ReadLine(); } } }
apache-2.0
C#
28418068437e93ff32c358781f18058b3e1b3d03
upgrade version to 1.3.0
tangxuehua/equeue,tangxuehua/equeue,Aaron-Liu/equeue,geffzhang/equeue,tangxuehua/equeue,Aaron-Liu/equeue,geffzhang/equeue
src/EQueue/Properties/AssemblyInfo.cs
src/EQueue/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的常规信息通过以下 // 特性集控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("EQueue")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("EQueue")] [assembly: AssemblyCopyright("Copyright © 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 将 ComVisible 设置为 false 使此程序集中的类型 // 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型, // 则将该类型上的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("75468a30-77e7-4b09-813c-51513179c550")] // 程序集的版本信息由下面四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // // 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, // 方法是按如下所示使用“*”: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.3.0")] [assembly: AssemblyFileVersion("1.3.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的常规信息通过以下 // 特性集控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("EQueue")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("EQueue")] [assembly: AssemblyCopyright("Copyright © 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 将 ComVisible 设置为 false 使此程序集中的类型 // 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型, // 则将该类型上的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("75468a30-77e7-4b09-813c-51513179c550")] // 程序集的版本信息由下面四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // // 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, // 方法是按如下所示使用“*”: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.2.9")] [assembly: AssemblyFileVersion("1.2.9")]
mit
C#
e28f648bbdc42868cc8f55b5db5c76a4200ab3a5
check the correct version of the file in - remaining == 0
jacksonh/manos,jacksonh/manos,mdavid/manos-spdy,jacksonh/manos,mdavid/manos-spdy,jmptrader/manos,mdavid/manos-spdy,mdavid/manos-spdy,jmptrader/manos,jmptrader/manos,mdavid/manos-spdy,jacksonh/manos,jacksonh/manos,jmptrader/manos,jmptrader/manos,jacksonh/manos,jmptrader/manos,mdavid/manos-spdy,mdavid/manos-spdy,jacksonh/manos,jmptrader/manos,jacksonh/manos,jmptrader/manos
src/Manos/Manos.Threading/Boundary.cs
src/Manos/Manos.Threading/Boundary.cs
// // Copyright (C) 2011 Robin Duerden (rduerden@gmail.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // // using System; using Manos.IO; using Libev; using System.Collections; using System.Collections.Generic; using System.Collections.Concurrent; namespace Manos.Threading { public class Boundary : IBoundary { public static readonly Boundary Instance = new Boundary (IOLoop.Instance); private readonly AsyncWatcher asyncWatcher; private readonly ConcurrentQueue<Action> workQueue; private int maxWorkPerLoop; public Boundary( IOLoop loop ) : this( loop, 18 ) {} public Boundary( IOLoop loop, int maxWorkPerLoop ) { asyncWatcher = new AsyncWatcher ((LibEvLoop)loop.EventLoop, ( l, w, et ) => ProcessWork()); asyncWatcher.Start (); workQueue = new ConcurrentQueue<Action> (); this.maxWorkPerLoop = maxWorkPerLoop; } public void ExecuteOnTargetLoop (Action action) { workQueue.Enqueue (action); asyncWatcher.Send (); } private void ProcessWork () { int remaining = maxWorkPerLoop + 1; while( --remaining > 0 ) { Action action; if( workQueue.TryDequeue (out action)) { try { action(); } catch (Exception ex) { Console.WriteLine ("Error in processing synchronized action"); Console.WriteLine (ex); } } else break; } if (remaining == 0) asyncWatcher.Send (); } } }
// // Copyright (C) 2011 Robin Duerden (rduerden@gmail.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // // using System; using Manos.IO; using Libev; using System.Collections; using System.Collections.Generic; using System.Collections.Concurrent; namespace Manos.Threading { public class Boundary : IBoundary { public static readonly Boundary Instance = new Boundary (IOLoop.Instance); private readonly AsyncWatcher asyncWatcher; private readonly ConcurrentQueue<Action> workQueue; private int maxWorkPerLoop; public Boundary( IOLoop loop ) : this( loop, 18 ) {} public Boundary( IOLoop loop, int maxWorkPerLoop ) { asyncWatcher = new AsyncWatcher ((LibEvLoop)loop.EventLoop, ( l, w, et ) => ProcessWork()); asyncWatcher.Start (); workQueue = new ConcurrentQueue<Action> (); this.maxWorkPerLoop = maxWorkPerLoop; } public void ExecuteOnTargetLoop (Action action) { workQueue.Enqueue (action); asyncWatcher.Send (); } private void ProcessWork () { int remaining = maxWorkPerLoop + 1; while( --remaining > 0 ) { Action action; if( workQueue.TryDequeue (out action)) { try { action(); } catch (Exception ex) { Console.WriteLine ("Error in processing synchronized action"); Console.WriteLine (ex); } } else break; } if (remaining < 0) asyncWatcher.Send (); } } }
mit
C#
c4c8fbb71063089ee4f3271dbd43813fa3dbd5d9
Fix NH-1668
fredericDelaporte/nhibernate-core,lnu/nhibernate-core,gliljas/nhibernate-core,nhibernate/nhibernate-core,RogerKratz/nhibernate-core,alobakov/nhibernate-core,nhibernate/nhibernate-core,lnu/nhibernate-core,livioc/nhibernate-core,fredericDelaporte/nhibernate-core,lnu/nhibernate-core,livioc/nhibernate-core,RogerKratz/nhibernate-core,RogerKratz/nhibernate-core,ManufacturingIntelligence/nhibernate-core,hazzik/nhibernate-core,hazzik/nhibernate-core,gliljas/nhibernate-core,nhibernate/nhibernate-core,nhibernate/nhibernate-core,fredericDelaporte/nhibernate-core,livioc/nhibernate-core,hazzik/nhibernate-core,ngbrown/nhibernate-core,gliljas/nhibernate-core,alobakov/nhibernate-core,alobakov/nhibernate-core,nkreipke/nhibernate-core,ngbrown/nhibernate-core,ManufacturingIntelligence/nhibernate-core,hazzik/nhibernate-core,ManufacturingIntelligence/nhibernate-core,fredericDelaporte/nhibernate-core,gliljas/nhibernate-core,nkreipke/nhibernate-core,ngbrown/nhibernate-core,RogerKratz/nhibernate-core,nkreipke/nhibernate-core
src/NHibernate/Driver/IngresDriver.cs
src/NHibernate/Driver/IngresDriver.cs
using System; namespace NHibernate.Driver { /// <summary> /// A NHibernate Driver for using the Ingres DataProvider /// </summary> /// <remarks> /// </remarks> public class IngresDriver : ReflectionBasedDriver { public IngresDriver() : base("Ingres.Client", "Ingres.Client.IngresConnection", "Ingres.Client.IngresCommand") {} public override bool UseNamedPrefixInSql { get { return false; } } public override bool UseNamedPrefixInParameter { get { return false; } } public override string NamedPrefix { get { return String.Empty; } } } }
using System; namespace NHibernate.Driver { /// <summary> /// A NHibernate Driver for using the Ingres DataProvider /// </summary> /// <remarks> /// </remarks> public class IngresDriver : ReflectionBasedDriver { /// <summary></summary> public IngresDriver() : base( "Ca.Ingres.Client", "Ca.Ingres.Client.IngresConnection", "Ca.Ingres.Client.IngresCommand") { } /// <summary></summary> public override bool UseNamedPrefixInSql { get { return false; } } /// <summary></summary> public override bool UseNamedPrefixInParameter { get { return false; } } /// <summary></summary> public override string NamedPrefix { get { return String.Empty; } } } }
lgpl-2.1
C#
91f362acfc99413caf715b7a6eadd7bd157727f5
Change sent from address for GC Eights EOI emails (#10)
croquet-australia/api.croquet-australia.com.au
source/CroquetAustralia.QueueProcessor/Email/EmailGenerators/GCEightsEOIEmailGenerator.cs
source/CroquetAustralia.QueueProcessor/Email/EmailGenerators/GCEightsEOIEmailGenerator.cs
using System.Linq; using CroquetAustralia.Domain.Features.TournamentEntry.Events; namespace CroquetAustralia.QueueProcessor.Email.EmailGenerators { public class GCEightsEOIEmailGenerator : BaseEmailGenerator { /* todo: remove hard coding of email addresses */ private static readonly EmailAddress GCSC = new EmailAddress("glenleslie@bigpond.com", "Croquet Australia - Chair GC Selection"); private static readonly EmailAddress[] BCC = { new EmailAddress("admin@croquet-australia.com.au", "Croquet Australia"), GCSC }; public GCEightsEOIEmailGenerator(EmailMessageSettings emailMessageSettings) : base(emailMessageSettings, GCSC, GetBCC(emailMessageSettings)) { } protected override string GetTemplateName(EntrySubmitted entrySubmitted) { return "GCEightsEOI"; } private static EmailAddress[] GetBCC(EmailMessageSettings emailMessageSettings) { return emailMessageSettings.Bcc.Any() ? BCC : new EmailAddress[] {}; } } }
using System.Linq; using CroquetAustralia.Domain.Features.TournamentEntry.Events; namespace CroquetAustralia.QueueProcessor.Email.EmailGenerators { public class GCEightsEOIEmailGenerator : BaseEmailGenerator { /* todo: remove hard coding of email addresses */ private static readonly EmailAddress GCSC = new EmailAddress("acquinn@bigpond.com", "Croquet Australia - Secretary GC Selection"); private static readonly EmailAddress[] BCC = { new EmailAddress("admin@croquet-australia.com.au", "Croquet Australia"), GCSC }; public GCEightsEOIEmailGenerator(EmailMessageSettings emailMessageSettings) : base(emailMessageSettings, GCSC, GetBCC(emailMessageSettings)) { } protected override string GetTemplateName(EntrySubmitted entrySubmitted) { return "GCEightsEOI"; } private static EmailAddress[] GetBCC(EmailMessageSettings emailMessageSettings) { return emailMessageSettings.Bcc.Any() ? BCC : new EmailAddress[] {}; } } }
mit
C#
8f790c732af1daccf927ee5f6ad639afacce4133
Add note about deprecation
cake-contrib/Cake.Prca.Website,cake-contrib/Cake.Prca.Website
input/index.cshtml
input/index.cshtml
--- Title: Cake Pull Request Code Analysis NoSidebar: true NoContainer: false NoGutter: true --- <div class="container"> <h1>Deprecated</h1> <p> <strong>This addins are no longer maintained.</strong> </p> <p> Please see <a href="https://cake-contrib.github.io/Cake.Issues.Website/">Cake Issues Addins</a> for fully maintained addins providing the same feature set as this addins. </p> <h1>What is it?</h1> <p> The Pull Request Code Analysis Addin for <a href="http://cakebuild.net/">Cake</a> allows you to add issues from any analyzer or linter to comments in pull requests. </p> <p> The addin is built in a modular architecture, allowing to easily enhance it for supporting additional analyzers, linters and code review systems. </p> <p> See <a href="docs">Documentation</a> for basic concepts and usage instructions. </p> <p> See <a href="addins">Addins</a> for a list of supported issue providers and pull request systems and <a href="dsl">Reference</a> for a list of aliases provided by these addins. </p> </div>
--- Title: Cake Pull Request Code Analysis NoSidebar: true NoContainer: false NoGutter: true --- <div class="container"> <h1>What is it?</h1> <p> The Pull Request Code Analysis Addin for <a href="http://cakebuild.net/">Cake</a> allows you to add issues from any analyzer or linter to comments in pull requests. </p> <p> The addin is built in a modular architecture, allowing to easily enhance it for supporting additional analyzers, linters and code review systems. </p> <p> See <a href="docs">Documentation</a> for basic concepts and usage instructions. </p> <p> See <a href="addins">Addins</a> for a list of supported issue providers and pull request systems and <a href="dsl">Reference</a> for a list of aliases provided by these addins. </p> </div>
mit
C#
27e7199f8f2e35f0316a6d34db26d928ede799dc
Fix proxied drawables never expiring.
DrabWeb/osu-framework,Tom94/osu-framework,DrabWeb/osu-framework,EVAST9919/osu-framework,Nabile-Rahmani/osu-framework,ZLima12/osu-framework,RedNesto/osu-framework,Tom94/osu-framework,DrabWeb/osu-framework,ZLima12/osu-framework,naoey/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,Nabile-Rahmani/osu-framework,default0/osu-framework,ppy/osu-framework,naoey/osu-framework,EVAST9919/osu-framework,RedNesto/osu-framework,peppy/osu-framework,paparony03/osu-framework,EVAST9919/osu-framework,default0/osu-framework,paparony03/osu-framework,peppy/osu-framework,ppy/osu-framework
osu.Framework/Graphics/ProxyDrawable.cs
osu.Framework/Graphics/ProxyDrawable.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 namespace osu.Framework.Graphics { public class ProxyDrawable : Drawable { public ProxyDrawable(Drawable original) { Original = original; } internal sealed override Drawable Original { get; } public override bool IsAlive => base.IsAlive && Original.IsAlive; // We do not want to receive updates. That is the business // of the original drawable. public override bool IsPresent => false; } }
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE namespace osu.Framework.Graphics { public class ProxyDrawable : Drawable { public ProxyDrawable(Drawable original) { Original = original; } internal sealed override Drawable Original { get; } // We do not want to receive updates. That is the business // of the original drawable. public override bool IsPresent => false; } }
mit
C#
aa2ba4a91fefb14de1300f12e90f73760ae983a4
Add MeshWrapper description
jlewin/MatterControl,larsbrubaker/MatterControl,mmoening/MatterControl,unlimitedbacon/MatterControl,jlewin/MatterControl,larsbrubaker/MatterControl,larsbrubaker/MatterControl,larsbrubaker/MatterControl,jlewin/MatterControl,mmoening/MatterControl,unlimitedbacon/MatterControl,mmoening/MatterControl,jlewin/MatterControl,unlimitedbacon/MatterControl,unlimitedbacon/MatterControl
PartPreviewWindow/View3D/Actions/MeshWrapper.cs
PartPreviewWindow/View3D/Actions/MeshWrapper.cs
/* Copyright (c) 2017, Lars Brubaker, John Lewin All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. */ using MatterHackers.DataConverters3D; using MatterHackers.VectorMath; namespace MatterHackers.MatterControl.PartPreviewWindow.View3D { /// <summary> /// The goal of MeshWrapper is to provide a mutated version of a source item by some operation. To do so we wrap and clone all /// properties of the source item and reset the source matrix to Identity, given that it now exists on the wrapping parent. /// </summary> public class MeshWrapper : Object3D { public MeshWrapper() { } public MeshWrapper(IObject3D child, string ownerId) { Children.Add(child); this.Name = child.Name; this.OwnerID = ownerId; this.MaterialIndex = child.MaterialIndex; this.ItemType = child.ItemType; this.OutputType = child.OutputType; this.Color = child.Color; this.Mesh = child.Mesh; this.Matrix = child.Matrix; child.Matrix = Matrix4X4.Identity; } } }
/* Copyright (c) 2017, Lars Brubaker, John Lewin All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. */ using MatterHackers.DataConverters3D; using MatterHackers.VectorMath; namespace MatterHackers.MatterControl.PartPreviewWindow.View3D { public class MeshWrapper : Object3D { public MeshWrapper() { } public MeshWrapper(IObject3D child, string ownerId) { Children.Add(child); this.Name = child.Name; this.OwnerID = ownerId; this.MaterialIndex = child.MaterialIndex; this.ItemType = child.ItemType; this.OutputType = child.OutputType; this.Color = child.Color; this.Mesh = child.Mesh; this.Matrix = child.Matrix; child.Matrix = Matrix4X4.Identity; } } }
bsd-2-clause
C#
fda4d0341440b1acf0f3478778909cfc6d6bccb0
Update Base64Url.cs
yuanrui/Examples,yuanrui/Examples,yuanrui/Examples,yuanrui/Examples,yuanrui/Examples
Simple.Common/Text/Base64Url.cs
Simple.Common/Text/Base64Url.cs
namespace Simple.Common.Text { using System; using System.Text; public static class Base64Url { public static string Encode(byte[] input) { var output = Convert.ToBase64String(input); output = output.Split('=')[0]; output = output.Replace('+', '-'); output = output.Replace('/', '_'); return output; } public static string Encode(string input) { return Encode(Encoding.UTF8.GetBytes(input)); } public static byte[] Decode(string input) { var output = input; output = output.Replace('-', '+'); output = output.Replace('_', '/'); switch (output.Length % 4) { case 0: break; case 2: output += "=="; break; case 3: output += "="; break; default: throw new System.ArgumentOutOfRangeException("input", "Illegal base64url string!"); } var converted = Convert.FromBase64String(output); return converted; } } }
namespace Simple.Common.Text { using System; public static class Base64Url { public static string Encode(byte[] input) { var output = Convert.ToBase64String(input); output = output.Split('=')[0]; output = output.Replace('+', '-'); output = output.Replace('/', '_'); return output; } public static byte[] Decode(string input) { var output = input; output = output.Replace('-', '+'); output = output.Replace('_', '/'); switch (output.Length % 4) { case 0: break; case 2: output += "=="; break; case 3: output += "="; break; default: throw new System.ArgumentOutOfRangeException("input", "Illegal base64url string!"); } var converted = Convert.FromBase64String(output); return converted; } } }
apache-2.0
C#
90489fe07a574695fe599251322b2dd978ac057b
Add a list of notification receivers for project create.
LykkeCity/CompetitionPlatform,LykkeCity/CompetitionPlatform,LykkeCity/CompetitionPlatform
src/CompetitionPlatform/Data/AzureRepositories/Settings/BaseSettings.cs
src/CompetitionPlatform/Data/AzureRepositories/Settings/BaseSettings.cs
using System.Collections.Generic; using Lykke.EmailSenderProducer.Interfaces; namespace CompetitionPlatform.Data.AzureRepositories.Settings { public class BaseSettings { public AzureSettings Azure { get; set; } public AuthenticationSettings Authentication { get; set; } public NotificationsSettings Notifications { get; set; } public string EmailServiceBusSettingsUrl { get; set; } public List<string> ProjectCreateNotificationReceiver { get; set; } } public class AuthenticationSettings { public string ClientId { get; set; } public string ClientSecret { get; set; } public string PostLogoutRedirectUri { get; set; } public string Authority { get; set; } } public class AzureSettings { public string StorageConnString { get; set; } } public class NotificationsSettings { public string EmailsQueueConnString { get; set; } public string SlackQueueConnString { get; set; } } public class EmailServiceBusSettings { public EmailServiceBus EmailServiceBus; } public class EmailServiceBus : IServiceBusEmailSettings { public string Key { get; set; } public string QueueName { get; set; } public string NamespaceUrl { get; set; } public string PolicyName { get; set; } } }
using Lykke.EmailSenderProducer.Interfaces; namespace CompetitionPlatform.Data.AzureRepositories.Settings { public class BaseSettings { public AzureSettings Azure { get; set; } public AuthenticationSettings Authentication { get; set; } public NotificationsSettings Notifications { get; set; } public string EmailServiceBusSettingsUrl { get; set; } } public class AuthenticationSettings { public string ClientId { get; set; } public string ClientSecret { get; set; } public string PostLogoutRedirectUri { get; set; } public string Authority { get; set; } } public class AzureSettings { public string StorageConnString { get; set; } } public class NotificationsSettings { public string EmailsQueueConnString { get; set; } public string SlackQueueConnString { get; set; } } public class EmailServiceBusSettings { public EmailServiceBus EmailServiceBus; } public class EmailServiceBus : IServiceBusEmailSettings { public string Key { get; set; } public string QueueName { get; set; } public string NamespaceUrl { get; set; } public string PolicyName { get; set; } } }
mit
C#
c415e5f0e982176d6f14eab517b835b92214aebe
Fix dependencies not showing in Solution window on Linux
mrward/monodevelop-dnx-addin
src/MonoDevelop.Dnx/Omnisharp/MonoDevelop/MetadataFileReferenceCache.cs
src/MonoDevelop.Dnx/Omnisharp/MonoDevelop/MetadataFileReferenceCache.cs
// // MetadataFileReferenceCache.cs // // Author: // Matt Ward <ward.matt@gmail.com> // // Copyright (c) 2015 Matthew Ward // // 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 Microsoft.CodeAnalysis; using OmniSharp.Services; using System.Collections.Concurrent; namespace MonoDevelop.Dnx.Omnisharp { public class MetadataFileReferenceCache : IMetadataFileReferenceCache { ConcurrentDictionary<string, MetadataReference> cache = new ConcurrentDictionary<string, MetadataReference> (); public MetadataReference GetMetadataReference (string path) { return cache.GetOrAdd (path, filePath => { return MetadataReference.CreateFromFile (filePath); }); } } }
// // MetadataFileReferenceCache.cs // // Author: // Matt Ward <ward.matt@gmail.com> // // Copyright (c) 2015 Matthew Ward // // 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 Microsoft.CodeAnalysis; using OmniSharp.Services; using System.Collections.Concurrent; namespace MonoDevelop.Dnx.Omnisharp { public class MetadataFileReferenceCache : IMetadataFileReferenceCache { ConcurrentDictionary<string, MetadataReference> cache = new ConcurrentDictionary<string, MetadataReference> (); public MetadataReference GetMetadataReference (string path) { string key = path.ToLowerInvariant (); return cache.GetOrAdd (key, filePath => { return MetadataReference.CreateFromFile (filePath); }); } } }
mit
C#
0a3426c31f358521d74ce393c406ef82a90f37e0
Add SetVariable method to ExternalTaskBpmnError
jlucansky/Camunda.Api.Client
Camunda.Api.Client/ExternalTask/ExternalTaskBpmnError.cs
Camunda.Api.Client/ExternalTask/ExternalTaskBpmnError.cs
using System.Collections.Generic; namespace Camunda.Api.Client.ExternalTask { public class ExternalTaskBpmnError { /// <summary> /// The id of the worker that reports the failure. Must match the id of the worker who has most recently locked the task. /// </summary> public string WorkerId; /// <summary> /// A error code that indicates the predefined error. Is used to identify the BPMN error handler. /// </summary> public string ErrorCode; /// <summary> /// An error message that describes the error. /// </summary> public string ErrorMessage; /// <summary> /// Object containing variable key-value pairs. /// </summary> public Dictionary<string, VariableValue> Variables; public ExternalTaskBpmnError SetVariable(string name, object value) { Variables = (Variables ?? new Dictionary<string, VariableValue>()).Set(name, value); return this; } public override string ToString() => ErrorCode; } }
using System.Collections.Generic; namespace Camunda.Api.Client.ExternalTask { public class ExternalTaskBpmnError { /// <summary> /// The id of the worker that reports the failure. Must match the id of the worker who has most recently locked the task. /// </summary> public string WorkerId; /// <summary> /// A error code that indicates the predefined error. Is used to identify the BPMN error handler. /// </summary> public string ErrorCode; /// <summary> /// An error message that describes the error. /// </summary> public string ErrorMessage; /// <summary> /// Object containing variable key-value pairs. /// </summary> public Dictionary<string, VariableValue> Variables = new Dictionary<string, VariableValue>(); public override string ToString() => ErrorCode; } }
mit
C#
64cd943c70e90064796d5bfd1c5b59d9431d5c8c
Remove unused using
justinjstark/Delivered,justinjstark/Verdeler
Verdeler/IEndpointRepository.cs
Verdeler/IEndpointRepository.cs
using System.Collections.Generic; namespace Verdeler { public interface IEndpointRepository<in TRecipient> where TRecipient : Recipient { IEnumerable<Endpoint> GetEndpointsForRecipient(TRecipient recipient); } }
using System.Collections.Generic; using System.Threading.Tasks; namespace Verdeler { public interface IEndpointRepository<in TRecipient> where TRecipient : Recipient { IEnumerable<Endpoint> GetEndpointsForRecipient(TRecipient recipient); } }
mit
C#
62d136830a3339a1db25dd9a2f9685b2bffb7642
добавить атрибут JsonProperty над свойствами
vknet/vk,vknet/vk
VkNet/Model/Attachments/Gift.cs
VkNet/Model/Attachments/Gift.cs
using System; using Newtonsoft.Json; using VkNet.Utils; namespace VkNet.Model.Attachments { /// <summary> /// Подарок. /// </summary> [Serializable] public class Gift : MediaAttachment { /// <inheritdoc /> protected override string Alias => "gift"; /// <summary> /// Изображение 48х48. /// </summary> [JsonProperty("thumb_48")] public Uri Thumb48 { get; set; } /// <summary> /// Изображение 96х96. /// </summary> [JsonProperty("thumb_96")] public Uri Thumb96 { get; set; } /// <summary> /// Изображение 256х256. /// </summary> [JsonProperty("thumb_256")] public Uri Thumb256 { get; set; } /// <summary> /// Разобрать из json. /// </summary> /// <param name="response"> Ответ сервера. </param> /// <returns> </returns> public static Gift FromJson(VkResponse response) { return new Gift { Id = response["id"], Thumb48 = response["thumb_48"], Thumb96 = response["thumb_96"], Thumb256 = response["thumb_256"] }; } /// <summary> /// Преобразование класса <see cref="Gift" /> в <see cref="VkParameters" /> /// </summary> /// <param name="response"> Ответ сервера. </param> /// <returns>Результат преобразования в <see cref="Gift" /></returns> public static implicit operator Gift(VkResponse response) { if (response == null) { return null; } return response.HasToken() ? FromJson(response) : null; } } }
using System; using VkNet.Utils; namespace VkNet.Model.Attachments { /// <summary> /// Подарок. /// </summary> [Serializable] public class Gift : MediaAttachment { /// <inheritdoc /> protected override string Alias => "gift"; /// <summary> /// Изображение 48х48. /// </summary> public Uri Thumb48 { get; set; } /// <summary> /// Изображение 96х96. /// </summary> public Uri Thumb96 { get; set; } /// <summary> /// Изображение 256х256. /// </summary> public Uri Thumb256 { get; set; } /// <summary> /// Разобрать из json. /// </summary> /// <param name="response"> Ответ сервера. </param> /// <returns> </returns> public static Gift FromJson(VkResponse response) { return new Gift { Id = response[key: "id"], Thumb48 = response[key: "thumb_48"], Thumb96 = response[key: "thumb_96"], Thumb256 = response[key: "thumb_256"] }; } /// <summary> /// Преобразование класса <see cref="Gift" /> в <see cref="VkParameters" /> /// </summary> /// <param name="response"> Ответ сервера. </param> /// <returns>Результат преобразования в <see cref="Gift" /></returns> public static implicit operator Gift(VkResponse response) { if (response == null) { return null; } return response.HasToken() ? FromJson(response) : null; } } }
mit
C#
ef1c4d1d064eab66f1bbb89abe5e248e9331993b
Remove unnecessary usings
Chess-Variants-Training/Chess-Variants-Training,Chess-Variants-Training/Chess-Variants-Training,Chess-Variants-Training/Chess-Variants-Training
src/AtomicChessPuzzles/DbRepositories/UserRepository.cs
src/AtomicChessPuzzles/DbRepositories/UserRepository.cs
using AtomicChessPuzzles.Models; using MongoDB.Driver; namespace AtomicChessPuzzles.DbRepositories { public class UserRepository : IUserRepository { MongoSettings settings; IMongoCollection<User> userCollection; public UserRepository() { settings = new MongoSettings(); GetCollection(); } private void GetCollection() { MongoClient client = new MongoClient(settings.MongoConnectionString); userCollection = client.GetDatabase(settings.Database).GetCollection<User>(settings.UserCollectionName); } public bool Add(User user) { var found = userCollection.FindSync<User>(new ExpressionFilterDefinition<User>(x => x.Username == user.Username)); if (found != null && found.Any()) return false; userCollection.InsertOne(user); return true; } public void Update(User user) { userCollection.ReplaceOne(new ExpressionFilterDefinition<User>(x => x.Username == user.Username), user); } public void Delete(User user) { userCollection.DeleteOne(new ExpressionFilterDefinition<User>(x => x.Username == user.Username)); } public User FindByUsername(string name) { var found = userCollection.FindSync<User>(new ExpressionFilterDefinition<User>(x => x.Username == name)); if (found == null) return null; return found.FirstOrDefault(); } } }
using MongoDB.Driver; using AtomicChessPuzzles.Models; using MongoDB.Bson; namespace AtomicChessPuzzles.DbRepositories { public class UserRepository : IUserRepository { MongoSettings settings; IMongoCollection<User> userCollection; public UserRepository() { settings = new MongoSettings(); GetCollection(); } private void GetCollection() { MongoClient client = new MongoClient(settings.MongoConnectionString); userCollection = client.GetDatabase(settings.Database).GetCollection<User>(settings.UserCollectionName); } public bool Add(User user) { var found = userCollection.FindSync<User>(new ExpressionFilterDefinition<User>(x => x.Username == user.Username)); if (found != null && found.Any()) return false; userCollection.InsertOne(user); return true; } public void Update(User user) { userCollection.ReplaceOne(new ExpressionFilterDefinition<User>(x => x.Username == user.Username), user); } public void Delete(User user) { userCollection.DeleteOne(new ExpressionFilterDefinition<User>(x => x.Username == user.Username)); } public User FindByUsername(string name) { var found = userCollection.FindSync<User>(new ExpressionFilterDefinition<User>(x => x.Username == name)); if (found == null) return null; return found.FirstOrDefault(); } } }
agpl-3.0
C#
2a20b71a269c7f22dd8abf67ccee7798a7d76a5a
Fix UWP Platform compile error #178
neuecc/UniRx,TORISOUP/UniRx,kimsama/UniRx
Assets/Plugins/UniRx/Scripts/UnityEngineBridge/Diagnostics/ObservableDebugExtensions.cs
Assets/Plugins/UniRx/Scripts/UnityEngineBridge/Diagnostics/ObservableDebugExtensions.cs
using System; namespace UniRx.Diagnostics { public static class ObservableDebugExtensions { /// <summary> /// Debug helper of observbale stream. Works for only DEBUG symbol. /// </summary> public static IObservable<T> Debug<T>(this IObservable<T> source, string label = null) { #if DEBUG var l = (label == null) ? "" : "[" + label + "]"; return source.Materialize() .Do(x => UnityEngine.Debug.Log(l + x.ToString())) .Dematerialize() .DoOnCancel(() => UnityEngine.Debug.Log(l + "OnCancel")) .DoOnSubscribe(() => UnityEngine.Debug.Log(l + "OnSubscribe")); #else return source; #endif } /// <summary> /// Debug helper of observbale stream. Works for only DEBUG symbol. /// </summary> public static IObservable<T> Debug<T>(this IObservable<T> source, UniRx.Diagnostics.Logger logger) { #if DEBUG return source.Materialize() .Do(x => logger.Debug(x.ToString())) .Dematerialize() .DoOnCancel(() => logger.Debug("OnCancel")) .DoOnSubscribe(() => logger.Debug("OnSubscribe")); #else return source; #endif } } }
namespace UniRx.Diagnostics { public static class ObservableDebugExtensions { /// <summary> /// Debug helper of observbale stream. Works for only DEBUG symbol. /// </summary> public static IObservable<T> Debug<T>(this IObservable<T> source, string label = null) { #if DEBUG var l = (label == null) ? "" : "[" + label + "]"; return source.Materialize() .Do(x => UnityEngine.Debug.Log(l + x.ToString())) .Dematerialize() .DoOnCancel(() => UnityEngine.Debug.Log(l + "OnCancel")) .DoOnSubscribe(() => UnityEngine.Debug.Log(l + "OnSubscribe")); #else return source; #endif } /// <summary> /// Debug helper of observbale stream. Works for only DEBUG symbol. /// </summary> public static IObservable<T> Debug<T>(this IObservable<T> source, UniRx.Diagnostics.Logger logger) { #if DEBUG return source.Materialize() .Do(x => logger.Debug(x.ToString())) .Dematerialize() .DoOnCancel(() => logger.Debug("OnCancel")) .DoOnSubscribe(() => logger.Debug("OnSubscribe")); #else return source; #endif } } }
mit
C#
46f0254d228d6e0eca7076fe98147ef1df20bb29
fix bug
aisaka-taiga/Battery_indicator
TAIGA_SOFTWARE_BATTERY_INDICATOR/SettingForm.cs
TAIGA_SOFTWARE_BATTERY_INDICATOR/SettingForm.cs
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace BATTERY_INDICATOR { public partial class SettingForm : Form { public SettingForm() { InitializeComponent(); } private void SettingForm_Load(object sender, EventArgs e) { currentFont.Text = Setting.IconFont?.Name ?? ""; currentFontSizeTB.Text = Setting.IconFont?.Size.ToString() ?? ""; xOffset.Value = (decimal)Setting.X; yOffset.Value = (decimal)Setting.Y; widthNum.Value = Setting.Width; heightNum.Value = Setting.Height; showIfFullCB.Checked = Setting.ShowIfFull; } private void changeFontBtn_Click(object sender, EventArgs e) { FontDialog dialog = new FontDialog(); dialog.Font = Setting.IconFont; dialog.FontMustExist = true; dialog.ShowDialog(); Setting.IconFont = dialog.Font; currentFont.Text = dialog.Font.Name; currentFontSizeTB.Text = dialog.Font.Size.ToString(); } private void ValueChanged(object sender, EventArgs e) { Setting.X = (float)xOffset.Value; Setting.Y = (float)yOffset.Value; } private void ResolutionValueChanged(object sender,EventArgs e) { Setting.Width = (int)widthNum.Value; Setting.Height = (int)heightNum.Value; } private void saveBtn_Click(object sender, EventArgs e) { Close(); } private void showIfFullCB_CheckedChanged(object sender, EventArgs e) { Setting.ShowIfFull = showIfFullCB.Checked; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace BATTERY_INDICATOR { public partial class SettingForm : Form { public SettingForm() { InitializeComponent(); } private void SettingForm_Load(object sender, EventArgs e) { currentFont.Text = Setting.IconFont?.Name ?? ""; currentFontSizeTB.Text = Setting.IconFont?.Size.ToString() ?? ""; xOffset.Value = (decimal)Setting.X; yOffset.Value = (decimal)Setting.Y; showIfFullCB.Checked = Setting.ShowIfFull; } private void changeFontBtn_Click(object sender, EventArgs e) { FontDialog dialog = new FontDialog(); dialog.Font = Setting.IconFont; dialog.FontMustExist = true; dialog.ShowDialog(); Setting.IconFont = dialog.Font; currentFont.Text = dialog.Font.Name; currentFontSizeTB.Text = dialog.Font.Size.ToString(); } private void ValueChanged(object sender, EventArgs e) { Setting.X = (float)xOffset.Value; Setting.Y = (float)yOffset.Value; } private void ResolutionValueChanged(object sender,EventArgs e) { Setting.Width = (int)widthNum.Value; Setting.Height = (int)heightNum.Value; } private void saveBtn_Click(object sender, EventArgs e) { Close(); } private void showIfFullCB_CheckedChanged(object sender, EventArgs e) { Setting.ShowIfFull = showIfFullCB.Checked; } } }
mit
C#
a6647b95de1f212947bea3f358f916c317557763
Add geometry in GeometryFeature constructor
charlenni/Mapsui,pauldendulk/Mapsui,charlenni/Mapsui
Tests/Mapsui.Tests/Layers/WritableLayerTests.cs
Tests/Mapsui.Tests/Layers/WritableLayerTests.cs
using Mapsui.Geometries; using Mapsui.GeometryLayer; using Mapsui.Layers; using NUnit.Framework; namespace Mapsui.Tests.Layers { [TestFixture] public class WritableLayerTests { [Test] public void DoNotCrashOnNullOrEmptyGeometries() { // arrange var writableLayer = new WritableLayer(); writableLayer.Add(new GeometryFeature()); writableLayer.Add(new GeometryFeature(new Point())); writableLayer.Add(new GeometryFeature(new LineString())); writableLayer.Add(new GeometryFeature(new Polygon())); // act var extent = writableLayer.Extent; // assert Assert.IsNull(extent); } } }
using Mapsui.Geometries; using Mapsui.GeometryLayer; using Mapsui.Layers; using Mapsui.Providers; using NUnit.Framework; namespace Mapsui.Tests.Layers { [TestFixture] public class WritableLayerTests { [Test] public void DoNotCrashOnNullOrEmptyGeometries() { // arrange var writableLayer = new WritableLayer(); writableLayer.Add(new GeometryFeature()); writableLayer.Add(new GeometryFeature { Geometry = new Point() }); writableLayer.Add(new GeometryFeature { Geometry = new LineString() }); writableLayer.Add(new GeometryFeature { Geometry = new Polygon() }); // act var extent = writableLayer.Extent; // assert Assert.IsNull(extent); } } }
mit
C#
3b999000e0eaab293a0440034e47820863db9e65
change from review
SkillsFundingAgency/vacancy-register-api,SkillsFundingAgency/vacancy-register-api,SkillsFundingAgency/vacancy-register-api
src/Esfa.Vacancy.Register.Api/App_Start/WebApiConfig.cs
src/Esfa.Vacancy.Register.Api/App_Start/WebApiConfig.cs
using System.Web.Http; using Esfa.Vacancy.Register.Api.App_Start; using Newtonsoft.Json; namespace Esfa.Vacancy.Register.Api { public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API configuration and services // JSON formatters config.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Local }; GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new StrictEnumConverter()); // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } } }
using System.Web.Http; using Esfa.Vacancy.Register.Api.App_Start; using Newtonsoft.Json; namespace Esfa.Vacancy.Register.Api { public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API configuration and services GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new StrictEnumConverter()); // Web API routes config.MapHttpAttributeRoutes(); config.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Local }; config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } } }
mit
C#
52bb3b698ab130b68506ca1a7a392c4551c8d45f
Remove debug line
Ludoratoire/LD39-133mhz
Assets/ZombileBehaviour.cs
Assets/ZombileBehaviour.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ZombileBehaviour : MonoBehaviour { public enum EnnemyType { Zombile } public EnnemyType currentType; // Use this for initialization void Start () { } // Update is called once per frame void Update () { } void OnTriggerEnter2D(Collider2D collider2D) { if (collider2D.gameObject.layer == LayerMask.NameToLayer("EnnemyWalls")) { GetComponent<EnnemyWalk>().SwitchDirection(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ZombileBehaviour : MonoBehaviour { public enum EnnemyType { Zombile } public EnnemyType currentType; // Use this for initialization void Start () { } // Update is called once per frame void Update () { } void OnTriggerEnter2D(Collider2D collider2D) { if (collider2D.gameObject.layer == LayerMask.NameToLayer("EnnemyWalls")) { Debug.Log("ZombileBehaviour.OnTriggerEnter2D : " + collider2D.gameObject.name); GetComponent<EnnemyWalk>().SwitchDirection(); } } }
apache-2.0
C#
f4d8341e4c04329616fd5f90ad37a516968549cf
Change the order of enumeration.
AIWolfSharp/AIWolf_NET,AIWolfSharp/AIWolfCore
AIWolfLib/Species.cs
AIWolfLib/Species.cs
// // Species.cs // // Copyright (c) 2016 Takashi OTSUKI // // This software is released under the MIT License. // http://opensource.org/licenses/mit-license.php // namespace AIWolf.Lib { /// <summary> /// Enumeration type for species. /// </summary> public enum Species { /// <summary> /// Human. /// </summary> HUMAN = 1, /// <summary> /// Uncertain. /// </summary> UNC, /// <summary> /// Werewolf. /// </summary> WEREWOLF } }
// // Species.cs // // Copyright (c) 2016 Takashi OTSUKI // // This software is released under the MIT License. // http://opensource.org/licenses/mit-license.php // namespace AIWolf.Lib { /// <summary> /// Enumeration type for species. /// </summary> public enum Species { /// <summary> /// Uncertain. /// </summary> UNC, /// <summary> /// Human. /// </summary> HUMAN, /// <summary> /// Werewolf. /// </summary> WEREWOLF } }
mit
C#
ec13ca680e5c65d93e0fc4bd1f049338fda8b38e
remove duplicate layout registration
mnadel/Metrics.NET,cvent/Metrics.NET,MetaG8/Metrics.NET,MetaG8/Metrics.NET,Recognos/Metrics.NET,huoxudong125/Metrics.NET,ntent-ad/Metrics.NET,mnadel/Metrics.NET,DeonHeyns/Metrics.NET,ntent-ad/Metrics.NET,alhardy/Metrics.NET,etishor/Metrics.NET,Recognos/Metrics.NET,DeonHeyns/Metrics.NET,alhardy/Metrics.NET,Liwoj/Metrics.NET,cvent/Metrics.NET,Liwoj/Metrics.NET,huoxudong125/Metrics.NET,etishor/Metrics.NET,MetaG8/Metrics.NET
Src/Adapters/Metrics.NLog/NLogReportsConfigExtensions.cs
Src/Adapters/Metrics.NLog/NLogReportsConfigExtensions.cs
 using System; using Metrics.NLog; using Metrics.Reporters; using Metrics.Reports; namespace Metrics { public static class NLogReportsConfigExtensions { /// <summary> /// Write CSV Metrics Reports using NLog. /// </summary> /// <param name="reports">Instance to configure</param> /// <param name="interval">Interval at which to report values</param> /// <param name="delimiter">Delimiter to use for CSV</param> /// <returns>Same Reports instance for chaining</returns> public static MetricsReports WithNLogCSVReports(this MetricsReports reports, TimeSpan interval, string delimiter = CSVAppender.CommaDelimiter) { global::NLog.Config.ConfigurationItemFactory.Default.Layouts.RegisterDefinition("CsvGaugeLayout", typeof(CsvGaugeLayout)); global::NLog.Config.ConfigurationItemFactory.Default.Layouts.RegisterDefinition("CsvCounterLayout", typeof(CsvCounterLayout)); global::NLog.Config.ConfigurationItemFactory.Default.Layouts.RegisterDefinition("CsvMeterLayout", typeof(CsvMeterLayout)); global::NLog.Config.ConfigurationItemFactory.Default.Layouts.RegisterDefinition("CsvHistogramLayout", typeof(CsvHistogramLayout)); global::NLog.Config.ConfigurationItemFactory.Default.Layouts.RegisterDefinition("CsvTimerLayout", typeof(CsvTimerLayout)); reports.WithReporter("NLog CSV Report", () => new CSVReporter(new NLogCSVAppender(delimiter)), interval); return reports; } /// <summary> /// Write human readable text using NLog /// </summary> /// <param name="reports">Instance to configure</param> /// <param name="interval">Interval at which to report values</param> /// <returns>Same Reports instance for chaining</returns> public static MetricsReports WithNLogTextReports(this MetricsReports reports, TimeSpan interval) { reports.WithReporter("NLog Text Report", () => new NLogTextReporter(), interval); return reports; } } }
 using System; using Metrics.NLog; using Metrics.Reporters; using Metrics.Reports; namespace Metrics { public static class NLogReportsConfigExtensions { /// <summary> /// Write CSV Metrics Reports using NLog. /// </summary> /// <param name="reports">Instance to configure</param> /// <param name="interval">Interval at which to report values</param> /// <param name="delimiter">Delimiter to use for CSV</param> /// <returns>Same Reports instance for chaining</returns> public static MetricsReports WithNLogCSVReports(this MetricsReports reports, TimeSpan interval, string delimiter = CSVAppender.CommaDelimiter) { global::NLog.Config.ConfigurationItemFactory.Default.Layouts.RegisterDefinition("CsvGaugeLayout", typeof(CsvGaugeLayout)); global::NLog.Config.ConfigurationItemFactory.Default.Layouts.RegisterDefinition("CsvCounterLayout", typeof(CsvCounterLayout)); global::NLog.Config.ConfigurationItemFactory.Default.Layouts.RegisterDefinition("CsvMeterLayout", typeof(CsvMeterLayout)); global::NLog.Config.ConfigurationItemFactory.Default.Layouts.RegisterDefinition("CsvHistogramLayout", typeof(CsvHistogramLayout)); global::NLog.Config.ConfigurationItemFactory.Default.Layouts.RegisterDefinition("CsvTimerLayout", typeof(CsvTimerLayout)); reports.WithReporter("NLog CSV Report", () => new CSVReporter(new NLogCSVAppender(delimiter)), interval); return reports; } public static MetricsReports WithNLogTextReports(this MetricsReports reports, TimeSpan interval) { global::NLog.Config.ConfigurationItemFactory.Default.Layouts.RegisterDefinition("CsvGaugeLayout", typeof(CsvGaugeLayout)); global::NLog.Config.ConfigurationItemFactory.Default.Layouts.RegisterDefinition("CsvCounterLayout", typeof(CsvCounterLayout)); global::NLog.Config.ConfigurationItemFactory.Default.Layouts.RegisterDefinition("CsvMeterLayout", typeof(CsvMeterLayout)); global::NLog.Config.ConfigurationItemFactory.Default.Layouts.RegisterDefinition("CsvHistogramLayout", typeof(CsvHistogramLayout)); global::NLog.Config.ConfigurationItemFactory.Default.Layouts.RegisterDefinition("CsvTimerLayout", typeof(CsvTimerLayout)); reports.WithReporter("NLog Text Report", () => new NLogTextReporter(), interval); return reports; } } }
apache-2.0
C#
ce119a1c66b61a875d6662235fa8257cf2dca7e7
Fix Blocker requiring non-MonoBehaviour
SnpM/Lockstep-Framework
Core/Simulation/Grid/Utility/Tools/Blocker/Blocker.cs
Core/Simulation/Grid/Utility/Tools/Blocker/Blocker.cs
using UnityEngine; using System.Collections; using Lockstep; //Blocker for static environment pieces in a scene. [RequireComponent (typeof (Lockstep.UnityLSBody))] public class Blocker : EnvironmentObject { static readonly FastList<Vector2d> bufferCoordinates = new FastList<Vector2d>(); [SerializeField] private bool _blockPathfinding = true; public bool BlockPathfinding {get {return _blockPathfinding;}} public LSBody CachedBody {get; private set;} protected override void OnLateInitialize() { base.OnInitialize(); CachedBody = this.GetComponent<UnityLSBody> ().InternalBody; if (this.BlockPathfinding) { const long gridSpacing = FixedMath.One; bufferCoordinates.FastClear(); CachedBody.GetCoveredSnappedPositions (gridSpacing, bufferCoordinates); foreach (Vector2d vec in bufferCoordinates) { GridNode node = GridManager.GetNode(vec.x,vec.y); int gridX, gridY; GridManager.GetCoordinates(vec.x,vec.y, out gridX, out gridY); if (node == null) continue; node.AddObstacle(); } } } }
using UnityEngine; using System.Collections; using Lockstep; //Blocker for static environment pieces in a scene. [RequireComponent (typeof (LSBody))] public class Blocker : EnvironmentObject { static readonly FastList<Vector2d> bufferCoordinates = new FastList<Vector2d>(); [SerializeField] private bool _blockPathfinding = true; public bool BlockPathfinding {get {return _blockPathfinding;}} public LSBody CachedBody {get; private set;} protected override void OnLateInitialize() { base.OnInitialize(); CachedBody = this.GetComponent<UnityLSBody> ().InternalBody; if (this.BlockPathfinding) { const long gridSpacing = FixedMath.One; bufferCoordinates.FastClear(); CachedBody.GetCoveredSnappedPositions (gridSpacing, bufferCoordinates); foreach (Vector2d vec in bufferCoordinates) { GridNode node = GridManager.GetNode(vec.x,vec.y); int gridX, gridY; GridManager.GetCoordinates(vec.x,vec.y, out gridX, out gridY); if (node == null) continue; node.AddObstacle(); } } } }
mit
C#
81a3df46ed8d588dcf03fd179f8e86af972959cf
remove the debug log
fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation
UnityProject/Assets/Scripts/HealthV2/Living/BodyParts/BodyPartSprites.cs
UnityProject/Assets/Scripts/HealthV2/Living/BodyParts/BodyPartSprites.cs
using Systems.Clothing; using HealthV2; using Mirror; using Newtonsoft.Json; using UnityEngine; /// <summary> /// This is used to contain data about the basic rendering of a body part. /// It will have info about what to render when there's no limb, the position of the rendering, etc. /// </summary> public class BodyPartSprites : MonoBehaviour { [SerializeField] public SpriteHandler baseSpriteHandler; [SerializeField] public BodyPartType BodyPartType; public RootBodyPartContainer ParentContainer; public SpriteRenderer spriteRenderer; public CharacterSettings ThisCharacter; public SpriteOrder SpriteOrder; public ClothingHideFlags ClothingHide; public string Data; public int referenceOffset = 0; public void UpdateHideDlags( ClothingHideFlags newOne) { ClothingHide = newOne; if (CustomNetworkManager.Instance._isServer) { ParentContainer.UpdateThis(); } } public void UpdateData(string InNew) { if (string.IsNullOrEmpty(InNew)) return; Data = InNew; if (CustomNetworkManager.Instance._isServer) { ParentContainer.UpdateThis(); return; } SpriteOrder = JsonConvert.DeserializeObject<SpriteOrder>(Data); SpriteOrder.Orders.RemoveRange(0, 4); if (SpriteOrder != null) { if (SpriteOrder.Orders.Count > referenceOffset) { spriteRenderer.sortingOrder = SpriteOrder.Orders[referenceOffset]; } } if (baseSpriteHandler == null) return; baseSpriteHandler.ChangeSpriteVariant(referenceOffset, false); } public virtual void UpdateSpritesForImplant(BodyPart implant,ClothingHideFlags INClothingHide, SpriteDataSO Sprite, RootBodyPartContainer rootBodyPartContainer, SpriteOrder _SpriteOrder = null) { if (baseSpriteHandler == null) return; ClothingHide = INClothingHide; UpdateData( JsonConvert.SerializeObject(_SpriteOrder)); //baseSpriteHandler.name = baseSpriteHandler.name + implant.name; baseSpriteHandler.SetSpriteSO(Sprite, Color.white); SpriteOrder = _SpriteOrder; if (SpriteOrder != null) { if (SpriteOrder.Orders.Count > 0) { spriteRenderer.sortingOrder = SpriteOrder.Orders[0]; } } baseSpriteHandler.ChangeSpriteVariant(referenceOffset, false); } public virtual void SetName(string Name) { this.gameObject.name = Name; baseSpriteHandler.name = Name; } public virtual void OnDirectionChange(Orientation direction) { referenceOffset = 0; if (direction == Orientation.Down) { referenceOffset = 0; } if (direction == Orientation.Up) { referenceOffset = 1; } if (direction == Orientation.Right) { referenceOffset = 2; } if (direction == Orientation.Left) { referenceOffset = 3; } if (SpriteOrder != null) { if (SpriteOrder.Orders.Count > referenceOffset) { spriteRenderer.sortingOrder = SpriteOrder.Orders[referenceOffset]; } } baseSpriteHandler.ChangeSpriteVariant(referenceOffset, false); } }
using Systems.Clothing; using HealthV2; using Mirror; using Newtonsoft.Json; using UnityEngine; /// <summary> /// This is used to contain data about the basic rendering of a body part. /// It will have info about what to render when there's no limb, the position of the rendering, etc. /// </summary> public class BodyPartSprites : MonoBehaviour { [SerializeField] public SpriteHandler baseSpriteHandler; [SerializeField] public BodyPartType BodyPartType; public RootBodyPartContainer ParentContainer; public SpriteRenderer spriteRenderer; public CharacterSettings ThisCharacter; public SpriteOrder SpriteOrder; public ClothingHideFlags ClothingHide; public string Data; public int referenceOffset = 0; public void UpdateHideDlags( ClothingHideFlags newOne) { ClothingHide = newOne; if (CustomNetworkManager.Instance._isServer) { ParentContainer.UpdateThis(); } } public void UpdateData(string InNew) { if (string.IsNullOrEmpty(InNew)) return; Data = InNew; if (CustomNetworkManager.Instance._isServer) { ParentContainer.UpdateThis(); return; } SpriteOrder = JsonConvert.DeserializeObject<SpriteOrder>(Data); if (SpriteOrder == null) { Logger.Log("o3o"); } SpriteOrder.Orders.RemoveRange(0, 4); if (SpriteOrder != null) { if (SpriteOrder.Orders.Count > referenceOffset) { spriteRenderer.sortingOrder = SpriteOrder.Orders[referenceOffset]; } } if (baseSpriteHandler == null) return; baseSpriteHandler.ChangeSpriteVariant(referenceOffset, false); } public virtual void UpdateSpritesForImplant(BodyPart implant,ClothingHideFlags INClothingHide, SpriteDataSO Sprite, RootBodyPartContainer rootBodyPartContainer, SpriteOrder _SpriteOrder = null) { if (baseSpriteHandler == null) return; ClothingHide = INClothingHide; UpdateData( JsonConvert.SerializeObject(_SpriteOrder)); //baseSpriteHandler.name = baseSpriteHandler.name + implant.name; baseSpriteHandler.SetSpriteSO(Sprite, Color.white); SpriteOrder = _SpriteOrder; if (SpriteOrder != null) { if (SpriteOrder.Orders.Count > 0) { spriteRenderer.sortingOrder = SpriteOrder.Orders[0]; } } baseSpriteHandler.ChangeSpriteVariant(referenceOffset, false); } public virtual void SetName(string Name) { this.gameObject.name = Name; baseSpriteHandler.name = Name; } public virtual void OnDirectionChange(Orientation direction) { referenceOffset = 0; if (direction == Orientation.Down) { referenceOffset = 0; } if (direction == Orientation.Up) { referenceOffset = 1; } if (direction == Orientation.Right) { referenceOffset = 2; } if (direction == Orientation.Left) { referenceOffset = 3; } if (SpriteOrder != null) { if (SpriteOrder.Orders.Count > referenceOffset) { spriteRenderer.sortingOrder = SpriteOrder.Orders[referenceOffset]; } } baseSpriteHandler.ChangeSpriteVariant(referenceOffset, false); } }
agpl-3.0
C#
079439df9345c8959b98ae051efa6b1085e8d2a6
Make "New" content item button scrollable. (#8076)
xkproject/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2
src/OrchardCore.Modules/OrchardCore.Contents/Views/ContentsAdminList-Create.cshtml
src/OrchardCore.Modules/OrchardCore.Contents/Views/ContentsAdminList-Create.cshtml
@model ContentOptionsViewModel <div class="form-group d-inline-flex float-right mb-0"> <div class="btn-group"> @if (Model.CreatableTypes.Any()) { @if (Model.CreatableTypes.Count == 1) { <a class="btn btn-sm btn-secondary" href="@Url.RouteUrl(new { area = "OrchardCore.Contents", controller = "Admin", action = "Create", id = Model.CreatableTypes.First().Value, returnUrl = FullRequestPath })">@T["New {0}", Model.CreatableTypes.First().Text]</a> } else { <div class="dropdown order-md-1"> <button class="btn btn-secondary btn-sm dropdown-toggle" type="button" id="new-dropdown" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> @T["New"] </button> <div class="dropdown-menu dropdown-menu-right scrollable" aria-labelledby="bulk-action-menu-button"> @foreach (var item in Model.CreatableTypes) { <a class="dropdown-item" href="@Url.RouteUrl(new { area = "OrchardCore.Contents", controller = "Admin", action = "Create", id = @item.Value, returnUrl = FullRequestPath })">@T[item.Text]</a> } </div> </div> } } </div> </div>
@model ContentOptionsViewModel <div class="form-group d-inline-flex float-right mb-0"> <div class="btn-group"> @if (Model.CreatableTypes.Any()) { @if (Model.CreatableTypes.Count == 1) { <a class="btn btn-sm btn-secondary" href="@Url.RouteUrl(new { area = "OrchardCore.Contents", controller = "Admin", action = "Create", id = Model.CreatableTypes.First().Value, returnUrl = FullRequestPath })">@T["New {0}", Model.CreatableTypes.First().Text]</a> } else { <div class="dropdown order-md-1"> <button class="btn btn-secondary btn-sm dropdown-toggle" type="button" id="new-dropdown" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> @T["New"] </button> <div class="dropdown-menu dropdown-menu-right" aria-labelledby="bulk-action-menu-button"> @foreach (var item in Model.CreatableTypes) { <a class="dropdown-item" href="@Url.RouteUrl(new { area = "OrchardCore.Contents", controller = "Admin", action = "Create", id = @item.Value, returnUrl = FullRequestPath })">@T[item.Text]</a> } </div> </div> } } </div> </div>
bsd-3-clause
C#
98947ac1d3c6c2bf80920b3240e2570688baaa10
Use the new PrimaryCountry field
BloomBooks/BloomDesktop,StephenMcConnel/BloomDesktop,BloomBooks/BloomDesktop,gmartin7/myBloomFork,andrew-polk/BloomDesktop,gmartin7/myBloomFork,StephenMcConnel/BloomDesktop,andrew-polk/BloomDesktop,andrew-polk/BloomDesktop,BloomBooks/BloomDesktop,StephenMcConnel/BloomDesktop,andrew-polk/BloomDesktop,andrew-polk/BloomDesktop,StephenMcConnel/BloomDesktop,gmartin7/myBloomFork,gmartin7/myBloomFork,gmartin7/myBloomFork,StephenMcConnel/BloomDesktop,BloomBooks/BloomDesktop,andrew-polk/BloomDesktop,BloomBooks/BloomDesktop,gmartin7/myBloomFork,BloomBooks/BloomDesktop,StephenMcConnel/BloomDesktop
src/BloomExe/CollectionCreating/LanguageIdControl.cs
src/BloomExe/CollectionCreating/LanguageIdControl.cs
using System; using System.Linq; using System.Windows.Forms; using Bloom.Collection; using Bloom.ToPalaso; namespace Bloom.CollectionCreating { public partial class LanguageIdControl : UserControl, IPageControl { public CollectionSettings _collectionInfo; private Action<UserControl, bool> _setNextButtonState; public LanguageIdControl() { InitializeComponent(); _lookupISOControl.SelectedLanguage = null; _lookupISOControl.IsShowRegionalDialectsCheckBoxVisible = false; } private void OnLookupISOControlReadinessChanged(object sender, EventArgs e) { if (_collectionInfo == null) return; if (_lookupISOControl.SelectedLanguage != null) { _collectionInfo.Language1Iso639Code = _lookupISOControl.SelectedLanguage.LanguageTag; _collectionInfo.Language1Name = _lookupISOControl.SelectedLanguage.DesiredName; _collectionInfo.Country = _lookupISOControl.SelectedLanguage.PrimaryCountry ?? string.Empty; //If there are multiple countries, just leave it blank so they can type something in if (_collectionInfo.Country.Contains(",")) { _collectionInfo.Country = ""; } } _setNextButtonState(this, _lookupISOControl.SelectedLanguage != null); } public void Init(Action<UserControl, bool> setNextButtonState, CollectionSettings collectionInfo) { _setNextButtonState = setNextButtonState; _collectionInfo = collectionInfo; _lookupISOControl.ReadinessChanged += OnLookupISOControlReadinessChanged; } public void NowVisible() { _setNextButtonState(this, _lookupISOControl.SelectedLanguage != null); } private void _lookupISOControl_Leave(object sender, EventArgs e) { _setNextButtonState(this, _lookupISOControl.SelectedLanguage != null); } } }
using System; using System.Linq; using System.Windows.Forms; using Bloom.Collection; using Bloom.ToPalaso; namespace Bloom.CollectionCreating { public partial class LanguageIdControl : UserControl, IPageControl { public CollectionSettings _collectionInfo; private Action<UserControl, bool> _setNextButtonState; public LanguageIdControl() { InitializeComponent(); _lookupISOControl.SelectedLanguage = null; _lookupISOControl.IsShowRegionalDialectsCheckBoxVisible = false; } private void OnLookupISOControlReadinessChanged(object sender, EventArgs e) { if (_collectionInfo == null) return; if (_lookupISOControl.SelectedLanguage != null) { _collectionInfo.Language1Iso639Code = _lookupISOControl.SelectedLanguage.LanguageTag; _collectionInfo.Language1Name = _lookupISOControl.SelectedLanguage.DesiredName; _collectionInfo.Country = _lookupISOControl.SelectedLanguage.Countries.FirstOrDefault() ?? string.Empty; //If there are multiple countries, just leave it blank so they can type something in if (_collectionInfo.Country.Contains(",")) { _collectionInfo.Country = ""; } } _setNextButtonState(this, _lookupISOControl.SelectedLanguage != null); } public void Init(Action<UserControl, bool> setNextButtonState, CollectionSettings collectionInfo) { _setNextButtonState = setNextButtonState; _collectionInfo = collectionInfo; _lookupISOControl.ReadinessChanged += OnLookupISOControlReadinessChanged; } public void NowVisible() { _setNextButtonState(this, _lookupISOControl.SelectedLanguage != null); } private void _lookupISOControl_Leave(object sender, EventArgs e) { _setNextButtonState(this, _lookupISOControl.SelectedLanguage != null); } } }
mit
C#
7d107737eb4e505ff1b647d1e37a50b8e0d32507
Add IsNeutralDrop bool to Dota 2 Game Item
babelshift/SteamWebAPI2
src/Steam.Models/DOTA2/ItemAbilitySchemaItemModel.cs
src/Steam.Models/DOTA2/ItemAbilitySchemaItemModel.cs
using System.Collections.Generic; namespace Steam.Models.DOTA2 { public class ItemAbilitySchemaItemModel { public uint Id { get; set; } public string Name { get; set; } /// <summary> /// Valve's source files don't include localized names. Instead, the callers are responsible for populating this value /// by performing a lookup in the various language/token mapping files. /// </summary> public string LocalizedName { get; set; } public string AbilityBehavior { get; set; } public string AbilityCastRange { get; set; } public string AbilityCastPoint { get; set; } public string AbilityChannelTime { get; set; } public string AbilityCooldown { get; set; } public string AbilityDuration { get; set; } public string AbilitySharedCooldown { get; set; } public string AbilityDamage { get; set; } public string AbilityManaCost { get; set; } public double AbilityModifierSupportValue { get; set; } public string AbilityUnitTargetTeam { get; set; } public string AbilityUnitDamageType { get; set; } public string AbilityUnitTargetFlags { get; set; } public string AbilityUnitTargetType { get; set; } public IList<AbilitySpecialSchemaItemModel> AbilitySpecials { get; set; } public uint ItemCost { get; set; } public string ItemShopTags { get; set; } public string ItemQuality { get; set; } public bool ItemStackable { get; set; } public string ItemShareability { get; set; } public bool ItemPermanent { get; set; } public uint? ItemInitialCharges { get; set; } public uint? ItemDisplayCharges { get; set; } public uint? ItemStockMax { get; set; } public uint? ItemStockInitial { get; set; } public double? ItemStockTime { get; set; } public bool? ItemPurchasable { get; set; } public bool? ItemSellable { get; set; } public bool? ItemKillable { get; set; } public string ItemDeclarations { get; set; } public bool? ItemCastOnPickup { get; set; } public bool? ItemSupport { get; set; } public string ItemResult { get; set; } public bool? ItemAlertable { get; set; } public bool? ItemDroppable { get; set; } public bool? ItemContributesToNetWorthWhenDropped { get; set; } public string ItemDisassembleRule { get; set; } public bool? ItemIsNeutralDrop { get; set; } } }
using System.Collections.Generic; namespace Steam.Models.DOTA2 { public class ItemAbilitySchemaItemModel { public uint Id { get; set; } public string Name { get; set; } /// <summary> /// Valve's source files don't include localized names. Instead, the callers are responsibel for populating this value /// by performing a lookup in the various language/token mapping files. /// </summary> public string LocalizedName { get; set; } public string AbilityBehavior { get; set; } public string AbilityCastRange { get; set; } public string AbilityCastPoint { get; set; } public string AbilityChannelTime { get; set; } public string AbilityCooldown { get; set; } public string AbilityDuration { get; set; } public string AbilitySharedCooldown { get; set; } public string AbilityDamage { get; set; } public string AbilityManaCost { get; set; } public double AbilityModifierSupportValue { get; set; } public string AbilityUnitTargetTeam { get; set; } public string AbilityUnitDamageType { get; set; } public string AbilityUnitTargetFlags { get; set; } public string AbilityUnitTargetType { get; set; } public IList<AbilitySpecialSchemaItemModel> AbilitySpecials { get; set; } public uint ItemCost { get; set; } public string ItemShopTags { get; set; } public string ItemQuality { get; set; } public bool ItemStackable { get; set; } public string ItemShareability { get; set; } public bool ItemPermanent { get; set; } public uint? ItemInitialCharges { get; set; } public uint? ItemDisplayCharges { get; set; } public uint? ItemStockMax { get; set; } public uint? ItemStockInitial { get; set; } public double? ItemStockTime { get; set; } public bool? ItemPurchasable { get; set; } public bool? ItemSellable { get; set; } public bool? ItemKillable { get; set; } public string ItemDeclarations { get; set; } public bool? ItemCastOnPickup { get; set; } public bool? ItemSupport { get; set; } public string ItemResult { get; set; } public bool? ItemAlertable { get; set; } public bool? ItemDroppable { get; set; } public bool? ItemContributesToNetWorthWhenDropped { get; set; } public string ItemDisassembleRule { get; set; } } }
mit
C#
6bda79345c5613c68e235e6301aee05a549a04b0
Revert to C#6
kyubisation/FluentRestBuilder,kyubisation/FluentRestBuilder
src/FluentRestBuilder/Pipes/FilterByClientRequest/Converters/FilterToBooleanConverter.cs
src/FluentRestBuilder/Pipes/FilterByClientRequest/Converters/FilterToBooleanConverter.cs
// <copyright file="FilterToBooleanConverter.cs" company="Kyubisation"> // Copyright (c) Kyubisation. All rights reserved. // </copyright> namespace FluentRestBuilder.Pipes.FilterByClientRequest.Converters { using Results; public class FilterToBooleanConverter : IFilterToTypeConverter<bool> { public FilterConversionResult<bool> Parse(string filter) { bool result; if (bool.TryParse(filter, out result) || TryParse(filter, out result)) { return new FilterConversionSuccess<bool>(result); } return new FilterConversionFailure<bool>(); } private static bool TryParse(string filter, out bool result) { result = false; switch (filter.Trim()) { case "0": return true; case "1": result = true; return true; default: return false; } } } }
// <copyright file="FilterToBooleanConverter.cs" company="Kyubisation"> // Copyright (c) Kyubisation. All rights reserved. // </copyright> namespace FluentRestBuilder.Pipes.FilterByClientRequest.Converters { using Results; public class FilterToBooleanConverter : IFilterToTypeConverter<bool> { public FilterConversionResult<bool> Parse(string filter) { if (bool.TryParse(filter, out var result) || TryParse(filter, out result)) { return new FilterConversionSuccess<bool>(result); } return new FilterConversionFailure<bool>(); } private static bool TryParse(string filter, out bool result) { result = false; switch (filter.Trim()) { case "0": return true; case "1": result = true; return true; default: return false; } } } }
mit
C#
0006db79f35608818901b2345fd43a170ef20634
Remove incorrect Invariant contract
peopleware/net-ppwcode-vernacular-persistence
src/PPWCode.Vernacular.Persistence.II/Implementations/InsertAuditablePersistentObject.cs
src/PPWCode.Vernacular.Persistence.II/Implementations/InsertAuditablePersistentObject.cs
using System; using System.Diagnostics.Contracts; using System.Runtime.Serialization; namespace PPWCode.Vernacular.Persistence.II { [Serializable, DataContract(IsReference = true)] public abstract class InsertAuditablePersistentObject<T> : PersistentObject<T>, IInsertAuditable where T : IEquatable<T> { [DataMember] private DateTime? m_CreatedAt; [DataMember] private string m_CreatedBy; protected InsertAuditablePersistentObject(T id) : base(id) { } protected InsertAuditablePersistentObject() { } [AuditLogPropertyIgnore] public virtual DateTime? CreatedAt { get { return m_CreatedAt; } set { m_CreatedAt = value; } } [AuditLogPropertyIgnore] public virtual string CreatedBy { get { return m_CreatedBy; } set { m_CreatedBy = value; } } } }
using System; using System.Diagnostics.Contracts; using System.Runtime.Serialization; namespace PPWCode.Vernacular.Persistence.II { [Serializable, DataContract(IsReference = true)] public abstract class InsertAuditablePersistentObject<T> : PersistentObject<T>, IInsertAuditable where T : IEquatable<T> { [DataMember] private DateTime? m_CreatedAt; [DataMember] private string m_CreatedBy; protected InsertAuditablePersistentObject(T id) : base(id) { } protected InsertAuditablePersistentObject() { } [AuditLogPropertyIgnore] public virtual DateTime? CreatedAt { get { return m_CreatedAt; } set { m_CreatedAt = value; } } [AuditLogPropertyIgnore] public virtual string CreatedBy { get { return m_CreatedBy; } set { m_CreatedBy = value; } } [ContractInvariantMethod] private void ObjectInvariant() { Contract.Invariant(CreatedBy != null); } } }
apache-2.0
C#
e7ba7d96778d0a2be449a33f61b6d6fc898138f6
Create a minimal constructor, useful for external providers
janjonas/OpenContent,janjonas/OpenContent,janjonas/OpenContent,janjonas/OpenContent,janjonas/OpenContent
Components/OpenContentInfo.cs
Components/OpenContentInfo.cs
/* ' Copyright (c) 2015 Satrabel.be ' All rights reserved. ' ' 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.Web.Caching; using DotNetNuke.Common.Utilities; using DotNetNuke.ComponentModel.DataAnnotations; using DotNetNuke.Entities.Content; using System.Collections.Generic; using Newtonsoft.Json.Linq; using Newtonsoft.Json; namespace Satrabel.OpenContent.Components { [TableName("OpenContent_Items")] [PrimaryKey("ContentId", AutoIncrement = true)] //[Cacheable("OpenContentItems", CacheItemPriority.Default, 20)] [Scope("ModuleId")] public class OpenContentInfo { public OpenContentInfo() { } public OpenContentInfo(string json) { Json = json; } public int ContentId { get; set; } public string Title { get; set; } public string Html { get; set; } public string Json { get; set; } public int ModuleId { get; set; } public int CreatedByUserId { get; set; } public int LastModifiedByUserId { get; set; } public DateTime CreatedOnDate { get; set; } public DateTime LastModifiedOnDate { get; set; } public string VersionsJson { get; set; } [IgnoreColumn] public List<OpenContentVersion> Versions { get { List<OpenContentVersion> lst; if (string.IsNullOrWhiteSpace(VersionsJson)) { lst = new List<OpenContentVersion>(); } else { lst = JsonConvert.DeserializeObject<List<OpenContentVersion>>(VersionsJson); } return lst; } set { VersionsJson = JsonConvert.SerializeObject(value); } } } }
/* ' Copyright (c) 2015 Satrabel.be ' All rights reserved. ' ' 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.Web.Caching; using DotNetNuke.Common.Utilities; using DotNetNuke.ComponentModel.DataAnnotations; using DotNetNuke.Entities.Content; using System.Collections.Generic; using Newtonsoft.Json.Linq; using Newtonsoft.Json; namespace Satrabel.OpenContent.Components { [TableName("OpenContent_Items")] [PrimaryKey("ContentId", AutoIncrement = true)] //[Cacheable("OpenContentItems", CacheItemPriority.Default, 20)] [Scope("ModuleId")] public class OpenContentInfo { public int ContentId { get; set; } public string Title { get; set; } public string Html { get; set; } public string Json { get; set; } public int ModuleId { get; set; } public int CreatedByUserId { get; set; } public int LastModifiedByUserId { get; set; } public DateTime CreatedOnDate { get; set; } public DateTime LastModifiedOnDate { get; set; } public string VersionsJson { get; set; } [IgnoreColumn] public List<OpenContentVersion> Versions { get { List<OpenContentVersion> lst; if (string.IsNullOrWhiteSpace(VersionsJson)) { lst = new List<OpenContentVersion>(); } else { lst = JsonConvert.DeserializeObject<List<OpenContentVersion>>(VersionsJson); } return lst; } set { VersionsJson = JsonConvert.SerializeObject(value); } } } }
mit
C#
ff68e9c814a845bbbf691d37695a928cd0c7e939
Put in undo redo counts and notifications.
larsbrubaker/agg-sharp,MatterHackers/agg-sharp,jlewin/agg-sharp
Gui/TextWidgets/UndoBuffer.cs
Gui/TextWidgets/UndoBuffer.cs
//---------------------------------------------------------------------------- // Anti-Grain Geometry - Version 2.4 // Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com) // // C# port by: Lars Brubaker // larsbrubaker@gmail.com // Copyright (C) 2007 // // Permission to copy, use, modify, sell and distribute this software // is granted provided this copyright notice appears in all copies. // This software is provided "as is" without express or implied // warranty, and with no claim as to its suitability for any purpose. // //---------------------------------------------------------------------------- // Contact: mcseem@antigrain.com // mcseemagg@yahoo.com // http://www.antigrain.com //---------------------------------------------------------------------------- using System; using System.Collections.Generic; namespace MatterHackers.Agg.UI { public class UndoBuffer { private Stack<IUndoRedoCommand> redoBuffer = new Stack<IUndoRedoCommand>(); public int RedoCount { get { return redoBuffer.Count; } } private Stack<IUndoRedoCommand> undoBuffer = new Stack<IUndoRedoCommand>(); public int UndoCount { get { return undoBuffer.Count; } } public event EventHandler Changed; public UndoBuffer() { } public void Add(IUndoRedoCommand command) { undoBuffer.Push(command); redoBuffer.Clear(); Changed?.Invoke(this, null); } public void Redo(int redoCount = 1) { for (int i = 1; i <= redoCount; i++) { if (redoBuffer.Count != 0) { IUndoRedoCommand command = redoBuffer.Pop(); command.Do(); undoBuffer.Push(command); } } Changed?.Invoke(this, null); } public void Undo(int undoCount = 1) { for (int i = 1; i <= undoCount; i++) { if (undoBuffer.Count != 0) { IUndoRedoCommand command = undoBuffer.Pop(); command.Undo(); redoBuffer.Push(command); } } Changed?.Invoke(this, null); } internal void ClearHistory() { undoBuffer.Clear(); redoBuffer.Clear(); Changed?.Invoke(this, null); } } public interface IUndoRedoCommand { void Do(); void Undo(); } }
//---------------------------------------------------------------------------- // Anti-Grain Geometry - Version 2.4 // Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com) // // C# port by: Lars Brubaker // larsbrubaker@gmail.com // Copyright (C) 2007 // // Permission to copy, use, modify, sell and distribute this software // is granted provided this copyright notice appears in all copies. // This software is provided "as is" without express or implied // warranty, and with no claim as to its suitability for any purpose. // //---------------------------------------------------------------------------- // Contact: mcseem@antigrain.com // mcseemagg@yahoo.com // http://www.antigrain.com //---------------------------------------------------------------------------- using System.Collections.Generic; namespace MatterHackers.Agg.UI { public class UndoBuffer { private Stack<IUndoRedoCommand> redoBuffer = new Stack<IUndoRedoCommand>(); private Stack<IUndoRedoCommand> undoBuffer = new Stack<IUndoRedoCommand>(); public UndoBuffer() { } public void Add(IUndoRedoCommand command) { undoBuffer.Push(command); redoBuffer.Clear(); } public void Redo(int redoCount = 1) { for (int i = 1; i <= redoCount; i++) { if (redoBuffer.Count != 0) { IUndoRedoCommand command = redoBuffer.Pop(); command.Do(); undoBuffer.Push(command); } } } public void Undo(int undoCount = 1) { for (int i = 1; i <= undoCount; i++) { if (undoBuffer.Count != 0) { IUndoRedoCommand command = undoBuffer.Pop(); command.Undo(); redoBuffer.Push(command); } } } internal void ClearHistory() { undoBuffer.Clear(); redoBuffer.Clear(); } } public interface IUndoRedoCommand { void Do(); void Undo(); } }
bsd-2-clause
C#
2c7a2ffc2270959cf7f59a56976eed3ee03ab990
Fix xUnit warning
benyblack/rest-mock-core
src/RestMockCore.Test/RequestHandlerTest.cs
src/RestMockCore.Test/RequestHandlerTest.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Xunit; namespace RestMockCore.Test { public class RequestHandlerTest { private readonly RequestHandler _requestHandler; private readonly RouteTableItem _route; public RequestHandlerTest() { var headers = new Dictionary<string, string> {{"Content-Type", "application/json"}}; _route = new RouteTableItem("GET", "/test/123/", headers); _requestHandler = new RequestHandler(_route); } [Fact] public void SendTest() { var headers = new Dictionary<string, string> {{"Content-Type", "application/json"}}; _requestHandler.Send("test body", 503, headers); Assert.NotNull(_route.Response); Assert.Equal("test body", _route.Response.Body); Assert.Equal(503, _route.Response.StatusCode); Assert.Single(_route.Response.Headers); Assert.Equal("application/json", _route.Response.Headers["Content-Type"]); } [Fact] public void SendTest_Action() { _requestHandler.Send(context => { }); Assert.NotNull(_route.Response); Assert.NotNull(_route.Response.Handler); } [Fact] public void Response_Getter_Test() { var response = _requestHandler.Response; Assert.NotNull(response); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Xunit; namespace RestMockCore.Test { public class RequestHandlerTest { private readonly RequestHandler _requestHandler; private readonly RouteTableItem _route; public RequestHandlerTest() { var headers = new Dictionary<string, string> {{"Content-Type", "application/json"}}; _route = new RouteTableItem("GET", "/test/123/", headers); _requestHandler = new RequestHandler(_route); } [Fact] public void SendTest() { var headers = new Dictionary<string, string> {{"Content-Type", "application/json"}}; _requestHandler.Send("test body", 503, headers); Assert.NotNull(_route.Response); Assert.Equal("test body", _route.Response.Body); Assert.Equal(503, _route.Response.StatusCode); Assert.Equal(1, _route.Response.Headers.Count); Assert.Equal("application/json", _route.Response.Headers["Content-Type"]); } [Fact] public void SendTest_Action() { _requestHandler.Send(context => { }); Assert.NotNull(_route.Response); Assert.NotNull(_route.Response.Handler); } [Fact] public void Response_Getter_Test() { var response = _requestHandler.Response; Assert.NotNull(response); } } }
mit
C#
69fdf01e15ed7a7585b9a9d5ed29c05b4c12b742
Update version 2.2
SonarSource-VisualStudio/sonar-scanner-msbuild,SonarSource-VisualStudio/sonar-scanner-msbuild,SonarSource-VisualStudio/sonar-msbuild-runner,duncanpMS/sonar-msbuild-runner,SonarSource-DotNet/sonar-msbuild-runner,duncanpMS/sonar-msbuild-runner,SonarSource-VisualStudio/sonar-msbuild-runner,duncanpMS/sonar-msbuild-runner,SonarSource/sonar-msbuild-runner,SonarSource-VisualStudio/sonar-scanner-msbuild
AssemblyInfo.Shared.cs
AssemblyInfo.Shared.cs
//----------------------------------------------------------------------- // <copyright file="AssemblyInfo.Shared.cs" company="SonarSource SA and Microsoft Corporation"> // Copyright (c) SonarSource SA and Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // </copyright> //----------------------------------------------------------------------- using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyVersion("2.2.0.0")] [assembly: AssemblyFileVersion("2.2.0.0")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("SonarSource and Microsoft")] [assembly: AssemblyCopyright("Copyright © SonarSource and Microsoft 2015/2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)]
//----------------------------------------------------------------------- // <copyright file="AssemblyInfo.Shared.cs" company="SonarSource SA and Microsoft Corporation"> // Copyright (c) SonarSource SA and Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // </copyright> //----------------------------------------------------------------------- using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyVersion("2.1.0.0")] [assembly: AssemblyFileVersion("2.1.0.0")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("SonarSource and Microsoft")] [assembly: AssemblyCopyright("Copyright © SonarSource and Microsoft 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)]
mit
C#
a9ba8490b99dae6a0294f966961b6af2678cd119
Bump version
gonzalocasas/NetMetrixSDK
Properties/AssemblyInfo.cs
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("NetMetrixSDK")] [assembly: AssemblyDescription("Net-Metrix SDK for Windows Phone applications")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Gonzalo Casas")] [assembly: AssemblyProduct("NetMetrix SDK")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("d26acda3-5465-4207-8fd0-a1bbedd41bbc")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.2.0")] [assembly: AssemblyFileVersion("1.0.2.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("NetMetrixSDK")] [assembly: AssemblyDescription("Net-Metrix SDK for Windows Phone applications")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Gonzalo Casas")] [assembly: AssemblyProduct("NetMetrix SDK")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("d26acda3-5465-4207-8fd0-a1bbedd41bbc")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.1.0")] [assembly: AssemblyFileVersion("1.0.1.0")] [assembly: NeutralResourcesLanguageAttribute("en-US")]
mit
C#
72bf9b9a74da7bcb1e6279dd7c5efb3b8da60981
Update AssemblyInfo.cs
anilhakanyarici/next-generation-crypto
Properties/AssemblyInfo.cs
Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("System.Security.Cryptography")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("System.Security.Cryptography")] [assembly: AssemblyCopyright("Copyright © 2016")] [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("6fd94afd-2c6c-4a3e-aa42-e178f4c74e9a")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#
9a1e78c025bf3d6fc8d5fa4c8438f48e7fc80e5e
bump version
lukesampson/HastyAPI.FreshBooks
Properties/AssemblyInfo.cs
Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("HastyAPI.FreshBooks")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("HastyAPI.FreshBooks")] [assembly: AssemblyCopyright("Copyright © 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("8a449dea-41b9-45f8-b169-ca95f0217dde")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.4")] [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("HastyAPI.FreshBooks")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("HastyAPI.FreshBooks")] [assembly: AssemblyCopyright("Copyright © 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("8a449dea-41b9-45f8-b169-ca95f0217dde")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.3")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#
3e300962b9ff57184e05d16fbaac987b2974f84c
Add initial client code
emailclue/emailclue-dotnet
EmailClue/EmailClue.cs
EmailClue/EmailClue.cs
using System; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; namespace EmailClue { public interface IEmailClue { // Validation validateEmail(string Email); Task<Validation> ValidateEmailAsync(string Email); // EmailSend SendEmail(string TemplateKey); // Task<EmailSend> sendEmailAsync(string TemplateKey); } public class EmailClue : IEmailClue, IDisposable { private readonly string apiToken; private readonly HttpClient client; public EmailClue(string apiToken) { this.client = new HttpClient(); client.DefaultRequestHeaders.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiToken); client.BaseAddress = new Uri("https://api.emailclue.com/"); this.apiToken = apiToken; } public async Task<Validation> ValidateEmailAsync(string Email) { // Check encoding works HttpResponseMessage response = await client.GetAsync("/v1/email/address/" + Email + "/status"); response.EnsureSuccessStatusCode(); return await response.Content.ReadAsAsync<Validation>(); } // public EmailSend SendEmail(string TemplateKey) // { // var result = new EmailSend(); // result.ID = "asdj19"; // return result; // } public void Dispose() { client.Dispose(); } } }
using System; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; namespace EmailClue { public interface IEmailClue { // Validation validateEmail(string Email); Task<Validation> ValidateEmailAsync(string Email); EmailSend SendEmail(string TemplateKey); // Task<EmailSend> sendEmailAsync(string TemplateKey); } public class EmailClue : IEmailClue, IDisposable { private readonly string apiToken; private readonly HttpClient client; public EmailClue(string apiToken) { this.client = new HttpClient(); client.DefaultRequestHeaders.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiToken); client.BaseAddress = new Uri("https://api.emailclue.com/"); this.apiToken = apiToken; } public async Task<Validation> ValidateEmailAsync(string Email) { // Check encoding works HttpResponseMessage response = await client.GetAsync("/v1/email/address/" + Email + "/status"); response.EnsureSuccessStatusCode(); return await response.Content.ReadAsAsync<Validation>(); } public EmailSend SendEmail(string TemplateKey) { var result = new EmailSend(); result.ID = "asdj19"; return result; } public void Dispose() { client.Dispose(); } } }
mit
C#
e4cbb511cd7d4013e7408656b001f175691901b1
Allow specifying document types to search.
mios-fi/mios.swiftype,mios-fi/mios.swiftype
Library/QuerySpecification.cs
Library/QuerySpecification.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Mios.Swiftype { public class QuerySpecification { public string Q { get; set; } public int Page { get; set; } public int? PerPage { get; set; } public string[] DocumentTypes { get; set; } public IDictionary<string, FilterCollection> Filters { get; set; } public IDictionary<string, IEnumerable<string>> SearchFields { get; set; } public IDictionary<string, IEnumerable<string>> FetchFields { get; set; } public QuerySpecification() { Page = 1; Filters = new Dictionary<string, FilterCollection>(); SearchFields = new Dictionary<string, IEnumerable<string>>(); FetchFields = new Dictionary<string, IEnumerable<string>>(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Mios.Swiftype { public class QuerySpecification { public string Q { get; set; } public int Page { get; set; } public int? PerPage { get; set; } public IDictionary<string, FilterCollection> Filters { get; set; } public IDictionary<string, IEnumerable<string>> SearchFields { get; set; } public IDictionary<string, IEnumerable<string>> FetchFields { get; set; } public QuerySpecification() { Page = 1; Filters = new Dictionary<string, FilterCollection>(); SearchFields = new Dictionary<string, IEnumerable<string>>(); FetchFields = new Dictionary<string, IEnumerable<string>>(); } } }
bsd-2-clause
C#
9f82d15137666f03cc265add0ef795c664d14f90
Fix compile error from merging Up and Down
rit-sse-mycroft/core
Mycroft/Cmd/App/AppCommand.cs
Mycroft/Cmd/App/AppCommand.cs
using Mycroft.App; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Mycroft.Cmd.App { class AppCommand : Command { /// <summary> /// Parses JSON into App command objects /// </summary> /// <param name="messageType">The message type that determines the command to create</param> /// <param name="json">The JSON body of the message</param> /// <returns>Returns a command object for the parsed message</returns> public static Command Parse(String type, String json, AppInstance instance) { switch (type) { case "APP_UP": case "APP_DOWN": return new DependencyChange(instance); case "APP_DESTROY": return new Destroy(json, instance); case "APP_MANIFEST": return Manifest.Parse(json, instance); default: //data is incorrect - can't do anything with it // TODO notify that is wrong break; } return null ; } } }
using Mycroft.App; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Mycroft.Cmd.App { class AppCommand : Command { /// <summary> /// Parses JSON into App command objects /// </summary> /// <param name="messageType">The message type that determines the command to create</param> /// <param name="json">The JSON body of the message</param> /// <returns>Returns a command object for the parsed message</returns> public static Command Parse(String type, String json, AppInstance instance) { switch (type) { case "APP_UP": return new Up(json, instance); case "APP_DOWN": return new DependencyChange(instance); case "APP_DESTROY": return new Destroy(json, instance); case "APP_MANIFEST": return Manifest.Parse(json, instance); default: //data is incorrect - can't do anything with it // TODO notify that is wrong break; } return null ; } } }
bsd-3-clause
C#
a9ee7bb10e92f82aa2e193b5e28f96f3a4145f67
Increase version to 2.4.3
Azure/amqpnetlite
src/Properties/Version.cs
src/Properties/Version.cs
// ------------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation // 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 CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR // CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR // NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing permissions and // limitations under the License. // ------------------------------------------------------------------------------------ using System.Reflection; // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // [assembly: AssemblyVersion("2.1.0")] [assembly: AssemblyFileVersion("2.4.3")] [assembly: AssemblyInformationalVersion("2.4.3")]
// ------------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation // 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 CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR // CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR // NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing permissions and // limitations under the License. // ------------------------------------------------------------------------------------ using System.Reflection; // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // [assembly: AssemblyVersion("2.1.0")] [assembly: AssemblyFileVersion("2.4.2")] [assembly: AssemblyInformationalVersion("2.4.2")]
apache-2.0
C#
14496f85fe1ba323d33922c534a7550dea30b73c
Send message to specific connection
ryanwersal/MorseL,ryanwersal/MorseL,radu-matei/websocket-manager,radu-matei/websocket-manager,radu-matei/websocket-manager,ryanwersal/MorseL,ryanwersal/MorseL
src/WebSocketManager/WebSocketManagerMiddleware.cs
src/WebSocketManager/WebSocketManagerMiddleware.cs
using System.Threading.Tasks; using Microsoft.AspNetCore.Http; namespace WebSocketManager { public class WebSocketManagerMiddleware { private readonly RequestDelegate _next; private WebSocketManager _webSocketManager { get; set; } private WebSocketMessageHandler _webSocketMessageHandler { get; set; } public WebSocketManagerMiddleware(RequestDelegate next, WebSocketManager webSocketManager, WebSocketMessageHandler webSocketMessageHandler) { _next = next; _webSocketManager = webSocketManager; _webSocketMessageHandler = webSocketMessageHandler; } public async Task Invoke(HttpContext context) { if(!context.WebSockets.IsWebSocketRequest) return; var socket = await context.WebSockets.AcceptWebSocketAsync(); _webSocketManager.AddSocket(socket); var socketId = _webSocketManager.GetId(socket); await _webSocketMessageHandler.SendMessageAsync(socketId: socketId, message: $"SocketId: {_webSocketManager.GetId(socket)}"); await _next.Invoke(context); } } }
using System.Threading.Tasks; using Microsoft.AspNetCore.Http; namespace WebSocketManager { public class WebSocketManagerMiddleware { private readonly RequestDelegate _next; private WebSocketManager _webSocketManager { get; set; } private WebSocketMessageHandler _webSocketMessageHandler { get; set; } public WebSocketManagerMiddleware(RequestDelegate next, WebSocketManager webSocketManager, WebSocketMessageHandler webSocketMessageHandler) { _next = next; _webSocketManager = webSocketManager; _webSocketMessageHandler = webSocketMessageHandler; } public async Task Invoke(HttpContext context) { if(!context.WebSockets.IsWebSocketRequest) return; var socket = await context.WebSockets.AcceptWebSocketAsync(); _webSocketManager.AddSocket(socket); await _webSocketMessageHandler.SendMessageAsync(socketId: "", message: _webSocketManager.GetId(socket)); await _next.Invoke(context); } } }
mit
C#
70362f2c057363cdd5fb157bc2ab74fe4c45981e
Update SyntaxEpsilon.cs
b3b00/csly
sly/parser/syntax/tree/SyntaxEpsilon.cs
sly/parser/syntax/tree/SyntaxEpsilon.cs
using sly.lexer; using System.Diagnostics.CodeAnalysis; namespace sly.parser.syntax.tree { public class SyntaxEpsilon<IN> : ISyntaxNode<IN> where IN : struct { public bool Discarded { get; } = false; public string Name => "Epsilon"; public bool HasByPassNodes { get; set; } = false; [ExcludeFromCodeCoverage] public string Dump(string tab) { return $"Epsilon"; } [ExcludeFromCodeCoverage] public string ToJson(int index = 0) { return $@"""{index}.Epsilon"":""e"""; } } }
using sly.lexer; namespace sly.parser.syntax.tree { public class SyntaxEpsilon<IN> : ISyntaxNode<IN> where IN : struct { public bool Discarded { get; } = false; public string Name => "Epsilon"; public bool HasByPassNodes { get; set; } = false; [ExcludeFromCodeCoverage] public string Dump(string tab) { return $"Epsilon"; } [ExcludeFromCodeCoverage] public string ToJson(int index = 0) { return $@"""{index}.Epsilon"":""e"""; } } }
mit
C#
731c5d7c839e2077bd5d29d5f00ca5b6a4497db2
Fix project not compiling
peppy/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,ppy/osu-framework,peppy/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework
osu.Framework/Lists/IWeakList.cs
osu.Framework/Lists/IWeakList.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; namespace osu.Framework.Lists { /// <summary> /// A slim interface for a list which stores weak references of objects. /// </summary> /// <typeparam name="T"></typeparam> public interface IWeakList<T> where T : class { /// <summary> /// Adds an item to this list. The item is added as a weak reference. /// </summary> /// <param name="item">The item to add.</param> void Add(T item); /// <summary> /// Adds a weak reference to this list. /// </summary> /// <param name="weakReference"></param> void Add(WeakReference<T> weakReference); /// <summary> /// Removes an item from this list. /// </summary> /// <param name="item"></param> void Remove(T item); /// <summary> /// Removes a weak reference from this list. /// </summary> /// <param name="weakReference"></param> bool Remove(WeakReference<T> weakReference); /// <summary> /// Searches for an item in the list. /// </summary> /// <param name="item">The item to search for.</param> /// <returns>Whether the item is alive and in this list.</returns> bool Contains(T item); /// <summary> /// Searches for a weak reference in the list. /// </summary> /// <param name="weakReference">The weak reference to search for.</param> /// <returns>Whether the weak reference is in the list.</returns> bool Contains(WeakReference<T> weakReference); /// <summary> /// Clears all items from this list. /// </summary> void 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. using System; namespace osu.Framework.Lists { /// <summary> /// A slim interface for a list which stores weak references of objects. /// </summary> /// <typeparam name="T"></typeparam> public interface IWeakList<T> where T : class { /// <summary> /// Adds an item to this list. The item is added as a weak reference. /// </summary> /// <param name="item">The item to add.</param> void Add(T item); /// <summary> /// Adds a weak reference to this list. /// </summary> /// <param name="weakReference"></param> void Add(WeakReference<T> weakReference); /// <summary> /// Removes an item from this list. /// </summary> /// <param name="item"></param> void Remove(T item); /// <summary> /// Removes a weak reference from this list. /// </summary> /// <param name="weakReference"></param> bool Remove(WeakReference<T> weakReference); /// <summary> /// Searches for an item in the list. /// </summary> /// <param name="item">The item to search for.</param> /// <returns>Whether the item is alive and in this list.</returns> bool Contains(T item); /// <summary> /// Searches for a weak reference in the list. /// </summary> /// <param name="weakReference">The weak reference to search for.</param> /// <returns>Whether the weak reference is in the list.</returns> bool Contains(WeakReference<T> weakReference); /// <summary> /// Clears all items from this list. /// </summary> void Clear(); /// <summary> /// Performs an action for each alive reference in this list. /// </summary> /// <param name="action">The action to perform.</param> void ForEachAlive(Action<T> action); } }
mit
C#
cc05a6b738649a981392ceb3b7bdef155abb2e6b
Remove comment about ffmpeg from interface
smoogipooo/osu-framework,peppy/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,peppy/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework
osu.Framework/Graphics/Animations/IAnimation.cs
osu.Framework/Graphics/Animations/IAnimation.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. namespace osu.Framework.Graphics.Animations { /// <summary> /// An animation / playback sequence. /// </summary> public interface IAnimation { /// <summary> /// The duration of the animation. /// </summary> public double Duration { get; } /// <summary> /// True if the animation has finished playing, false otherwise. /// </summary> public bool FinishedPlaying => !Loop && PlaybackPosition > Duration; /// <summary> /// True if the animation is playing, false otherwise. Starts true. /// </summary> bool IsPlaying { get; set; } /// <summary> /// True if the animation should start over from the first frame after finishing. False if it should stop playing and keep displaying the last frame when finishing. /// </summary> bool Loop { get; set; } /// <summary> /// Seek the animation to a specific time value. /// </summary> /// <param name="time">The time value to seek to.</param> void Seek(double time); /// <summary> /// The current position of playback. /// </summary> public double PlaybackPosition { get; set; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. namespace osu.Framework.Graphics.Animations { /// <summary> /// An animation / playback sequence. /// </summary> public interface IAnimation { /// <summary> /// The duration of the animation. Can only be queried after the decoder has started decoding has loaded. This value may be an estimate by FFmpeg, depending on the video loaded. /// </summary> public double Duration { get; } /// <summary> /// True if the animation has finished playing, false otherwise. /// </summary> public bool FinishedPlaying => !Loop && PlaybackPosition > Duration; /// <summary> /// True if the animation is playing, false otherwise. Starts true. /// </summary> bool IsPlaying { get; set; } /// <summary> /// True if the animation should start over from the first frame after finishing. False if it should stop playing and keep displaying the last frame when finishing. /// </summary> bool Loop { get; set; } /// <summary> /// Seek the animation to a specific time value. /// </summary> /// <param name="time">The time value to seek to.</param> void Seek(double time); /// <summary> /// The current position of playback. /// </summary> public double PlaybackPosition { get; set; } } }
mit
C#
be301076cc95127c3ba585ee0f1a2cbd1558b859
add more test case
Wox-launcher/Wox,qianlifeng/Wox,qianlifeng/Wox,qianlifeng/Wox,Wox-launcher/Wox
Wox.Test/PluginManagerTest.cs
Wox.Test/PluginManagerTest.cs
using System; using System.Collections.Generic; using System.Linq; using NUnit.Framework; using Wox.Core; using Wox.Core.Configuration; using Wox.Core.Plugin; using Wox.Infrastructure; using Wox.Infrastructure.Image; using Wox.Infrastructure.UserSettings; using Wox.Plugin; using Wox.ViewModel; namespace Wox.Test { [TestFixture] class PluginManagerTest { [OneTimeSetUp] public void setUp() { // todo remove i18n from application / ui, so it can be tested in a modular way new App(); Constant.Initialize(); ImageLoader.Initialize(); Updater updater = new Updater(""); Portable portable = new Portable(); SettingWindowViewModel settingsVm = new SettingWindowViewModel(updater, portable); Settings settings = settingsVm.Settings; Alphabet alphabet = new Alphabet(); alphabet.Initialize(settings); StringMatcher stringMatcher = new StringMatcher(alphabet); StringMatcher.Instance = stringMatcher; stringMatcher.UserSettingSearchPrecision = settings.QuerySearchPrecision; PluginManager.LoadPlugins(settings.PluginSettings); MainViewModel mainVm = new MainViewModel(settings, false); PublicAPIInstance api = new PublicAPIInstance(settingsVm, mainVm, alphabet); PluginManager.InitializePlugins(api); } [TestCase("powershell", "PowerShell")] [TestCase("note", "Notepad")] [TestCase("setting", "Settings")] [TestCase("compu", "computer")] [TestCase("netwo", "Network and Sharing Center")] public void ProgramPluginTest(string QueryText, string ResultTitle) { Query query = QueryBuilder.Build(QueryText.Trim(), PluginManager.NonGlobalPlugins); List<PluginPair> plugins = PluginManager.ValidPluginsForQuery(query); Result result = plugins.SelectMany( p => PluginManager.QueryForPlugin(p, query) ) .OrderByDescending(r => r.Score) .First(); // we won't compre all content, since content description may too long to write testcase Assert.IsTrue(result.Title.StartsWith(ResultTitle)); } } }
using System; using System.Collections.Generic; using System.Linq; using NUnit.Framework; using Wox.Core; using Wox.Core.Configuration; using Wox.Core.Plugin; using Wox.Infrastructure; using Wox.Infrastructure.Image; using Wox.Infrastructure.UserSettings; using Wox.Plugin; using Wox.ViewModel; namespace Wox.Test { [TestFixture] class PluginManagerTest { [Test] public void ProgramPluginTest() { String QueryText = "PowerShell"; String ResultTitle = "PowerShell"; // todo remove i18n from application / ui, so it can be tested in a modular way var application = new App(); Constant.Initialize(); ImageLoader.Initialize(); Updater updater = new Updater(""); Portable portable = new Portable(); SettingWindowViewModel settingsVm = new SettingWindowViewModel(updater, portable); Settings settings = settingsVm.Settings; Alphabet alphabet = new Alphabet(); alphabet.Initialize(settings); StringMatcher stringMatcher = new StringMatcher(alphabet); StringMatcher.Instance = stringMatcher; stringMatcher.UserSettingSearchPrecision = settings.QuerySearchPrecision; PluginManager.LoadPlugins(settings.PluginSettings); MainViewModel mainVm = new MainViewModel(settings, false); PublicAPIInstance api = new PublicAPIInstance(settingsVm, mainVm, alphabet); PluginManager.InitializePlugins(api); Query query = QueryBuilder.Build(QueryText.Trim(), PluginManager.NonGlobalPlugins); List<PluginPair> plugins = PluginManager.ValidPluginsForQuery(query); var results = plugins.SelectMany( p => PluginManager.QueryForPlugin(p, query) ) .OrderByDescending(r => r.Score) .Take(settings.MaxResultsToShow) // check title within the first page .Any(r => r.Title == ResultTitle); } } }
mit
C#
93c7c3064831000dd709ab3f5e12a9569021f44e
Fix resharper warnings.
mattgray/SevenDigital.Api.Wrapper,bnathyuw/SevenDigital.Api.Wrapper,minkaotic/SevenDigital.Api.Wrapper,knocte/SevenDigital.Api.Wrapper,raoulmillais/SevenDigital.Api.Wrapper,actionshrimp/SevenDigital.Api.Wrapper,danbadge/SevenDigital.Api.Wrapper,bettiolo/SevenDigital.Api.Wrapper,emashliles/SevenDigital.Api.Wrapper,AnthonySteele/SevenDigital.Api.Wrapper,danhaller/SevenDigital.Api.Wrapper,luiseduardohdbackup/SevenDigital.Api.Wrapper,gregsochanik/SevenDigital.Api.Wrapper
src/SevenDigital.Api.Wrapper/Utility/Serialization/ApiXmlDeSerializer.cs
src/SevenDigital.Api.Wrapper/Utility/Serialization/ApiXmlDeSerializer.cs
using System; using System.Xml; using System.Xml.Linq; using SevenDigital.Api.Wrapper.Exceptions; namespace SevenDigital.Api.Wrapper.Utility.Serialization { public class ApiXmlDeSerializer<T> : IDeSerializer<T> where T : class { private readonly IDeSerializer<T> _deSerializer; public ApiXmlDeSerializer(IDeSerializer<T> deSerializer) { _deSerializer = deSerializer; } public T DeSerialize(string response) { try { var responseNode = GetResponseAsXml(response); AssertError(responseNode); var resourceNode = responseNode.FirstNode.ToString(); return _deSerializer.DeSerialize(resourceNode); } catch (Exception e) { if (e is ApiXmlException) throw; throw new ApplicationException("Internal error while deserializing response " + response, e); } } private static void AssertError(XElement response) { var status = response.Attribute("status"); string statusAttribute = status == null ? response.Name.LocalName : status.Value; if (statusAttribute == "error") throw new ApiXmlException("An error has occured in the Api, see Error property for details", response.FirstNode.ToString()); } private static XElement GetResponseAsXml(string output) { XDocument xml; try { xml = XDocument.Parse(output); } catch (XmlException) { string errorXml = string.Format("<?xml version=\"1.0\" encoding=\"utf-8\" ?><response status=\"error\" version=\"1.2\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"http://api.7digital.com/1.2/static/7digitalAPI.xsd\" ><error code=\"9001\"><errorMessage>{0}</errorMessage></error></response>", output); xml = XDocument.Parse(errorXml); } return xml.Element("response"); } } }
using System; using System.IO; using System.Xml; using System.Xml.Linq; using System.Xml.Serialization; using SevenDigital.Api.Wrapper.Exceptions; namespace SevenDigital.Api.Wrapper.Utility.Serialization { public class ApiXmlDeSerializer<T> : IDeSerializer<T> where T : class { private readonly IDeSerializer<T> _deSerializer; public ApiXmlDeSerializer(IDeSerializer<T> deSerializer) { _deSerializer = deSerializer; } public T DeSerialize(string response) { try { var responseNode = GetResponseAsXml(response); AssertError(responseNode); var resourceNode = responseNode.FirstNode.ToString(); return _deSerializer.DeSerialize(resourceNode); } catch (Exception e) { if (e is ApiXmlException) throw; throw new ApplicationException("Internal error while deserializing response " + response, e); } } private static void AssertError(XElement response) { var status = response.Attribute("status"); string statusAttribute = status == null ? response.Name.LocalName : status.Value; if (statusAttribute == "error") throw new ApiXmlException("An error has occured in the Api, see Error property for details", response.FirstNode.ToString()); } private static XElement GetResponseAsXml(string output) { var xml = new XDocument(); try { xml = XDocument.Parse(output); } catch (XmlException) { string errorXml = string.Format("<?xml version=\"1.0\" encoding=\"utf-8\" ?><response status=\"error\" version=\"1.2\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"http://api.7digital.com/1.2/static/7digitalAPI.xsd\" ><error code=\"9001\"><errorMessage>{0}</errorMessage></error></response>", output); xml = XDocument.Parse(errorXml); } return xml.Element("response"); } } }
mit
C#
e1644df06fa601074691b17e85d448820a5fde82
Use context methods that explicitly work with keys instead of generic services.
mthamil/Autofac.Extras.Alternatives
Autofac.Extras.Alternatives/KeyedServiceDictionary.cs
Autofac.Extras.Alternatives/KeyedServiceDictionary.cs
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using Autofac.Core; namespace Autofac.Extras.Alternatives { internal class KeyedServiceDictionary<TKey, TValue> : IReadOnlyDictionary<TKey, TValue> { private readonly IComponentContext _context; public KeyedServiceDictionary(IComponentContext context) { if (context == null) throw new ArgumentNullException(nameof(context)); _context = context; } public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { foreach (var service in GetServices()) { yield return new KeyValuePair<TKey, TValue>( (TKey)service.ServiceKey, (TValue)_context.ResolveService(service)); } } IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); public int Count => GetServices().Count(); public bool ContainsKey(TKey key) => _context.IsRegisteredWithKey<TValue>(key); public bool TryGetValue(TKey key, out TValue value) { object instance; if (_context.TryResolveKeyed(key, typeof(TValue), out instance)) { value = (TValue)instance; return true; } value = default(TValue); return false; } public TValue this[TKey key] => _context.ResolveKeyed<TValue>(key); public IEnumerable<TKey> Keys => GetServices().Select(s => s.ServiceKey).Cast<TKey>(); public IEnumerable<TValue> Values => this.Select(kvp => kvp.Value); private IEnumerable<KeyedService> GetServices() { return ( from r in _context.ComponentRegistry.Registrations from s in r.Services.OfType<KeyedService>() where s.ServiceKey is TKey && s.ServiceType == typeof(TValue) select s).ToArray(); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using Autofac.Core; namespace Autofac.Extras.Alternatives { internal class KeyedServiceDictionary<TKey, TValue> : IReadOnlyDictionary<TKey, TValue> { private readonly IComponentContext _context; public KeyedServiceDictionary(IComponentContext context) { if (context == null) throw new ArgumentNullException(nameof(context)); _context = context; } public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { foreach (var service in GetServices()) { yield return new KeyValuePair<TKey, TValue>( (TKey)service.ServiceKey, (TValue)_context.ResolveService(service)); } } IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); public int Count => GetServices().Count(); public bool ContainsKey(TKey key) => _context.IsRegisteredService(GetService(key)); public bool TryGetValue(TKey key, out TValue value) { object instance; if (_context.TryResolveService(GetService(key), out instance)) { value = (TValue)instance; return true; } value = default(TValue); return false; } public TValue this[TKey key] => (TValue)_context.ResolveService(GetService(key)); public IEnumerable<TKey> Keys => GetServices().Select(s => s.ServiceKey).Cast<TKey>(); public IEnumerable<TValue> Values => this.Select(kvp => kvp.Value); private IEnumerable<KeyedService> GetServices() { return ( from r in _context.ComponentRegistry.Registrations from s in r.Services.OfType<KeyedService>() where s.ServiceKey is TKey && s.ServiceType == typeof(TValue) select s).ToArray(); } private static KeyedService GetService(TKey key) => new KeyedService(key, typeof(TValue)); } }
apache-2.0
C#
8416a38cc2ad88db712e5afe9a3686cf23eed2ff
Refactor LocalServiceTest and add a synchronous test
GoogleCloudPlatform/grpc-gcp-csharp,GoogleCloudPlatform/grpc-gcp-csharp
Grpc.Gcp/Grpc.Gcp.IntegrationTest/LocalServiceTest.cs
Grpc.Gcp/Grpc.Gcp.IntegrationTest/LocalServiceTest.cs
using Grpc.Core; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Grpc.Gcp.IntegrationTest { [TestClass] public class LocalServiceTest { [TestMethod] public async Task ExceptionPropagation() { await RunWithServer( new ThrowingService(), null, async (invoker, client) => await Assert.ThrowsExceptionAsync<RpcException>(async () => await client.DoSimpleAsync(new SimpleRequest())), (invoker, client) => Assert.ThrowsException<RpcException>(() => client.DoSimple(new SimpleRequest()))); } /// <summary> /// Starts up a service, creates a call invoker and a client, using an optional API config, /// then executes the asynchronous and/or synchronous test methods provided. /// </summary> private static async Task RunWithServer( TestService.TestServiceBase serviceImpl, ApiConfig apiConfig, Func<GcpCallInvoker, TestService.TestServiceClient, Task> asyncTestAction, Action<GcpCallInvoker, TestService.TestServiceClient> testAction) { var server = new Server { Services = { TestService.BindService(serviceImpl) }, Ports = { new ServerPort("localhost", 0, ServerCredentials.Insecure) } }; server.Start(); try { var port = server.Ports.First(); var options = new List<ChannelOption>(); if (apiConfig != null) { options.Add(new ChannelOption(GcpCallInvoker.ApiConfigChannelArg, apiConfig.ToString())); } var invoker = new GcpCallInvoker(port.Host, port.BoundPort, ChannelCredentials.Insecure, options); var client = new TestService.TestServiceClient(invoker); await (asyncTestAction?.Invoke(invoker, client) ?? Task.FromResult(0)); testAction?.Invoke(invoker, client); } finally { await server.ShutdownAsync(); } } private class ThrowingService : TestService.TestServiceBase { #pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously public override async Task<SimpleResponse> DoSimple(SimpleRequest request, ServerCallContext context) #pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously { throw new Exception("Bang"); } } } }
using Grpc.Core; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Linq; using System.Threading.Tasks; namespace Grpc.Gcp.IntegrationTest { [TestClass] public class LocalServiceTest { [TestMethod] public async Task ExceptionPropagation() { var server = new Server { Services = { TestService.BindService(new ThrowingService()) }, Ports = { new ServerPort("localhost", 0, ServerCredentials.Insecure) } }; server.Start(); try { var port = server.Ports.First(); var invoker = new GcpCallInvoker(port.Host, port.BoundPort, ChannelCredentials.Insecure); var client = new TestService.TestServiceClient(invoker); await Assert.ThrowsExceptionAsync<RpcException>(async () => await client.DoSimpleAsync(new SimpleRequest())); } finally { await server.ShutdownAsync(); } } private class ThrowingService : TestService.TestServiceBase { #pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously public override async Task<SimpleResponse> DoSimple(SimpleRequest request, ServerCallContext context) #pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously { throw new Exception("Bang"); } } } }
apache-2.0
C#
731e689f2da41dcaa040b5dde209f02b1306754d
Add summary tags to the doc comments
ppy/osu,peppy/osu-new,peppy/osu,NeoAdonis/osu,UselessToucan/osu,UselessToucan/osu,peppy/osu,UselessToucan/osu,ppy/osu,smoogipoo/osu,ppy/osu,smoogipoo/osu,NeoAdonis/osu,peppy/osu,smoogipooo/osu,NeoAdonis/osu,smoogipoo/osu
osu.Game/Utils/StatelessRNG.cs
osu.Game/Utils/StatelessRNG.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. namespace osu.Game.Utils { /// <summary> /// Provides a fast stateless function that can be used in randomly-looking visual elements. /// </summary> public static class StatelessRNG { private static ulong mix(ulong x) { unchecked { x ^= x >> 33; x *= 0xff51afd7ed558ccd; x ^= x >> 33; x *= 0xc4ceb9fe1a85ec53; x ^= x >> 33; return x; } } /// <summary> /// Compute an integer from given seed and series number. /// </summary> /// <param name="seed"> /// The seed value of this random number generator. /// </param> /// <param name="series"> /// The series number. /// Different values are computed for the same seed in different series. /// </param> public static ulong Get(int seed, int series = 0) => unchecked(mix(((ulong)(uint)series << 32) | ((uint)seed ^ 0x12345678))); /// <summary> /// Compute a floating point value between 0 and 1 (excluding 1) from given seed and series number. /// </summary> /// <param name="seed"> /// The seed value of this random number generator. /// </param> /// <param name="series"> /// The series number. /// Different values are computed for the same seed in different series. /// </param> public static float GetSingle(int seed, int series = 0) => (float)(Get(seed, series) & ((1 << 24) - 1)) / (1 << 24); // float has 24-bit precision } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. namespace osu.Game.Utils { /// Provides a fast stateless function that can be used in randomly-looking visual elements. public static class StatelessRNG { private static ulong mix(ulong x) { unchecked { x ^= x >> 33; x *= 0xff51afd7ed558ccd; x ^= x >> 33; x *= 0xc4ceb9fe1a85ec53; x ^= x >> 33; return x; } } /// Compute an integer from given seed and series number. /// <param name="seed"> /// The seed value of this random number generator. /// </param> /// <param name="series"> /// The series number. /// Different values are computed for the same seed in different series. /// </param> public static ulong Get(int seed, int series = 0) => unchecked(mix(((ulong)(uint)series << 32) | ((uint)seed ^ 0x12345678))); /// Compute a floating point value between 0 and 1 (excluding 1) from given seed and series number. /// <param name="seed"> /// The seed value of this random number generator. /// </param> /// <param name="series"> /// The series number. /// Different values are computed for the same seed in different series. /// </param> public static float GetSingle(int seed, int series = 0) => (float)(Get(seed, series) & ((1 << 24) - 1)) / (1 << 24); // float has 24-bit precision } }
mit
C#
20604fb6256766757b940eb73d08d0f5cf080c15
Remove unused code
takenet/blip-sdk-csharp
src/Take.Blip.Builder/StorageManager.cs
src/Take.Blip.Builder/StorageManager.cs
using System; using System.Threading; using System.Threading.Tasks; using Lime.Protocol; using Take.Blip.Builder.Hosting; using Take.Blip.Client.Extensions.Bucket; namespace Take.Blip.Builder { public class StorageManager : IStorageManager { private const string STATE_ID_KEY = "stateId"; private readonly IBucketExtension _bucketExtension; private readonly IConfiguration _configuration; public StorageManager(IBucketExtension bucketExtension, IConfiguration configuration) { _bucketExtension = bucketExtension; _configuration = configuration; } public Task<string> GetStateIdAsync(string flowId, Identity user, CancellationToken cancellationToken) => _bucketExtension.GetAsync(BucketIdHelper.GetPrivateId(flowId, user, STATE_ID_KEY), cancellationToken); public Task SetStateIdAsync(string flowId, Identity user, string stateId, CancellationToken cancellationToken) => _bucketExtension.SetAsync(BucketIdHelper.GetPrivateId(flowId, user, STATE_ID_KEY), stateId, cancellationToken, _configuration.SessionExpiration); public Task DeleteStateIdAsync(string flowId, Identity user, CancellationToken cancellationToken) => _bucketExtension.DeleteAsync(BucketIdHelper.GetPrivateId(flowId, user, STATE_ID_KEY), cancellationToken); } }
using System; using System.Threading; using System.Threading.Tasks; using Lime.Protocol; using Take.Blip.Builder.Hosting; using Take.Blip.Client.Extensions.Bucket; namespace Take.Blip.Builder { public class StorageManager : IStorageManager { private const string STATE_ID_KEY = "stateId"; private const string ACTION_ID_KEY = "actionId"; private readonly IBucketExtension _bucketExtension; private readonly IConfiguration _configuration; public StorageManager(IBucketExtension bucketExtension, IConfiguration configuration) { _bucketExtension = bucketExtension; _configuration = configuration; } public Task<string> GetStateIdAsync(string flowId, Identity user, CancellationToken cancellationToken) => _bucketExtension.GetAsync(BucketIdHelper.GetPrivateId(flowId, user, STATE_ID_KEY), cancellationToken); public Task SetStateIdAsync(string flowId, Identity user, string stateId, CancellationToken cancellationToken) => _bucketExtension.SetAsync(BucketIdHelper.GetPrivateId(flowId, user, STATE_ID_KEY), stateId, cancellationToken, _configuration.SessionExpiration); public Task DeleteStateIdAsync(string flowId, Identity user, CancellationToken cancellationToken) => _bucketExtension.DeleteAsync(BucketIdHelper.GetPrivateId(flowId, user, STATE_ID_KEY), cancellationToken); public Task<string> GetActionIdAsync(string flowId, Identity user, CancellationToken cancellationToken) => _bucketExtension.GetAsync(BucketIdHelper.GetPrivateId(flowId, user, ACTION_ID_KEY), cancellationToken); } }
apache-2.0
C#
67942c96bdd5267d0adf7a5cc7a675c25c75fb49
Update info
WhitefangGreytail/WG_RealisticCitySkylines
WG_BalancePopMod/Code/info.cs
WG_BalancePopMod/Code/info.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using ICities; using UnityEngine; namespace WG_BalancedPopMod { public class PopBalanceMod : IUserMod { public string Name { get { return "WG Realistic Population v7.9"; } } public string Description { get { return "Related population to volume and utility needs are changed to be more realistic."; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using ICities; using UnityEngine; namespace WG_BalancedPopMod { public class PopBalanceMod : IUserMod { public string Name { get { return "WG Realistic Population v7.9 beta"; } } public string Description { get { return "Related population to volume and utility needs are changed to be more realistic."; } } } }
apache-2.0
C#
33fb6af7e624ff99462b8eea577940a5c6e891fb
Fix UWP VirtualAlloc import (dotnet/corert#6882)
wtgodbe/coreclr,wtgodbe/coreclr,wtgodbe/coreclr,mmitche/coreclr,cshung/coreclr,cshung/coreclr,poizan42/coreclr,krk/coreclr,cshung/coreclr,wtgodbe/coreclr,poizan42/coreclr,mmitche/coreclr,mmitche/coreclr,mmitche/coreclr,poizan42/coreclr,krk/coreclr,krk/coreclr,krk/coreclr,mmitche/coreclr,cshung/coreclr,krk/coreclr,wtgodbe/coreclr,poizan42/coreclr,poizan42/coreclr,cshung/coreclr,krk/coreclr,cshung/coreclr,mmitche/coreclr,poizan42/coreclr,wtgodbe/coreclr
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.VirtualAlloc.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.VirtualAlloc.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.InteropServices; internal partial class Interop { internal partial class Kernel32 { internal const int MEM_COMMIT = 0x1000; internal const int MEM_RESERVE = 0x2000; internal const int MEM_RELEASE = 0x8000; internal const int MEM_FREE = 0x10000; internal const int PAGE_READWRITE = 0x04; #if ENABLE_WINRT [DllImport("api-ms-win-core-memory-l1-1-3.dll", EntryPoint = "VirtualAllocFromApp")] internal static extern unsafe void* VirtualAlloc(void* BaseAddress, UIntPtr Size, int AllocationType, int Protection); #else [DllImport(Libraries.Kernel32)] internal static extern unsafe void* VirtualAlloc(void* lpAddress, UIntPtr dwSize, int flAllocationType, int flProtect); #endif } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.InteropServices; internal partial class Interop { internal partial class Kernel32 { internal const int MEM_COMMIT = 0x1000; internal const int MEM_RESERVE = 0x2000; internal const int MEM_RELEASE = 0x8000; internal const int MEM_FREE = 0x10000; internal const int PAGE_READWRITE = 0x04; #if ENABLE_WINRT [DllImport(Libraries.Kernel32, EntryPoint = "VirtualAllocFromApp")] internal static extern unsafe void* VirtualAlloc(void* BaseAddress, UIntPtr Size, int AllocationType, int Protection); #else [DllImport(Libraries.Kernel32)] internal static extern unsafe void* VirtualAlloc(void* lpAddress, UIntPtr dwSize, int flAllocationType, int flProtect); #endif } }
mit
C#
7af439f8fe313d00bcf580d4dc44ba49b8bc3212
Use better legacy syntax
brycekbargar/Nilgiri,brycekbargar/Nilgiri
Nilgiri/Expect.cs
Nilgiri/Expect.cs
namespace Nilgiri { using System; using Nilgiri.Core; using Nilgiri.Core.DependencyInjection; public static class ExpectStyle { public static IToableAssertionManager<T> Expect<T>(T testValue) { return new AssertionManager<T>(new AssertionState<T>(() => testValue), new AsserterFactory()); } } } namespace Nilgiri.LegacyExpectStyle { using System; using Nilgiri.Core; public static class E { public static IToableAssertionManager<T> xpect<T>(T testValue) { return ExpectStyle.Expect(testValue); } } }
namespace Nilgiri { using System; using Nilgiri.Core; using Nilgiri.Core.DependencyInjection; public static class ExpectStyle { public static IToableAssertionManager<T> Expect<T>(T testValue) { return new AssertionManager<T>(new AssertionState<T>(() => testValue), new AsserterFactory()); } } } namespace Nilgiri.LegacyExpectStyle { using System; using Nilgiri.Core; public static class _ { public static IToableAssertionManager<T> Expect<T>(T testValue) { return ExpectStyle.Expect(testValue); } } }
mit
C#
e3f8bc05883e126e176d6b12e54e0df39c85003a
Revert `Availability` to `private`
NeoAdonis/osu,NeoAdonis/osu,peppy/osu,NeoAdonis/osu,ppy/osu,peppy/osu,ppy/osu,ppy/osu,peppy/osu
osu.Game/Screens/OnlinePlay/Components/ReadyButton.cs
osu.Game/Screens/OnlinePlay/Components/ReadyButton.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics.Cursor; using osu.Framework.Localisation; using osu.Game.Graphics.UserInterface; using osu.Game.Online; using osu.Game.Online.Rooms; namespace osu.Game.Screens.OnlinePlay.Components { public abstract class ReadyButton : TriangleButton, IHasTooltip { public new readonly BindableBool Enabled = new BindableBool(); private readonly IBindable<BeatmapAvailability> availability = new Bindable<BeatmapAvailability>(); [BackgroundDependencyLoader] private void load(OnlinePlayBeatmapAvailabilityTracker beatmapTracker) { availability.BindTo(beatmapTracker.Availability); availability.BindValueChanged(_ => updateState()); Enabled.BindValueChanged(_ => updateState(), true); } private void updateState() => base.Enabled.Value = availability.Value.State == DownloadState.LocallyAvailable && Enabled.Value; public virtual LocalisableString TooltipText { get { if (Enabled.Value) return string.Empty; if (availability.Value.State != DownloadState.LocallyAvailable) return "Beatmap not downloaded"; return string.Empty; } } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics.Cursor; using osu.Framework.Localisation; using osu.Game.Graphics.UserInterface; using osu.Game.Online; using osu.Game.Online.Rooms; namespace osu.Game.Screens.OnlinePlay.Components { public abstract class ReadyButton : TriangleButton, IHasTooltip { public new readonly BindableBool Enabled = new BindableBool(); protected readonly IBindable<BeatmapAvailability> Availability = new Bindable<BeatmapAvailability>(); [BackgroundDependencyLoader] private void load(OnlinePlayBeatmapAvailabilityTracker beatmapTracker) { Availability.BindTo(beatmapTracker.Availability); Availability.BindValueChanged(_ => updateState()); Enabled.BindValueChanged(_ => updateState(), true); } private void updateState() => base.Enabled.Value = Availability.Value.State == DownloadState.LocallyAvailable && Enabled.Value; public virtual LocalisableString TooltipText { get { if (Enabled.Value) return string.Empty; if (Availability.Value.State != DownloadState.LocallyAvailable) return "Beatmap not downloaded"; return string.Empty; } } } }
mit
C#
e1a436f815f5bfd6feee747d415046a611a731b9
Update Viktor.cs
FireBuddy/adevade
AdEvade/AdEvade/Data/Spells/SpecialSpells/Viktor.cs
AdEvade/AdEvade/Data/Spells/SpecialSpells/Viktor.cs
using System; using EloBuddy; using EloBuddy.SDK; namespace AdEvade.Data.Spells.SpecialSpells { class Viktor : IChampionPlugin { static Viktor() { } public const string ChampionName = "Viktor"; public string GetChampionName() { return ChampionName; } public void LoadSpecialSpell(SpellData spellData) { if (spellData.SpellName == "ViktorDeathRay") { Obj_AI_Base.OnProcessSpellCast += Obj_AI_Base_OnProcessSpellCast3; } } private static void Obj_AI_Base_OnProcessSpellCast3(Obj_AI_Base sender, GameObjectProcessSpellCastEventArgs args) { if (sender != null && sender.Team != ObjectManager.Player.Team && args.SData.Name != null && args.SData.Name == "ViktorDeathRay") { var endpoint = sender.Path; // var missileDist = End.To2D().Distance(args.Start.To2D()); // var delay = missileDist / 1.5f + 600; // spellData.SpellDelay = delay; // SpellDetector.CreateSpellData(sender, args.Start, End, spellData); } } } }
using System; using EloBuddy; using EloBuddy.SDK; namespace AdEvade.Data.Spells.SpecialSpells { class Viktor : IChampionPlugin { static Viktor() { } public const string ChampionName = "Viktor"; public string GetChampionName() { return ChampionName; } public void LoadSpecialSpell(SpellData spellData) { if (spellData.SpellName == "ViktorDeathRay") { Obj_AI_Base.OnProcessSpellCast += Obj_AI_Base_OnProcessSpellCast3; } } private static void Obj_AI_Base_OnProcessSpellCast3(Obj_AI_Base sender, GameObjectProcessSpellCastEventArgs args) { if (sender != null && sender.Team != ObjectManager.Player.Team && args.SData.Name != null && args.SData.Name == "ViktorDeathRay") { var endpoint = sender.Path.Last(); // var missileDist = End.To2D().Distance(args.Start.To2D()); // var delay = missileDist / 1.5f + 600; // spellData.SpellDelay = delay; // SpellDetector.CreateSpellData(sender, args.Start, End, spellData); } } } }
mit
C#
1992949a144cd887bba2035dd500ce5d4fa2b223
Test fix
victoria92/university-program-generator,victoria92/university-program-generator
UnitTests/UnitTest1.cs
UnitTests/UnitTest1.cs
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Collections.Generic; using UniProgramGen.Data; using UniProgramGen.Helpers; namespace UnitTests { [TestClass] public class UnitTest1 { [TestMethod] public void initalizeExampleData() { var organic_room_types = new List<RoomType>(); organic_room_types.Add(RoomType.Projector); organic_room_types.Add(RoomType.Komin); var available_timeslot = new TimeSlot(DayOfWeek.Monday, 9, 22); var available_timeslots = new List<TimeSlot>(); available_timeslots.Add(available_timeslot); var room = new Room(organic_room_types, 150, available_timeslots, "ХФ210"); var rooms = new List<Room>(); rooms.Add(room); var organic_chemistry_room_requirements = new Requirements(10, available_timeslots, rooms); var organich_chemistry_teacher = new Teacher(organic_chemistry_room_requirements, "Prof. Hristo Hristov"); var organic_chemistry_teachers = new List<Teacher>(); var s = new Subject(organic_room_types, organic_chemistry_teachers, "Organic Chemistry Lectures", 1); } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Collections.Generic; using UniProgramGen.Data; using UniProgramGen.Helpers; namespace UnitTests { [TestClass] public class UnitTest1 { [TestMethod] public void initalizeExampleData() { var organic_room_types = new List<RoomType>(); organic_room_types.Add(RoomType.Projector); organic_room_types.Add(RoomType.Komin); var available_timeslot = new TimeSlot(DayOfWeek.Monday, 9, 22); var available_timeslots = new List<TimeSlot>(); available_timeslots.Add(available_timeslot); var room = new Room(organic_room_types, 150, available_timeslots, "ХФ210"); var rooms = new List<Room>(); rooms.Add(room); var organic_chemistry_room_requirements = new Requirements(10, available_timeslots, rooms); var organich_chemistry_teacher = new Teacher(organic_chemistry_room_requirements, "Prof. Hristo Hristov"); var organic_chemistry_teachers = new List<Teacher>(); var s = new Subject(organic_room_types, organic_chemistry_teachers, "", 1); } } }
bsd-2-clause
C#