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
e905b9a94741faf6d08e7664e25dbb574ad608f7
clean up code
IvanZheng/IFramework,IvanZheng/IFramework,IvanZheng/IFramework
Src/iFramework/Infrastructure/UniqueConstrainExceptionParser.cs
Src/iFramework/Infrastructure/UniqueConstrainExceptionParser.cs
using System; using System.Data.Common; using System.Linq; namespace IFramework.Infrastructure { public class UniqueConstrainExceptionParser : IUniqueConstrainExceptionParser { public bool IsUniqueConstrainException(Exception exception, string[] uniqueConstrainNames) { var needRetry = false; if (uniqueConstrainNames?.Length > 0 && exception.GetBaseException() is DbException dbException) { var number = dbException.GetPropertyValue<int>("Number"); needRetry = ( number == 1062 && dbException.Source.Contains("MySql") || (number == 2601 || number == 2627 || number == 547) && dbException.Source.Contains("SqlClient") || number == 23505 && dbException.Source.Contains("Npgsql") ) && uniqueConstrainNames.Any(dbException.Message.Contains); } return needRetry; } } }
using System; using System.Collections.Generic; using System.Data.Common; using System.Linq; using System.Text; namespace IFramework.Infrastructure { public class UniqueConstrainExceptionParser: IUniqueConstrainExceptionParser { public bool IsUniqueConstrainException(Exception exception, string[] uniqueConstrainNames) { var needRetry = false; if (uniqueConstrainNames?.Length > 0 && exception.GetBaseException() is DbException dbException) { var number = dbException.GetPropertyValue<int>("Number"); needRetry = (dbException.Source.Contains("MySql") && number == 1062 || dbException.Source.Contains("SqlClient") && (number == 2601 || number == 2627 || number == 547) || dbException.Source.Contains("Npgsql") && number == 23505) && uniqueConstrainNames.Any(dbException.Message.Contains); } return needRetry; } } }
mit
C#
82e136549e9f04ec88718f505af6de580d7c71cd
Fix for Issue #1.
thegoldenmule/UnityInEnglish
MonoBehavior.cs
MonoBehavior.cs
namespace UnityEngine { public class MonoBehavior : MonoBehaviour { // proper English codes } }
public class MonoBehavior : UnityEngine.MonoBehaviour { // proper English }
mit
C#
03c5e7653b23fb43244be68086d360e62c626708
Add one more discovery test
siyo-wang/IdentityServer4,MienDev/IdentityServer4,IdentityServer/IdentityServer4,jbijlsma/IdentityServer4,jbijlsma/IdentityServer4,jbijlsma/IdentityServer4,MienDev/IdentityServer4,IdentityServer/IdentityServer4,chrisowhite/IdentityServer4,siyo-wang/IdentityServer4,siyo-wang/IdentityServer4,chrisowhite/IdentityServer4,chrisowhite/IdentityServer4,jbijlsma/IdentityServer4,MienDev/IdentityServer4,IdentityServer/IdentityServer4,IdentityServer/IdentityServer4,MienDev/IdentityServer4
test/IdentityServer.IntegrationTests/Clients/DiscoveryClient.cs
test/IdentityServer.IntegrationTests/Clients/DiscoveryClient.cs
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using FluentAssertions; using IdentityModel.Client; using IdentityServer4.IntegrationTests.Clients; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using Xunit; namespace IdentityServer.IntegrationTests.Clients { public class DiscoveryClientTests { const string DiscoveryEndpoint = "https://server/.well-known/openid-configuration"; private readonly HttpClient _client; private readonly HttpMessageHandler _handler; public DiscoveryClientTests() { var builder = new WebHostBuilder() .UseStartup<Startup>(); var server = new TestServer(builder); _handler = server.CreateHandler(); _client = server.CreateClient(); } [Fact] public async Task Retrieving_discovery_document_should_succeed() { var client = new DiscoveryClient(DiscoveryEndpoint, _handler); var doc = await client.GetAsync(); } [Fact] public async Task Discovery_document_should_have_expected_values() { var client = new DiscoveryClient(DiscoveryEndpoint, _handler); var doc = await client.GetAsync(); // endpoints doc.TokenEndpoint.Should().Be("https://server/connect/token"); doc.AuthorizationEndpoint.Should().Be("https://server/connect/authorize"); doc.IntrospectionEndpoint.Should().Be("https://server/connect/introspect"); doc.EndSessionEndpoint.Should().Be("https://server/connect/endsession"); // jwk doc.Keys.Keys.Count.Should().Be(1); doc.Keys.Keys.First().E.Should().NotBeNull(); doc.Keys.Keys.First().N.Should().NotBeNull(); } } }
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using IdentityModel.Client; using IdentityServer4.IntegrationTests.Clients; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; using System.Net.Http; using System.Threading.Tasks; using Xunit; namespace IdentityServer.IntegrationTests.Clients { public class DiscoveryClientTests { const string DiscoveryEndpoint = "https://server/.well-known/openid-configuration"; private readonly HttpClient _client; private readonly HttpMessageHandler _handler; public DiscoveryClientTests() { var builder = new WebHostBuilder() .UseStartup<Startup>(); var server = new TestServer(builder); _handler = server.CreateHandler(); _client = server.CreateClient(); } [Fact] public async Task Retrieving_discovery_document_should_succeed() { var client = new DiscoveryClient(DiscoveryEndpoint, _handler); var doc = await client.GetAsync(); } } }
apache-2.0
C#
5a8692ad6690e3ba842e79d63802928cf7ac49c7
Bump version to 1.1
mhutch/MonoDevelop.AddinMaker,mhutch/MonoDevelop.AddinMaker
Properties/AddinInfo.cs
Properties/AddinInfo.cs
using System; using Mono.Addins; using Mono.Addins.Description; [assembly:Addin ( "AddinMaker", Namespace = "MonoDevelop", Version = "1.1.0", Url = "http://github.com/mhutch/MonoDevelop.AddinMaker" )] [assembly:AddinName ("Addin Maker")] [assembly:AddinCategory ("Addin Development")] [assembly:AddinDescription ("Makes it easy to create and edit addins")] [assembly:AddinAuthor ("Michael Hutchinson")]
using System; using Mono.Addins; using Mono.Addins.Description; [assembly:Addin ( "AddinMaker", Namespace = "MonoDevelop", Version = "1.0.1", Url = "http://github.com/mhutch/MonoDevelop.AddinMaker" )] [assembly:AddinName ("Addin Maker")] [assembly:AddinCategory ("Addin Development")] [assembly:AddinDescription ("Makes it easy to create and edit addins")] [assembly:AddinAuthor ("Michael Hutchinson")]
mit
C#
69882b39f9181bdfb84159ec93b37cffa7b0a9d4
Remove unused import.
sshnet/SSH.NET
src/Renci.SshNet.Tests/Classes/Messages/Transport/KeyExchangeDhGroupExchangeReplyBuilder.cs
src/Renci.SshNet.Tests/Classes/Messages/Transport/KeyExchangeDhGroupExchangeReplyBuilder.cs
using System.Text; using Renci.SshNet.Common; using Renci.SshNet.Messages.Transport; namespace Renci.SshNet.Tests.Classes.Messages.Transport { public class KeyExchangeDhGroupExchangeReplyBuilder { private byte[] _hostKeyAlgorithm; private byte[] _hostKeys; private BigInteger _f; private byte[] _signature; public KeyExchangeDhGroupExchangeReplyBuilder WithHostKey(string hostKeyAlgorithm, params BigInteger[] hostKeys) { _hostKeyAlgorithm = Encoding.UTF8.GetBytes(hostKeyAlgorithm); var sshDataStream = new SshDataStream(0); foreach (var hostKey in hostKeys) sshDataStream.Write(hostKey); _hostKeys = sshDataStream.ToArray(); return this; } public KeyExchangeDhGroupExchangeReplyBuilder WithF(BigInteger f) { _f = f; return this; } public KeyExchangeDhGroupExchangeReplyBuilder WithSignature(byte[] signature) { _signature = signature; return this; } public byte[] Build() { var sshDataStream = new SshDataStream(0); sshDataStream.WriteByte(KeyExchangeDhGroupExchangeReply.MessageNumber); sshDataStream.Write((uint)(4 + _hostKeyAlgorithm.Length + _hostKeys.Length)); sshDataStream.Write((uint) _hostKeyAlgorithm.Length); sshDataStream.Write(_hostKeyAlgorithm, 0, _hostKeyAlgorithm.Length); sshDataStream.Write(_hostKeys, 0, _hostKeys.Length); sshDataStream.Write(_f); sshDataStream.WriteBinary(_signature); return sshDataStream.ToArray(); } } }
using System.Collections.Generic; using System.Text; using Renci.SshNet.Common; using Renci.SshNet.Messages.Transport; namespace Renci.SshNet.Tests.Classes.Messages.Transport { public class KeyExchangeDhGroupExchangeReplyBuilder { private byte[] _hostKeyAlgorithm; private byte[] _hostKeys; private BigInteger _f; private byte[] _signature; public KeyExchangeDhGroupExchangeReplyBuilder WithHostKey(string hostKeyAlgorithm, params BigInteger[] hostKeys) { _hostKeyAlgorithm = Encoding.UTF8.GetBytes(hostKeyAlgorithm); var sshDataStream = new SshDataStream(0); foreach (var hostKey in hostKeys) sshDataStream.Write(hostKey); _hostKeys = sshDataStream.ToArray(); return this; } public KeyExchangeDhGroupExchangeReplyBuilder WithF(BigInteger f) { _f = f; return this; } public KeyExchangeDhGroupExchangeReplyBuilder WithSignature(byte[] signature) { _signature = signature; return this; } public byte[] Build() { var sshDataStream = new SshDataStream(0); sshDataStream.WriteByte(KeyExchangeDhGroupExchangeReply.MessageNumber); sshDataStream.Write((uint)(4 + _hostKeyAlgorithm.Length + _hostKeys.Length)); sshDataStream.Write((uint) _hostKeyAlgorithm.Length); sshDataStream.Write(_hostKeyAlgorithm, 0, _hostKeyAlgorithm.Length); sshDataStream.Write(_hostKeys, 0, _hostKeys.Length); sshDataStream.Write(_f); sshDataStream.WriteBinary(_signature); return sshDataStream.ToArray(); } } }
mit
C#
32fe2d0fbc1bdd8b33eb20d99cb2e7da112bfe4c
Fix comment (spelling).
Microsoft/ApplicationInsights-SDK-Labs
AggregateMetrics/AggregateMetrics/AzureWebApp/Implementation/AzureWebEnvironmentVariables.cs
AggregateMetrics/AggregateMetrics/AzureWebApp/Implementation/AzureWebEnvironmentVariables.cs
namespace Microsoft.ApplicationInsights.Extensibility.AggregateMetrics.AzureWebApp { using System; /// <summary> /// Enum for Azure Web App environment variables. /// </summary> [Flags] public enum AzureWebApEnvironmentVariables { /// <summary> /// ASP.NET. /// </summary> AspNet = 0, /// <summary> /// Application. /// </summary> App = 1, /// <summary> /// Common Language Runtime. /// </summary> CLR = 2, /// <summary> /// All of the above. /// </summary> All = 3 }; }
namespace Microsoft.ApplicationInsights.Extensibility.AggregateMetrics.AzureWebApp { using System; /// <summary> /// Enum for Azure Web App environment variables. /// </summary> [Flags] public enum AzureWebApEnvironmentVariables { /// <summary> /// ASP.NET. /// </summary> AspNet = 0, /// <summary> /// Application. /// </summary> App = 1, /// <summary> /// Common Language Runtime. /// </summary> CLR = 2, /// <summary> /// All the above. /// </summary> All = 3 }; }
mit
C#
933c694487c96763af1c03b0160ddf427540a403
Add ":" to default suffix
Deliay/osuSync,Deliay/Sync
Sync/IRC/MessageFilter/Filters/DefaultFormat.cs
Sync/IRC/MessageFilter/Filters/DefaultFormat.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Sync.IRC.MessageFilter.Filters { class DefaultFormat : FilterBase, IDanmaku, IOsu { public override void onMsg(ref MessageBase msg) { msg.user.setPerfix("<"); msg.user.setSuffix(">: "); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Sync.IRC.MessageFilter.Filters { class DefaultFormat : FilterBase, IDanmaku, IOsu { public override void onMsg(ref MessageBase msg) { msg.user.setPerfix("<"); msg.user.setSuffix(">"); } } }
mit
C#
c360fb58b78c13db8c68ae8194c56e87e3cf784c
Update AdUnitSelectorOptions.cs
tiksn/TIKSN-Framework
TIKSN.Core/Advertising/AdUnitSelectorOptions.cs
TIKSN.Core/Advertising/AdUnitSelectorOptions.cs
namespace TIKSN.Advertising { public class AdUnitSelectorOptions { public AdUnitSelectorOptions() { this.IsDebuggerSensitive = true; this.IsDebug = false; } public bool IsDebuggerSensitive { get; set; } public bool IsDebug { get; set; } } }
namespace TIKSN.Advertising { public class AdUnitSelectorOptions { public AdUnitSelectorOptions() { IsDebuggerSensitive = true; IsDebug = false; } public bool IsDebuggerSensitive { get; set; } public bool IsDebug { get; set; } } }
mit
C#
079c4797886504deea292014f6dbbeaccd4d3bcf
Update Wiki.cs
arcaneex/hash,arcaneex/hash,arcaneex/hash,arcaneex/hash
RohBot/Commands/Wiki.cs
RohBot/Commands/Wiki.cs
namespace RohBot.Commands { public class Wiki : Command { public override string Type { get { return "wiki"; } } public override string Format(CommandTarget target, string type) { return "]"; } public override void Handle(CommandTarget target, string type, string[] parameters) { if ( !target.IsRoom || parameters.Length == 0) return; var username = target.Connection.Session.Account.Name; var room = target.Room; if (room.IsBanned(username)) { target.Send("You are banned from this room."); return; } var line = string.Format("http://glua.me/docs/#?f={0}", parameters[0]); target.Room.SendLine(line); return; } } }
namespace RohBot.Commands { public class Wiki : Command { public override string Type { get { return "wiki"; } } public override string Format(CommandTarget target, string type) { return "]"; } public override void Handle(CommandTarget target, string type, string[] parameters) { if ( !target.IsRoom || parameters.Length == 0) return; var username = target.Connection.Session.Account.Name; var room = target.Room; if (room.IsBanned(username)) { target.Send("You are banned from this room."); return; } var send = string.Format("http://glua.me/docs/#?f={0}", parameters[0]); target.Room.SendLine(line); return; } } }
mit
C#
0fbdd5eacb473a1b4e00c06da0fc465ef294161b
Fix test
EVAST9919/osu-framework,ppy/osu-framework,ppy/osu-framework,peppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework
osu.Framework.Tests/Visual/Containers/TestSceneCompositeAsync.cs
osu.Framework.Tests/Visual/Containers/TestSceneCompositeAsync.cs
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; namespace osu.Framework.Tests.Visual.Containers { public class TestSceneCompositeAsync : FrameworkTestScene { [Test] public void TestUnpublishedChildStillDisposed() { AsyncChildLoadingComposite composite = null; AddStep("Add new composite", () => { Child = composite = new AsyncChildLoadingComposite(); }); AddUntilStep("Wait for child load", () => composite.AsyncChild.LoadState == LoadState.Ready); AddStep("Dispose composite", Clear); AddUntilStep("Child was disposed", () => composite.AsyncChildDisposed); } private class AsyncChildLoadingComposite : CompositeDrawable { public Container AsyncChild { get; } = new Container(); public bool AsyncChildDisposed { get; private set; } protected override void LoadComplete() { AsyncChild.OnDispose += () => AsyncChildDisposed = true; // load but never add to hierarchy LoadComponentAsync(AsyncChild); base.LoadComplete(); } } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Framework.Graphics.Containers; namespace osu.Framework.Tests.Visual.Containers { public class TestSceneCompositeAsync : FrameworkTestScene { [SetUp] public void SetUp() => Schedule(Clear); [Test] public void TestAddToCompositeAsync() { AsyncLoadingContainer comp = null; bool disposed = false; AddStep("Add new composite", () => { disposed = false; Add(comp = new AsyncLoadingContainer()); comp.ChildContainer.OnDispose += () => disposed = true; }); AddStep("Dispose composite", () => { Remove(comp); comp.Dispose(); }); AddAssert("Is disposed", () => disposed); } private class AsyncLoadingContainer : CompositeDrawable { public Container ChildContainer { get; } = new Container(); protected override void LoadComplete() { LoadComponentAsync(ChildContainer); base.LoadComplete(); } } } }
mit
C#
8b78536a110f9470adb29d6a29e6c9135db3fee6
Change File Info repository save method, file info can now be updated.
LykkeCity/CompetitionPlatform,LykkeCity/CompetitionPlatform,LykkeCity/CompetitionPlatform
src/CompetitionPlatform/Data/AzureRepositories/Project/ProjectFileInfoRepository.cs
src/CompetitionPlatform/Data/AzureRepositories/Project/ProjectFileInfoRepository.cs
using System.Threading.Tasks; using AzureStorage.Tables; using Microsoft.WindowsAzure.Storage.Table; namespace CompetitionPlatform.Data.AzureRepositories.Project { public class ProjectFileInfoEntity : TableEntity, IProjectFileInfoData { public static string GeneratePartitionKey() { return "ProjectFileInfo"; } public static string GenerateRowKey(string projectId) { return projectId; } public string ProjectId => RowKey; public string FileName { get; set; } public string ContentType { get; set; } public static ProjectFileInfoEntity Create(IProjectFileInfoData src) { var result = new ProjectFileInfoEntity { PartitionKey = GeneratePartitionKey(), RowKey = GenerateRowKey(src.ProjectId), FileName = src.FileName, ContentType = src.ContentType }; return result; } } public class ProjectFileInfoRepository : IProjectFileInfoRepository { private readonly IAzureTableStorage<ProjectFileInfoEntity> _projectFileInfoTableStorage; public ProjectFileInfoRepository(IAzureTableStorage<ProjectFileInfoEntity> projectFileInfoTableStorage) { _projectFileInfoTableStorage = projectFileInfoTableStorage; } public async Task<IProjectFileInfoData> GetAsync(string projectId) { var partitionKey = ProjectFileInfoEntity.GeneratePartitionKey(); var rowKey = ProjectFileInfoEntity.GenerateRowKey(projectId); return await _projectFileInfoTableStorage.GetDataAsync(partitionKey, rowKey); } public async Task SaveAsync(IProjectFileInfoData fileInfoData) { var newEntity = ProjectFileInfoEntity.Create(fileInfoData); await _projectFileInfoTableStorage.InsertOrReplaceAsync(newEntity); } } }
using System.Threading.Tasks; using AzureStorage.Tables; using Microsoft.WindowsAzure.Storage.Table; namespace CompetitionPlatform.Data.AzureRepositories.Project { public class ProjectFileInfoEntity : TableEntity, IProjectFileInfoData { public static string GeneratePartitionKey() { return "ProjectFileInfo"; } public static string GenerateRowKey(string projectId) { return projectId; } public string ProjectId => RowKey; public string FileName { get; set; } public string ContentType { get; set; } public static ProjectFileInfoEntity Create(IProjectFileInfoData src) { var result = new ProjectFileInfoEntity { PartitionKey = GeneratePartitionKey(), RowKey = GenerateRowKey(src.ProjectId), FileName = src.FileName, ContentType = src.ContentType }; return result; } } public class ProjectFileInfoRepository : IProjectFileInfoRepository { private readonly IAzureTableStorage<ProjectFileInfoEntity> _projectFileInfoTableStorage; public ProjectFileInfoRepository(IAzureTableStorage<ProjectFileInfoEntity> projectFileInfoTableStorage) { _projectFileInfoTableStorage = projectFileInfoTableStorage; } public async Task<IProjectFileInfoData> GetAsync(string projectId) { var partitionKey = ProjectFileInfoEntity.GeneratePartitionKey(); var rowKey = ProjectFileInfoEntity.GenerateRowKey(projectId); return await _projectFileInfoTableStorage.GetDataAsync(partitionKey, rowKey); } public async Task SaveAsync(IProjectFileInfoData fileInfoData) { var newEntity = ProjectFileInfoEntity.Create(fileInfoData); await _projectFileInfoTableStorage.InsertAsync(newEntity); } } }
mit
C#
cbbad7c74affdbeeea2927df5246df7fb0990cb7
Change name of daabase for IoC
generik0/Smooth.IoC.Dapper.Repository.UnitOfWork,generik0/Smooth.IoC.Dapper.Repository.UnitOfWork
src/Smooth.IoC.Dapper.Repository.UnitOfWork.Tests/TestHelpers/MyDatabaseSettings.cs
src/Smooth.IoC.Dapper.Repository.UnitOfWork.Tests/TestHelpers/MyDatabaseSettings.cs
using NUnit.Framework; namespace Smooth.IoC.Dapper.FastCRUD.Repository.UnitOfWork.Tests.TestHelpers { public class MyDatabaseSettings : IMyDatabaseSettings { public string ConnectionString { get; } = $@"Data Source={TestContext.CurrentContext.TestDirectory}\IoCTests.db;Version=3;New=True;BinaryGUID=False;"; } }
using NUnit.Framework; namespace Smooth.IoC.Dapper.FastCRUD.Repository.UnitOfWork.Tests.TestHelpers { public class MyDatabaseSettings : IMyDatabaseSettings { public string ConnectionString { get; } = $@"Data Source={TestContext.CurrentContext.TestDirectory}\Tests.db;Version=3;New=True;BinaryGUID=False;"; } }
mit
C#
02853394825dde73cf0534190ee83b97468feffa
Add CancellationContext comment
PowerShell/PowerShellEditorServices
src/PowerShellEditorServices/Services/PowerShell/Utility/CancellationContext.cs
src/PowerShellEditorServices/Services/PowerShell/Utility/CancellationContext.cs
using System; using System.Collections.Concurrent; using System.Threading; namespace Microsoft.PowerShell.EditorServices.Services.PowerShell.Utility { /// <summary> /// Encapsulates the scoping logic for cancellation tokens. /// As PowerShell commands nest, this class maintains a stack of cancellation scopes /// that allow each scope of logic to be cancelled at its own level. /// Implicitly handles the merging and cleanup of cancellation token sources. /// </summary> /// <example> /// The <see cref="Microsoft.PowerShell.EditorServices.Services.PowerShell.Utility.CancellationContext"/> class /// and the <see cref="Microsoft.PowerShell.EditorServices.Services.PowerShell.Utility.CancellationScope"/> struct /// are intended to be used with a <c>using</c> block so you can do this: /// <code> /// using (CancellationScope cancellationScope = _cancellationContext.EnterScope(_globalCancellationSource.CancellationToken, localCancellationToken)) /// { /// ExecuteCommandAsync(command, cancellationScope.CancellationToken); /// } /// </code> /// </example> internal class CancellationContext { private readonly ConcurrentStack<CancellationTokenSource> _cancellationSourceStack; public CancellationContext() { _cancellationSourceStack = new ConcurrentStack<CancellationTokenSource>(); } public CancellationScope EnterScope(params CancellationToken[] linkedTokens) { return EnterScope(CancellationTokenSource.CreateLinkedTokenSource(linkedTokens)); } public CancellationScope EnterScope(CancellationToken linkedToken1, CancellationToken linkedToken2) { return EnterScope(CancellationTokenSource.CreateLinkedTokenSource(linkedToken1, linkedToken2)); } public void CancelCurrentTask() { if (_cancellationSourceStack.TryPeek(out CancellationTokenSource currentCancellationSource)) { currentCancellationSource.Cancel(); } } private CancellationScope EnterScope(CancellationTokenSource cancellationFrameSource) { _cancellationSourceStack.Push(cancellationFrameSource); return new CancellationScope(_cancellationSourceStack, cancellationFrameSource.Token); } } internal struct CancellationScope : IDisposable { private readonly ConcurrentStack<CancellationTokenSource> _cancellationStack; internal CancellationScope(ConcurrentStack<CancellationTokenSource> cancellationStack, CancellationToken currentCancellationToken) { _cancellationStack = cancellationStack; CancellationToken = currentCancellationToken; } public readonly CancellationToken CancellationToken; public void Dispose() { if (_cancellationStack.TryPop(out CancellationTokenSource contextCancellationTokenSource)) { contextCancellationTokenSource.Dispose(); } } } }
using System; using System.Collections.Concurrent; using System.Threading; namespace Microsoft.PowerShell.EditorServices.Services.PowerShell.Utility { internal class CancellationContext { private readonly ConcurrentStack<CancellationTokenSource> _cancellationSourceStack; public CancellationContext() { _cancellationSourceStack = new ConcurrentStack<CancellationTokenSource>(); } public CancellationScope EnterScope(params CancellationToken[] linkedTokens) { return EnterScope(CancellationTokenSource.CreateLinkedTokenSource(linkedTokens)); } public CancellationScope EnterScope(CancellationToken linkedToken1, CancellationToken linkedToken2) { return EnterScope(CancellationTokenSource.CreateLinkedTokenSource(linkedToken1, linkedToken2)); } public void CancelCurrentTask() { if (_cancellationSourceStack.TryPeek(out CancellationTokenSource currentCancellationSource)) { currentCancellationSource.Cancel(); } } private CancellationScope EnterScope(CancellationTokenSource cancellationFrameSource) { _cancellationSourceStack.Push(cancellationFrameSource); return new CancellationScope(_cancellationSourceStack, cancellationFrameSource.Token); } } internal struct CancellationScope : IDisposable { private readonly ConcurrentStack<CancellationTokenSource> _cancellationStack; internal CancellationScope(ConcurrentStack<CancellationTokenSource> cancellationStack, CancellationToken currentCancellationToken) { _cancellationStack = cancellationStack; CancellationToken = currentCancellationToken; } public readonly CancellationToken CancellationToken; public void Dispose() { if (_cancellationStack.TryPop(out CancellationTokenSource contextCancellationTokenSource)) { contextCancellationTokenSource.Dispose(); } } } }
mit
C#
9e7278ab028f84c0818efb84f975e1e46e98b0f6
修复一个低级Bug. :bug:
Automao/Automao.Data
src/Mapping/ProcedureNode.cs
src/Mapping/ProcedureNode.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; namespace Automao.Data.Mapping { public class ProcedureNode { #region 字段 private System.Type _entityType; private string _name; private string _procedure; private string _schema; private List<ProcedureParameterNode> _parameterList; #endregion #region 属性 public string Name { get { return _name; } } public string Procedure { get { return _procedure; } } public string Schema { get { return _schema; } } public List<ProcedureParameterNode> ParameterList { get { return _parameterList; } } /// <summary> /// 所在文件路径 /// </summary> public string MappingFileFullName { get; set; } #endregion #region 公共方法 public string GetProcedureName(bool caseSensitive) { var schema = string.IsNullOrEmpty(_schema) ? "" : (_schema + "."); var procedureName = string.Format(caseSensitive ? "{0}\"{1}\"" : "{0}{1}", schema, _procedure); return procedureName; } #endregion #region 静态方法 public static ProcedureNode Create(XElement element) { string attribuleValue; var info = new ProcedureNode(); info._parameterList = new List<ProcedureParameterNode>(); if(MappingInfo.GetAttribuleValue(element, "name", out attribuleValue)) info._name = attribuleValue; if(MappingInfo.GetAttribuleValue(element, "procedure", out attribuleValue)) info._procedure = attribuleValue; if(MappingInfo.GetAttribuleValue(element, "schema", out attribuleValue)) info._schema = attribuleValue; foreach(var property in element.Elements()) { var parameter = ProcedureParameterNode.Create(property); info.ParameterList.Add(parameter); } return info; } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; namespace Automao.Data.Mapping { public class ProcedureNode { #region 字段 private System.Type _entityType; private string _name; private string _procedure; private string _schema; private List<ProcedureParameterNode> _parameterList; #endregion #region 属性 public string Name { get { return _name; } } public string Procedure { get { return _procedure; } } public string Schema { get { return _schema; } } public List<ProcedureParameterNode> ParameterList { get { return _parameterList; } } /// <summary> /// 所在文件路径 /// </summary> public string MappingFileFullName { get; set; } #endregion #region 公共方法 public string GetProcedureName(bool caseSensitive) { var schema = string.IsNullOrEmpty(_schema) ? "" : (_schema + "."); var procedureName = string.Format(caseSensitive ? "{0}\"{1}\"" : "{0}{1}", schema + _procedure); return procedureName; } #endregion #region 静态方法 public static ProcedureNode Create(XElement element) { string attribuleValue; var info = new ProcedureNode(); info._parameterList = new List<ProcedureParameterNode>(); if(MappingInfo.GetAttribuleValue(element, "name", out attribuleValue)) info._name = attribuleValue; if(MappingInfo.GetAttribuleValue(element, "procedure", out attribuleValue)) info._procedure = attribuleValue; if(MappingInfo.GetAttribuleValue(element, "schema", out attribuleValue)) info._schema = attribuleValue; foreach(var property in element.Elements()) { var parameter = ProcedureParameterNode.Create(property); info.ParameterList.Add(parameter); } return info; } #endregion } }
lgpl-2.1
C#
12ec7b59ecd1f1db8de32ab5a9b79c43cbc69c3a
Change CAT spawn sound.
fr1tz/rotc-ethernet-game,fr1tz/rotc-ethernet-game,fr1tz/rotc-ethernet-game,fr1tz/rotc-ethernet-game
game/server/base/cats.sfx.cs
game/server/base/cats.sfx.cs
//------------------------------------------------------------------------------ // Revenge Of The Cats: Ethernet // Copyright (C) 2008, mEthLab Interactive //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Revenge Of The Cats - cats.sfx.cs // Sounds for all CATs //------------------------------------------------------------------------------ datablock AudioProfile(CatSpawnSound) { filename = "~/data/sfx/deploy1.wav"; description = AudioDefault3D; preload = true; }; datablock AudioProfile(PlayerSlideSound) { filename = "~/data/players/standardcat/slide.wav"; description = AudioCloseLooping3D; preload = true; }; datablock AudioProfile(PlayerSlideContactSound) { filename = "~/data/players/standardcat/slidecontact.wav"; description = AudioCloseLooping3D; preload = true; }; datablock AudioProfile(CatJumpExplosionSound) { filename = "~/data/sfx/explosion3.wav"; description = AudioFar3D; preload = true; }; //datablock AudioProfile(ExitingWaterLightSound) //{ // filename = "~/data/sound/replaceme.wav"; // description = AudioClose3d; // preload = true; //}; //datablock AudioProfile(DeathCrySound) //{ // fileName = ""; // description = AudioClose3d; // preload = true; //}; //datablock AudioProfile(PainCrySound) //{ // fileName = ""; // description = AudioClose3d; // preload = true; //}; //datablock AudioProfile(PlayerSharedMoveBubblesSound) //{ // filename = "~/data/sound/replaceme.wav"; // description = AudioCloseLooping3d; // preload = true; //}; //datablock AudioProfile(WaterBreathMaleSound) //{ // filename = "~/data/sound/replaceme.wav"; // description = AudioClosestLooping3d; // preload = true; //};
//------------------------------------------------------------------------------ // Revenge Of The Cats: Ethernet // Copyright (C) 2008, mEthLab Interactive //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Revenge Of The Cats - cats.sfx.cs // Sounds for all CATs //------------------------------------------------------------------------------ datablock AudioProfile(CatSpawnSound) { filename = "~/data/players/shared/sound.spawn.wav"; description = AudioDefault3D; preload = true; }; datablock AudioProfile(PlayerSlideSound) { filename = "~/data/players/standardcat/slide.wav"; description = AudioCloseLooping3D; preload = true; }; datablock AudioProfile(PlayerSlideContactSound) { filename = "~/data/players/standardcat/slidecontact.wav"; description = AudioCloseLooping3D; preload = true; }; datablock AudioProfile(CatJumpExplosionSound) { filename = "~/data/sfx/explosion3.wav"; description = AudioFar3D; preload = true; }; //datablock AudioProfile(ExitingWaterLightSound) //{ // filename = "~/data/sound/replaceme.wav"; // description = AudioClose3d; // preload = true; //}; //datablock AudioProfile(DeathCrySound) //{ // fileName = ""; // description = AudioClose3d; // preload = true; //}; //datablock AudioProfile(PainCrySound) //{ // fileName = ""; // description = AudioClose3d; // preload = true; //}; //datablock AudioProfile(PlayerSharedMoveBubblesSound) //{ // filename = "~/data/sound/replaceme.wav"; // description = AudioCloseLooping3d; // preload = true; //}; //datablock AudioProfile(WaterBreathMaleSound) //{ // filename = "~/data/sound/replaceme.wav"; // description = AudioClosestLooping3d; // preload = true; //};
lgpl-2.1
C#
456885256a8643158fbd7adf190a72c385a7f552
Bump nuget version number to 0.1.2, includes HaleSerializer
mdsol/crichton-dotnet,edandersen/Edsoft.Hypermedia,edandersen/Edsoft.Hypermedia
src/Crichton.Representors/Properties/AssemblyInfo.cs
src/Crichton.Representors/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. using System.Security; [assembly: AssemblyTitle("Crichton.Representors")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Crichton.Representors")] [assembly: AssemblyCopyright("Copyright © Medidata Solutions 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] [assembly: AllowPartiallyTrustedCallers] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.1.2")] [assembly: AssemblyFileVersionAttribute("0.1.2")] [assembly: AssemblyInformationalVersion("0.1.2-alpha")]
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. using System.Security; [assembly: AssemblyTitle("Crichton.Representors")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Crichton.Representors")] [assembly: AssemblyCopyright("Copyright © Medidata Solutions 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] [assembly: AllowPartiallyTrustedCallers] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.1.1")] [assembly: AssemblyFileVersionAttribute("0.1.1")] [assembly: AssemblyInformationalVersion("0.1.1-alpha")]
mit
C#
b48dc8ed456a89096033c5a325a9e7650d1255a7
Revert "=test2"
Peymanpn/FilenameHelper
Renamer/Program.cs
Renamer/Program.cs
using System; using System.Collections.Generic; using System.Windows.Forms; namespace Renamer { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { //Test Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new frmMain( )); } } }
using System; using System.Collections.Generic; using System.Windows.Forms; namespace Renamer { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { //Test //test 2 Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new frmMain( )); } } }
apache-2.0
C#
be5169aa5a1f4f37fcb3636f79e6aad5ff941849
Add null checks
generik0/Smooth.IoC.Dapper.Repository.UnitOfWork,generik0/Smooth.IoC.Dapper.Repository.UnitOfWork
src/Smooth.IoC.Dapper.Repository.UnitOfWork/Data/DbConnection.cs
src/Smooth.IoC.Dapper.Repository.UnitOfWork/Data/DbConnection.cs
using System; using System.Data; namespace Smooth.IoC.Dapper.Repository.UnitOfWork.Data { public abstract class DbConnection : IDbConnection { private readonly IDbFactory _factory; public IDbConnection Connection { get; protected set; } public IsolationLevel IsolationLevel { get; } protected bool Disposed; public DbConnection(IDbFactory factory) { _factory = factory; } public IDbTransaction BeginTransaction() { return BeginTransaction(IsolationLevel.Serializable); } public IDbTransaction BeginTransaction(IsolationLevel isolationLevel) { return Connection?.BeginTransaction(isolationLevel); } public void Close() { Connection?.Close(); } public void ChangeDatabase(string databaseName) { Connection?.ChangeDatabase(databaseName); } public IDbCommand CreateCommand() { return Connection.CreateCommand(); } public void Open() { if (Connection?.State != ConnectionState.Open) { Connection?.Open(); } } public string ConnectionString { get { return Connection?.ConnectionString; } set { Connection.ConnectionString = value; } } public int ConnectionTimeout => Connection?.ConnectionTimeout ?? 0; public string Database => Connection?.Database; public ConnectionState State => Connection?.State ?? ConnectionState.Closed; ~DbConnection() { Dispose(false); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private void Dispose(bool disposing) { if (Disposed) return; Disposed = true; if (!disposing) return; try { Connection?.Dispose(); } finally { _factory.Release(this); } } } }
using System; using System.Data; namespace Smooth.IoC.Dapper.Repository.UnitOfWork.Data { public abstract class DbConnection : IDbConnection { private readonly IDbFactory _factory; public IDbConnection Connection { get; protected set; } public IsolationLevel IsolationLevel { get; } protected bool Disposed; public DbConnection(IDbFactory factory) { _factory = factory; } public IDbTransaction BeginTransaction() { return BeginTransaction(IsolationLevel.Serializable); } public IDbTransaction BeginTransaction(IsolationLevel isolationLevel) { return Connection?.BeginTransaction(isolationLevel); } public void Close() { Connection?.Close(); } public void ChangeDatabase(string databaseName) { Connection?.ChangeDatabase(databaseName); } public IDbCommand CreateCommand() { return Connection.CreateCommand(); } public void Open() { Connection?.Open(); } public string ConnectionString { get { return Connection?.ConnectionString; } set { Connection.ConnectionString = value; } } public int ConnectionTimeout => Connection?.ConnectionTimeout ?? 0; public string Database => Connection?.Database; public ConnectionState State => Connection?.State ?? ConnectionState.Closed; ~DbConnection() { Dispose(false); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private void Dispose(bool disposing) { if (Disposed) return; Disposed = true; if (!disposing) return; try { Connection?.Dispose(); } finally { _factory.Release(this); } } } }
mit
C#
a057c2e89eaa7c7701ff7b78fe7979656c42f577
Deploy 1.0.0.
Faithlife/Parsing
SolutionInfo.cs
SolutionInfo.cs
using System.Reflection; [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyCompany("Faithlife Corporation")] [assembly: AssemblyCopyright("Copyright 2016 Faithlife Corporation")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")]
using System.Reflection; [assembly: AssemblyVersion("0.1.5.0")] [assembly: AssemblyCompany("Faithlife Corporation")] [assembly: AssemblyCopyright("Copyright 2016 Faithlife Corporation")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")]
mit
C#
8eca12bd624e253c6c54ac7f2acb390774b297e8
Fix layers content type rule to not include stereotypes (#8868)
xkproject/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2
src/OrchardCore.Modules/OrchardCore.Rules/Drivers/ContentTypeConditionEvaluatorDriver.cs
src/OrchardCore.Modules/OrchardCore.Rules/Drivers/ContentTypeConditionEvaluatorDriver.cs
using System; using System.Collections.Generic; using System.Threading.Tasks; using OrchardCore.ContentManagement; using OrchardCore.ContentManagement.Display.ContentDisplay; using OrchardCore.ContentManagement.Metadata.Settings; using OrchardCore.DisplayManagement; using OrchardCore.DisplayManagement.Handlers; using OrchardCore.DisplayManagement.Views; using OrchardCore.Rules.Models; namespace OrchardCore.Rules.Drivers { /// <summary> /// Saves references to content types which have been displayed during a request. /// </summary> public class ContentTypeConditionEvaluatorDriver : ContentDisplayDriver, IConditionEvaluator { private static ValueTask<bool> True = new ValueTask<bool>(true); private static ValueTask<bool> False = new ValueTask<bool>(false); private readonly IConditionOperatorResolver _operatorResolver; // Hashset to prevent duplicate entries, but comparison is done by the comparers. private readonly HashSet<string> _contentTypes = new HashSet<string>(); public ContentTypeConditionEvaluatorDriver(IConditionOperatorResolver operatorResolver) { _operatorResolver = operatorResolver; } public override Task<IDisplayResult> DisplayAsync(ContentItem contentItem, BuildDisplayContext context) { // Do not include Widgets or any display type other than detail. if (context.DisplayType == "Detail" && !context.Shape.TryGetProperty(nameof(ContentTypeSettings.Stereotype), out string _)) { _contentTypes.Add(contentItem.ContentType); } return Task.FromResult<IDisplayResult>(null); } public ValueTask<bool> EvaluateAsync(Condition condition) => EvaluateAsync(condition as ContentTypeCondition); private ValueTask<bool> EvaluateAsync(ContentTypeCondition condition) { var operatorComparer = _operatorResolver.GetOperatorComparer(condition.Operation); foreach (var contentType in _contentTypes) { if (operatorComparer.Compare(condition.Operation, contentType, condition.Value)) { return True; } } return False; } } }
using System.Collections.Generic; using System.Threading.Tasks; using OrchardCore.ContentManagement; using OrchardCore.ContentManagement.Display.ContentDisplay; using OrchardCore.ContentManagement.Metadata.Settings; using OrchardCore.DisplayManagement; using OrchardCore.DisplayManagement.Handlers; using OrchardCore.DisplayManagement.Views; using OrchardCore.Rules.Models; namespace OrchardCore.Rules.Drivers { /// <summary> /// Saves references to content types which have been displayed during a request. /// </summary> public class ContentTypeConditionEvaluatorDriver : ContentDisplayDriver, IConditionEvaluator { private static ValueTask<bool> True = new ValueTask<bool>(true); private static ValueTask<bool> False = new ValueTask<bool>(false); private readonly IConditionOperatorResolver _operatorResolver; // Hashset to prevent duplicate entries, but comparison is done by the comparers. private readonly HashSet<string> _contentTypes = new HashSet<string>(); public ContentTypeConditionEvaluatorDriver(IConditionOperatorResolver operatorResolver) { _operatorResolver = operatorResolver; } public override Task<IDisplayResult> DisplayAsync(ContentItem contentItem, BuildDisplayContext context) { // Do not include Widgets or any display type other than detail. if (context.DisplayType == "Detail" && context.Shape.TryGetProperty(nameof(ContentTypeSettings.Stereotype), out string stereotype)) { _contentTypes.Add(contentItem.ContentType); } return Task.FromResult<IDisplayResult>(null); } public ValueTask<bool> EvaluateAsync(Condition condition) => EvaluateAsync(condition as ContentTypeCondition); private ValueTask<bool> EvaluateAsync(ContentTypeCondition condition) { var operatorComparer = _operatorResolver.GetOperatorComparer(condition.Operation); foreach (var contentType in _contentTypes) { if (operatorComparer.Compare(condition.Operation, contentType, condition.Value)) { return True; } } return False; } } }
bsd-3-clause
C#
77447127d1828d912b227a66f9193944daebce57
Fix ShipMapper: relation to CargoContainer
peopleware/net-ppwcode-vernacular-nhibernate
src/PPWCode.Vernacular.NHibernate.I.Tests/RepositoryWithDtoMapping/Mappers/ShipMapper.cs
src/PPWCode.Vernacular.NHibernate.I.Tests/RepositoryWithDtoMapping/Mappers/ShipMapper.cs
// Copyright 2017 by PeopleWare n.v.. // // 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 NHibernate.Mapping.ByCode; using PPWCode.Vernacular.NHibernate.I.MappingByCode; using PPWCode.Vernacular.NHibernate.I.Tests.RepositoryWithDtoMapping.Models; namespace PPWCode.Vernacular.NHibernate.I.Tests.RepositoryWithDtoMapping.Mappers { public class ShipMapper : PersistentObjectMapper<Ship, int> { public ShipMapper() { Property(s => s.Code); Set( s => s.CargoContainers, m => { m.Inverse(true); m.Cascade(Cascade.All | Cascade.Merge); }, r => r.OneToMany()); } } }
// Copyright 2017 by PeopleWare n.v.. // // 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 NHibernate.Mapping.ByCode; using PPWCode.Vernacular.NHibernate.I.MappingByCode; using PPWCode.Vernacular.NHibernate.I.Tests.RepositoryWithDtoMapping.Models; namespace PPWCode.Vernacular.NHibernate.I.Tests.RepositoryWithDtoMapping.Mappers { public class ShipMapper : PersistentObjectMapper<Ship, int> { public ShipMapper() { Property(s => s.Code); Set( s => s.CargoContainers, m => { // m.Inverse(true); m.Cascade(Cascade.All | Cascade.Merge); }, r => r.OneToMany(m => m.Class(typeof(CargoContainer)))); } } }
apache-2.0
C#
f77e260ae834634fa0d49e6d5ba5719cb2497fe6
Extend OperatorOverloadsSample
ulrichb/ImplicitNullability,ulrichb/ImplicitNullability,ulrichb/ImplicitNullability
Src/ImplicitNullability.Samples.CodeWithIN/NullabilityAnalysis/OperatorOverloadsSample.cs
Src/ImplicitNullability.Samples.CodeWithIN/NullabilityAnalysis/OperatorOverloadsSample.cs
using System; using JetBrains.Annotations; using static ImplicitNullability.Samples.CodeWithIN.ReSharper; namespace ImplicitNullability.Samples.CodeWithIN.NullabilityAnalysis { public static class OperatorOverloadsSample { public class Simple { public static int operator +(Simple left, Simple right) { TestValueAnalysis(left, left == null /*Expect:ConditionIsAlwaysTrueOrFalse[MIn]*/); TestValueAnalysis(right, right == null /*Expect:ConditionIsAlwaysTrueOrFalse[MIn]*/); return 0; } public static Simple operator ++(Simple value) { TestValueAnalysis(value, value == null /*Expect:ConditionIsAlwaysTrueOrFalse[MIn]*/); return new Simple(); } public static explicit operator Simple(string s) { TestValueAnalysis(s, s == null /*Expect:ConditionIsAlwaysTrueOrFalse[MIn]*/); return new Simple(); } } public class CanBeNull { public static int operator +([CanBeNull] CanBeNull left, [CanBeNull] CanBeNull right) { TestValueAnalysis(left /*Expect:AssignNullToNotNullAttribute*/, left == null); TestValueAnalysis(right /*Expect:AssignNullToNotNullAttribute*/, right == null); return 0; } [CanBeNull] public static CanBeNull operator ++([CanBeNull] CanBeNull value) { TestValueAnalysis(value /*Expect:AssignNullToNotNullAttribute*/, value == null); return null; } [CanBeNull] public static explicit operator CanBeNull([CanBeNull] string s) { TestValueAnalysis(s /*Expect:AssignNullToNotNullAttribute*/, s == null); return null; } } public class NotNullReturnValue { public static NotNullReturnValue operator ++(NotNullReturnValue value) { return null /*Expect:AssignNullToNotNullAttribute[MOut]*/; } public static explicit operator NotNullReturnValue(string s) { return null /*Expect:AssignNullToNotNullAttribute[MOut]*/; } } } }
using System; using JetBrains.Annotations; using static ImplicitNullability.Samples.CodeWithIN.ReSharper; namespace ImplicitNullability.Samples.CodeWithIN.NullabilityAnalysis { public static class OperatorOverloadsSample { public class Simple { public static int operator +(Simple left, Simple right) { TestValueAnalysis(left, left == null /*Expect:ConditionIsAlwaysTrueOrFalse[MIn]*/); TestValueAnalysis(right, right == null /*Expect:ConditionIsAlwaysTrueOrFalse[MIn]*/); return 0; } public static Simple operator ++(Simple value) { TestValueAnalysis(value, value == null /*Expect:ConditionIsAlwaysTrueOrFalse[MIn]*/); return new Simple(); } } public class CanBeNull { public static int operator +([CanBeNull] CanBeNull left, [CanBeNull] CanBeNull right) { TestValueAnalysis(left /*Expect:AssignNullToNotNullAttribute*/, left == null); TestValueAnalysis(right /*Expect:AssignNullToNotNullAttribute*/, right == null); return 0; } [CanBeNull] public static CanBeNull operator ++([CanBeNull] CanBeNull value) { TestValueAnalysis(value /*Expect:AssignNullToNotNullAttribute*/, value == null); return null; } } public class NotNullReturnValue { public static NotNullReturnValue operator ++(NotNullReturnValue value) { return null /*Expect:AssignNullToNotNullAttribute[MOut]*/; } } } }
mit
C#
be741a3f46844a27055c1ddfada949b7d59a5eb8
Update KeneticProjectileDamageInterity.cs
fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation
UnityProject/Assets/Scripts/Weapons/Projectiles/Behaviours/KeneticProjectileDamageInterity.cs
UnityProject/Assets/Scripts/Weapons/Projectiles/Behaviours/KeneticProjectileDamageInterity.cs
using UnityEngine; using ScriptableObjects.Gun; namespace Weapons.Projectiles.Behaviours { /// <summary> /// Damages integrity on collision /// only for kenetic weapons /// </summary> public class KeneticProjectileDamageInterity : MonoBehaviour, IOnShoot, IOnHit { private GameObject shooter; private Gun weapon; [SerializeField] private DamageData damageData = null; public void OnShoot(Vector2 direction, GameObject shooter, Gun weapon, BodyPartType targetZone = BodyPartType.Chest) { this.shooter = shooter; this.weapon = weapon; } public bool OnHit(RaycastHit2D hit) { return TryDamage(hit); } private bool TryDamage(RaycastHit2D hit) { float pressure = MatrixManager.AtPoint((Vector3Int)hit.point.To2Int(), true).MetaDataLayer.Get(hit.transform.localPosition.RoundToInt()).GasMix.Pressure; var newDamage = damageData.Damage; var coll = hit.collider; var integrity = coll.GetComponent<Integrity>(); if (integrity == null) return false; // checks if its a high atmosphere newDamage = (1175 / 26) - ((15 - pressure) / 26); integrity.ApplyDamage(newDamage, damageData.AttackType, damageData.DamageType); Chat.AddAttackMsgToChat(shooter, coll.gameObject, BodyPartType.None, weapon.gameObject); Logger.LogTraceFormat("Hit {0} for {1} with HealthBehaviour! bullet absorbed", Category.Firearms, integrity.gameObject.name, damageData.Damage); return true; } private void OnDisable() { weapon = null; shooter = null; } } }
using UnityEngine; using ScriptableObjects.Gun; namespace Weapons.Projectiles.Behaviours { /// <summary> /// Damages integrity on collision /// only for kenetic weapons /// </summary> public class KeneticProjectileDamageInterity : MonoBehaviour, IOnShoot, IOnHit { private GameObject shooter; private Gun weapon; [SerializeField] private DamageData damageData = null; public void OnShoot(Vector2 direction, GameObject shooter, Gun weapon, BodyPartType targetZone = BodyPartType.Chest) { this.shooter = shooter; this.weapon = weapon; } public bool OnHit(RaycastHit2D hit) { return TryDamage(hit); } private bool TryDamage(RaycastHit2D hit) { float pressure = MatrixManager.AtPoint((Vector3Int)hit.point.To2Int(), true).MetaDataLayer.Get(hit.transform.localPosition.RoundToInt()).GasMix.Pressure; var newDamage = damageData.Damage; var coll = hit.collider; var integrity = coll.GetComponent<Integrity>(); if (integrity == null) return false; // checks if its a high atmosphere newDamage = (1175 / 26) - ((15 - pressure) / 26); integrity.ApplyDamage(newDamage, damageData.AttackType, damageData.DamageType); Chat.AddAttackMsgToChat(shooter, coll.gameObject, BodyPartType.None, weapon.gameObject); Logger.LogTraceFormat("Hit {0} for {1} with HealthBehaviour! bullet absorbed", Category.Firearms, integrity.gameObject.name, damageData.Damage); return true; } private void OnDisable() { weapon = null; shooter = null; } } }
agpl-3.0
C#
c1dfd37d3c5489061f79ddf1196ac4884a588f86
Add TODO for flay restore url test
cstlaurent/elasticsearch-net,KodrAus/elasticsearch-net,KodrAus/elasticsearch-net,elastic/elasticsearch-net,UdiBen/elasticsearch-net,KodrAus/elasticsearch-net,cstlaurent/elasticsearch-net,adam-mccoy/elasticsearch-net,CSGOpenSource/elasticsearch-net,azubanov/elasticsearch-net,azubanov/elasticsearch-net,UdiBen/elasticsearch-net,CSGOpenSource/elasticsearch-net,TheFireCookie/elasticsearch-net,RossLieberman/NEST,adam-mccoy/elasticsearch-net,cstlaurent/elasticsearch-net,CSGOpenSource/elasticsearch-net,RossLieberman/NEST,azubanov/elasticsearch-net,elastic/elasticsearch-net,adam-mccoy/elasticsearch-net,UdiBen/elasticsearch-net,TheFireCookie/elasticsearch-net,RossLieberman/NEST,TheFireCookie/elasticsearch-net
src/Tests/Modules/SnapshotAndRestore/Restore/RestoreApiTests.cs
src/Tests/Modules/SnapshotAndRestore/Restore/RestoreApiTests.cs
using System; using System.IO; using Elasticsearch.Net; using Nest; using Tests.Framework; using Tests.Framework.Integration; using Xunit; namespace Tests.Modules.SnapshotAndRestore.Restore { // TODO HitsTheCorrectUrl is flaky here, sometimes it fails sometimes it passes [Collection(IntegrationContext.Indexing)] public class RestoreApiTests : ApiIntegrationTestBase<IRestoreResponse, IRestoreRequest, RestoreDescriptor, RestoreRequest> { public RestoreApiTests(IndexingCluster cluster, EndpointUsage usage) : base(cluster, usage) { _repositoryName = RandomString(); _snapshotName = RandomString(); if (!TestClient.Configuration.RunIntegrationTests) return; var createRepository = this.Client.CreateRepository(_repositoryName, r => r .FileSystem(fs => fs .Settings(Path.Combine(cluster.Node.RepositoryPath, _repositoryName)) ) ); if (!createRepository.IsValid) throw new Exception("Setup: failed to create snapshot repository"); var snapshot = this.Client.Snapshot(_repositoryName, _snapshotName, s => s .WaitForCompletion() ); if (!snapshot.IsValid) throw new Exception("Setup: snapshot failed"); } private readonly string _repositoryName; private readonly string _snapshotName; protected override LazyResponses ClientUsage() => Calls( fluent: (client, f) => client.Restore(_repositoryName, _snapshotName, f), fluentAsync: (client, f) => client.RestoreAsync(_repositoryName, _snapshotName, f), request: (client, r) => client.Restore(r), requestAsync: (client, r) => client.RestoreAsync(r) ); protected override HttpMethod HttpMethod => HttpMethod.POST; protected override string UrlPath => $"/_snapshot/{_repositoryName}/{_snapshotName}/_restore"; protected override int ExpectStatusCode => 200; protected override bool ExpectIsValid => true; protected override object ExpectJson { get; } = new { rename_pattern = "nest-(.+)", rename_replacement = "nest-restored-$1", }; protected override bool SupportsDeserialization => false; protected override RestoreDescriptor NewDescriptor() => new RestoreDescriptor(_repositoryName, _snapshotName); protected override Func<RestoreDescriptor, IRestoreRequest> Fluent => d => d .RenamePattern("nest-(.+)") .RenameReplacement("nest-restored-$1"); protected override RestoreRequest Initializer => new RestoreRequest(_repositoryName, _snapshotName) { RenamePattern = "nest-(.+)", RenameReplacement = "nest-restored-$1" }; } }
using System; using System.IO; using Elasticsearch.Net; using Nest; using Tests.Framework; using Tests.Framework.Integration; using Xunit; namespace Tests.Modules.SnapshotAndRestore.Restore { [Collection(IntegrationContext.Indexing)] public class RestoreApiTests : ApiIntegrationTestBase<IRestoreResponse, IRestoreRequest, RestoreDescriptor, RestoreRequest> { public RestoreApiTests(IndexingCluster cluster, EndpointUsage usage) : base(cluster, usage) { _repositoryName = RandomString(); _snapshotName = RandomString(); if (!TestClient.Configuration.RunIntegrationTests) return; var createRepository = this.Client.CreateRepository(_repositoryName, r => r .FileSystem(fs => fs .Settings(Path.Combine(cluster.Node.RepositoryPath, _repositoryName)) ) ); if (!createRepository.IsValid) throw new Exception("Setup: failed to create snapshot repository"); var snapshot = this.Client.Snapshot(_repositoryName, _snapshotName, s => s .WaitForCompletion() ); if (!snapshot.IsValid) throw new Exception("Setup: snapshot failed"); } private readonly string _repositoryName; private readonly string _snapshotName; protected override LazyResponses ClientUsage() => Calls( fluent: (client, f) => client.Restore(_repositoryName, _snapshotName, f), fluentAsync: (client, f) => client.RestoreAsync(_repositoryName, _snapshotName, f), request: (client, r) => client.Restore(r), requestAsync: (client, r) => client.RestoreAsync(r) ); protected override HttpMethod HttpMethod => HttpMethod.POST; protected override string UrlPath => $"/_snapshot/{_repositoryName}/{_snapshotName}/_restore"; protected override int ExpectStatusCode => 200; protected override bool ExpectIsValid => true; protected override object ExpectJson { get; } = new { rename_pattern = "nest-(.+)", rename_replacement = "nest-restored-$1", }; protected override bool SupportsDeserialization => false; protected override RestoreDescriptor NewDescriptor() => new RestoreDescriptor(_repositoryName, _snapshotName); protected override Func<RestoreDescriptor, IRestoreRequest> Fluent => d => d .RenamePattern("nest-(.+)") .RenameReplacement("nest-restored-$1"); protected override RestoreRequest Initializer => new RestoreRequest(_repositoryName, _snapshotName) { RenamePattern = "nest-(.+)", RenameReplacement = "nest-restored-$1" }; } }
apache-2.0
C#
243417c97bd97e293ad4f6e2c5d25c7d4b82b1b0
change to serilog logger to unwrap the LogMessage correctly to get the format and arguments, and also make the ctor public so I could get it to work.
adamhathcock/akka.net,naveensrinivasan/akka.net,eisendle/akka.net,willieferguson/akka.net,rodrigovidal/akka.net,skotzko/akka.net,rogeralsing/akka.net,forki/akka.net,nvivo/akka.net,AntoineGa/akka.net,nvivo/akka.net,forki/akka.net,willieferguson/akka.net,JeffCyr/akka.net,Silv3rcircl3/akka.net,zbrad/akka.net,jordansjones/akka.net,bruinbrown/akka.net,Micha-kun/akka.net,stefansedich/akka.net,KadekM/akka.net,alexpantyukhin/akka.net,skotzko/akka.net,neekgreen/akka.net,amichel/akka.net,simonlaroche/akka.net,thelegendofando/akka.net,Chinchilla-Software-Com/akka.net,eisendle/akka.net,billyxing/akka.net,tillr/akka.net,alexvaluyskiy/akka.net,ali-ince/akka.net,nanderto/akka.net,heynickc/akka.net,adamhathcock/akka.net,dbolkensteyn/akka.net,forki/akka.net,ali-ince/akka.net,akoshelev/akka.net,linearregression/akka.net,billyxing/akka.net,MAOliver/akka.net,kerryjiang/akka.net,naveensrinivasan/akka.net,silentnull/akka.net,michal-franc/akka.net,cpx/akka.net,alexvaluyskiy/akka.net,alex-kondrashov/akka.net,AntoineGa/akka.net,alexpantyukhin/akka.net,forki/akka.net,dbolkensteyn/akka.net,dyanarose/akka.net,rodrigovidal/akka.net,d--g/akka.net,Micha-kun/akka.net,linearregression/akka.net,vchekan/akka.net,kekekeks/akka.net,amichel/akka.net,JeffCyr/akka.net,eloraiby/akka.net,chris-ray/akka.net,kstaruch/akka.net,rogeralsing/akka.net,cpx/akka.net,derwasp/akka.net,michal-franc/akka.net,matiii/akka.net,eloraiby/akka.net,kstaruch/akka.net,akoshelev/akka.net,thelegendofando/akka.net,ashic/akka.net,GeorgeFocas/akka.net,silentnull/akka.net,simonlaroche/akka.net,alex-kondrashov/akka.net,MAOliver/akka.net,bruinbrown/akka.net,gwokudasam/akka.net,stefansedich/akka.net,nanderto/akka.net,tillr/akka.net,matiii/akka.net,derwasp/akka.net,cdmdotnet/akka.net,jordansjones/akka.net,kekekeks/akka.net,dyanarose/akka.net,heynickc/akka.net,Silv3rcircl3/akka.net,KadekM/akka.net,zbrad/akka.net,numo16/akka.net,ashic/akka.net,trbngr/akka.net,Chinchilla-Software-Com/akka.net,numo16/akka.net,GeorgeFocas/akka.net,gwokudasam/akka.net,kerryjiang/akka.net,chris-ray/akka.net,trbngr/akka.net,vchekan/akka.net,cdmdotnet/akka.net,neekgreen/akka.net,d--g/akka.net
src/contrib/loggers/Akka.Serilog/Event/Serilog/SerilogLogger.cs
src/contrib/loggers/Akka.Serilog/Event/Serilog/SerilogLogger.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Akka.Actor; using Akka.Event; using Serilog; namespace Akka.Serilog.Event.Serilog { public class SerilogLogger : ReceiveActor { private readonly LoggingAdapter _log = Logging.GetLogger(Context); private void WithSerilog(Action<ILogger> logStatement) { var logger = Log.Logger.ForContext(GetType()); logStatement(logger); } private ILogger SetContextFromLogEvent(ILogger logger, LogEvent logEvent) { logger.ForContext("Timestamp", logEvent.Timestamp); logger.ForContext("LogSource", logEvent.LogSource); logger.ForContext("Thread", logEvent.Thread); return logger; } public SerilogLogger() { Receive<Error>(m => WithSerilog(logger => SetContextFromLogEvent(logger, m).Error(m.Cause, GetFormat(m.Message), GetArgs(m.Message)))); Receive<Warning>(m => WithSerilog(logger => SetContextFromLogEvent(logger, m).Warning(GetFormat(m.Message), GetArgs(m.Message)))); Receive<Info>(m => WithSerilog(logger => SetContextFromLogEvent(logger, m).Information(GetFormat(m.Message), GetArgs(m.Message)))); Receive<Debug>(m => WithSerilog(logger => SetContextFromLogEvent(logger, m).Debug(GetFormat(m.Message), GetArgs(m.Message)))); Receive<InitializeLogger>(m => { _log.Info("SerilogLogger started"); Sender.Tell(new LoggerInitialized()); }); } private static string GetFormat(object message) { var logMessage = message as LogMessage; return logMessage != null ? logMessage.Format : "{Message}"; } private static object[] GetArgs(object message) { var logMessage = message as LogMessage; return logMessage != null ? logMessage.Args : new[] { message }; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Akka.Actor; using Akka.Event; using Serilog; namespace Akka.Serilog.Event.Serilog { public class SerilogLogger : ReceiveActor { private readonly LoggingAdapter _log = Logging.GetLogger(Context); private void WithSerilog(Action<ILogger> logStatement) { var logger = Log.Logger.ForContext(GetType()); logStatement(logger); } private ILogger SetContextFromLogEvent(ILogger logger, LogEvent logEvent) { logger.ForContext("Timestamp", logEvent.Timestamp); logger.ForContext("LogSource", logEvent.LogSource); logger.ForContext("Thread", logEvent.Thread); return logger; } protected SerilogLogger() { Receive<Error>(m => WithSerilog(logger => SetContextFromLogEvent(logger, m).Error(m.Cause, GetFormat(m), GetArgs(m)))); Receive<Warning>(m => WithSerilog(logger => SetContextFromLogEvent(logger, m).Warning(GetFormat(m), GetArgs(m)))); Receive<Info>(m => WithSerilog(logger => SetContextFromLogEvent(logger, m).Information(GetFormat(m), GetArgs(m)))); Receive<Debug>(m => WithSerilog(logger => SetContextFromLogEvent(logger, m).Debug(GetFormat(m), GetArgs(m)))); Receive<InitializeLogger>(m => { _log.Info("SerilogLogger started"); Sender.Tell(new LoggerInitialized()); }); } private static string GetFormat(object message) { var logMessage = message as LogMessage; return logMessage != null ? logMessage.Format : "{Message}"; } private static object GetArgs(object message) { var logMessage = message as LogMessage; return logMessage != null ? logMessage.Args : message; } } }
apache-2.0
C#
b2f9a68e231bb9a53d5bd9cd1b0630326188ab92
use preferred api
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi.Gui/Controls/WalletExplorer/ClosedWalletViewModel.cs
WalletWasabi.Gui/Controls/WalletExplorer/ClosedWalletViewModel.cs
using AvalonStudio.Extensibility; using ReactiveUI; using Splat; using System; using System.IO; using System.Linq; using System.Reactive; using System.Reactive.Linq; using System.Threading; using WalletWasabi.Gui.Helpers; using WalletWasabi.Logging; using WalletWasabi.Wallets; namespace WalletWasabi.Gui.Controls.WalletExplorer { public class ClosedWalletViewModel : WalletViewModelBase { public ClosedWalletViewModel(Wallet wallet) : base(wallet) { OpenWalletCommand = ReactiveCommand.CreateFromTask(async () => { try { IsBusy = true; var global = Locator.Current.GetService<Global>(); if (!await global.WaitForInitializationCompletedAsync(CancellationToken.None)) { return; } await global.WalletManager.StartWalletAsync(wallet); var walletExplorer = IoC.Get<WalletExplorerViewModel>(); var select = walletExplorer.SelectedItem == this; walletExplorer.RemoveWallet(this); if (wallet.Coins.Any()) { // If already have coins then open the last active tab first. walletExplorer.OpenWallet(wallet, receiveDominant: false, select: select); } else // Else open with Receive tab first. { walletExplorer.OpenWallet(wallet, receiveDominant: true, select: select); } } catch (Exception e) { NotificationHelpers.Error($"Error loading Wallet: {Title}"); Logger.LogError(e.Message); } finally { IsBusy = false; } }, this.WhenAnyValue(x => x.IsBusy).Select(x => !x)); } public ReactiveCommand<Unit, Unit> OpenWalletCommand { get; } } }
using AvalonStudio.Extensibility; using ReactiveUI; using Splat; using System; using System.IO; using System.Linq; using System.Reactive; using System.Reactive.Linq; using System.Threading; using WalletWasabi.Gui.Helpers; using WalletWasabi.Logging; using WalletWasabi.Wallets; namespace WalletWasabi.Gui.Controls.WalletExplorer { public class ClosedWalletViewModel : WalletViewModelBase { public ClosedWalletViewModel(Wallet wallet) : base(wallet) { OpenWalletCommand = ReactiveCommand.CreateFromTask(async () => { try { IsBusy = true; var global = Locator.Current.GetService<Global>(); if (!await global.WaitForInitializationCompletedAsync(CancellationToken.None)) { return; } await global.WalletManager.StartWalletAsync(wallet.KeyManager); var walletExplorer = IoC.Get<WalletExplorerViewModel>(); var select = walletExplorer.SelectedItem == this; walletExplorer.RemoveWallet(this); if (wallet.Coins.Any()) { // If already have coins then open the last active tab first. walletExplorer.OpenWallet(wallet, receiveDominant: false, select: select); } else // Else open with Receive tab first. { walletExplorer.OpenWallet(wallet, receiveDominant: true, select: select); } } catch (Exception e) { NotificationHelpers.Error($"Error loading Wallet: {Title}"); Logger.LogError(e.Message); } finally { IsBusy = false; } }, this.WhenAnyValue(x => x.IsBusy).Select(x => !x)); } public ReactiveCommand<Unit, Unit> OpenWalletCommand { get; } } }
mit
C#
1b5d4f2cfc0fa928c8c0f030810e67645c1a239c
Make HtmlContentFormatterTests use MockFileSystem
blorgbeard/pickles,irfanah/pickles,magicmonty/pickles,magicmonty/pickles,blorgbeard/pickles,picklesdoc/pickles,picklesdoc/pickles,irfanah/pickles,dirkrombauts/pickles,blorgbeard/pickles,magicmonty/pickles,blorgbeard/pickles,dirkrombauts/pickles,irfanah/pickles,ludwigjossieaux/pickles,ludwigjossieaux/pickles,irfanah/pickles,dirkrombauts/pickles,dirkrombauts/pickles,ludwigjossieaux/pickles,magicmonty/pickles,picklesdoc/pickles,picklesdoc/pickles
src/Pickles/Pickles.Test/Formatters/HtmlContentFormatterTests.cs
src/Pickles/Pickles.Test/Formatters/HtmlContentFormatterTests.cs
using System; using System.Xml.Linq; using Autofac; using Moq; using NUnit.Framework; using PicklesDoc.Pickles.DirectoryCrawler; using PicklesDoc.Pickles.DocumentationBuilders.HTML; using PicklesDoc.Pickles.Parser; namespace PicklesDoc.Pickles.Test.Formatters { [TestFixture] public class HtmlContentFormatterTests : BaseFixture { [Test] public void Constructor_NullHtmlFeatureFormatter_ThrowsArgumentNullException() { var exception = Assert.Throws<ArgumentNullException>( () => new HtmlContentFormatter(null, null, null)); Assert.AreEqual("htmlFeatureFormatter", exception.ParamName); } [Test] public void Constructor_NullHtmlIndexFormatter_ThrowsArgumentNullException() { var exception = Assert.Throws<ArgumentNullException>( () => new HtmlContentFormatter( Container.Resolve<HtmlFeatureFormatter>(), null, null)); Assert.AreEqual("htmlIndexFormatter", exception.ParamName); } [Test] public void Format_ContentIsFeatureNode_UsesHtmlFeatureFormatterWithCorrectArgument() { var fakeHtmlFeatureFormatter = new Mock<IHtmlFeatureFormatter>(); var fakeHtmlImageRelocator = new Mock<HtmlImageRelocator>(null, null); fakeHtmlImageRelocator.Setup(x => x.Relocate(It.IsAny<INode>(), It.IsAny<XElement>())); var formatter = new HtmlContentFormatter(fakeHtmlFeatureFormatter.Object, Container.Resolve<HtmlIndexFormatter>(), fakeHtmlImageRelocator.Object); var featureNode = new FeatureNode( MockFileSystem.FileInfo.FromFileName(@"c:\temp\test.feature"), ".", new Feature()); formatter.Format(featureNode, new INode[0]); fakeHtmlFeatureFormatter.Verify(f => f.Format(featureNode.Feature)); } } }
using System; using System.Xml.Linq; using Autofac; using Moq; using NUnit.Framework; using PicklesDoc.Pickles.DirectoryCrawler; using PicklesDoc.Pickles.DocumentationBuilders.HTML; using PicklesDoc.Pickles.Parser; namespace PicklesDoc.Pickles.Test.Formatters { [TestFixture] public class HtmlContentFormatterTests : BaseFixture { [Test] public void Constructor_NullHtmlFeatureFormatter_ThrowsArgumentNullException() { var exception = Assert.Throws<ArgumentNullException>( () => new HtmlContentFormatter(null, null, null)); Assert.AreEqual("htmlFeatureFormatter", exception.ParamName); } [Test] public void Constructor_NullHtmlIndexFormatter_ThrowsArgumentNullException() { var exception = Assert.Throws<ArgumentNullException>( () => new HtmlContentFormatter( Container.Resolve<HtmlFeatureFormatter>(), null, null)); Assert.AreEqual("htmlIndexFormatter", exception.ParamName); } [Test] public void Format_ContentIsFeatureNode_UsesHtmlFeatureFormatterWithCorrectArgument() { var fakeHtmlFeatureFormatter = new Mock<IHtmlFeatureFormatter>(); var fakeHtmlImageRelocator = new Mock<HtmlImageRelocator>(null, null); fakeHtmlImageRelocator.Setup(x => x.Relocate(It.IsAny<INode>(), It.IsAny<XElement>())); var formatter = new HtmlContentFormatter(fakeHtmlFeatureFormatter.Object, Container.Resolve<HtmlIndexFormatter>(), fakeHtmlImageRelocator.Object); var featureNode = new FeatureNode( RealFileSystem.FileInfo.FromFileName(@"c:\temp\test.feature"), ".", new Feature()); formatter.Format(featureNode, new INode[0]); fakeHtmlFeatureFormatter.Verify(f => f.Format(featureNode.Feature)); } } }
apache-2.0
C#
dfeae2cc47d0eb8696b10d0bb0e12d267a09bfd2
Simplify string replacement in template.json
mrward/monodevelop-template-creator-addin,mrward/monodevelop-template-creator-addin
src/MonoDevelop.TemplateCreator/MonoDevelop.Templating/TemplateInformationViewModel.cs
src/MonoDevelop.TemplateCreator/MonoDevelop.Templating/TemplateInformationViewModel.cs
// // TemplateInformationViewModel.cs // // Author: // Matt Ward <[email protected]> // // Copyright (c) 2017 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.Reflection; using MonoDevelop.Core.StringParsing; using MonoDevelop.Projects; namespace MonoDevelop.Templating { class TemplateInformationViewModel : IStringTagModel { DotNetProject project; public TemplateInformationViewModel (DotNetProject project) { this.project = project; GenerateDefaults (); } public string Author { get; set; } public string DisplayName { get; set; } public string ShortName { get; set; } public string DefaultProjectName { get; set; } public string Identity { get; set; } public string GroupIdentity { get; set; } public string SourceName { get; set; } public string Language { get; set; } void GenerateDefaults () { Author = AuthorInformation.Default.Name; DefaultProjectName = project.Name; DisplayName = project.Name; ShortName = project.Name; Language = project.LanguageName; GroupIdentity = $"MyTemplate.{project.Name}"; Identity = $"{GroupIdentity}.{project.GetTemplateLanguageName ()}"; SourceName = project.FileName.FileNameWithoutExtension; } public object GetValue (string name) { var bindingFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase; PropertyInfo property = GetType ().GetProperty (name, bindingFlags); if (property != null) { return property.GetValue (this) as string; } return null; } } }
// // TemplateInformationViewModel.cs // // Author: // Matt Ward <[email protected]> // // Copyright (c) 2017 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 MonoDevelop.Projects; using MonoDevelop.Core.StringParsing; using System; namespace MonoDevelop.Templating { class TemplateInformationViewModel : IStringTagModel { DotNetProject project; public TemplateInformationViewModel (DotNetProject project) { this.project = project; GenerateDefaults (); } public string Author { get; set; } public string DisplayName { get; set; } public string ShortName { get; set; } public string DefaultProjectName { get; set; } public string Identity { get; set; } public string GroupIdentity { get; set; } public string SourceName { get; set; } public string Language { get; set; } void GenerateDefaults () { Author = AuthorInformation.Default.Name; DefaultProjectName = project.Name; DisplayName = project.Name; ShortName = project.Name; Language = project.LanguageName; GroupIdentity = $"MyTemplate.{project.Name}"; Identity = $"{GroupIdentity}.{project.GetTemplateLanguageName ()}"; SourceName = project.FileName.FileNameWithoutExtension; } public object GetValue (string name) { if (IsMatch (nameof (Author), name)) { return Author; } else if (IsMatch (nameof (DisplayName), name)) { return DisplayName; } else if (IsMatch (nameof (ShortName), name)) { return ShortName; } else if (IsMatch (nameof (DefaultProjectName), name)) { return DefaultProjectName; } else if (IsMatch (nameof (Identity), name)) { return Identity; } else if (IsMatch (nameof (GroupIdentity), name)) { return GroupIdentity; } else if (IsMatch (nameof (SourceName), name)) { return SourceName; } else if (IsMatch (nameof (Language), name)) { return Language; } return null; } static bool IsMatch (string x, string y) { return StringComparer.OrdinalIgnoreCase.Equals (x, y); } } }
mit
C#
32a2a0ed99a23c06c6d7d544a9d44f9c837eeac6
Add BitChoiceGroup component Documentation Comments (#560)
bit-foundation/bit-framework,bit-foundation/bit-framework,bit-foundation/bit-framework,bit-foundation/bit-framework
src/Client/Web/Bit.Client.Web.BlazorUI/Components/Inputs/BitChoiceGroup.razor.cs
src/Client/Web/Bit.Client.Web.BlazorUI/Components/Inputs/BitChoiceGroup.razor.cs
using System; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.AspNetCore.Components; namespace Bit.Client.Web.BlazorUI { public partial class BitChoiceGroup { private readonly List<BitChoiceOption> _options = new(); /// <summary> /// Name of ChoiceGroup, this name is used to group each ChoiceOption into the same logical ChoiceGroup /// </summary> [Parameter] public string Name { get; set; } = Guid.NewGuid().ToString(); /// <summary> /// Value of ChoiceGroup, the value of selected ChoiceOption set on it /// </summary> [Parameter] public string? Value { get; set; } /// <summary> /// The content of ChoiceGroup, common values are ChoiceOption component /// </summary> [Parameter] public RenderFragment? ChildContent { get; set; } /// <summary> /// Callback that is called when the value parameter changed /// </summary> [Parameter] public EventCallback<string> OnValueChange { get; set; } protected override string RootElementClass => "bit-chg"; internal async Task ChangeSelection(BitChoiceOption option) { if (IsEnabled) { foreach (BitChoiceOption item in _options) { item.SetOptionCheckedStatus(item == option); } Value = option.Value; await OnValueChange.InvokeAsync(option.Value); } } internal void RegisterOption(BitChoiceOption option) { if (IsEnabled is false) { option.IsEnabled = false; } _options.Add(option); } internal void UnregisterOption(BitChoiceOption option) { _options.Remove(option); } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.AspNetCore.Components; namespace Bit.Client.Web.BlazorUI { public partial class BitChoiceGroup { private readonly List<BitChoiceOption> _options = new(); [Parameter] public string Name { get; set; } = Guid.NewGuid().ToString(); [Parameter] public string? Value { get; set; } [Parameter] public RenderFragment? ChildContent { get; set; } [Parameter] public EventCallback<string> OnValueChange { get; set; } protected override string RootElementClass => "bit-chg"; internal async Task ChangeSelection(BitChoiceOption option) { if (IsEnabled) { foreach (BitChoiceOption item in _options) { item.SetOptionCheckedStatus(item == option); } Value = option.Value; await OnValueChange.InvokeAsync(option.Value); } } internal void RegisterOption(BitChoiceOption option) { if (IsEnabled is false) { option.IsEnabled = false; } _options.Add(option); } internal void UnregisterOption(BitChoiceOption option) { _options.Remove(option); } } }
mit
C#
2e46a8b1ac3f7251db1936b1da1c4ae5d415c901
Add useful overload for instruction remover
fistak/MaterialColor
Injector/InstructionRemover.cs
Injector/InstructionRemover.cs
using Mono.Cecil; using Mono.Cecil.Cil; using System.Linq; namespace Injector { public class InstructionRemover { public InstructionRemover(ModuleDefinition targetModule) { _targetModule = targetModule; } ModuleDefinition _targetModule; public void ReplaceByNopAt(string typeName, string methodName, int instructionIndex) { var method = CecilHelper.GetMethodDefinition(_targetModule, typeName, methodName); var methodBody = method.Body; ReplaceByNop(methodBody, methodBody.Instructions[instructionIndex]); } public void ReplaceByNop(MethodBody methodBody, Instruction instruction) { methodBody.GetILProcessor().Replace(instruction, Instruction.Create(OpCodes.Nop)); } public void ClearAllButLast(string typeName, string methodName) { var method = CecilHelper.GetMethodDefinition(_targetModule, typeName, methodName); var methodBody = method.Body; ClearAllButLast(methodBody); } public void ClearAllButLast(MethodBody methodBody) { var methodILProcessor = methodBody.GetILProcessor(); for (int i = methodBody.Instructions.Count - 1; i > 0; i--) { methodILProcessor.Remove(methodBody.Instructions.First()); } } } }
using Mono.Cecil; using Mono.Cecil.Cil; using System.Linq; namespace Injector { public class InstructionRemover { public InstructionRemover(ModuleDefinition targetModule) { _targetModule = targetModule; } ModuleDefinition _targetModule; public void ReplaceByNopAt(string typeName, string methodName, int instructionIndex) { var method = CecilHelper.GetMethodDefinition(_targetModule, typeName, methodName); var methodBody = method.Body; ReplaceByNop(methodBody, methodBody.Instructions[instructionIndex]); } public void ReplaceByNop(MethodBody methodBody, Instruction instruction) { methodBody.GetILProcessor().Replace(instruction, Instruction.Create(OpCodes.Nop)); } public void ClearAllButLast(string typeName, string methodName) { var method = CecilHelper.GetMethodDefinition(_targetModule, typeName, methodName); var methodBody = method.Body; var methodILProcessor = methodBody.GetILProcessor(); for (int i = methodBody.Instructions.Count - 1; i > 0; i--) { methodILProcessor.Remove(methodBody.Instructions.First()); } } } }
mit
C#
fe3878304f0a115a6451e24176c102d4adb42d4c
Fix connection bug for fresh environments
davghouse/Daves.DeepDataDuplicator
Daves.DeepDataDuplicator.IntegrationTests/SqlDatabaseSetup.cs
Daves.DeepDataDuplicator.IntegrationTests/SqlDatabaseSetup.cs
using Microsoft.Data.Tools.Schema.Sql.UnitTesting; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Data; using System.Data.SqlClient; using System.Transactions; namespace Daves.DeepDataDuplicator.IntegrationTests { [TestClass] public class SqlDatabaseSetup { [AssemblyInitialize] public static void InitializeAssembly(TestContext testContext) { SqlDatabaseTestClass.TestService.DeployDatabaseProject(); string connectionString; using (var executionContext = SqlDatabaseTestClass.TestService.OpenExecutionContext()) { connectionString = executionContext.Connection.ConnectionString; } using (var transaction = new TransactionScope()) { using (var connection = new SqlConnection(connectionString)) { connection.Open(); using (IDbCommand command = connection.CreateCommand()) { command.CommandText = DeepCopyGenerator.GenerateProcedure( connection: connection, rootTableName: "Nations"); command.ExecuteNonQuery(); } } transaction.Complete(); } } } }
using Microsoft.Data.Tools.Schema.Sql.UnitTesting; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Data; using System.Data.SqlClient; using System.Transactions; namespace Daves.DeepDataDuplicator.IntegrationTests { [TestClass] public class SqlDatabaseSetup { public static readonly string ConnectionString; static SqlDatabaseSetup() { using (var executionContext = SqlDatabaseTestClass.TestService.OpenExecutionContext()) { ConnectionString = executionContext.Connection.ConnectionString; } } [AssemblyInitialize] public static void InitializeAssembly(TestContext testContext) { SqlDatabaseTestClass.TestService.DeployDatabaseProject(); using (var transaction = new TransactionScope()) { using (var connection = new SqlConnection(ConnectionString)) { connection.Open(); using (IDbCommand command = connection.CreateCommand()) { command.CommandText = DeepCopyGenerator.GenerateProcedure( connection: connection, rootTableName: "Nations"); command.ExecuteNonQuery(); } } transaction.Complete(); } } } }
mit
C#
32c650c6413ee6d71cb0358d5cd802b461e63347
fix force node test
adam-mccoy/elasticsearch-net,UdiBen/elasticsearch-net,RossLieberman/NEST,cstlaurent/elasticsearch-net,azubanov/elasticsearch-net,elastic/elasticsearch-net,adam-mccoy/elasticsearch-net,KodrAus/elasticsearch-net,CSGOpenSource/elasticsearch-net,KodrAus/elasticsearch-net,RossLieberman/NEST,UdiBen/elasticsearch-net,UdiBen/elasticsearch-net,CSGOpenSource/elasticsearch-net,TheFireCookie/elasticsearch-net,elastic/elasticsearch-net,azubanov/elasticsearch-net,TheFireCookie/elasticsearch-net,cstlaurent/elasticsearch-net,TheFireCookie/elasticsearch-net,CSGOpenSource/elasticsearch-net,adam-mccoy/elasticsearch-net,RossLieberman/NEST,KodrAus/elasticsearch-net,azubanov/elasticsearch-net,cstlaurent/elasticsearch-net
src/Tests/ClientConcepts/ConnectionPooling/RequestOverrides/RespectsForceNode.cs
src/Tests/ClientConcepts/ConnectionPooling/RequestOverrides/RespectsForceNode.cs
using System; using System.Threading.Tasks; using Elasticsearch.Net; using Tests.Framework; using static Elasticsearch.Net.AuditEvent; namespace Tests.ClientConcepts.ConnectionPooling.RequestOverrides { public class RespectsForceNode { /** == Forcing nodes * Sometimes you might want to fire a single request to a specific node. You can do so using the `ForceNode` * request configuration. This will ignore the pool and not retry. */ [U] public async Task OnlyCallsForcedNode() { var audit = new Auditor(() => Framework.Cluster .Nodes(10) .ClientCalls(r => r.SucceedAlways()) .ClientCalls(r => r.OnPort(9208).FailAlways()) .StaticConnectionPool() .Settings(s => s.DisablePing()) ); audit = await audit.TraceCall( new ClientCall(r => r.ForceNode(new Uri("http://localhost:9208"))) { { BadResponse, 9208 } } ); } } }
using System; using System.Threading.Tasks; using Elasticsearch.Net; using Tests.Framework; using static Elasticsearch.Net.AuditEvent; namespace Tests.ClientConcepts.ConnectionPooling.RequestOverrides { public class RespectsForceNode { /** == Forcing nodes * Sometimes you might want to fire a single request to a specific node. You can do so using the `ForceNode` * request configuration. This will ignore the pool and not retry. */ [U] public async Task OnlyCallsForcedNode() { var audit = new Auditor(() => Framework.Cluster .Nodes(10) .ClientCalls(r => r.SucceedAlways()) .ClientCalls(r => r.OnPort(9220).FailAlways()) .StaticConnectionPool() .Settings(s => s.DisablePing()) ); audit = await audit.TraceCall( new ClientCall(r=>r.ForceNode(new Uri("http://localhost:9220"))) { { BadResponse, 9220 } } ); } } }
apache-2.0
C#
4557f2a42fdd53fb1cce47f7f58f8948d5890be1
update help message
MichaelSimons/cli,nguerrera/cli,JohnChen0/cli,Faizan2304/cli,AbhitejJohn/cli,mylibero/cli,blackdwarf/cli,johnbeisner/cli,ravimeda/cli,naamunds/cli,mlorbetske/cli,Faizan2304/cli,dasMulli/cli,mlorbetske/cli,EdwardBlair/cli,dasMulli/cli,mylibero/cli,AbhitejJohn/cli,MichaelSimons/cli,AbhitejJohn/cli,borgdylan/dotnet-cli,harshjain2/cli,mlorbetske/cli,borgdylan/dotnet-cli,weshaggard/cli,naamunds/cli,nguerrera/cli,jonsequitur/cli,weshaggard/cli,blackdwarf/cli,blackdwarf/cli,borgdylan/dotnet-cli,svick/cli,EdwardBlair/cli,naamunds/cli,dasMulli/cli,harshjain2/cli,borgdylan/dotnet-cli,livarcocc/cli-1,nguerrera/cli,nguerrera/cli,AbhitejJohn/cli,harshjain2/cli,weshaggard/cli,JohnChen0/cli,blackdwarf/cli,weshaggard/cli,svick/cli,johnbeisner/cli,svick/cli,mylibero/cli,MichaelSimons/cli,jonsequitur/cli,livarcocc/cli-1,Faizan2304/cli,jonsequitur/cli,livarcocc/cli-1,jonsequitur/cli,naamunds/cli,EdwardBlair/cli,mlorbetske/cli,mylibero/cli,naamunds/cli,ravimeda/cli,MichaelSimons/cli,mylibero/cli,ravimeda/cli,borgdylan/dotnet-cli,JohnChen0/cli,johnbeisner/cli,MichaelSimons/cli,weshaggard/cli,JohnChen0/cli
src/dotnet/commands/dotnet-help/HelpCommand.cs
src/dotnet/commands/dotnet-help/HelpCommand.cs
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Reflection; using Microsoft.DotNet.Cli.Utils; namespace Microsoft.DotNet.Tools.Help { public class HelpCommand { private const string UsageText = @"Usage: dotnet [host-options] [command] [arguments] [common-options] Arguments: [command] The command to execute [arguments] Arguments to pass to the command [host-options] Options specific to dotnet (host) [common-options] Options common to all commands Common options: -v|--verbose Enable verbose output -h|--help Show help Host options (passed before the command): -v|--verbose Enable verbose output --version Display .NET CLI Version Number --info Display .NET CLI Info Common Commands: new Initialize a basic .NET project restore Restore dependencies specified in the .NET project build Builds a .NET project publish Publishes a .NET project for deployment (including the runtime) run Compiles and immediately executes a .NET project test Runs unit tests using the test runner specified in the project pack Creates a NuGet package"; public static int Run(string[] args) { if (args.Length == 0) { PrintHelp(); return 0; } else { return Cli.Program.Main(new[] { args[0], "--help" }); } } public static void PrintHelp() { PrintVersionHeader(); Reporter.Output.WriteLine(UsageText); } public static void PrintVersionHeader() { var versionString = string.IsNullOrEmpty(Product.Version) ? string.Empty : $" ({Product.Version})"; Reporter.Output.WriteLine(Product.LongName + versionString); } } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Reflection; using Microsoft.DotNet.Cli.Utils; namespace Microsoft.DotNet.Tools.Help { public class HelpCommand { private const string UsageText = @"Usage: dotnet [common-options] [command] [arguments] Arguments: [command] The command to execute [arguments] Arguments to pass to the command Common Options (passed before the command): -v|--verbose Enable verbose output --version Display .NET CLI Version Number --info Display .NET CLI Info Common Commands: new Initialize a basic .NET project restore Restore dependencies specified in the .NET project build Builds a .NET project publish Publishes a .NET project for deployment (including the runtime) run Compiles and immediately executes a .NET project test Runs unit tests using the test runner specified in the project pack Creates a NuGet package"; public static int Run(string[] args) { if (args.Length == 0) { PrintHelp(); return 0; } else { return Cli.Program.Main(new[] { args[0], "--help" }); } } public static void PrintHelp() { PrintVersionHeader(); Reporter.Output.WriteLine(UsageText); } public static void PrintVersionHeader() { var versionString = string.IsNullOrEmpty(Product.Version) ? string.Empty : $" ({Product.Version})"; Reporter.Output.WriteLine(Product.LongName + versionString); } } }
mit
C#
5ab3700ebf44a8d4c81a3bcde4b5a2ba3e3d9de6
Add more meaningful error messages while searching for plugin path
earalov/Skylines-ModTools
Debugger/Utils/FileUtil.cs
Debugger/Utils/FileUtil.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions; using ColossalFramework.Plugins; using ICities; namespace ModTools.Utils { internal static class FileUtil { public static List<string> ListFilesInDirectory(string path, List<string> filesMustBeNull = null) { filesMustBeNull = filesMustBeNull ?? new List<string>(); foreach (var file in Directory.GetFiles(path)) { filesMustBeNull.Add(file); } return filesMustBeNull; } public static string FindPluginPath(Type type) { foreach (var item in PluginManager.instance.GetPluginsInfo()) { try { var instances = item.GetInstances<IUserMod>(); var instance = instances.FirstOrDefault(); if (instance != null && instance.GetType() != type) { continue; } foreach (var file in Directory.GetFiles(item.modPath)) { if (Path.GetExtension(file) == ".dll") { return file; } } } catch { UnityEngine.Debug.LogWarning($"FYI, ModTools failed to check mod {item.name} (published file ID {item.publishedFileID}) while searching for type {type.FullName}. That mod may malfunction." ); } } throw new FileNotFoundException($"Failed to find plugin path of type {type.FullName}"); } public static string LegalizeFileName(string illegal) { if (string.IsNullOrEmpty(illegal)) { return DateTime.Now.ToString("yyyyMMddhhmmss"); } var regexSearch = new string(Path.GetInvalidFileNameChars()); var r = new Regex($"[{Regex.Escape(regexSearch)}]"); return r.Replace(illegal, "_"); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions; using ColossalFramework.Plugins; using ICities; namespace ModTools.Utils { internal static class FileUtil { public static List<string> ListFilesInDirectory(string path, List<string> filesMustBeNull = null) { filesMustBeNull = filesMustBeNull ?? new List<string>(); foreach (var file in Directory.GetFiles(path)) { filesMustBeNull.Add(file); } return filesMustBeNull; } public static string FindPluginPath(Type type) { foreach (var item in PluginManager.instance.GetPluginsInfo()) { var instances = item.GetInstances<IUserMod>(); var instance = instances.FirstOrDefault(); if (instance != null && instance.GetType() != type) { continue; } foreach (var file in Directory.GetFiles(item.modPath)) { if (Path.GetExtension(file) == ".dll") { return file; } } } throw new FileNotFoundException("Failed to find assembly!"); } public static string LegalizeFileName(string illegal) { if (string.IsNullOrEmpty(illegal)) { return DateTime.Now.ToString("yyyyMMddhhmmss"); } var regexSearch = new string(Path.GetInvalidFileNameChars()); var r = new Regex($"[{Regex.Escape(regexSearch)}]"); return r.Replace(illegal, "_"); } } }
mit
C#
df31bef8820d3513dd6d17a6cff4d07f5780de31
Add help comment about test location (#82)
googleapis/gapic-generator-csharp,googleapis/gapic-generator-csharp
Google.Api.Generator.Tests/ProtoTests/ServerStreaming/Testing.ServerStreaming/ServerStreamingClient.cs
Google.Api.Generator.Tests/ProtoTests/ServerStreaming/Testing.ServerStreaming/ServerStreamingClient.cs
using gaxgrpc = Google.Api.Gax.Grpc; namespace Testing.ServerStreaming { public abstract class ServerStreamingClient { // Class generation is tested in `BasicServerStreaming`. public abstract class SignatureMethodStream : gaxgrpc::ServerStreamingBase<Response> { } public SignatureMethodStream SignatureMethod(Request request, gaxgrpc::CallSettings callSettings = null) => null; // TEST_START /// <summary> /// Test a server-streaming RPC with a method signature. /// </summary> /// <param name="name"> /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The server stream.</returns> public virtual SignatureMethodStream SignatureMethod(string name, gaxgrpc::CallSettings callSettings = null) => SignatureMethod(new Request { Name = name ?? "", }, callSettings); // TEST_END public abstract class ResourcedMethodStream : gaxgrpc::ServerStreamingBase<Response> { } public ResourcedMethodStream ResourcedMethod(ResourceRequest request, gaxgrpc::CallSettings callSettings = null) => null; // TEST_START /// <summary> /// Test a server-streaming RPC with a method signature and resource-name. /// </summary> /// <param name="name"> /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The server stream.</returns> public virtual ResourcedMethodStream ResourcedMethod(string name, gaxgrpc::CallSettings callSettings = null) => ResourcedMethod(new ResourceRequest { Name = name ?? "", }, callSettings); /// <summary> /// Test a server-streaming RPC with a method signature and resource-name. /// </summary> /// <param name="name"> /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The server stream.</returns> public virtual ResourcedMethodStream ResourcedMethod(ResourceName name, gaxgrpc::CallSettings callSettings = null) => ResourcedMethod(new ResourceRequest { ResourceName = name, }, callSettings); // TEST_END } }
using gaxgrpc = Google.Api.Gax.Grpc; namespace Testing.ServerStreaming { public abstract class ServerStreamingClient { public abstract class SignatureMethodStream : gaxgrpc::ServerStreamingBase<Response> { } public SignatureMethodStream SignatureMethod(Request request, gaxgrpc::CallSettings callSettings = null) => null; // TEST_START /// <summary> /// Test a server-streaming RPC with a method signature. /// </summary> /// <param name="name"> /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The server stream.</returns> public virtual SignatureMethodStream SignatureMethod(string name, gaxgrpc::CallSettings callSettings = null) => SignatureMethod(new Request { Name = name ?? "", }, callSettings); // TEST_END public abstract class ResourcedMethodStream : gaxgrpc::ServerStreamingBase<Response> { } public ResourcedMethodStream ResourcedMethod(ResourceRequest request, gaxgrpc::CallSettings callSettings = null) => null; // TEST_START /// <summary> /// Test a server-streaming RPC with a method signature and resource-name. /// </summary> /// <param name="name"> /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The server stream.</returns> public virtual ResourcedMethodStream ResourcedMethod(string name, gaxgrpc::CallSettings callSettings = null) => ResourcedMethod(new ResourceRequest { Name = name ?? "", }, callSettings); /// <summary> /// Test a server-streaming RPC with a method signature and resource-name. /// </summary> /// <param name="name"> /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The server stream.</returns> public virtual ResourcedMethodStream ResourcedMethod(ResourceName name, gaxgrpc::CallSettings callSettings = null) => ResourcedMethod(new ResourceRequest { ResourceName = name, }, callSettings); // TEST_END } }
apache-2.0
C#
20754426cde51331c05554c29048d0681bbe58d0
Use SyntaxFactoryWriter in RoslynAssert.Ast()
JohanLarsson/Gu.Roslyn.Asserts
Gu.Roslyn.Asserts/RoslynAssert.Ast.cs
Gu.Roslyn.Asserts/RoslynAssert.Ast.cs
namespace Gu.Roslyn.Asserts { using Microsoft.CodeAnalysis; public static partial class RoslynAssert { /// <summary> /// Serializes the syntax tree and compares the strings. /// This can be useful when having trouble getting whitespace right. /// </summary> /// <typeparam name="T">The node type.</typeparam> /// <param name="expected">The expected shape of the AST.</param> /// <param name="actual">The actual node.</param> public static void Ast<T>(T expected, T actual) where T : SyntaxNode { CodeAssert.AreEqual(SyntaxFactoryWriter.Serialize(expected), SyntaxFactoryWriter.Serialize(actual)); } } }
namespace Gu.Roslyn.Asserts { using Microsoft.CodeAnalysis; public static partial class RoslynAssert { /// <summary> /// Serializes the syntax tree and compares the strings. /// This can be useful when having trouble getting whitespace right. /// </summary> /// <typeparam name="T">The node type.</typeparam> /// <param name="expected">The expected shape of the AST.</param> /// <param name="actual">The actual node.</param> /// <param name="settings"><see cref="AstWriterSettings"/>.</param> public static void Ast<T>(T expected, T actual, AstWriterSettings settings = null) where T : SyntaxNode { CodeAssert.AreEqual(AstWriter.Serialize(expected, settings), AstWriter.Serialize(actual, settings)); } } }
mit
C#
cd000535eb44c1e80ca0703069f011b992c8e6ec
Add ToString() to LogEntry to help debugging
badescuga/kudu,sitereactor/kudu,shibayan/kudu,kali786516/kudu,EricSten-MSFT/kudu,barnyp/kudu,EricSten-MSFT/kudu,barnyp/kudu,EricSten-MSFT/kudu,puneet-gupta/kudu,projectkudu/kudu,chrisrpatterson/kudu,uQr/kudu,chrisrpatterson/kudu,barnyp/kudu,sitereactor/kudu,sitereactor/kudu,uQr/kudu,chrisrpatterson/kudu,bbauya/kudu,shibayan/kudu,projectkudu/kudu,puneet-gupta/kudu,shibayan/kudu,uQr/kudu,kali786516/kudu,barnyp/kudu,juvchan/kudu,badescuga/kudu,shibayan/kudu,YOTOV-LIMITED/kudu,puneet-gupta/kudu,juvchan/kudu,bbauya/kudu,projectkudu/kudu,sitereactor/kudu,kali786516/kudu,EricSten-MSFT/kudu,juvchan/kudu,YOTOV-LIMITED/kudu,bbauya/kudu,juvchan/kudu,badescuga/kudu,YOTOV-LIMITED/kudu,juvchan/kudu,puneet-gupta/kudu,EricSten-MSFT/kudu,uQr/kudu,badescuga/kudu,badescuga/kudu,shibayan/kudu,sitereactor/kudu,projectkudu/kudu,projectkudu/kudu,chrisrpatterson/kudu,bbauya/kudu,kali786516/kudu,YOTOV-LIMITED/kudu,puneet-gupta/kudu
Kudu.Contracts/Deployment/LogEntry.cs
Kudu.Contracts/Deployment/LogEntry.cs
using System; using System.Diagnostics.CodeAnalysis; using Kudu.Contracts.Infrastructure; using Newtonsoft.Json; namespace Kudu.Core.Deployment { public class LogEntry : INamedObject { [JsonIgnore] [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "to provide ARM spceific name")] string INamedObject.Name { get { return Id; } } [JsonProperty(PropertyName = "log_time")] public DateTime LogTime { get; set; } [JsonProperty(PropertyName = "id")] public string Id { get; set; } [JsonProperty(PropertyName = "message")] public string Message { get; set; } [JsonProperty(PropertyName = "type")] public LogEntryType Type { get; set; } [JsonProperty(PropertyName = "details_url")] public Uri DetailsUrl { get; set; } [JsonIgnore] public bool HasDetails { get; set; } public LogEntry() { } public LogEntry(DateTime logTime, string id, string message, LogEntryType type) { LogTime = logTime; Id = id; Message = message; Type = type; } public override string ToString() { return Message; } } }
using System; using System.Diagnostics.CodeAnalysis; using Kudu.Contracts.Infrastructure; using Newtonsoft.Json; namespace Kudu.Core.Deployment { public class LogEntry : INamedObject { [JsonIgnore] [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "to provide ARM spceific name")] string INamedObject.Name { get { return Id; } } [JsonProperty(PropertyName = "log_time")] public DateTime LogTime { get; set; } [JsonProperty(PropertyName = "id")] public string Id { get; set; } [JsonProperty(PropertyName = "message")] public string Message { get; set; } [JsonProperty(PropertyName = "type")] public LogEntryType Type { get; set; } [JsonProperty(PropertyName = "details_url")] public Uri DetailsUrl { get; set; } [JsonIgnore] public bool HasDetails { get; set; } public LogEntry() { } public LogEntry(DateTime logTime, string id, string message, LogEntryType type) { LogTime = logTime; Id = id; Message = message; Type = type; } } }
apache-2.0
C#
a4c3a17dd7f6e4ecace410c043b52dae73012138
Bump version
Deadpikle/NetSparkle,Deadpikle/NetSparkle
AssemblyInfo.cs
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("NetSparkle")] [assembly: AssemblyDescription("NetSparkle is an auto update framework for .NET developers")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("NetSparkle")] [assembly: AssemblyCopyright("Portions Copyright © Dirk Eisenberg 2010, Deadpikle 2017")] [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("279448fc-5103-475e-b209-68f3268df7b5")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.13.0")] [assembly: AssemblyFileVersion("0.13.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("NetSparkle")] [assembly: AssemblyDescription("NetSparkle is an auto update framework for .NET developers")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("NetSparkle")] [assembly: AssemblyCopyright("Portions Copyright © Dirk Eisenberg 2010, Deadpikle 2017")] [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("279448fc-5103-475e-b209-68f3268df7b5")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.12.0")] [assembly: AssemblyFileVersion("0.12.0")]
mit
C#
02099729a4fcb867f3bcb0ecaf7b04e605aa53ae
Bump for v0.7.0
jrick/Paymetheus,decred/Paymetheus
Paymetheus/Properties/AssemblyInfo.cs
Paymetheus/Properties/AssemblyInfo.cs
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // 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("Paymetheus Decred Wallet")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Paymetheus")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyMetadata("Organization", "Decred")] // 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)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.7.0.0")] [assembly: AssemblyFileVersion("0.7.0.0")]
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // 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("Paymetheus Decred Wallet")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Paymetheus")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyMetadata("Organization", "Decred")] // 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)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.6.1.0")] [assembly: AssemblyFileVersion("0.6.1.0")]
isc
C#
660a86e83e9c7fa5ce0aac39e55e127b85b146ed
Make sure it writes to a place that will not cause errors in release.
rytz/MatterControl,jlewin/MatterControl,rytz/MatterControl,rytz/MatterControl,tellingmachine/MatterControl,gregory-diaz/MatterControl,ddpruitt/MatterControl,mmoening/MatterControl,larsbrubaker/MatterControl,unlimitedbacon/MatterControl,larsbrubaker/MatterControl,unlimitedbacon/MatterControl,ddpruitt/MatterControl,gregory-diaz/MatterControl,mmoening/MatterControl,larsbrubaker/MatterControl,CodeMangler/MatterControl,unlimitedbacon/MatterControl,tellingmachine/MatterControl,larsbrubaker/MatterControl,mmoening/MatterControl,MatterHackers/MatterControl,CodeMangler/MatterControl,ddpruitt/MatterControl,MatterHackers/MatterControl,unlimitedbacon/MatterControl,CodeMangler/MatterControl,jlewin/MatterControl,jlewin/MatterControl,MatterHackers/MatterControl,jlewin/MatterControl
CrashTracker.cs
CrashTracker.cs
/* Copyright (c) 2014, Lars Brubaker All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. */ #define USE_CRASH_TRACKER using System.IO; using MatterHackers.MatterControl.DataStorage; namespace MatterHackers.MatterControl { public static class CrashTracker { static string outputFilename; public static void Reset() { outputFilename = Path.Combine(DataStorage.ApplicationDataStorage.Instance.ApplicationUserDataPath, "CrashTracker.txt"); #if USE_CRASH_TRACKER // Create the file to clear its contents using (StreamWriter sw = File.CreateText(outputFilename)) { sw.WriteLine("Hello"); sw.WriteLine("And"); sw.WriteLine("Welcome"); } #endif } public static void Write(string info) { #if USE_CRASH_TRACKER using (StreamWriter sw = File.AppendText(outputFilename)) { sw.WriteLine(info); } #endif } } }
/* Copyright (c) 2014, Lars Brubaker All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. */ #define USE_CRASH_TRACKER using System.IO; namespace MatterHackers.MatterControl { public static class CrashTracker { static readonly string outputFilename = "CrashTracker.txt"; public static void Reset() { #if USE_CRASH_TRACKER // Create the file to clear its contents using (StreamWriter sw = File.CreateText(outputFilename)) { sw.WriteLine("Hello"); sw.WriteLine("And"); sw.WriteLine("Welcome"); } #endif } public static void Write(string info) { #if USE_CRASH_TRACKER using (StreamWriter sw = File.AppendText(outputFilename)) { sw.WriteLine(info); } #endif } } }
bsd-2-clause
C#
242ce75fee7ade56fdbc62a9b7dfad900d729273
Improve test coverage of LineColumn and ParseResult.
Faithlife/Parsing
tests/Faithlife.Parsing.Tests/CommonTests.cs
tests/Faithlife.Parsing.Tests/CommonTests.cs
using System.Linq; using Xunit; namespace Faithlife.Parsing.Tests { public class CommonTests { [Fact] public void ResultShouldAlwaysSucceed() { Parser.Success(true).TryParse("").ShouldSucceed(true, 0); Parser.Success(true).TryParse("x").ShouldSucceed(true, 0); Parser.Success(true).TryParse("xabc").ShouldSucceed(true, 0); } [Fact] public void EndShouldSucceedAtEnd() { Parser.Success(true).End().TryParse("x", 1).ShouldSucceed(true, 1); } [Fact] public void EndShouldFailNotAtEnd() { Parser.Success(true).End().TryParse("xabc", 1).ShouldFail(1); } [Fact] public void ParseThrowsOnFailure() { try { Parser.Success(true).End().Parse("xabc", 1); Assert.True(false); } catch (ParseException exception) { exception.Result.NextPosition.Index.ShouldBe(1); } } [Fact] public void NamedShouldNameFailure() { var namedFailure = Parser.String("abc").Named("epic").TryParse("xabc").GetNamedFailures().Single(); namedFailure.Name.ShouldBe("epic"); namedFailure.Position.Index.ShouldBe(0); } [Fact] public void PositionedShouldPositionSuccess() { var positioned = Parser.String("ab").Positioned().Parse("xabc", 1); positioned.Position.Index.ShouldBe(1); positioned.Length.ShouldBe(2); } [Fact] public void LineColumnEquality() { var a1 = new LineColumn(1, 2); var a2 = new LineColumn(1, 2); var b = new LineColumn(2, 1); (a1 == a2).ShouldBe(true); (a1 != b).ShouldBe(true); Equals(a1, b).ShouldBe(false); a1.GetHashCode().ShouldBe(a2.GetHashCode()); } [Fact] public void ParseResult_GetValueOrDefault() { ParseResult.Success(1, new TextPosition()).GetValueOrDefault().ShouldBe(1); ParseResult.Success(1, new TextPosition()).GetValueOrDefault(2).ShouldBe(1); ParseResult.Failure<int>(new TextPosition()).GetValueOrDefault().ShouldBe(0); ParseResult.Failure<int>(new TextPosition()).GetValueOrDefault(2).ShouldBe(2); } [Fact] public void ParseResult_ToMessage() { Parser.Char('a').TryParse("a").ToMessage().ShouldBe("success at 1,2"); Parser.Char('a').TryParse("b").ToMessage().ShouldBe("failure at 1,1"); Parser.Char('a').Named("'a'").TryParse("b").ToMessage().ShouldBe("failure at 1,1; expected 'a' at 1,1"); } } }
using System.Linq; using Xunit; namespace Faithlife.Parsing.Tests { public class CommonTests { [Fact] public void ResultShouldAlwaysSucceed() { Parser.Success(true).TryParse("").ShouldSucceed(true, 0); Parser.Success(true).TryParse("x").ShouldSucceed(true, 0); Parser.Success(true).TryParse("xabc").ShouldSucceed(true, 0); } [Fact] public void EndShouldSucceedAtEnd() { Parser.Success(true).End().TryParse("x", 1).ShouldSucceed(true, 1); } [Fact] public void EndShouldFailNotAtEnd() { Parser.Success(true).End().TryParse("xabc", 1).ShouldFail(1); } [Fact] public void ParseThrowsOnFailure() { try { Parser.Success(true).End().Parse("xabc", 1); Assert.True(false); } catch (ParseException exception) { exception.Result.NextPosition.Index.ShouldBe(1); } } [Fact] public void NamedShouldNameFailure() { var namedFailure = Parser.String("abc").Named("epic").TryParse("xabc").GetNamedFailures().Single(); namedFailure.Name.ShouldBe("epic"); namedFailure.Position.Index.ShouldBe(0); } [Fact] public void PositionedShouldPositionSuccess() { var positioned = Parser.String("ab").Positioned().Parse("xabc", 1); positioned.Position.Index.ShouldBe(1); positioned.Length.ShouldBe(2); } } }
mit
C#
23800bbd9ebb7b700d1ae58c5f611820e6578da7
Update comment
Archie-Yang/PcscDotNet
src/PcscDotNet/SCardReaderGroupExtensions.cs
src/PcscDotNet/SCardReaderGroupExtensions.cs
namespace PcscDotNet { /// <summary> /// Extension method of SCardReaderGroup. /// </summary> public static class SCardReaderGroupExtensions { /// <summary> /// Defined value of SCardReaderGroup.All. /// </summary> private const string All = "SCard$AllReaders\000"; /// <summary> /// Defined value of SCardReaderGroup.Default. /// </summary> private const string Default = "SCard$DefaultReaders\000"; /// <summary> /// Defined value of SCardReaderGroup.Local. /// </summary> private const string Local = "SCard$LocalReaders\000"; /// <summary> /// Defined value of SCardReaderGroup.System. /// </summary> private const string System = "SCard$SystemReaders\000"; /// <summary> /// Gets defined value for specific SCardReaderGroup. /// </summary> /// <param name="group">SCardReaderGroup value.</param> /// <returns>Defined value.</returns> public static string GetDefinedValue(this SCardReaderGroup group) { switch (group) { case SCardReaderGroup.All: return All; case SCardReaderGroup.Defualt: return Default; case SCardReaderGroup.Local: return Local; case SCardReaderGroup.System: return System; default: return null; } } } }
namespace PcscDotNet { /// <summary> /// Extension method of SCardReaderGroup. /// </summary> public static class SCardReaderGroupExtensions { /// <summary> /// Defined value of SCardReaderGroup.All. /// </summary> private const string All = "SCard$AllReaders\000"; /// <summary> /// Defined value of SCardReaderGroup.Default. /// </summary> private const string Default = "SCard$DefaultReaders\000"; /// <summary> /// Defined value of SCardReaderGroup.Local. /// </summary> private const string Local = "SCard$LocalReaders\000"; /// <summary> /// Defined value of SCardReaderGroup.System. /// </summary> private const string System = "SCard$SystemReaders\000"; /// <summary> /// Gets defined value of SCardReaderGroup. /// </summary> /// <param name="group">SCardReaderGroup value.</param> /// <returns>Defined value.</returns> public static string GetDefinedValue(this SCardReaderGroup group) { switch (group) { case SCardReaderGroup.All: return All; case SCardReaderGroup.Defualt: return Default; case SCardReaderGroup.Local: return Local; case SCardReaderGroup.System: return System; default: return null; } } } }
mit
C#
fc50f1f149f7f66a6a7911f71fec94d4631136d1
Update ConvertHelper
WeihanLi/WeihanLi.Common,WeihanLi/WeihanLi.Common,WeihanLi/WeihanLi.Common
src/WeihanLi.Common/Helpers/ConvertHelper.cs
src/WeihanLi.Common/Helpers/ConvertHelper.cs
using System.Net; namespace WeihanLi.Common.Helpers; public static class ConvertHelper { public static EndPoint ToEndPoint(string ipOrHost, int port) { if (IPAddress.TryParse(ipOrHost, out var address)) { return new IPEndPoint(address, port); } return new DnsEndPoint(ipOrHost, port); } }
using System.Net; namespace WeihanLi.Common.Helpers; public static class ConvertHelper { /// <summary> /// ip或域名转换为 EndPoint /// </summary> /// <param name="ipOrHost">ipOrHost</param> /// <param name="port">port</param> /// <returns>EndPoint</returns> public static EndPoint ToEndPoint(string ipOrHost, int port) { if (IPAddress.TryParse(ipOrHost, out var address)) { return new IPEndPoint(address, port); } return new DnsEndPoint(ipOrHost, port); } }
mit
C#
0f1aac396a6f36b04fb8881e37e566570c4d6f0e
Fix do_after cancellations
space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14
Content.Shared/DoAfter/SharedDoAfterComponent.cs
Content.Shared/DoAfter/SharedDoAfterComponent.cs
using Robust.Shared.GameStates; using Robust.Shared.Map; using Robust.Shared.Serialization; namespace Content.Shared.DoAfter { [NetworkedComponent()] public abstract class SharedDoAfterComponent : Component { } [Serializable, NetSerializable] public sealed class DoAfterComponentState : ComponentState { public List<ClientDoAfter> DoAfters { get; } public DoAfterComponentState(List<ClientDoAfter> doAfters) { DoAfters = doAfters; } } [Serializable, NetSerializable] public sealed class CancelledDoAfterMessage : EntityEventArgs { public EntityUid Uid; public byte ID { get; } public CancelledDoAfterMessage(EntityUid uid, byte id) { Uid = uid; ID = id; } } /// <summary> /// We send a trimmed-down version of the DoAfter for the client for it to use. /// </summary> [Serializable, NetSerializable] public sealed class ClientDoAfter { // To see what these do look at DoAfter and DoAfterEventArgs public byte ID { get; } public TimeSpan StartTime { get; } public EntityCoordinates UserGrid { get; } public EntityCoordinates TargetGrid { get; } public EntityUid? Target { get; } public float Delay { get; } // TODO: The other ones need predicting public bool BreakOnUserMove { get; } public bool BreakOnTargetMove { get; } public float MovementThreshold { get; } public ClientDoAfter(byte id, EntityCoordinates userGrid, EntityCoordinates targetGrid, TimeSpan startTime, float delay, bool breakOnUserMove, bool breakOnTargetMove, float movementThreshold, EntityUid? target = null) { ID = id; UserGrid = userGrid; TargetGrid = targetGrid; StartTime = startTime; Delay = delay; BreakOnUserMove = breakOnUserMove; BreakOnTargetMove = breakOnTargetMove; MovementThreshold = movementThreshold; Target = target; } } }
using Robust.Shared.GameStates; using Robust.Shared.Map; using Robust.Shared.Serialization; namespace Content.Shared.DoAfter { [NetworkedComponent()] public abstract class SharedDoAfterComponent : Component { } [Serializable, NetSerializable] public sealed class DoAfterComponentState : ComponentState { public List<ClientDoAfter> DoAfters { get; } public DoAfterComponentState(List<ClientDoAfter> doAfters) { DoAfters = doAfters; } } [Serializable, NetSerializable] public sealed class CancelledDoAfterMessage : EntityEventArgs { public EntityUid Uid; public byte ID { get; } public CancelledDoAfterMessage(EntityUid uid, byte id) { ID = id; } } /// <summary> /// We send a trimmed-down version of the DoAfter for the client for it to use. /// </summary> [Serializable, NetSerializable] public sealed class ClientDoAfter { // To see what these do look at DoAfter and DoAfterEventArgs public byte ID { get; } public TimeSpan StartTime { get; } public EntityCoordinates UserGrid { get; } public EntityCoordinates TargetGrid { get; } public EntityUid? Target { get; } public float Delay { get; } // TODO: The other ones need predicting public bool BreakOnUserMove { get; } public bool BreakOnTargetMove { get; } public float MovementThreshold { get; } public ClientDoAfter(byte id, EntityCoordinates userGrid, EntityCoordinates targetGrid, TimeSpan startTime, float delay, bool breakOnUserMove, bool breakOnTargetMove, float movementThreshold, EntityUid? target = null) { ID = id; UserGrid = userGrid; TargetGrid = targetGrid; StartTime = startTime; Delay = delay; BreakOnUserMove = breakOnUserMove; BreakOnTargetMove = breakOnTargetMove; MovementThreshold = movementThreshold; Target = target; } } }
mit
C#
9f53b7d6e9cf522464901e8aed0c9e2b01cdce36
Fix up Octokit.Rx
chunkychode/octokit.net,adamralph/octokit.net,gdziadkiewicz/octokit.net,darrelmiller/octokit.net,SamTheDev/octokit.net,gabrielweyer/octokit.net,octokit-net-test/octokit.net,editor-tools/octokit.net,rlugojr/octokit.net,fffej/octokit.net,ivandrofly/octokit.net,Sarmad93/octokit.net,devkhan/octokit.net,nsrnnnnn/octokit.net,hitesh97/octokit.net,eriawan/octokit.net,cH40z-Lord/octokit.net,chunkychode/octokit.net,Red-Folder/octokit.net,kolbasov/octokit.net,shana/octokit.net,magoswiat/octokit.net,editor-tools/octokit.net,gdziadkiewicz/octokit.net,mminns/octokit.net,geek0r/octokit.net,TattsGroup/octokit.net,devkhan/octokit.net,khellang/octokit.net,hahmed/octokit.net,forki/octokit.net,thedillonb/octokit.net,khellang/octokit.net,M-Zuber/octokit.net,takumikub/octokit.net,ivandrofly/octokit.net,octokit/octokit.net,shiftkey-tester/octokit.net,alfhenrik/octokit.net,naveensrinivasan/octokit.net,dlsteuer/octokit.net,michaKFromParis/octokit.net,fake-organization/octokit.net,eriawan/octokit.net,kdolan/octokit.net,mminns/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,thedillonb/octokit.net,daukantas/octokit.net,octokit-net-test-org/octokit.net,brramos/octokit.net,octokit/octokit.net,bslliw/octokit.net,shiftkey-tester/octokit.net,nsnnnnrn/octokit.net,rlugojr/octokit.net,SLdragon1989/octokit.net,SmithAndr/octokit.net,TattsGroup/octokit.net,SmithAndr/octokit.net,octokit-net-test-org/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,shiftkey/octokit.net,gabrielweyer/octokit.net,SamTheDev/octokit.net,shana/octokit.net,dampir/octokit.net,Sarmad93/octokit.net,hahmed/octokit.net,ChrisMissal/octokit.net,dampir/octokit.net,shiftkey/octokit.net,M-Zuber/octokit.net,alfhenrik/octokit.net
Octokit.Reactive/Helpers/ConnectionExtensions.cs
Octokit.Reactive/Helpers/ConnectionExtensions.cs
using System; using System.Collections.Generic; using System.Reactive.Linq; using System.Reactive.Threading.Tasks; namespace Octokit.Reactive.Internal { internal static class ConnectionExtensions { public static IObservable<T> GetAndFlattenAllPages<T>(this IConnection connection, Uri url, IDictionary<string, string> parameters = null, string accepts = null) { return GetPages(url, parameters, (pageUrl, pageParams) => connection.Get<List<T>>(pageUrl, pageParams, accepts).ToObservable()); } static IObservable<T> GetPages<T>(Uri uri, IDictionary<string, string> parameters, Func<Uri, IDictionary<string, string>, IObservable<IResponse<List<T>>>> getPageFunc) { return getPageFunc(uri, parameters).Expand(resp => { var nextPageUrl = resp.ApiInfo.GetNextPageUrl(); return nextPageUrl == null ? Observable.Empty<IResponse<List<T>>>() : Observable.Defer(() => getPageFunc(nextPageUrl, null)); }) .Where(resp => resp != null) .SelectMany(resp => resp.BodyAsObject); } } }
using System; using System.Collections.Generic; using System.Reactive.Linq; using System.Reactive.Threading.Tasks; namespace Octokit.Reactive.Internal { internal static class ConnectionExtensions { public static IObservable<T> GetAndFlattenAllPages<T>(this IConnection connection, Uri url, IDictionary<string, string> parameters = null, string accepts = null) { return GetPages(url, parameters, (pageUrl, pageParams) => connection.GetAsync<List<T>>(pageUrl, pageParams, accepts).ToObservable()); } static IObservable<T> GetPages<T>(Uri uri, IDictionary<string, string> parameters, Func<Uri, IDictionary<string, string>, IObservable<IResponse<List<T>>>> getPageFunc) { return getPageFunc(uri, parameters).Expand(resp => { var nextPageUrl = resp.ApiInfo.GetNextPageUrl(); return nextPageUrl == null ? Observable.Empty<IResponse<List<T>>>() : Observable.Defer(() => getPageFunc(nextPageUrl, null)); }) .Where(resp => resp != null) .SelectMany(resp => resp.BodyAsObject); } } }
mit
C#
085739cf562b569cb9effc69261ba3af8a1c22e2
Fix NSwag to quote tool path
nuke-build/nuke,nuke-build/nuke,nuke-build/nuke,nuke-build/nuke
source/Nuke.Common/Tools/NSwag/NSwagSettings.cs
source/Nuke.Common/Tools/NSwag/NSwagSettings.cs
// Copyright 2019 Maintainers of NUKE. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.Linq; using JetBrains.Annotations; using Nuke.Common.IO; using Nuke.Common.Tooling; using Nuke.Common.Tools.DotNet; using Nuke.Common.Utilities; namespace Nuke.Common.Tools.NSwag { [PublicAPI] [Serializable] public class NSwagSettings : ToolSettings { /// <summary>The runtime of the nswag tool to use.</summary> public string NSwagRuntime { get; set; } = NSwagTasks.Runtime.Win.ToString(); private bool IsNetCore => NSwagRuntime != null && NSwagRuntime.StartsWith("NetCore", StringComparison.OrdinalIgnoreCase); public override Action<OutputType, string> CustomLogger { get; } [NotNull] protected override Arguments ConfigureArguments([NotNull] Arguments arguments) { if (!IsNetCore) return base.ConfigureArguments(arguments); var args = new Arguments(); args.Add($"{GetNetCoreDllPath(NSwagRuntime).DoubleQuoteIfNeeded()}"); args.Concatenate(arguments); return base.ConfigureArguments(args); } protected string GetToolPath() { if (IsNetCore) return DotNetTasks.DotNetPath; return GetPackageFrameworkDir() / "Win" / "NSwag.exe"; } protected string GetNSwagRuntime() { return string.Empty; } private string GetNetCoreDllPath(string runtime) { return GetPackageFrameworkDir() / runtime / "dotnet-nswag.dll"; } private PathConstruction.AbsolutePath GetPackageFrameworkDir() { var package = NuGetPackageResolver.GetLocalInstalledPackage("nswag.msbuild", ToolPathResolver.NuGetPackagesConfigFile); return package.Directory / (package.Version.Version >= new Version(major: 11, minor: 18, build: 1) ? "tools" : "build"); } } }
// Copyright 2019 Maintainers of NUKE. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.Linq; using JetBrains.Annotations; using Nuke.Common.IO; using Nuke.Common.Tooling; using Nuke.Common.Tools.DotNet; namespace Nuke.Common.Tools.NSwag { [PublicAPI] [Serializable] public class NSwagSettings : ToolSettings { /// <summary>The runtime of the nswag tool to use.</summary> public string NSwagRuntime { get; set; } = NSwagTasks.Runtime.Win.ToString(); private bool _isNetCore => NSwagRuntime != null && NSwagRuntime.StartsWith("NetCore", StringComparison.OrdinalIgnoreCase); public override Action<OutputType, string> CustomLogger { get; } [NotNull] protected override Arguments ConfigureArguments([NotNull] Arguments arguments) { if (!_isNetCore) return base.ConfigureArguments(arguments); var args = new Arguments(); args.Add($"{GetNetCoreDllPath(NSwagRuntime)}"); args.Concatenate(arguments); return base.ConfigureArguments(args); } protected string GetToolPath() { if (_isNetCore) return DotNetTasks.DotNetPath; return GetPackageFrameworkDir() / "Win" / "NSwag.exe"; } protected string GetNSwagRuntime() { return string.Empty; } private string GetNetCoreDllPath(string runtime) { return GetPackageFrameworkDir() / runtime / "dotnet-nswag.dll"; } private PathConstruction.AbsolutePath GetPackageFrameworkDir() { var package = NuGetPackageResolver.GetLocalInstalledPackage("nswag.msbuild", ToolPathResolver.NuGetPackagesConfigFile); return package.Directory / (package.Version.Version >= new Version(major: 11, minor: 18, build: 1) ? "tools" : "build"); } } }
mit
C#
5e2bce869a4d341ff7f6fd39e8e853088ca86ec6
Update assembly info
KevinDockx/JsonPatch
src/Marvin.JsonPatch/Properties/AssemblyInfo.cs
src/Marvin.JsonPatch/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("Json Patch (RFC 6902) support for .NET")] [assembly: AssemblyDescription("JSON Patch (RFC 6902) support for .NET to easily allow & apply partial REST-ful service (through Web API) updates from any client (portable class library).")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Kevin Dockx (Marvin)")] [assembly: AssemblyProduct("Json Patch (RFC 6902) support for .NET")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.9.0")] [assembly: AssemblyFileVersion("0.9.0")] [assembly: AssemblyInformationalVersion("0.9.0")]
using System.Resources; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Json Patch (RFC 6902) support for .NET")] [assembly: AssemblyDescription("JSON Patch (RFC 6902) support for .NET to easily allow & apply partial REST-ful service (through Web API) updates from any client (portable class library).")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Kevin Dockx (Marvin)")] [assembly: AssemblyProduct("Json Patch (RFC 6902) support for .NET")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.7.0")] [assembly: AssemblyFileVersion("0.7.0")] [assembly: AssemblyInformationalVersion("0.7.0")]
mit
C#
9810ec02deae2182c0528abcbdd37228ab139820
Apply NH-2335 (by Patrick Earl)
livioc/nhibernate-core,lnu/nhibernate-core,fredericDelaporte/nhibernate-core,ManufacturingIntelligence/nhibernate-core,alobakov/nhibernate-core,gliljas/nhibernate-core,hazzik/nhibernate-core,nkreipke/nhibernate-core,alobakov/nhibernate-core,livioc/nhibernate-core,nhibernate/nhibernate-core,gliljas/nhibernate-core,nkreipke/nhibernate-core,fredericDelaporte/nhibernate-core,RogerKratz/nhibernate-core,gliljas/nhibernate-core,nhibernate/nhibernate-core,RogerKratz/nhibernate-core,nhibernate/nhibernate-core,hazzik/nhibernate-core,gliljas/nhibernate-core,ngbrown/nhibernate-core,alobakov/nhibernate-core,hazzik/nhibernate-core,livioc/nhibernate-core,nhibernate/nhibernate-core,lnu/nhibernate-core,nkreipke/nhibernate-core,hazzik/nhibernate-core,fredericDelaporte/nhibernate-core,RogerKratz/nhibernate-core,ngbrown/nhibernate-core,RogerKratz/nhibernate-core,ManufacturingIntelligence/nhibernate-core,ngbrown/nhibernate-core,ManufacturingIntelligence/nhibernate-core,lnu/nhibernate-core,fredericDelaporte/nhibernate-core
src/NHibernate/Context/ReflectiveHttpContext.cs
src/NHibernate/Context/ReflectiveHttpContext.cs
using System; using System.Collections; using System.Linq.Expressions; using System.Reflection; namespace NHibernate.Context { /// <summary> /// This class allows access to the HttpContext without referring to HttpContext at compile time. /// The accessors are cached as delegates for performance. /// </summary> public static class ReflectiveHttpContext { static ReflectiveHttpContext() { CreateCurrentHttpContextGetter(); CreateHttpContextItemsGetter(); } public static Func<object> HttpContextCurrentGetter { get; private set; } public static Func<object, IDictionary> HttpContextItemsGetter { get; private set; } public static IDictionary HttpContextCurrentItems { get { return HttpContextItemsGetter(HttpContextCurrentGetter()); } } private static System.Type HttpContextType { get { string mscorlibVersion = typeof(object).Assembly.GetName().Version.ToString(); return System.Type.GetType("System.Web.HttpContext, System.Web, Version=" + mscorlibVersion + ", Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"); } } private static void CreateCurrentHttpContextGetter() { PropertyInfo currentProperty = HttpContextType.GetProperty("Current", BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy); Expression propertyExpression = Expression.Property(null, currentProperty); Expression convertedExpression = Expression.Convert(propertyExpression, typeof (object)); HttpContextCurrentGetter = (Func<object>) Expression.Lambda(convertedExpression).Compile(); } private static void CreateHttpContextItemsGetter() { ParameterExpression contextParam = Expression.Parameter(typeof (object), "context"); Expression convertedParam = Expression.Convert(contextParam, HttpContextType); Expression itemsProperty = Expression.Property(convertedParam, "Items"); HttpContextItemsGetter = (Func<object, IDictionary>) Expression.Lambda(itemsProperty, contextParam).Compile(); } } }
using System; using System.Collections; using System.Linq.Expressions; using System.Reflection; namespace NHibernate.Context { /// <summary> /// This class allows access to the HttpContext without referring to HttpContext at compile time. /// The accessors are cached as delegates for performance. /// </summary> public static class ReflectiveHttpContext { static ReflectiveHttpContext() { CreateCurrentHttpContextGetter(); CreateHttpContextItemsGetter(); } public static Func<object> HttpContextCurrentGetter { get; private set; } public static Func<object, IDictionary> HttpContextItemsGetter { get; private set; } public static IDictionary HttpContextCurrentItems { get { return HttpContextItemsGetter(HttpContextCurrentGetter()); } } private static System.Type HttpContextType { get { return System.Type.GetType("System.Web.HttpContext, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"); } } private static void CreateCurrentHttpContextGetter() { PropertyInfo currentProperty = HttpContextType.GetProperty("Current", BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy); Expression propertyExpression = Expression.Property(null, currentProperty); Expression convertedExpression = Expression.Convert(propertyExpression, typeof (object)); HttpContextCurrentGetter = (Func<object>) Expression.Lambda(convertedExpression).Compile(); } private static void CreateHttpContextItemsGetter() { ParameterExpression contextParam = Expression.Parameter(typeof (object), "context"); Expression convertedParam = Expression.Convert(contextParam, HttpContextType); Expression itemsProperty = Expression.Property(convertedParam, "Items"); HttpContextItemsGetter = (Func<object, IDictionary>) Expression.Lambda(itemsProperty, contextParam).Compile(); } } }
lgpl-2.1
C#
c4d00f9b96236f68efd6d6a6deb30668fe707c15
Fix #1478: Typo in stem_exclusion property serialization
KodrAus/elasticsearch-net,CSGOpenSource/elasticsearch-net,cstlaurent/elasticsearch-net,CSGOpenSource/elasticsearch-net,KodrAus/elasticsearch-net,TheFireCookie/elasticsearch-net,RossLieberman/NEST,RossLieberman/NEST,jonyadamit/elasticsearch-net,RossLieberman/NEST,UdiBen/elasticsearch-net,CSGOpenSource/elasticsearch-net,elastic/elasticsearch-net,TheFireCookie/elasticsearch-net,jonyadamit/elasticsearch-net,adam-mccoy/elasticsearch-net,UdiBen/elasticsearch-net,azubanov/elasticsearch-net,jonyadamit/elasticsearch-net,elastic/elasticsearch-net,KodrAus/elasticsearch-net,adam-mccoy/elasticsearch-net,cstlaurent/elasticsearch-net,azubanov/elasticsearch-net,azubanov/elasticsearch-net,UdiBen/elasticsearch-net,adam-mccoy/elasticsearch-net,cstlaurent/elasticsearch-net,TheFireCookie/elasticsearch-net
src/Nest/Analysis/Analyzers/LanguageAnalyzer.cs
src/Nest/Analysis/Analyzers/LanguageAnalyzer.cs
using System; using System.Collections.Generic; using Newtonsoft.Json; namespace Nest { /// <summary> /// A set of analyzers aimed at analyzing specific language text. /// </summary> public class LanguageAnalyzer : AnalyzerBase { public LanguageAnalyzer(Language language) { language.ThrowIfNull("language"); var name = Enum.GetName(typeof (Language), language); if (name == null) language.ThrowIfNull("language"); var langName = name.ToLowerInvariant(); Type = langName; } /// <summary> /// A list of stopword to initialize the stop filter with. Defaults to the english stop words. /// </summary> [JsonProperty("stopwords")] public IEnumerable<string> StopWords { get; set; } [JsonProperty("stem_exclusion")] public IEnumerable<string> StemExclusionList { get; set; } /// <summary> /// A path (either relative to config location, or absolute) to a stopwords file configuration. /// </summary> [JsonProperty("stopwords_path")] public string StopwordsPath { get; set; } } }
using System; using System.Collections.Generic; using Newtonsoft.Json; namespace Nest { /// <summary> /// A set of analyzers aimed at analyzing specific language text. /// </summary> public class LanguageAnalyzer : AnalyzerBase { public LanguageAnalyzer(Language language) { language.ThrowIfNull("language"); var name = Enum.GetName(typeof (Language), language); if (name == null) language.ThrowIfNull("language"); var langName = name.ToLowerInvariant(); Type = langName; } /// <summary> /// A list of stopword to initialize the stop filter with. Defaults to the english stop words. /// </summary> [JsonProperty("stopwords")] public IEnumerable<string> StopWords { get; set; } [JsonProperty("stem_exclusion ")] public IEnumerable<string> StemExclusionList { get; set; } /// <summary> /// A path (either relative to config location, or absolute) to a stopwords file configuration. /// </summary> [JsonProperty("stopwords_path")] public string StopwordsPath { get; set; } } }
apache-2.0
C#
d7e17f9d824e42927eba7c0325b422bb51e32477
Update SqliteConnectionStringParser.cs
msallin/SQLiteCodeFirst,liujunhua/SQLiteCodeFirst
SQLite.CodeFirst/SqliteConnectionStringParser.cs
SQLite.CodeFirst/SqliteConnectionStringParser.cs
using System; using System.Collections.Generic; namespace SQLite.CodeFirst { internal static class SqliteConnectionStringParser { private const string DataDirectoryVariable = "|DataDirectory|"; private const char KeyValuePairSeperator = ';'; private const char KeyValueSeperator = '='; private const int KeyPosition = 0; private const int ValuePosition = 1; public static IDictionary<string, string> ParseSqliteConnectionString(string connectionString) { connectionString = connectionString.Trim(); string[] keyValuePairs = connectionString.Split(KeyValuePairSeperator); IDictionary<string, string> keyValuePairDictionary = new Dictionary<string, string>(); foreach (var keyValuePair in keyValuePairs) { string[] keyValue = keyValuePair.Split(KeyValueSeperator); keyValuePairDictionary.Add(keyValue[KeyPosition].ToLower(), keyValue[ValuePosition]); } return keyValuePairDictionary; } public static string GetDataSource(string connectionString) { if (connectionString.ToLower().Contains(DataDirectoryVariable.ToLower())) { var baseDirectory = AppDomain.CurrentDomain.BaseDirectory + @"\"; connectionString = connectionString.ToLower().Replace(DataDirectoryVariable.ToLower(), baseDirectory).Replace(@"\\", @"\"); } return ParseSqliteConnectionString(connectionString)["data source"]; } } }
using System.Collections.Generic; namespace SQLite.CodeFirst { internal static class SqliteConnectionStringParser { private const char KeyValuePairSeperator = ';'; private const char KeyValueSeperator = '='; private const int KeyPosition = 0; private const int ValuePosition = 1; public static IDictionary<string, string> ParseSqliteConnectionString(string connectionString) { connectionString = connectionString.Trim(); string[] keyValuePairs = connectionString.Split(KeyValuePairSeperator); IDictionary<string, string> keyValuePairDictionary = new Dictionary<string, string>(); foreach (var keyValuePair in keyValuePairs) { string[] keyValue = keyValuePair.Split(KeyValueSeperator); keyValuePairDictionary.Add(keyValue[KeyPosition].ToLower(), keyValue[ValuePosition]); } return keyValuePairDictionary; } public static string GetDataSource(string connectionString) { return ParseSqliteConnectionString(connectionString)["data source"]; } } }
apache-2.0
C#
a28f33f4297e92c6b7ad112fdfb43b7ac3c36c68
comment out the OrderConsoleApplication from Main() to show first how the IModule works and do exercise 1
iQuarc/Code-Design-Training,iQuarc/Code-Design-Training
AppInfraDemo/UI/ConsoleApplication/Program.cs
AppInfraDemo/UI/ConsoleApplication/Program.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using iQuarc.AppBoot; using iQuarc.AppBoot.Unity; using iQuarc.DataAccess.AppBoot; using Microsoft.Practices.ServiceLocation; namespace ConsoleApplication { internal class Program { private static void Main(string[] args) { SetupDataDirectory(); IServiceLocator serviceLocator = Bootstrapp(); //OrdersConsoleApplication app = serviceLocator.GetInstance<OrdersConsoleApplication>(); //app.ShowAllOrders(); Console.WriteLine(); Console.WriteLine("Press any key to close the application..."); Console.ReadKey(); } private static IServiceLocator Bootstrapp() { var assemblies = GetApplicationAssemblies().ToArray(); Bootstrapper bootstrapper = new Bootstrapper(assemblies); bootstrapper.ConfigureWithUnity(); bootstrapper.AddRegistrationBehavior(new ServiceRegistrationBehavior()); bootstrapper.AddRegistrationBehavior(DataAccessConfigurations.DefaultRegistrationConventions); bootstrapper.Run(); return bootstrapper.ServiceLocator; } private static IEnumerable<Assembly> GetApplicationAssemblies() { yield return Assembly.GetExecutingAssembly(); string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); foreach (string dll in Directory.GetFiles(path, "*.dll")) { string filename = Path.GetFileName(dll); if (filename != null && (filename.StartsWith("Common") || filename.StartsWith("Contracts") || filename.StartsWith("DataAccess") || filename.StartsWith("iQuarc.DataAccess") || filename.StartsWith("Export.") || filename.StartsWith("Notifications.") || filename.StartsWith("Sales.") )) { Assembly assembly = Assembly.LoadFile(dll); yield return assembly; } } } private static void SetupDataDirectory() { string baseDirectory = AppDomain.CurrentDomain.BaseDirectory; AppDomain.CurrentDomain.SetData("DataDirectory", Path.GetFullPath(Path.Combine(baseDirectory, @"..\..\.App_Data"))); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using iQuarc.AppBoot; using iQuarc.AppBoot.Unity; using iQuarc.DataAccess.AppBoot; using Microsoft.Practices.ServiceLocation; namespace ConsoleApplication { internal class Program { private static void Main(string[] args) { SetupDataDirectory(); IServiceLocator serviceLocator = Bootstrapp(); OrdersConsoleApplication app = serviceLocator.GetInstance<OrdersConsoleApplication>(); app.ShowAllOrders(); Console.WriteLine(); Console.WriteLine("Press any key to close the application..."); Console.ReadKey(); } private static IServiceLocator Bootstrapp() { var assemblies = GetApplicationAssemblies().ToArray(); Bootstrapper bootstrapper = new Bootstrapper(assemblies); bootstrapper.ConfigureWithUnity(); bootstrapper.AddRegistrationBehavior(new ServiceRegistrationBehavior()); bootstrapper.AddRegistrationBehavior(DataAccessConfigurations.DefaultRegistrationConventions); bootstrapper.Run(); return bootstrapper.ServiceLocator; } private static IEnumerable<Assembly> GetApplicationAssemblies() { yield return Assembly.GetExecutingAssembly(); string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); foreach (string dll in Directory.GetFiles(path, "*.dll")) { string filename = Path.GetFileName(dll); if (filename != null && (filename.StartsWith("Common") || filename.StartsWith("Contracts") || filename.StartsWith("DataAccess") || filename.StartsWith("iQuarc.DataAccess") || filename.StartsWith("Export.") || filename.StartsWith("Notifications.") || filename.StartsWith("Sales.") )) { Assembly assembly = Assembly.LoadFile(dll); yield return assembly; } } } private static void SetupDataDirectory() { string baseDirectory = AppDomain.CurrentDomain.BaseDirectory; AppDomain.CurrentDomain.SetData("DataDirectory", Path.GetFullPath(Path.Combine(baseDirectory, @"..\..\.App_Data"))); } } }
mit
C#
ba11f0b35704fa0f7b40eb60bda7f6d19d326232
validate the name when copy a page.
lingxyd/CMS,lingxyd/CMS,techwareone/Kooboo-CMS,jtm789/CMS,jtm789/CMS,andyshao/CMS,andyshao/CMS,jtm789/CMS,Kooboo/CMS,lingxyd/CMS,techwareone/Kooboo-CMS,andyshao/CMS,Kooboo/CMS,Kooboo/CMS,techwareone/Kooboo-CMS
Kooboo.CMS/Kooboo.CMS.Web/Models/CopyModel.cs
Kooboo.CMS/Kooboo.CMS.Web/Models/CopyModel.cs
#region License // // Copyright (c) 2013, Kooboo team // // Licensed under the BSD License // See the file LICENSE.txt for details. // #endregion using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; namespace Kooboo.CMS.Web.Models { public class CopyModel { public string UUID { get; set; } [Required(ErrorMessage = "Required")] [Display(Name = "Destination name")] [RegularExpression(RegexPatterns.FileName, ErrorMessage = "A name cannot contain a space or any of the following characters:\\/:*?<>|~")] [RemoteEx("CopyNameAvailabled", "*", RouteFields = "SiteName,RepositoryName,UUID", AdditionalFields = "ParentPage")] public virtual string DestinationName { get; set; } } }
#region License // // Copyright (c) 2013, Kooboo team // // Licensed under the BSD License // See the file LICENSE.txt for details. // #endregion using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; namespace Kooboo.CMS.Web.Models { public class CopyModel { public string UUID { get; set; } [Required(ErrorMessage = "Required")] [Display(Name = "Destination name")] [RemoteEx("CopyNameAvailabled", "*", RouteFields = "SiteName,RepositoryName,UUID", AdditionalFields = "ParentPage")] public virtual string DestinationName { get; set; } } }
bsd-3-clause
C#
f59faa2fa2f14c3b68122d262ed7b0af16f09d23
Increment build number
emoacht/SnowyImageCopy
Source/SnowyImageCopy/Properties/AssemblyInfo.cs
Source/SnowyImageCopy/Properties/AssemblyInfo.cs
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // 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("Snowy")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Snowy")] [assembly: AssemblyCopyright("Copyright © 2014-2018 emoacht")] [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("55df0585-a26e-489e-bd94-4e6a50a83e23")] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US" , UltimateResourceFallbackLocation.MainAssembly)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // 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.5.4.32")] [assembly: AssemblyFileVersion("1.5.4.32")] // For unit test [assembly: InternalsVisibleTo("SnowyImageCopy.Test")]
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // 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("Snowy")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Snowy")] [assembly: AssemblyCopyright("Copyright © 2014-2018 emoacht")] [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("55df0585-a26e-489e-bd94-4e6a50a83e23")] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US" , UltimateResourceFallbackLocation.MainAssembly)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // 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.5.2.30")] [assembly: AssemblyFileVersion("1.5.2.30")] // For unit test [assembly: InternalsVisibleTo("SnowyImageCopy.Test")]
mit
C#
3f9b1334fb924141b43ddfe46738d2c37861abb6
Implement third step of automation layer
dirkrombauts/fizz-buzz
Specification/AutomationLayer/StepDefinitions.cs
Specification/AutomationLayer/StepDefinitions.cs
using System; using FizzBuzz.ConsoleApp; using NFluent; using TechTalk.SpecFlow; namespace FizzBuzz.Specification.AutomationLayer { [Binding] public class StepDefinitions { private int currentNumber; private string currentResult; [Given(@"the current number is '(.*)'")] public void GivenTheCurrentNumberIs(int currentNumber) { this.currentNumber = currentNumber; } [When(@"I print the number")] public void WhenIPrintTheNumber() { this.currentResult = new FizzBuzzer().Print(this.currentNumber); } [Then(@"the result is '(.*)'")] public void ThenTheResultIs(string expectedResult) { Check.That(this.currentResult).IsEqualTo(expectedResult); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using FizzBuzz.ConsoleApp; using TechTalk.SpecFlow; namespace FizzBuzz.Specification.AutomationLayer { [Binding] public class StepDefinitions { private int currentNumber; private string currentResult; [Given(@"the current number is '(.*)'")] public void GivenTheCurrentNumberIs(int currentNumber) { this.currentNumber = currentNumber; } [When(@"I print the number")] public void WhenIPrintTheNumber() { this.currentResult = new FizzBuzzer().Print(this.currentNumber); } [Then(@"the result is '(.*)'")] public void ThenTheResultIs(int p0) { ScenarioContext.Current.Pending(); } } }
mit
C#
8bd80eeb2d0754e9a5959cb3a0fc167883ff0485
fix assemblyinfo
splitice/SystemInteract.Net,splitice/SystemInteract.Net
SystemInteract.Remote/Properties/AssemblyInfo.cs
SystemInteract.Remote/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("SystemInteract.Remote")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SystemInteract.Remote")] [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("0e4a7bb2-c119-4dbf-b9b2-9f95891d539b")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
using System.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("IPTables.Net.Remote")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("IPTables.Net.Remote")] [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("0e4a7bb2-c119-4dbf-b9b2-9f95891d539b")] // 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")]
apache-2.0
C#
8b60ce2e42eefcdeb1f3e9791223bcc82daec89b
Update MongoClientProviderBase.cs
tiksn/TIKSN-Framework
TIKSN.Core/Data/Mongo/MongoClientProviderBase.cs
TIKSN.Core/Data/Mongo/MongoClientProviderBase.cs
using Microsoft.Extensions.Configuration; using MongoDB.Driver; namespace TIKSN.Data.Mongo { public abstract class MongoClientProviderBase : IMongoClientProvider { private readonly IConfiguration _configuration; private readonly string _connectionStringKey; private readonly object _locker; private MongoClient _mongoClient; protected MongoClientProviderBase(IConfiguration configuration, string connectionStringKey) { this._locker = new object(); this._configuration = configuration; this._connectionStringKey = connectionStringKey; } public IMongoClient GetMongoClient() { if (this._mongoClient == null) { lock (this._locker) { if (this._mongoClient == null) { var connectionString = this._configuration.GetConnectionString(this._connectionStringKey); var mongoUrl = MongoUrl.Create(connectionString); this._mongoClient = new MongoClient(mongoUrl); } } } return this._mongoClient; } } }
using Microsoft.Extensions.Configuration; using MongoDB.Driver; namespace TIKSN.Data.Mongo { public abstract class MongoClientProviderBase : IMongoClientProvider { private readonly IConfiguration _configuration; private readonly string _connectionStringKey; private readonly object _locker; private MongoClient _mongoClient; protected MongoClientProviderBase(IConfiguration configuration, string connectionStringKey) { _locker = new object(); _configuration = configuration; _connectionStringKey = connectionStringKey; } public IMongoClient GetMongoClient() { if (_mongoClient == null) { lock (_locker) { if (_mongoClient == null) { var connectionString = _configuration.GetConnectionString(_connectionStringKey); var mongoUrl = MongoUrl.Create(connectionString); _mongoClient = new MongoClient(mongoUrl); } } } return _mongoClient; } } }
mit
C#
f425d6b67891a1d8ed4f700bca586393818b3b4d
add HasComponent (#576)
ericmbernier/Nez,prime31/Nez,prime31/Nez,prime31/Nez
Nez.Portable/Utils/Extensions/ComponentExt.cs
Nez.Portable/Utils/Extensions/ComponentExt.cs
using System.Collections.Generic; using System.Runtime.CompilerServices; namespace Nez { public static class ComponentExt { #region Entity Component management [MethodImpl(MethodImplOptions.AggressiveInlining)] public static T AddComponent<T>(this Component self, T component) where T : Component { return self.Entity.AddComponent(component); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static T AddComponent<T>(this Component self) where T : Component, new() { return self.Entity.AddComponent<T>(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static T GetComponent<T>(this Component self) where T : Component { return self.Entity.GetComponent<T>(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool HasComponent<T>(this Component self) where T : Component { return self.Entity.HasComponent<T>(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void GetComponents<T>(this Component self, List<T> componentList) where T : class { self.Entity.GetComponents<T>(componentList); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static List<T> GetComponents<T>(this Component self) where T : Component { return self.Entity.GetComponents<T>(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool RemoveComponent<T>(this Component self) where T : Component { return self.Entity.RemoveComponent<T>(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void RemoveComponent(this Component self, Component component) { self.Entity.RemoveComponent(component); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void RemoveComponent(this Component self) { self.Entity.RemoveComponent(self); } #endregion } }
using System.Collections.Generic; using System.Runtime.CompilerServices; namespace Nez { public static class ComponentExt { #region Entity Component management [MethodImpl(MethodImplOptions.AggressiveInlining)] public static T AddComponent<T>(this Component self, T component) where T : Component { return self.Entity.AddComponent(component); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static T AddComponent<T>(this Component self) where T : Component, new() { return self.Entity.AddComponent<T>(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static T GetComponent<T>(this Component self) where T : Component { return self.Entity.GetComponent<T>(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void GetComponents<T>(this Component self, List<T> componentList) where T : class { self.Entity.GetComponents<T>(componentList); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static List<T> GetComponents<T>(this Component self) where T : Component { return self.Entity.GetComponents<T>(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool RemoveComponent<T>(this Component self) where T : Component { return self.Entity.RemoveComponent<T>(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void RemoveComponent(this Component self, Component component) { self.Entity.RemoveComponent(component); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void RemoveComponent(this Component self) { self.Entity.RemoveComponent(self); } #endregion } }
mit
C#
aa5d453664d3a7ff54f297af8ee2f7d1b47d5049
remove unused parameter
kaosborn/KaosCollections
Source/RankedSet/RankedSetEqualityComparer.cs
Source/RankedSet/RankedSetEqualityComparer.cs
// // Library: KaosCollections // File: RankedSetEqualityComparer.cs // // Copyright © 2009-2018 Kasey Osborn (github.com/kaosborn) // MIT License - Use and redistribute freely // using System.Collections.Generic; namespace Kaos.Collections { public partial class RankedSet<T> { private class RankedSetEqualityComparer : IEqualityComparer<RankedSet<T>> { private readonly IComparer<T> comparer; private readonly IEqualityComparer<T> equalityComparer; public RankedSetEqualityComparer (IEqualityComparer<T> equalityComparer) { this.comparer = Comparer<T>.Default; this.equalityComparer = equalityComparer ?? EqualityComparer<T>.Default; } public bool Equals (RankedSet<T> s1, RankedSet<T> s2) => RankedSet<T>.RankedSetEquals (s1, s2, comparer); public int GetHashCode (RankedSet<T> set) { int hashCode = 0; if (set != null) foreach (T item in set) hashCode = hashCode ^ (equalityComparer.GetHashCode (item) & 0x7FFFFFFF); return hashCode; } public override bool Equals (object obComparer) { var rsComparer = obComparer as RankedSetEqualityComparer; return rsComparer != null && comparer == rsComparer.comparer; } public override int GetHashCode() => comparer.GetHashCode() ^ equalityComparer.GetHashCode(); } } }
// // Library: KaosCollections // File: RankedSetEqualityComparer.cs // // Copyright © 2009-2018 Kasey Osborn (github.com/kaosborn) // MIT License - Use and redistribute freely // using System.Collections.Generic; namespace Kaos.Collections { public partial class RankedSet<T> { private class RankedSetEqualityComparer : IEqualityComparer<RankedSet<T>> { private readonly IComparer<T> comparer; private readonly IEqualityComparer<T> equalityComparer; public RankedSetEqualityComparer (IEqualityComparer<T> equalityComparer, IComparer<T> comparer=null) { this.comparer = comparer ?? Comparer<T>.Default; this.equalityComparer = equalityComparer ?? EqualityComparer<T>.Default; } public bool Equals (RankedSet<T> s1, RankedSet<T> s2) => RankedSet<T>.RankedSetEquals (s1, s2, comparer); public int GetHashCode (RankedSet<T> set) { int hashCode = 0; if (set != null) foreach (T item in set) hashCode = hashCode ^ (equalityComparer.GetHashCode (item) & 0x7FFFFFFF); return hashCode; } public override bool Equals (object obComparer) { var rsComparer = obComparer as RankedSetEqualityComparer; return rsComparer != null && comparer == rsComparer.comparer; } public override int GetHashCode() => comparer.GetHashCode() ^ equalityComparer.GetHashCode(); } } }
mit
C#
fbf9cf0b56b1e2017dda9e035a1f0e29b0b96eb2
Test for CRLF line ending bug
Guema/Arcanix
Scripts/Unit.cs
Scripts/Unit.cs
using UnityEngine; using System.Collections; [SelectionBase] [DisallowMultipleComponent] public class Unit : MonoBehaviour { [SerializeField] string faction; [SerializeField] int maxHeath = 100; [SerializeField] int health; // This function is called on Component Placement/Replacement void Reset() { } // Use this for initialization void Start () { } // Update is called once per frame void Update () { } //Called every frame in editor void OnDrawGizmos() { } }
using UnityEngine; using System.Collections; [SelectionBase] [DisallowMultipleComponent] public class Unit : MonoBehaviour { [SerializeField] string faction; [SerializeField] int maxHeath = 100; [SerializeField] int health; // This function is called on Component Placement/Replacement void Reset() { } // Use this for initialization void Start () { } // Update is called once per frame void Update () { } }
cc0-1.0
C#
86e6e63a811ccb56de7ca28b47e1dd40005eb6bf
Bump version to 0.1.2.
FacilityApi/Facility,ejball/Facility
SolutionInfo.cs
SolutionInfo.cs
using System.Reflection; [assembly: AssemblyVersion("0.1.2.0")] [assembly: AssemblyCompany("")] [assembly: AssemblyCopyright("Copyright 2016 Ed Ball")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")]
using System.Reflection; [assembly: AssemblyVersion("0.1.1.0")] [assembly: AssemblyCompany("")] [assembly: AssemblyCopyright("Copyright 2016 Ed Ball")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")]
mit
C#
695487bdc6a4f90fd62c86b80284ced78924ebc7
Update version number.
Damnae/storybrew
editor/Properties/AssemblyInfo.cs
editor/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("storybrew editor")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("storybrew editor")] [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("ff59aeea-c133-4bf8-8a0b-620a3c99022b")] // 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.30.*")]
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("storybrew editor")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("storybrew editor")] [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("ff59aeea-c133-4bf8-8a0b-620a3c99022b")] // 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.29.*")]
mit
C#
a6d3996af0cff8eb7608f8e395a2312484044527
Update version number.
Damnae/storybrew
editor/Properties/AssemblyInfo.cs
editor/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("storybrew editor")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("storybrew editor")] [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("ff59aeea-c133-4bf8-8a0b-620a3c99022b")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.1.*")]
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("storybrew editor")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("storybrew editor")] [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("ff59aeea-c133-4bf8-8a0b-620a3c99022b")] // 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.*")]
mit
C#
006368a1e2aae244941647ca18d715d35ce8f18b
Update AddSiteCollectionAppCatalog.cs
OfficeDev/PnP-PowerShell,kilasuit/PnP-PowerShell
Commands/Admin/AddSiteCollectionAppCatalog.cs
Commands/Admin/AddSiteCollectionAppCatalog.cs
#if !ONPREMISES using Microsoft.Online.SharePoint.TenantAdministration; using Microsoft.SharePoint.Client; using SharePointPnP.PowerShell.CmdletHelpAttributes; using SharePointPnP.PowerShell.Commands.Base; using System.Management.Automation; using OfficeDevPnP.Core.Sites; using SharePointPnP.PowerShell.Commands.Base.PipeBinds; using System; namespace SharePointPnP.PowerShell.Commands.Admin { [Cmdlet(VerbsCommon.Add, "PnPSiteCollectionAppCatalog")] [CmdletHelp("Adds a Site Collection scoped App Catalog to a site", SupportedPlatform = CmdletSupportedPlatform.Online, Category = CmdletHelpCategory.TenantAdmin)] [CmdletExample( Code = @"PS:> Add-PnPSiteCollectionAppCatalog -Site ""https://contoso.sharepoint.com/sites/FinanceTeamsite""", Remarks = @"This will add a SiteCollection app catalog to the specified site", SortOrder = 1)] public class AddSiteCollectionAppCatalog: PnPAdminCmdlet { [Parameter(Mandatory = true, HelpMessage = @"Url of the site to add the app catalog to.")] public SitePipeBind Site; protected override void ExecuteCmdlet() { string url = null; if(Site.Site != null) { Site.Site.EnsureProperty(s => s.Url); url = Site.Site.Url; } else if(!string.IsNullOrEmpty(Site.Url)) { url = Site.Url; } Tenant.GetSiteByUrl(url).RootWeb.TenantAppCatalog.SiteCollectionAppCatalogsSites.Add(url); ClientContext.ExecuteQueryRetry(); } } } #endif
#if !ONPREMISES using Microsoft.Online.SharePoint.TenantAdministration; using Microsoft.SharePoint.Client; using SharePointPnP.PowerShell.CmdletHelpAttributes; using SharePointPnP.PowerShell.Commands.Base; using System.Management.Automation; using OfficeDevPnP.Core.Sites; using SharePointPnP.PowerShell.Commands.Base.PipeBinds; using System; namespace SharePointPnP.PowerShell.Commands.Admin { [Cmdlet(VerbsCommon.Add, "PnPSiteCollectionAppCatalog")] [CmdletHelp("Adds a Site Collection scoped App Catalog to a site", SupportedPlatform = CmdletSupportedPlatform.Online, Category = CmdletHelpCategory.TenantAdmin)] [CmdletExample( Code = @"PS:> Add-PnPOffice365GroupToSite -Site ""https://contoso.sharepoint.com/sites/FinanceTeamsite""", Remarks = @"This will add a SiteCollection app catalog to the specified site", SortOrder = 1)] public class AddSiteCollectionAppCatalog: PnPAdminCmdlet { [Parameter(Mandatory = true, HelpMessage = @"Url of the site to add the app catalog to.")] public SitePipeBind Site; protected override void ExecuteCmdlet() { string url = null; if(Site.Site != null) { Site.Site.EnsureProperty(s => s.Url); url = Site.Site.Url; } else if(!string.IsNullOrEmpty(Site.Url)) { url = Site.Url; } Tenant.GetSiteByUrl(url).RootWeb.TenantAppCatalog.SiteCollectionAppCatalogsSites.Add(url); ClientContext.ExecuteQueryRetry(); } } } #endif
mit
C#
47ded411863d45bd25ccd1dafeff6d613d620fb4
Add it to the job log too.
ucdavis/Commencement,ucdavis/Commencement,ucdavis/Commencement
Commencement.Jobs.Common/Logging/LogHelper.cs
Commencement.Jobs.Common/Logging/LogHelper.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Serilog; using Serilog.Exceptions.Destructurers; namespace Commencement.Jobs.Common.Logging { public static class LogHelper { private static bool _loggingSetup = false; public static void ConfigureLogging() { if (_loggingSetup) return; //only setup logging once Log.Logger = new LoggerConfiguration() .WriteTo.Stackify() .WriteTo.Console() .Enrich.With<ExceptionEnricher>() .CreateLogger(); AppDomain.CurrentDomain.UnhandledException += (sender, eventArgs) => Log.Fatal(eventArgs.ExceptionObject as Exception, eventArgs.ExceptionObject.ToString()); _loggingSetup = true; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Serilog; namespace Commencement.Jobs.Common.Logging { public static class LogHelper { private static bool _loggingSetup = false; public static void ConfigureLogging() { if (_loggingSetup) return; //only setup logging once Log.Logger = new LoggerConfiguration() .WriteTo.Stackify() .WriteTo.Console() .CreateLogger(); AppDomain.CurrentDomain.UnhandledException += (sender, eventArgs) => Log.Fatal(eventArgs.ExceptionObject as Exception, eventArgs.ExceptionObject.ToString()); _loggingSetup = true; } } }
mit
C#
f5a89a2e7e6aa0dcbfd33b7888745e895d72675f
update version number
CampusLabs/identity-token-cache
IdentityTokenCache/Properties/AssemblyInfo.cs
IdentityTokenCache/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("IdentityTokenCache")] [assembly: AssemblyDescription("Windows Identity Foundation Token Caches")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Campus Labs")] [assembly: AssemblyProduct("IdentityTokenCache")] [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("146b1103-26cc-410c-807f-cfa4f8245540")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.1.0.0")] [assembly: AssemblyFileVersion("0.1.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("IdentityTokenCache")] [assembly: AssemblyDescription("Windows Identity Foundation Token Caches")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Campus Labs")] [assembly: AssemblyProduct("IdentityTokenCache")] [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("146b1103-26cc-410c-807f-cfa4f8245540")] // 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.1")] [assembly: AssemblyFileVersion("1.0.0.1")]
mit
C#
82efee615df6379eff46b1c599daed7cca1b6d89
change documentation to not use xml literal substitutions [ci]
louthy/language-ext,StanJav/language-ext
LanguageExt.Core/Effects/Schedule/Schedule.cs
LanguageExt.Core/Effects/Schedule/Schedule.cs
#nullable enable using System.Collections; using System.Collections.Generic; namespace LanguageExt; /// <summary> /// A schedule is defined as a potentially infinite stream of durations, combined with mechanisms for composing them. /// </summary> /// <remarks> /// Used heavily by `repeat`, `retry`, and `fold` with the `Aff` and `Eff` types. Use the static methods to create parts /// of schedulers and then union them using `|` or intersect them using `&`. Union will take the minimum of the two /// schedules to the length of the longest, intersect will take the maximum of the two schedules to the length of the shortest. /// /// Any `IEnumerable<Duration>` can be converted to a `Schedule` using `ToSchedule()` or `Schedule.FromDurations(...)`. /// `Schedule` also implements `IEnumerable<Duration>` so can make use of any transformation on `IEnumerable`. /// A `Schedule` is a struct so an `AsEnumerable()` method is also provided to avoid boxing. /// </remarks> /// <example> /// This example creates a schedule that repeats 5 times, with an exponential delay between each stage, starting /// at 10 milliseconds: /// /// var s = Schedule.Recurs(5) | Schedule.Exponential(10 * ms) /// /// </example> /// <example> /// This example creates a schedule that repeats 5 times, with an exponential delay between each stage, starting /// at 10 milliseconds and with a maximum delay of 2000 milliseconds: /// /// var s = Schedule.Recurs(5) | Schedule.Exponential(10 * ms) | Schedule.Spaced(2000 * ms) /// </example> /// <example> /// This example creates a schedule that repeats 5 times, with an exponential delay between each stage, starting /// at 10 milliseconds and with a minimum delay of 300 milliseconds: /// /// var s = Schedule.Recurs(5) | Schedule.Exponential(10 * ms) & Schedule.Spaced(300 * ms) /// </example> public readonly partial struct Schedule : IEnumerable<Duration> { readonly IEnumerable<Duration> Durations; internal Schedule(IEnumerable<Duration> durations) => Durations = durations; public static Schedule operator |(Schedule a, Schedule b) => a.Union(b); public static Schedule operator |(Schedule a, ScheduleTransformer b) => b(a); public static Schedule operator |(ScheduleTransformer a, Schedule b) => a(b); public static Schedule operator &(Schedule a, Schedule b) => a.Intersect(b); public static Schedule operator &(Schedule a, ScheduleTransformer b) => b(a); public static Schedule operator &(ScheduleTransformer a, Schedule b) => a(b); public static Schedule operator +(Schedule a, Schedule b) => a.AsEnumerable().Append(b.AsEnumerable()).ToSchedule(); public IEnumerable<Duration> AsEnumerable() => Durations; public IEnumerator<Duration> GetEnumerator() => Durations.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } /// <summary> /// Transforms a schedule into another schedule. /// </summary> public delegate Schedule ScheduleTransformer(Schedule schedule);
#nullable enable using System.Collections; using System.Collections.Generic; namespace LanguageExt; /// <summary> /// A schedule is defined as a potentially infinite stream of durations, combined with mechanisms for composing them. /// </summary> /// <remarks> /// Used heavily by `repeat`, `retry`, and `fold` with the `Aff` and `Eff` types. Use the static methods to create parts /// of schedulers and then union them using `|` or intersect them using `&amp;`. Union will take the minimum of the two /// schedules to the length of the longest, intersect will take the maximum of the two schedules to the length of the shortest. /// /// Any `IEnumerable&lt;Duration&gt;` can be converted to a Schedule using `ToSchedule()` or `Schedule.FromDurations(...)`. /// Schedule also implements `IEnumerable&lt;Duration&gt;` so can make use of any transformation on IEnumerable. /// A Schedule is a struct so an `AsEnumerable()` method is also provided to avoid boxing. /// </remarks> /// <example> /// This example creates a schedule that repeats 5 times, with an exponential delay between each stage, starting /// at 10 milliseconds: /// /// var s = Schedule.Recurs(5) | Schedule.Exponential(10 * ms) /// /// </example> /// <example> /// This example creates a schedule that repeats 5 times, with an exponential delay between each stage, starting /// at 10 milliseconds and with a maximum delay of 2000 milliseconds: /// /// var s = Schedule.Recurs(5) | Schedule.Exponential(10 * ms) | Schedule.Spaced(2000 * ms) /// </example> /// <example> /// This example creates a schedule that repeats 5 times, with an exponential delay between each stage, starting /// at 10 milliseconds and with a minimum delay of 300 milliseconds: /// /// var s = Schedule.Recurs(5) | Schedule.Exponential(10 * ms) &amp; Schedule.Spaced(300 * ms) /// </example> public readonly partial struct Schedule : IEnumerable<Duration> { readonly IEnumerable<Duration> Durations; internal Schedule(IEnumerable<Duration> durations) => Durations = durations; public static Schedule operator |(Schedule a, Schedule b) => a.Union(b); public static Schedule operator |(Schedule a, ScheduleTransformer b) => b(a); public static Schedule operator |(ScheduleTransformer a, Schedule b) => a(b); public static Schedule operator &(Schedule a, Schedule b) => a.Intersect(b); public static Schedule operator &(Schedule a, ScheduleTransformer b) => b(a); public static Schedule operator &(ScheduleTransformer a, Schedule b) => a(b); public static Schedule operator +(Schedule a, Schedule b) => a.AsEnumerable().Append(b.AsEnumerable()).ToSchedule(); public IEnumerable<Duration> AsEnumerable() => Durations; public IEnumerator<Duration> GetEnumerator() => Durations.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } /// <summary> /// Transforms a schedule into another schedule. /// </summary> public delegate Schedule ScheduleTransformer(Schedule schedule);
mit
C#
3c0df8de3a74053924dafc42505fc62a49b38a41
Add note about build overwriting AssemblyInfo
jbialobr/NSubstitute,dnm240/NSubstitute,jbialobr/NSubstitute,dnm240/NSubstitute,iamkoch/NSubstitute,iamkoch/NSubstitute,jbialobr/NSubstitute,huoxudong125/NSubstitute,dnm240/NSubstitute,iamkoch/NSubstitute,jannickj/NSubstitute,jannickj/NSubstitute,jannickj/NSubstitute,mrinaldi/NSubstitute,iamkoch/NSubstitute,mrinaldi/NSubstitute,dnm240/NSubstitute,mrinaldi/NSubstitute,dnm240/NSubstitute,mrinaldi/NSubstitute,huoxudong125/NSubstitute,huoxudong125/NSubstitute,jbialobr/NSubstitute,jannickj/NSubstitute,jbialobr/NSubstitute,mrinaldi/NSubstitute,huoxudong125/NSubstitute,jannickj/NSubstitute,iamkoch/NSubstitute,huoxudong125/NSubstitute
Source/NSubstitute/Properties/AssemblyInfo.cs
Source/NSubstitute/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; // This file will be re-written by full build process. // Make changes in build script (build.fsx) [assembly: AssemblyTitle("NSubstitute")] [assembly: AssemblyDescription("A simple substitute for .NET mocking frameworks.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("NSubstitute")] [assembly: AssemblyCopyright("Copyright © 2009 NSubstitute Team")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("0.0.0.0")] [assembly: AssemblyFileVersion("0.0.0.0")] // 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("f1571463-8354-493c-b67c-cd9cec9adf78")]
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("NSubstitute")] [assembly: AssemblyDescription("A simple substitute for .NET mocking frameworks.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("NSubstitute")] [assembly: AssemblyCopyright("Copyright © 2009 NSubstitute Team")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("0.0.0.0")] [assembly: AssemblyFileVersion("0.0.0.0")] // 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("f1571463-8354-493c-b67c-cd9cec9adf78")]
bsd-3-clause
C#
f4e1cda208d26d861523c9a8e320a96cf14f02c2
Fix Android font size (#626)
FormsCommunityToolkit/FormsCommunityToolkit
src/CommunityToolkit/Xamarin.CommunityToolkit/Views/Snackbar/SnackBar.android.cs
src/CommunityToolkit/Xamarin.CommunityToolkit/Views/Snackbar/SnackBar.android.cs
using Xamarin.Forms; using Android.Graphics; using Android.Widget; using Xamarin.Forms.Platform.Android; using Xamarin.CommunityToolkit.UI.Views.Options; using Android.Util; #if MONOANDROID10_0 using AndroidSnackBar = Google.Android.Material.Snackbar.Snackbar; #else using AndroidSnackBar = Android.Support.Design.Widget.Snackbar; #endif namespace Xamarin.CommunityToolkit.UI.Views { class SnackBar { internal void Show(Page sender, SnackBarOptions arguments) { var view = Platform.GetRenderer(sender).View; var snackBar = AndroidSnackBar.Make(view, arguments.MessageOptions.Message, (int)arguments.Duration.TotalMilliseconds); var snackBarView = snackBar.View; snackBarView.SetBackgroundColor(arguments.BackgroundColor.ToAndroid()); var snackTextView = snackBarView.FindViewById<TextView>(Resource.Id.snackbar_text); snackTextView.SetMaxLines(10); snackTextView.SetTextColor(arguments.MessageOptions.Foreground.ToAndroid()); snackTextView.SetTextSize(ComplexUnitType.Px, (float)arguments.MessageOptions.FontSize); snackTextView.LayoutDirection = arguments.IsRtl ? global::Android.Views.LayoutDirection.Rtl : global::Android.Views.LayoutDirection.Inherit; foreach (var action in arguments.Actions) { snackBar.SetAction(action.Text, async v => await action.Action()); snackBar.SetActionTextColor(action.ForegroundColor.ToAndroid()); var snackActionButtonView = snackBarView.FindViewById<TextView>(Resource.Id.snackbar_action); snackActionButtonView.SetBackgroundColor(action.BackgroundColor.ToAndroid()); snackActionButtonView.SetTextSize(ComplexUnitType.Px, (float)action.FontSize); snackActionButtonView.LayoutDirection = arguments.IsRtl ? global::Android.Views.LayoutDirection.Rtl : global::Android.Views.LayoutDirection.Inherit; } snackBar.AddCallback(new SnackBarCallback(arguments)); snackBar.Show(); } class SnackBarCallback : AndroidSnackBar.BaseCallback { readonly SnackBarOptions arguments; public SnackBarCallback(SnackBarOptions arguments) => this.arguments = arguments; public override void OnDismissed(Java.Lang.Object transientBottomBar, int e) { base.OnDismissed(transientBottomBar, e); switch (e) { case DismissEventTimeout: arguments.SetResult(false); break; case DismissEventAction: arguments.SetResult(true); break; } } } } }
using Xamarin.Forms; using Android.Graphics; using Android.Widget; using Xamarin.Forms.Platform.Android; using Xamarin.CommunityToolkit.UI.Views.Options; using Android.Util; #if MONOANDROID10_0 using AndroidSnackBar = Google.Android.Material.Snackbar.Snackbar; #else using AndroidSnackBar = Android.Support.Design.Widget.Snackbar; #endif namespace Xamarin.CommunityToolkit.UI.Views { class SnackBar { internal void Show(Page sender, SnackBarOptions arguments) { var view = Platform.GetRenderer(sender).View; var snackBar = AndroidSnackBar.Make(view, arguments.MessageOptions.Message, (int)arguments.Duration.TotalMilliseconds); var snackBarView = snackBar.View; snackBarView.SetBackgroundColor(arguments.BackgroundColor.ToAndroid()); var snackTextView = snackBarView.FindViewById<TextView>(Resource.Id.snackbar_text); snackTextView.SetMaxLines(10); snackTextView.SetTextColor(arguments.MessageOptions.Foreground.ToAndroid()); snackTextView.SetTextSize(ComplexUnitType.Pt, (float)arguments.MessageOptions.FontSize); snackTextView.LayoutDirection = arguments.IsRtl ? global::Android.Views.LayoutDirection.Rtl : global::Android.Views.LayoutDirection.Inherit; foreach (var action in arguments.Actions) { snackBar.SetAction(action.Text, async v => await action.Action()); snackBar.SetActionTextColor(action.ForegroundColor.ToAndroid()); var snackActionButtonView = snackBarView.FindViewById<TextView>(Resource.Id.snackbar_action); snackActionButtonView.SetBackgroundColor(action.BackgroundColor.ToAndroid()); snackActionButtonView.SetTextSize(ComplexUnitType.Pt, (float)action.FontSize); snackActionButtonView.LayoutDirection = arguments.IsRtl ? global::Android.Views.LayoutDirection.Rtl : global::Android.Views.LayoutDirection.Inherit; } snackBar.AddCallback(new SnackBarCallback(arguments)); snackBar.Show(); } class SnackBarCallback : AndroidSnackBar.BaseCallback { readonly SnackBarOptions arguments; public SnackBarCallback(SnackBarOptions arguments) => this.arguments = arguments; public override void OnDismissed(Java.Lang.Object transientBottomBar, int e) { base.OnDismissed(transientBottomBar, e); switch (e) { case DismissEventTimeout: arguments.SetResult(false); break; case DismissEventAction: arguments.SetResult(true); break; } } } } }
mit
C#
b9d5b3c6b2f4d034b9d1b7367fdd46d098bfe6d9
Change notification api endpoint
SkillsFundingAgency/das-employerusers,SkillsFundingAgency/das-employerusers,SkillsFundingAgency/das-employerusers
src/SFA.DAS.EmployerUsers.Application/Services/Notification/HttpClientWrapper.cs
src/SFA.DAS.EmployerUsers.Application/Services/Notification/HttpClientWrapper.cs
using System; using System.Collections.Generic; using System.Net.Http; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; using SFA.DAS.Configuration; using SFA.DAS.EmployerUsers.Infrastructure.Configuration; namespace SFA.DAS.EmployerUsers.Application.Services.Notification { public class HttpClientWrapper : IHttpClientWrapper { private readonly IConfigurationService _configurationService; public HttpClientWrapper(IConfigurationService configurationService) { _configurationService = configurationService; } public async Task SendMessage<T>(T content) { using (var httpClient = await CreateHttpClient()) { var serializeObject = JsonConvert.SerializeObject(content); var response = await httpClient.SendAsync(new HttpRequestMessage(HttpMethod.Post, "/api/email") { Content = new StringContent(serializeObject, Encoding.UTF8, "application/json") }); response.EnsureSuccessStatusCode(); } } private async Task<HttpClient> CreateHttpClient() { var configuration = await _configurationService.GetAsync<EmployerUsersConfiguration>(); return new HttpClient { BaseAddress = new Uri(configuration.EmployerPortalConfiguration.ApiBaseUrl) }; } } }
using System; using System.Collections.Generic; using System.Net.Http; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; using SFA.DAS.Configuration; using SFA.DAS.EmployerUsers.Infrastructure.Configuration; namespace SFA.DAS.EmployerUsers.Application.Services.Notification { public class HttpClientWrapper : IHttpClientWrapper { private readonly IConfigurationService _configurationService; public HttpClientWrapper(IConfigurationService configurationService) { _configurationService = configurationService; } public async Task SendMessage<T>(T content) { using (var httpClient = await CreateHttpClient()) { var serializeObject = JsonConvert.SerializeObject(content); var response = await httpClient.SendAsync(new HttpRequestMessage(HttpMethod.Post, "/api/notification") { Content = new StringContent(serializeObject, Encoding.UTF8, "application/json") }); response.EnsureSuccessStatusCode(); } } private async Task<HttpClient> CreateHttpClient() { var configuration = await _configurationService.GetAsync<EmployerUsersConfiguration>(); return new HttpClient { BaseAddress = new Uri(configuration.EmployerPortalConfiguration.ApiBaseUrl) }; } } }
mit
C#
897233eccb33c3da5fe8495eef3c0cb087b2086a
Update FunModule - using statement can now be removed as we are using the type keyword for char
mariocatch/MODiX,mariocatch/MODiX,mariocatch/MODiX,mariocatch/MODiX
Modix/Modules/FunModule.cs
Modix/Modules/FunModule.cs
using System.IO; using System.Net.Http; using System.Threading.Tasks; using Discord; using Discord.Commands; using Serilog; namespace Modix.Modules { [Name("Fun"), Summary("A bunch of miscellaneous, fun commands")] public class FunModule : ModuleBase { [Command("jumbo"), Summary("Jumbofy an emoji")] public async Task Jumbo(string emoji) { string emojiUrl = null; if (Emote.TryParse(emoji, out var found)) { emojiUrl = found.Url; } else { var codepoint = char.ConvertToUtf32(emoji, 0); var codepointHex = codepoint.ToString("X").ToLower(); emojiUrl = $"https://raw.githubusercontent.com/twitter/twemoji/gh-pages/2/72x72/{codepointHex}.png"; } try { var client = new HttpClient(); var req = await client.GetStreamAsync(emojiUrl); await Context.Channel.SendFileAsync(req, Path.GetFileName(emojiUrl), Context.User.Mention); try { await Context.Message.DeleteAsync(); } catch (HttpRequestException) { Log.Information("Couldn't delete message after jumbofying."); } } catch (HttpRequestException) { await ReplyAsync($"Sorry {Context.User.Mention}, I don't recognize that emoji."); } } } }
using System; using System.IO; using System.Net.Http; using System.Threading.Tasks; using Discord; using Discord.Commands; using Serilog; namespace Modix.Modules { [Name("Fun"), Summary("A bunch of miscellaneous, fun commands")] public class FunModule : ModuleBase { [Command("jumbo"), Summary("Jumbofy an emoji")] public async Task Jumbo(string emoji) { string emojiUrl = null; if (Emote.TryParse(emoji, out var found)) { emojiUrl = found.Url; } else { var codepoint = char.ConvertToUtf32(emoji, 0); var codepointHex = codepoint.ToString("X").ToLower(); emojiUrl = $"https://raw.githubusercontent.com/twitter/twemoji/gh-pages/2/72x72/{codepointHex}.png"; } try { var client = new HttpClient(); var req = await client.GetStreamAsync(emojiUrl); await Context.Channel.SendFileAsync(req, Path.GetFileName(emojiUrl), Context.User.Mention); try { await Context.Message.DeleteAsync(); } catch (HttpRequestException) { Log.Information("Couldn't delete message after jumbofying."); } } catch (HttpRequestException) { await ReplyAsync($"Sorry {Context.User.Mention}, I don't recognize that emoji."); } } } }
mit
C#
60ceee282143cb64b9216814d922b609c9622717
remove unused namespace
auz34/js-studio
src/Examples/MyStudio/Behaviors/BindableEditorText.cs
src/Examples/MyStudio/Behaviors/BindableEditorText.cs
namespace MyStudio.Behaviors { using System.Windows; using ICSharpCode.AvalonEdit; public static class BindableEditorText { /// <summary> /// The is persistent layout enabled property. /// </summary> public static readonly DependencyProperty BindableTextProperty = DependencyProperty.RegisterAttached( "BindableText", typeof(string), typeof(BindableEditorText), new PropertyMetadata(string.Empty, OnBindableTextPropertyChanged)); /// <summary> /// Gets current bind text. /// </summary> /// <param name="obj"> /// The object. /// </param> /// <returns> /// The text. /// </returns> public static string GetBindableText(DependencyObject obj) { return (string)obj.GetValue(BindableTextProperty); } public static void SetBindableText(DependencyObject obj, string value) { obj.SetValue(BindableTextProperty, value); } /// <summary> /// The on is persistent layout enabled property changed. /// </summary> /// <param name="obj"> /// The object. /// </param> /// <param name="e"> /// The e. /// </param> private static void OnBindableTextPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e) { var textEditor = obj as TextEditor; if (textEditor == null) { return; } textEditor.Text = e.NewValue as string; } } }
namespace MyStudio.Behaviors { using System.Windows; using ICSharpCode.AvalonEdit; using Xceed.Wpf.AvalonDock.Layout; public static class BindableEditorText { /// <summary> /// The is persistent layout enabled property. /// </summary> public static readonly DependencyProperty BindableTextProperty = DependencyProperty.RegisterAttached( "BindableText", typeof(string), typeof(BindableEditorText), new PropertyMetadata(string.Empty, OnBindableTextPropertyChanged)); /// <summary> /// Gets current bind text. /// </summary> /// <param name="obj"> /// The object. /// </param> /// <returns> /// The text. /// </returns> public static string GetBindableText(DependencyObject obj) { return (string)obj.GetValue(BindableTextProperty); } public static void SetBindableText(DependencyObject obj, string value) { obj.SetValue(BindableTextProperty, value); } /// <summary> /// The on is persistent layout enabled property changed. /// </summary> /// <param name="obj"> /// The object. /// </param> /// <param name="e"> /// The e. /// </param> private static void OnBindableTextPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e) { var textEditor = obj as TextEditor; if (textEditor == null) { return; } textEditor.Text = e.NewValue as string; } } }
mit
C#
2bc0eaee7ba64c3416e3387b6d24fd85301540a7
Fix unprivileged file symlink creation
tgstation/tgstation-server,Cyberboss/tgstation-server,Cyberboss/tgstation-server,tgstation/tgstation-server,tgstation/tgstation-server-tools
src/Tgstation.Server.Host/IO/WindowsSymlinkFactory.cs
src/Tgstation.Server.Host/IO/WindowsSymlinkFactory.cs
using System; using System.ComponentModel; using System.IO; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; namespace Tgstation.Server.Host.IO { /// <summary> /// <see cref="ISymlinkFactory"/> for windows systems /// </summary> sealed class WindowsSymlinkFactory : ISymlinkFactory { /// <inheritdoc /> public Task CreateSymbolicLink(string targetPath, string linkPath, CancellationToken cancellationToken) => Task.Factory.StartNew(() => { if (targetPath == null) throw new ArgumentNullException(nameof(targetPath)); if (linkPath == null) throw new ArgumentNullException(nameof(linkPath)); //check if its not a file var flags = File.Exists(targetPath) ? 2 : 3; //SYMBOLIC_LINK_FLAG_DIRECTORY and SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE on win10 1607+ developer mode cancellationToken.ThrowIfCancellationRequested(); if (!NativeMethods.CreateSymbolicLink(linkPath, targetPath, flags)) throw new Win32Exception(Marshal.GetLastWin32Error()); }, cancellationToken, TaskCreationOptions.LongRunning, TaskScheduler.Current); } }
using System; using System.ComponentModel; using System.IO; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; namespace Tgstation.Server.Host.IO { /// <summary> /// <see cref="ISymlinkFactory"/> for windows systems /// </summary> sealed class WindowsSymlinkFactory : ISymlinkFactory { /// <inheritdoc /> public Task CreateSymbolicLink(string targetPath, string linkPath, CancellationToken cancellationToken) => Task.Factory.StartNew(() => { if (targetPath == null) throw new ArgumentNullException(nameof(targetPath)); if (linkPath == null) throw new ArgumentNullException(nameof(linkPath)); //check if its not a file var flags = File.Exists(targetPath) ? 0 : 3; //SYMBOLIC_LINK_FLAG_DIRECTORY | SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE on win10 1607+ developer mode cancellationToken.ThrowIfCancellationRequested(); if (!NativeMethods.CreateSymbolicLink(linkPath, targetPath, flags)) throw new Win32Exception(Marshal.GetLastWin32Error()); }, cancellationToken, TaskCreationOptions.LongRunning, TaskScheduler.Current); } }
agpl-3.0
C#
dcf74f2709456dd2fd5be432d9da9e0c20d148a1
Enhance seed.cs.
exKAZUu/ParserTests,exKAZUu/ParserTests,exKAZUu/ParserTests,exKAZUu/ParserTests,exKAZUu/ParserTests,exKAZUu/ParserTests,exKAZUu/ParserTests
fixture/CSharp/input_code/Seed.cs
fixture/CSharp/input_code/Seed.cs
using System; namespace Occf.Learner.Core.Ts.Experiments { internal class Seed { public static void Main(string[] a) { Contract.Requires(b); Contract.Requires(b, ""); Contract.Requires<Exception>(b); Contract.Requires<Exception>(b, ""); XXXXXXXX.Requires(b); System.Diagnostics.Contracts.Contract.Requires(b); System.Diagnostics.Contracts.Contract.Requires(b, ""); System.Diagnostics.Contracts.Contract.Requires<Exception>(b); System.Diagnostics.Contracts.Contract.Requires<Exception>(b, ""); T: f(0 + 1 - 2 * 3 / 4 % 5); ; { f(); } for (; b;) { } while (b) { } do { } while (b); if (b) { } else if (b) { } else { } switch (1) { case 0: case 1: break; default: break; } Contract.Requires(true); Contract.Requires(true, ""); Contract.Requires<Exception>(true); Contract.Requires<Exception>(true, ""); System.Diagnostics.Contracts.Contract.Requires(true); System.Diagnostics.Contracts.Contract.Requires(true, ""); System.Diagnostics.Contracts.Contract.Requires<Exception>(true); System.Diagnostics.Contracts.Contract.Requires<Exception>(true, ""); for (; true;) { } while (true) { } do { } while (true); if (true) { } else if (true) { } else { } } } }
using System; namespace Occf.Learner.Core.Ts.Experiments { internal class Seed { public static void Main(string[] a) { Contract.Requires(b); Contract.Requires(b, ""); Contract.Requires<Exception>(b); Contract.Requires<Exception>(b, ""); System.Diagnostics.Contracts.Contract.Requires(b); System.Diagnostics.Contracts.Contract.Requires(b, ""); System.Diagnostics.Contracts.Contract.Requires<Exception>(b); System.Diagnostics.Contracts.Contract.Requires<Exception>(b, ""); T: f(0 + 1 - 2 * 3 / 4 % 5); ; { f(); } for (; b;) { } while (b) { } do { } while (b); if (b) { } else if (b) { } else { } switch (1) { case 0: case 1: break; default: break; } Contract.Requires(true); Contract.Requires(true, ""); Contract.Requires<Exception>(true); Contract.Requires<Exception>(true, ""); System.Diagnostics.Contracts.Contract.Requires(true); System.Diagnostics.Contracts.Contract.Requires(true, ""); System.Diagnostics.Contracts.Contract.Requires<Exception>(true); System.Diagnostics.Contracts.Contract.Requires<Exception>(true, ""); for (; true;) { } while (true) { } do { } while (true); if (true) { } else if (true) { } else { } } } }
apache-2.0
C#
1e8b7ded385698b0973e4c2cd23fc1c1b701c7e6
Add utility method that gets the device number for a path
hatton/libpalaso,JohnThomson/libpalaso,hatton/libpalaso,tombogle/libpalaso,marksvc/libpalaso,gtryus/libpalaso,mccarthyrb/libpalaso,ermshiperete/libpalaso,JohnThomson/libpalaso,darcywong00/libpalaso,andrew-polk/libpalaso,gtryus/libpalaso,mccarthyrb/libpalaso,sillsdev/libpalaso,JohnThomson/libpalaso,glasseyes/libpalaso,tombogle/libpalaso,tombogle/libpalaso,gmartin7/libpalaso,gtryus/libpalaso,ddaspit/libpalaso,ermshiperete/libpalaso,glasseyes/libpalaso,darcywong00/libpalaso,ermshiperete/libpalaso,marksvc/libpalaso,gmartin7/libpalaso,sillsdev/libpalaso,mccarthyrb/libpalaso,JohnThomson/libpalaso,sillsdev/libpalaso,andrew-polk/libpalaso,ddaspit/libpalaso,chrisvire/libpalaso,tombogle/libpalaso,ddaspit/libpalaso,chrisvire/libpalaso,andrew-polk/libpalaso,darcywong00/libpalaso,gmartin7/libpalaso,gmartin7/libpalaso,hatton/libpalaso,andrew-polk/libpalaso,gtryus/libpalaso,chrisvire/libpalaso,marksvc/libpalaso,ermshiperete/libpalaso,chrisvire/libpalaso,hatton/libpalaso,glasseyes/libpalaso,sillsdev/libpalaso,ddaspit/libpalaso,glasseyes/libpalaso,mccarthyrb/libpalaso
Palaso/IO/PathUtilities.cs
Palaso/IO/PathUtilities.cs
// Copyright (c) 2014 SIL International // This software is licensed under the MIT License (http://opensource.org/licenses/MIT) using System; using System.Diagnostics; namespace Palaso.IO { public static class PathUtilities { // On Unix there are more characters valid in file names, but we // want the result to be identical on both platforms, so we want // to use the larger invalid Windows list for both platforms public static char[] GetInvalidOSIndependentFileNameChars() { return new char[] { '\0', '\u0001', '\u0002', '\u0003', '\u0004', '\u0005', '\u0006', '\a', '\b', '\t', '\n', '\v', '\f', '\r', '\u000e', '\u000f', '\u0010', '\u0011', '\u0012', '\u0013', '\u0014', '\u0015', '\u0016', '\u0017', '\u0018', '\u0019', '\u001a', '\u001b', '\u001c', '\u001d', '\u001e', '\u001f', '"', '<', '>', '|', ':', '*', '?', '\\', '/' }; } public static int GetDeviceNumber(string filePath) { if (Palaso.PlatformUtilities.Platform.IsWindows) { var driveInfo = new DriveInfo(Path.GetPathRoot(filePath)); return driveInfo.Name.ToUpper()[0] - 'A' + 1; } var process = new Process() { StartInfo = new ProcessStartInfo { FileName = "stat", Arguments = string.Format("-c %d {0}", filePath), UseShellExecute = false, RedirectStandardOutput = true, CreateNoWindow = true } }; process.Start(); process.WaitForExit(); var output = process.StandardOutput.ReadToEnd(); return Convert.ToInt32(output); } } }
// Copyright (c) 2014 SIL International // This software is licensed under the MIT License (http://opensource.org/licenses/MIT) using System; namespace Palaso.IO { public static class PathUtilities { // On Unix there are more characters valid in file names, but we // want the result to be identical on both platforms, so we want // to use the larger invalid Windows list for both platforms public static char[] GetInvalidOSIndependentFileNameChars() { return new char[] { '\0', '\u0001', '\u0002', '\u0003', '\u0004', '\u0005', '\u0006', '\a', '\b', '\t', '\n', '\v', '\f', '\r', '\u000e', '\u000f', '\u0010', '\u0011', '\u0012', '\u0013', '\u0014', '\u0015', '\u0016', '\u0017', '\u0018', '\u0019', '\u001a', '\u001b', '\u001c', '\u001d', '\u001e', '\u001f', '"', '<', '>', '|', ':', '*', '?', '\\', '/' }; } } }
mit
C#
c25c3e259f90d106e81c97bcb4e2e03a7b6bd76d
Remove /
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi.Backend/UnversionedWebBuilder.cs
WalletWasabi.Backend/UnversionedWebBuilder.cs
using NBitcoin; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; namespace WalletWasabi.Backend { public static class UnversionedWebBuilder { #if DEBUG public static string UnversionedFolder { get; } = Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "..\\..\\..\\wwwroot", "unversioned")); #else public static string UnversionedFolder { get; } = Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "wwwroot", "unversioned")); #endif public static string CreateFilePath(string fileName) => Path.Combine(UnversionedFolder, fileName); public static string HtmlStartLine { get; } = "<link href=\"../css/bootstrap.css\" rel=\"stylesheet\" type=\"text/css\" />\r\n<link href=\"../css/OpenSansCondensed300700.css\" rel=\"stylesheet\" type=\"text/css\" />\r\n"; public static void CreateDownloadTextWithVersionHtml() { var filePath = CreateFilePath("download-text-with-version.html"); var content = HtmlStartLine + $"<h1 class=\"text-center\">Download Wasabi Wallet {Helpers.Constants.ClientVersion.ToString()}</h1>"; File.WriteAllText(filePath, content); } public static void UpdateMixedTextHtml(Money amount) { var filePath = CreateFilePath("mixed-text.html"); var moneyString = amount.ToString(false, false); int index = moneyString.IndexOf("."); if (index > 0) { moneyString = moneyString.Substring(0, index); } var content = HtmlStartLine + $"<h2 class=\"text-center\">Wasabi made over <span style=\"padding-left:5px; padding-right:5px; display:inline-block\" class=\"inline border border-dark rounded bg-muted\">{moneyString} BTC</span> fungible since August 1, 2018.</h2>"; File.WriteAllText(filePath, content); } public static void UpdateCoinJoinsHtml(IEnumerable<string> coinJoins) { var filePath = CreateFilePath("coinjoins-table.html"); var content = HtmlStartLine + "<ul class=\"text-center\" style=\"list-style: none;\">"; var endContent = "</ul>"; string smartBitPath; if (Global.Config.Network == Network.TestNet) { smartBitPath = "https://testnet.smartbit.com.au/tx/"; } else { smartBitPath = "https://smartbit.com.au/tx/"; } var coinJoinsList = coinJoins.ToList(); for (int i = 0; i < coinJoinsList.Count; i++) { string cjHash = coinJoinsList[i]; if (i % 2 == 0) { content += $"<li style=\"background:#e6e6e6; margin:5px;\"><a href=\"{smartBitPath}{cjHash}\">{cjHash}</a></li>"; } else { content += $"<li><a href=\"{smartBitPath}{cjHash}\">{cjHash}</a></li>"; } } content += endContent; File.WriteAllText(filePath, content); } } }
using NBitcoin; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; namespace WalletWasabi.Backend { public static class UnversionedWebBuilder { #if DEBUG public static string UnversionedFolder { get; } = Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "..\\..\\..\\wwwroot", "unversioned")); #else public static string UnversionedFolder { get; } = Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "wwwroot", "unversioned")); #endif public static string CreateFilePath(string fileName) => Path.Combine(UnversionedFolder, fileName); public static string HtmlStartLine { get; } = "<link href=\"../css/bootstrap.css\" rel=\"stylesheet\" type=\"text/css\" />\r\n<link href=\"../css/OpenSansCondensed300700.css\" rel=\"stylesheet\" type=\"text/css\" />\r\n"; public static void CreateDownloadTextWithVersionHtml() { var filePath = CreateFilePath("download-text-with-version.html"); var content = HtmlStartLine + $"<h1 class=\"text-center\">Download Wasabi Wallet {Helpers.Constants.ClientVersion.ToString()}</h1>"; File.WriteAllText(filePath, content); } public static void UpdateMixedTextHtml(Money amount) { var filePath = CreateFilePath("mixed-text.html"); var moneyString = amount.ToString(false, false); int index = moneyString.IndexOf("."); if (index > 0) { moneyString = moneyString.Substring(0, index); } var content = HtmlStartLine + $"<h2 class=\"text-center\">Wasabi made over <span style=\"padding-left:5px; padding-right:5px; display:inline-block\" class=\"inline border border-dark rounded bg-muted\">{moneyString} BTC</span> fungible since August 1, 2018.</h2>"; File.WriteAllText(filePath, content); } public static void UpdateCoinJoinsHtml(IEnumerable<string> coinJoins) { var filePath = CreateFilePath("coinjoins-table.html"); var content = HtmlStartLine + "<ul class=\"text-center\" style=\"list-style: none;\">"; var endContent = "</ul>"; string smartBitPath; if (Global.Config.Network == Network.TestNet) { smartBitPath = "https://testnet.smartbit.com.au/tx/"; } else { smartBitPath = "https://smartbit.com.au/tx/"; } var coinJoinsList = coinJoins.ToList(); for (int i = 0; i < coinJoinsList.Count; i++) { string cjHash = coinJoinsList[i]; if (i % 2 == 0) { content += $"<li style=\"background:#e6e6e6; margin:5px;\"><a href=\"{smartBitPath}{cjHash}\">{cjHash}</a></li>"; } else { content += $"<li><a href=\"{smartBitPath}/{cjHash}\">{cjHash}</a></li>"; } } content += endContent; File.WriteAllText(filePath, content); } } }
mit
C#
436b9d1205dd813e12a7837c94aa37563cc3ed6a
update version
smartsheet-platform/smartsheet-csharp-sdk,smartsheet-platform/smartsheet-csharp-sdk
Properties/AssemblyInfo.cs
Properties/AssemblyInfo.cs
// #[license] // Smartsheet SDK for C# // %% // Copyright (C) 2014 Smartsheet // %% // 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.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("Smartsheet C# SDK")] [assembly: AssemblyDescription("Library that uses C# to connect to Smartsheet services.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Smartsheet")] [assembly: AssemblyProduct("Smartsheet_csharp_sdk.Properties")] [assembly: AssemblyCopyright("Copyright © 2014-2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: CLSCompliant(true)] // 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("77f0da27-4da3-437b-ac15-82643cdf2fa6")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // [assembly: AssemblyVersion("2.3.0.0")] [assembly: AssemblyFileVersion("2.2.1.0")]
// #[license] // Smartsheet SDK for C# // %% // Copyright (C) 2014 Smartsheet // %% // 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.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("Smartsheet C# SDK")] [assembly: AssemblyDescription("Library that uses C# to connect to Smartsheet services.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Smartsheet")] [assembly: AssemblyProduct("Smartsheet_csharp_sdk.Properties")] [assembly: AssemblyCopyright("Copyright © 2014-2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: CLSCompliant(true)] // 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("77f0da27-4da3-437b-ac15-82643cdf2fa6")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // [assembly: AssemblyVersion("2.2.1.0")] [assembly: AssemblyFileVersion("2.2.1.0")]
apache-2.0
C#
2b1954c11f836c951ff836b30c39731faf177aa5
Add overload to gdax client for making authentication easier
ChristopherHaws/gdax-dotnet
Gdax/GdaxClient.cs
Gdax/GdaxClient.cs
using System; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; namespace Gdax { /// <summary> /// The GdaxClient is thread safe and can be used as a singleton for the lifetime of your application. /// </summary> public class GdaxClient : IDisposable { private readonly IAuthenticator authenticator; private readonly ISerialzer serialzer; private readonly HttpClient http; public GdaxClient(String apiKey, String passphrase, String secret) : this(new GdaxAuthenticator(apiKey, passphrase, secret), new JsonSerializer()) { } public GdaxClient(IAuthenticator authenticator) : this(authenticator, new JsonSerializer()) { } public GdaxClient(IAuthenticator authenticator, ISerialzer serialzer) { this.authenticator = Check.NotNull(authenticator, nameof(authenticator)); this.serialzer = Check.NotNull(serialzer, nameof(serialzer)); this.http = new HttpClient(); } public void Dispose() { this.http?.Dispose(); } public Boolean UseSandbox { get; set; } = false; public Uri BaseUri => this.UseSandbox ? new Uri(@"https://api-public.sandbox.gdax.com") : new Uri(@"https://api.gdax.com"); public async Task<GdaxResponse<TResponse>> GetResponseAsync<TResponse>(GdaxRequest request) { var httpResponse = await this.GetResponseAsync(request).ConfigureAwait(false); var contentBody = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); return new GdaxResponse<TResponse>( httpResponse.Headers.ToArray(), httpResponse.StatusCode, contentBody, this.serialzer.Deserialize<TResponse>(contentBody) ); } public async Task<HttpResponseMessage> GetResponseAsync(GdaxRequest request) { var httpRequest = this.BuildRequestMessagee(request); httpRequest.Headers.Add("User-Agent", @"gdax-dotnet"); return await this.http.SendAsync(httpRequest).ConfigureAwait(false); } private HttpRequestMessage BuildRequestMessagee(GdaxRequest request) { var requestMessage = new HttpRequestMessage { RequestUri = new Uri(this.BaseUri, request.RequestUrl), Method = request.HttpMethod }; if (request.RequestBody != null) { requestMessage.Content = new StringContent(request.RequestBody, Encoding.UTF8, "application/json"); } var token = this.authenticator.GetAuthenticationToken(request); SetHttpRequestHeaders(requestMessage, token); return requestMessage; } private static void SetHttpRequestHeaders(HttpRequestMessage requestMessage, AuthenticationToken token) { requestMessage.Headers.Add("CB-ACCESS-KEY", token.ApiKey); requestMessage.Headers.Add("CB-ACCESS-SIGN", token.Signature); requestMessage.Headers.Add("CB-ACCESS-TIMESTAMP", token.Timestamp); requestMessage.Headers.Add("CB-ACCESS-PASSPHRASE", token.Passphrase); } } }
using System; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; namespace Gdax { /// <summary> /// The GdaxClient is thread safe and can be used as a singleton for the lifetime of your application. /// </summary> public class GdaxClient : IDisposable { private readonly IAuthenticator authenticator; private readonly ISerialzer serialzer; private readonly HttpClient http; public GdaxClient(IAuthenticator authenticator) : this(authenticator, new JsonSerializer()) { } public GdaxClient(IAuthenticator authenticator, ISerialzer serialzer) { this.authenticator = Check.NotNull(authenticator, nameof(authenticator)); this.serialzer = Check.NotNull(serialzer, nameof(serialzer)); this.http = new HttpClient(); } public void Dispose() { this.http?.Dispose(); } public Boolean UseSandbox { get; set; } = false; public Uri BaseUri => this.UseSandbox ? new Uri(@"https://api-public.sandbox.gdax.com") : new Uri(@"https://api.gdax.com"); public async Task<GdaxResponse<TResponse>> GetResponseAsync<TResponse>(GdaxRequest request) { var httpResponse = await this.GetResponseAsync(request).ConfigureAwait(false); var contentBody = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); return new GdaxResponse<TResponse>( httpResponse.Headers.ToArray(), httpResponse.StatusCode, contentBody, this.serialzer.Deserialize<TResponse>(contentBody) ); } public async Task<HttpResponseMessage> GetResponseAsync(GdaxRequest request) { var httpRequest = this.BuildRequestMessagee(request); httpRequest.Headers.Add("User-Agent", @"gdax-dotnet"); return await this.http.SendAsync(httpRequest).ConfigureAwait(false); } private HttpRequestMessage BuildRequestMessagee(GdaxRequest request) { var requestMessage = new HttpRequestMessage { RequestUri = new Uri(this.BaseUri, request.RequestUrl), Method = request.HttpMethod }; if (request.RequestBody != null) { requestMessage.Content = new StringContent(request.RequestBody, Encoding.UTF8, "application/json"); } var token = this.authenticator.GetAuthenticationToken(request); SetHttpRequestHeaders(requestMessage, token); return requestMessage; } private static void SetHttpRequestHeaders(HttpRequestMessage requestMessage, AuthenticationToken token) { requestMessage.Headers.Add("CB-ACCESS-KEY", token.ApiKey); requestMessage.Headers.Add("CB-ACCESS-SIGN", token.Signature); requestMessage.Headers.Add("CB-ACCESS-TIMESTAMP", token.Timestamp); requestMessage.Headers.Add("CB-ACCESS-PASSPHRASE", token.Passphrase); } } }
mit
C#
4bf764d1a714563b295da2616954453bf9944f77
Remove whitespace and add using
aloisdg/algo
Algo/FisherYates/FisherYates.cs
Algo/FisherYates/FisherYates.cs
using System; using System.Collections.Generic; using System.Linq; namespace FisherYates { public static class FisherYates { /* ** http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle */ static readonly Random Rand = new Random(); public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> list) { var rand = Rand; var enumerable = list as T[] ?? list.ToArray(); for (var i = enumerable.Length; i > 1; i--) { // First step : Pick random element to swap. var j = rand.Next(i); // Second step : Swap. var tmp = enumerable[j]; enumerable[j] = enumerable[i - 1]; enumerable[i - 1] = tmp; } return enumerable; } } }
using System; using System.Collections.Generic; namespace FisherYates { public static class FisherYates { /* ** http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle */ static readonly Random Rand = new Random(); public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> list) { var rand = Rand; var enumerable = list as T[] ?? list.ToArray(); for (var i = enumerable.Length; i > 1; i--) { // First step : Pick random element to swap. var j = rand.Next(i); // Second step : Swap. var tmp = enumerable[j]; enumerable[j] = enumerable[i - 1]; enumerable[i - 1] = tmp; } return enumerable; } } }
bsd-3-clause
C#
0dadea9077ee36a37425866e2b67976736834cf5
update to test WMI further
ZXeno/Andromeda
Andromeda/Andromeda/Command/DebugToConsole.cs
Andromeda/Andromeda/Command/DebugToConsole.cs
using System; using System.Management; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Andromeda.Command { class DebugToConsole : Action { NetworkConnections netconn; ConnectionOptions connOps; public DebugToConsole() { ActionName = "Debug to Console"; Desctiption = "For testing new commands, actions, and abilities."; Category = ActionGroup.Debug; netconn = new NetworkConnections(); connOps = new ConnectionOptions(); connOps.Impersonation = ImpersonationLevel.Impersonate; } public override void RunCommand(string input) { foreach (string d in ParseDeviceList(input)) { if (netconn.CheckWMIAccessible(d, "\\root\\CIMV2", connOps)) { ManagementScope testscope = netconn.ConnectToRemoteWMI(d, "\\root\\CIMV2", connOps); if (testscope != null) { ResultConsole.AddConsoleLine("Successfull connection"); } } } } } }
using System; using System.Management; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Andromeda.Command { class DebugToConsole : Action { NetworkConnections netconn; public DebugToConsole() { ActionName = "Debug to Console"; Desctiption = "For testing new commands, actions, and abilities."; Category = ActionGroup.Debug; netconn = new NetworkConnections(); } public override void RunCommand(string input) { foreach (string d in ParseDeviceList(input)) { if (netconn.CheckWMIAccessible(d, "\\root\\CIMV2")) { ManagementScope testscope = netconn.ConnectToRemoteWMI(d, "\\root\\CIMV2"); if (testscope != null) { ResultConsole.AddConsoleLine("Successfull connection"); } } } } } }
agpl-3.0
C#
2839e21c5fa55ca525c6789a273fe25e4305b885
Fix view
mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander
Battery-Commander.Web/Views/Admin/Jobs.cshtml
Battery-Commander.Web/Views/Admin/Jobs.cshtml
@model IEnumerable<FluentScheduler.Schedule> <table> @foreach (var schedule in Model) { <tr> <td>@Html.DisplayFor(_ => schedule.Name)</td> <td>@schedule.NextRun.ToEst()</td> <td> <form action="/api/Jobs/@schedule.Name" method="post"> <button type="submit">Run Now</button> </form> </td> </tr> } </table>
@model IEnumerable<FluentScheduler.Schedule> <table> @foreach (var schedule in Model) { <tr> <td>@Html.DisplayFor(_ => schedule.Name)</td> <td>@Html.DisplayFor(_ => schedule.NextRun.ToEst()</td> <td> <form action="/api/Jobs/@schedule.Name" method="post"> <button type="submit">Run Now</button> </form> </td> </tr> } </table>
mit
C#
06fa6d5d65093fed15cf14de8a5e69f1623f64d6
Move the ExprSMTLIB test cases (there's only one right now) into their own namespace.
symbooglix/symbooglix,symbooglix/symbooglix,symbooglix/symbooglix
symbooglix/SymbooglixLibTests/ExprSMTLIB/Literal.cs
symbooglix/SymbooglixLibTests/ExprSMTLIB/Literal.cs
using NUnit.Framework; using System; using Microsoft.Boogie; using Microsoft.Basetypes; using System.IO; using symbooglix; namespace ExprSMTLIBTest { [TestFixture()] public class Literal { public Literal() { SymbooglixLibTests.SymbooglixTest.setupDebug(); } [Test()] public void bitvector() { var literal = new LiteralExpr(Token.NoToken, BigNum.FromInt(19), 32); // 19bv32 checkLiteral(literal, "(_ bv19 32)"); } [Test()] public void Bools() { checkLiteral(Expr.True, "true"); checkLiteral(Expr.False, "false"); } private void checkLiteral(LiteralExpr e, string expected) { using (var writer = new StringWriter()) { var printer = new SMTLIBQueryPrinter(writer); printer.Traverse(e); Assert.IsTrue(writer.ToString() == expected); } } } }
using NUnit.Framework; using System; using Microsoft.Boogie; using Microsoft.Basetypes; using System.IO; using symbooglix; namespace SymbooglixLibTests { [TestFixture()] public class Literal { public Literal() { SymbooglixTest.setupDebug(); } [Test()] public void bitvector() { var literal = new LiteralExpr(Token.NoToken, BigNum.FromInt(19), 32); // 19bv32 checkLiteral(literal, "(_ bv19 32)"); } [Test()] public void Bools() { checkLiteral(Expr.True, "true"); checkLiteral(Expr.False, "false"); } private void checkLiteral(LiteralExpr e, string expected) { using (var writer = new StringWriter()) { var printer = new SMTLIBQueryPrinter(writer); printer.Traverse(e); Assert.IsTrue(writer.ToString() == expected); } } } }
bsd-2-clause
C#
8d2a744dbb05522621446e291097324c684042e2
rename [m_dic] to [m_dic_nameKey]
yasokada/unity-160820-Inventory-UI
Assets/DataBaseManager.cs
Assets/DataBaseManager.cs
using UnityEngine; //using System.Collections; using System.IO; using System.Collections.Generic; using System.Linq; using NS_MyStringUtil; /* * - rename [m_dic] to [m_dic_nameKey] * - add GetUniqueIndexString() * v0.5 2016 Aug. 25 * - rename [kIndex_caseNo] to [kIndex_shelfNo] * v0.4 2016 Aug. 25 * - fix typo > [Resouce] to [Resource] * v0.3 2016 Aug. 24 * - GetString() takes [itemName] arg * v0.2 2016 Aug. 24 * - update getString() to use getElementWithLikeSearch() * - add getElementWithLikeSearch() * - add dictionary [m_dic] * - add [kIndex_checkDate] * - add [kIndex_XXX] such as kIndex_row * v0.1 2016 Aug. 23 * - add LoadCsvResouce() */ namespace NS_DataBaseManager { public class DataBaseManager { Dictionary <string, string> m_dic_nameKey; public const int kIndex_shelfNo = 0; public const int kIndex_row = 1; public const int kIndex_column = 2; public const int kIndex_name = 3; public const int kIndex_about = 4; public const int kIndex_url = 5; public const int kIndex_checkDate = 6; public void LoadCsvResource() { if (m_dic_nameKey == null) { m_dic_nameKey = new Dictionary<string, string>(); } TextAsset csv = Resources.Load ("inventory") as TextAsset; StringReader reader = new StringReader (csv.text); string line = ""; string itmnm; while (reader.Peek () != -1) { line = reader.ReadLine (); itmnm = MyStringUtil.ExtractCsvColumn (line, kIndex_name); m_dic_nameKey.Add (itmnm, line); } } public string GetUniqueIndexString(int shelfNo, int row, int column) { string res; res = string.Format ("{0:0000}", shelfNo); res = res + string.Format ("{0:00}", row); res = res + string.Format ("{0:00}", column); return res; } public string GetString(string itemName) { string res = getElementWithLikeSearch (m_dic_nameKey, itemName); return res; } private static string getElementWithLikeSearch(Dictionary<string, string> myDic, string searchKey) { //Dictionaryの規定値は「null, null」なので、空文字を返したい場合はnull判定を入れる return myDic.Where(n => n.Key.Contains(searchKey)).FirstOrDefault().Value; } } }
using UnityEngine; //using System.Collections; using System.IO; using System.Collections.Generic; using System.Linq; using NS_MyStringUtil; /* * - add GetUniqueIndexString() * v0.5 2016 Aug. 25 * - rename [kIndex_caseNo] to [kIndex_shelfNo] * v0.4 2016 Aug. 25 * - fix typo > [Resouce] to [Resource] * v0.3 2016 Aug. 24 * - GetString() takes [itemName] arg * v0.2 2016 Aug. 24 * - update getString() to use getElementWithLikeSearch() * - add getElementWithLikeSearch() * - add dictionary [m_dic] * - add [kIndex_checkDate] * - add [kIndex_XXX] such as kIndex_row * v0.1 2016 Aug. 23 * - add LoadCsvResouce() */ namespace NS_DataBaseManager { public class DataBaseManager { Dictionary <string, string> m_dic; public const int kIndex_shelfNo = 0; public const int kIndex_row = 1; public const int kIndex_column = 2; public const int kIndex_name = 3; public const int kIndex_about = 4; public const int kIndex_url = 5; public const int kIndex_checkDate = 6; public void LoadCsvResource() { if (m_dic == null) { m_dic = new Dictionary<string, string>(); } TextAsset csv = Resources.Load ("inventory") as TextAsset; StringReader reader = new StringReader (csv.text); string line = ""; string itmnm; while (reader.Peek () != -1) { line = reader.ReadLine (); itmnm = MyStringUtil.ExtractCsvColumn (line, kIndex_name); m_dic.Add (itmnm, line); } } public string GetUniqueIndexString(int shelfNo, int row, int column) { string res; res = string.Format ("{0:0000}", shelfNo); res = res + string.Format ("{0:00}", row); res = res + string.Format ("{0:00}", column); return res; } public string GetString(string itemName) { string res = getElementWithLikeSearch (m_dic, itemName); return res; } private static string getElementWithLikeSearch(Dictionary<string, string> myDic, string searchKey) { //Dictionaryの規定値は「null, null」なので、空文字を返したい場合はnull判定を入れる return myDic.Where(n => n.Key.Contains(searchKey)).FirstOrDefault().Value; } } }
mit
C#
74a42920ff4c9b2ac96ec678c5df713db47a8494
Fix up/rework BindableBool parsing
Tom94/osu-framework,EVAST9919/osu-framework,DrabWeb/osu-framework,Tom94/osu-framework,peppy/osu-framework,default0/osu-framework,smoogipooo/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,Nabile-Rahmani/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,DrabWeb/osu-framework,ppy/osu-framework,ZLima12/osu-framework,peppy/osu-framework,ZLima12/osu-framework,DrabWeb/osu-framework,Nabile-Rahmani/osu-framework,ppy/osu-framework,peppy/osu-framework,ppy/osu-framework,default0/osu-framework
osu.Framework/Configuration/BindableBool.cs
osu.Framework/Configuration/BindableBool.cs
// Copyright (c) 2007-2018 ppy Pty Ltd <[email protected]>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System; namespace osu.Framework.Configuration { public class BindableBool : Bindable<bool> { public BindableBool(bool value = false) : base(value) { } public static implicit operator bool(BindableBool value) => value?.Value ?? throw new InvalidCastException($"Casting a null {nameof(BindableBool)} to a bool is likely a mistake"); public override string ToString() => Value.ToString(); public override void Parse(object input) { if (input.Equals("1")) Value = true; else if (input.Equals("0")) Value = false; else base.Parse(input); } public void Toggle() => Value = !Value; } }
// Copyright (c) 2007-2018 ppy Pty Ltd <[email protected]>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System; namespace osu.Framework.Configuration { public class BindableBool : Bindable<bool> { public BindableBool(bool value = false) : base(value) { } public static implicit operator bool(BindableBool value) => value?.Value ?? throw new InvalidCastException($"Casting a null {nameof(BindableBool)} to a bool is likely a mistake"); public override string ToString() => Value.ToString(); public override void Parse(object s) { string str = s as string; if (str == null) throw new InvalidCastException($@"Input type {s.GetType()} could not be cast to a string for parsing"); Value = str == @"1" || str.Equals(@"true", StringComparison.OrdinalIgnoreCase); } public void Toggle() => Value = !Value; } }
mit
C#
68be0b230dd77e3a8aa7c9e507de5f2384b4f2c1
Add version method
fredatgithub/UsefulFunctions
FonctionsUtiles.Fred.Csharp/FunctionsWindows.cs
FonctionsUtiles.Fred.Csharp/FunctionsWindows.cs
using System; using System.Diagnostics; using System.Reflection; namespace FonctionsUtiles.Fred.Csharp { public class FunctionsWindows { public static bool IsInWinPath(string substring) { bool result = false; string winPath = Environment.GetEnvironmentVariable("Path", EnvironmentVariableTarget.Machine); if (winPath != null) result = winPath.Contains(substring); return result; } public static string DisplayTitle() { Assembly assembly = Assembly.GetExecutingAssembly(); FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(assembly.Location); return $@"V{fvi.FileMajorPart}.{fvi.FileMinorPart}.{fvi.FileBuildPart}.{fvi.FilePrivatePart}"; } } }
using System; namespace FonctionsUtiles.Fred.Csharp { public class FunctionsWindows { public static bool IsInWinPath(string substring) { bool result = false; string winPath = Environment.GetEnvironmentVariable("Path", EnvironmentVariableTarget.Machine); if (winPath != null) result = winPath.Contains(substring); return result; } } }
mit
C#
fafe30bda316fe239af661dce96bbc0288de3b31
Add Guid as name for workspace registration
balazs4/mef
MEF/UI/App.xaml.cs
MEF/UI/App.xaml.cs
using System; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Data; using System.Linq; using System.Threading.Tasks; using System.Windows; using Microsoft.Practices.Unity; using UI.AddComponent; namespace UI { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); this.MainWindow = new MainWindow(); var compManager = new MEF_CompositionManager(); compManager.ComposeParts(); var container = new UnityContainer(); foreach (var component in compManager.ImportedComponents) { container.RegisterType(component.Provider.Key, component.Provider.Value); container.RegisterType(typeof(WorkspaceViewModel), component.Workspace, Guid.NewGuid().ToString()); } container.RegisterType<IWorkspaceService, WorkspaceService>(); this.MainWindow.DataContext = container.Resolve<CalculatorViewModel>(); this.MainWindow.Show(); } } public interface IWorkspaceService { IEnumerable<WorkspaceViewModel> GetWorkspaces(); } public class WorkspaceService : IWorkspaceService { private readonly IUnityContainer container; public WorkspaceService(IUnityContainer container) { this.container = container; } public IEnumerable<WorkspaceViewModel> GetWorkspaces() { return container.ResolveAll<WorkspaceViewModel>().ToArray(); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Data; using System.Linq; using System.Threading.Tasks; using System.Windows; using Microsoft.Practices.Unity; using UI.AddComponent; namespace UI { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); this.MainWindow = new MainWindow(); var compManager = new MEF_CompositionManager(); compManager.ComposeParts(); var container = new UnityContainer(); foreach (var component in compManager.ImportedComponents) { container.RegisterType(component.Provider.Key, component.Provider.Value); container.RegisterType(typeof(WorkspaceViewModel), component.Workspace, component.Workspace.Name); } container.RegisterType<IWorkspaceService, WorkspaceService>(); this.MainWindow.DataContext = container.Resolve<CalculatorViewModel>(); this.MainWindow.Show(); } } public interface IWorkspaceService { IEnumerable<WorkspaceViewModel> GetWorkspaces(); } public class WorkspaceService : IWorkspaceService { private readonly IUnityContainer container; public WorkspaceService(IUnityContainer container) { this.container = container; } public IEnumerable<WorkspaceViewModel> GetWorkspaces() { return container.ResolveAll<WorkspaceViewModel>().ToArray();; } } }
unlicense
C#
9c8dc96b6c60099943f7bd25d4e6a40ae5b97d49
Fix to use GetType instead of typeof(T).
cube-soft/Cube.Core,cube-soft/Cube.Core
Libraries/Sources/Aggregator.cs
Libraries/Sources/Aggregator.cs
/* ------------------------------------------------------------------------- */ // // Copyright (c) 2010 CubeSoft, 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. // /* ------------------------------------------------------------------------- */ using Cube.Collections; using System; using System.Collections.Concurrent; using System.Linq; namespace Cube { /* --------------------------------------------------------------------- */ /// /// Aggregator /// /// <summary> /// Represents the type based message aggregator. /// </summary> /// /* --------------------------------------------------------------------- */ public sealed class Aggregator { #region Methods /* --------------------------------------------------------------------- */ /// /// Publish /// /// <summary> /// Publishes the specified message. /// </summary> /// /// <param name="message">Message to be published.</param> /// /* --------------------------------------------------------------------- */ public void Publish<T>(T message) { if (_subscription.TryGetValue(message.GetType(), out var dest)) { foreach (var e in dest.OfType<Action<T>>()) e(message); } } /* --------------------------------------------------------------------- */ /// /// Subscribe /// /// <summary> /// Subscribes the message of type T. /// </summary> /// /// <typeparam name="T">Message type.</typeparam> /// /// <param name="callback"> /// Callback function for the message of type T. /// </param> /// /// <returns>Object to clear the subscription.</returns> /// /* --------------------------------------------------------------------- */ public IDisposable Subscribe<T>(Action<T> callback) => _subscription.GetOrAdd(typeof(T), e => new Subscription<Delegate>()).Subscribe(callback); #endregion #region Fields private readonly ConcurrentDictionary<Type, Subscription<Delegate>> _subscription = new ConcurrentDictionary<Type, Subscription<Delegate>>(); #endregion } }
/* ------------------------------------------------------------------------- */ // // Copyright (c) 2010 CubeSoft, 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. // /* ------------------------------------------------------------------------- */ using Cube.Collections; using System; using System.Collections.Concurrent; using System.Linq; namespace Cube { /* --------------------------------------------------------------------- */ /// /// Aggregator /// /// <summary> /// Represents the type based message aggregator. /// </summary> /// /* --------------------------------------------------------------------- */ public sealed class Aggregator { #region Methods /* --------------------------------------------------------------------- */ /// /// Publish /// /// <summary> /// Publishes the specified message. /// </summary> /// /// <param name="message">Message to be publishd.</param> /// /* --------------------------------------------------------------------- */ public void Publish<T>(T message) { if (_subscription.TryGetValue(typeof(T), out var dest)) { foreach (var e in dest.OfType<Action<T>>()) e(message); } } /* --------------------------------------------------------------------- */ /// /// Subscribe /// /// <summary> /// Subscribes the message of type T. /// </summary> /// /// <typeparam name="T">Message type.</typeparam> /// /// <param name="callback"> /// Callback function for the message of type T. /// </param> /// /// <returns>Object to clear the subscription.</returns> /// /* --------------------------------------------------------------------- */ public IDisposable Subscribe<T>(Action<T> callback) => _subscription.GetOrAdd(typeof(T), e => new Subscription<Delegate>()).Subscribe(callback); #endregion #region Fields private readonly ConcurrentDictionary<Type, Subscription<Delegate>> _subscription = new ConcurrentDictionary<Type, Subscription<Delegate>>(); #endregion } }
apache-2.0
C#
e8cfe07b73013f20f60bcb4843501caef82f5ee3
bump version
Fody/Obsolete
CommonAssemblyInfo.cs
CommonAssemblyInfo.cs
using System.Reflection; [assembly: AssemblyTitle("Obsolete")] [assembly: AssemblyProduct("Obsolete")] [assembly: AssemblyVersion("1.5.4.0")] [assembly: AssemblyFileVersion("1.5.4.0")]
using System.Reflection; [assembly: AssemblyTitle("Obsolete")] [assembly: AssemblyProduct("Obsolete")] [assembly: AssemblyVersion("1.5.3.0")] [assembly: AssemblyFileVersion("1.5.3.0")]
mit
C#
3f0b6b2ac7cb2514575e88991f141df73d36c8ea
Copy AssemblyInfo fro old project
wgross/Elementary.Hierarchy
Elementary.Hierarchy/Properties/AssemblyInfo.cs
Elementary.Hierarchy/Properties/AssemblyInfo.cs
using System.Reflection; 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("Elementary.Hierarchy")] [assembly: AssemblyDescription("Elementary Hierarchy provides structures and algorithms for developing of tree-like/hierarchical data structures.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Wolfgang Groß")] [assembly: AssemblyProduct("Elementary.Hierarchy")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.4.0.0")] [assembly: AssemblyFileVersion("1.4.0.0")]
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("Elementary.Hierarchy")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Elementary.Hierarchy")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#
d119abddc7327977160f88a45b4141393ad0acab
Set MaxSpeed and Mass to nonzero values in Follower.
Gluestick/AIssignment
Game/Entities/Follower.cs
Game/Entities/Follower.cs
using System.Drawing; using ISGPAI.Game.Maths; using ISGPAI.Game.SteeringBehaviors; namespace ISGPAI.Game.Entities { /// <summary> /// Entity that arrives the specified target. /// </summary> internal class Follower : MovingEntity { private ISteeringBehavior _steering; public Follower(Entity target) { MaxSpeed = 200; Mass = 0.5; _steering = new ArriveSteering(target); } public override void Update(double elapsed) { Vector2 steeringForce = _steering.Steer(this, elapsed) * 1000; Vector2 acceleration = steeringForce / Mass; Velocity += acceleration * elapsed; Velocity = Velocity.Truncate(MaxSpeed); Position += Velocity * elapsed; } public override void Paint(System.Drawing.Graphics g) { const int Size = 10; g.FillEllipse(Brushes.Red, (int)Position.X - Size / 2, (int)Position.Y - Size / 2, Size, Size ); } } }
using System.Drawing; using ISGPAI.Game.Maths; using ISGPAI.Game.SteeringBehaviors; namespace ISGPAI.Game.Entities { /// <summary> /// Entity that arrives the specified target. /// </summary> internal class Follower : MovingEntity { private ISteeringBehavior _steering; public Follower(Entity target) { _steering = new ArriveSteering(target); } public override void Update(double elapsed) { Vector2 steeringForce = _steering.Steer(this, elapsed) * 1000; Vector2 acceleration = steeringForce / Mass; Velocity += acceleration * elapsed; Velocity = Velocity.Truncate(MaxSpeed); Position += Velocity * elapsed; } public override void Paint(System.Drawing.Graphics g) { const int Size = 10; g.FillEllipse(Brushes.Red, (int)Position.X - Size / 2, (int)Position.Y - Size / 2, Size, Size ); } } }
mit
C#
4affcb679913e60091747fad0676e77d26310950
Add some more benchmark methods
HangfireIO/Cronos
benchmarks/Cronos.Benchmark/CronBenchmarks.cs
benchmarks/Cronos.Benchmark/CronBenchmarks.cs
using System; using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Attributes.Jobs; namespace Cronos.Benchmark { [RyuJitX64Job] public class CronBenchmarks { private static readonly CronExpression SimpleExpression = CronExpression.Parse("* * * * * ?"); private static readonly CronExpression ComplexExpression = CronExpression.Parse("* */10 12-20 * DEC 3"); private static readonly DateTime DateTimeNow = DateTime.Now; [Benchmark] public unsafe string ParseBaseline() { fixed (char* pointer = "* * * * * ?") { var ptr = pointer; while (*ptr != '\0' && *ptr != '\n' && *ptr != ' ') ptr++; return new string(pointer); } } [Benchmark] public CronExpression ParseStars() { return CronExpression.Parse("* * * * * *"); } [Benchmark] public CronExpression ParseNumber() { return CronExpression.Parse("20 * * * * *"); } [Benchmark] public CronExpression ParseRange() { return CronExpression.Parse("20-40 * * * * *"); } [Benchmark] public CronExpression ParseList() { return CronExpression.Parse("20,30,40,50 * * * * *"); } [Benchmark] public CronExpression ParseComplex() { return CronExpression.Parse("* */10 12-20 ? DEC 3"); } [Benchmark] public DateTimeOffset? NextSimple() { return SimpleExpression.Next(DateTimeNow, DateTimeNow.AddYears(100), TimeZoneInfo.Utc); } [Benchmark] public DateTimeOffset? NextComplex() { return ComplexExpression.Next(DateTimeNow, DateTimeNow.AddYears(100), TimeZoneInfo.Utc); } } }
using System; using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Attributes.Jobs; namespace Cronos.Benchmark { [RyuJitX64Job] public class CronBenchmarks { private static readonly CronExpression SimpleExpression = CronExpression.Parse("* * * * * ?"); private static readonly CronExpression ComplexExpression = CronExpression.Parse("* */10 12-20 * DEC 3"); private static readonly DateTime DateTimeNow = DateTime.Now; [Benchmark] public unsafe string ParseBaseline() { fixed (char* pointer = "* * * * * ?") { var ptr = pointer; while (*ptr != '\0' && *ptr != '\n' && *ptr != ' ') ptr++; return new string(pointer); } } [Benchmark] public CronExpression ParseSimple() { return CronExpression.Parse("* * * * * *"); } [Benchmark] public CronExpression ParseComplex() { return CronExpression.Parse("* */10 12-20 ? DEC 3"); } [Benchmark] public DateTimeOffset? NextSimple() { return SimpleExpression.Next(DateTimeNow, DateTimeNow.AddYears(100), TimeZoneInfo.Utc); } [Benchmark] public DateTimeOffset? NextComplex() { return ComplexExpression.Next(DateTimeNow, DateTimeNow.AddYears(100), TimeZoneInfo.Utc); } } }
mit
C#
a894ba438481715b8f9daf97b896f3205ec09b0f
Update LearnThisFirst.cs
MartinChavez/CSharp
SchoolOfCSharp/Fundamentals/LearnThisFirst.cs
SchoolOfCSharp/Fundamentals/LearnThisFirst.cs
using System; //Use 'using' keyword to tell the compiler that you are using the 'System' namespace namespace Fundamentals //'namespace' is a special keyword that allows to separate the code in a meaninful manner { class LearnThisFirst //Every single time you want to execute code, it needs to be inside of a Type, in this case, a Class { static void Main() //Method that will execute first when running the program { //Every Object you work with, has a type, in this case, it is a System.Int type, which we use the keyword 'int' to represent it int firstType = 3; //Your first Type Console.WriteLine("Hello World"); //Your first statement, this will output to console 'Hello World' /*When writting Console Applications, you can use this statement to wait for User Input Then the CMD Window won't automatically close*/ int sum = 3 + 3;// '3+3' is an Expression Statement since it evaluates and creates a value Console.ReadLine(); } } }
using System; //Use 'using' keyboard to tell the compiler that you are using the 'System' namespace namespace Fundamentals //'namespace' is a special keyboard that allows to separate the code in a meaninful manner { class LearnThisFirst //Every single time you want to execute code, it needs to be inside of a Type, in this case, a Class { static void Main() //Method that will execute first when running the program { //Every Object you work with, has a type, in this case, it is a System.Int type, which we use the keyword 'int' to represent it int firstType = 3; //Your first Type Console.WriteLine("Hello World"); //Your first statement, this will output to console 'Hello World' /*When writting Console Applications, you can use this statement to wait for User Input Then the CMD Window won't automatically close*/ int sum = 3 + 3;// '3+3' is an Expression Statement since it evaluates and creates a value Console.ReadLine(); } } }
mit
C#
1764349d3ad252331863bb0b28b641868729ace1
Update now actually does things in EvoCommand
pampersrocker/EvoNet
EvoCommand/Program.cs
EvoCommand/Program.cs
using EvoSim; using Microsoft.Xna.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace EvoCommand { class Program { static void Main(string[] args) { Simulation sim = new Simulation(); sim.Initialize(sim); DateTime startTime = DateTime.UtcNow; DateTime lastUpdate; DateTime lastSerializationTime = DateTime.UtcNow; long i = 0; while (true) { lastUpdate = DateTime.UtcNow; sim.NotifyTick(new GameTime(DateTime.UtcNow - startTime, lastUpdate - lastUpdate)); i++; if (i % 1000000 == 1) Console.WriteLine("Programm still active - " + DateTime.Now.ToString()); // Save progress every minute if ((DateTime.UtcNow - lastSerializationTime).TotalSeconds > 10) { lastSerializationTime = DateTime.UtcNow; sim.TileMap.SerializeToFile("tilemap.dat"); sim.CreatureManager.Serialize("creatures.dat", "graveyard/graveyard"); Console.WriteLine("Save everything."); } } } } }
using EvoSim; using Microsoft.Xna.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace EvoCommand { class Program { static void Main(string[] args) { Simulation sim = new Simulation(); sim.Initialize(sim); DateTime startTime = DateTime.UtcNow; DateTime lastUpdate; DateTime lastSerializationTime = DateTime.UtcNow; long i = 0; while (true) { lastUpdate = DateTime.UtcNow; update(new GameTime(DateTime.UtcNow - startTime, lastUpdate - lastUpdate)); i++; if (i % 1000000 == 1) Console.WriteLine("Programm still active - " + DateTime.Now.ToString()); // Save progress every minute if ((DateTime.UtcNow - lastSerializationTime).TotalSeconds > 10) { lastSerializationTime = DateTime.UtcNow; sim.TileMap.SerializeToFile("tilemap.dat"); sim.CreatureManager.Serialize("creatures.dat", "graveyard/graveyard"); Console.WriteLine("Save everything."); } } } public static void update(GameTime gametime) { } } }
mit
C#
01aac32d9b412b9a0875aac4f258257614274bbe
add test query execution to make sure we generate valid sql
LinqToDB4iSeries/linq2db,MaceWindu/linq2db,linq2db/linq2db,MaceWindu/linq2db,LinqToDB4iSeries/linq2db,linq2db/linq2db
Tests/Linq/UserTests/IndexOutOfRangeInUnions.cs
Tests/Linq/UserTests/IndexOutOfRangeInUnions.cs
using System; using System.Linq; using LinqToDB; using NUnit.Framework; namespace Tests.UserTests { public class IndexOutOfRangeInUnions : TestBase { [Test] public void ErrorInUinon([DataSources] string context) { using (var db = GetDataContext(context)) using (db.CreateLocalTable<ClassTypeOne>("O1")) using (db.CreateLocalTable<ClassTypeOne>("O2")) using (db.CreateLocalTable<ClassTypeOne>("O3")) { IQueryable<ClassTypeOfResult> query = null; foreach (var tipoDeDocumento in Enumerable.Range(1, 3)) { var innerQuery = from doSap in db.GetTable<ClassTypeOne>() .TableName($"O{tipoDeDocumento}") select new ClassTypeOfResult { NumeroInterno = doSap.DocEntry, StatusValor = doSap.DocStatus == "O" ? "Aberto" : "Fechado", DescricaoStatus = "Manual/Externo", }; query = query?.Union(innerQuery) ?? innerQuery; } Assert.DoesNotThrow(() => Console.WriteLine(query?.ToString())); query.ToList(); } } public class ClassTypeOne { public int DocEntry { get; set; } public int BplId { get; set; } public string ChaveAcesso { get; set; } public string DocStatus { get; set; } } public class ClassTypeOfResult { public int NumeroInterno { get; set; } public string ChaveDeAcesso { get; set; } public string StatusValor { get; set; } public string DescricaoStatus { get; set; } } } }
using System; using System.Linq; using LinqToDB; using NUnit.Framework; namespace Tests.UserTests { public class IndexOutOfRangeInUnions : TestBase { [Test] public void ErrorInUinon([DataSources] string context) { using (var db = GetDataContext(context)) { IQueryable<ClassTypeOfResult> query = null; foreach (var tipoDeDocumento in Enumerable.Range(1, 3)) { var innerQuery = from doSap in db.GetTable<ClassTypeOne>() .TableName($"O{tipoDeDocumento}") select new ClassTypeOfResult { NumeroInterno = doSap.DocEntry, StatusValor = doSap.DocStatus == "O" ? "Aberto" : "Fechado", DescricaoStatus = "Manual/Externo", }; query = query?.Union(innerQuery) ?? innerQuery; } Assert.DoesNotThrow(() => Console.WriteLine(query?.ToString())); } } public class ClassTypeOne { public int DocEntry { get; set; } public int BplId { get; set; } public string ChaveAcesso { get; set; } public string DocStatus { get; set; } } public class ClassTypeOfResult { /// <summary> /// DocEntry /// </summary> public int NumeroInterno { get; set; } public string ChaveDeAcesso { get; set; } public string StatusValor { get; set; } public string DescricaoStatus { get; set; } } } }
mit
C#
b9ddd6e0a6af3670a67a857ce07a53efc532c5dd
Fix query to handle empty search terms
projecteon/thecollection,projecteon/thecollection,projecteon/thecollection,projecteon/thecollection
TheCollection.Web/Services/SearchableQuery.cs
TheCollection.Web/Services/SearchableQuery.cs
using Microsoft.Azure.Documents; using System.Collections.Generic; using System.Linq; using TheCollection.Web.Models; namespace TheCollection.Web.Services { public class SearchableQuery<T> where T : ISearchable { public static SqlQuerySpec Create(string collectionId, IEnumerable<string> searchTerms, int top = 0) { var topSelect = top > 0 ? $"TOP {top}" : ""; var query = $"SELECT {topSelect} VALUE o FROM {collectionId} o WHERE 1=1 {CreateSearchTermWhereClause(searchTerms)}"; return new SqlQuerySpec { QueryText = query, Parameters = CreateParams(searchTerms) }; } public static SqlQuerySpec Count(string collectionId, IEnumerable<string> searchTerms) { var query = $"SELECT COUNT(1) as Count FROM {collectionId} o WHERE 1=1 {CreateSearchTermWhereClause(searchTerms)}"; return new SqlQuerySpec { QueryText = query, Parameters = CreateParams(searchTerms) }; } static string CreateSearchTermWhereClause(IEnumerable<string> searchTerms) { var counter = 0; var searchterms = searchTerms.Where(term => term.Length > 0).Select(term => $"CONTAINS(o.{nameof(ISearchable.SearchString).ToLower()}, @param{counter++})").ToArray(); if (counter > 0) return $"AND {searchterms.Aggregate((current, next) => $"{current} AND {next}")}"; return ""; } static SqlParameterCollection CreateParams(IEnumerable<string> searchTerms) { var counter = 0; return new SqlParameterCollection(searchTerms.Select(searchTerm => new SqlParameter { Name = $"@param{counter++}", Value = searchTerm })); } } }
using Microsoft.Azure.Documents; using System.Collections.Generic; using System.Linq; using TheCollection.Web.Models; namespace TheCollection.Web.Services { public class SearchableQuery<T> where T : ISearchable { public static SqlQuerySpec Create(string collectionId, IEnumerable<string> searchTerms, int top = 0) { var counter = 0; var topSelect = top > 0 ? $"TOP {top}" : ""; var searchterms = searchTerms.Select(term => $"CONTAINS(o.{nameof(ISearchable.SearchString).ToLower()}, @param{counter++})").ToArray(); var query = $"SELECT {topSelect} VALUE o FROM {collectionId} o WHERE {searchterms.Aggregate((current, next) => current + " AND " + next)}"; return new SqlQuerySpec { QueryText = query, Parameters = CreateParams(searchTerms) }; } public static SqlQuerySpec Count(string collectionId, IEnumerable<string> searchTerms) { var counter = 0; var searchterms = searchTerms.Select(term => $"CONTAINS(o.{nameof(ISearchable.SearchString).ToLower()}, @param{counter++})").ToArray(); var query = $"SELECT COUNT(1) as Count FROM {collectionId} o WHERE {searchterms.Aggregate((current, next) => current + " AND " + next)}"; return new SqlQuerySpec { QueryText = query, Parameters = CreateParams(searchTerms) }; } static SqlParameterCollection CreateParams(IEnumerable<string> searchTerms) { var counter = 0; return new SqlParameterCollection(searchTerms.Select(searchTerm => new SqlParameter { Name = $"@param{counter++}", Value = searchTerm })); } } }
apache-2.0
C#
fee007d07f86002b6aa96897136c098487020b9e
fix test
bijakatlykkex/NBitcoin.Indexer,NicolasDorier/NBitcoin.Indexer,MetacoSA/NBitcoin.Indexer
NBitcoin.Indexer/IndexerTransactionRepository.cs
NBitcoin.Indexer/IndexerTransactionRepository.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NBitcoin.Indexer { public class IndexerTransactionRepository : ITransactionRepository { private readonly IndexerConfiguration _Configuration; public IndexerConfiguration Configuration { get { return _Configuration; } } public IndexerTransactionRepository(IndexerConfiguration config) { if (config == null) throw new ArgumentNullException("config"); _Configuration = config; } #region ITransactionRepository Members public Transaction Get(uint256 txId) { var tx = _Configuration.CreateIndexerClient().GetTransactionAsync(false, txId).Result; if (tx == null) return null; return tx.Transaction; } public void Put(uint256 txId, Transaction tx) { _Configuration.CreateIndexer().Index(new TransactionEntry.Entity(txId, tx, null)); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NBitcoin.Indexer { public class IndexerTransactionRepository : ITransactionRepository { private readonly IndexerConfiguration _Configuration; public IndexerConfiguration Configuration { get { return _Configuration; } } public IndexerTransactionRepository(IndexerConfiguration config) { if (config == null) throw new ArgumentNullException("config"); _Configuration = config; } #region ITransactionRepository Members public Transaction Get(uint256 txId) { var tx = _Configuration.CreateIndexerClient().GetTransactionAsync(txId).Result; if (tx == null) return null; return tx.Transaction; } public void Put(uint256 txId, Transaction tx) { _Configuration.CreateIndexer().Index(new TransactionEntry.Entity(txId, tx, null)); } #endregion } }
mit
C#
b145aa4cc99d63399f579da9de46b3c90fed3f42
Make sure Android back button doesn't return to the menu when we are on a game screen.
Noxalus/Xmas-Hell
Xmas-Hell/Xmas-Hell-Core/Screens/ScreenManager.cs
Xmas-Hell/Xmas-Hell-Core/Screens/ScreenManager.cs
using Microsoft.Xna.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace XmasHell.Screens { public class ScreenManager { private XmasHell _game; private List<Screen> _screens; private Screen _currentScreen; private Stack<Screen> _screenHistory; public ScreenManager(XmasHell game) { _game = game; _screens = new List<Screen>(); _currentScreen = null; _screenHistory = new Stack<Screen>(); } public void AddScreen(Screen screen) { if (_screens.Contains(screen)) throw new Exception("This screen already exists!"); _screens.Add(screen); } public T GetScreen<T>() where T : Screen { return _screens.OfType<T>().FirstOrDefault(); } public void GoTo<T>() where T : Screen { var screen = GetScreen<T>(); if (screen == null) throw new InvalidOperationException($"{typeof(T).Name} not registered"); GoTo(screen); } private void GoTo(Screen screen) { _currentScreen?.Hide(); if (_currentScreen != null && _currentScreen.StackInHistory) _screenHistory.Push(_currentScreen); _currentScreen = screen; _currentScreen.Show(); } public void Back() { if (_screenHistory.Count > 0 && _currentScreen.GetScreenType() != ScreenType.Game) GoTo(_screenHistory.Pop()); } public Screen GetPreviousScreen() { if (_screenHistory.Count == 0) return null; return _screenHistory.Peek(); } public void Update(GameTime gameTime) { _currentScreen?.Update(gameTime); } } }
using Microsoft.Xna.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace XmasHell.Screens { public class ScreenManager { private XmasHell _game; private List<Screen> _screens; private Screen _currentScreen; private Stack<Screen> _screenHistory; public ScreenManager(XmasHell game) { _game = game; _screens = new List<Screen>(); _currentScreen = null; _screenHistory = new Stack<Screen>(); } public void AddScreen(Screen screen) { if (_screens.Contains(screen)) throw new Exception("This screen already exists!"); _screens.Add(screen); } public T GetScreen<T>() where T : Screen { return _screens.OfType<T>().FirstOrDefault(); } public void GoTo<T>() where T : Screen { var screen = GetScreen<T>(); if (screen == null) throw new InvalidOperationException($"{typeof(T).Name} not registered"); GoTo(screen); } private void GoTo(Screen screen) { _currentScreen?.Hide(); if (_currentScreen != null && _currentScreen.StackInHistory) _screenHistory.Push(_currentScreen); _currentScreen = screen; _currentScreen.Show(); } public void Back() { if (_screenHistory.Count > 0) GoTo(_screenHistory.Pop()); } public Screen GetPreviousScreen() { if (_screenHistory.Count == 0) return null; return _screenHistory.Peek(); } public void Update(GameTime gameTime) { _currentScreen?.Update(gameTime); } } }
mit
C#
c3695a081a4e0964b32a99e3e5caa16f6accfbb9
Add the OrderTableId to RetrieveConstants for syncing
Dav2070/UniversalSoundBoard
UniversalSoundBoard/Common/RetrieveConstants.cs
UniversalSoundBoard/Common/RetrieveConstants.cs
using System.Collections.Generic; using davClassLibrary.Common; using UniversalSoundBoard.DataAccess; namespace UniversalSoundboard.Common { public class RetrieveConstants : IRetrieveConstants { public string GetApiKey() { return FileManager.ApiKey; } public string GetDataPath() { return FileManager.GetDavDataPath(); } public int GetAppId() { return FileManager.AppId; } public List<int> GetTableIds() { return new List<int> { FileManager.OrderTableId, FileManager.CategoryTableId, FileManager.SoundTableId, FileManager.SoundFileTableId, FileManager.PlayingSoundTableId, FileManager.ImageFileTableId }; } public List<int> GetParallelTableIds() { return new List<int> { FileManager.SoundTableId, FileManager.SoundFileTableId }; } } }
using System.Collections.Generic; using davClassLibrary.Common; using UniversalSoundBoard.DataAccess; namespace UniversalSoundboard.Common { public class RetrieveConstants : IRetrieveConstants { public string GetApiKey() { return FileManager.ApiKey; } public string GetDataPath() { return FileManager.GetDavDataPath(); } public int GetAppId() { return FileManager.AppId; } public List<int> GetTableIds() { return new List<int> { FileManager.CategoryTableId, FileManager.SoundTableId, FileManager.SoundFileTableId, FileManager.PlayingSoundTableId, FileManager.ImageFileTableId }; } public List<int> GetParallelTableIds() { return new List<int> { FileManager.SoundTableId, FileManager.SoundFileTableId }; } } }
mit
C#
01000d50cd63c32966b0c765950f2d5eafc461ce
Use local NullNotificationManager
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi.Gui/Helpers/NotificationHelpers.cs
WalletWasabi.Gui/Helpers/NotificationHelpers.cs
using Avalonia.Controls.Notifications; using ReactiveUI; using Splat; using System; using System.Reactive.Concurrency; namespace WalletWasabi.Gui.Helpers { public static class NotificationHelpers { class NullNotificationManager : INotificationManager { public void Show(INotification notification) { } } private static readonly INotificationManager nullNotificationManager = new NullNotificationManager(); public static INotificationManager GetNotificationManager() { return Locator.Current.GetService<INotificationManager>() ?? nullNotificationManager; } public static void Success(string message, string title = "Success!") { RxApp.MainThreadScheduler .Schedule(() => GetNotificationManager() .Show(new Notification(title, message, NotificationType.Success, TimeSpan.FromSeconds(7)))); } public static void Information(string message, string title = "Info") { RxApp.MainThreadScheduler .Schedule(() => GetNotificationManager() .Show(new Notification(title, message, NotificationType.Information, TimeSpan.FromSeconds(7)))); } public static void Warning(string message, string title = "Warning!") { RxApp.MainThreadScheduler .Schedule(() => GetNotificationManager() .Show(new Notification(title, message, NotificationType.Warning, TimeSpan.FromSeconds(7)))); } public static void Error(string message, string title = "Error") { RxApp.MainThreadScheduler .Schedule(() => GetNotificationManager() .Show(new Notification(title, message, NotificationType.Error, TimeSpan.FromSeconds(7)))); } } }
using Avalonia.Controls.Notifications; using ReactiveUI; using Splat; using System; using System.Reactive.Concurrency; namespace WalletWasabi.Gui.Helpers { public static class NotificationHelpers { public static INotificationManager GetNotificationManager() { return Locator.Current.GetService<INotificationManager>(); } public static void Success(string message, string title = "Success!") { RxApp.MainThreadScheduler .Schedule(() => GetNotificationManager() .Show(new Notification(title, message, NotificationType.Success, TimeSpan.FromSeconds(7)))); } public static void Information(string message, string title = "Info") { RxApp.MainThreadScheduler .Schedule(() => GetNotificationManager() .Show(new Notification(title, message, NotificationType.Information, TimeSpan.FromSeconds(7)))); } public static void Warning(string message, string title = "Warning!") { RxApp.MainThreadScheduler .Schedule(() => GetNotificationManager() .Show(new Notification(title, message, NotificationType.Warning, TimeSpan.FromSeconds(7)))); } public static void Error(string message, string title = "Error") { RxApp.MainThreadScheduler .Schedule(() => GetNotificationManager() .Show(new Notification(title, message, NotificationType.Error, TimeSpan.FromSeconds(7)))); } } }
mit
C#
fb6e243b2892fc6d7479524b5f2abf33a2d9e956
Resolve output path for download, so that on restart will go to the correct location.
dipeshc/BTDeploy
BTDeploy/Client.Commands/Add.cs
BTDeploy/Client.Commands/Add.cs
using ServiceStack.Service; using ServiceStack.Common.Web; using System.IO; using BTDeploy.ServiceDaemon.TorrentClients; using BTDeploy.ServiceDaemon; using System.Linq; using System.Threading; using System; namespace BTDeploy.Client.Commands { public class Add : ClientCommandBase { public string TorrentPath; public string OuputDirectoryPath; public bool Mirror = false; public bool Wait = false; public Add (IRestClient client) : base(client) { IsCommand ("add", "Adds a torrent to be deployed."); HasRequiredOption ("t|torrent=", "Torrent file path.", o => TorrentPath = o); HasRequiredOption ("o|outputDirectory=", "Output directory path for downloaded torrent.", o => OuputDirectoryPath = o); HasOption ("m|mirror", "Walks the output directory to make sure it mirrors the torrent. Any additional files will be deleted.", o => Mirror = o != null); HasOption ("w|wait", "Wait for torrent to finish downloading before exiting.", o => Wait = o != null); } public override int Run (string[] remainingArguments) { var OutputDirectoryPathFull = Path.GetFullPath (OuputDirectoryPath); var postUri = "/api/torrents?OutputDirectoryPath=" + OutputDirectoryPathFull + "&mirror=" + Mirror.ToString(); var addedTorrentDetails = Client.PostFile<TorrentDetails> (postUri, new FileInfo(TorrentPath), MimeTypes.GetMimeType (TorrentPath)); if (!Wait) return 0; while(true) { Thread.Sleep(1000); var trackedTorrentDetails = Client.Get (new TorrentsListRequest ()).First(torrentDetails => torrentDetails.Id == addedTorrentDetails.Id); if (trackedTorrentDetails.Status == TorrentStatus.Error) return 1; if (trackedTorrentDetails.Status == TorrentStatus.Seeding) break; var downloadSpeedInKBs = Math.Round(trackedTorrentDetails.DownloadBytesPerSecond / Math.Pow(2, 10), 2); Console.Write ("Completed {0:f2}%, {1:f2}KB/s\r", trackedTorrentDetails.Progress, downloadSpeedInKBs); } return 0; } } }
using ServiceStack.Service; using ServiceStack.Common.Web; using System.IO; using BTDeploy.ServiceDaemon.TorrentClients; using BTDeploy.ServiceDaemon; using System.Linq; using System.Threading; using System; namespace BTDeploy.Client.Commands { public class Add : ClientCommandBase { public string TorrentPath; public string OuputDirectoryPath; public bool Mirror = false; public bool Wait = false; public Add (IRestClient client) : base(client) { IsCommand ("add", "Adds a torrent to be deployed."); HasRequiredOption ("t|torrent=", "Torrent file path.", o => TorrentPath = o); HasRequiredOption ("o|outputDirectory=", "Output directory path for downloaded torrent.", o => OuputDirectoryPath = o); HasOption ("m|mirror", "Walks the output directory to make sure it mirrors the torrent. Any additional files will be deleted.", o => Mirror = o != null); HasOption ("w|wait", "Wait for torrent to finish downloading before exiting.", o => Wait = o != null); } public override int Run (string[] remainingArguments) { var postUri = "/api/torrents?OutputDirectoryPath=" + OuputDirectoryPath + "&mirror=" + Mirror.ToString(); var addedTorrentDetails = Client.PostFile<TorrentDetails> (postUri, new FileInfo(TorrentPath), MimeTypes.GetMimeType (TorrentPath)); if (!Wait) return 0; while(true) { Thread.Sleep(1000); var trackedTorrentDetails = Client.Get (new TorrentsListRequest ()).First(torrentDetails => torrentDetails.Id == addedTorrentDetails.Id); if (trackedTorrentDetails.Status == TorrentStatus.Error) return 1; if (trackedTorrentDetails.Status == TorrentStatus.Seeding) break; var downloadSpeedInKBs = Math.Round(trackedTorrentDetails.DownloadBytesPerSecond / Math.Pow(2, 10), 2); Console.Write ("Completed {0:f2}%, {1:f2}KB/s\r", trackedTorrentDetails.Progress, downloadSpeedInKBs); } return 0; } } }
mit
C#
5738f12bc11550dd3c8605d9beb03c71abc1b07a
Make NilProcess singleton
lou1306/CIV,lou1306/CIV
CIV.Ccs/Processes/NilProcess.cs
CIV.Ccs/Processes/NilProcess.cs
using System.Collections.Generic; using System.Linq; using CIV.Interfaces; namespace CIV.Ccs { /// <summary> /// Nil process. Implemented as a singleton class. /// </summary> class NilProcess : CcsProcess { public static NilProcess Instance { get; } = new NilProcess(); NilProcess(){} public override IEnumerable<Transition> Transitions() { return Enumerable.Empty<Transition>(); } public override bool Equals(CcsProcess other) => other is NilProcess; public override int GetHashCode() => 1; } }
using System.Collections.Generic; using System.Linq; using CIV.Interfaces; namespace CIV.Ccs { class NilProcess : CcsProcess { public override IEnumerable<Transition> Transitions() { return Enumerable.Empty<Transition>(); } } }
mit
C#