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
8d6d724970903e46516ca6ef7eac2323182f0a75
Add missing await on CachingClientStore
MienDev/IdentityServer4,MienDev/IdentityServer4,IdentityServer/IdentityServer4,IdentityServer/IdentityServer4,IdentityServer/IdentityServer4,IdentityServer/IdentityServer4,MienDev/IdentityServer4,MienDev/IdentityServer4
src/IdentityServer4/src/Stores/Caching/CachingClientStore.cs
src/IdentityServer4/src/Stores/Caching/CachingClientStore.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 IdentityServer4.Extensions; using IdentityServer4.Models; using IdentityServer4.Services; using System.Threading.Tasks; using IdentityServer4.Configuration; using Microsoft.Extensions.Logging; namespace IdentityServer4.Stores { /// <summary> /// Cache decorator for IClientStore /// </summary> /// <typeparam name="T"></typeparam> /// <seealso cref="IdentityServer4.Stores.IClientStore" /> public class CachingClientStore<T> : IClientStore where T : IClientStore { private readonly IdentityServerOptions _options; private readonly ICache<Client> _cache; private readonly IClientStore _inner; private readonly ILogger _logger; /// <summary> /// Initializes a new instance of the <see cref="CachingClientStore{T}"/> class. /// </summary> /// <param name="options">The options.</param> /// <param name="inner">The inner.</param> /// <param name="cache">The cache.</param> /// <param name="logger">The logger.</param> public CachingClientStore(IdentityServerOptions options, T inner, ICache<Client> cache, ILogger<CachingClientStore<T>> logger) { _options = options; _inner = inner; _cache = cache; _logger = logger; } /// <summary> /// Finds a client by id /// </summary> /// <param name="clientId">The client id</param> /// <returns> /// The client /// </returns> public async Task<Client> FindClientByIdAsync(string clientId) { var client = await _cache.GetAsync(clientId, _options.Caching.ClientStoreExpiration, async () => await _inner.FindClientByIdAsync(clientId), _logger); return client; } } }
// 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 IdentityServer4.Extensions; using IdentityServer4.Models; using IdentityServer4.Services; using System.Threading.Tasks; using IdentityServer4.Configuration; using Microsoft.Extensions.Logging; namespace IdentityServer4.Stores { /// <summary> /// Cache decorator for IClientStore /// </summary> /// <typeparam name="T"></typeparam> /// <seealso cref="IdentityServer4.Stores.IClientStore" /> public class CachingClientStore<T> : IClientStore where T : IClientStore { private readonly IdentityServerOptions _options; private readonly ICache<Client> _cache; private readonly IClientStore _inner; private readonly ILogger _logger; /// <summary> /// Initializes a new instance of the <see cref="CachingClientStore{T}"/> class. /// </summary> /// <param name="options">The options.</param> /// <param name="inner">The inner.</param> /// <param name="cache">The cache.</param> /// <param name="logger">The logger.</param> public CachingClientStore(IdentityServerOptions options, T inner, ICache<Client> cache, ILogger<CachingClientStore<T>> logger) { _options = options; _inner = inner; _cache = cache; _logger = logger; } /// <summary> /// Finds a client by id /// </summary> /// <param name="clientId">The client id</param> /// <returns> /// The client /// </returns> public async Task<Client> FindClientByIdAsync(string clientId) { var client = await _cache.GetAsync(clientId, _options.Caching.ClientStoreExpiration, () => _inner.FindClientByIdAsync(clientId), _logger); return client; } } }
apache-2.0
C#
d73afe3973005de93e639fa155e1af61b380404c
Fix Shy sound trigger
bschug/boatbaby
Assets/ShyAnimationBehaviour.cs
Assets/ShyAnimationBehaviour.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ShyAnimationBehaviour : StateMachineBehaviour { // OnStateEnter is called when a transition starts and the state machine starts to evaluate this state override public void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) { BabySoundManager.Instance.Shy(); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ShyAnimationBehaviour : StateMachineBehaviour { // OnStateEnter is called when a transition starts and the state machine starts to evaluate this state //override public void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) { // //} // OnStateUpdate is called on each Update frame between OnStateEnter and OnStateExit callbacks //override public void OnStateUpdate(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) { // //} // OnStateExit is called when a transition ends and the state machine finishes evaluating this state //override public void OnStateExit(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) { // //} // OnStateMove is called right after Animator.OnAnimatorMove(). Code that processes and affects root motion should be implemented here //override public void OnStateMove(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) { // //} // OnStateIK is called right after Animator.OnAnimatorIK(). Code that sets up animation IK (inverse kinematics) should be implemented here. //override public void OnStateIK(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) { // //} }
mit
C#
4c344f360cd0788b26fd4af28b7e3f7e195dab5f
Bump version
klesta490/BTDB,karasek/BTDB,Bobris/BTDB
BTDB/Properties/AssemblyInfo.cs
BTDB/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("BTDB")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("BTDB")] [assembly: AssemblyCopyright("Copyright � Boris Letocha 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM componenets. 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("d949b20a-70ec-46bf-8eed-3a3cfb0d4593")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision [assembly: AssemblyVersion("3.2.3.0")] [assembly: AssemblyFileVersion("3.2.3.0")] [assembly: InternalsVisibleTo("BTDBTest")]
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("BTDB")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("BTDB")] [assembly: AssemblyCopyright("Copyright � Boris Letocha 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM componenets. 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("d949b20a-70ec-46bf-8eed-3a3cfb0d4593")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision [assembly: AssemblyVersion("3.2.2.0")] [assembly: AssemblyFileVersion("3.2.2.0")] [assembly: InternalsVisibleTo("BTDBTest")]
mit
C#
580b738f2f12b7b84872459ce94d2855580058bd
Update SmallAppliances.cs
jkanchelov/Telerik-OOP-Team-StarFruit
TeamworkStarFruit/CatalogueLib/Products/SmallAppliances.cs
TeamworkStarFruit/CatalogueLib/Products/SmallAppliances.cs
namespace CatalogueLib { using CatalogueLib.Products.Enumerations; public abstract class SmallAppliances : Product { public SmallAppliances() { } public SmallAppliances(int ID, decimal price, bool isAvailable, Brand brand, double Capacity, double CableLength, int Affixes) : base(ID, price, isAvailable, brand) { this.Capacity = Capacity; this.CableLength = CableLength; this.Affixes = Affixes; } public double Capacity { get; private set; } public double CableLength { get; private set; } public int Affixes { get; private set; } public override string ToString() { StringBuilder stroitel = new StringBuilder(); stroitel = stroitel.Append(string.Format("{0}", base.ToString())); stroitel = stroitel.Append(string.Format(" Capacity: {0}\n Cable length: {1}\n Affixes: {2}", this.Capacity, this.CableLength, this.Affixes)); return stroitel.AppendLine().ToString(); } } }
namespace CatalogueLib { using CatalogueLib.Products.Enumerations; public abstract class SmallAppliances : Product { public SmallAppliances() { } public SmallAppliances(int ID, decimal price, bool isAvailable, Brand brand, double Capacity, double CableLength, int Affixes) : base(ID, price, isAvailable, brand) { this.Capacity = Capacity; this.CableLength = CableLength; this.Affixes = Affixes; } public double Capacity { get; private set; } public double CableLength { get; private set; } public int Affixes { get; private set; } public override string ToString() { return base.ToString() + $"\nCapacity: {this.Capacity}\nCable length:{this.CableLength}\nAffixes: {this.Affixes}"; } } }
mit
C#
aebc23e3ca77512ff2665b6261453c2be01d0a32
Revert code coverage test
ClearPeopleLtd/Habitat,ClearPeopleLtd/Habitat,nurunquebec/Habitat,bhaveshmaniya/Habitat,zyq524/Habitat,zyq524/Habitat,bhaveshmaniya/Habitat,GoranHalvarsson/Habitat,nurunquebec/Habitat,GoranHalvarsson/Habitat
src/Feature/Person/code/Indexing/PersonIndexContentProvider.cs
src/Feature/Person/code/Indexing/PersonIndexContentProvider.cs
namespace Sitecore.Feature.Person.Indexing { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq.Expressions; using Sitecore.Foundation.Indexing.Infrastructure; using Sitecore.Foundation.Indexing.Models; using Sitecore.Foundation.SitecoreExtensions.Repositories; using Sitecore.ContentSearch.SearchTypes; using Sitecore.Data; using Sitecore.Web.UI.WebControls; public class PersonIndexContentProvider : IndexContentProviderBase { public override string ContentType => DictionaryRepository.Get("/person/search/contenttype", "Person"); public override IEnumerable<ID> SupportedTemplates => new[] { Templates.Employee.ID }; public override Expression<Func<SearchResultItem, bool>> GetQueryPredicate(IQuery query) { var fieldNames = new[] { Templates.Person.Fields.Title_FieldName, Templates.Person.Fields.Summary_FieldName, Templates.Person.Fields.Name_FieldName, Templates.Employee.Fields.Biography_FieldName }; return this.GetFreeTextPredicate(fieldNames, query); } public override void FormatResult(SearchResultItem item, ISearchResult formattedResult) { var contentItem = item.GetItem(); formattedResult.Title = FieldRenderer.Render(contentItem, Templates.Person.Fields.Name.ToString()); formattedResult.Description = FieldRenderer.Render(contentItem, Templates.Person.Fields.Summary.ToString()); } } }
namespace Sitecore.Feature.Person.Indexing { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq.Expressions; using Sitecore.Foundation.Indexing.Infrastructure; using Sitecore.Foundation.Indexing.Models; using Sitecore.Foundation.SitecoreExtensions.Repositories; using Sitecore.ContentSearch.SearchTypes; using Sitecore.Data; using Sitecore.Web.UI.WebControls; public class PersonIndexContentProvider : IndexContentProviderBase { public override string ContentType => DictionaryRepository.Get("/person/search/contenttype", "Person"); public override IEnumerable<ID> SupportedTemplates => new[] { Templates.Employee.ID }; //TODO: Unit test [ExcludeFromCodeCoverage] public override Expression<Func<SearchResultItem, bool>> GetQueryPredicate(IQuery query) { var fieldNames = new[] { Templates.Person.Fields.Title_FieldName, Templates.Person.Fields.Summary_FieldName, Templates.Person.Fields.Name_FieldName, Templates.Employee.Fields.Biography_FieldName }; return this.GetFreeTextPredicate(fieldNames, query); } //TODO: Unit test [ExcludeFromCodeCoverage] public override void FormatResult(SearchResultItem item, ISearchResult formattedResult) { var contentItem = item.GetItem(); formattedResult.Title = FieldRenderer.Render(contentItem, Templates.Person.Fields.Name.ToString()); formattedResult.Description = FieldRenderer.Render(contentItem, Templates.Person.Fields.Summary.ToString()); } } }
apache-2.0
C#
6660aab35e41501c78e382d7d08880367f07d2fc
Update AssemblyInfo
michaelcfanning/codeformatter,twsouthwick/codeformatter,mmitche/codeformatter,shiftkey/Octokit.CodeFormatter,srivatsn/codeformatter,weltkante/codeformatter,dotnet/codeformatter,david-mitchell/codeformatter,cbjugstad/codeformatter,shiftkey/codeformatter,BertTank/codeformatter,jeremyabbott/codeformatter,rollie42/codeformatter,dotnet/codeformatter,kharaone/codeformatter,Maxwe11/codeformatter,BradBarnich/codeformatter,twsouthwick/codeformatter,jaredpar/codeformatter,mmitche/codeformatter,hickford/codeformatter,rainersigwald/codeformatter
src/Microsoft.DotNet.CodeFormatting/Properties/AssemblyInfo.cs
src/Microsoft.DotNet.CodeFormatting/Properties/AssemblyInfo.cs
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyCopyright("\x00a9 Microsoft Corporation. All rights reserved.")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0.0")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyTitle("Microsoft.DotNet.CodeFormatting")] [assembly: AssemblyProduct("Microsoft.DotNet.CodeFormatting")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: InternalsVisibleTo("Microsoft.DotNet.CodeFormatting.Tests")]
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Microsoft.DotNet.CodeFormatting")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Microsoft.DotNet.CodeFormatting")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: InternalsVisibleTo("Microsoft.DotNet.CodeFormatting.Tests")] // 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("c950a4bd-7014-4d1f-a1e0-9945016cf07f")] // 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#
ae1393f20faa126b585c6477eadcb9461004f3a3
refactor header test
northwoodspd/UIA.Extensions,northwoodspd/UIA.Extensions
src/UIA.Fluent.Units/AutomationProviders/HeaderProviderTest.cs
src/UIA.Fluent.Units/AutomationProviders/HeaderProviderTest.cs
using System.Collections.Generic; using System.Windows.Automation; using System.Windows.Automation.Provider; using NUnit.Framework; using Should.Fluent; namespace UIA.Fluent.AutomationProviders { [TestFixture] public class HeaderProviderTest { private List<string> _headers; [SetUp] public void SetUp() { _header = null; _headers = new List<string>(); } [Test] public void ItHasTheCorrectControlType() { HeaderProvider.GetPropertyValue(AutomationElementIdentifiers.ControlTypeProperty.Id) .Should().Equal(ControlType.Header.Id); } [Test] public void FirstHeaderIsTheFirstChild() { _headers.Add("First Column"); FirstChild.Name.Should().Equal("First Column"); } [Test] public void LastHeaderIsTheLastChild() { _headers.AddRange(new[] { "First Column", "Last Column" }); LastChild.Name.Should().Equal("Last Column"); } private HeaderItemProvider FirstChild { get { return HeaderProvider.Navigate(NavigateDirection.FirstChild) as HeaderItemProvider; } } private HeaderItemProvider LastChild { get { return HeaderProvider.Navigate(NavigateDirection.LastChild) as HeaderItemProvider; } } private HeaderProvider _header; private HeaderProvider HeaderProvider { get { return _header ?? (_header = new HeaderProvider(null, _headers)); } } } }
using System.Collections.Generic; using System.Windows.Automation; using System.Windows.Automation.Provider; using NUnit.Framework; using Should.Fluent; namespace UIA.Fluent.AutomationProviders { [TestFixture] public class HeaderProviderTest { private List<string> _headers; [SetUp] public void SetUp() { _header = null; _headers = new List<string>(); } [Test] public void ItHasTheCorrectControlType() { HeaderProvider.GetPropertyValue(AutomationElementIdentifiers.ControlTypeProperty.Id) .Should().Equal(ControlType.Header.Id); } [Test] public void FirstHeaderIsTheFirstChild() { _headers.Add("First Column"); var firstChild = HeaderProvider.Navigate(NavigateDirection.FirstChild) as HeaderItemProvider; firstChild.Name.Should().Equal("First Column"); } [Test] public void LastHeaderIsTheLastChild() { _headers.Add("First Column"); _headers.Add("Last Column"); var lastChild = HeaderProvider.Navigate(NavigateDirection.LastChild) as HeaderItemProvider; lastChild.Name.Should().Equal("Last Column"); } private HeaderProvider _header; private HeaderProvider HeaderProvider { get { return _header ?? (_header = new HeaderProvider(null, _headers)); } } } }
mit
C#
49c1ad5e7c7a38b1924b332b4db29e9a03967265
Remove ISubject's covariance/contravariance
Useurmind/UniRx,OrangeCube/UniRx,neuecc/UniRx,zhutaorun/UniRx,kimsama/UniRx,cruwel/UniRx,juggernate/UniRx,zillakot/UniRx,ufcpp/UniRx,juggernate/UniRx,m-ishikawa/UniRx,saruiwa/UniRx,ic-sys/UniRx,zhutaorun/UniRx,ppcuni/UniRx,zhutaorun/UniRx,cruwel/UniRx,endo0407/UniRx,zillakot/UniRx,ataihei/UniRx,InvertGames/UniRx,TORISOUP/UniRx,juggernate/UniRx,Useurmind/UniRx,Useurmind/UniRx,ic-sys/UniRx,zillakot/UniRx,ic-sys/UniRx,cruwel/UniRx,OC-Leon/UniRx
Assets/UniRx/Scripts/Subjects/ISubject.cs
Assets/UniRx/Scripts/Subjects/ISubject.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace UniRx { public interface ISubject<TSource, TResult> : IObserver<TSource>, IObservable<TResult> { } public interface ISubject<T> : ISubject<T, T>, IObserver<T>, IObservable<T> { } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace UniRx { public interface ISubject<in TSource, out TResult> : IObserver<TSource>, IObservable<TResult> { } public interface ISubject<T> : ISubject<T, T>, IObserver<T>, IObservable<T> { } }
mit
C#
934a0da93af1e26049e5a7e0e8d77fd5e0e4c83d
Update AssemblyInfo.cs
alexguirre/RAGENativeUI,alexguirre/RAGENativeUI
Source/Properties/AssemblyInfo.cs
Source/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("RAGENativeUI")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("RAGENativeUI")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("f3e16ed9-dbf7-4e7b-b04b-9b24b11891d3")] [assembly: AssemblyVersion("1.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("NativeUI")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("NativeUI")] [assembly: AssemblyCopyright("Copyright 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("f3e16ed9-dbf7-4e7b-b04b-9b24b11891d3")] // 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#
ceaa6312742f26040a6dedaae37c53ccedf0ed5c
Remove unused code
EamonNerbonne/ExpressionToCode
ExpressionToCodeLib/FormatStringParser.cs
ExpressionToCodeLib/FormatStringParser.cs
namespace ExpressionToCodeLib; public static class FormatStringParser { public struct Segment { public string InitialStringPart; public object FollowedByValue; public string WithFormatString; } public static (Segment[] segments, string Tail) ParseFormatString(string formatString, object[] formatArguments) => new FormattableStringParser(formatString, formatArguments).Finish(); sealed class FormattableStringParser : IFormatProvider, ICustomFormatter { //Format strings have exceptions for stuff like double curly braces //There are also corner-cases that non-compiler generated format strings might hit //All in all: rather than reimplement a custom parser, this readonly StringBuilder sb = new(); readonly List<Segment> Segments = new(); public FormattableStringParser(string formatString, object[] formatArguments) => sb.AppendFormat(this, formatString, formatArguments); object IFormatProvider.GetFormat(Type formatType) => this; public (Segment[] segments, string Tail) Finish() => (Segments.ToArray(), sb.ToString()); string ICustomFormatter.Format(string format, object arg, IFormatProvider formatProvider) { Segments.Add( new Segment { InitialStringPart = sb.ToString(), FollowedByValue = arg, WithFormatString = format, }); sb.Length = 0; return ""; } } }
namespace ExpressionToCodeLib; public static class FormatStringParser { public struct Segment { public string InitialStringPart; public object FollowedByValue; public string WithFormatString; } #if !NET452 public static (Segment[] segments, string Tail) ParseFormatString(FormattableString formattableString) => new FormattableStringParser(formattableString.Format, formattableString.GetArguments()).Finish(); #endif public static (Segment[] segments, string Tail) ParseFormatString(string formatString, object[] formatArguments) => new FormattableStringParser(formatString, formatArguments).Finish(); sealed class FormattableStringParser : IFormatProvider, ICustomFormatter { //Format strings have exceptions for stuff like double curly braces //There are also corner-cases that non-compiler generated format strings might hit //All in all: rather than reimplement a custom parser, this readonly StringBuilder sb = new(); readonly List<Segment> Segments = new(); public FormattableStringParser(string formatString, object[] formatArguments) => sb.AppendFormat(this, formatString, formatArguments); object IFormatProvider.GetFormat(Type formatType) => this; public (Segment[] segments, string Tail) Finish() => (Segments.ToArray(), sb.ToString()); string ICustomFormatter.Format(string format, object arg, IFormatProvider formatProvider) { Segments.Add( new Segment { InitialStringPart = sb.ToString(), FollowedByValue = arg, WithFormatString = format, }); sb.Length = 0; return ""; } } }
apache-2.0
C#
eb780ec44e964e6f0a21e8d4f9b7a909575e2b24
remove whitespace
MarcosMeli/FileHelpers
FileHelpers.Tests/Helpers/FSharpHelper.cs
FileHelpers.Tests/Helpers/FSharpHelper.cs
#if NETCOREAPP using System; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading; using System.Threading.Tasks; using FSharp.Compiler; using FSharp.Compiler.SourceCodeServices; using Microsoft.FSharp.Control; using Microsoft.FSharp.Core; namespace FileHelpers.Tests.Helpers { public static class FSharpHelper { public static Assembly Compile(string source) { var fileHelpersAssembly = typeof(EngineBase).Assembly; var checker = FSharpChecker.Create( FSharpOption<int>.None, FSharpOption<bool>.None, FSharpOption<bool>.None, FSharpOption<LegacyReferenceResolver>.None, FSharpOption<FSharpFunc<Tuple<string, DateTime>, FSharpOption<Tuple<object, IntPtr, int>>>>.None, FSharpOption<bool>.None, FSharpOption<bool>.None, FSharpOption<bool>.None, FSharpOption<bool>.None); var file = Path.GetTempFileName(); File.WriteAllText(file + ".fs", source); var action = checker.CompileToDynamicAssembly( new[] {"-o", file + ".dll", "-a", file + ".fs", "--reference:" + fileHelpersAssembly.Location}, FSharpOption<Tuple<TextWriter, TextWriter>>.None, FSharpOption<string>.None); var compileResult = FSharpAsync .StartAsTask(action, FSharpOption<TaskCreationOptions>.None, FSharpOption<CancellationToken>.None) .Result; var exitCode = compileResult.Item2; var compilationErrors = compileResult.Item1; if (compilationErrors.Any() && exitCode != 0) { var errors = new StringBuilder(); foreach (var error in compilationErrors) { errors.AppendLine(error.ToString()); } throw new InvalidOperationException($"Cannot compile fsharp: {errors}"); } return compileResult.Item3.Value; } } } #endif
#if NETCOREAPP using System; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading; using System.Threading.Tasks; using FSharp.Compiler; using FSharp.Compiler.SourceCodeServices; using Microsoft.FSharp.Control; using Microsoft.FSharp.Core; namespace FileHelpers.Tests.Helpers { public static class FSharpHelper { public static Assembly Compile(string source) { var fileHelpersAssembly = typeof(EngineBase).Assembly; var checker = FSharpChecker.Create( FSharpOption<int>.None, FSharpOption<bool>.None, FSharpOption<bool>.None, FSharpOption<LegacyReferenceResolver>.None, FSharpOption<FSharpFunc<Tuple<string, DateTime>, FSharpOption<Tuple<object, IntPtr, int>>>>.None, FSharpOption<bool>.None, FSharpOption<bool>.None, FSharpOption<bool>.None, FSharpOption<bool>.None); var file = Path.GetTempFileName(); File.WriteAllText(file + ".fs", source); var action = checker.CompileToDynamicAssembly( new[] {"-o", file + ".dll", "-a", file + ".fs", "--reference:" + fileHelpersAssembly.Location}, FSharpOption<Tuple<TextWriter, TextWriter>>.None, FSharpOption<string>.None); var compileResult = FSharpAsync .StartAsTask(action, FSharpOption<TaskCreationOptions>.None, FSharpOption<CancellationToken>.None) .Result; var exitCode = compileResult.Item2; var compilationErrors = compileResult.Item1; if (compilationErrors.Any() && exitCode != 0) { var errors = new StringBuilder(); foreach (var error in compilationErrors) { errors.AppendLine(error.ToString()); } throw new InvalidOperationException($"Cannot compile fsharp: {errors}"); } return compileResult.Item3.Value; } } } #endif
mit
C#
3c67ee7856610a7634647bab7dcba889b9b715f1
Check before and repair after releasing
macro187/verbot
Verbot/Commands/ReleaseCommand.cs
Verbot/Commands/ReleaseCommand.cs
using System.Collections.Generic; using System.Diagnostics; using MacroExceptions; using MacroGit; namespace Verbot.Commands { class ReleaseCommand : ICommand { readonly Context Context; public ReleaseCommand(Context context) { Context = context; } public int Run(Queue<string> args) { if (args.Count > 0) throw new UserException("Unexpected arguments"); if (new CheckCommand(Context).Run(new Queue<string>()) != 0) return 1; var version = Context.CalculationContext.Calculate(Context.RefContext.Head.Target).CalculatedReleaseVersion; var release = Context.ReleaseContext.FindRelease(version); if (release != null) throw new UserException($"Version {version} already released"); Trace.TraceInformation($"Tagging {version}"); Context.GitRepository.CreateTag(new GitRefNameComponent(version)); Context.ResetContexts(); return new RepairCommand(Context).Run(new Queue<string>()); } } }
using System.Collections.Generic; using System.Diagnostics; using MacroExceptions; using MacroGit; namespace Verbot.Commands { class ReleaseCommand : ICommand { readonly Context Context; public ReleaseCommand(Context context) { Context = context; } public int Run(Queue<string> args) { if (args.Count > 0) throw new UserException("Unexpected arguments"); Release(); return 0; } void Release() { // CheckMasterBranches(); // So master branch hasn't gone past feature/breaking commits /* var commit = Head.Target; var state = GetCommitState(commit); // Calculate release version X.Y.Z var version = state.CalculatedReleaseVersion; // Check: No releases on this commit != X.Y.Z var areOtherReleasesOnCommit = GetReleases(commit).Any(r => r.Version != version); if (areOtherReleasesOnCommit) { throw new UserException("HEAD already released as a different version"); } // Check: X.Y.Z hasn't been released (from a different commit, if on same commit warn?) var existingRelease = FindRelease(version); if (existingRelease != null) { throw new UserException($"{version} already released at {existingRelease.Commit.Sha1}"); } // Check: On correct [X.Y-]master branch var masterBranchName = CalculateMasterBranchName(version); // (more checks?) // tag() GitRepository.CreateTag(new GitRefNameComponent(version)); // if minor release // create/move X-latest branch // create/switchto [X.Y-]master branch // create/move previous [-]master branch to most recent branch point. HARD! // create/move X.Y-latest branch // if latest release in repo // create/move latest branch // if --push git push tag and updated branches // // This is getting hard and duplicates some check/repair logic. Maybe just always do a full pre-check before // and repair after? Wasn't the idea to be really strict anyways? Yes but need repair command first. */ /* // TODO Basic checks if (version != null) { Trace.TraceInformation($"Already released as {version}"); } else { version = state.CalculatedReleaseVersion; var existingRelease = FindRelease(version); if (existingRelease != null) { var existingSha1 = existingRelease.Commit.Sha1; throw new UserException($"Can't release {version} because it already exists at {existingSha1}"); } } */ var version = Context.CalculationContext.Calculate(Context.RefContext.Head.Target).CalculatedReleaseVersion; if (Context.ReleaseContext.FindRelease(version) != null) { throw new UserException($"Version {version} has already been released"); } Trace.TraceInformation($"Tagging {version}"); Context.GitRepository.CreateTag(new GitRefNameComponent(version)); } } }
mit
C#
be96b7d17ce7308a83c46084bc0a122ae39315db
Fix for system not being cleaned
HarmonicOrder/WarpedDrive
Assets/Harmonic/SubroutineCombat/Scripts/ActiveSubroutines.cs
Assets/Harmonic/SubroutineCombat/Scripts/ActiveSubroutines.cs
using UnityEngine; using System.Collections; using System.Collections.Generic; public static class ActiveSubroutines { public static List<Subroutine> List = new List<Subroutine>(); public static List<IMalware> MalwareList = new List<IMalware>(); public delegate void ChangeHandler(); public static event ChangeHandler OnMalwareListChange; public static void Add(Subroutine newlyActive) { if (!List.Contains(newlyActive)) { List.Add(newlyActive); //notify viruses of this foreach(IMalware iMal in MalwareList) { if (iMal is VirusAI) { (iMal as VirusAI).OnSubroutineActive(newlyActive); } } } } public static void Remove(Subroutine newlyInactive) { if (List.Contains(newlyInactive)) { List.Remove(newlyInactive); //notify viruses of this foreach(IMalware iMal in MalwareList) { if (iMal is VirusAI) { (iMal as VirusAI).OnSubroutineInactive(newlyInactive); } } } } public static void AddVirus(IMalware newVirus) { MalwareList.Add(newVirus); Machine m = CyberspaceBattlefield.Current.FindByName(newVirus.transform.root.name); if (m != null) m.ActiveMalware.Add(newVirus); if (OnMalwareListChange != null) OnMalwareListChange(); } public static void RemoveVirus(IMalware oldVirus) { Machine m = CyberspaceBattlefield.Current.FindByName(oldVirus.transform.root.name); if (m != null) { m.ActiveMalware.Remove(oldVirus); if ((m.ActiveMalware.Count == 0) && (m.OnSystemClean != null)) m.IsInfected = false; m.OnSystemClean(); } MalwareList.Remove(oldVirus); if (OnMalwareListChange != null) OnMalwareListChange(); } public static Transform FindClosestActiveSubroutine(Vector3 fromPosition, float range) { if (ActiveSubroutines.List.Count == 0) { return null; } //comparing range squared vs magnitude squared is a performance enhancement //it eliminates the expensive square root calculation float closest = range * range; Transform result = null; foreach( Subroutine mal in ActiveSubroutines.List) { float dist = (mal.transform.position - fromPosition).sqrMagnitude; //if this has a higher priority than now //and the distance is closer if (dist < closest) { result = mal.transform; closest = dist; } } return result; } }
using UnityEngine; using System.Collections; using System.Collections.Generic; public static class ActiveSubroutines { public static List<Subroutine> List = new List<Subroutine>(); public static List<IMalware> MalwareList = new List<IMalware>(); public delegate void ChangeHandler(); public static event ChangeHandler OnMalwareListChange; public static void Add(Subroutine newlyActive) { if (!List.Contains(newlyActive)) { List.Add(newlyActive); //notify viruses of this foreach(IMalware iMal in MalwareList) { if (iMal is VirusAI) { (iMal as VirusAI).OnSubroutineActive(newlyActive); } } } } public static void Remove(Subroutine newlyInactive) { if (List.Contains(newlyInactive)) { List.Remove(newlyInactive); //notify viruses of this foreach(IMalware iMal in MalwareList) { if (iMal is VirusAI) { (iMal as VirusAI).OnSubroutineInactive(newlyInactive); } } } } public static void AddVirus(IMalware newVirus) { MalwareList.Add(newVirus); Machine m = CyberspaceBattlefield.Current.FindByName(newVirus.transform.root.name); if (m != null) m.ActiveMalware.Add(newVirus); if (OnMalwareListChange != null) OnMalwareListChange(); } public static void RemoveVirus(IMalware oldVirus) { Machine m = CyberspaceBattlefield.Current.FindByName(oldVirus.transform.root.name); if (m != null) { m.ActiveMalware.Remove(oldVirus); if ((m.ActiveMalware.Count == 0) && (m.OnSystemClean != null)) m.OnSystemClean(); } MalwareList.Remove(oldVirus); if (OnMalwareListChange != null) OnMalwareListChange(); } public static Transform FindClosestActiveSubroutine(Vector3 fromPosition, float range) { if (ActiveSubroutines.List.Count == 0) { return null; } //comparing range squared vs magnitude squared is a performance enhancement //it eliminates the expensive square root calculation float closest = range * range; Transform result = null; foreach( Subroutine mal in ActiveSubroutines.List) { float dist = (mal.transform.position - fromPosition).sqrMagnitude; //if this has a higher priority than now //and the distance is closer if (dist < closest) { result = mal.transform; closest = dist; } } return result; } }
mit
C#
09c519b0e72b5ee002a8a91f2d1534f83e1fbae9
Update CustomDwellHandler.cs
DDReaper/MixedRealityToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity
Assets/MRTK/Examples/Experimental/Dwell/CustomDwellHandler.cs
Assets/MRTK/Examples/Experimental/Dwell/CustomDwellHandler.cs
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using UnityEngine; namespace Microsoft.MixedReality.Toolkit.Experimental.Dwell { /// <summary> /// Example to demonstrate DwellHandler override when a custom profile is used /// This example script works with the DwellProfileWithDecay custom profile. /// </summary> [AddComponentMenu("Scripts/MRTK/Examples/CustomDwellHandler")] public class CustomDwellHandler : DwellHandler { protected override void UpdateFillTimer() { switch (CurrentDwellState) { case DwellStateType.DwellCanceled: if (dwellProfile is DwellProfileWithDecay profileWithDecay) { FillTimer -= Time.deltaTime * (float)dwellProfile.TimeToCompleteDwell.TotalSeconds / profileWithDecay.TimeToAllowDwellDecay; if (FillTimer <= 0) { FillTimer = 0; CurrentDwellState = DwellStateType.None; } } else { Debug.LogError("The assigned profile is not DwellProfileWithDecay!"); } break; default: base.UpdateFillTimer(); break; } } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using UnityEngine; namespace Microsoft.MixedReality.Toolkit.Experimental.Dwell { /// <summary> /// Example to demonstrate DwellHandler override /// </summary> [AddComponentMenu("Scripts/MRTK/Examples/CustomDwellHandler")] public class CustomDwellHandler : DwellHandler { protected override void UpdateFillTimer() { switch (CurrentDwellState) { case DwellStateType.DwellCanceled: if (dwellProfile is DwellProfileWithDecay profileWithDecay) { FillTimer -= Time.deltaTime * (float)dwellProfile.TimeToCompleteDwell.TotalSeconds / profileWithDecay.TimeToAllowDwellDecay; if (FillTimer <= 0) { FillTimer = 0; CurrentDwellState = DwellStateType.None; } } else { Debug.LogError("The assigned profile is not DwellProfileWithDecay!"); } break; default: base.UpdateFillTimer(); break; } } } }
mit
C#
25964c541b8753c55b6b6e3329d1aff25e469f12
Revert "Changed generic object to a system object"
tedbouskill/m-r-core-of,tedbouskill/m-r-core-of
EventSourcingCQRS/Application/Interfaces/IInventoryService.cs
EventSourcingCQRS/Application/Interfaces/IInventoryService.cs
using System; using System.Collections.Generic; using System.Threading.Tasks; using DomainCore; namespace Application.Interfaces { public interface IInventoryService { /* ReadModel */ // Get all Task<IEnumerable<InventoryItemDto>> InventoryAsync(); // Get one Task<InventoryItemDto> GetItemAsync(Guid id); Task<IEnumerable<InventoryItemEvent>> InventoryEventsAsync(Guid id); /* Commands */ // Create Item Task PostItemAsync(InventoryItemDto item); // Update Full Item Task PutItemAsync(InventoryItemDto item); // Delete Item Task DeleteItemAsync(Guid id); // Edit Item Task PatchItemCountAsync(Guid id, int count, string reason); Task PatchItemNameAsync(Guid id, string name, string reason); Task PatchItemNoteAsync(Guid id, string note, string reason); // Increase Item count Task IncreaseInventory(Guid id, uint amount, string reason); // Decrease Item count Task DecreaseInventory(Guid id, uint amount, string reason); // Activate Item Task ActivateItem(Guid id, string reason); // Deactivate Item Task DisableItem(Guid id, string reason); } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using DomainCore; using DomainCore.Interfaces; namespace Application.Interfaces { /// <summary> /// Primary application interface /// </summary> public interface IInventoryService { /* ReadModel */ // Get all Task<IEnumerable<InventoryItemDto>> InventoryAsync(); // Get one Task<InventoryItemDto> GetItemAsync(Guid id); Task<IEnumerable<AInventoryItemEvent>> InventoryEventsAsync(Guid id); /* Commands */ // Create Item Task PostItemAsync(InventoryItemDto item); // Update Full Item Task PutItemAsync(InventoryItemDto item); // Delete Item Task DeleteItemAsync(Guid id); // Edit Item Task PatchItemCountAsync(Guid id, int count, string reason); Task PatchItemNameAsync(Guid id, string name, string reason); Task PatchItemNoteAsync(Guid id, string note, string reason); // Increase Item count Task IncreaseInventory(Guid id, uint amount, string reason); // Decrease Item count Task DecreaseInventory(Guid id, uint amount, string reason); // Activate Item Task ActivateItem(Guid id, string reason); // Deactivate Item Task DisableItem(Guid id, string reason); } }
mit
C#
5e06eef844a5e4c3687e5794780eebd7e0a63b7c
Add documentation for movie images.
henrikfroehling/TraktApiSharp
Source/Lib/TraktApiSharp/Objects/Get/Movies/TraktMovieImages.cs
Source/Lib/TraktApiSharp/Objects/Get/Movies/TraktMovieImages.cs
namespace TraktApiSharp.Objects.Get.Movies { using Basic; using Newtonsoft.Json; /// <summary>A collection of images and image sets for a Trakt movie.</summary> public class TraktMovieImages { /// <summary>Gets or sets the fan art image set.</summary> [JsonProperty(PropertyName = "fanart")] public TraktImageSet FanArt { get; set; } /// <summary>Gets or sets the poster image set.</summary> [JsonProperty(PropertyName = "poster")] public TraktImageSet Poster { get; set; } /// <summary>Gets or sets the loge image.</summary> [JsonProperty(PropertyName = "logo")] public TraktImage Logo { get; set; } /// <summary>Gets or sets the clear art image.</summary> [JsonProperty(PropertyName = "clearart")] public TraktImage ClearArt { get; set; } /// <summary>Gets or sets the banner image.</summary> [JsonProperty(PropertyName = "banner")] public TraktImage Banner { get; set; } /// <summary>Gets or sets the thumb image.</summary> [JsonProperty(PropertyName = "thumb")] public TraktImage Thumb { get; set; } } }
namespace TraktApiSharp.Objects.Get.Movies { using Basic; using Newtonsoft.Json; public class TraktMovieImages { [JsonProperty(PropertyName = "fanart")] public TraktImageSet FanArt { get; set; } [JsonProperty(PropertyName = "poster")] public TraktImageSet Poster { get; set; } [JsonProperty(PropertyName = "logo")] public TraktImage Logo { get; set; } [JsonProperty(PropertyName = "clearart")] public TraktImage ClearArt { get; set; } [JsonProperty(PropertyName = "banner")] public TraktImage Banner { get; set; } [JsonProperty(PropertyName = "thumb")] public TraktImage Thumb { get; set; } } }
mit
C#
ebd887b1ba46e224a00a1addc37edd5e29fb38bc
Call LockScreenBase OnInitialise
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi.Gui/Controls/LockScreen/LockScreenViewModelBase.cs
WalletWasabi.Gui/Controls/LockScreen/LockScreenViewModelBase.cs
using System; using ReactiveUI; using System.Reactive.Disposables; using WalletWasabi.Helpers; using System.Reactive.Linq; using WalletWasabi.Gui.ViewModels; using Splat; namespace WalletWasabi.Gui.Controls.LockScreen { public abstract class LockScreenViewModelBase : ViewModelBase { private bool _isLocked; private CompositeDisposable Disposables { get; } public LockScreenViewModelBase() { Disposables = new CompositeDisposable(); var global = Locator.Current.GetService<Global>(); global.UiConfig .WhenAnyValue(x => x.LockScreenActive) .ObserveOn(RxApp.MainThreadScheduler) .BindTo(this, y => y.IsLocked) .DisposeWith(Disposables); this.WhenAnyValue(x => x.IsLocked) .ObserveOn(RxApp.MainThreadScheduler) .BindTo(global.UiConfig, y => y.LockScreenActive) .DisposeWith(Disposables); IsLocked = global.UiConfig.LockScreenActive; OnInitialise(Disposables); } public bool IsLocked { get => _isLocked; set => this.RaiseAndSetIfChanged(ref _isLocked, value); } protected abstract void OnInitialise(CompositeDisposable disposables); } }
using System; using ReactiveUI; using System.Reactive.Disposables; using WalletWasabi.Helpers; using System.Reactive.Linq; using WalletWasabi.Gui.ViewModels; using Splat; namespace WalletWasabi.Gui.Controls.LockScreen { public abstract class LockScreenViewModelBase : ViewModelBase { private bool _isLocked; private CompositeDisposable Disposables { get; } public LockScreenViewModelBase() { Disposables = new CompositeDisposable(); var global = Locator.Current.GetService<Global>(); global.UiConfig .WhenAnyValue(x => x.LockScreenActive) .ObserveOn(RxApp.MainThreadScheduler) .BindTo(this, y => y.IsLocked) .DisposeWith(Disposables); this.WhenAnyValue(x => x.IsLocked) .ObserveOn(RxApp.MainThreadScheduler) .BindTo(global.UiConfig, y => y.LockScreenActive) .DisposeWith(Disposables); IsLocked = global.UiConfig.LockScreenActive; } public bool IsLocked { get => _isLocked; set => this.RaiseAndSetIfChanged(ref _isLocked, value); } protected abstract void OnInitialise(CompositeDisposable disposables); } }
mit
C#
ad25f6f78780d54c5bf6dc1abfb1a592181fe45b
Use var instead of string
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi.Tests/UnitTests/SerializableExceptionTests.cs
WalletWasabi.Tests/UnitTests/SerializableExceptionTests.cs
using System; using System.Collections.Generic; using System.Text; using WalletWasabi.Models; using Xunit; namespace WalletWasabi.Tests.UnitTests { public class SerializableExceptionTests { [Fact] public void UtxoRefereeSerialization() { var message = "Foo Bar Buzz"; var innerMessage = "Inner Foo Bar Buzz"; var innerStackTrace = ""; Exception ex; string stackTrace; try { try { throw new OperationCanceledException(innerMessage); } catch (Exception inner) { innerStackTrace = inner.StackTrace; throw new InvalidOperationException(message, inner); } } catch (Exception x) { stackTrace = x.StackTrace; ex = x; } var serializableException = ex.ToSerializableException(); var base64string = SerializableException.ToBase64String(serializableException); var result = SerializableException.FromBase64String(base64string); Assert.Equal(message, result.Message); Assert.Equal(stackTrace, result.StackTrace); Assert.Equal(typeof(InvalidOperationException).FullName, result.ExceptionType); Assert.Equal(innerMessage, result.InnerException.Message); Assert.Equal(innerStackTrace, result.InnerException.StackTrace); Assert.Equal(typeof(OperationCanceledException).FullName, result.InnerException.ExceptionType); } } }
using System; using System.Collections.Generic; using System.Text; using WalletWasabi.Models; using Xunit; namespace WalletWasabi.Tests.UnitTests { public class SerializableExceptionTests { [Fact] public void UtxoRefereeSerialization() { var message = "Foo Bar Buzz"; var innerMessage = "Inner Foo Bar Buzz"; string innerStackTrace = ""; Exception ex; string stackTrace; try { try { throw new OperationCanceledException(innerMessage); } catch (Exception inner) { innerStackTrace = inner.StackTrace; throw new InvalidOperationException(message, inner); } } catch (Exception x) { stackTrace = x.StackTrace; ex = x; } var serializableException = ex.ToSerializableException(); var base64string = SerializableException.ToBase64String(serializableException); var result = SerializableException.FromBase64String(base64string); Assert.Equal(message, result.Message); Assert.Equal(stackTrace, result.StackTrace); Assert.Equal(typeof(InvalidOperationException).FullName, result.ExceptionType); Assert.Equal(innerMessage, result.InnerException.Message); Assert.Equal(innerStackTrace, result.InnerException.StackTrace); Assert.Equal(typeof(OperationCanceledException).FullName, result.InnerException.ExceptionType); } } }
mit
C#
566cdec77a981985a7d03dbb6a67a6f36b76ae0b
Create the repository only when it's needed for deployment.
juoni/kudu,juoni/kudu,MavenRain/kudu,projectkudu/kudu,bbauya/kudu,duncansmart/kudu,kali786516/kudu,puneet-gupta/kudu,YOTOV-LIMITED/kudu,shrimpy/kudu,MavenRain/kudu,WeAreMammoth/kudu-obsolete,projectkudu/kudu,duncansmart/kudu,EricSten-MSFT/kudu,juoni/kudu,shibayan/kudu,shibayan/kudu,WeAreMammoth/kudu-obsolete,puneet-gupta/kudu,barnyp/kudu,chrisrpatterson/kudu,juoni/kudu,sitereactor/kudu,oliver-feng/kudu,badescuga/kudu,shanselman/kudu,kenegozi/kudu,puneet-gupta/kudu,EricSten-MSFT/kudu,MavenRain/kudu,projectkudu/kudu,mauricionr/kudu,shanselman/kudu,oliver-feng/kudu,shibayan/kudu,dev-enthusiast/kudu,badescuga/kudu,juvchan/kudu,barnyp/kudu,EricSten-MSFT/kudu,chrisrpatterson/kudu,sitereactor/kudu,bbauya/kudu,kali786516/kudu,juvchan/kudu,uQr/kudu,projectkudu/kudu,barnyp/kudu,shibayan/kudu,duncansmart/kudu,dev-enthusiast/kudu,kali786516/kudu,dev-enthusiast/kudu,badescuga/kudu,sitereactor/kudu,mauricionr/kudu,uQr/kudu,kenegozi/kudu,shrimpy/kudu,mauricionr/kudu,oliver-feng/kudu,chrisrpatterson/kudu,puneet-gupta/kudu,shanselman/kudu,shibayan/kudu,uQr/kudu,YOTOV-LIMITED/kudu,badescuga/kudu,shrimpy/kudu,MavenRain/kudu,dev-enthusiast/kudu,EricSten-MSFT/kudu,kenegozi/kudu,juvchan/kudu,badescuga/kudu,duncansmart/kudu,puneet-gupta/kudu,sitereactor/kudu,juvchan/kudu,EricSten-MSFT/kudu,sitereactor/kudu,YOTOV-LIMITED/kudu,kali786516/kudu,chrisrpatterson/kudu,bbauya/kudu,YOTOV-LIMITED/kudu,shrimpy/kudu,WeAreMammoth/kudu-obsolete,oliver-feng/kudu,uQr/kudu,kenegozi/kudu,projectkudu/kudu,juvchan/kudu,mauricionr/kudu,bbauya/kudu,barnyp/kudu
Kudu.Core/Deployment/DeploymentManager.cs
Kudu.Core/Deployment/DeploymentManager.cs
using System; using System.Collections.Generic; using System.Linq; using Kudu.Core.SourceControl; namespace Kudu.Core.Deployment { public class DeploymentManager : IDeploymentManager { private readonly IRepositoryManager _repositoryManager; private readonly IDeployerFactory _deployerFactory; public DeploymentManager(IRepositoryManager repositoryManager, IDeployerFactory deployerFactory) { _repositoryManager = repositoryManager; _deployerFactory = deployerFactory; } public IEnumerable<DeployResult> GetResults() { throw new NotImplementedException(); } public DeployResult GetResult(string id) { throw new NotImplementedException(); } public void Deploy(string id) { IDeployer deployer = _deployerFactory.CreateDeployer(); deployer.Deploy(id); } public void Deploy() { var repository = _repositoryManager.GetRepository(); if (repository == null) { return; } var activeBranch = repository.GetBranches().FirstOrDefault(b => b.Active); string id = repository.CurrentId; if (activeBranch != null) { repository.Update(activeBranch.Name); } else { repository.Update(id); } Deploy(id); } } }
using System; using System.Collections.Generic; using System.Linq; using Kudu.Core.SourceControl; namespace Kudu.Core.Deployment { public class DeploymentManager : IDeploymentManager { private readonly IRepository _repository; private readonly IDeployerFactory _deployerFactory; public DeploymentManager(IRepositoryManager repositoryManager, IDeployerFactory deployerFactory) { _repository = repositoryManager.GetRepository(); _deployerFactory = deployerFactory; } public IEnumerable<DeployResult> GetResults() { throw new NotImplementedException(); } public DeployResult GetResult(string id) { throw new NotImplementedException(); } public void Deploy(string id) { IDeployer deployer = _deployerFactory.CreateDeployer(); deployer.Deploy(id); } public void Deploy() { var activeBranch = _repository.GetBranches().FirstOrDefault(b => b.Active); string id = _repository.CurrentId; if (activeBranch != null) { _repository.Update(activeBranch.Name); } else { _repository.Update(id); } Deploy(id); } } }
apache-2.0
C#
2c6f5f5e27d44a508a95636d1368d472ddb9f066
Update ConwaysGameOfLife.cs
WorldOfZero/UnityVisualizations
GameOfLife/ConwaysGameOfLife.cs
GameOfLife/ConwaysGameOfLife.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ConwaysGameOfLife : MonoBehaviour { public Texture input; public int width = 512; public int height = 512; public ComputeShader compute; public RenderTexture renderTexPing; public RenderTexture renderTexPong; public Material material; private int kernel; private bool pingPong; // Use this for initialization void Start () { if (height < 1 || width < 1) return; kernel = compute.FindKernel("GameOfLife"); renderTexPing = new RenderTexture(width, height, 24); renderTexPing.wrapMode = TextureWrapMode.Repeat; renderTexPing.enableRandomWrite = true; renderTexPing.filterMode = FilterMode.Point; renderTexPing.useMipMap = false; renderTexPing.Create(); renderTexPong = new RenderTexture(width, height, 24); renderTexPong.wrapMode = TextureWrapMode.Repeat; renderTexPong.enableRandomWrite = true; renderTexPong.filterMode = FilterMode.Point; renderTexPong.useMipMap = false; renderTexPong.Create(); Graphics.Blit(input, renderTexPing); pingPong = true; compute.SetFloat("Width", width); compute.SetFloat("Height", height); } // Update is called once per frame void Update () { //if (!step) return; //step = false; if (height < 1 || width < 1) return; if (true == pingPong) { compute.SetTexture(kernel, "Input", renderTexPing); compute.SetTexture(kernel, "Result", renderTexPong); compute.Dispatch(kernel, width / 8, height / 8, 1); material.mainTexture = renderTexPong; pingPong = false; } else { compute.SetTexture(kernel, "Input", renderTexPong); compute.SetTexture(kernel, "Result", renderTexPing); compute.Dispatch(kernel, width / 8, height / 8, 1); material.mainTexture = renderTexPing; pingPong = true; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ConwaysGameOfLife : MonoBehaviour { public Texture input; public int width = 512; public int height = 512; public ComputeShader compute; public RenderTexture result; public Material material; public bool step = false; //TODO: Implement double buffering // Use this for initialization void Start () { result = new RenderTexture(width, height, 24); result.enableRandomWrite = true; result.Create(); } // Update is called once per frame void Update () { //if (!step) return; //step = false; if (height < 1 || width < 1) return; int kernel = compute.FindKernel("GameOfLife"); compute.SetTexture(kernel, "Input", input); compute.SetFloat("Width", width); compute.SetFloat("Height", height); result = new RenderTexture(width, height, 24); result.wrapMode = TextureWrapMode.Repeat; result.enableRandomWrite = true; result.filterMode = FilterMode.Point; result.useMipMap = false; result.Create(); compute.SetTexture(kernel, "Result", result); compute.Dispatch(kernel, width / 8, height / 8, 1); input = result; material.mainTexture = input; } }
apache-2.0
C#
bb19616eeebb9ac9e7fc2961af0b05c4529dd31d
Update new-blog.cshtml
daveaglick/daveaglick,mishrsud/sudhanshutheone.com,mishrsud/sudhanshutheone.com,daveaglick/daveaglick,mishrsud/sudhanshutheone.com
Somedave/Views/Blog/Posts/new-blog.cshtml
Somedave/Views/Blog/Posts/new-blog.cshtml
@{ Title = "New Blog"; Published = new DateTime(2014, 9, 2); Tags = new[] { "blog", "meta" }; } <p>Test</p>
@{ Title = "New Blog"; Lead = "Look, Ma, no database!"; Published = new DateTime(2014, 9, 2); Tags = new[] { "blog", "meta" }; } <p>It's been a little while coming, but I'm finally launching my new blog. It's built from scratch in ASP.NET MVC. Why go to all the trouble to build a blog engine from scratch when there are a gazillion great engines already out there? That's a very good question, let's break it down.</p> <h1>Own Your Content</h1> <p>I'll thank Scott Hanselman for really driving this point home.</p> <p>So that's <em>why</em> I created this new blog, but what about <em>how</em>? This blog engine uses no database, makes it easy to mix content pages with blog articles, is hosted on GitHub, and uses continuous deployment to automatically publish to an Azure Website.</p>
mit
C#
b3c93f74b5a5fbe427d3127ad75455143ffcd5df
Add ResourceView.ResourceAs<T> method.
TechPriest/SharpDX,shoelzer/SharpDX,fmarrabal/SharpDX,shoelzer/SharpDX,dazerdude/SharpDX,RobyDX/SharpDX,TechPriest/SharpDX,Ixonos-USA/SharpDX,RobyDX/SharpDX,weltkante/SharpDX,waltdestler/SharpDX,PavelBrokhman/SharpDX,TechPriest/SharpDX,TigerKO/SharpDX,weltkante/SharpDX,dazerdude/SharpDX,mrvux/SharpDX,mrvux/SharpDX,fmarrabal/SharpDX,Ixonos-USA/SharpDX,TigerKO/SharpDX,Ixonos-USA/SharpDX,dazerdude/SharpDX,TigerKO/SharpDX,wyrover/SharpDX,dazerdude/SharpDX,VirusFree/SharpDX,VirusFree/SharpDX,davidlee80/SharpDX-1,jwollen/SharpDX,shoelzer/SharpDX,sharpdx/SharpDX,shoelzer/SharpDX,shoelzer/SharpDX,jwollen/SharpDX,sharpdx/SharpDX,mrvux/SharpDX,manu-silicon/SharpDX,weltkante/SharpDX,waltdestler/SharpDX,davidlee80/SharpDX-1,wyrover/SharpDX,andrewst/SharpDX,davidlee80/SharpDX-1,VirusFree/SharpDX,wyrover/SharpDX,RobyDX/SharpDX,weltkante/SharpDX,waltdestler/SharpDX,wyrover/SharpDX,sharpdx/SharpDX,VirusFree/SharpDX,manu-silicon/SharpDX,fmarrabal/SharpDX,fmarrabal/SharpDX,PavelBrokhman/SharpDX,andrewst/SharpDX,waltdestler/SharpDX,Ixonos-USA/SharpDX,TechPriest/SharpDX,PavelBrokhman/SharpDX,manu-silicon/SharpDX,TigerKO/SharpDX,PavelBrokhman/SharpDX,andrewst/SharpDX,manu-silicon/SharpDX,davidlee80/SharpDX-1,jwollen/SharpDX,RobyDX/SharpDX,jwollen/SharpDX
Source/SharpDX.Direct3D11/ResourceView.cs
Source/SharpDX.Direct3D11/ResourceView.cs
// Copyright (c) 2010-2012 SharpDX - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; namespace SharpDX.Direct3D11 { public partial class ResourceView { /// <summary> /// <p>Get the resource that is accessed through this view.</p> /// </summary> /// <remarks> /// <p>This function increments the reference count of the resource by one, so it is necessary to call <strong>Release</strong> on the returned reference when the application is done with it. Destroying (or losing) the returned reference before <strong>Release</strong> is called will result in a memory leak.</p> /// </remarks> /// <msdn-id>ff476643</msdn-id> /// <unmanaged>GetResource</unmanaged> /// <unmanaged-short>GetResource</unmanaged-short> /// <unmanaged>void ID3D11View::GetResource([Out] ID3D11Resource** ppResource)</unmanaged> public SharpDX.Direct3D11.Resource Resource { get { IntPtr __output__; GetResource(out __output__); return new Resource(__output__); } } /// <summary> /// <p>Get the resource that is accessed through this view.</p> /// </summary> /// <remarks> /// <p>This function increments the reference count of the resource by one, so it is necessary to call <strong>Dispose</strong> on the returned reference when the application is done with it. Destroying (or losing) the returned reference before <strong>Release</strong> is called will result in a memory leak.</p> /// </remarks> /// <msdn-id>ff476643</msdn-id> /// <unmanaged>GetResource</unmanaged> /// <unmanaged-short>GetResource</unmanaged-short> /// <unmanaged>void ID3D11View::GetResource([Out] ID3D11Resource** ppResource)</unmanaged> public T ResourceAs<T>() where T : Resource { IntPtr resourcePtr; GetResource(out resourcePtr); return As<T>(resourcePtr); } } }
using System; namespace SharpDX.Direct3D11 { public partial class ResourceView { /// <summary> /// <p>Get the resource that is accessed through this view.</p> /// </summary> /// <remarks> /// <p>This function increments the reference count of the resource by one, so it is necessary to call <strong>Release</strong> on the returned reference when the application is done with it. Destroying (or losing) the returned reference before <strong>Release</strong> is called will result in a memory leak.</p> /// </remarks> /// <msdn-id>ff476643</msdn-id> /// <unmanaged>GetResource</unmanaged> /// <unmanaged-short>GetResource</unmanaged-short> /// <unmanaged>void ID3D11View::GetResource([Out] ID3D11Resource** ppResource)</unmanaged> public SharpDX.Direct3D11.Resource Resource { get { IntPtr __output__; GetResource(out __output__); return new Resource(__output__); } } } }
mit
C#
63b3a87a33692aa73595fdfaaefd65278325fa7f
Fix doc
maxwellb/csharp-driver,datastax/csharp-driver,maxwellb/csharp-driver,datastax/csharp-driver
src/Dse/IDseSession.cs
src/Dse/IDseSession.cs
// // Copyright (C) 2016 DataStax, Inc. // // Please see the license for details: // http://www.datastax.com/terms/datastax-dse-driver-license-terms // using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Dse; using Dse.Graph; namespace Dse { /// <summary> /// Represents an <see cref="ISession"/> suitable for querying a DataStax Enterprise (DSE) Cluster. /// <para> /// Session instances are designed to be long-lived, thread-safe and usually a single instance is enough per /// application. /// </para> /// </summary> public interface IDseSession : ISession { /// <summary> /// Executes a graph statement. /// </summary> /// <param name="statement">The graph statement containing the query</param> /// <example> /// <code> /// GraphResultSet rs = session.ExecuteGraph(new SimpleGraphStatement("g.V()")); /// </code> /// </example> GraphResultSet ExecuteGraph(IGraphStatement statement); /// <summary> /// Executes a graph statement. /// </summary> /// <param name="statement">The graph statement containing the query</param> /// <example> /// <code> /// Task&lt;GraphResultSet$gt; task = session.ExecuteGraphAsync(new SimpleGraphStatement("g.V()")); /// </code> /// </example> Task<GraphResultSet> ExecuteGraphAsync(IGraphStatement statement); } }
// // Copyright (C) 2016 DataStax, Inc. // // Please see the license for details: // http://www.datastax.com/terms/datastax-dse-driver-license-terms // using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Dse; using Dse.Graph; namespace Dse { /// <summary> /// Represents an <see cref="ISession"/> suitable for querying a DataStax Enterprise (DSE) Cluster. /// <para> /// Session instances are designed to be long-lived, thread-safe and usually a single instance is enough per /// application. /// </para> /// </summary> public interface IDseSession : ISession { /// <summary> /// Executes a graph statement. /// </summary> /// <param name="statement">The graph statement containing the query</param> /// <example> /// <code> /// GraphResultSet rs = session.ExecuteGraph(new SimpleGraphStatement("g.V()")); /// </code> /// </example> GraphResultSet ExecuteGraph(IGraphStatement statement); /// <summary> /// Executes a graph statement. /// </summary> /// <param name="statement">The graph statement containing the query</param> /// <example> /// <code> /// GraphResultSet rs = await session.ExecuteGraphAsync(new SimpleGraphStatement("g.V()")); /// </code> /// </example> Task<GraphResultSet> ExecuteGraphAsync(IGraphStatement statement); } }
apache-2.0
C#
434bc322301081938f68d6597c79fa94db19ead4
fix docs for NewRepository
shana/octokit.net,ChrisMissal/octokit.net,SamTheDev/octokit.net,M-Zuber/octokit.net,michaKFromParis/octokit.net,khellang/octokit.net,hahmed/octokit.net,takumikub/octokit.net,naveensrinivasan/octokit.net,thedillonb/octokit.net,octokit/octokit.net,octokit/octokit.net,darrelmiller/octokit.net,chunkychode/octokit.net,editor-tools/octokit.net,yonglehou/octokit.net,alfhenrik/octokit.net,octokit-net-test-org/octokit.net,alfhenrik/octokit.net,shiftkey/octokit.net,shiftkey/octokit.net,octokit-net-test-org/octokit.net,ivandrofly/octokit.net,SamTheDev/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,brramos/octokit.net,yonglehou/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,SLdragon1989/octokit.net,daukantas/octokit.net,forki/octokit.net,kolbasov/octokit.net,octokit-net-test/octokit.net,fffej/octokit.net,eriawan/octokit.net,dlsteuer/octokit.net,TattsGroup/octokit.net,mminns/octokit.net,magoswiat/octokit.net,Red-Folder/octokit.net,ivandrofly/octokit.net,editor-tools/octokit.net,gabrielweyer/octokit.net,dampir/octokit.net,Sarmad93/octokit.net,nsnnnnrn/octokit.net,TattsGroup/octokit.net,nsrnnnnn/octokit.net,Sarmad93/octokit.net,gabrielweyer/octokit.net,kdolan/octokit.net,SmithAndr/octokit.net,devkhan/octokit.net,rlugojr/octokit.net,eriawan/octokit.net,shiftkey-tester/octokit.net,mminns/octokit.net,khellang/octokit.net,adamralph/octokit.net,M-Zuber/octokit.net,cH40z-Lord/octokit.net,fake-organization/octokit.net,gdziadkiewicz/octokit.net,rlugojr/octokit.net,SmithAndr/octokit.net,shiftkey-tester/octokit.net,shana/octokit.net,chunkychode/octokit.net,bslliw/octokit.net,thedillonb/octokit.net,hitesh97/octokit.net,hahmed/octokit.net,geek0r/octokit.net,dampir/octokit.net,gdziadkiewicz/octokit.net,devkhan/octokit.net
Octokit/Models/NewRepository.cs
Octokit/Models/NewRepository.cs
using System.Diagnostics.CodeAnalysis; namespace Octokit { /// <summary> /// Describes a new repository to create via the <see cref="IRepositoriesClient.Create(NewRepository)"/> method. /// </summary> public class NewRepository { /// <summary> /// Optional. Gets or sets whether to create an initial commit with empty README. The default is false. /// </summary> public bool? AutoInit { get; set; } /// <summary> /// Required. Gets or sets the new repository's description /// </summary> public string Description { get; set; } /// <summary>s /// Optional. Gets or sets whether to the enable downloads for the new repository. The default is true. /// </summary> public bool? HasDownloads { get; set; } /// <summary>s /// Optional. Gets or sets whether to the enable issues for the new repository. The default is true. /// </summary> public bool? HasIssues { get; set; } /// <summary>s /// Optional. Gets or sets whether to the enable the wiki for the new repository. The default is true. /// </summary> public bool? HasWiki { get; set; } /// <summary> /// Optional. Gets or sets the new repository's optional website. /// </summary> public string Homepage { get; set; } /// <summary> /// Optional. Gets or sets the desired language's or platform's .gitignore template to apply. Use the name of the template without the extension; "Haskell", for example. Ignored if <see cref="AutoInit"/> is null or false. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Gitignore", Justification = "It needs to be this way for proper serialization.")] public string GitignoreTemplate { get; set; } /// <summary> /// Required. Gets or sets the new repository's name. /// </summary> public string Name { get; set; } /// <summary> /// Optional. Gets or sets whether the new repository is private; the default is false. /// </summary> public bool? Private { get; set; } /// <summary> /// Optional. Gets or sets the ID of the team to grant access to this repository. This is only valid when creating a repository for an organization. /// </summary> public int? TeamId { get; set; } } }
using System.Diagnostics.CodeAnalysis; namespace Octokit { /// <summary> /// Describes a new repository to create via the <see cref="IRepositoriesClient.Create"/> method. /// </summary> public class NewRepository { /// <summary> /// Optional. Gets or sets whether to create an initial commit with empty README. The default is false. /// </summary> public bool? AutoInit { get; set; } /// <summary> /// Required. Gets or sets the new repository's description /// </summary> public string Description { get; set; } /// <summary>s /// Optional. Gets or sets whether to the enable downloads for the new repository. The default is true. /// </summary> public bool? HasDownloads { get; set; } /// <summary>s /// Optional. Gets or sets whether to the enable issues for the new repository. The default is true. /// </summary> public bool? HasIssues { get; set; } /// <summary>s /// Optional. Gets or sets whether to the enable the wiki for the new repository. The default is true. /// </summary> public bool? HasWiki { get; set; } /// <summary> /// Optional. Gets or sets the new repository's optional website. /// </summary> public string Homepage { get; set; } /// <summary> /// Optional. Gets or sets the desired language's or platform's .gitignore template to apply. Use the name of the template without the extension; "Haskell", for example. Ignored if <see cref="AutoInit"/> is null or false. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Gitignore", Justification = "It needs to be this way for proper serialization.")] public string GitignoreTemplate { get; set; } /// <summary> /// Required. Gets or sets the new repository's name. /// </summary> public string Name { get; set; } /// <summary> /// Optional. Gets or sets whether the new repository is private; the default is false. /// </summary> public bool? Private { get; set; } /// <summary> /// Optional. Gets or sets the ID of the team to grant access to this repository. This is only valid when creating a repository for an organization. /// </summary> public int? TeamId { get; set; } } }
mit
C#
6bbd175348dd9c03ee496464ecd77b0adaf23505
update AssemblyInfo
syo00/ReactiveLinqToObservableCollection
ReactiveObservableCollectionMapper/Properties/AssemblyInfo.cs
ReactiveObservableCollectionMapper/Properties/AssemblyInfo.cs
using System.Resources; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // アセンブリに関する一般情報は以下の属性セットをとおして制御されます。 // アセンブリに関連付けられている情報を変更するには、 // これらの属性値を変更してください。 [assembly: AssemblyTitle("ReactiveObservableCollectionMapper")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ReactiveObservableCollectionMapper")] [assembly: AssemblyCopyright("Copyright (C) 2014 syo00")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("ja")] // アセンブリのバージョン情報は、以下の 4 つの値で構成されています: // // メジャー バージョン // マイナー バージョン // ビルド番号 // リビジョン // // すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を // 既定値にすることができます: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.0.*")] [assembly: AssemblyFileVersion("0.0.*")] [assembly: AssemblyInformationalVersion("0.0 beta")]
using System.Resources; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // アセンブリに関する一般情報は以下の属性セットをとおして制御されます。 // アセンブリに関連付けられている情報を変更するには、 // これらの属性値を変更してください。 [assembly: AssemblyTitle("ReactiveObservableCollectionMapper")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ReactiveObservableCollectionMapper")] [assembly: AssemblyCopyright("Copyright (C) 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("ja")] // アセンブリのバージョン情報は、以下の 4 つの値で構成されています: // // メジャー バージョン // マイナー バージョン // ビルド番号 // リビジョン // // すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を // 既定値にすることができます: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#
8757a464068c5a3ac754720e4cdbe6217549d703
Sort languages by ascending order.
GeorgeAlexandria/CoCo
src/common/CoCo.UI/ViewModels/OptionViewModel.cs
src/common/CoCo.UI/ViewModels/OptionViewModel.cs
using System.Collections.ObjectModel; using System.ComponentModel; using System.Windows.Data; using CoCo.UI.Data; namespace CoCo.UI.ViewModels { public class OptionViewModel : BaseViewModel { private readonly ObservableCollection<LanguageViewModel> _languages = new ObservableCollection<LanguageViewModel>(); public OptionViewModel(Option option, IResetValuesProvider resetValuesProvider) { // TODO: it will invoke one event at invocation of clear and by one event per added item // Write custom BulkObservableCollection to avoid so many events _languages.Clear(); foreach (var language in option.Languages) { _languages.Add(new LanguageViewModel(language, resetValuesProvider)); } Languages = CollectionViewSource.GetDefaultView(_languages); Languages.SortDescriptions.Add(new SortDescription(nameof(LanguageViewModel.Name), ListSortDirection.Ascending)); } public ICollectionView Languages { get; } private LanguageViewModel _selectedLanguage; public LanguageViewModel SelectedLanguage { get { if (_selectedLanguage is null && Languages.MoveCurrentToFirst()) { SelectedLanguage = (LanguageViewModel)Languages.CurrentItem; } return _selectedLanguage; } set => SetProperty(ref _selectedLanguage, value); } public Option ExtractData() { var option = new Option(); foreach (var languageViewModel in _languages) { option.Languages.Add(languageViewModel.ExtractData()); } return option; } } }
using System.Collections.ObjectModel; using CoCo.UI.Data; namespace CoCo.UI.ViewModels { public class OptionViewModel : BaseViewModel { public OptionViewModel(Option option, IResetValuesProvider resetValuesProvider) { // TODO: it will invoke one event at invocation of clear and by one event per added item // Write custom BulkObservableCollection to avoid so many events Languages.Clear(); foreach (var language in option.Languages) { Languages.Add(new LanguageViewModel(language, resetValuesProvider)); } } public ObservableCollection<LanguageViewModel> Languages { get; } = new ObservableCollection<LanguageViewModel>(); private LanguageViewModel _selectedLanguage; public LanguageViewModel SelectedLanguage { get { if (_selectedLanguage is null && Languages.Count > 0) { SelectedLanguage = Languages[0]; } return _selectedLanguage; } set => SetProperty(ref _selectedLanguage, value); } public Option ExtractData() { var option = new Option(); foreach (var languageViewModel in Languages) { option.Languages.Add(languageViewModel.ExtractData()); } return option; } } }
mit
C#
84e231da12158645157c169375212243db4f1404
change lib name for Windows+D3D config
florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho
Bindings/Portable/Consts.cs
Bindings/Portable/Consts.cs
using System; using System.Runtime.InteropServices; namespace Urho { internal static class Consts { #if IOS public const string NativeImport = "@rpath/Urho.framework/Urho"; #elif UWP_HOLO public const string NativeImport = "mono-holourho"; #elif WINDOWS_D3D public const string NativeImport = "mono-urho-d3d"; #else public const string NativeImport = "mono-urho"; #endif } }
using System; using System.Runtime.InteropServices; namespace Urho { internal static class Consts { #if IOS public const string NativeImport = "@rpath/Urho.framework/Urho"; #elif UWP_HOLO public const string NativeImport = "mono-holourho"; #else public const string NativeImport = "mono-urho"; #endif } }
mit
C#
f065b0c8b19bb15aabbda207ba554389fe79d48a
Fix PaymentService
lucasdavid/Gamedalf,lucasdavid/Gamedalf
Gamedalf.Services/PaymentService.cs
Gamedalf.Services/PaymentService.cs
using Gamedalf.Core.Data; using Gamedalf.Core.Models; using Gamedalf.Services.Infrastructure; using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Threading.Tasks; namespace Gamedalf.Services { public class PaymentService: Service<Payment> { public PaymentService(ApplicationDbContext db): base(db){} public virtual async Task<ICollection<Payment>> Search(string q) { if (String.IsNullOrEmpty(q)) { return await All(); } return await Db.Payments .Where(e => e.Player.UserName.Contains(q)) .OrderBy(e => e.Player) .ToListAsync(); } } }
using Gamedalf.Core.Data; using Gamedalf.Core.Models; using Gamedalf.Services.Infrastructure; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Gamedalf.Services { public class PaymentService: Service<Payment> { public PaymentService(ApplicationDbContext db): base(db){} public virtual async Task<ICollection<Payment>> Search(string q) { if (String.IsNullOrEmpty(q)) { return await All(); } return await Db.Payments .Where(e => e.Player.UserName.Contains(q)) .OrderBy(e => e.Player) .ToListAsync(); } } }
mit
C#
53ffb2271c545837de71111eeb39339ae5f34814
Add the licence header and remove unused usings
EVAST9919/osu-framework,peppy/osu-framework,ppy/osu-framework,ZLima12/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,peppy/osu-framework
osu.Framework.Tests/Visual/Sprites/TestSceneTexturedTriangle.cs
osu.Framework.Tests/Visual/Sprites/TestSceneTexturedTriangle.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics.Shapes; using osu.Framework.Graphics; using osu.Framework.Graphics.Textures; using osuTK; namespace osu.Framework.Tests.Visual.Sprites { public class TestSceneTexturedTriangle : FrameworkTestScene { public TestSceneTexturedTriangle() { Add(new TexturedTriangle { Anchor = Anchor.Centre, Origin = Anchor.Centre, Size = new Vector2(300, 150) }); } private class TexturedTriangle : Triangle { [BackgroundDependencyLoader] private void load(TextureStore textures) { Texture = textures.Get(@"sample-texture"); } } } }
using osu.Framework.Allocation; using osu.Framework.Graphics.Shapes; using osu.Framework.Graphics; using osu.Framework.Graphics.Textures; using System; using System.Collections.Generic; using osuTK; namespace osu.Framework.Tests.Visual.Sprites { public class TestSceneTexturedTriangle : FrameworkTestScene { public TestSceneTexturedTriangle() { Add(new TexturedTriangle { Anchor = Anchor.Centre, Origin = Anchor.Centre, Size = new Vector2(300, 150) }); } private class TexturedTriangle : Triangle { [BackgroundDependencyLoader] private void load(TextureStore textures) { Texture = textures.Get(@"sample-texture"); } } } }
mit
C#
8f168efd4e04aed2b3b2333a1070dee8f8607476
Allow skipping publish of package when fixing docs.
spectresystems/commandline
res/scripts/appveyor.cake
res/scripts/appveyor.cake
public sealed class AppVeyorSettings { public bool IsLocal { get; set; } public bool IsRunningOnAppVeyor { get; set; } public bool IsPullRequest { get; set; } public bool IsDevelopBranch { get; set; } public bool IsMasterBranch { get; set; } public bool IsTaggedBuild { get; set; } public bool IsMaintenanceBuild { get; set; } public static AppVeyorSettings Initialize(ICakeContext context) { var buildSystem = context.BuildSystem(); var branchName = buildSystem.AppVeyor.Environment.Repository.Branch; var commitMessage = buildSystem.AppVeyor.Environment.Repository.Commit.Message?.Trim(); var isMaintenanceBuild = (commitMessage?.StartsWith("(build)", StringComparison.OrdinalIgnoreCase) ?? false) || (commitMessage?.StartsWith("(docs)", StringComparison.OrdinalIgnoreCase) ?? false); return new AppVeyorSettings { IsLocal = buildSystem.IsLocalBuild, IsRunningOnAppVeyor = buildSystem.AppVeyor.IsRunningOnAppVeyor, IsPullRequest = buildSystem.AppVeyor.Environment.PullRequest.IsPullRequest, IsDevelopBranch = "develop".Equals(branchName, StringComparison.OrdinalIgnoreCase), IsMasterBranch = "master".Equals(branchName, StringComparison.OrdinalIgnoreCase), IsTaggedBuild = IsBuildTagged(buildSystem), IsMaintenanceBuild = isMaintenanceBuild }; } public static bool IsBuildTagged(BuildSystem buildSystem) { return buildSystem.AppVeyor.Environment.Repository.Tag.IsTag && !string.IsNullOrWhiteSpace(buildSystem.AppVeyor.Environment.Repository.Tag.Name); } }
public sealed class AppVeyorSettings { public bool IsLocal { get; set; } public bool IsRunningOnAppVeyor { get; set; } public bool IsPullRequest { get; set; } public bool IsDevelopBranch { get; set; } public bool IsMasterBranch { get; set; } public bool IsTaggedBuild { get; set; } public bool IsMaintenanceBuild { get; set; } public static AppVeyorSettings Initialize(ICakeContext context) { var buildSystem = context.BuildSystem(); var branchName = buildSystem.AppVeyor.Environment.Repository.Branch; var commitMessage = buildSystem.AppVeyor.Environment.Repository.Commit.Message?.Trim(); var isMaintenanceBuild = commitMessage?.StartsWith("(build)", StringComparison.OrdinalIgnoreCase) ?? false; return new AppVeyorSettings { IsLocal = buildSystem.IsLocalBuild, IsRunningOnAppVeyor = buildSystem.AppVeyor.IsRunningOnAppVeyor, IsPullRequest = buildSystem.AppVeyor.Environment.PullRequest.IsPullRequest, IsDevelopBranch = "develop".Equals(branchName, StringComparison.OrdinalIgnoreCase), IsMasterBranch = "master".Equals(branchName, StringComparison.OrdinalIgnoreCase), IsTaggedBuild = IsBuildTagged(buildSystem), IsMaintenanceBuild = isMaintenanceBuild }; } public static bool IsBuildTagged(BuildSystem buildSystem) { return buildSystem.AppVeyor.Environment.Repository.Tag.IsTag && !string.IsNullOrWhiteSpace(buildSystem.AppVeyor.Environment.Repository.Tag.Name); } }
mit
C#
f3650f8dd95dca9aff4be8419f866a34bf8b4dbe
Increase the version to 1.1.1.
Alovel/BindableApplicationBar,Alovel/BindableApplicationBar
BindableApplicationBar/Properties/AssemblyInfo.cs
BindableApplicationBar/Properties/AssemblyInfo.cs
using System.Reflection; using System.Resources; 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("BindableApplicationBar")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Filip Skakun")] [assembly: AssemblyProduct("BindableApplicationBar")] [assembly: AssemblyCopyright("Copyright © Filip Skakun, 2011-2013")] [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("d0df5e03-2f69-4d10-a40d-25afcbbb7e09")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.1.1")] [assembly: AssemblyFileVersion("1.1.1")] [assembly: NeutralResourcesLanguageAttribute("en-US")]
using System.Reflection; using System.Resources; 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("BindableApplicationBar")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Filip Skakun")] [assembly: AssemblyProduct("BindableApplicationBar")] [assembly: AssemblyCopyright("Copyright © Filip Skakun, 2011-2013")] [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("d0df5e03-2f69-4d10-a40d-25afcbbb7e09")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.1.0.0")] [assembly: AssemblyFileVersion("1.1.0.0")] [assembly: NeutralResourcesLanguageAttribute("en-US")]
mit
C#
5b2c0af105787653214bbbf5d0da31edfa27b979
Change release manager zip file name
GliderPro/CoolFish,dgladkov/CoolFish
CoolFish/ReleaseManager/ReleaseManager/Program.cs
CoolFish/ReleaseManager/ReleaseManager/Program.cs
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.IO.Compression; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ReleaseManager { class Program { static void Main(string[] args) { try { if (args.Length == 0) { return; } var mainFileName = args[0]; var version = FileVersionInfo.GetVersionInfo(mainFileName).FileVersion; var archive = ZipFile.Open(version + ".zip", ZipArchiveMode.Create); archive.CreateEntryFromFile(mainFileName, mainFileName); for (int i = 1; i < args.Length; i++) { archive.CreateEntryFromFile(args[i], args[i]); } archive.Dispose(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); Environment.Exit(1); } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.IO.Compression; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ReleaseManager { class Program { static void Main(string[] args) { try { if (args.Length == 0) { return; } var mainFileName = args[0]; var version = FileVersionInfo.GetVersionInfo(mainFileName).FileVersion; var archive = ZipFile.Open("Release_" + version + ".zip", ZipArchiveMode.Create); archive.CreateEntryFromFile(mainFileName, mainFileName); for (int i = 1; i < args.Length; i++) { archive.CreateEntryFromFile(args[i], args[i]); } archive.Dispose(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); Environment.Exit(1); } } } }
mit
C#
7ca4131cef37505e195d8ec2b402049681c42474
update tests
andyshao/NHibernate.AspNet.Identity,smallkid/NHibernate.AspNet.Identity,smallkid/NHibernate.AspNet.Identity,lnu/NHibernate.AspNet.Identity,andyshao/NHibernate.AspNet.Identity,lnu/NHibernate.AspNet.Identity,andyshao/NHibernate.AspNet.Identity,smallkid/NHibernate.AspNet.Identity,lnu/NHibernate.AspNet.Identity,nhibernate/NHibernate.AspNet.Identity,nhibernate/NHibernate.AspNet.Identity,nhibernate/NHibernate.AspNet.Identity
source/MilesiBastos.AspNet.Identity.NHibernate.Tests/MapTest.cs
source/MilesiBastos.AspNet.Identity.NHibernate.Tests/MapTest.cs
using System; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using FluentNHibernate.Testing; using FluentNHibernate.Cfg.Db; using SharpArch.NHibernate; using NHibernate.Mapping.ByCode; using SharpArch.Domain.DomainModel; using NHibernate.Cfg; using NHibernate; using System.IO; using NHibernate.Tool.hbm2ddl; namespace MilesiBastos.AspNet.Identity.NHibernate.Tests { [TestClass] public class MapTest { [TestMethod] public void CanCorrectlyMapIdentityUser() { var mapper = new ModelMapper(); mapper.AddMapping<IdentityUserMap>(); mapper.AddMapping<IdentityRoleMap>(); mapper.AddMapping<IdentityUserClaimMap>(); mapper.AddMapping<IdentityUserLoginMap>(); var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities(); var configuration = new Configuration(); configuration.Configure("sqlite-nhibernate-config.xml"); configuration.AddDeserializedMapping(mapping, null); var factory = configuration.BuildSessionFactory(); var session = factory.OpenSession(); BuildSchema(configuration); new PersistenceSpecification<IdentityUser>(session) .CheckProperty(c => c.UserName, "John") .VerifyTheMappings(); } private static void BuildSchema(Configuration config) { var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"App_Data\sql\schema.sql"); if (!Directory.Exists(Path.GetDirectoryName(path))) Directory.CreateDirectory(Path.GetDirectoryName(path)); // this NHibernate tool takes a configuration (with mapping info in) // and exports a database schema from it new SchemaExport(config) .SetOutputFile(path) .Create(true, true /* DROP AND CREATE SCHEMA */); } } }
using FluentNHibernate.Testing; using Microsoft.VisualStudio.TestTools.UnitTesting; using NHibernate.Cfg; using NHibernate.Mapping.ByCode; using NHibernate.Tool.hbm2ddl; using SharpArch.NHibernate; using System; using System.IO; namespace MilesiBastos.AspNet.Identity.NHibernate.Tests { [TestClass] public class MapTest { [TestMethod] public void CanCorrectlyMapIdentityUser() { var mapper = new ConventionModelMapper(); mapper.AddMapping<IdentityUserMap>(); mapper.AddMapping<IdentityRoleMap>(); mapper.AddMapping<IdentityUserClaimMap>(); mapper.AddMapping<IdentityUserLoginMap>(); var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities(); var configuration = NHibernateSession.Init( new SimpleSessionStorage(), mapping, "sqlite-nhibernate-config.xml"); BuildSchema(configuration); var session = NHibernateSession.Current; new PersistenceSpecification<IdentityUser>(session) .CheckProperty(c => c.UserName, "John") .VerifyTheMappings(); NHibernateSession.Reset(); } private static void BuildSchema(Configuration config) { var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"App_Data\sql\schema.sql"); if (!Directory.Exists(Path.GetDirectoryName(path))) Directory.CreateDirectory(Path.GetDirectoryName(path)); // this NHibernate tool takes a configuration (with mapping info in) // and exports a database schema from it new SchemaExport(config) .SetOutputFile(path) .Create(true, true /* DROP AND CREATE SCHEMA */); } } }
mit
C#
70de6bd65707519cc0ed9e4ff3acc3048f1d238c
disable eibd integration tests for now
CumpsD/knx.net,CumpsD/knx.net,CumpsD/knx.net,lifeemotions/knx.net,lifeemotions/knx.net,CumpsD/knx.net,lifeemotions/knx.net,lifeemotions/knx.net
KNXLibTests/Integration/Routing/ActionFeedback.cs
KNXLibTests/Integration/Routing/ActionFeedback.cs
using System; using System.Threading; using KNXLib; using NUnit.Framework; namespace KNXLibTests.Unit.DataPoint { [TestFixture] internal class ActionFeedback { [TestFixtureSetUp] public void SetUp() { if (!Support.Eibd.DaemonManager.IsEibdAvailable()) throw new PlatformNotSupportedException("Can't run integration tests without eibd daemon installed on the system"); if (!Support.Eibd.DaemonManager.StartRouting()) throw new Exception("Could not start eibd daemon"); } [TestFixtureTearDown] public void TearDown() { Support.Eibd.DaemonManager.Stop(); } private ManualResetEventSlim ResetEvent { get; set; } private const string LightOnOffAddress = "5/0/2"; private const bool LightOnOffActionStatus = true; private const int Timeout = 100; [Category("KNXLib.Integration.Routing.ActionFeedback"), Test] public void RoutingActionFeedbackTest() { // disable for now to prevent build failure return; ResetEvent = new ManualResetEventSlim(); KnxConnection _connection; _connection = new KnxConnectionRouting { Debug = false }; _connection.KnxEventDelegate += Event; _connection.Connect(); _connection.Action(LightOnOffAddress, true); if (!ResetEvent.Wait(Timeout)) Assert.Fail("Didn't receive feedback from the action"); } private void Event(string address, string state) { if (LightOnOffAddress.Equals(address) && LightOnOffActionStatus.Equals(state)) ResetEvent.Set(); } } }
using System; using System.Threading; using KNXLib; using NUnit.Framework; namespace KNXLibTests.Unit.DataPoint { [TestFixture] internal class ActionFeedback { [TestFixtureSetUp] public void SetUp() { if (!Support.Eibd.DaemonManager.IsEibdAvailable()) throw new PlatformNotSupportedException("Can't run integration tests without eibd daemon installed on the system"); Support.Eibd.DaemonManager.StartRouting(); } [TestFixtureTearDown] public void TearDown() { } private ManualResetEventSlim ResetEvent { get; set; } private const string LightOnOffAddress = "5/0/2"; private const bool LightOnOffActionStatus = true; private const int Timeout = 100; [Category("KNXLib.Integration.Routing.ActionFeedback"), Test] public void RoutingActionFeedbackTest() { ResetEvent = new ManualResetEventSlim(); KnxConnection _connection; _connection = new KnxConnectionRouting { Debug = false }; _connection.KnxEventDelegate += Event; //_connection.KnxStatusDelegate += Status; _connection.Connect(); _connection.Action(LightOnOffAddress, true); if (!ResetEvent.Wait(Timeout)) Assert.Fail("Didn't receive feedback from the action"); } private void Event(string address, string state) { if (LightOnOffAddress.Equals(address) && LightOnOffActionStatus.Equals(state)) ResetEvent.Set(); } } }
mit
C#
d0bc9f19a3067f0fbf0891f2c45be731baecb58f
Use correct parameter order!
AvaloniaUI/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,grokys/Perspex,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,Perspex/Perspex,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,grokys/Perspex,wieslawsoltes/Perspex,jkoritzinsky/Perspex,akrisiun/Perspex,Perspex/Perspex,SuperJMN/Avalonia,SuperJMN/Avalonia
src/Avalonia.Base/Data/Converters/StringFormatValueConverter.cs
src/Avalonia.Base/Data/Converters/StringFormatValueConverter.cs
using System; using System.Globalization; namespace Avalonia.Data.Converters { /// <summary> /// A value converter which calls <see cref="string.Format(string, object)"/> /// </summary> public class StringFormatValueConverter : IValueConverter { /// <summary> /// Initializes a new instance of the <see cref="StringFormatValueConverter"/> class. /// </summary> /// <param name="format">The format string.</param> /// <param name="inner"> /// An optional inner converter to be called before the format takes place. /// </param> public StringFormatValueConverter(string format, IValueConverter inner) { Contract.Requires<ArgumentNullException>(format != null); Format = format; Inner = inner; } /// <summary> /// Gets an inner value converter which will be called before the string format takes place. /// </summary> public IValueConverter Inner { get; } /// <summary> /// Gets the format string. /// </summary> public string Format { get; } /// <inheritdoc/> public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { value = Inner?.Convert(value, targetType, parameter, culture) ?? value; return string.Format(culture, Format, value); } /// <inheritdoc/> public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotSupportedException("Two way bindings are not supported with a string format"); } } }
using System; using System.Globalization; namespace Avalonia.Data.Converters { /// <summary> /// A value converter which calls <see cref="string.Format(string, object)"/> /// </summary> public class StringFormatValueConverter : IValueConverter { /// <summary> /// Initializes a new instance of the <see cref="StringFormatValueConverter"/> class. /// </summary> /// <param name="format">The format string.</param> /// <param name="inner"> /// An optional inner converter to be called before the format takes place. /// </param> public StringFormatValueConverter(string format, IValueConverter inner) { Contract.Requires<ArgumentNullException>(format != null); Format = format; Inner = inner; } /// <summary> /// Gets an inner value converter which will be called before the string format takes place. /// </summary> public IValueConverter Inner { get; } /// <summary> /// Gets the format string. /// </summary> public string Format { get; } /// <inheritdoc/> public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { value = Inner?.Convert(value, targetType, parameter, culture) ?? value; return string.Format(Format, value, culture); } /// <inheritdoc/> public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotSupportedException("Two way bindings are not supported with a string format"); } } }
mit
C#
1956d9b33f5d10068ed9cac6d913494288f29039
Make test async.
mseamari/Stuff,jaredpar/roslyn,Maxwe11/roslyn,rgani/roslyn,khyperia/roslyn,davkean/roslyn,sharwell/roslyn,bartdesmet/roslyn,TyOverby/roslyn,lorcanmooney/roslyn,shyamnamboodiripad/roslyn,ErikSchierboom/roslyn,vcsjones/roslyn,sharadagrawal/Roslyn,jcouv/roslyn,xoofx/roslyn,HellBrick/roslyn,mattwar/roslyn,antonssonj/roslyn,eriawan/roslyn,dpoeschl/roslyn,MatthieuMEZIL/roslyn,TyOverby/roslyn,xoofx/roslyn,tannergooding/roslyn,HellBrick/roslyn,balajikris/roslyn,SeriaWei/roslyn,mmitche/roslyn,KevinH-MS/roslyn,HellBrick/roslyn,tvand7093/roslyn,stephentoub/roslyn,wvdd007/roslyn,drognanar/roslyn,DustinCampbell/roslyn,KevinH-MS/roslyn,heejaechang/roslyn,ValentinRueda/roslyn,a-ctor/roslyn,a-ctor/roslyn,mavasani/roslyn,jasonmalinowski/roslyn,mgoertz-msft/roslyn,rgani/roslyn,weltkante/roslyn,TyOverby/roslyn,MattWindsor91/roslyn,tvand7093/roslyn,Hosch250/roslyn,eriawan/roslyn,bbarry/roslyn,AmadeusW/roslyn,heejaechang/roslyn,bbarry/roslyn,akrisiun/roslyn,drognanar/roslyn,CaptainHayashi/roslyn,Maxwe11/roslyn,tmeschter/roslyn,AArnott/roslyn,zooba/roslyn,basoundr/roslyn,amcasey/roslyn,VPashkov/roslyn,paulvanbrenk/roslyn,sharwell/roslyn,SeriaWei/roslyn,AnthonyDGreen/roslyn,agocke/roslyn,dotnet/roslyn,SeriaWei/roslyn,panopticoncentral/roslyn,tmat/roslyn,budcribar/roslyn,ljw1004/roslyn,eriawan/roslyn,tmat/roslyn,srivatsn/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,VPashkov/roslyn,Pvlerick/roslyn,abock/roslyn,tmeschter/roslyn,shyamnamboodiripad/roslyn,reaction1989/roslyn,mattscheffer/roslyn,OmarTawfik/roslyn,rgani/roslyn,tannergooding/roslyn,cston/roslyn,zooba/roslyn,jkotas/roslyn,VPashkov/roslyn,CyrusNajmabadi/roslyn,mseamari/Stuff,KiloBravoLima/roslyn,mmitche/roslyn,jcouv/roslyn,aelij/roslyn,MatthieuMEZIL/roslyn,khyperia/roslyn,sharadagrawal/Roslyn,swaroop-sridhar/roslyn,jmarolf/roslyn,KevinRansom/roslyn,physhi/roslyn,bkoelman/roslyn,dpoeschl/roslyn,weltkante/roslyn,AArnott/roslyn,mavasani/roslyn,srivatsn/roslyn,aelij/roslyn,thomaslevesque/roslyn,diryboy/roslyn,ErikSchierboom/roslyn,Giftednewt/roslyn,nguerrera/roslyn,balajikris/roslyn,jaredpar/roslyn,MattWindsor91/roslyn,Shiney/roslyn,leppie/roslyn,ValentinRueda/roslyn,natidea/roslyn,KevinRansom/roslyn,CyrusNajmabadi/roslyn,managed-commons/roslyn,nguerrera/roslyn,natidea/roslyn,Giftednewt/roslyn,natgla/roslyn,xasx/roslyn,yeaicc/roslyn,KirillOsenkov/roslyn,reaction1989/roslyn,jaredpar/roslyn,Maxwe11/roslyn,MichalStrehovsky/roslyn,natgla/roslyn,lorcanmooney/roslyn,KevinRansom/roslyn,leppie/roslyn,jhendrixMSFT/roslyn,genlu/roslyn,jmarolf/roslyn,jasonmalinowski/roslyn,dpoeschl/roslyn,MatthieuMEZIL/roslyn,ljw1004/roslyn,jmarolf/roslyn,yeaicc/roslyn,shyamnamboodiripad/roslyn,jasonmalinowski/roslyn,mgoertz-msft/roslyn,diryboy/roslyn,jhendrixMSFT/roslyn,ericfe-ms/roslyn,cston/roslyn,antonssonj/roslyn,basoundr/roslyn,bkoelman/roslyn,srivatsn/roslyn,abock/roslyn,jkotas/roslyn,zooba/roslyn,ErikSchierboom/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,AArnott/roslyn,a-ctor/roslyn,dotnet/roslyn,KirillOsenkov/roslyn,thomaslevesque/roslyn,orthoxerox/roslyn,KevinH-MS/roslyn,ericfe-ms/roslyn,VSadov/roslyn,budcribar/roslyn,davkean/roslyn,stephentoub/roslyn,sharadagrawal/Roslyn,MichalStrehovsky/roslyn,AnthonyDGreen/roslyn,agocke/roslyn,Pvlerick/roslyn,bbarry/roslyn,diryboy/roslyn,MichalStrehovsky/roslyn,Giftednewt/roslyn,kelltrick/roslyn,jamesqo/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,ericfe-ms/roslyn,vslsnap/roslyn,vcsjones/roslyn,vslsnap/roslyn,xasx/roslyn,drognanar/roslyn,jamesqo/roslyn,reaction1989/roslyn,khellang/roslyn,jeffanders/roslyn,gafter/roslyn,AlekseyTs/roslyn,nguerrera/roslyn,bartdesmet/roslyn,sharwell/roslyn,paulvanbrenk/roslyn,jcouv/roslyn,brettfo/roslyn,ValentinRueda/roslyn,akrisiun/roslyn,jamesqo/roslyn,VSadov/roslyn,amcasey/roslyn,physhi/roslyn,tmat/roslyn,wvdd007/roslyn,natidea/roslyn,agocke/roslyn,Pvlerick/roslyn,cston/roslyn,khellang/roslyn,DustinCampbell/roslyn,mseamari/Stuff,OmarTawfik/roslyn,genlu/roslyn,mattwar/roslyn,orthoxerox/roslyn,mattscheffer/roslyn,VSadov/roslyn,mmitche/roslyn,AlekseyTs/roslyn,KiloBravoLima/roslyn,managed-commons/roslyn,dotnet/roslyn,brettfo/roslyn,KiloBravoLima/roslyn,panopticoncentral/roslyn,xoofx/roslyn,aelij/roslyn,CaptainHayashi/roslyn,AlekseyTs/roslyn,mattwar/roslyn,kelltrick/roslyn,Shiney/roslyn,swaroop-sridhar/roslyn,michalhosala/roslyn,robinsedlaczek/roslyn,michalhosala/roslyn,Hosch250/roslyn,robinsedlaczek/roslyn,tannergooding/roslyn,AmadeusW/roslyn,Shiney/roslyn,jhendrixMSFT/roslyn,pdelvo/roslyn,physhi/roslyn,weltkante/roslyn,jeffanders/roslyn,MattWindsor91/roslyn,jkotas/roslyn,pdelvo/roslyn,stephentoub/roslyn,kelltrick/roslyn,KirillOsenkov/roslyn,tvand7093/roslyn,robinsedlaczek/roslyn,yeaicc/roslyn,mattscheffer/roslyn,Hosch250/roslyn,amcasey/roslyn,wvdd007/roslyn,michalhosala/roslyn,khyperia/roslyn,managed-commons/roslyn,ljw1004/roslyn,natgla/roslyn,xasx/roslyn,lorcanmooney/roslyn,leppie/roslyn,akrisiun/roslyn,genlu/roslyn,orthoxerox/roslyn,MattWindsor91/roslyn,balajikris/roslyn,budcribar/roslyn,vcsjones/roslyn,tmeschter/roslyn,CyrusNajmabadi/roslyn,jeffanders/roslyn,CaptainHayashi/roslyn,khellang/roslyn,swaroop-sridhar/roslyn,DustinCampbell/roslyn,brettfo/roslyn,gafter/roslyn,mavasani/roslyn,davkean/roslyn,vslsnap/roslyn,OmarTawfik/roslyn,antonssonj/roslyn,mgoertz-msft/roslyn,panopticoncentral/roslyn,basoundr/roslyn,paulvanbrenk/roslyn,pdelvo/roslyn,bkoelman/roslyn,gafter/roslyn,heejaechang/roslyn,AnthonyDGreen/roslyn,AmadeusW/roslyn,thomaslevesque/roslyn,abock/roslyn,bartdesmet/roslyn
src/Workspaces/CSharpTest/Formatting/FormattingTreeEditTests.cs
src/Workspaces/CSharpTest/Formatting/FormattingTreeEditTests.cs
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using Microsoft.CodeAnalysis.CSharp.Formatting; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using System.Linq; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Formatting { public class FormattingTreeEditTests : CSharpFormattingTestBase { private Document GetDocument(string code) { var ws = new AdhocWorkspace(); var project = ws.AddProject("project", LanguageNames.CSharp); return project.AddDocument("code", SourceText.From(code)); } [Fact] public async Task SpaceAfterAttribute() { string code = @" public class C { void M(int? p) { } } "; var document = GetDocument(code); var g = SyntaxGenerator.GetGenerator(document); var root = document.GetSyntaxRootAsync().Result; var attr = g.Attribute("MyAttr"); var param = root.DescendantNodes().OfType<ParameterSyntax>().First(); Assert.Equal(@" public class C { void M([MyAttr] int? p) { } } ", (await Formatter.FormatAsync(root.ReplaceNode(param, g.AddAttributes(param, g.Attribute("MyAttr"))), document.Project.Solution.Workspace)).ToFullString()); // verify change doesn't affect how attributes appear before other kinds of declarations var method = root.DescendantNodes().OfType<MethodDeclarationSyntax>().First(); Assert.Equal(@" public class C { [MyAttr] void M(int? p) { } } ", (await Formatter.FormatAsync(root.ReplaceNode(method, g.AddAttributes(method, g.Attribute("MyAttr"))), document.Project.Solution.Workspace)).ToFullString()); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using Microsoft.CodeAnalysis.CSharp.Formatting; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using System.Linq; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Formatting { public class FormattingTreeEditTests : CSharpFormattingTestBase { private Document GetDocument(string code) { var ws = new AdhocWorkspace(); var project = ws.AddProject("project", LanguageNames.CSharp); return project.AddDocument("code", SourceText.From(code)); } [Fact] public void SpaceAfterAttribute() { string code = @" public class C { void M(int? p) { } } "; var document = GetDocument(code); var g = SyntaxGenerator.GetGenerator(document); var root = document.GetSyntaxRootAsync().Result; var attr = g.Attribute("MyAttr"); var param = root.DescendantNodes().OfType<ParameterSyntax>().First(); Assert.Equal(@" public class C { void M([MyAttr] int? p) { } } ", Formatter.Format(root.ReplaceNode(param, g.AddAttributes(param, g.Attribute("MyAttr"))), document.Project.Solution.Workspace).ToFullString()); // verify change doesn't affect how attributes appear before other kinds of declarations var method = root.DescendantNodes().OfType<MethodDeclarationSyntax>().First(); Assert.Equal(@" public class C { [MyAttr] void M(int? p) { } } ", Formatter.Format(root.ReplaceNode(method, g.AddAttributes(method, g.Attribute("MyAttr"))), document.Project.Solution.Workspace).ToFullString()); } } }
mit
C#
9c286a11e1c43bda49fc6e082559de7dfe777b11
Update raw sending
WojcikMike/docs.particular.net
Snippets/Snippets_6/UpgradeGuides/5to6/RawSend.cs
Snippets/Snippets_6/UpgradeGuides/5to6/RawSend.cs
// ReSharper disable PossibleNullReferenceException namespace Snippets6.UpgradeGuides._5to6 { using System.Collections.Generic; using System.Threading.Tasks; using NServiceBus; using NServiceBus.Extensibility; using NServiceBus.Routing; using NServiceBus.Transports; public class RawSend { public async Task RawSending() { IDispatchMessages dispatcher = null; #region DispatcherRawSending Dictionary<string, string> headers = new Dictionary<string, string>(); OutgoingMessage outgoingMessage = new OutgoingMessage("MessageId", headers, new byte[] { }); NonDurableDelivery[] constraints = { new NonDurableDelivery() }; UnicastAddressTag address = new UnicastAddressTag("Destination"); TransportOperation transportOperation = new TransportOperation(outgoingMessage, address, DispatchConsistency.Default, constraints); TransportOperations operations = new TransportOperations(transportOperation); await dispatcher.Dispatch(operations, new ContextBag()); #endregion } } }
// ReSharper disable PossibleNullReferenceException namespace Snippets6.UpgradeGuides._5to6 { using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using NServiceBus; using NServiceBus.Extensibility; using NServiceBus.Routing; using NServiceBus.Transports; public class RawSend { public async Task RawSending() { IDispatchMessages dispatcher = null; #region DispatcherRawSending Dictionary<string, string> headers = new Dictionary<string, string>(); OutgoingMessage outgoingMessage = new OutgoingMessage("MessageId", headers, new byte[] { }); NonDurableDelivery[] constraints = { new NonDurableDelivery() }; UnicastAddressTag address = new UnicastAddressTag("Destination"); TransportOperation transportOperation = new TransportOperation(outgoingMessage, address, DispatchConsistency.Default, constraints); UnicastTransportOperation unicastTransportOperation = new UnicastTransportOperation(outgoingMessage, "destination"); IEnumerable<MulticastTransportOperation> multicastOperations = Enumerable.Empty<MulticastTransportOperation>(); UnicastTransportOperation[] unicastOperations = { unicastTransportOperation }; TransportOperations operations = new TransportOperations(multicastOperations, unicastOperations); await dispatcher.Dispatch(operations, new ContextBag()); #endregion } } }
apache-2.0
C#
b9d99b5f4049531bcb9c255d78c088652c094b29
Fix nullref when exiting the last screen.
peppy/osu,DrabWeb/osu,naoey/osu,ppy/osu,naoey/osu,2yangk23/osu,johnneijzen/osu,naoey/osu,ppy/osu,ppy/osu,NeoAdonis/osu,peppy/osu-new,ZLima12/osu,UselessToucan/osu,NeoAdonis/osu,peppy/osu,EVAST9919/osu,johnneijzen/osu,smoogipoo/osu,smoogipoo/osu,peppy/osu,UselessToucan/osu,smoogipoo/osu,2yangk23/osu,smoogipooo/osu,ZLima12/osu,DrabWeb/osu,NeoAdonis/osu,UselessToucan/osu,DrabWeb/osu,EVAST9919/osu
osu.Game/Graphics/UserInterface/ScreenBreadcrumbControl.cs
osu.Game/Graphics/UserInterface/ScreenBreadcrumbControl.cs
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System.Linq; using osu.Framework.Extensions.IEnumerableExtensions; using osu.Framework.Screens; namespace osu.Game.Graphics.UserInterface { /// <summary> /// A <see cref="BreadcrumbControl"/> which follows the active screen (and allows navigation) in a <see cref="Screen"/> stack. /// </summary> public class ScreenBreadcrumbControl : BreadcrumbControl<Screen> { private Screen last; public ScreenBreadcrumbControl(Screen initialScreen) { Current.ValueChanged += newScreen => { if (last != newScreen && !newScreen.IsCurrentScreen) newScreen.MakeCurrent(); }; onPushed(initialScreen); } private void screenChanged(Screen newScreen) { if (newScreen == null) return; if (last != null) { last.Exited -= screenChanged; last.ModePushed -= onPushed; } last = newScreen; newScreen.Exited += screenChanged; newScreen.ModePushed += onPushed; Current.Value = newScreen; } private void onPushed(Screen screen) { Items.ToList().SkipWhile(i => i != Current.Value).Skip(1).ForEach(RemoveItem); AddItem(screen); screenChanged(screen); } } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System.Linq; using osu.Framework.Extensions.IEnumerableExtensions; using osu.Framework.Screens; namespace osu.Game.Graphics.UserInterface { /// <summary> /// A <see cref="BreadcrumbControl"/> which follows the active screen (and allows navigation) in a <see cref="Screen"/> stack. /// </summary> public class ScreenBreadcrumbControl : BreadcrumbControl<Screen> { private Screen last; public ScreenBreadcrumbControl(Screen initialScreen) { Current.ValueChanged += newScreen => { if (last != newScreen && !newScreen.IsCurrentScreen) newScreen.MakeCurrent(); }; onPushed(initialScreen); } private void screenChanged(Screen newScreen) { if (last != null) { last.Exited -= screenChanged; last.ModePushed -= onPushed; } last = newScreen; newScreen.Exited += screenChanged; newScreen.ModePushed += onPushed; Current.Value = newScreen; } private void onPushed(Screen screen) { Items.ToList().SkipWhile(i => i != Current.Value).Skip(1).ForEach(RemoveItem); AddItem(screen); screenChanged(screen); } } }
mit
C#
39bbb826dbcdb18a26f3014b8c8fc810f2fef4f5
Fix for DIActorProducer #941
dbolkensteyn/akka.net,Chinchilla-Software-Com/akka.net,KadekM/akka.net,trbngr/akka.net,kerryjiang/akka.net,ali-ince/akka.net,billyxing/akka.net,JeffCyr/akka.net,simonlaroche/akka.net,rogeralsing/akka.net,MAOliver/akka.net,dbolkensteyn/akka.net,amichel/akka.net,Silv3rcircl3/akka.net,matiii/akka.net,naveensrinivasan/akka.net,neekgreen/akka.net,akoshelev/akka.net,ali-ince/akka.net,jordansjones/akka.net,kstaruch/akka.net,chris-ray/akka.net,bruinbrown/akka.net,alexpantyukhin/akka.net,skotzko/akka.net,nanderto/akka.net,chris-ray/akka.net,AntoineGa/akka.net,thelegendofando/akka.net,gwokudasam/akka.net,Silv3rcircl3/akka.net,naveensrinivasan/akka.net,alexvaluyskiy/akka.net,dyanarose/akka.net,eisendle/akka.net,willieferguson/akka.net,alexvaluyskiy/akka.net,kekekeks/akka.net,silentnull/akka.net,MAOliver/akka.net,cpx/akka.net,derwasp/akka.net,michal-franc/akka.net,Micha-kun/akka.net,dyanarose/akka.net,eloraiby/akka.net,gwokudasam/akka.net,trbngr/akka.net,alexpantyukhin/akka.net,tillr/akka.net,skotzko/akka.net,kekekeks/akka.net,vchekan/akka.net,silentnull/akka.net,Chinchilla-Software-Com/akka.net,numo16/akka.net,d--g/akka.net,Micha-kun/akka.net,neekgreen/akka.net,kerryjiang/akka.net,michal-franc/akka.net,KadekM/akka.net,GeorgeFocas/akka.net,tillr/akka.net,alex-kondrashov/akka.net,bruinbrown/akka.net,AntoineGa/akka.net,cdmdotnet/akka.net,stefansedich/akka.net,akoshelev/akka.net,nanderto/akka.net,stefansedich/akka.net,alex-kondrashov/akka.net,heynickc/akka.net,amichel/akka.net,vchekan/akka.net,ashic/akka.net,willieferguson/akka.net,JeffCyr/akka.net,numo16/akka.net,eisendle/akka.net,linearregression/akka.net,eloraiby/akka.net,GeorgeFocas/akka.net,cdmdotnet/akka.net,ashic/akka.net,linearregression/akka.net,derwasp/akka.net,heynickc/akka.net,cpx/akka.net,matiii/akka.net,rogeralsing/akka.net,thelegendofando/akka.net,jordansjones/akka.net,billyxing/akka.net,d--g/akka.net,simonlaroche/akka.net,kstaruch/akka.net,zbrad/akka.net,zbrad/akka.net
src/contrib/dependencyInjection/Akka.DI.Core/DIActorProducer.cs
src/contrib/dependencyInjection/Akka.DI.Core/DIActorProducer.cs
//----------------------------------------------------------------------- // <copyright file="DIActorProducer.cs" company="Akka.NET Project"> // Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> // Copyright (C) 2013-2015 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using Akka.Actor; namespace Akka.DI.Core { /// <summary> /// Dependency Injection Backed IndirectActorProducer /// </summary> public class DIActorProducer : IIndirectActorProducer { private IDependencyResolver dependencyResolver; private Type actorType; readonly Func<ActorBase> actorFactory; public DIActorProducer(IDependencyResolver dependencyResolver, Type actorType) { if (dependencyResolver == null) throw new ArgumentNullException("dependencyResolver"); if (actorType == null) throw new ArgumentNullException("actorType"); this.dependencyResolver = dependencyResolver; this.actorType = actorType; this.actorFactory = dependencyResolver.CreateActorFactory(actorType); } /// <summary> /// The System.Type of the Actor specified in the constructor parameter actorName /// </summary> public Type ActorType { get { return this.actorType.GetType(); } } /// <summary> /// Creates an instance of the Actor based on the Type specified in the constructor parameter actorName /// </summary> /// <returns></returns> public ActorBase Produce() { return actorFactory(); } /// <summary> /// This method is used to signal the DI Container that it can /// release it's reference to the actor. <see href="http://www.amazon.com/Dependency-Injection-NET-Mark-Seemann/dp/1935182501/ref=sr_1_1?ie=UTF8&qid=1425861096&sr=8-1&keywords=mark+seemann">HERE</see> /// </summary> /// <param name="actor"></param> public void Release(ActorBase actor) { dependencyResolver.Release(actor); } } }
//----------------------------------------------------------------------- // <copyright file="DIActorProducer.cs" company="Akka.NET Project"> // Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> // Copyright (C) 2013-2015 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using Akka.Actor; namespace Akka.DI.Core { /// <summary> /// Dependency Injection Backed IndirectActorProducer /// </summary> public class DIActorProducer : IIndirectActorProducer { private IDependencyResolver dependencyResolver; private Type actorType; readonly Func<ActorBase> actorFactory; public DIActorProducer(IDependencyResolver dependencyResolver, Type actorType) { if (dependencyResolver == null) throw new ArgumentNullException("dependencyResolver"); if (actorType == null) throw new ArgumentNullException("actorType"); this.dependencyResolver = dependencyResolver; this.actorType = actorType; this.actorFactory = dependencyResolver.CreateActorFactory(actorType); } /// <summary> /// The System.Type of the Actor specified in the constructor parameter actorName /// </summary> public Type ActorType { get { return this.dependencyResolver.GetType(); } } /// <summary> /// Creates an instance of the Actor based on the Type specified in the constructor parameter actorName /// </summary> /// <returns></returns> public ActorBase Produce() { return actorFactory(); } /// <summary> /// This method is used to signal the DI Container that it can /// release it's reference to the actor. <see href="http://www.amazon.com/Dependency-Injection-NET-Mark-Seemann/dp/1935182501/ref=sr_1_1?ie=UTF8&qid=1425861096&sr=8-1&keywords=mark+seemann">HERE</see> /// </summary> /// <param name="actor"></param> public void Release(ActorBase actor) { dependencyResolver.Release(actor); } } }
apache-2.0
C#
6237e4595fc0a7f9c4c8ad144115c35be4e81d63
Improve console menu for "visual" tests
roman-yagodin/R7.University,roman-yagodin/R7.University,roman-yagodin/R7.University
R7.University.Core.Tests/Program.cs
R7.University.Core.Tests/Program.cs
using System; using R7.University.Core.Templates; namespace R7.University.Core.Tests { class Program { static void Main (string [] args) { while (true) { Console.WriteLine ("> Please enter test number and press [Enter]:"); Console.WriteLine ("---"); Console.WriteLine ("1. Workbook to CSV"); Console.WriteLine ("2. Workbook to linear CSV"); Console.WriteLine ("0. Exit"); if (int.TryParse (Console.ReadLine (), out int testNum)) { switch (testNum) { case 1: WorkbookToCsv (); break; case 2: WorkbookToLinearCsv (); break; case 0: return; } Console.WriteLine ("> Press any key to continue..."); Console.ReadKey (); Console.WriteLine (); } } } static void WorkbookToCsv () { Console.WriteLine ("--- Start test output"); var workbookManager = new WorkbookManager (); Console.Write (workbookManager.SerializeWorkbook ("./assets/templates/workbook-1.xls", WorkbookSerializationFormat.CSV)); Console.WriteLine ("--- End test output"); } static void WorkbookToLinearCsv () { Console.WriteLine ("--- Start test output"); var workbookManager = new WorkbookManager (); Console.Write (workbookManager.SerializeWorkbook ("./assets/templates/workbook-1.xls", WorkbookSerializationFormat.LinearCSV)); Console.WriteLine ("--- End test output"); } } }
using System; using R7.University.Core.Templates; namespace R7.University.Core.Tests { class Program { static void Main (string [] args) { Console.WriteLine ("Please enter test number and press [Enter]:"); Console.WriteLine ("1. Workbook to CSV"); Console.WriteLine ("2. Workbook to linear CSV"); Console.WriteLine ("0. Exit"); if (int.TryParse (Console.ReadLine (), out int testNum)) { switch (testNum) { case 1: WorkbookToCsv (); break; case 2: WorkbookToLinearCsv (); break; } } } static void WorkbookToCsv () { var workbookManager = new WorkbookManager (); Console.Write (workbookManager.SerializeWorkbook ("./assets/templates/workbook-1.xls", WorkbookSerializationFormat.CSV)); } static void WorkbookToLinearCsv () { var workbookManager = new WorkbookManager (); Console.Write (workbookManager.SerializeWorkbook ("./assets/templates/workbook-1.xls", WorkbookSerializationFormat.LinearCSV)); } } }
agpl-3.0
C#
0d5e99546e195c9fdb333676e42f2df147de3e8e
Bump v1.0.21
karronoli/tiny-sato
TinySato/Properties/AssemblyInfo.cs
TinySato/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // アセンブリに関する一般情報は以下の属性セットをとおして制御されます。 // アセンブリに関連付けられている情報を変更するには、 // これらの属性値を変更してください。 [assembly: AssemblyTitle("TinySato")] [assembly: AssemblyDescription("You can construct and send SBPL packet to Sato printer. Sato printer is needed to be recognized by windows driver.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("TinySato")] [assembly: AssemblyCopyright("Copyright 2016 karronoli")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから // 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、 // その型の ComVisible 属性を true に設定してください。 [assembly: ComVisible(false)] // このプロジェクトが COM に公開される場合、次の GUID が typelib の ID になります [assembly: Guid("f56213db-fa1f-42da-b930-b642a56ee840")] // アセンブリのバージョン情報は次の 4 つの値で構成されています: // // メジャー バージョン // マイナー バージョン // ビルド番号 // Revision // // すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を // 既定値にすることができます: [assembly: AssemblyVersion("1.0.21.*")] [assembly: AssemblyFileVersion("1.0.21")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // アセンブリに関する一般情報は以下の属性セットをとおして制御されます。 // アセンブリに関連付けられている情報を変更するには、 // これらの属性値を変更してください。 [assembly: AssemblyTitle("TinySato")] [assembly: AssemblyDescription("You can construct and send SBPL packet to Sato printer. Sato printer is needed to be recognized by windows driver.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("TinySato")] [assembly: AssemblyCopyright("Copyright 2016 karronoli")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから // 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、 // その型の ComVisible 属性を true に設定してください。 [assembly: ComVisible(false)] // このプロジェクトが COM に公開される場合、次の GUID が typelib の ID になります [assembly: Guid("f56213db-fa1f-42da-b930-b642a56ee840")] // アセンブリのバージョン情報は次の 4 つの値で構成されています: // // メジャー バージョン // マイナー バージョン // ビルド番号 // Revision // // すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を // 既定値にすることができます: [assembly: AssemblyVersion("1.0.20.*")] [assembly: AssemblyFileVersion("1.0.20")]
apache-2.0
C#
5f2a8d4039143ef5c59fdac752db45979d2d9729
Update AssemblyDescription
karronoli/tiny-sato
TinySato/Properties/AssemblyInfo.cs
TinySato/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // アセンブリに関する一般情報は以下の属性セットをとおして制御されます。 // アセンブリに関連付けられている情報を変更するには、 // これらの属性値を変更してください。 [assembly: AssemblyTitle("TinySato")] [assembly: AssemblyDescription("You can construct and send SBPL packet to SATO printer. The printer is needed to be configured by windows driver or TCP connection.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("TinySato")] [assembly: AssemblyCopyright("Copyright 2016 karronoli")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから // 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、 // その型の ComVisible 属性を true に設定してください。 [assembly: ComVisible(false)] // このプロジェクトが COM に公開される場合、次の GUID が typelib の ID になります [assembly: Guid("f56213db-fa1f-42da-b930-b642a56ee840")] // アセンブリのバージョン情報は次の 4 つの値で構成されています: // // メジャー バージョン // マイナー バージョン // ビルド番号 // Revision // // すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を // 既定値にすることができます: [assembly: AssemblyVersion("1.1.5.*")] [assembly: AssemblyFileVersion("1.1.5")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // アセンブリに関する一般情報は以下の属性セットをとおして制御されます。 // アセンブリに関連付けられている情報を変更するには、 // これらの属性値を変更してください。 [assembly: AssemblyTitle("TinySato")] [assembly: AssemblyDescription("You can construct and send SBPL packet to Sato printer. Sato printer is needed to be recognized by windows driver.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("TinySato")] [assembly: AssemblyCopyright("Copyright 2016 karronoli")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから // 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、 // その型の ComVisible 属性を true に設定してください。 [assembly: ComVisible(false)] // このプロジェクトが COM に公開される場合、次の GUID が typelib の ID になります [assembly: Guid("f56213db-fa1f-42da-b930-b642a56ee840")] // アセンブリのバージョン情報は次の 4 つの値で構成されています: // // メジャー バージョン // マイナー バージョン // ビルド番号 // Revision // // すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を // 既定値にすることができます: [assembly: AssemblyVersion("1.1.5.*")] [assembly: AssemblyFileVersion("1.1.5")]
apache-2.0
C#
f4dd2323214073141a4378b89a56158af36fe51e
Stabilize TimeCoordinatorTests
williamlord/HealthMonitoring,wongatech/HealthMonitoring,williamlord/HealthMonitoring,Pawlyha/HealthMonitoring,Pawlyha/HealthMonitoring,andronz/HealthMonitoring,Pawlyha/HealthMonitoring,Suremaker/HealthMonitoring,andronz/HealthMonitoring,Suremaker/HealthMonitoring,wongatech/HealthMonitoring,wongatech/HealthMonitoring,andronz/HealthMonitoring,Suremaker/HealthMonitoring,williamlord/HealthMonitoring
HealthMonitoring.Monitors.Core.UnitTests/TimeCoordinatorTests.cs
HealthMonitoring.Monitors.Core.UnitTests/TimeCoordinatorTests.cs
using System; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using HealthMonitoring.Monitors.Core.Helpers.Time; using Xunit; namespace HealthMonitoring.Monitors.Core.UnitTests { public class TimeCoordinatorTests { private readonly ITimeCoordinator _coordinator = new TimeCoordinator(); [Fact] public async Task CreateStopWatch_should_return_object_measuring_time() { var watch = _coordinator.CreateStopWatch(); //before start await Task.Delay(200); Assert.Equal(TimeSpan.Zero, watch.Elapsed); //real measurement var expected = Stopwatch.StartNew(); watch.Start(); await Task.Delay(500); watch.Stop(); expected.Stop(); Assert.True((expected.Elapsed - watch.Elapsed).Duration() < TimeSpan.FromMilliseconds(300), "(expected.Elapsed - watch.Elapsed) < TimeSpan.FromMilliseconds(100)"); //after stop var afterStop = watch.Elapsed; await Task.Delay(200); Assert.Equal(afterStop, watch.Elapsed); } [Fact] public void CreateStopWatch_should_return_new_instances_of_stopwatches() { Assert.NotSame(_coordinator.CreateStopWatch(), _coordinator.CreateStopWatch()); } [Fact] public void UtcNow_should_return_proper_time() { Assert.True((DateTime.UtcNow - _coordinator.UtcNow).Duration() < TimeSpan.FromSeconds(1)); } [Fact] public async Task Delay_should_postpone_task_execution() { var watch = Stopwatch.StartNew(); await _coordinator.Delay(TimeSpan.FromMilliseconds(500), CancellationToken.None); watch.Stop(); Assert.True(watch.Elapsed > TimeSpan.FromMilliseconds(400), "watch.Elapsed > TimeSpan.FromMilliseconds(400)"); } [Fact] public async Task Delay_should_be_cancellable() { await Assert.ThrowsAsync<TaskCanceledException>(() => _coordinator.Delay(TimeSpan.FromSeconds(5), new CancellationTokenSource(TimeSpan.FromMilliseconds(100)).Token)); } } }
using System; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using HealthMonitoring.Monitors.Core.Helpers.Time; using Xunit; namespace HealthMonitoring.Monitors.Core.UnitTests { public class TimeCoordinatorTests { private readonly ITimeCoordinator _coordinator = new TimeCoordinator(); [Fact] public async Task CreateStopWatch_should_return_object_measuring_time() { var watch = _coordinator.CreateStopWatch(); //before start await Task.Delay(200); Assert.Equal(TimeSpan.Zero, watch.Elapsed); //real measurement var expected = Stopwatch.StartNew(); watch.Start(); await Task.Delay(200); watch.Stop(); expected.Stop(); Assert.True((expected.Elapsed - watch.Elapsed).Duration() < TimeSpan.FromMilliseconds(100), "(expected.Elapsed - watch.Elapsed) < TimeSpan.FromMilliseconds(100)"); //after stop var afterStop = watch.Elapsed; await Task.Delay(200); Assert.Equal(afterStop, watch.Elapsed); } [Fact] public void CreateStopWatch_should_return_new_instances_of_stopwatches() { Assert.NotSame(_coordinator.CreateStopWatch(), _coordinator.CreateStopWatch()); } [Fact] public void UtcNow_should_return_proper_time() { Assert.True((DateTime.UtcNow - _coordinator.UtcNow).Duration() < TimeSpan.FromMilliseconds(100)); } [Fact] public async Task Delay_should_postpone_task_execution() { var watch = Stopwatch.StartNew(); await _coordinator.Delay(TimeSpan.FromMilliseconds(500), CancellationToken.None); watch.Stop(); Assert.True(watch.Elapsed > TimeSpan.FromMilliseconds(400), "watch.Elapsed > TimeSpan.FromMilliseconds(400)"); } [Fact] public async Task Delay_should_be_cancellable() { await Assert.ThrowsAsync<TaskCanceledException>(() => _coordinator.Delay(TimeSpan.FromSeconds(5), new CancellationTokenSource(TimeSpan.FromMilliseconds(100)).Token)); } } }
mit
C#
95f282cba4f1e420e128eae2a8b2f99ade601719
Introduce variable to make code more readable
terrajobst/nquery-vnext
NQuery.Language.ActiproWpf/ComposableLanguageServiceRegistrar.cs
NQuery.Language.ActiproWpf/ComposableLanguageServiceRegistrar.cs
using System; using System.Collections.Generic; using System.ComponentModel.Composition; using ActiproSoftware.Text.Implementation; namespace NQueryViewerActiproWpf { [Export(typeof(ILanguageServiceRegistrar))] internal sealed class ComposableLanguageServiceRegistrar : ILanguageServiceRegistrar { [ImportMany] public IEnumerable<Lazy<object, ILanguageServiceMetadata>> LanguageServices { get; set; } public void RegisterServices(SyntaxLanguage syntaxLanguage) { foreach (var languageService in LanguageServices) { var serviceType = languageService.Metadata.ServiceType; var service = languageService.Value; syntaxLanguage.RegisterService(serviceType, service); } } } }
using System; using System.Collections.Generic; using System.ComponentModel.Composition; using ActiproSoftware.Text.Implementation; namespace NQueryViewerActiproWpf { [Export(typeof(ILanguageServiceRegistrar))] internal sealed class ComposableLanguageServiceRegistrar : ILanguageServiceRegistrar { [ImportMany] public IEnumerable<Lazy<object, ILanguageServiceMetadata>> LanguageServices { get; set; } public void RegisterServices(SyntaxLanguage syntaxLanguage) { foreach (var languageService in LanguageServices) { var type = languageService.Metadata.ServiceType; syntaxLanguage.RegisterService(type, languageService.Value); } } } }
mit
C#
851a4382fd60bf29252e8c05e88f56c0622f619f
Package Update #CHANGE: Pushed AdamsLair.WinForms 1.1.7
AdamsLair/winforms
WinForms/Properties/AssemblyInfo.cs
WinForms/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Allgemeine Informationen über eine Assembly werden über die folgenden // Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern, // die mit einer Assembly verknüpft sind. [assembly: AssemblyTitle("AdamsLair.WinForms")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("AdamsLair.WinForms")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar // für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von // COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest. [assembly: ComVisible(false)] // Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird [assembly: Guid("735ee5dc-8c18-4a06-8e64-2f172ddd01cc")] // Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten: // // Hauptversion // Nebenversion // Buildnummer // Revision // // Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern // übernehmen, indem Sie "*" eingeben: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.1.7")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Allgemeine Informationen über eine Assembly werden über die folgenden // Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern, // die mit einer Assembly verknüpft sind. [assembly: AssemblyTitle("AdamsLair.WinForms")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("AdamsLair.WinForms")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar // für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von // COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest. [assembly: ComVisible(false)] // Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird [assembly: Guid("735ee5dc-8c18-4a06-8e64-2f172ddd01cc")] // Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten: // // Hauptversion // Nebenversion // Buildnummer // Revision // // Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern // übernehmen, indem Sie "*" eingeben: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.1.6")]
mit
C#
556c61c2a9303457e44a62bcb3cd71f50702a514
Format code like a civilized man
jjnguy/LRU.Net
LRU.Net/LRU.Net/LruCache.cs
LRU.Net/LRU.Net/LruCache.cs
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LRU.Net { public class LruCache<TKey, TValue> { private readonly int _maxObjects; private OrderedDictionary _data; public LruCache(int maxObjects = 1000) { _maxObjects = maxObjects; _data = new OrderedDictionary(); } public void Add(TKey key, TValue value) { if (_data.Count >= _maxObjects) { _data.RemoveAt(0); } _data.Add(key, value); } public TValue Get(TKey key) { if (!_data.Contains(key)) { throw new Exception($"Could not find item with key {key}"); } var result = _data[key]; _data.Remove(key); _data.Add(key, result); return (TValue)result; } public bool Contains(TKey key) { return _data.Contains(key); } public TValue this[TKey key] { get { return Get(key); } set { Add(key, value); } } } }
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LRU.Net { public class LruCache<TKey, TValue> { private readonly int _maxObjects; private OrderedDictionary _data; public LruCache(int maxObjects = 1000) { _maxObjects = maxObjects; _data = new OrderedDictionary(); } public void Add(TKey key, TValue value) { if (_data.Count >= _maxObjects) { _data.RemoveAt(0); } _data.Add(key, value); } public TValue Get(TKey key) { if (!_data.Contains(key)) throw new Exception(); var result = _data[key]; if (result == null) throw new Exception(); _data.Remove(key); _data.Add(key, result); return (TValue)result; } public bool Contains(TKey key) { return _data.Contains(key); } public TValue this[TKey key] { get { return Get(key); } set { Add(key, value); } } } }
mit
C#
c50c401371666df4d0e1d32220fe1661f5754d3c
Fix path building for plugins views
lionelplessis/Nubot,laurentkempe/Nubot,laurentkempe/Nubot,lionelplessis/Nubot
Nubot/Nancy/Bootstrapper.cs
Nubot/Nancy/Bootstrapper.cs
namespace Nubot.Core.Nancy { using System.Linq; using Abstractions; using global::Nancy; using global::Nancy.Conventions; using global::Nancy.TinyIoc; public class Bootstrapper : DefaultNancyBootstrapper { private readonly IRobot _robot; public Bootstrapper(IRobot robot) { _robot = robot; } /// <summary> /// Configures the container using AutoRegister followed by registration /// of default INancyModuleCatalog and IRouteResolver. /// </summary> /// <param name="container">Container instance</param> protected override void ConfigureApplicationContainer(TinyIoCContainer container) { base.ConfigureApplicationContainer(container); container.Register(_robot); } protected override void ConfigureConventions(NancyConventions nancyConventions) { base.ConfigureConventions(nancyConventions); var httpPluginsStaticPaths = _robot.RobotPlugins.OfType<HttpPluginBase>().SelectMany(httpPlugin => httpPlugin.StaticPaths); foreach (var staticPath in httpPluginsStaticPaths) { nancyConventions.StaticContentsConventions.Add(StaticContentConventionBuilder.AddDirectory(staticPath.Item1, staticPath.Item2)); } nancyConventions.ViewLocationConventions.Add((viewName, model, viewLocationContext) => string.Concat("plugins", viewLocationContext.ModulePath, "/Views/", viewName)); } } }
namespace Nubot.Core.Nancy { using System.Linq; using Abstractions; using global::Nancy; using global::Nancy.Conventions; using global::Nancy.TinyIoc; public class Bootstrapper : DefaultNancyBootstrapper { private readonly IRobot _robot; public Bootstrapper(IRobot robot) { _robot = robot; } /// <summary> /// Configures the container using AutoRegister followed by registration /// of default INancyModuleCatalog and IRouteResolver. /// </summary> /// <param name="container">Container instance</param> protected override void ConfigureApplicationContainer(TinyIoCContainer container) { base.ConfigureApplicationContainer(container); container.Register(_robot); } protected override void ConfigureConventions(NancyConventions nancyConventions) { base.ConfigureConventions(nancyConventions); foreach (var staticPath in _robot.RobotPlugins.OfType<HttpPluginBase>().SelectMany(httpPlugin => httpPlugin.StaticPaths)) { nancyConventions.StaticContentsConventions.Add(StaticContentConventionBuilder.AddDirectory(staticPath.Item1, staticPath.Item2)); } nancyConventions.ViewLocationConventions.Add((viewName, model, viewLocationContext) => string.Concat("plugins/", viewLocationContext.ModulePath, "/Views/", viewName)); } } }
mit
C#
ac99ca47a71762f9535870a2b4c42e890eb3cd20
Add HtmlHelper.Raw which renders unencoded HTML.
xamarin/PortableRazor,MilenPavlov/PortableRazor
PortableRazor/HtmlHelper.cs
PortableRazor/HtmlHelper.cs
using System; using System.IO; using System.Reflection; using System.Text; using PortableRazor.Web; namespace PortableRazor.Web.Mvc { public partial class HtmlHelper { private TextWriter _writer; public HtmlHelper(TextWriter writer) { _writer = writer; } public IHtmlString Raw(string value) { return new HtmlString (value); } private string GenerateHtmlAttributes(object htmlAttributes) { var attrs = new StringBuilder (); if (htmlAttributes != null) { foreach (var property in htmlAttributes.GetType ().GetRuntimeProperties()) attrs.AppendFormat (@" {0}=""{1}""", property.Name.Replace('_', '-'), property.GetMethod.Invoke (htmlAttributes, null)); } return attrs.ToString (); } } }
using System; using System.IO; using System.Reflection; using System.Text; using PortableRazor.Web; namespace PortableRazor.Web.Mvc { public partial class HtmlHelper { private TextWriter _writer; public HtmlHelper(TextWriter writer) { _writer = writer; } private string GenerateHtmlAttributes(object htmlAttributes) { var attrs = new StringBuilder (); if (htmlAttributes != null) { foreach (var property in htmlAttributes.GetType ().GetRuntimeProperties()) attrs.AppendFormat (@" {0}=""{1}""", property.Name.Replace('_', '-'), property.GetMethod.Invoke (htmlAttributes, null)); } return attrs.ToString (); } } }
mit
C#
8462a096238c31eb4f65c1967dd64978141c311b
Rename "me" -> "request".
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi/Tor/Http/Extensions/HttpRequestMessageExtensions.cs
WalletWasabi/Tor/Http/Extensions/HttpRequestMessageExtensions.cs
using System.Linq; using System.Net.Http; using System.Threading.Tasks; using WalletWasabi.Tor.Http.Models; using static WalletWasabi.Tor.Http.Constants; namespace WalletWasabi.Tor.Http.Extensions { public static class HttpRequestMessageExtensions { public static async Task<string> ToHttpStringAsync(this HttpRequestMessage request) { // https://tools.ietf.org/html/rfc7230#section-5.4 // The "Host" header field in a request provides the host and port // information from the target URI, enabling the origin server to // distinguish among resources while servicing requests for multiple // host names on a single IP address. // Host = uri - host[":" port] ; Section 2.7.1 // A client MUST send a Host header field in all HTTP/1.1 request messages. if (request.Method != new HttpMethod("CONNECT")) { if (!request.Headers.Contains("Host")) { // https://tools.ietf.org/html/rfc7230#section-5.4 // If the target URI includes an authority component, then a // client MUST send a field-value for Host that is identical to that // authority component, excluding any userinfo subcomponent and its "@" // delimiter(Section 2.7.1).If the authority component is missing or // undefined for the target URI, then a client MUST send a Host header // field with an empty field - value. request.Headers.TryAddWithoutValidation("Host", request.RequestUri.Authority); } } var startLine = new RequestLine(request.Method, request.RequestUri, new HttpProtocol($"HTTP/{request.Version.Major}.{request.Version.Minor}")).ToString(); string headers = ""; if (request.Headers.NotNullAndNotEmpty()) { var headerSection = HeaderSection.CreateNew(request.Headers); headers += headerSection.ToString(endWithTwoCRLF: false); } string messageBody = ""; if (request.Content is { }) { if (request.Content.Headers.NotNullAndNotEmpty()) { var headerSection = HeaderSection.CreateNew(request.Content.Headers); headers += headerSection.ToString(endWithTwoCRLF: false); } messageBody = await request.Content.ReadAsStringAsync().ConfigureAwait(false); } return startLine + headers + CRLF + messageBody; } } }
using System.Linq; using System.Net.Http; using System.Threading.Tasks; using WalletWasabi.Tor.Http.Models; using static WalletWasabi.Tor.Http.Constants; namespace WalletWasabi.Tor.Http.Extensions { public static class HttpRequestMessageExtensions { public static async Task<string> ToHttpStringAsync(this HttpRequestMessage me) { // https://tools.ietf.org/html/rfc7230#section-5.4 // The "Host" header field in a request provides the host and port // information from the target URI, enabling the origin server to // distinguish among resources while servicing requests for multiple // host names on a single IP address. // Host = uri - host[":" port] ; Section 2.7.1 // A client MUST send a Host header field in all HTTP/1.1 request messages. if (me.Method != new HttpMethod("CONNECT")) { if (!me.Headers.Contains("Host")) { // https://tools.ietf.org/html/rfc7230#section-5.4 // If the target URI includes an authority component, then a // client MUST send a field-value for Host that is identical to that // authority component, excluding any userinfo subcomponent and its "@" // delimiter(Section 2.7.1).If the authority component is missing or // undefined for the target URI, then a client MUST send a Host header // field with an empty field - value. me.Headers.TryAddWithoutValidation("Host", me.RequestUri.Authority); } } var startLine = new RequestLine(me.Method, me.RequestUri, new HttpProtocol($"HTTP/{me.Version.Major}.{me.Version.Minor}")).ToString(); string headers = ""; if (me.Headers.NotNullAndNotEmpty()) { var headerSection = HeaderSection.CreateNew(me.Headers); headers += headerSection.ToString(endWithTwoCRLF: false); } string messageBody = ""; if (me.Content is { }) { if (me.Content.Headers.NotNullAndNotEmpty()) { var headerSection = HeaderSection.CreateNew(me.Content.Headers); headers += headerSection.ToString(endWithTwoCRLF: false); } messageBody = await me.Content.ReadAsStringAsync().ConfigureAwait(false); } return startLine + headers + CRLF + messageBody; } } }
mit
C#
14c72f85fa56387b3932908c616c0de68e3aee36
Fix incorrect beatmap set info equality check on non-online set info
johnneijzen/osu,smoogipoo/osu,ppy/osu,2yangk23/osu,EVAST9919/osu,UselessToucan/osu,UselessToucan/osu,EVAST9919/osu,peppy/osu,NeoAdonis/osu,2yangk23/osu,smoogipooo/osu,smoogipoo/osu,NeoAdonis/osu,smoogipoo/osu,peppy/osu,peppy/osu-new,ppy/osu,UselessToucan/osu,peppy/osu,NeoAdonis/osu,ppy/osu,johnneijzen/osu
osu.Game/Beatmaps/BeatmapSetInfo.cs
osu.Game/Beatmaps/BeatmapSetInfo.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using osu.Game.Database; namespace osu.Game.Beatmaps { public class BeatmapSetInfo : IHasPrimaryKey, IHasFiles<BeatmapSetFileInfo>, ISoftDelete, IEquatable<BeatmapSetInfo> { public int ID { get; set; } private int? onlineBeatmapSetID; public int? OnlineBeatmapSetID { get => onlineBeatmapSetID; set => onlineBeatmapSetID = value > 0 ? value : null; } public DateTimeOffset DateAdded { get; set; } public BeatmapSetOnlineStatus Status { get; set; } = BeatmapSetOnlineStatus.None; public BeatmapMetadata Metadata { get; set; } public List<BeatmapInfo> Beatmaps { get; set; } [NotMapped] public BeatmapSetOnlineInfo OnlineInfo { get; set; } [NotMapped] public BeatmapSetMetrics Metrics { get; set; } /// <summary> /// The maximum star difficulty of all beatmaps in this set. /// </summary> public double MaxStarDifficulty => Beatmaps?.Max(b => b.StarDifficulty) ?? 0; /// <summary> /// The maximum playable length in milliseconds of all beatmaps in this set. /// </summary> public double MaxLength => Beatmaps?.Max(b => b.Length) ?? 0; /// <summary> /// The maximum BPM of all beatmaps in this set. /// </summary> public double MaxBPM => Beatmaps?.Max(b => b.BPM) ?? 0; [NotMapped] public bool DeletePending { get; set; } public string Hash { get; set; } public string StoryboardFile => Files?.Find(f => f.Filename.EndsWith(".osb"))?.Filename; public List<BeatmapSetFileInfo> Files { get; set; } public override string ToString() => Metadata?.ToString() ?? base.ToString(); public bool Protected { get; set; } public bool Equals(BeatmapSetInfo other) { if (!OnlineBeatmapSetID.HasValue || !(other?.OnlineBeatmapSetID.HasValue ?? false)) return ReferenceEquals(this, other); return OnlineBeatmapSetID == other.OnlineBeatmapSetID; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using osu.Game.Database; namespace osu.Game.Beatmaps { public class BeatmapSetInfo : IHasPrimaryKey, IHasFiles<BeatmapSetFileInfo>, ISoftDelete, IEquatable<BeatmapSetInfo> { public int ID { get; set; } private int? onlineBeatmapSetID; public int? OnlineBeatmapSetID { get => onlineBeatmapSetID; set => onlineBeatmapSetID = value > 0 ? value : null; } public DateTimeOffset DateAdded { get; set; } public BeatmapSetOnlineStatus Status { get; set; } = BeatmapSetOnlineStatus.None; public BeatmapMetadata Metadata { get; set; } public List<BeatmapInfo> Beatmaps { get; set; } [NotMapped] public BeatmapSetOnlineInfo OnlineInfo { get; set; } [NotMapped] public BeatmapSetMetrics Metrics { get; set; } /// <summary> /// The maximum star difficulty of all beatmaps in this set. /// </summary> public double MaxStarDifficulty => Beatmaps?.Max(b => b.StarDifficulty) ?? 0; /// <summary> /// The maximum playable length in milliseconds of all beatmaps in this set. /// </summary> public double MaxLength => Beatmaps?.Max(b => b.Length) ?? 0; /// <summary> /// The maximum BPM of all beatmaps in this set. /// </summary> public double MaxBPM => Beatmaps?.Max(b => b.BPM) ?? 0; [NotMapped] public bool DeletePending { get; set; } public string Hash { get; set; } public string StoryboardFile => Files?.Find(f => f.Filename.EndsWith(".osb"))?.Filename; public List<BeatmapSetFileInfo> Files { get; set; } public override string ToString() => Metadata?.ToString() ?? base.ToString(); public bool Protected { get; set; } public bool Equals(BeatmapSetInfo other) => OnlineBeatmapSetID == other?.OnlineBeatmapSetID; } }
mit
C#
304ec3d9c3b2787c36c834a733f0a676bfb40e83
Tweak the struct test
jonathanvdc/flame-llvm,jonathanvdc/flame-llvm,jonathanvdc/flame-llvm
tests/struct/struct.cs
tests/struct/struct.cs
public struct Utf8String { public Utf8String(byte* data) { this.Data = data; this.Length = (int)strlen(data); } public int Length; public byte* Data; private extern static ulong strlen(byte* str); } public static class Program { public extern static void putchar(byte c); private static void WriteLine(Utf8String str) { for (int i = 0; i < str.Length; i++) { putchar(str.Data[i]); } putchar('\n'); } private static Utf8String ToUtf8String(byte* str) { return new Utf8String(str); } public static int Main(int argc, byte* * argv) { WriteLine(ToUtf8String(argv[1])); return 0; } }
public struct Utf8String { public Utf8String(byte* data, int length) { this.Data = data; this.Length = length; } public int Length; public byte* Data; } public static class Program { public extern static ulong strlen(byte* str); public extern static void putchar(byte c); private static void WriteLine(Utf8String str) { for (int i = 0; i < str.Length; i++) { putchar(str.Data[i]); } putchar('\n'); } private static Utf8String ToUtf8String(byte* str) { return new Utf8String(str, (int)strlen(str)); } public static int Main(int argc, byte* * argv) { WriteLine(ToUtf8String(argv[1])); return 0; } }
mit
C#
01be37cd749ccc91f0323da367495de3936360cc
Print min/max time
xPaw/adventofcode-solutions,xPaw/adventofcode-solutions,xPaw/adventofcode-solutions
2021/Answers/Program.cs
2021/Answers/Program.cs
using System; using System.Diagnostics; using System.Globalization; using System.Text; using AdventOfCode2021; Console.OutputEncoding = Encoding.UTF8; CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture; var day = DateTime.Today.Day; var runs = 1; if (args.Length > 0) { if (args[0] != "today" && !int.TryParse(args[0], out day)) { Console.Error.WriteLine("Usage: [day [runs]]"); return 1; } if (args.Length > 1) { if (!int.TryParse(args[1], out runs)) { Console.Error.WriteLine("Usage: <day> [runs]"); return 1; } } } Console.Write("Day: "); Console.WriteLine(day); string part1 = string.Empty; string part2 = string.Empty; var data = await Solver.LoadData(day); var type = Solver.GetSolutionType(day); await Solver.SolveExample(day, type); Console.WriteLine(); double total = 0; double max = 0; double min = double.MaxValue; var stopWatch = new Stopwatch(); for (var i = 0; i < runs; i++) { stopWatch.Restart(); (part1, part2) = Solver.Solve(type, data); stopWatch.Stop(); var elapsed = stopWatch.Elapsed.TotalMilliseconds; total += elapsed; if (min > elapsed) { min = elapsed; } if (max < elapsed) { max = elapsed; } } stopWatch.Stop(); Console.Write("Part 1: "); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine(part1); Console.ResetColor(); Console.Write("Part 2: "); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine(part2); Console.ResetColor(); Console.WriteLine(); Console.Write("Time: "); if (runs > 1) { Console.ForegroundColor = ConsoleColor.Blue; Console.Write("{0:N6}", total / runs); Console.ResetColor(); Console.Write("ms average for "); Console.ForegroundColor = ConsoleColor.Blue; Console.Write(runs); Console.ResetColor(); Console.WriteLine(" runs"); Console.Write("Min : "); Console.ForegroundColor = ConsoleColor.Blue; Console.Write("{0:N6}", min); Console.ResetColor(); Console.WriteLine("ms"); Console.Write("Max : "); Console.ForegroundColor = ConsoleColor.Blue; Console.Write("{0:N6}", max); Console.ResetColor(); Console.WriteLine("ms"); } else { Console.ForegroundColor = ConsoleColor.Blue; Console.Write("{0:N6}", stopWatch.Elapsed.TotalMilliseconds); Console.ResetColor(); Console.WriteLine("ms"); } return 0;
using System; using System.Diagnostics; using System.Globalization; using System.Text; using AdventOfCode2021; Console.OutputEncoding = Encoding.UTF8; CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture; var day = DateTime.Today.Day; var runs = 1; if (args.Length > 0) { if (args[0] != "today" && !int.TryParse(args[0], out day)) { Console.Error.WriteLine("Usage: [day [runs]]"); return 1; } if (args.Length > 1) { if (!int.TryParse(args[1], out runs)) { Console.Error.WriteLine("Usage: <day> [runs]"); return 1; } } } Console.Write("Day: "); Console.WriteLine(day); string part1 = string.Empty; string part2 = string.Empty; var data = await Solver.LoadData(day); var type = Solver.GetSolutionType(day); await Solver.SolveExample(day, type); Console.WriteLine(); var stopWatch = new Stopwatch(); stopWatch.Start(); for (var i = 0; i < runs; i++) { (part1, part2) = Solver.Solve(type, data); } stopWatch.Stop(); Console.Write("Part 1: "); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine(part1); Console.ResetColor(); Console.Write("Part 2: "); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine(part2); Console.ResetColor(); Console.WriteLine(); Console.Write("Time : "); if (runs > 1) { Console.ForegroundColor = ConsoleColor.Blue; Console.Write("{0:N6}", stopWatch.Elapsed.TotalMilliseconds / runs); Console.ResetColor(); Console.Write("ms average for "); Console.ForegroundColor = ConsoleColor.Blue; Console.Write(runs); Console.ResetColor(); Console.WriteLine(" runs"); } else { Console.ForegroundColor = ConsoleColor.Blue; Console.Write("{0:N6}", stopWatch.Elapsed.TotalMilliseconds); Console.ResetColor(); Console.WriteLine("ms for a single run"); } return 0;
unlicense
C#
19d7ff47719b9265b549a5dfbefb035394cc8663
add using to the probe test
ClogenyTechnologies/azure-powershell,ClogenyTechnologies/azure-powershell,AzureAutomationTeam/azure-powershell,devigned/azure-powershell,AzureAutomationTeam/azure-powershell,devigned/azure-powershell,AzureAutomationTeam/azure-powershell,devigned/azure-powershell,ClogenyTechnologies/azure-powershell,AzureAutomationTeam/azure-powershell,AzureAutomationTeam/azure-powershell,ClogenyTechnologies/azure-powershell,devigned/azure-powershell,ClogenyTechnologies/azure-powershell,devigned/azure-powershell,devigned/azure-powershell,AzureAutomationTeam/azure-powershell
src/Common/Commands.Common.Tests/ProbeTests.cs
src/Common/Commands.Common.Tests/ProbeTests.cs
using Microsoft.WindowsAzure.Commands.ScenarioTest; using Microsoft.WindowsAzure.Commands.Utilities.Common; using System; using System.Linq; using System.Runtime.InteropServices; using Xunit; namespace Commands.Common.Tests { public class ProbeTests { private readonly string _pwsh; public ProbeTests() { _pwsh = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "powershell" : "pwsh"; } [Fact] [Trait(Category.AcceptanceType, Category.CheckIn)] public void FalseWhenProgramDoesNotExistTest() { Assert.False(GeneralUtilities.Probe("foo")); } [Fact] [Trait(Category.AcceptanceType, Category.CheckIn)] public void TrueWhenProgramDoesExistTest() { Assert.True(GeneralUtilities.Probe(_pwsh, " -c 'echo hello world!'")); } [Fact] [Trait(Category.AcceptanceType, Category.CheckIn)] public void FailIfStdOutDoesNotMatchTest() { Assert.False( GeneralUtilities.Probe( _pwsh, " -c 'echo foo'", criterion: (processExitInfo) => { return processExitInfo.StdOut.Any(x => x.Contains("bar")); })); } [Fact] [Trait(Category.AcceptanceType, Category.CheckIn)] public void TrueIfStdOutDoesMatchTest() { Assert.True( GeneralUtilities.Probe( _pwsh, " -c 'echo foo'", criterion: (processExitInfo) => { return processExitInfo.StdOut.Any(x => x.Contains("foo")); })); } [Fact] [Trait(Category.AcceptanceType, Category.CheckIn)] public void FailIfProcessTakesTooLongToRespondTest() { Assert.False(GeneralUtilities.Probe(_pwsh, "-c \"sleep 4\"")); } } }
using Microsoft.WindowsAzure.Commands.ScenarioTest; using Microsoft.WindowsAzure.Commands.Utilities.Common; using System; using System.Linq; using Xunit; namespace Commands.Common.Tests { public class ProbeTests { private readonly string _pwsh; public ProbeTests() { _pwsh = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "powershell" : "pwsh"; } [Fact] [Trait(Category.AcceptanceType, Category.CheckIn)] public void FalseWhenProgramDoesNotExistTest() { Assert.False(GeneralUtilities.Probe("foo")); } [Fact] [Trait(Category.AcceptanceType, Category.CheckIn)] public void TrueWhenProgramDoesExistTest() { Assert.True(GeneralUtilities.Probe(_pwsh, " -c 'echo hello world!'")); } [Fact] [Trait(Category.AcceptanceType, Category.CheckIn)] public void FailIfStdOutDoesNotMatchTest() { Assert.False( GeneralUtilities.Probe( _pwsh, " -c 'echo foo'", criterion: (processExitInfo) => { return processExitInfo.StdOut.Any(x => x.Contains("bar")); })); } [Fact] [Trait(Category.AcceptanceType, Category.CheckIn)] public void TrueIfStdOutDoesMatchTest() { Assert.True( GeneralUtilities.Probe( _pwsh, " -c 'echo foo'", criterion: (processExitInfo) => { return processExitInfo.StdOut.Any(x => x.Contains("foo")); })); } [Fact] [Trait(Category.AcceptanceType, Category.CheckIn)] public void FailIfProcessTakesTooLongToRespondTest() { Assert.False(GeneralUtilities.Probe(_pwsh, "-c \"sleep 4\"")); } } }
apache-2.0
C#
a92c27da3bb119691a2ba094cd6c79a0a2b5a264
Remove wrong parameter from FFMPEG audio example
Confruggy/Discord.Net,AntiTcb/Discord.Net,RogueException/Discord.Net
docs/guides/voice/samples/audio_ffmpeg.cs
docs/guides/voice/samples/audio_ffmpeg.cs
private async Task SendAsync(IAudioClient client, string path) { // Create FFmpeg using the previous example var ffmpeg = CreateStream(path); var output = ffmpeg.StandardOutput.BaseStream; var discord = client.CreatePCMStream(AudioApplication.Mixed); await output.CopyToAsync(discord); await discord.FlushAsync(); }
private async Task SendAsync(IAudioClient client, string path) { // Create FFmpeg using the previous example var ffmpeg = CreateStream(path); var output = ffmpeg.StandardOutput.BaseStream; var discord = client.CreatePCMStream(AudioApplication.Mixed, 1920); await output.CopyToAsync(discord); await discord.FlushAsync(); }
mit
C#
a65f12782f7dabd339b5437df43d041ef394501d
Add placeholder option with default - need to figure out how to allow manually specifying an upload service as another option
factormystic/ProSnap
Actions/UploadAction.cs
Actions/UploadAction.cs
using System.ComponentModel; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace ProSnap.ActionItems { class UploadAction : IActionItem { public enum Modes { UseSelectedDefault }; [DescriptionAttribute("Determines which upload provider should be used to upload the screenshot.")] [DefaultValueAttribute(Modes.UseSelectedDefault)] public Modes UploadMode { get; set; } #region IActionItem Members [Browsable(false)] public ActionTypes ActionType { get { return ActionTypes.Upload; } } [Browsable(false)] public IActionItem Clone() { return new UploadAction(); } #endregion public ExtendedScreenshot Invoke(ExtendedScreenshot LatestScreenshot) { Trace.WriteLine("Applying UploadAction...", string.Format("UploadAction.Invoke [{0}]", System.Threading.Thread.CurrentThread.Name)); var ActiveService = Configuration.UploadServices.FirstOrDefault(u => u.isActive); if (ActiveService == null) { Trace.WriteLine("No active upload service has been configured", string.Format("UploadAction.Invoke [{0}]", System.Threading.Thread.CurrentThread.Name)); MessageBox.Show(Program.Preview, "You must configure an upload service before uploading any screenshots.", "Upload a screenshot", MessageBoxButtons.OK, MessageBoxIcon.Information); return null; } ActiveService.UploadStarted += Program.Preview.UploadStarted; ActiveService.UploadProgress += Program.Preview.UploadProgress; ActiveService.UploadEnded += Program.Preview.UploadEnded; Task.WaitAll(ActiveService.Upload(LatestScreenshot).ContinueWith(t => { ActiveService.UploadStarted -= Program.Preview.UploadStarted; ActiveService.UploadProgress -= Program.Preview.UploadProgress; ActiveService.UploadEnded -= Program.Preview.UploadEnded; return LatestScreenshot; })); return LatestScreenshot; } } }
using System.ComponentModel; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace ProSnap.ActionItems { class UploadAction : IActionItem { #region IActionItem Members [Browsable(false)] public ActionTypes ActionType { get { return ActionTypes.Upload; } } [Browsable(false)] public IActionItem Clone() { return new UploadAction(); } #endregion public ExtendedScreenshot Invoke(ExtendedScreenshot LatestScreenshot) { Trace.WriteLine("Applying UploadAction...", string.Format("UploadAction.Invoke [{0}]", System.Threading.Thread.CurrentThread.Name)); var ActiveService = Configuration.UploadServices.FirstOrDefault(u => u.isActive); if (ActiveService == null) { Trace.WriteLine("No active upload service has been configured", string.Format("UploadAction.Invoke [{0}]", System.Threading.Thread.CurrentThread.Name)); MessageBox.Show(Program.Preview, "You must configure an upload service before uploading any screenshots.", "Upload a screenshot", MessageBoxButtons.OK, MessageBoxIcon.Information); return null; } ActiveService.UploadStarted += Program.Preview.UploadStarted; ActiveService.UploadProgress += Program.Preview.UploadProgress; ActiveService.UploadEnded += Program.Preview.UploadEnded; Task.WaitAll(ActiveService.Upload(LatestScreenshot).ContinueWith(t => { ActiveService.UploadStarted -= Program.Preview.UploadStarted; ActiveService.UploadProgress -= Program.Preview.UploadProgress; ActiveService.UploadEnded -= Program.Preview.UploadEnded; return LatestScreenshot; })); return LatestScreenshot; } } }
bsd-2-clause
C#
f5a2e0faf18776dc346738d7f85c682f55736731
Test commit
Efril/WorktimeTracker
Core/ProjectsManager.cs
Core/ProjectsManager.cs
using Core.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Core { public class ProjectsManager { private readonly Dictionary<string, Project> _projects = new Dictionary<string, Project>(StringComparer.OrdinalIgnoreCase); public Project[] Projects { get { return _projects.Values.ToArray(); } } public MethodCallResult CreateProject(string ProjectName, out Project Project) { MethodCallResult projectsLoaded = EnsureProjectsLoaded(); if (projectsLoaded) { if (_projects.ContainsKey(ProjectName)) { Project = null; return MethodCallResult.CreateFail("Project '" + ProjectName + "' already exist."); } else { Project = new Project(ProjectName); MethodCallResult addedToStorage = AddProjectToStorage(Project); if(addedToStorage) { _projects.Add(Project.Name, Project); return MethodCallResult.Success; } else { Project = null; return addedToStorage; } } } else { Project = null; return projectsLoaded; } } private MethodCallResult EnsureProjectsLoaded() { } private MethodCallResult AddProjectToStorage(Project Project) { } } }
using Core.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Core { public class ProjectsManager { private readonly Dictionary<string, Project> _projects = new Dictionary<string, Project>(StringComparer.OrdinalIgnoreCase); public Project[] Projects { get { return _projects.Values.ToArray(); } } public MethodCallResult CreateProject(string ProjectName, out Project Project) { MethodCallResult projectsLoaded = EnsureProjectsLoaded(); if (projectsLoaded) { if (_projects.ContainsKey(ProjectName)) { Project = null; return MethodCallResult.CreateFail("Project '" + ProjectName + "' already exist."); } else { Project = new Project(ProjectName); MethodCallResult addedToStorage = AddProjectToStorage(Project); if(addedToStorage) { _projects.Add(Project.Name, Project); return MethodCallResult.Success; } else { Project = null; return addedToStorage; } } } else { Project = null; return projectsLoaded; } } private MethodCallResult EnsureProjectsLoaded() { fsfsdf } private MethodCallResult AddProjectToStorage(Project Project) { } } }
mit
C#
d2696f9d97a15b92d0915ec7d2252285821e4678
Remove a CA suppression.
chtoucas/Narvalo.NET,chtoucas/Narvalo.NET
src/Narvalo.Fx/GlobalSuppressions.cs
src/Narvalo.Fx/GlobalSuppressions.cs
// Copyright (c) Narvalo.Org. All rights reserved. See LICENSE.txt in the project root for license information. using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes", Scope = "namespace", Target = "Narvalo.Fx.Linq", Justification = "[Intentionally] One class to rule them all.")]
// Copyright (c) Narvalo.Org. All rights reserved. See LICENSE.txt in the project root for license information. using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes", Scope = "namespace", Target = "Narvalo.Fx.Extensions")] [assembly: SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes", Scope = "namespace", Target = "Narvalo.Fx.Linq", Justification = "[Intentionally] One class to rule them all.")]
bsd-2-clause
C#
99e13b8ed9c124484b4410eb9b03da4f2be03997
Add better xml documentation and extract fetch method
UselessToucan/osu,NeoAdonis/osu,smoogipoo/osu,NeoAdonis/osu,smoogipoo/osu,smoogipoo/osu,UselessToucan/osu,UselessToucan/osu,ppy/osu,peppy/osu,NeoAdonis/osu,ppy/osu,peppy/osu-new,smoogipooo/osu,ppy/osu,peppy/osu,peppy/osu
osu.Game/Overlays/OverlayView.cs
osu.Game/Overlays/OverlayView.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Online.API; namespace osu.Game.Overlays { /// <summary> /// A subview containing online content, to be displayed inside a <see cref="FullscreenOverlay"/>. /// </summary> /// <remarks> /// Automatically performs a data fetch on load. /// </remarks> /// <typeparam name="T">The type of the API response.</typeparam> public abstract class OverlayView<T> : CompositeDrawable, IOnlineComponent where T : class { [Resolved] protected IAPIProvider API { get; private set; } private APIRequest<T> request; protected OverlayView() { RelativeSizeAxes = Axes.X; AutoSizeAxes = Axes.Y; } protected override void LoadComplete() { base.LoadComplete(); API.Register(this); } /// <summary> /// Create the API request for fetching data. /// </summary> protected abstract APIRequest<T> CreateRequest(); /// <summary> /// Fired when results arrive from the main API request. /// </summary> /// <param name="response"></param> protected abstract void OnSuccess(T response); /// <summary> /// Force a re-request for data from the API. /// </summary> protected void PerformFetch() { request?.Cancel(); request = CreateRequest(); request.Success += response => Schedule(() => OnSuccess(response)); API.Queue(request); } public virtual void APIStateChanged(IAPIProvider api, APIState state) { switch (state) { case APIState.Online: PerformFetch(); break; } } protected override void Dispose(bool isDisposing) { request?.Cancel(); API?.Unregister(this); base.Dispose(isDisposing); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Online.API; namespace osu.Game.Overlays { /// <summary> /// A subview containing online content, to be displayed inside a <see cref="FullscreenOverlay"/>. /// </summary> /// <typeparam name="T">Response type</typeparam> public abstract class OverlayView<T> : CompositeDrawable, IOnlineComponent where T : class { [Resolved] protected IAPIProvider API { get; private set; } protected OverlayView() { RelativeSizeAxes = Axes.X; AutoSizeAxes = Axes.Y; } protected override void LoadComplete() { base.LoadComplete(); API.Register(this); } private APIRequest<T> request; protected abstract APIRequest<T> CreateRequest(); protected abstract void OnSuccess(T response); public virtual void APIStateChanged(IAPIProvider api, APIState state) { switch (state) { case APIState.Online: request = CreateRequest(); request.Success += response => Schedule(() => OnSuccess(response)); api.Queue(request); break; } } protected override void Dispose(bool isDisposing) { request?.Cancel(); API?.Unregister(this); base.Dispose(isDisposing); } } }
mit
C#
077dcf5cd99d98be377356250c2cbdf1f8f1bbe3
Add missing documentation for `SourceChanged`
ppy/osu,peppy/osu,NeoAdonis/osu,peppy/osu-new,peppy/osu,ppy/osu,smoogipoo/osu,peppy/osu,NeoAdonis/osu,smoogipoo/osu,smoogipooo/osu,ppy/osu,NeoAdonis/osu,smoogipoo/osu
osu.Game/Skinning/ISkinSource.cs
osu.Game/Skinning/ISkinSource.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using JetBrains.Annotations; namespace osu.Game.Skinning { /// <summary> /// Provides access to skinnable elements. /// </summary> public interface ISkinSource : ISkin { /// <summary> /// Fired whenever a source change occurs, signalling that consumers should re-query as required. /// </summary> event Action SourceChanged; /// <summary> /// Find the first (if any) skin that can fulfill the lookup. /// This should be used for cases where subsequent lookups (for related components) need to occur on the same skin. /// </summary> /// <returns>The skin to be used for subsequent lookups, or <c>null</c> if none is available.</returns> [CanBeNull] ISkin FindProvider(Func<ISkin, bool> lookupFunction); /// <summary> /// Retrieve all sources available for lookup, with highest priority source first. /// </summary> IEnumerable<ISkin> AllSources { get; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using JetBrains.Annotations; namespace osu.Game.Skinning { /// <summary> /// Provides access to skinnable elements. /// </summary> public interface ISkinSource : ISkin { event Action SourceChanged; /// <summary> /// Find the first (if any) skin that can fulfill the lookup. /// This should be used for cases where subsequent lookups (for related components) need to occur on the same skin. /// </summary> /// <returns>The skin to be used for subsequent lookups, or <c>null</c> if none is available.</returns> [CanBeNull] ISkin FindProvider(Func<ISkin, bool> lookupFunction); /// <summary> /// Retrieve all sources available for lookup, with highest priority source first. /// </summary> IEnumerable<ISkin> AllSources { get; } } }
mit
C#
dd5496d99b4ba608636403886ed2ade7a9a4bb2e
Update Assembly Info
Davipb/BluwolfIcons
BluwolfIcons/Properties/AssemblyInfo.cs
BluwolfIcons/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("BluwolfIcons")] [assembly: AssemblyDescription("A .NET library for manipulating icon files.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Davipb")] [assembly: AssemblyProduct("Bluwolf Icons")] [assembly: AssemblyCopyright("MIT License")] [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("eb396d32-149a-4aa3-9720-51f1409cc68a")] // 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("BluwolfIcons")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("BluwolfIcons")] [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("eb396d32-149a-4aa3-9720-51f1409cc68a")] // 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#
160cb96363b5a2107f6bfada70f3912f837fcb18
Fix comment
yskatsumata/resharper-workshop,yskatsumata/resharper-workshop,yskatsumata/resharper-workshop
CSharp/02-Editing/10-Commenting_code.cs
CSharp/02-Editing/10-Commenting_code.cs
using System; namespace JetBrains.ReSharper.Koans.Editing { // Toggle line comment // // Ctrl+Alt+/ (VS) // Ctrl+/ (IntelliJ) // Toggle block comment // // Ctrl+Shift+/ (VS + IntelliJ) // 1. Toggle comment on single line // Place caret on line below, press Ctrl+Alt+/ using System.Collections; // 2. Toggle comment on multiple lines // Select both lines, invoke Toggle line comment // Toggle line comment to uncomment again using System.Collections; using System.Data; // 3. Toggle block comment // Inserts block comment at text caret location // Toggle removes it again using System.Collections; // 4. Comment selection with block comment // Select some text, invoke block comment // Only creates block comment, doesn't remove using System.Collections; }
using System; namespace JetBrains.ReSharper.Koans.Editing { // Toggle line comment // // Ctrl+Alt+/ (VS) // Ctrl+/ (IntelliJ) // Toggle block comment // // Ctrl+Shift+/ (VS + IntelliJ) // 1. Toggle comment on single line // Place caret on line below, select Ctrl+D using System.Collections; // 2. Toggle comment on multiple lines // Select both lines, invoke Toggle line comment // Toggle line comment to uncomment again using System.Collections; using System.Data; // 3. Toggle block comment // Inserts block comment at text caret location // Toggle removes it again using System.Collections; // 4. Comment selection with block comment // Select some text, invoke block comment // Only creates block comment, doesn't remove using System.Collections; }
apache-2.0
C#
41bccdcd1b19eb69516b2d36a1f441efe40744c7
Use assembly version from NugetCracker assembly to print headline
monoman/NugetCracker,monoman/NugetCracker
NugetCracker/Program.cs
NugetCracker/Program.cs
using System; using NugetCracker.Persistence; namespace NugetCracker { class Program { private static MetaProjectPersistence _metaProjectPersistence; static Version Version { get { return new System.Reflection.AssemblyName(System.Reflection.Assembly.GetCallingAssembly().FullName).Version; } } static void Main(string[] args) { Console.WriteLine("NugetCracker {0}\nSee https://github.com/monoman/NugetCracker\n", Version.ToString(2)); _metaProjectPersistence = new MetaProjectPersistence(args.GetMetaProjectFilePath()); Console.WriteLine("Using {0}", _metaProjectPersistence.FilePath); Console.WriteLine("Will be scanning directories:"); foreach (string dir in _metaProjectPersistence.ListOfDirectories) Console.WriteLine("-- '{0}' > '{1}'", dir, _metaProjectPersistence.ToAbsolutePath(dir)); Console.WriteLine("Done!"); } } }
using System; using NugetCracker.Persistence; namespace NugetCracker { class Program { private static MetaProjectPersistence _metaProjectPersistence; static void Main(string[] args) { Console.WriteLine("NugetCracker 0.1\nSee https://github.com/monoman/NugetCracker\n"); _metaProjectPersistence = new MetaProjectPersistence(args.GetMetaProjectFilePath()); Console.WriteLine("Using {0}", _metaProjectPersistence.FilePath); Console.WriteLine("Will be scanning directories:"); foreach (string dir in _metaProjectPersistence.ListOfDirectories) Console.WriteLine("-- '{0}' > '{1}'", dir, _metaProjectPersistence.ToAbsolutePath(dir)); } } }
apache-2.0
C#
49a1681511e0fe4915468983d9e5e7e8767ae631
Tweak UseEnyimMemcached
cnblogs/EnyimMemcachedCore,cnblogs/EnyimMemcachedCore
Enyim.Caching/EnyimMemcachedApplicationBuilderExtensions.cs
Enyim.Caching/EnyimMemcachedApplicationBuilderExtensions.cs
using Enyim.Caching; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Enyim.Caching.Configuration; using Enyim.Caching.Memcached; namespace Microsoft.AspNetCore.Builder { public static class EnyimMemcachedApplicationBuilderExtensions { public static IApplicationBuilder UseEnyimMemcached(this IApplicationBuilder app) { var logger = app.ApplicationServices.GetService<ILogger<IMemcachedClient>>(); try { var client = app.ApplicationServices.GetRequiredService<IMemcachedClient>(); } catch (Exception ex) { logger.LogError(ex, "Failed in UseEnyimMemcached"); } return app; } } }
using Enyim.Caching; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Enyim.Caching.Configuration; using Enyim.Caching.Memcached; namespace Microsoft.AspNetCore.Builder { public static class EnyimMemcachedApplicationBuilderExtensions { public static IApplicationBuilder UseEnyimMemcached(this IApplicationBuilder app) { var logger = app.ApplicationServices.GetService<ILogger<IMemcachedClient>>(); try { var client = app.ApplicationServices.GetRequiredService<IMemcachedClient>(); client.GetValueAsync<string>("UseEnyimMemcached").Wait(); Console.WriteLine("EnyimMemcached connected memcached servers."); } catch (Exception ex) { logger.LogError(ex, "Failed in UseEnyimMemcached"); } return app; } } }
apache-2.0
C#
4520e9a12d7bc18efe4a38736105cd80c077ebbf
Update OpeningFilesThroughStream.cs
maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET
Examples/CSharp/Files/Handling/OpeningFilesThroughStream.cs
Examples/CSharp/Files/Handling/OpeningFilesThroughStream.cs
using System.IO; using Aspose.Cells; using System; namespace Aspose.Cells.Examples.Files.Handling { public class OpeningFilesThroughStream { public static void Main(string[] args) { //Exstart:1 // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // Opening through Stream //Create a Stream object FileStream fstream = new FileStream(dataDir + "Book2.xls", FileMode.Open); //Creating a Workbook object, open the file from a Stream object //that contains the content of file and it should support seeking Workbook workbook2 = new Workbook(fstream); Console.WriteLine("Workbook opened using stream successfully!"); fstream.Close(); //ExEnd:1 } } }
using System.IO; using Aspose.Cells; using System; namespace Aspose.Cells.Examples.Files.Handling { public class OpeningFilesThroughStream { public static void Main(string[] args) { //Exstart:1 // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // 2. // Opening through Stream //Create a Stream object FileStream fstream = new FileStream(dataDir + "Book2.xls", FileMode.Open); //Creating a Workbook object, open the file from a Stream object //that contains the content of file and it should support seeking Workbook workbook2 = new Workbook(fstream); Console.WriteLine("Workbook opened using stream successfully!"); fstream.Close(); //ExEnd:1 } } }
mit
C#
05dd7c6bf3976895e16d92672f5b9e1ce44624c6
Allow response to be altered after retrieving it
shrayasr/pinboard.net
pinboard.net/Endpoints/PBEndpoint.cs
pinboard.net/Endpoints/PBEndpoint.cs
using System.Net.Http; using System.Threading.Tasks; using Flurl; using Newtonsoft.Json; using System; namespace pinboard.net.Endpoints { public class PBEndpoint { private string _apiToken; private HttpClient _httpClient; private const string BASEURL = "https://api.pinboard.in/v1"; public const string DATETIME_FORMAT = "yyyy-MM-ddTHH:mm:ssK"; public const string DATE_FORMAT = "yyyy-MM-dd"; protected string PostsURL { get { return BASEURL + "/posts"; } } protected string TagsURL { get { return BASEURL + "/tags"; } } protected string UsersURL { get { return BASEURL + "/user"; } } protected string NotesURL { get { return BASEURL + "/notes"; } } public PBEndpoint(string apiToken, HttpClient httpClient) { _apiToken = apiToken; _httpClient = httpClient; } protected async Task<T> MakeRequestAsync<T>(Url url) { url .SetQueryParam("auth_token", _apiToken) .SetQueryParam("format", "json"); var response = await _httpClient.GetAsync(url); var content = await response.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject<T>(content); } protected async Task<T> MakeRequestAsync<T>(Url url, Func<string, T> postProcessAction) { url .SetQueryParam("auth_token", _apiToken) .SetQueryParam("format", "json"); var response = await _httpClient.GetAsync(url); var content = await response.Content.ReadAsStringAsync(); return postProcessAction(content); } protected string GetYesNo(bool? value) { if (value.HasValue) { return value.Value ? "yes" : "no"; } else { return ""; } } } }
using System.Net.Http; using System.Threading.Tasks; using Flurl; using Newtonsoft.Json; namespace pinboard.net.Endpoints { public class PBEndpoint { private string _apiToken; private HttpClient _httpClient; private const string BASEURL = "https://api.pinboard.in/v1"; public const string DATETIME_FORMAT = "yyyy-MM-ddTHH:mm:ssK"; public const string DATE_FORMAT = "yyyy-MM-dd"; protected string PostsURL { get { return BASEURL + "/posts"; } } protected string TagsURL { get { return BASEURL + "/tags"; } } protected string UsersURL { get { return BASEURL + "/user"; } } protected string NotesURL { get { return BASEURL + "/notes"; } } public PBEndpoint(string apiToken, HttpClient httpClient) { _apiToken = apiToken; _httpClient = httpClient; } protected async Task<T> MakeRequestAsync<T>(Url url) { url .SetQueryParam("auth_token", _apiToken) .SetQueryParam("format", "json"); var response = await _httpClient.GetAsync(url); var content = await response.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject<T>(content); } protected string GetYesNo(bool? value) { if (value.HasValue) { return value.Value ? "yes" : "no"; } else { return ""; } } } }
mit
C#
ee05d5cb14b7d946a0335f9f7208b6213da6ed57
Remove no-longer-necessary play trigger on skin change
NeoAdonis/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu,ppy/osu,UselessToucan/osu,smoogipoo/osu,peppy/osu-new,ppy/osu,smoogipooo/osu,UselessToucan/osu,ppy/osu,NeoAdonis/osu,peppy/osu,peppy/osu,smoogipoo/osu,smoogipoo/osu
osu.Game/Screens/Play/PauseOverlay.cs
osu.Game/Screens/Play/PauseOverlay.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Linq; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Game.Audio; using osu.Game.Graphics; using osu.Game.Skinning; using osuTK.Graphics; namespace osu.Game.Screens.Play { public class PauseOverlay : GameplayMenuOverlay { public Action OnResume; public override bool IsPresent => base.IsPresent || pauseLoop.IsPlaying; public override string Header => "paused"; public override string Description => "you're not going to do what i think you're going to do, are ya?"; private SkinnableSound pauseLoop; protected override Action BackAction => () => InternalButtons.Children.First().Click(); private const float minimum_volume = 0.0001f; [BackgroundDependencyLoader] private void load(OsuColour colours) { AddButton("Continue", colours.Green, () => OnResume?.Invoke()); AddButton("Retry", colours.YellowDark, () => OnRetry?.Invoke()); AddButton("Quit", new Color4(170, 27, 39, 255), () => OnQuit?.Invoke()); AddInternal(pauseLoop = new SkinnableSound(new SampleInfo("pause-loop")) { Looping = true, }); // SkinnableSound only plays a sound if its aggregate volume is > 0, so the volume must be turned up before playing it pauseLoop.VolumeTo(minimum_volume); } protected override void PopIn() { base.PopIn(); pauseLoop.VolumeTo(1.0f, TRANSITION_DURATION, Easing.InQuint); pauseLoop.Play(); } protected override void PopOut() { base.PopOut(); pauseLoop.VolumeTo(minimum_volume, TRANSITION_DURATION, Easing.OutQuad).Finally(_ => pauseLoop.Stop()); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Linq; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Game.Audio; using osu.Game.Graphics; using osu.Game.Skinning; using osuTK.Graphics; namespace osu.Game.Screens.Play { public class PauseOverlay : GameplayMenuOverlay { public Action OnResume; public override bool IsPresent => base.IsPresent || pauseLoop.IsPlaying; public override string Header => "paused"; public override string Description => "you're not going to do what i think you're going to do, are ya?"; private SkinnableSound pauseLoop; protected override Action BackAction => () => InternalButtons.Children.First().Click(); private const float minimum_volume = 0.0001f; [BackgroundDependencyLoader] private void load(OsuColour colours) { AddButton("Continue", colours.Green, () => OnResume?.Invoke()); AddButton("Retry", colours.YellowDark, () => OnRetry?.Invoke()); AddButton("Quit", new Color4(170, 27, 39, 255), () => OnQuit?.Invoke()); AddInternal(pauseLoop = new SkinnableSound(new SampleInfo("pause-loop")) { Looping = true, }); // PopIn is called before updating the skin, and when a sample is updated, its "playing" value is reset // the sample must be played again pauseLoop.OnSkinChanged += () => pauseLoop.Play(); // SkinnableSound only plays a sound if its aggregate volume is > 0, so the volume must be turned up before playing it pauseLoop.VolumeTo(minimum_volume); } protected override void PopIn() { base.PopIn(); pauseLoop.VolumeTo(1.0f, TRANSITION_DURATION, Easing.InQuint); pauseLoop.Play(); } protected override void PopOut() { base.PopOut(); pauseLoop.VolumeTo(minimum_volume, TRANSITION_DURATION, Easing.OutQuad).Finally(_ => pauseLoop.Stop()); } } }
mit
C#
ee968c1e4eb6c5a3c08ad02f3a6dec9876cad297
Remove unnecessary HttpClient registration in Unity
piotrpMSFT/BuildServices,piotrpMSFT/BuildServices
MyGetConnector.Tests/TestUnityConfig.cs
MyGetConnector.Tests/TestUnityConfig.cs
using System.Net.Http; using Microsoft.Practices.Unity; using Moq; using MyGetConnector.Repositories; namespace MyGetConnector.Tests { public static class TestUnityConfig { public static IUnityContainer GetMockedContainer() { var container = new UnityContainer(); container.RegisterInstance(typeof(ITriggerRepository), new Mock<ITriggerRepository>(MockBehavior.Strict).Object); return container; } } }
using System.Net.Http; using Microsoft.Practices.Unity; using Moq; using MyGetConnector.Repositories; namespace MyGetConnector.Tests { public static class TestUnityConfig { public static IUnityContainer GetMockedContainer() { var container = new UnityContainer(); container.RegisterInstance(new HttpClient()); container.RegisterInstance(typeof(ITriggerRepository), new Mock<ITriggerRepository>(MockBehavior.Strict).Object); return container; } } }
mit
C#
39875b48d0ef9d8a860f57b7ad33402f44b76ae4
Fix already closed connection and 'kak go napravi tova' exception
Elders/Cronus.Transport.RabbitMQ,Elders/Cronus.Transport.RabbitMQ
src/Elders.Cronus.Transport.RabbitMQ/PublisherChannelResolver.cs
src/Elders.Cronus.Transport.RabbitMQ/PublisherChannelResolver.cs
using System.Collections.Generic; using RabbitMQ.Client; namespace Elders.Cronus.Transport.RabbitMQ { public class PublisherChannelResolver { private readonly Dictionary<string, IModel> channelPerBoundedContext; private readonly ConnectionResolver connectionResolver; private static readonly object @lock = new object(); public PublisherChannelResolver(ConnectionResolver connectionResolver) { channelPerBoundedContext = new Dictionary<string, IModel>(); this.connectionResolver = connectionResolver; } public IModel Resolve(string boundedContext, IRabbitMqOptions options) { IModel channel = GetExistingChannel(boundedContext); if (channel is null || channel.IsClosed) { lock (@lock) { channel = GetExistingChannel(boundedContext); if (channel?.IsClosed == true) { channelPerBoundedContext.Remove(boundedContext); } if (channel is null) { var connection = connectionResolver.Resolve(boundedContext, options); IModel scopedChannel = connection.CreateModel(); scopedChannel.ConfirmSelect(); channelPerBoundedContext.Add(boundedContext, scopedChannel); } } } return GetExistingChannel(boundedContext); } private IModel GetExistingChannel(string boundedContext) { channelPerBoundedContext.TryGetValue(boundedContext, out IModel channel); return channel; } } }
using System; using System.Collections.Concurrent; using RabbitMQ.Client; namespace Elders.Cronus.Transport.RabbitMQ { public class PublisherChannelResolver { private readonly ConcurrentDictionary<string, IModel> channelPerBoundedContext; private readonly ConnectionResolver connectionResolver; private static readonly object @lock = new object(); public PublisherChannelResolver(ConnectionResolver connectionResolver) { channelPerBoundedContext = new ConcurrentDictionary<string, IModel>(); this.connectionResolver = connectionResolver; } public IModel Resolve(string boundedContext, IRabbitMqOptions options) { IModel channel = GetExistingChannel(boundedContext); if (channel is null || channel.IsClosed) { lock (@lock) { channel = GetExistingChannel(boundedContext); if (channel is null || channel.IsClosed) { var connection = connectionResolver.Resolve(boundedContext, options); channel = connection.CreateModel(); channel.ConfirmSelect(); if (channelPerBoundedContext.TryAdd(boundedContext, channel) == false) { throw new Exception("Kak go napravi tova?"); } } } } return channel; } private IModel GetExistingChannel(string boundedContext) { channelPerBoundedContext.TryGetValue(boundedContext, out IModel channel); return channel; } } }
apache-2.0
C#
4d8336452aa50532e5c8580f725f83c917cd9e8c
Handle long values when writing version variables
GitTools/GitVersion,GitTools/GitVersion
src/GitVersion.Core/Model/VersionVariablesJsonNumberConverter.cs
src/GitVersion.Core/Model/VersionVariablesJsonNumberConverter.cs
using System.Buffers; using System.Buffers.Text; using System.Text.Json; using System.Text.Json.Serialization; using GitVersion.Extensions; namespace GitVersion.OutputVariables; public class VersionVariablesJsonNumberConverter : JsonConverter<string> { public override bool CanConvert(Type typeToConvert) => typeToConvert == typeof(string); public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.TokenType != JsonTokenType.Number && typeToConvert == typeof(string)) return reader.GetString() ?? ""; var span = reader.HasValueSequence ? reader.ValueSequence.ToArray() : reader.ValueSpan; if (Utf8Parser.TryParse(span, out long number, out var bytesConsumed) && span.Length == bytesConsumed) return number.ToString(); var data = reader.GetString(); throw new InvalidOperationException($"'{data}' is not a correct expected value!") { Source = nameof(VersionVariablesJsonNumberConverter) }; } public override void Write(Utf8JsonWriter writer, string? value, JsonSerializerOptions options) { if (value.IsNullOrWhiteSpace()) { writer.WriteNullValue(); } else if (long.TryParse(value, out var number)) { writer.WriteNumberValue(number); } else { throw new InvalidOperationException($"'{value}' is not a correct expected value!") { Source = nameof(VersionVariablesJsonStringConverter) }; } } public override bool HandleNull => true; }
using System.Buffers; using System.Buffers.Text; using System.Text.Json; using System.Text.Json.Serialization; using GitVersion.Extensions; namespace GitVersion.OutputVariables; public class VersionVariablesJsonNumberConverter : JsonConverter<string> { public override bool CanConvert(Type typeToConvert) => typeToConvert == typeof(string); public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.TokenType != JsonTokenType.Number && typeToConvert == typeof(string)) return reader.GetString() ?? ""; var span = reader.HasValueSequence ? reader.ValueSequence.ToArray() : reader.ValueSpan; if (Utf8Parser.TryParse(span, out long number, out var bytesConsumed) && span.Length == bytesConsumed) return number.ToString(); var data = reader.GetString(); throw new InvalidOperationException($"'{data}' is not a correct expected value!") { Source = nameof(VersionVariablesJsonNumberConverter) }; } public override void Write(Utf8JsonWriter writer, string? value, JsonSerializerOptions options) { if (value.IsNullOrWhiteSpace()) { writer.WriteNullValue(); } else if (int.TryParse(value, out var number)) { writer.WriteNumberValue(number); } else { throw new InvalidOperationException($"'{value}' is not a correct expected value!") { Source = nameof(VersionVariablesJsonStringConverter) }; } } public override bool HandleNull => true; }
mit
C#
68f0522ad205d47ac2723cf7b9cd482307178d17
Reduce VersionInfo to minimal complexity
jlewin/MatterControl,unlimitedbacon/MatterControl,jlewin/MatterControl,mmoening/MatterControl,MatterHackers/MatterControl,mmoening/MatterControl,rytz/MatterControl,CodeMangler/MatterControl,MatterHackers/MatterControl,jlewin/MatterControl,rytz/MatterControl,CodeMangler/MatterControl,tellingmachine/MatterControl,MatterHackers/MatterControl,tellingmachine/MatterControl,unlimitedbacon/MatterControl,CodeMangler/MatterControl,rytz/MatterControl,larsbrubaker/MatterControl,larsbrubaker/MatterControl,unlimitedbacon/MatterControl,larsbrubaker/MatterControl,larsbrubaker/MatterControl,unlimitedbacon/MatterControl,mmoening/MatterControl,jlewin/MatterControl
VersionManagement/VersionFileHandler.cs
VersionManagement/VersionFileHandler.cs
/* Copyright (c) 2014, Kevin Pope All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. */ using System; using System.IO; using MatterHackers.Agg.PlatformAbstract; using Newtonsoft.Json; namespace MatterHackers.MatterControl { public sealed class VersionInfo { public readonly static VersionInfo Instance = DeserializeFromDisk(); // Prevent external construction and limit to singleton Instance above private VersionInfo() { } public string ReleaseVersion { get; set; } public string BuildVersion { get; set; } public string BuildToken { get; set; } public string ProjectToken { get; set; } private static VersionInfo DeserializeFromDisk() { string content = StaticData.Instance.ReadAllText("BuildInfo.txt"); return JsonConvert.DeserializeObject<VersionInfo>(content); } } }
/* Copyright (c) 2014, Kevin Pope All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. */ using MatterHackers.Agg.PlatformAbstract; using System.IO; namespace MatterHackers.MatterControl { public class VersionInfo { private static VersionInfoContainer globalInstance; public static VersionInfoContainer Instance { get { if (globalInstance == null) { VersionInfoHandler versionInfoHandler = new VersionInfoHandler(); globalInstance = versionInfoHandler.ImportVersionInfoFromJson(); } return globalInstance; } } } public class VersionInfoContainer { public VersionInfoContainer() { } public string ReleaseVersion { get; set; } public string BuildVersion { get; set; } public string BuildToken { get; set; } public string ProjectToken { get; set; } } internal class VersionInfoHandler { public VersionInfoHandler() { } public VersionInfoContainer ImportVersionInfoFromJson(string loadedFileName = null) { // TODO: Review all cases below. What happens if we return a default instance of VersionInfoContainer or worse yet, null. It seems likely we end up with a null // reference error when someone attempts to use VersionInfo.Instance and it's invalide. Consider removing the error handing below and throwing an error when // an error condition is found rather than masking it until the user goes to a section that relies on the instance - thus moving detection of the problem to // an earlier stage and expanding the number of cases where it would be noticed. string content = loadedFileName == null ? StaticData.Instance.ReadAllText(Path.Combine("BuildInfo.txt")) : System.IO.File.Exists(loadedFileName) ? System.IO.File.ReadAllText(loadedFileName) : ""; if (!string.IsNullOrWhiteSpace(content)) { VersionInfoContainer versionInfo = (VersionInfoContainer)Newtonsoft.Json.JsonConvert.DeserializeObject(content, typeof(VersionInfoContainer)); if (versionInfo == null) { return new VersionInfoContainer(); } return versionInfo; } else { return null; } } } }
bsd-2-clause
C#
145b9754aacaa03a2af5eb3b74de6b8defbe50e4
Build Trigger
AccelerateX-org/WiQuiz,AccelerateX-org/WiQuiz
setup.cake
setup.cake
#load "nuget:https://www.myget.org/F/cake-contrib/api/v2?package=Cake.Recipe&prerelease&version=0.3.0-unstable0278" #addin "nuget:?package=Octopus.Client&version=4.22.1" #tool "nuget:?package=OctopusTools&version=4.22.1" #load "./Build/rps.cake" #load "./Build/targets.cake" #load "./Build/adjustments.cake" #load "./Build/package.cake" #load "./Build/deployment.cake" #load "./Build/uat.cake" Information(Figlet("RPS")); Warning("Rocket Production System"); Environment.SetVariableNames(); BuildParameters.SetParameters(context: Context, buildSystem: BuildSystem, sourceDirectoryPath: "./Sources", integrationTestScriptPath: ".", // Workaround: NULL Exception testFilePattern: "/**/*.Tests.dll", title: "WIQuest", repositoryOwner: "AccelerateX-org", repositoryName: "WiQuiz", appVeyorAccountName: "AccelerateX", shouldExecuteGitLink: false, shouldRunDupFinder: false, shouldRunInspectCode: false); BuildParameters.PrintParameters(Context); ToolSettings.SetToolSettings(context: Context, testCoverageFilter: "+[WIQuest*]* -[WIQuest*.Tests]* -[WIQuest*.UaTests]*"); RPS.Init(context: Context, buildSystem: BuildSystem, uaTestFilePattern: "/**/*.UaTests.dll", branchDeployment: new BranchDeployment() { Master = "Staging", Develop = "Dev", Feature = "Dev", Release = "QA", Hotfix = "Staging", Support = "Staging" }); Build.Run();
#load "nuget:https://www.myget.org/F/cake-contrib/api/v2?package=Cake.Recipe&prerelease&version=0.3.0-unstable0278" #addin "nuget:?package=Octopus.Client&version=4.22.1" #tool "nuget:?package=OctopusTools&version=4.22.1" #load "./Build/rps.cake" #load "./Build/targets.cake" #load "./Build/adjustments.cake" #load "./Build/package.cake" #load "./Build/deployment.cake" #load "./Build/uat.cake" Information(Figlet("RPS")); Environment.SetVariableNames(); BuildParameters.SetParameters(context: Context, buildSystem: BuildSystem, sourceDirectoryPath: "./Sources", integrationTestScriptPath: ".", // Workaround: NULL Exception testFilePattern: "/**/*.Tests.dll", title: "WIQuest", repositoryOwner: "AccelerateX-org", repositoryName: "WiQuiz", appVeyorAccountName: "AccelerateX", shouldExecuteGitLink: false, shouldRunDupFinder: false, shouldRunInspectCode: false); BuildParameters.PrintParameters(Context); ToolSettings.SetToolSettings(context: Context, testCoverageFilter: "+[WIQuest*]* -[WIQuest*.Tests]* -[WIQuest*.UaTests]*"); RPS.Init(context: Context, buildSystem: BuildSystem, uaTestFilePattern: "/**/*.UaTests.dll", branchDeployment: new BranchDeployment() { Master = "Staging", Develop = "Dev", Feature = "Dev", Release = "QA", Hotfix = "Staging", Support = "Staging" }); Build.Run();
mit
C#
82ca716cca8cd879becc13bd5351d296ef67693e
Remove ref counting from ClockBase.
wieslawsoltes/Perspex,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,SuperJMN/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,Perspex/Perspex,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,grokys/Perspex,SuperJMN/Avalonia,Perspex/Perspex,AvaloniaUI/Avalonia,jkoritzinsky/Perspex,SuperJMN/Avalonia,grokys/Perspex,SuperJMN/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex
src/Avalonia.Animation/ClockBase.cs
src/Avalonia.Animation/ClockBase.cs
using System; using System.Collections.Generic; using System.Reactive.Linq; using System.Text; using Avalonia.Reactive; namespace Avalonia.Animation { public class ClockBase : IClock { private readonly ClockObservable _observable; private TimeSpan? _previousTime; private TimeSpan _internalTime; protected ClockBase() { _observable = new ClockObservable(); } protected bool HasSubscriptions => _observable.HasSubscriptions; public PlayState PlayState { get; set; } protected void Pulse(TimeSpan systemTime) { if (!_previousTime.HasValue) { _previousTime = systemTime; _internalTime = TimeSpan.Zero; } else { if (PlayState == PlayState.Pause) { _previousTime = systemTime; return; } var delta = systemTime - _previousTime; _internalTime += delta.Value; _previousTime = systemTime; } _observable.Pulse(_internalTime); if (PlayState == PlayState.Stop) { Stop(); } } protected virtual void Stop() { } public IDisposable Subscribe(IObserver<TimeSpan> observer) { return _observable.Subscribe(observer); } private class ClockObservable : LightweightObservableBase<TimeSpan> { public bool HasSubscriptions { get; private set; } public void Pulse(TimeSpan time) => PublishNext(time); protected override void Initialize() => HasSubscriptions = true; protected override void Deinitialize() => HasSubscriptions = false; } } }
using System; using System.Collections.Generic; using System.Reactive.Linq; using System.Text; using Avalonia.Reactive; namespace Avalonia.Animation { public class ClockBase : IClock { private ClockObservable _observable; private IObservable<TimeSpan> _connectedObservable; private TimeSpan? _previousTime; private TimeSpan _internalTime; protected ClockBase() { _observable = new ClockObservable(); _connectedObservable = _observable.Publish().RefCount(); } protected bool HasSubscriptions => _observable.HasSubscriptions; public PlayState PlayState { get; set; } protected void Pulse(TimeSpan systemTime) { if (!_previousTime.HasValue) { _previousTime = systemTime; _internalTime = TimeSpan.Zero; } else { if (PlayState == PlayState.Pause) { _previousTime = systemTime; return; } var delta = systemTime - _previousTime; _internalTime += delta.Value; _previousTime = systemTime; } _observable.Pulse(_internalTime); if (PlayState == PlayState.Stop) { Stop(); } } protected virtual void Stop() { } public IDisposable Subscribe(IObserver<TimeSpan> observer) { return _connectedObservable.Subscribe(observer); } private class ClockObservable : LightweightObservableBase<TimeSpan> { public bool HasSubscriptions { get; private set; } public void Pulse(TimeSpan time) => PublishNext(time); protected override void Initialize() => HasSubscriptions = true; protected override void Deinitialize() => HasSubscriptions = false; } } }
mit
C#
628583af55a80825ab9aefe3f0b04708d7612dee
use IList instead of concrete impl in constructor
ve-interactive/ve-metrics-statsdclient-csharp
Ve.Metrics.StatsDClient/SystemMetrics/SystemMetricsExecutor.cs
Ve.Metrics.StatsDClient/SystemMetrics/SystemMetricsExecutor.cs
using System.Collections.Generic; using System.Timers; namespace Ve.Metrics.StatsDClient.SystemMetrics { public class SystemMetricsExecutor { private readonly IList<SystemMetric> _metrics; private readonly IVeStatsDClient _client; private static ITimer _timer; public int Interval { get { return _timer.Interval; } set { _timer.Interval = value; } } public SystemMetricsExecutor(IList<SystemMetric> metrics, IVeStatsDClient client) : this(metrics, client, new TimerWrapper()) { Interval = 10000; } internal SystemMetricsExecutor(IList<SystemMetric> metrics, IVeStatsDClient client, ITimer timer) { _metrics = metrics; _client = client; _timer = timer; _timer.Elapsed += Invoke; _timer.Start(); } private void Invoke(object sender, ElapsedEventArgs e) { foreach (var metric in _metrics) { metric.Execute(_client); } } } }
using System.Collections.Generic; using System.Timers; namespace Ve.Metrics.StatsDClient.SystemMetrics { public class SystemMetricsExecutor { private readonly List<SystemMetric> _metrics; private readonly IVeStatsDClient _client; private static ITimer _timer; public int Interval { get { return _timer.Interval; } set { _timer.Interval = value; } } public SystemMetricsExecutor(List<SystemMetric> metrics, IVeStatsDClient client) : this(metrics, client, new TimerWrapper()) { Interval = 10000; } internal SystemMetricsExecutor(List<SystemMetric> metrics, IVeStatsDClient client, ITimer timer) { _metrics = metrics; _client = client; _timer = timer; _timer.Elapsed += Invoke; _timer.Start(); } private void Invoke(object sender, ElapsedEventArgs e) { foreach (var metric in _metrics) { metric.Execute(_client); } } } }
mit
C#
82094fd18da1e8725d4a829d451dc0c0f8db5ee4
fix multiplayer regression introduced in 3a9a86c
ad510/plausible-deniability
Assets/Scripts/User.cs
Assets/Scripts/User.cs
// Copyright (c) 2013 Andrew Downing // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Linq; using System.Text; public class User { public SimEvtList cmdReceived; // commands received from this user to be applied in next update public long timeSync; // latest time at which commands from this user are ready to be applied public Dictionary<long, int> checksums; // checksums calculated by this user to be compared to our checksum (key is timeSync when checksum is received) public User() { cmdReceived = new SimEvtList(); timeSync = 0; checksums = new Dictionary<long, int>(); } }
// Copyright (c) 2013 Andrew Downing // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Linq; using System.Text; public class User { public SimEvtList cmdReceived; // commands received from this user to be applied in next update public long timeSync; // latest time at which commands from this user are ready to be applied public Dictionary<long, int> checksums; // checksums calculated by this user to be compared to our checksum (key is timeSync when checksum is received) public User() { cmdReceived = new SimEvtList(); timeSync = -1; checksums = new Dictionary<long, int>(); } }
mit
C#
4741c1f5323b430ea9034c0d263a415113e3731c
Format KinesisException
carbon/Amazon
src/Amazon.Kinesis/Exceptions/KinesisException.cs
src/Amazon.Kinesis/Exceptions/KinesisException.cs
using System; using System.Net; using Amazon.Scheduling; namespace Amazon.Kinesis { public sealed class KinesisException : Exception, IException { private readonly ErrorResult error; public KinesisException(ErrorResult error) : base(error.Type ?? error.Text) { this.error = error; } public string Type => error.Type; public HttpStatusCode StatusCode { get; set; } public bool IsTransient => string.Equals(error.Type, "ProvisionedThroughputExceededException", StringComparison.Ordinal) || string.Equals(error.Type, "InternalFailure", StringComparison.Ordinal); } } /* { "ErrorCode": "ProvisionedThroughputExceededException", "ErrorMessage": "Rate exceeded for shard shardId-000000000001 in stream exampleStreamName under account 111111111111." }, */
using System; using System.Net; using Amazon.Scheduling; namespace Amazon.Kinesis { public sealed class KinesisException : Exception, IException { private readonly ErrorResult error; public KinesisException(ErrorResult error) : base(error.Type ?? error.Text) { this.error = error; } public string Type => error.Type; public HttpStatusCode StatusCode { get; set; } public bool IsTransient => error.Type == "ProvisionedThroughputExceededException" || error.Type == "InternalFailure"; } } /* { "ErrorCode": "ProvisionedThroughputExceededException", "ErrorMessage": "Rate exceeded for shard shardId-000000000001 in stream exampleStreamName under account 111111111111." }, */
mit
C#
daf8f1679c047fe61805e26af2a63c27c5d1088c
Update build script
HalidCisse/ConfuserEx,engdata/ConfuserEx,HalidCisse/ConfuserEx,JPVenson/ConfuserEx,manojdjoshi/ConfuserEx,fretelweb/ConfuserEx,timnboys/ConfuserEx,modulexcite/ConfuserEx,Desolath/Confuserex,arpitpanwar/ConfuserEx,AgileJoshua/ConfuserEx,mirbegtlax/ConfuserEx,farmaair/ConfuserEx,MetSystem/ConfuserEx,apexrichard/ConfuserEx,mirbegtlax/ConfuserEx,Immortal-/ConfuserEx,yuligang1234/ConfuserEx,jbeshir/ConfuserEx,Desolath/ConfuserEx3,yeaicc/ConfuserEx,JPVenson/ConfuserEx,yuligang1234/ConfuserEx,KKKas/ConfuserEx
Build/UpdateVersion.cs
Build/UpdateVersion.cs
using System; using System.Diagnostics; using System.IO; public static class Program { public static int Main(string[] args) { if (args.Length != 1) { Console.WriteLine("invalid argument length."); return -1; } string dir = args[0]; string ver = File.ReadAllText(Path.Combine(dir, "VERSION")); string tag = null; string gitDir = Path.Combine(dir, ".git"); if (!Directory.Exists(gitDir)) { Console.WriteLine("git repository not found."); } else { try { var info = new ProcessStartInfo("git", "describe"); info.RedirectStandardOutput = true; info.UseShellExecute = false; using (Process ps = Process.Start(info)) { tag = ps.StandardOutput.ReadLine(); string[] infos = tag.Split('-'); if (infos.Length >= 3) ver = ver + "." + infos[infos.Length - 2]; else ver = infos[0].Substring(1); ps.WaitForExit(); if (ps.ExitCode != 0) { Console.WriteLine("error when executing git describe: " + ps.ExitCode); } } } catch { Console.WriteLine("error when executing git describe."); } } tag = tag ?? "v" + ver + "-custom"; string template = Path.Combine(dir, "GlobalAssemblyInfo.Template.cs"); string output = Path.Combine(dir, "GlobalAssemblyInfo.cs"); string verInfo = File.ReadAllText(template); verInfo = verInfo.Replace("{{VER}}", ver); verInfo = verInfo.Replace("{{TAG}}", tag); File.WriteAllText(output, verInfo); Console.WriteLine("Version updated."); return 0; } }
using System; using System.Diagnostics; using System.IO; public static class Program { public static int Main(string[] args) { if (args.Length != 1) { Console.WriteLine("invalid argument length."); return -1; } string dir = args[0]; string ver = File.ReadAllText(Path.Combine(dir, "VERSION")); string tag = null; string gitDir = Path.Combine(dir, ".git"); if (!Directory.Exists(gitDir)) { Console.WriteLine("git repository not found."); } else { try { var info = new ProcessStartInfo("git", "describe"); info.RedirectStandardOutput = true; info.UseShellExecute = false; using (Process ps = Process.Start(info)) { tag = ps.StandardOutput.ReadLine(); string[] infos = tag.Split('-'); if (infos.Length >= 3) ver = ver + "." + infos[infos.Length - 2]; else ver = ver + ".0"; ps.WaitForExit(); if (ps.ExitCode != 0) { Console.WriteLine("error when executing git describe: " + ps.ExitCode); } } } catch { Console.WriteLine("error when executing git describe."); } } tag = tag ?? "v" + ver + "-custom"; string template = Path.Combine(dir, "GlobalAssemblyInfo.Template.cs"); string output = Path.Combine(dir, "GlobalAssemblyInfo.cs"); string verInfo = File.ReadAllText(template); verInfo = verInfo.Replace("{{VER}}", ver); verInfo = verInfo.Replace("{{TAG}}", tag); File.WriteAllText(output, verInfo); Console.WriteLine("Version updated."); return 0; } }
mit
C#
302c80d20ccd464f6a7062aacbe53719b9254ec4
Remove "at Microsoft" (#158)
planetxamarin/planetxamarin,MabroukENG/planetxamarin,MabroukENG/planetxamarin,MabroukENG/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin
src/Firehose.Web/Authors/DanRigby.cs
src/Firehose.Web/Authors/DanRigby.cs
using System; using System.Collections.Generic; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class DanRigby : IWorkAtXamarinOrMicrosoft { public string FirstName => "Dan"; public string LastName => "Rigby"; public string ShortBioOrTagLine => "is a Xamarin Technical Solutions Professional"; public string StateOrRegion => "Raleigh, North Carolina"; public string EmailAddress => "Dan.Rigby@Xamarin.com"; public string TwitterHandle => "DanRigby"; public string GitHubHandle => "DanRigby"; public string GravatarHash => "f025f772418fbcfd3a1e15a74bf0f8a4"; public GeoPosition Position => new GeoPosition(35.7795900,-78.6381790); public Uri WebSite => new Uri("http://danrigby.com/"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://feeds.feedburner.com/DanRigby"); } } } }
using System; using System.Collections.Generic; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class DanRigby : IWorkAtXamarinOrMicrosoft { public string FirstName => "Dan"; public string LastName => "Rigby"; public string ShortBioOrTagLine => "is a Xamarin Technical Solutions Professional at Microsoft."; public string StateOrRegion => "Raleigh, North Carolina"; public string EmailAddress => "Dan.Rigby@Xamarin.com"; public string TwitterHandle => "DanRigby"; public string GitHubHandle => "DanRigby"; public string GravatarHash => "f025f772418fbcfd3a1e15a74bf0f8a4"; public GeoPosition Position => new GeoPosition(35.7795900,-78.6381790); public Uri WebSite => new Uri("http://danrigby.com/"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://feeds.feedburner.com/DanRigby"); } } } }
mit
C#
dbbf407a3db29175e7917e43f0fcb288f93ca130
Put the program example ini file in a string
rickyah/ini-parser,rickyah/ini-parser
src/IniFileParser.Example/Program.cs
src/IniFileParser.Example/Program.cs
using System; using IniParser.Model; using IniParser.Parser; namespace IniFileParser.Example { public class MainProgram { public static void Main() { var testIniFile = @"#This section provides the general configuration of the application [GeneralConfiguration] #Update rate in msecs setUpdate = 100 #Maximun errors before quit setMaxErrors = 2 #Users allowed to access the system #format: user = pass [Users] ricky = rickypass patty = pattypass "; //Create an instance of a ini file parser var parser = new IniDataParser(); // This is a special ini file where we use the '#' character for comment lines // instead of ';' so we need to change the configuration of the parser: parser.Scheme.CommentString = "#"; // Here we'll be storing the contents of the ini file we are about to read: IniData parsedData = parser.Parse(testIniFile); // Write down the contents of the ini file to the console Console.WriteLine("---- Printing contents of the INI file ----\n"); Console.WriteLine(parsedData); Console.WriteLine(); // Get concrete data from the ini file Console.WriteLine("---- Printing setMaxErrors value from GeneralConfiguration section ----"); Console.WriteLine("setMaxErrors = " + parsedData["GeneralConfiguration"]["setMaxErrors"]); Console.WriteLine(); // Modify the INI contents and save Console.WriteLine(); // Modify the loaded ini file parsedData["GeneralConfiguration"]["setMaxErrors"] = "10"; parsedData.Sections.AddSection("newSection"); parsedData.Sections.GetSectionData("newSection").Comments .Add("This is a new comment for the section"); parsedData.Sections.GetSectionData("newSection").Keys.AddKey("myNewKey", "value"); parsedData.Sections.GetSectionData("newSection").Keys.GetKeyData("myNewKey").Comments .Add("new key comment"); // Write down the contents of the modified ini file to the console Console.WriteLine("---- Printing contents of the new INI file ----"); Console.WriteLine(parsedData); Console.WriteLine(); } } }
using System; using System.IO; using IniParser.Model; using IniParser.Parser; namespace IniFileParser.Example { public class MainProgram { public static void Main() { var testIniFileName = "TestIniFile.ini"; var newTestIniFileName = "NewTestIniFile.ini"; //Create an instance of a ini file parser var parser = new IniDataParser(); if (File.Exists(newTestIniFileName)) File.Delete(newTestIniFileName); // This is a special ini file where we use the '#' character for comment lines // instead of ';' so we need to change the configuration of the parser: parser.Scheme.CommentString = "#"; // Here we'll be storing the contents of the ini file we are about to read: IniData parsedData; // Read and parse the ini file using (FileStream fs = File.Open(testIniFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { using (StreamReader sr = new StreamReader(fs, System.Text.Encoding.UTF8)) { parsedData = parser.Parse(sr.ReadToEnd()); } } // Write down the contents of the ini file to the console Console.WriteLine("---- Printing contents of the INI file ----\n"); Console.WriteLine(parsedData); Console.WriteLine(); // Get concrete data from the ini file Console.WriteLine("---- Printing setMaxErrors value from GeneralConfiguration section ----"); Console.WriteLine("setMaxErrors = " + parsedData["GeneralConfiguration"]["setMaxErrors"]); Console.WriteLine(); // Modify the INI contents and save Console.WriteLine(); // Modify the loaded ini file parsedData["GeneralConfiguration"]["setMaxErrors"] = "10"; parsedData.Sections.AddSection("newSection"); parsedData.Sections.GetSectionData("newSection").Comments .Add("This is a new comment for the section"); parsedData.Sections.GetSectionData("newSection").Keys.AddKey("myNewKey", "value"); parsedData.Sections.GetSectionData("newSection").Keys.GetKeyData("myNewKey").Comments .Add("new key comment"); // Write down the contents of the modified ini file to the console Console.WriteLine("---- Printing contents of the new INI file ----"); Console.WriteLine(parsedData); Console.WriteLine(); } } }
mit
C#
846a9b6997ef046715a04c22b72c5a13a5cd4301
Clean up local variable
Archie-Yang/PcscDotNet
src/PcscDotNet/PcscReaderStatus_1.cs
src/PcscDotNet/PcscReaderStatus_1.cs
using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Threading; namespace PcscDotNet { public sealed class PcscReaderStatus<TIScardReaderState> : PcscReaderStatus where TIScardReaderState : struct, ISCardReaderState { private readonly TIScardReaderState[] _readerStates; private unsafe static void CopyAndFree(IPcscProvider provider, ref TIScardReaderState src, PcscReaderState dest) { var state = src.EventState; src.CurrentState = state; dest.Atr = src.Atr; dest.EventNumber = (int)((long)state >> 16) & 0x0000FFFF; dest.State = state & (SCardReaderStates)0x0000FFFF; provider.FreeString(src.Reader); } public PcscReaderStatus(PcscContext context, IList<string> readerNames) : base(context, readerNames) { _readerStates = new TIScardReaderState[readerNames.Count]; } public unsafe override PcscReaderStatus WaitForChanged(int timeout = Timeout.Infinite) { if (Context.IsDisposed) throw new ObjectDisposedException(nameof(PcscContext), nameof(WaitForChanged)); var provider = Context.Pcsc.Provider; var readerStates = _readerStates; var length = readerStates.Length; GCHandle hReaderStates; try { for (var i = 0; i < length; ++i) { readerStates[i].Reader = (void*)provider.AllocateString(Items[i].ReaderName); } hReaderStates = GCHandle.Alloc(readerStates, GCHandleType.Pinned); provider.SCardGetStatusChange(Context.Handle, timeout, (void*)hReaderStates.AddrOfPinnedObject(), length).ThrowIfNotSuccess(); } finally { if (hReaderStates.IsAllocated) hReaderStates.Free(); for (var i = 0; i < length; ++i) { CopyAndFree(provider, ref readerStates[i], Items[i]); } } return this; } } }
using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Threading; namespace PcscDotNet { public sealed class PcscReaderStatus<TIScardReaderState> : PcscReaderStatus where TIScardReaderState : struct, ISCardReaderState { private readonly TIScardReaderState[] _readerStates; private unsafe static void CopyAndFree(IPcscProvider provider, ref TIScardReaderState src, PcscReaderState dest) { var state = src.EventState; src.CurrentState = state; dest.Atr = src.Atr; dest.EventNumber = (int)((long)state >> 16) & 0x0000FFFF; dest.State = state & (SCardReaderStates)0x0000FFFF; provider.FreeString(src.Reader); } public PcscReaderStatus(PcscContext context, IList<string> readerNames) : base(context, readerNames) { _readerStates = new TIScardReaderState[readerNames.Count]; } public unsafe override PcscReaderStatus WaitForChanged(int timeout = Timeout.Infinite) { if (Context.IsDisposed) throw new ObjectDisposedException(nameof(PcscContext), nameof(WaitForChanged)); var provider = Context.Pcsc.Provider; var readerStates = _readerStates; var length = readerStates.Length; GCHandle hReaderStates; try { for (var i = 0; i < length; ++i) { _readerStates[i].Reader = (void*)provider.AllocateString(Items[i].ReaderName); } hReaderStates = GCHandle.Alloc(readerStates, GCHandleType.Pinned); var pReaderStates = (void*)hReaderStates.AddrOfPinnedObject(); provider.SCardGetStatusChange(Context.Handle, timeout, pReaderStates, length).ThrowIfNotSuccess(); } finally { if (hReaderStates.IsAllocated) hReaderStates.Free(); for (var i = 0; i < length; ++i) { CopyAndFree(provider, ref _readerStates[i], Items[i]); } } return this; } } }
mit
C#
4f9d3f6b47af7124dcca687913e9d342096fabee
clean up
filipw/dotnet-script,filipw/dotnet-script
src/Dotnet.Script.Core/Internal/PreprocessorLineRewriter.cs
src/Dotnet.Script.Core/Internal/PreprocessorLineRewriter.cs
using System.Linq; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Dotnet.Script { internal class PreprocessorLineRewriter : CSharpSyntaxRewriter { public PreprocessorLineRewriter() : base(visitIntoStructuredTrivia: true) { } public override SyntaxNode VisitLoadDirectiveTrivia(LoadDirectiveTriviaSyntax node) { return HandleSkippedTrivia(base.VisitLoadDirectiveTrivia(node)); } public override SyntaxNode VisitReferenceDirectiveTrivia(ReferenceDirectiveTriviaSyntax node) { return HandleSkippedTrivia(base.VisitReferenceDirectiveTrivia(node)); } private SyntaxNode HandleSkippedTrivia(SyntaxNode node) { var skippedTrivia = node.DescendantTrivia().Where(x => x.RawKind == (int)SyntaxKind.SkippedTokensTrivia).FirstOrDefault(); if (skippedTrivia != null) { return node.ReplaceTrivia(skippedTrivia, SyntaxFactory.TriviaList(SyntaxFactory.LineFeed, skippedTrivia)); } return node; } } }
using System.Linq; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Dotnet.Script { internal class PreprocessorLineRewriter : CSharpSyntaxRewriter { public PreprocessorLineRewriter() : base(visitIntoStructuredTrivia: true) { } public override SyntaxNode VisitLoadDirectiveTrivia(LoadDirectiveTriviaSyntax node) { var currentNode = base.VisitLoadDirectiveTrivia(node); var skippedTrivia = currentNode.DescendantTrivia().Where(x => x.RawKind == (int)SyntaxKind.SkippedTokensTrivia).FirstOrDefault(); return currentNode.ReplaceTrivia(skippedTrivia, SyntaxFactory.TriviaList(SyntaxFactory.LineFeed, skippedTrivia)); } public override SyntaxNode VisitReferenceDirectiveTrivia(ReferenceDirectiveTriviaSyntax node) { var currentNode = base.VisitReferenceDirectiveTrivia(node); var skippedTrivia = currentNode.DescendantTrivia().Where(x => x.RawKind == (int)SyntaxKind.SkippedTokensTrivia).FirstOrDefault(); return currentNode.ReplaceTrivia(skippedTrivia, SyntaxFactory.TriviaList(SyntaxFactory.LineFeed, skippedTrivia)); } } }
mit
C#
0930afa8b75a761ee9410169a93218d005cf5ae3
Optimize by using string format
stsrki/fluentmigrator,jogibear9988/fluentmigrator,wolfascu/fluentmigrator,spaccabit/fluentmigrator,mstancombe/fluentmigrator,istaheev/fluentmigrator,tommarien/fluentmigrator,itn3000/fluentmigrator,FabioNascimento/fluentmigrator,lcharlebois/fluentmigrator,jogibear9988/fluentmigrator,alphamc/fluentmigrator,MetSystem/fluentmigrator,alphamc/fluentmigrator,IRlyDontKnow/fluentmigrator,amroel/fluentmigrator,barser/fluentmigrator,spaccabit/fluentmigrator,tommarien/fluentmigrator,fluentmigrator/fluentmigrator,itn3000/fluentmigrator,dealproc/fluentmigrator,lcharlebois/fluentmigrator,KaraokeStu/fluentmigrator,eloekset/fluentmigrator,bluefalcon/fluentmigrator,akema-fr/fluentmigrator,igitur/fluentmigrator,MetSystem/fluentmigrator,modulexcite/fluentmigrator,vgrigoriu/fluentmigrator,amroel/fluentmigrator,eloekset/fluentmigrator,drmohundro/fluentmigrator,wolfascu/fluentmigrator,dealproc/fluentmigrator,fluentmigrator/fluentmigrator,drmohundro/fluentmigrator,stsrki/fluentmigrator,IRlyDontKnow/fluentmigrator,vgrigoriu/fluentmigrator,bluefalcon/fluentmigrator,FabioNascimento/fluentmigrator,schambers/fluentmigrator,barser/fluentmigrator,KaraokeStu/fluentmigrator,igitur/fluentmigrator,istaheev/fluentmigrator,akema-fr/fluentmigrator,modulexcite/fluentmigrator,istaheev/fluentmigrator,mstancombe/fluentmigrator,schambers/fluentmigrator
src/FluentMigrator.Runner/Generators/Oracle/OracleQuoter.cs
src/FluentMigrator.Runner/Generators/Oracle/OracleQuoter.cs
using System; using FluentMigrator.Runner.Generators.Generic; namespace FluentMigrator.Runner.Generators.Oracle { public class OracleQuoter : GenericQuoter { public override string FormatDateTime(DateTime value) { var result = string.Format("to_date({0}{1}{0}, {0}yyyy-mm-dd hh24:mi:ss{0})", ValueQuote, value.ToString("yyyy-MM-dd HH:mm:ss")); //ISO 8601 DATETIME FORMAT (EXCEPT 'T' CHAR) return result; } public override string QuoteColumnName(string columnName) { return columnName; } public override string QuoteConstraintName(string constraintName) { return constraintName; } public override string QuoteIndexName(string indexName) { return indexName; } public override string QuoteSchemaName(string schemaName) { return schemaName; } public override string QuoteTableName(string tableName) { return tableName; } public override string QuoteSequenceName(string sequenceName) { return sequenceName; } public override string FromTimeSpan(TimeSpan value) { return String.Format("{0}{1} {2}:{3}:{4}.{5}{0}" , ValueQuote , value.Days , value.Hours , value.Minutes , value.Seconds , value.Milliseconds); } public override string FormatGuid(Guid value) { return string.Format("{0}{1}{0}", ValueQuote, BitConverter.ToString(value.ToByteArray()).Replace("-", string.Empty)); } } }
using System; using FluentMigrator.Runner.Generators.Generic; namespace FluentMigrator.Runner.Generators.Oracle { public class OracleQuoter : GenericQuoter { public override string FormatDateTime(DateTime value) { var result = string.Format("to_date({0}{1}{0}, {0}yyyy-mm-dd hh24:mi:ss{0})", ValueQuote, value.ToString("yyyy-MM-dd HH:mm:ss")); //ISO 8601 DATETIME FORMAT (EXCEPT 'T' CHAR) return result; } public override string QuoteColumnName(string columnName) { return columnName; } public override string QuoteConstraintName(string constraintName) { return constraintName; } public override string QuoteIndexName(string indexName) { return indexName; } public override string QuoteSchemaName(string schemaName) { return schemaName; } public override string QuoteTableName(string tableName) { return tableName; } public override string QuoteSequenceName(string sequenceName) { return sequenceName; } public override string FromTimeSpan(TimeSpan value) { return String.Format("{0}{1} {2}:{3}:{4}.{5}{0}" , ValueQuote , value.Days , value.Hours , value.Minutes , value.Seconds , value.Milliseconds); } public override string FormatGuid(Guid value) { return ValueQuote + BitConverter.ToString(value.ToByteArray()).Replace("-", string.Empty) + ValueQuote; } } }
apache-2.0
C#
6b8133d6410cb633659e8da842f54366b8dff94e
Update secureHttpClient to use MI when client secret not present
SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice
src/SFA.DAS.EmployerAccounts.Api.Client/SecureHttpClient.cs
src/SFA.DAS.EmployerAccounts.Api.Client/SecureHttpClient.cs
using System.Net.Http; using System.Net.Http.Headers; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Services.AppAuthentication; using Microsoft.IdentityModel.Clients.ActiveDirectory; namespace SFA.DAS.EmployerAccounts.Api.Client { internal class SecureHttpClient : ISecureHttpClient { private readonly IEmployerAccountsApiClientConfiguration _configuration; public SecureHttpClient(IEmployerAccountsApiClientConfiguration configuration) { _configuration = configuration; } protected SecureHttpClient() { // so we can mock for testing } public virtual async Task<string> GetAsync(string url, CancellationToken cancellationToken = default) { var accessToken = IsClientCredentialConfiguration(_configuration.ClientId, _configuration.ClientSecret, _configuration.Tenant) ? await GetClientCredentialAuthenticationResult(_configuration.ClientId, _configuration.ClientSecret, _configuration.IdentifierUri, _configuration.Tenant) : await GetManagedIdentityAuthenticationResult(_configuration.IdentifierUri); using (var client = new HttpClient()) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); var response = await client.GetAsync(url); response.EnsureSuccessStatusCode(); return await response.Content.ReadAsStringAsync(); } } private async Task<string> GetClientCredentialAuthenticationResult(string clientId, string clientSecret, string resource, string tenant) { var authority = $"https://login.microsoftonline.com/{tenant}"; var clientCredential = new ClientCredential(clientId, clientSecret); var context = new AuthenticationContext(authority, true); var result = await context.AcquireTokenAsync(resource, clientCredential); return result.AccessToken; } private async Task<string> GetManagedIdentityAuthenticationResult(string resource) { var azureServiceTokenProvider = new AzureServiceTokenProvider(); return await azureServiceTokenProvider.GetAccessTokenAsync(resource); } private bool IsClientCredentialConfiguration(string clientId, string clientSecret, string tenant) { return !string.IsNullOrEmpty(clientId) && !string.IsNullOrEmpty(clientSecret) && !string.IsNullOrEmpty(tenant); } } }
using System; using System.Net.Http; using System.Net.Http.Headers; using System.Threading; using System.Threading.Tasks; using Microsoft.IdentityModel.Clients.ActiveDirectory; namespace SFA.DAS.EmployerAccounts.Api.Client { internal class SecureHttpClient : ISecureHttpClient { private readonly IEmployerAccountsApiClientConfiguration _configuration; public SecureHttpClient(IEmployerAccountsApiClientConfiguration configuration) { _configuration = configuration; } public async Task<string> GetAsync(string url, CancellationToken cancellationToken = new CancellationToken()) { var baseAddress = new Uri(_configuration.ApiBaseUrl); var authenticationResult = await GetAuthenticationResult( _configuration.ClientId, _configuration.ClientSecret, _configuration.IdentifierUri, _configuration.Tenant).ConfigureAwait(false); using (var client = new HttpClient { BaseAddress = baseAddress }) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authenticationResult.AccessToken); var response = await client.GetAsync(url, cancellationToken).ConfigureAwait(false); response.EnsureSuccessStatusCode(); return await response.Content.ReadAsStringAsync().ConfigureAwait(false); } } private async Task<AuthenticationResult> GetAuthenticationResult(string clientId, string appKey, string resourceId, string tenant) { var authority = $"https://login.microsoftonline.com/{tenant}"; var clientCredential = new ClientCredential(clientId, appKey); var context = new AuthenticationContext(authority, true); var result = await context.AcquireTokenAsync(resourceId, clientCredential).ConfigureAwait(false); return result; } } }
mit
C#
8d366e327005984d362aea5e7e82b3b2d6713275
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.5.*")]
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.4.*")]
mit
C#
a10c8a08cee73d18f2107d7c0db8cbc5c6241412
Fix HexUtils.ToString
0xd4d/iced,0xd4d/iced,0xd4d/iced,0xd4d/iced,0xd4d/iced
Iced/Intel/HexUtils.cs
Iced/Intel/HexUtils.cs
/* Copyright (C) 2018 de4dot@gmail.com This file is part of Iced. Iced is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Iced is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with Iced. If not, see <https://www.gnu.org/licenses/>. */ #if (!NO_DECODER32 || !NO_DECODER64) && !NO_DECODER using System; using System.Text; namespace Iced.Intel { static class HexUtils { public static byte[] ToByteArray(string hexData) { if (hexData == null) throw new ArgumentNullException(nameof(hexData)); if (hexData.Length == 0) return Array.Empty<byte>(); var data = new byte[hexData.Length / 2]; int w = 0; for (int i = 0; ;) { while (i < hexData.Length && char.IsWhiteSpace(hexData[i])) i++; if (i >= hexData.Length) break; int hi = TryParseHexChar(hexData[i++]); if (hi < 0) throw new ArgumentOutOfRangeException(nameof(hexData)); while (i < hexData.Length && char.IsWhiteSpace(hexData[i])) i++; if (i >= hexData.Length) throw new ArgumentOutOfRangeException(nameof(hexData)); int lo = TryParseHexChar(hexData[i++]); if (lo < 0) throw new ArgumentOutOfRangeException(nameof(hexData)); data[w++] = (byte)((hi << 4) | lo); } if (w != data.Length) Array.Resize(ref data, w); return data; } public static string ToString(byte[] hexData) { if (hexData == null) throw new ArgumentNullException(nameof(hexData)); if (hexData.Length == 0) return string.Empty; var builder = new StringBuilder(hexData.Length * 3 - 1); for(int i = 0; i < hexData.Length; i++) { builder.Append(hexData[i].ToString("X2")); if (i + 1 < hexData.Length) builder.Append(' '); } return builder.ToString(); } static int TryParseHexChar(char c) { if ('0' <= c && c <= '9') return c - '0'; if ('a' <= c && c <= 'f') return c - 'a' + 10; if ('A' <= c && c <= 'F') return c - 'A' + 10; return -1; } } } #endif
/* Copyright (C) 2018 de4dot@gmail.com This file is part of Iced. Iced is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Iced is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with Iced. If not, see <https://www.gnu.org/licenses/>. */ #if (!NO_DECODER32 || !NO_DECODER64) && !NO_DECODER using System; using System.Text; namespace Iced.Intel { static class HexUtils { public static byte[] ToByteArray(string hexData) { if (hexData == null) throw new ArgumentNullException(nameof(hexData)); if (hexData.Length == 0) return Array.Empty<byte>(); var data = new byte[hexData.Length / 2]; int w = 0; for (int i = 0; ;) { while (i < hexData.Length && char.IsWhiteSpace(hexData[i])) i++; if (i >= hexData.Length) break; int hi = TryParseHexChar(hexData[i++]); if (hi < 0) throw new ArgumentOutOfRangeException(nameof(hexData)); while (i < hexData.Length && char.IsWhiteSpace(hexData[i])) i++; if (i >= hexData.Length) throw new ArgumentOutOfRangeException(nameof(hexData)); int lo = TryParseHexChar(hexData[i++]); if (lo < 0) throw new ArgumentOutOfRangeException(nameof(hexData)); data[w++] = (byte)((hi << 4) | lo); } if (w != data.Length) Array.Resize(ref data, w); return data; } public static string ToString(byte[] hexData) { if (hexData == null) throw new ArgumentNullException(nameof(hexData)); if (hexData.Length == 0) return string.Empty; var builder = new StringBuilder(hexData.Length * 3 - 1); for(int i = 0; i < hexData.Length; i++) { builder.Append(hexData[i].ToString("2X")); if (i + 1 < hexData.Length) builder.Append(' '); } return builder.ToString(); } static int TryParseHexChar(char c) { if ('0' <= c && c <= '9') return c - '0'; if ('a' <= c && c <= 'f') return c - 'a' + 10; if ('A' <= c && c <= 'F') return c - 'A' + 10; return -1; } } } #endif
mit
C#
a9e3742c42745927cbb20c178ed3ad38b06f399e
Allow TestCategory at the class level. This was not allowed in MsTest, but it is very handy.
sebastianburckhardt/orleans,ticup/orleans,shlomiw/orleans,dotnet/orleans,ibondy/orleans,shayhatsor/orleans,amccool/orleans,MikeHardman/orleans,brhinescot/orleans,ReubenBond/orleans,gigya/orleans,dVakulen/orleans,jkonecki/orleans,ElanHasson/orleans,veikkoeeva/orleans,yevhen/orleans,jdom/orleans,Carlm-MS/orleans,ashkan-saeedi-mazdeh/orleans,amccool/orleans,gigya/orleans,Liversage/orleans,waynemunro/orleans,LoveElectronics/orleans,MikeHardman/orleans,jason-bragg/orleans,sebastianburckhardt/orleans,SoftWar1923/orleans,yevhen/orleans,brhinescot/orleans,tsibelman/orleans,hoopsomuah/orleans,Liversage/orleans,ashkan-saeedi-mazdeh/orleans,ElanHasson/orleans,pherbel/orleans,centur/orleans,xclayl/orleans,SoftWar1923/orleans,jokin/orleans,centur/orleans,jokin/orleans,Joshua-Ferguson/orleans,Carlm-MS/orleans,gabikliot/orleans,jthelin/orleans,jokin/orleans,galvesribeiro/orleans,jkonecki/orleans,Liversage/orleans,kylemc/orleans,shayhatsor/orleans,gabikliot/orleans,benjaminpetit/orleans,dVakulen/orleans,ibondy/orleans,bstauff/orleans,brhinescot/orleans,dotnet/orleans,hoopsomuah/orleans,dVakulen/orleans,bstauff/orleans,galvesribeiro/orleans,rrector/orleans,LoveElectronics/orleans,Joshua-Ferguson/orleans,tsibelman/orleans,xclayl/orleans,sergeybykov/orleans,shlomiw/orleans,rrector/orleans,sergeybykov/orleans,waynemunro/orleans,amccool/orleans,kylemc/orleans,ashkan-saeedi-mazdeh/orleans,jdom/orleans,ticup/orleans,pherbel/orleans
test/TestExtensions/TestCategory.cs
test/TestExtensions/TestCategory.cs
using System; using System.Collections.Generic; using System.Linq; using Xunit.Abstractions; using Xunit.Sdk; /// <summary> /// This is a replacement for the MSTest [TestCategoryAttribute] on xunit /// xunit does not have the concept of Category for tests and instead, the have [TraitAttribute(string key, string value)] /// If we replace the MSTest [TestCategoryAttribute] for the [Trait("Category", "BVT")], we will surely fall at some time in cases /// where people will typo on the "Category" key part of the Trait. /// On order to achieve the same behaviour as on MSTest, a custom [TestCategory] was created /// to mimic the MSTest one and avoid replace it on every exitent test. /// The tests can be filtered by xunit runners by usage of "-trait" on the command line with the expresion like /// <code>-trait "Category=BVT"</code> for example that will only run the tests with [TestCategory("BVT")] on it. /// More on Trait extensibility <see cref="https://github.com/xunit/samples.xunit/tree/master/TraitExtensibility"/> /// </summary> [TraitDiscoverer("CategoryDiscoverer", "TestExtensions")] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)] public class TestCategoryAttribute : Attribute, ITraitAttribute { public TestCategoryAttribute(string category) { } } public class CategoryDiscoverer : ITraitDiscoverer { public IEnumerable<KeyValuePair<string, string>> GetTraits(IAttributeInfo traitAttribute) { var ctorArgs = traitAttribute.GetConstructorArguments().ToList(); yield return new KeyValuePair<string, string>("Category", ctorArgs[0].ToString()); } }
using System; using System.Collections.Generic; using System.Linq; using Xunit.Abstractions; using Xunit.Sdk; /// <summary> /// This is a replacement for the MSTest [TestCategoryAttribute] on xunit /// xunit does not have the concept of Category for tests and instead, the have [TraitAttribute(string key, string value)] /// If we replace the MSTest [TestCategoryAttribute] for the [Trait("Category", "BVT")], we will surely fall at some time in cases /// where people will typo on the "Category" key part of the Trait. /// On order to achieve the same behaviour as on MSTest, a custom [TestCategory] was created /// to mimic the MSTest one and avoid replace it on every exitent test. /// The tests can be filtered by xunit runners by usage of "-trait" on the command line with the expresion like /// <code>-trait "Category=BVT"</code> for example that will only run the tests with [TestCategory("BVT")] on it. /// More on Trait extensibility <see cref="https://github.com/xunit/samples.xunit/tree/master/TraitExtensibility"/> /// </summary> [TraitDiscoverer("CategoryDiscoverer", "TestExtensions")] [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] public class TestCategoryAttribute : Attribute, ITraitAttribute { public TestCategoryAttribute(string category) { } } public class CategoryDiscoverer : ITraitDiscoverer { public IEnumerable<KeyValuePair<string, string>> GetTraits(IAttributeInfo traitAttribute) { var ctorArgs = traitAttribute.GetConstructorArguments().ToList(); yield return new KeyValuePair<string, string>("Category", ctorArgs[0].ToString()); } }
mit
C#
294307ea9c9752b2988f799f934ee6dfeb928d00
Bump version to 1.2
miratechcorp/CsProjArrange
Projects/CsProjArrange/CsProjArrange/Properties/AssemblyInfo.cs
Projects/CsProjArrange/CsProjArrange/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("CsProjArrange")] [assembly: AssemblyDescription("Arrange .csproj files")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("MIRATECH")] [assembly: AssemblyProduct("CsProjArrange")] [assembly: AssemblyCopyright("Copyright © MIRATECH 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("5baf2fd1-f411-40bf-a558-a8aea5cfe670")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.2.0.0")] [assembly: AssemblyFileVersion("1.2.0.0")]
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("CsProjArrange")] [assembly: AssemblyDescription("Arrange .csproj files")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("MIRATECH")] [assembly: AssemblyProduct("CsProjArrange")] [assembly: AssemblyCopyright("Copyright © MIRATECH 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("5baf2fd1-f411-40bf-a558-a8aea5cfe670")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.1.0.0")] [assembly: AssemblyFileVersion("1.1.0.0")]
apache-2.0
C#
9fcdc72802ce8feb267c7fbd596bcf7d3c48145d
Update assembly version
Iluvatar82/helix-toolkit,holance/helix-toolkit,JeremyAnsel/helix-toolkit,chrkon/helix-toolkit,helix-toolkit/helix-toolkit
Source/AssemblyInfo.cs
Source/AssemblyInfo.cs
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="GlobalAssemblyInfo.cs" company="Helix Toolkit"> // Copyright (c) 2014 Helix Toolkit contributors // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System.Reflection; [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Helix Toolkit")] [assembly: AssemblyCompany("Helix Toolkit")] [assembly: AssemblyCopyright("Copyright (C) Helix Toolkit 2010-2017.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("2017.10.9.1")] [assembly: AssemblyFileVersion("2017.10.9.1")]
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="GlobalAssemblyInfo.cs" company="Helix Toolkit"> // Copyright (c) 2014 Helix Toolkit contributors // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System.Reflection; [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Helix Toolkit")] [assembly: AssemblyCompany("Helix Toolkit")] [assembly: AssemblyCopyright("Copyright (C) Helix Toolkit 2010-2014.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("2014.2.1.1")] [assembly: AssemblyFileVersion("2014.2.1.1")]
mit
C#
17a31cda7d1120d8f83a3a4dbc30240a060ff45d
Fix ThrowIf.Argument.IsInvalidArrayRange
copygirl/EntitySystem
src/Utility/ThrowIf.cs
src/Utility/ThrowIf.cs
using System; namespace EntitySystem.Utility { public static class ThrowIf { public static class Argument { public static T IsNull<T>(T param, string paramName) { if (param == null) throw new ArgumentNullException(paramName); return param; } public static void OutOfRange<T>(T value, T min, T max, string paramName, bool minInclusive = true, bool maxInclusive = true) where T : IComparable<T> { ThrowIf.Argument.IsNull(value, paramName); if ((value.CompareTo(min) < (minInclusive ? 0 : 1)) || (value.CompareTo(max) > (maxInclusive ? 0 : -1))) throw new ArgumentOutOfRangeException(paramName, value, $"{ paramName } ({ value }) is out of range ({ min } - { max })"); } public static void IsInvalidArrayIndex(Array array, int index, string arrayParamName = "array", string indexParamName = "index") { ThrowIf.Argument.IsNull(array, arrayParamName); if (array.Rank > 1) throw new RankException( $"{ arrayParamName } is a multi-dimensional array"); if (index < array.GetLowerBound(0)) throw new ArgumentOutOfRangeException(indexParamName, index, $"{ indexParamName } ({ index }) is before the beginning of { arrayParamName }"); if (index > array.GetUpperBound(0)) throw new ArgumentOutOfRangeException(indexParamName, index, $"{ indexParamName } ({ index }) after the end of { arrayParamName } ({ array.GetUpperBound(0) })"); } public static void IsInvalidArrayRange(Array array, int index, int length, string arrayParamName = "array", string indexParamName = "index", string lengthParamName = "length") { ThrowIf.Argument.IsNull(array, arrayParamName); if (array.Rank > 1) throw new RankException( $"{ arrayParamName } is a multi-dimensional array"); if (index < array.GetLowerBound(0)) throw new ArgumentOutOfRangeException(indexParamName, index, $"{ indexParamName } ({ index }) is before the beginning of { arrayParamName }"); if (length < 0) throw new ArgumentOutOfRangeException(lengthParamName, length, $"{ lengthParamName } ({ length }) is negative"); if (index + length - 1 > array.GetUpperBound(0)) throw new ArgumentException( $"{ indexParamName } + { lengthParamName } - 1 ({ index } + { length } - 1) is after the end of { arrayParamName } ({ array.GetUpperBound(0) })"); } } public static class Params { public static T[] IsEmpty<T>(T[] array, string paramName) { ThrowIf.Argument.IsNull(array, paramName); if (array.Length == 0) throw new ArgumentException( $"{ paramName } is empty, at least one { nameof(T) } is required", paramName); return array; } } } }
using System; namespace EntitySystem.Utility { public static class ThrowIf { public static class Argument { public static T IsNull<T>(T param, string paramName) { if (param == null) throw new ArgumentNullException(paramName); return param; } public static void OutOfRange<T>(T value, T min, T max, string paramName, bool minInclusive = true, bool maxInclusive = true) where T : IComparable<T> { ThrowIf.Argument.IsNull(value, paramName); if ((value.CompareTo(min) < (minInclusive ? 0 : 1)) || (value.CompareTo(max) > (maxInclusive ? 0 : -1))) throw new ArgumentOutOfRangeException(paramName, value, $"{ paramName } ({ value }) is out of range ({ min } - { max })"); } public static void IsInvalidArrayIndex(Array array, int index, string arrayParamName = "array", string indexParamName = "index") { ThrowIf.Argument.IsNull(array, arrayParamName); if (array.Rank > 1) throw new RankException( $"{ arrayParamName } is a multi-dimensional array"); if (index < array.GetLowerBound(0)) throw new ArgumentOutOfRangeException(indexParamName, index, $"{ indexParamName } ({ index }) is before the beginning of { arrayParamName }"); if (index > array.GetUpperBound(0)) throw new ArgumentOutOfRangeException(indexParamName, index, $"{ indexParamName } ({ index }) after the end of { arrayParamName } ({ array.GetUpperBound(0) })"); } public static void IsInvalidArrayRange(Array array, int index, int length, string arrayParamName = "array", string indexParamName = "index", string lengthParamName = "length") { ThrowIf.Argument.IsNull(array, arrayParamName); if (array.Rank > 1) throw new RankException( $"{ arrayParamName } is a multi-dimensional array"); if (index < array.GetLowerBound(0)) throw new ArgumentOutOfRangeException(indexParamName, index, $"{ indexParamName } ({ index }) is before the beginning of { arrayParamName }"); if (length < 0) throw new ArgumentOutOfRangeException(lengthParamName, length, $"{ lengthParamName } ({ length }) is negative"); if (index + length > array.GetUpperBound(0)) throw new ArgumentException( $"{ indexParamName } + { lengthParamName } ({ index } + { length }) is after the end of { arrayParamName } ({ array.GetUpperBound(0) })"); } } public static class Params { public static T[] IsEmpty<T>(T[] array, string paramName) { ThrowIf.Argument.IsNull(array, paramName); if (array.Length == 0) throw new ArgumentException( $"{ paramName } is empty, at least one { nameof(T) } is required", paramName); return array; } } } }
mit
C#
90a64abd403c10424a4f170f0080a9ebc14333db
Fix tests that don't work on the build server (apparently .pdf and .docx file extentions are not recognised by Windows out of the box)
jcvandan/XeroAPI.Net,XeroAPI/XeroAPI.Net,MatthewSteeples/XeroAPI.Net,TDaphneB/XeroAPI.Net
source/XeroApi.Tests/MimeTypesTests.cs
source/XeroApi.Tests/MimeTypesTests.cs
using System.IO; using NUnit.Framework; namespace XeroApi.Tests { public class MimeTypesTests { [Test] public void it_can_return_the_mime_type_for_a_filename() { string mimeType = MimeTypes.GetMimeType("anyFilename.png"); Assert.AreEqual("image/png", mimeType); } [Test] public void it_can_return_the_mime_type_for_a_filepath() { string mimeType = MimeTypes.GetMimeType(@"c:\any\dir\anyFilename.jpeg"); Assert.AreEqual("image/jpeg", mimeType); } [Test] public void it_can_return_the_mime_type_for_a_fileinfo() { var mimeType = MimeTypes.GetMimeType(new FileInfo("anyFilename.txt")); Assert.AreEqual("text/plain", mimeType); } } }
using System.IO; using NUnit.Framework; namespace XeroApi.Tests { public class MimeTypesTests { [Test] public void it_can_return_the_mime_type_for_a_filename() { string mimeType = MimeTypes.GetMimeType("anyFilename.pdf"); Assert.AreEqual("application/pdf", mimeType); } [Test] public void it_can_return_the_mime_type_for_a_filepath() { string mimeType = MimeTypes.GetMimeType(@"c:\any\dir\anyFilename.jpeg"); Assert.AreEqual("image/jpeg", mimeType); } [Test] public void it_can_return_the_mime_type_for_a_fileinfo() { var mimeType = MimeTypes.GetMimeType(new FileInfo("anyFilename.docx")); Assert.AreEqual("application/vnd.openxmlformats-officedocument.wordprocessingml.document", mimeType); } } }
mit
C#
463c959da36aed1a30000eb51d388320d2dfaf91
add IsNumbersOnly string helper
martinlindhe/Punku
punku/Extensions/StringExtensions.cs
punku/Extensions/StringExtensions.cs
using System; using System.Text; using Punku; public static class StringExtensions { public static string Repeat (this string input, int count) { var builder = new StringBuilder ((input == null ? 0 : input.Length) * count); for (int i = 0; i < count; i++) builder.Append (input); return builder.ToString (); } public static int Count (this string input, char letter) { int count = 0; foreach (char c in input) if (c == letter) count++; return count; } public static bool IsNumbersOnly (this string input) { if (input == "") return false; foreach (char c in input) if (c < '0' || c > '9') return false; return true; } /** * Debug: print line to console */ public static void Log (this string input) { string paramName = MemberInfoGetter.GetMemberName (() => input); Console.WriteLine ("<string " + paramName + ", " + input.Length + "> " + input); } }
using System; using System.Text; using Punku; public static class StringExtensions { public static string Repeat (this string input, int count) { var builder = new StringBuilder ((input == null ? 0 : input.Length) * count); for (int i = 0; i < count; i++) builder.Append (input); return builder.ToString (); } public static int Count (this string input, char letter) { int count = 0; foreach (char c in input) if (c == letter) count++; return count; } /** * Debug: print line to console */ public static void Log (this string input) { string paramName = MemberInfoGetter.GetMemberName (() => input); Console.WriteLine ("<string " + paramName + ", " + input.Length + "> " + input); } }
mit
C#
0096bba274ba2287c8790c116fd3f4c550c23b5d
Destroy bricks
babeya/Block-Breaker
Assets/Scripts/Brick.cs
Assets/Scripts/Brick.cs
using UnityEngine; public class Brick : MonoBehaviour { public int maxHits; int timesHit; LevelManager levelManager; // Use this for initialization void Start () { timesHit = 0; levelManager = FindObjectOfType<LevelManager>(); } // Update is called once per frame void Update () { } void OnCollisionEnter2D(Collision2D collision) { timesHit++; if (timesHit >= maxHits) { Destroy(gameObject); } } // TODO : remove this methods when we can actually win void SimulateWin() { levelManager.LoadNextLevel(); } }
using UnityEngine; public class Brick : MonoBehaviour { public int maxHits; int timesHit; LevelManager levelManager; // Use this for initialization void Start () { timesHit = 0; levelManager = FindObjectOfType<LevelManager>(); } // Update is called once per frame void Update () { } void OnCollisionEnter2D(Collision2D collision) { timesHit++; SimulateWin(); } // TODO : remove this methods when we can actually win void SimulateWin() { levelManager.LoadNextLevel(); } }
mit
C#
773ded77f362114d9a2ecd6547382e87057d9bbd
Correct behaviour of Lazy ORM implementation
hgcummings/DataAccessExamples,hgcummings/DataAccessExamples
DataAccessExamples.Core/Services/LazyOrmDepartmentService.cs
DataAccessExamples.Core/Services/LazyOrmDepartmentService.cs
using System; using System.Linq; using DataAccessExamples.Core.Data; using DataAccessExamples.Core.ViewModels; namespace DataAccessExamples.Core.Services { public class LazyOrmDepartmentService : IDepartmentService { private readonly EmployeesContext context; public LazyOrmDepartmentService(EmployeesContext context) { this.context = context; } public DepartmentList ListDepartments() { return new DepartmentList { Departments = context.Departments.OrderBy(d => d.Code).Select(d => new DepartmentSummary { Code = d.Code, Name = d.Name }) }; } public DepartmentList ListAverageSalaryPerDepartment() { return new DepartmentList { Departments = context.Departments.AsEnumerable().Select(d => new DepartmentSalary { Code = d.Code, Name = d.Name, AverageSalary = (int) d.DepartmentEmployees.Select( e => e.Employee.Salaries.LastOrDefault(s => s.ToDate > DateTime.Now)) .Where(s => s != null) .Average(s => s.Amount) }).OrderByDescending(d => d.AverageSalary) }; } } }
using System; using System.Linq; using DataAccessExamples.Core.Data; using DataAccessExamples.Core.ViewModels; namespace DataAccessExamples.Core.Services { public class LazyOrmDepartmentService : IDepartmentService { private readonly EmployeesContext context; public LazyOrmDepartmentService(EmployeesContext context) { this.context = context; } public DepartmentList ListDepartments() { return new DepartmentList { Departments = context.Departments.OrderBy(d => d.Code).Select(d => new DepartmentSummary { Code = d.Code, Name = d.Name }) }; } public DepartmentList ListAverageSalaryPerDepartment() { return new DepartmentList { Departments = context.Departments.AsEnumerable().Select(d => new DepartmentSalary { Code = d.Code, Name = d.Name, AverageSalary = (int) d.DepartmentEmployees.Select( e => e.Employee.Salaries.LastOrDefault(s => s.ToDate > DateTime.Now)) .Where(s => s != null) .Average(s => s.Amount) }) }; } } }
cc0-1.0
C#
4bb47668e747bae4a6a1bda4157f362e0920864c
fix typo
valadas/Dnn.Platform,svdv71/Dnn.Platform,dnnsoftware/Dnn.Platform,bdukes/Dnn.Platform,svdv71/Dnn.Platform,nvisionative/Dnn.Platform,wael101/Dnn.Platform,RichardHowells/Dnn.Platform,RichardHowells/Dnn.Platform,dnnsoftware/Dnn.Platform,nvisionative/Dnn.Platform,robsiera/Dnn.Platform,mitchelsellers/Dnn.Platform,dnnsoftware/Dnn.Platform,bdukes/Dnn.Platform,bdukes/Dnn.Platform,EPTamminga/Dnn.Platform,mitchelsellers/Dnn.Platform,bdukes/Dnn.Platform,mitchelsellers/Dnn.Platform,nvisionative/Dnn.Platform,wael101/Dnn.Platform,valadas/Dnn.Platform,robsiera/Dnn.Platform,RichardHowells/Dnn.Platform,wael101/Dnn.Platform,mitchelsellers/Dnn.Platform,mitchelsellers/Dnn.Platform,EPTamminga/Dnn.Platform,valadas/Dnn.Platform,dnnsoftware/Dnn.Platform,RichardHowells/Dnn.Platform,dnnsoftware/Dnn.Platform,valadas/Dnn.Platform,robsiera/Dnn.Platform,svdv71/Dnn.Platform,EPTamminga/Dnn.Platform,valadas/Dnn.Platform
Build/cake/version.cake
Build/cake/version.cake
#addin Cake.XdtTransform #addin "Cake.FileHelpers" #addin Cake.Powershell #tool "nuget:?package=GitVersion.CommandLine&prerelease" GitVersion version; var buildId = EnvironmentVariable("Build.BuildId") ?? string.Empty; Task("BuildServerSetVersion") .IsDependentOn("GitVersion") .Does(() => { StartPowershellScript("Write-Host", args => { args.AppendQuoted($"##vso[build.updatebuildnumber]{version.FullSemVer}.{buildId}"); }); }); Task("GitVersion") .Does(() => { version = GitVersion(new GitVersionSettings { UpdateAssemblyInfo = true, UpdateAssemblyInfoFilePath = @"SolutionInfo.cs" }); }); Task("UpdateDnnManifests") .IsDependentOn("GitVersion") .DoesForEach(GetFiles("**/*.dnn"), (file) => { var transformFile = File(System.IO.Path.GetTempFileName()); FileAppendText(transformFile, GetXdtTransformation()); XdtTransformConfig(file, transformFile, file); }); public string GetBuildNumber() { return version.LegacySemVerPadded; } public string GetProductVersion() { return version.MajorMinorPatch; } public string GetXdtTransformation() { var versionString = $"{version.Major.ToString("00")}.{version.Minor.ToString("00")}.{version.Patch.ToString("00")}"; return $@"<?xml version=""1.0""?> <dotnetnuke xmlns:xdt=""http://schemas.microsoft.com/XML-Document-Transform""> <packages> <package version=""{versionString}"" xdt:Transform=""SetAttributes(version)"" xdt:Locator=""Condition([not(@version)])"" /> </packages> </dotnetnuke>"; }
#addin Cake.XdtTransform #addin "Cake.FileHelpers" #addin Cake.Powershell #tool "nuget:?package=GitVersion.CommandLine&prerelease" GitVersion version; var buildId = EnvironmentVariable("Build.BuildId") ?? string.Empty; Task("BuildServerSetVersion") .IsDependentOn("GitVersion") .Does(() => { StartPowershellScript("Write-Host", args => { args.AppendQuoted($"##vso[build.updatebuildnumber]{version.FullSemver}.{buildId}"); }); }); Task("GitVersion") .Does(() => { version = GitVersion(new GitVersionSettings { UpdateAssemblyInfo = true, UpdateAssemblyInfoFilePath = @"SolutionInfo.cs" }); }); Task("UpdateDnnManifests") .IsDependentOn("GitVersion") .DoesForEach(GetFiles("**/*.dnn"), (file) => { var transformFile = File(System.IO.Path.GetTempFileName()); FileAppendText(transformFile, GetXdtTransformation()); XdtTransformConfig(file, transformFile, file); }); public string GetBuildNumber() { return version.LegacySemVerPadded; } public string GetProductVersion() { return version.MajorMinorPatch; } public string GetXdtTransformation() { var versionString = $"{version.Major.ToString("00")}.{version.Minor.ToString("00")}.{version.Patch.ToString("00")}"; return $@"<?xml version=""1.0""?> <dotnetnuke xmlns:xdt=""http://schemas.microsoft.com/XML-Document-Transform""> <packages> <package version=""{versionString}"" xdt:Transform=""SetAttributes(version)"" xdt:Locator=""Condition([not(@version)])"" /> </packages> </dotnetnuke>"; }
mit
C#
7931a9a2320e1232ec647fa2b0b36a83616c3e5e
Update AlainAssaf.cs
planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell
src/Firehose.Web/Authors/AlainAssaf.cs
src/Firehose.Web/Authors/AlainAssaf.cs
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using System.Web; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class AlainAssaf : IAmACommunityMember { public string FirstName => "Alain"; public string LastName => "Alain"; public string ShortBioOrTagLine => "Citrix Specialist at SECU - Citrix Technology Advocate - Feedspot Top 50 PowerShell Blogs on the web"; public string StateOrRegion => "North Carolina, USA"; public string EmailAddress => ""; public string TwitterHandle => "alainassaf"; public string GitHubHandle => "alainassaf"; public string GravatarHash => "55e3ac1ac8ca9129cc9e138a158b07bb"; public GeoPosition Position => new GeoPosition(35.7795900, -78.6381790); public Uri WebSite => new Uri("https://alainassaf.github.io/"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://alainassaf.github.io/feed.xml"); } } public string FeedLanguageCode => "en"; } }
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using System.Web; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class AlainAssaf : IAmACommunityMember { public string FirstName => "Alain"; public string LastName => "Alain"; public string ShortBioOrTagLine => "Citrix Specialist at SECU - Citrix Technology Advocate - Feedspot Top 50 PowerShell Blogs on the web"; public string StateOrRegion => "North Carolina, USA"; public string EmailAddress => ""; public string TwitterHandle => "alainassaf"; public string GitHubHandle => "alainassaf"; public string GravatarHash => "55e3ac1ac8ca9129cc9e138a158b07bb"; public GeoPosition Position => new GeoPosition(35.7795900, -78.6381790); public Uri WebSite => new Uri("https://alainassaf.github.io/"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://alainassaf.github.io/feed"); } } public string FeedLanguageCode => "en"; } }
mit
C#
8787d3879f9a209ff3774c65416b4e7750e4cb43
Add Printer.PrintFunction
DotNetKit/DotNetKit.Wpf.Printing
DotNetKit.Wpf.Printing.Demo/Printing/Printer.cs
DotNetKit.Wpf.Printing.Demo/Printing/Printer.cs
using System; using System.Collections.Generic; using System.Linq; using System.Printing; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Documents; using DotNetKit.Windows.Documents; using DotNetKit.Wpf.Printing.Demo.Printing.Xps; namespace DotNetKit.Wpf.Printing.Demo.Printing { public class Printer { sealed class PrintFunction<TPrintable> { readonly TPrintable printable; readonly IPaginator<TPrintable> paginator; readonly Size pageSize; readonly PrintQueue printQueue; readonly CancellationToken cancellationToken; readonly bool isLandscape; readonly Size mediaSize; void Setup() { var ticket = printQueue.DefaultPrintTicket; ticket.PageMediaSize = new PageMediaSize(mediaSize.Width, mediaSize.Height); ticket.PageOrientation = PageOrientation.Portrait; } FixedDocument Document() { return paginator.ToFixedDocument(printable, pageSize); } public Task PrintAsync() { Setup(); var document = Document(); var writer = PrintQueue.CreateXpsDocumentWriter(printQueue); return writer.WriteAsyncAsTask(document, cancellationToken); } public PrintFunction( TPrintable printable, IPaginator<TPrintable> paginator, Size pageSize, PrintQueue printQueue, CancellationToken cancellationToken ) { this.printable = printable; this.paginator = paginator; this.pageSize = pageSize; this.printQueue = printQueue; this.cancellationToken = cancellationToken; isLandscape = pageSize.Width > pageSize.Height; mediaSize = isLandscape ? new Size(pageSize.Height, pageSize.Width) : pageSize; } } public Task PrintAsync<P>( P printable, IPaginator<P> paginator, Size pageSize, PrintQueue printQueue, CancellationToken cancellationToken = default(CancellationToken) ) { return new PrintFunction<P>(printable, paginator, pageSize, printQueue, cancellationToken) .PrintAsync(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Printing; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows; using DotNetKit.Windows.Documents; using DotNetKit.Wpf.Printing.Demo.Printing.Xps; namespace DotNetKit.Wpf.Printing.Demo.Printing { public class Printer { public Task PrintAsync<P>( P printable, IPaginator<P> paginator, Size pageSize, PrintQueue printQueue, CancellationToken cancellationToken = default(CancellationToken) ) { var isLandscape = pageSize.Width > pageSize.Height; var mediaSize = isLandscape ? new Size(pageSize.Height, pageSize.Width) : pageSize; var document = paginator.ToFixedDocument(printable, pageSize); var ticket = printQueue.DefaultPrintTicket; ticket.PageMediaSize = new PageMediaSize(mediaSize.Width, mediaSize.Height); ticket.PageOrientation = PageOrientation.Portrait; var writer = PrintQueue.CreateXpsDocumentWriter(printQueue); return writer.WriteAsyncAsTask(document, cancellationToken); } } }
mit
C#
96c28e8e322feb5ed53f77f5da684f371a132346
Rename Tardigrade to Storj DCS
duplicati/duplicati,mnaiman/duplicati,duplicati/duplicati,mnaiman/duplicati,mnaiman/duplicati,duplicati/duplicati,mnaiman/duplicati,duplicati/duplicati,mnaiman/duplicati,duplicati/duplicati
Duplicati/Library/Backend/Tardigrade/Strings.cs
Duplicati/Library/Backend/Tardigrade/Strings.cs
using Duplicati.Library.Localization.Short; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Duplicati.Library.Backend.Strings { internal static class Tardigrade { public static string DisplayName { get { return LC.L(@"Storj DCS (Decentralized Cloud Storage)"); } } public static string Description { get { return LC.L(@"This backend can read and write data to the Storj DCS."); } } public static string TestConnectionFailed { get { return LC.L(@"The connection-test failed."); } } public static string TardigradeAuthMethodDescriptionShort { get { return LC.L(@"The authentication method"); } } public static string TardigradeAuthMethodDescriptionLong { get { return LC.L(@"The authentication method describes which way to use to connect to the network - either via API key or via an access grant."); } } public static string TardigradeSatelliteDescriptionShort { get { return LC.L(@"The satellite"); } } public static string TardigradeSatelliteDescriptionLong { get { return LC.L(@"The satellite that keeps track of all metadata. Use a Storj DCS server for high-performance SLA-backed connectivity or use a community server. Or even host your own."); } } public static string TardigradeAPIKeyDescriptionShort { get { return LC.L(@"The API key"); } } public static string TardigradeAPIKeyDescriptionLong { get { return LC.L(@"The API key grants access to a specific project on your chosen satellite. Head over to the dashboard of your satellite to create one if you do not already have an API key."); } } public static string TardigradeSecretDescriptionShort { get { return LC.L(@"The encryption passphrase"); } } public static string TardigradeSecretDescriptionLong { get { return LC.L(@"The encryption passphrase is used to encrypt your data before sending it to the Storj network. This passphrase can be the only secret to provide - for Storj you do not necessary need any additional encryption (from Duplicati) in place."); } } public static string TardigradeSharedAccessDescriptionShort { get { return LC.L(@"The access grant"); } } public static string TardigradeSharedAccessDescriptionLong { get { return LC.L(@"An access grant contains all information in one encrypted string. You may use it instead of a satellite, API key and secret."); } } public static string TardigradeBucketDescriptionShort { get { return LC.L(@"The bucket"); } } public static string TardigradeBucketDescriptionLong { get { return LC.L(@"The bucket where the backup will reside in."); } } public static string TardigradeFolderDescriptionShort { get { return LC.L(@"The folder"); } } public static string TardigradeFolderDescriptionLong { get { return LC.L(@"The folder within the bucket where the backup will reside in."); } } } }
using Duplicati.Library.Localization.Short; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Duplicati.Library.Backend.Strings { internal static class Tardigrade { public static string DisplayName { get { return LC.L(@"Tardigrade Decentralized Cloud Storage"); } } public static string Description { get { return LC.L(@"This backend can read and write data to the Tardigrade Decentralized Cloud Storage."); } } public static string TestConnectionFailed { get { return LC.L(@"The connection-test failed."); } } public static string TardigradeAuthMethodDescriptionShort { get { return LC.L(@"The authentication method"); } } public static string TardigradeAuthMethodDescriptionLong { get { return LC.L(@"The authentication method describes which way to use to connect to the network - either via API key or via an access grant."); } } public static string TardigradeSatelliteDescriptionShort { get { return LC.L(@"The satellite"); } } public static string TardigradeSatelliteDescriptionLong { get { return LC.L(@"The satellite that keeps track of all metadata. Use a Tardigrade-grade server for high-performance SLA-backed connectivity or use a community server. Or even host your own."); } } public static string TardigradeAPIKeyDescriptionShort { get { return LC.L(@"The API key"); } } public static string TardigradeAPIKeyDescriptionLong { get { return LC.L(@"The API key grants access to a specific project on your chosen satellite. Head over to the dashboard of your satellite to create one if you do not already have an API key."); } } public static string TardigradeSecretDescriptionShort { get { return LC.L(@"The encryption passphrase"); } } public static string TardigradeSecretDescriptionLong { get { return LC.L(@"The encryption passphrase is used to encrypt your data before sending it to the tardigrade network. This passphrase can be the only secret to provide - for Tardigrade you do not necessary need any additional encryption (from Duplicati) in place."); } } public static string TardigradeSharedAccessDescriptionShort { get { return LC.L(@"The access grant"); } } public static string TardigradeSharedAccessDescriptionLong { get { return LC.L(@"An access grant contains all information in one encrypted string. You may use it instead of a satellite, API key and secret."); } } public static string TardigradeBucketDescriptionShort { get { return LC.L(@"The bucket"); } } public static string TardigradeBucketDescriptionLong { get { return LC.L(@"The bucket where the backup will reside in."); } } public static string TardigradeFolderDescriptionShort { get { return LC.L(@"The folder"); } } public static string TardigradeFolderDescriptionLong { get { return LC.L(@"The folder within the bucket where the backup will reside in."); } } } }
lgpl-2.1
C#
5f6f6d063843d0fcb9e2a58c564c3a4ab49ac447
Add license to newly added ExportSphereSystems.cs
jthorpe4/EDDiscovery,jeoffman/EDDiscovery,jeoffman/EDDiscovery,jgoode/EDDiscovery,mwerle/EDDiscovery,mwerle/EDDiscovery,jgoode/EDDiscovery
EDDiscovery/ExportImport/ExportSphereSystems.cs
EDDiscovery/ExportImport/ExportSphereSystems.cs
/* * Copyright © 2017 EDDiscovery development team * * 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. * * EDDiscovery is not affiliated with Fronter Developments plc. */ using EDDiscovery.Export; using EDDiscovery2.EDSM; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace EDDiscovery.ExportImport { class ExportSphereSystems { private EDDiscoveryForm _discoveryForm; public ExportSphereSystems(EDDiscoveryForm _discoveryForm) { this._discoveryForm = _discoveryForm; } public void Execute(String systemName, double radius) { SaveFileDialog dlg = new SaveFileDialog(); dlg.Filter = "SphereSystems export| *.txt"; dlg.Title = TITLE; dlg.FileName = "SphereSystems.txt"; if (dlg.ShowDialog() != DialogResult.OK) return; String fileName = dlg.FileName; EDSMClass edsm = new EDSMClass(); Task taskEDSM = Task<List<String>>.Factory.StartNew(() => { return edsm.GetSphereSystems(systemName, radius); }).ContinueWith(task => ExportFile(task, fileName)); } private String TITLE = "Export Sphere Systems"; private void ExportFile(Task<List<String>> task, String filename) { try { using (StreamWriter writer = new StreamWriter(filename, false)) { foreach (String system in task.Result) { writer.WriteLine(system); } } // MessageBox.Show(String.Format("Export complete {0}", // filename), TITLE); } catch (IOException) { // MessageBox.Show(String.Format("Is file {0} open?", filename), TITLE, MessageBoxButtons.OK, MessageBoxIcon.Error); } } } }
using EDDiscovery.Export; using EDDiscovery2.EDSM; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace EDDiscovery.ExportImport { class ExportSphereSystems { private EDDiscoveryForm _discoveryForm; public ExportSphereSystems(EDDiscoveryForm _discoveryForm) { this._discoveryForm = _discoveryForm; } public void Execute(String systemName, double radius) { SaveFileDialog dlg = new SaveFileDialog(); dlg.Filter = "SphereSystems export| *.txt"; dlg.Title = TITLE; dlg.FileName = "SphereSystems.txt"; if (dlg.ShowDialog() != DialogResult.OK) return; String fileName = dlg.FileName; EDSMClass edsm = new EDSMClass(); Task taskEDSM = Task<List<String>>.Factory.StartNew(() => { return edsm.GetSphereSystems(systemName, radius); }).ContinueWith(task => ExportFile(task, fileName)); } private String TITLE = "Export Sphere Systems"; private void ExportFile(Task<List<String>> task, String filename) { try { using (StreamWriter writer = new StreamWriter(filename, false)) { foreach (String system in task.Result) { writer.WriteLine(system); } } // MessageBox.Show(String.Format("Export complete {0}", // filename), TITLE); } catch (IOException) { // MessageBox.Show(String.Format("Is file {0} open?", filename), TITLE, MessageBoxButtons.OK, MessageBoxIcon.Error); } } } }
apache-2.0
C#
cc9071b6823ffc6864d3dff0788c72061137cc20
Remove incorrect Assembly GUID
File-New-Project/EarTrumpet
EarTrumpet/UI/Helpers/SingleInstanceAppMutex.cs
EarTrumpet/UI/Helpers/SingleInstanceAppMutex.cs
using System.Globalization; using System.Reflection; using System.Threading; namespace EarTrumpet.UI.Helpers { class SingleInstanceAppMutex { private static Mutex _mutex; public static bool TakeExclusivity() { var assembly = Assembly.GetExecutingAssembly(); var mutexName = $"Local\\{assembly.GetName().Name}-0e510f7b-aed2-40b0-ad72-d2d3fdc89a02"; _mutex = new Mutex(true, mutexName, out bool mutexCreated); if (!mutexCreated) { _mutex = null; return false; } App.Current.Exit += App_Exit; return true; } private static void App_Exit(object sender, System.Windows.ExitEventArgs e) { ReleaseExclusivity(); } public static void ReleaseExclusivity() { if (_mutex == null) return; _mutex.ReleaseMutex(); _mutex.Close(); _mutex = null; } } }
using System.Globalization; using System.Reflection; using System.Threading; namespace EarTrumpet.UI.Helpers { class SingleInstanceAppMutex { private static Mutex _mutex; public static bool TakeExclusivity() { var assembly = Assembly.GetExecutingAssembly(); var mutexName = string.Format(CultureInfo.InvariantCulture, "Local\\{{{0}}}{{{1}}}", assembly.GetType().GUID, assembly.GetName().Name); _mutex = new Mutex(true, mutexName, out bool mutexCreated); if (!mutexCreated) { _mutex = null; return false; } App.Current.Exit += App_Exit; return true; } private static void App_Exit(object sender, System.Windows.ExitEventArgs e) { ReleaseExclusivity(); } public static void ReleaseExclusivity() { if (_mutex == null) return; _mutex.ReleaseMutex(); _mutex.Close(); _mutex = null; } } }
mit
C#
4ec4720727a9fa15374ae07f44347463dfb39c70
disable checkip service
NTumbleBit/NTumbleBit,DanGould/NTumbleBit
NTumbleBit.ClassicTumbler.Client.CLI/Program.cs
NTumbleBit.ClassicTumbler.Client.CLI/Program.cs
using Microsoft.Extensions.Logging; using System.Linq; using Microsoft.Extensions.Logging.Console; using System; using NTumbleBit.Logging; using System.Text; using NBitcoin.RPC; using CommandLine; using System.Reflection; using NTumbleBit.ClassicTumbler; using NTumbleBit.Configuration; using NTumbleBit.ClassicTumbler.Client; using NTumbleBit.ClassicTumbler.CLI; namespace NTumbleBit.ClassicTumbler.Client.CLI { public partial class Program { public static void Main(string[] args) { new Program().Run(args); } public void Run(string[] args) { Logs.Configure(new FuncLoggerFactory(i => new CustomerConsoleLogger(i, (a, b) => true, false))); using(var interactive = new Interactive()) { try { var config = new TumblerClientConfiguration(); config.LoadArgs(args); var runtime = TumblerClientRuntime.FromConfiguration(config, new TextWriterClientInteraction(Console.Out, Console.In)); interactive.Runtime = new ClientInteractiveRuntime(runtime); var broadcaster = runtime.CreateBroadcasterJob(); broadcaster.Start(); interactive.Services.Add(broadcaster); //interactive.Services.Add(new CheckIpService(runtime)); //interactive.Services.Last().Start(); if(!config.OnlyMonitor) { var stateMachine = runtime.CreateStateMachineJob(); stateMachine.Start(); interactive.Services.Add(stateMachine); } interactive.StartInteractive(); } catch(ClientInteractionException ex) { if(!string.IsNullOrEmpty(ex.Message)) Logs.Configuration.LogError(ex.Message); } catch(ConfigException ex) { if(!string.IsNullOrEmpty(ex.Message)) Logs.Configuration.LogError(ex.Message); } catch(InterruptedConsoleException) { } catch(Exception ex) { Logs.Configuration.LogError(ex.Message); Logs.Configuration.LogDebug(ex.StackTrace); } } } } }
using Microsoft.Extensions.Logging; using System.Linq; using Microsoft.Extensions.Logging.Console; using System; using NTumbleBit.Logging; using System.Text; using NBitcoin.RPC; using CommandLine; using System.Reflection; using NTumbleBit.ClassicTumbler; using NTumbleBit.Configuration; using NTumbleBit.ClassicTumbler.Client; using NTumbleBit.ClassicTumbler.CLI; namespace NTumbleBit.ClassicTumbler.Client.CLI { public partial class Program { public static void Main(string[] args) { new Program().Run(args); } public void Run(string[] args) { Logs.Configure(new FuncLoggerFactory(i => new CustomerConsoleLogger(i, (a, b) => true, false))); using(var interactive = new Interactive()) { try { var config = new TumblerClientConfiguration(); config.LoadArgs(args); var runtime = TumblerClientRuntime.FromConfiguration(config, new TextWriterClientInteraction(Console.Out, Console.In)); interactive.Runtime = new ClientInteractiveRuntime(runtime); var broadcaster = runtime.CreateBroadcasterJob(); broadcaster.Start(); interactive.Services.Add(broadcaster); interactive.Services.Add(new CheckIpService(runtime)); interactive.Services.Last().Start(); if(!config.OnlyMonitor) { var stateMachine = runtime.CreateStateMachineJob(); stateMachine.Start(); interactive.Services.Add(stateMachine); } interactive.StartInteractive(); } catch(ClientInteractionException ex) { if(!string.IsNullOrEmpty(ex.Message)) Logs.Configuration.LogError(ex.Message); } catch(ConfigException ex) { if(!string.IsNullOrEmpty(ex.Message)) Logs.Configuration.LogError(ex.Message); } catch(InterruptedConsoleException) { } catch(Exception ex) { Logs.Configuration.LogError(ex.Message); Logs.Configuration.LogDebug(ex.StackTrace); } } } } }
mit
C#
090c0d9eecb926b0f55b00d90ddccb1d288ed7c8
Add zoom into rasterlayer data in the sample
charlenni/Mapsui,charlenni/Mapsui,pauldendulk/Mapsui
Samples/Mapsui.Samples.Common/Maps/RasterizingLayerSample.cs
Samples/Mapsui.Samples.Common/Maps/RasterizingLayerSample.cs
using System; using Mapsui.Layers; using Mapsui.Providers; using Mapsui.Styles; using Mapsui.UI; using Mapsui.Utilities; namespace Mapsui.Samples.Common.Maps { public class RasterizingLayerSample : ISample { public string Name => "Rasterizing Layer"; public string Category => "Special"; public void Setup(IMapControl mapControl) { mapControl.Map = CreateMap(); } public static Map CreateMap() { var map = new Map(); map.Layers.Add(OpenStreetMap.CreateTileLayer()); map.Layers.Add(new RasterizingLayer(CreateRandomPointLayer())); map.Home = n => n.NavigateTo(map.Layers[1].Envelope.Grow(map.Layers[1].Envelope.Width * 0.1)); return map; } private static MemoryLayer CreateRandomPointLayer() { var rnd = new Random(3462); // Fix the random seed so the features don't move after a refresh var features = new Features(); for (var i = 0; i < 100; i++) { var feature = new Feature { Geometry = new Geometries.Point(rnd.Next(0, 5000000), rnd.Next(0, 5000000)) }; features.Add(feature); } var provider = new MemoryProvider(features); return new MemoryLayer { DataSource = provider, Style = new SymbolStyle { SymbolType = SymbolType.Triangle, Fill = new Brush(Color.Red) } }; } } }
using System; using Mapsui.Layers; using Mapsui.Providers; using Mapsui.Styles; using Mapsui.UI; using Mapsui.Utilities; namespace Mapsui.Samples.Common.Maps { public class RasterizingLayerSample : ISample { public string Name => "Rasterizing Layer"; public string Category => "Special"; public void Setup(IMapControl mapControl) { mapControl.Map = CreateMap(); } public static Map CreateMap() { var map = new Map(); map.Layers.Add(OpenStreetMap.CreateTileLayer()); map.Layers.Add(new RasterizingLayer(CreateRandomPointLayer())); return map; } private static MemoryLayer CreateRandomPointLayer() { var rnd = new Random(); var features = new Features(); for (var i = 0; i < 100; i++) { var feature = new Feature { Geometry = new Geometries.Point(rnd.Next(0, 5000000), rnd.Next(0, 5000000)) }; features.Add(feature); } var provider = new MemoryProvider(features); return new MemoryLayer { DataSource = provider, Style = new SymbolStyle { SymbolType = SymbolType.Triangle, Fill = new Brush(Color.Red) } }; } } }
mit
C#